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:
+152
-42
@@ -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();
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user