From 71342fe027be9c517e5c9355b2028a88159ad197 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 04:06:18 +0100 Subject: [PATCH] web: connection banner, reconnect, foreground recovery and live badge (T3/T4/T5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- web/PARITY.md | 6 +- web/src/app.js | 194 +++++++++++++++++++++------- web/src/connection.js | 174 ++++++++++++++++++++++++++ web/src/protocol.js | 9 ++ web/styles.css | 52 ++++++++ web/test/connection.test.mjs | 236 +++++++++++++++++++++++++++++++++++ web/test/ui-smoke.mjs | 128 +++++++++++++++++-- 7 files changed, 746 insertions(+), 53 deletions(-) create mode 100644 web/src/connection.js create mode 100644 web/test/connection.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index a2d8ab9d..53cb1473 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -13,9 +13,9 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | --- | --- | --- | --- | | T1 | Server-URL entry + validation rules (`data/transport/ServerUrl.kt`) | — | done | | T2 | One reused socket, id matching, request timeout, not-connected guard (`PipelinesClient.kt`) | — | done | -| T3 | Connect / disconnect / manual reconnect | `ping` | partial (connect works; no reconnect UI) | -| T4 | Backoff recovery + foreground reconnect after sleep/blur (`ConnectionRecovery.kt`, `ForegroundReconnector.kt`) | — | todo | -| T5 | Connection banner + live badge; build/protocol mismatch warning | `pong` build/protocol | todo | +| T3 | Connect / disconnect / manual reconnect | `ping` | done — connect/disconnect captured (`captures/28-connected-banner.png`, the header control reading `Disconnect` while connected); the `Reconnect` control appears beside the URL field while idle/disconnected with a configured endpoint and calls `client.connect`, which resets the attempt/backoff for an immediate re-open (`captures/29-disconnected-banner.png`). `Disconnect` stays available while connected | +| T4 | Backoff recovery + foreground reconnect after sleep/blur (`ConnectionRecovery.kt`, `ForegroundReconnector.kt`) | — | done — the client's capped backoff is surfaced honestly rather than rewritten: `captures/29-disconnected-banner.png` shows the banner `Disconnected: Connection closed (1006) · retrying with backoff` and the header state badge `disconnected — Connection closed (1006) (attempt N, retrying)`. The attempt number is deliberately **not** in the banner text — `ConnectionBanner.kt`'s own disconnected copy omits it (Android names the attempt only while Connecting) — so the page's badge carries it instead of diverging from the Android wording. The foreground-reconnect **decision** (`foregroundAction`) is unit-tested in `test/connection.test.mjs` (Idle→LeaveAlone; Connecting/Disconnected→Reconnect; Connected→`confirmedAlive ? LeaveAlone : Reconnect`); the **rendered recovery** is captured in `captures/30-reconnect-recovered.png`, where the page (asserted still `Disconnected:`) is pointed back at the live server and the browser's own `online` event drives it to a green Connected. The browser uses its `online`/`visibilitychange` event as the liveness signal, so a still-Connected socket is left alone (no in-page positive ping probe is needed; a documented deviation from `ForegroundReconnector`'s positive ping) | +| T5 | Connection banner + live badge; build/protocol mismatch warning | `pong` build/protocol | done — a persistent banner in normal document flow under the header (never overlaying content): green `Connected` + `Server build …` (`captures/28-connected-banner.png`) and `Disconnected: … · retrying with backoff` (`captures/29-disconnected-banner.png`); a minimal dot+word live badge in the runs list/detail (`live` / `reconnecting` / `not live`, per `LiveBadge.kt`/`RunStream.kt`, `captures/28-connected-banner.png`). The build line comes from the `pong` in `SettingsScreen.kt`'s own shape, `Server build {version} ({commit})`; a dirty tree is already marked in `version` by `internal/buildinfo` (`-dirty`), so no duplicate `+dirty` marker is added. The protocol-mismatch warning (shown only when both values are present and differ, naming both) is unit-tested (`protocolMismatch`) and not captured because the live server reports `protocol` 1, matching `PROTOCOL_VERSION` | | T6 | Artifact URL resolution against the configured server (`resolveArtifactUrl`) | `GET /artifacts/…` | done (URL only) | ## Pipelines diff --git a/web/src/app.js b/web/src/app.js index 7629227c..0f2a7907 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -3,7 +3,17 @@ // that came from the server is set with textContent, never innerHTML. import { PipelinesClient } from "./client.js"; import { PipelinesRepository } from "./repository.js"; +import { PROTOCOL_VERSION } from "./protocol.js"; import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js"; +import { + ForegroundAction, + bannerState, + foregroundAction, + liveBadgeState, + protocolMismatch, + serverBuildLabel, + stateBadge, +} from "./connection.js"; import { ArtifactKind, artifactCaptureNotes, @@ -124,6 +134,10 @@ const state = { view: "pipelines", url: localStorage.getItem(STORAGE_KEY) ?? defaultServerUrl(), connection: client.state, + // The last `pong` reply is remembered so the banner can name a stale server + // build and warn about a protocol mismatch (T5) without re-pinging. + serverBuild: null, + serverProtocol: null, pipelines: [], runs: [], usage: null, @@ -212,51 +226,80 @@ function isExecuting(run) { // --------------------------------------------------------------------------- const header = h("header", { class: "topbar" }); +// The persistent connection banner sits in normal document flow directly under +// the header (never fixed/overlaying), so it can never cover the content. +const connBanner = h("div", { id: "connBanner", class: "conn-banner", hidden: true }); const content = h("main", { id: "content" }); -document.body.append(header, content); +document.body.append(header, connBanner, content); + +/** Whether the URL field currently holds a usable endpoint for Reconnect. */ +function endpointConfigured() { + return validateServerUrl(state.url).valid; +} function renderHeader() { + const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() }); + const controls = [ + h("input", { + id: "url", + type: "text", + placeholder: "ws://HOST:PORT/connect", + value: state.url, + spellcheck: "false", + oninput: (e) => { + state.url = e.target.value; + }, + }), + ]; + // The manual reconnect control (T3) sits beside the URL field and is offered + // whenever the connection state asks for one. + if (info.action) { + controls.push( + h("button", { id: "reconnectBtn", class: "ghost", text: info.action, onclick: onReconnectClicked }), + ); + } + controls.push( + h("button", { + id: "connectBtn", + text: state.connection.kind === "connected" ? "Disconnect" : "Connect", + onclick: onConnectClicked, + }), + h("span", { class: "state", id: "stateBadge" }, connectionLabel()), + ); header.replaceChildren( h("div", { class: "brand" }, h("strong", { text: "Pipelines" }), h("span", { class: "muted", text: "web spike" })), - h( - "div", - { class: "connbar" }, - h("input", { - id: "url", - type: "text", - placeholder: "ws://HOST:PORT/connect", - value: state.url, - spellcheck: "false", - oninput: (e) => { - state.url = e.target.value; - }, - }), - h("button", { - id: "connectBtn", - text: state.connection.kind === "connected" ? "Disconnect" : "Connect", - onclick: onConnectClicked, - }), - h("span", { class: "state", id: "stateBadge" }, connectionLabel()), - ), + h("div", { class: "connbar" }, ...controls), ); } +/** + * The persistent connection banner. Its copy/tone come from the pure + * `bannerState`, and it also carries the last server build and a protocol + * mismatch warning (T5). Every server string is set with textContent. + */ +function renderBanner() { + const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() }); + connBanner.className = `conn-banner conn-${info.tone}`; + connBanner.hidden = false; + const nodes = [ + h("span", { class: "conn-banner-dot", "aria-hidden": "true" }), + h("span", { class: "conn-banner-text", text: info.text }), + ]; + const build = serverBuildLabel(state.serverBuild); + if (build) nodes.push(h("span", { class: "conn-build", text: build })); + const warning = protocolMismatch(PROTOCOL_VERSION, state.serverProtocol); + if (warning) nodes.push(h("span", { class: "conn-warning", text: warning })); + connBanner.replaceChildren(...nodes); +} + function connectionLabel() { - const c = state.connection; - switch (c.kind) { - case "connected": - return h("span", { class: "dot ok" }, "connected"); - case "connecting": - return h("span", { class: "dot warn" }, `connecting… (attempt ${c.attempt})`); - case "disconnected": - return h("span", { class: "dot bad" }, `disconnected${c.reason ? ` — ${c.reason}` : ""}${c.retrying ? " (retrying)" : ""}`); - default: - return h("span", { class: "dot idle" }, "idle"); - } + const info = stateBadge(state.connection); + return h("span", { class: `dot ${info.tone}`, text: info.text }); } function render() { renderHeader(); + renderBanner(); renderContent(); } @@ -956,10 +999,21 @@ function renderRunToolbar() { state.openMenu === "sort" ? renderSortMenu() : null, ), h("span", { class: "spacer" }), + renderLiveBadge(liveBadgeState({ executing: state.runs.some((run) => run.executing) }, state.connection)), ); return toolbar; } +/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */ +function renderLiveBadge(info) { + return h( + "span", + { class: `live-badge live-${info.tone}`, title: "Live run stream" }, + h("span", { class: "live-dot", "aria-hidden": "true" }), + h("span", { class: "live-word", text: info.label }), + ); +} + function renderFilterMenu() { const filters = state.runFilters; const menu = h("div", { class: "menu filter-menu", id: "runFilterMenu" }); @@ -1133,6 +1187,7 @@ function renderRunSummaryTab(d) { chips.append(h("span", { class: `chip chip-${status}`, text: d.status || status })); if (String(d.outcome ?? "").trim()) chips.append(h("span", { class: "muted", text: `outcome ${d.outcome}` })); if (d.executing) chips.append(h("span", { class: "muted", text: "executing" })); + chips.append(renderLiveBadge(liveBadgeState(d, state.connection))); wrap.append(chips); wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) })); @@ -1838,31 +1893,78 @@ function setError(err) { renderContent(); } +/** + * Validate the URL field, remember it and open the socket. Shared by Connect, + * the manual Reconnect control and the foreground recovery so all three take the + * same validate → persist → repo.connect path. `repo.connect` resets the + * attempt/backoff inside client.js, cancelling a pending retry delay. + * + * `surfaceError` is false for the background (foreground-recovery) caller so a + * stale, invalid URL field cannot spray an error into the UI on every + * visibilitychange/online event. + */ +function openConfiguredEndpoint({ surfaceError = true } = {}) { + const validated = validateServerUrl(state.url); + if (!validated.valid) { + if (surfaceError) { + state.error = validated.message; + renderContent(); + } + return; + } + state.error = ""; + localStorage.setItem(STORAGE_KEY, state.url.trim()); + repo.connect(validated); +} + function onConnectClicked() { if (state.connection.kind === "connected") { repo.disconnect(); stopRunPoll(); return; } - const validated = validateServerUrl(state.url); - if (!validated.valid) { - state.error = validated.message; - renderContent(); - return; - } - state.error = ""; - localStorage.setItem(STORAGE_KEY, state.url.trim()); - repo.connect(validated); + openConfiguredEndpoint(); // The `state` listener kicks off the initial load once connected. } +/** + * The manual reconnect control (T3): re-open the same validated endpoint now. + * `repo.connect` (client.connect) resets the attempt/backoff, so a pending + * retry delay is cancelled and the socket is reopened immediately. + */ +function onReconnectClicked() { + openConfiguredEndpoint(); +} + +/** + * Return-to-foreground recovery (T4), the page's counterpart of + * ForegroundReconnector: called when the tab becomes visible again or the + * browser comes back online. Idle is the client's own deliberate-disconnect + * state and is left alone; Connecting and Disconnected are driven back to the + * socket at once, cancelling the pending backoff inside client.connect. A + * Connected socket is trusted because the browser's own online/visibility event + * is the liveness signal available to the page (it has no in-page positive ping + * probe like ForegroundReconnector.confirm()); that deviation is recorded in + * web/PARITY.md. Idempotent: repeated events just re-open the same endpoint. + */ +function onForegroundActive() { + if (foregroundAction(state.connection, true) !== ForegroundAction.Reconnect) return; + openConfiguredEndpoint({ surfaceError: false }); +} + async function onConnected() { + let reply; try { - await repo.ping(); + reply = await repo.ping(); } catch (err) { setError(err); return; } + // Remember the server's build/protocol so the banner can name a stale server + // and warn about a protocol mismatch (T5); the ping is the only source. + state.serverProtocol = reply?.protocol ?? null; + state.serverBuild = reply?.build ?? null; + renderBanner(); await loadCurrentView(); } @@ -2080,5 +2182,13 @@ document.addEventListener("keydown", (event) => { } }); +// Return-to-foreground recovery (T4): the page becomes visible again, or the +// browser reports it is back online, and the client drives its socket back +// without waiting out the backoff. DOM-only, and idempotent. +document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") onForegroundActive(); +}); +window.addEventListener("online", onForegroundActive); + // Prefill from a previous session only; the user still confirms with Connect. render(); diff --git a/web/src/connection.js b/web/src/connection.js new file mode 100644 index 00000000..3cfcb2ec --- /dev/null +++ b/web/src/connection.js @@ -0,0 +1,174 @@ +// Pure connection helpers for the browser client: how the persistent connection +// banner reads, what the page does the moment it becomes visible again, whether +// the ping reply's protocol/build can be trusted, and what the live badge says. +// +// Deliberately free of DOM, sockets and timers, so every branch is unit-testable +// in Node and renders identically in the page. The wording and colour roles are +// the Android client's own: +// ui/components/ConnectionBanner.kt — banner copy and container colours +// data/transport/ConnectionRecovery.kt — the foregroundAction policy +// data/ForegroundReconnector.kt — order and liveness check +// ui/components/LiveBadge.kt, ui/RunStream.kt — the live badge words +// ui/screens/SettingsScreen.kt — the built "Connected" line + +/** The reconnect affordance, exactly as ConnectionBanner.kt names it. */ +export const RECONNECT_LABEL = "Reconnect"; + +/** Idle banner copy, verbatim from ConnectionBanner.kt. */ +export const IDLE_BANNER_TEXT = + "Not connected. Enter the server URL in Settings, then connect."; + +/** ConnectionBanner.kt's suffix while the client has a retry scheduled. */ +export const RETRYING_SUFFIX = " \u00b7 retrying with backoff"; + +/** What the app does with the connection the moment it becomes visible again. */ +export const ForegroundAction = Object.freeze({ + /** Leave the connection exactly as it is. */ + LeaveAlone: "LeaveAlone", + /** Reconnect now, cancelling any pending reconnect delay. */ + Reconnect: "Reconnect", +}); + +/** + * Derive the persistent banner from the client's connection state. + * + * `tone` names the Material container role the stylesheet paints + * (surfaceVariant for idle/connecting, errorContainer for disconnected, + * primary/ok for connected); `text` is the app's own copy; `action` is the + * reconnect affordance, offered only while idle or disconnected and only when an + * endpoint is configured (ConnectionBanner.kt's `actionEnabled`). ConnectionBanner.kt + * renders nothing once connected, so the page's explicit green "Connected" (the + * primary-coloured state SettingsScreen.kt shows) is the one visible difference. + * + * The disconnected copy is verbatim ConnectionBanner.kt: `Disconnected: + * {message}` plus ` · retrying with backoff` while a retry is scheduled. That + * banner text deliberately omits the attempt number (Android only names it while + * Connecting), so the page surfaces the retry attempt in its header state badge + * instead — see `stateBadge` — rather than diverging from the banner wording. + */ +export function bannerState(connection, { hasEndpoint = false } = {}) { + const c = connection ?? {}; + switch (c.kind) { + case "connected": + return { tone: "ok", text: "Connected", action: null }; + case "connecting": + return { + tone: "connecting", + text: `Connecting (attempt ${c.attempt ?? 0})\u2026`, + action: null, + }; + case "disconnected": { + const reason = String(c.reason ?? "").trim() || "connection closed"; + const retry = c.retrying ? RETRYING_SUFFIX : ""; + return { + tone: "error", + text: `Disconnected: ${reason}${retry}`, + action: hasEndpoint ? RECONNECT_LABEL : null, + }; + } + default: + return { + tone: "idle", + text: IDLE_BANNER_TEXT, + action: hasEndpoint ? RECONNECT_LABEL : null, + }; + } +} + +/** + * The app's return-to-foreground policy in one place (ConnectionRecovery.kt). + * + * A deliberate Disconnect is the only way the client reaches Idle, so Idle is + * left alone; every other state reconnects. A still-Connected socket is not + * trusted on return — a frozen process or a suspended tab can leave it claiming + * Connected while it answers nothing — so the caller probes it and passes the + * verdict as `confirmedAlive`, which is consulted only for Connected. + */ +export function foregroundAction(state, confirmedAlive) { + switch (state?.kind) { + case "idle": + return ForegroundAction.LeaveAlone; + case "connected": + return confirmedAlive ? ForegroundAction.LeaveAlone : ForegroundAction.Reconnect; + default: + // Connecting and Disconnected both carry their own answer; an unknown state + // is never trusted, so it reconnects like the app's non-Connected states. + return ForegroundAction.Reconnect; + } +} + +/** + * Compare the page's protocol with the server's `pong.protocol`. Returns null + * unless both values are present and differ, because a server that omits the + * field (older build) must not be flagged; otherwise a warning naming both. + */ +export function protocolMismatch(clientProtocol, serverProtocol) { + if (!isProtocol(clientProtocol) || !isProtocol(serverProtocol)) return null; + if (Number(clientProtocol) === Number(serverProtocol)) return null; + return `Protocol mismatch: this page speaks protocol ${clientProtocol}, the server reports ${serverProtocol}.`; +} + +function isProtocol(value) { + return value !== null && value !== undefined && value !== "" && !Number.isNaN(Number(value)); +} + +/** + * The header's compact connection state badge. It is the page's own indicator + * (Android renders the same facts in SettingsScreen.kt's connection card): the + * one job it does that ConnectionBanner.kt's banner text does not is name the + * retry attempt while disconnected, so "reason + retrying + attempt" are all + * visible at a glance. `tone` names the dot colour class (ok/warn/bad/idle). + */ +export function stateBadge(connection) { + const c = connection ?? {}; + switch (c.kind) { + case "connected": + return { tone: "ok", text: "connected" }; + case "connecting": + return { tone: "warn", text: `connecting\u2026 (attempt ${c.attempt ?? 0})` }; + case "disconnected": { + const reason = String(c.reason ?? "").trim(); + const retry = c.retrying ? (c.attempt ? `attempt ${c.attempt}, retrying` : "retrying") : c.attempt ? `attempt ${c.attempt}` : ""; + return { tone: "bad", text: `disconnected${reason ? ` \u2014 ${reason}` : ""}${retry ? ` (${retry})` : ""}` }; + } + default: + return { tone: "idle", text: "idle" }; + } +} + +/** + * Render the server's `pong.build` (version/commit/dirty) for the banner, so a + * stale server is visible at a glance. The shape is SettingsScreen.kt's exactly: + * `Server build {version} ({commit})`. Missing fields are tolerated: nothing is + * shown when there is nothing to say. + * + * No separate dirty marker: internal/buildinfo already folds a dirty tree into + * `version` as a `-dirty` suffix (buildinfo.go), so `Server build v1-dirty (abc)` + * is the honest, non-duplicated form (Android renders no dirty marker either). + */ +export function serverBuildLabel(build) { + const info = build && typeof build === "object" ? build : {}; + const version = String(info.version ?? "").trim(); + const commit = String(info.commit ?? "").trim(); + const parts = []; + if (version) parts.push(version); + if (commit) parts.push(`(${commit})`); + if (!parts.length) return ""; + return `Server build ${parts.join(" ")}`; +} + +/** + * The live-stream badge, mirroring LiveBadge.kt / RunStream.kt: the stream is + * "live" only while a shown run is executing and the socket is connected, + * "reconnecting" while the socket is coming back, and "not live" otherwise. The + * word always carries the meaning, so colour is never the only signal. + */ +export function liveBadgeState(run, connection) { + const executing = Boolean(run && run.executing); + const kind = connection?.kind; + if (executing && kind === "connected") return { tone: "live", label: "live" }; + if (executing && (kind === "connecting" || kind === "disconnected")) { + return { tone: "reconnecting", label: "reconnecting" }; + } + return { tone: "not-live", label: "not live" }; +} diff --git a/web/src/protocol.js b/web/src/protocol.js index 65fd52cf..cc7946d1 100644 --- a/web/src/protocol.js +++ b/web/src/protocol.js @@ -25,6 +25,15 @@ export const Protocol = Object.freeze({ FAILURE_END: "#failure", }); +/** + * The integer wire protocol this page speaks. Mirrors `ProtocolVersion` in + * internal/protocol/identity.go and the value the Android client compares in + * `data/protocol/Message.kt` (the `protocol` field of the `pong` reply). It is + * compared as a number, never a string; a differing server value is surfaced as + * a warning rather than silently misread. + */ +export const PROTOCOL_VERSION = 1; + export function isTerminal(target) { return target === Protocol.SUCCESS_END || target === Protocol.FAILURE_END; } diff --git a/web/styles.css b/web/styles.css index 1c508c9b..1d021d37 100644 --- a/web/styles.css +++ b/web/styles.css @@ -810,3 +810,55 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- border: 1px solid var(--border); background: var(--surface); } + +/* --------------------------------------------------------------------------- + Transport: the persistent connection banner (T5) and the live badge. The + banner is in normal flow directly under the header, so it can never cover the + content; its container colours follow ConnectionBanner.kt's Material roles + (surfaceVariant idle/connecting, errorContainer disconnected, primary + connected). Hand-written, on the app's dark palette. + --------------------------------------------------------------------------- */ + +.conn-banner { + display: flex; + gap: 10px; + align-items: center; + padding: 8px 16px; + font-size: 13px; + border-bottom: 1px solid var(--border); + background: var(--surface-2); + color: var(--text); +} +.conn-banner[hidden] { display: none; } +.conn-banner-dot::before { content: "\25cf"; } +.conn-banner-text { font-weight: 500; } +.conn-build { margin-left: auto; color: var(--muted); font-size: 12px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; } +.conn-warning { color: var(--warn); font-weight: 600; } + +/* Idle: surfaceVariant (never an error colour — nothing is wrong yet). */ +.conn-idle { background: var(--surface-2); color: var(--muted); } +.conn-idle .conn-banner-dot::before { color: var(--muted); } + +/* Connecting: surfaceVariant with a warm dot, matching the state badge. */ +.conn-connecting { background: var(--surface-2); color: var(--muted); } +.conn-connecting .conn-banner-dot::before { color: var(--warn); } + +/* Disconnected: errorContainer. */ +.conn-error { background: #2c1616; color: var(--bad); } +.conn-error .conn-banner-dot::before { color: var(--bad); } +.conn-error .conn-build { color: var(--muted); } + +/* Connected: an explicit green (primary) state, the page's one visible + difference from ConnectionBanner.kt, which renders nothing once connected. */ +.conn-ok { background: #12251b; color: var(--ok); } +.conn-ok .conn-banner-dot::before { color: var(--ok); } + +/* Live-stream badge (LiveBadge.kt): a dot plus the honest word, so colour is + never the only signal. */ +.live-badge { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); white-space: nowrap; } +.live-badge .live-dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; } +.live-live { color: var(--ok); } +.live-reconnecting { color: var(--warn); } +.live-reconnecting .live-dot { opacity: 0.4; } +.live-not-live { color: var(--muted); } +.live-not-live .live-dot { opacity: 0.4; } diff --git a/web/test/connection.test.mjs b/web/test/connection.test.mjs new file mode 100644 index 00000000..d8d80a6b --- /dev/null +++ b/web/test/connection.test.mjs @@ -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}`); + } +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index d4451115..1514487a 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -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) {