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
+152 -42
View File
@@ -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();