Merge lane-go: titles, verdicts, human stage, line result format, stale-client guard

Integrates nine commits of reviewed work from the lane-go branch after the
automated resolver failed on this merge five times (each attempt dying on the
malformed-result defect whose fix is contained in this same merge).

Integration decisions:
- Search: kept main's shipped design (Store.Search + SearchResponse.Results) and
  dropped lane-go's parallel, older attempt (an unused Message.Matches field, an
  absent runs.search, and two partial TUI plumbing blocks). lane-go itself did not
  compile: protocol.SearchMatch was undefined and model.go referenced searchNav,
  requestSearch and applyRunNav, which exist nowhere. Those partial TUI blocks are
  removed; the queued TUI omni-search item will implement the surface properly on
  main's design.
- Both sides' additions are kept where they are independent: run titles and
  provenance, the human decision stage and its CLI/TUI surface, the derived stage
  verdict, the stale-client guard, the line-oriented result format, and main's
  search command.
- The search key's help label is now "/ omni search"; the two tests asserting the
  old label are updated rather than the label reverted.
- docs/cli.md and the packaged operations reference carry both sides' text.

Verified: go build ./... , go vet ./... and the full go test ./... suite pass.
This commit is contained in:
2026-10-16 22:21:43 +01:00
669 changed files with 7205 additions and 276 deletions
+141
View File
@@ -0,0 +1,141 @@
# Pipelines web spike (Route B)
A throwaway, dependency-free browser client that proves the Pipelines
**WebSocket protocol works from a web page** end to end. It is a spike, not a
product: it renders a pipeline list and a run detail and nothing else.
This directory is deliberately **separate from `android/`** and does not touch
it. The Android app remains the Kotlin/Compose client.
## Why this route
Two ways to expose the app as a web app were considered:
- **Route A — Compose Multiplatform Web (WASM):** reuse the Kotlin protocol
layer and Compose UI. Most code reuse, but needs the Kotlin/WASM toolchain.
- **Route B — browser-native client (this spike):** a small JS app using the
browser's native `WebSocket`. No toolchain, browser-native behaviour, and it
can be verified against a live server immediately.
This spike is Route B. The `android/` protocol models were the spec: the wire
format, server-URL rules and reply matching here mirror
`android/app/src/main/java/net/awan/pipelines/data/`.
## Safety (unchanged from the Android client)
- **Trusted LAN/VPN only.** The Pipelines API has **no authentication** and is
**not internet-safe**. Do not expose the server to untrusted networks. A web
page widens that surface: any tab can open the socket.
- **No secrets.** Nothing is stored except the server URL, in `localStorage`.
- **No hardcoded server.** The URL is entered by the user; there is no default
address baked in.
## Layout
| File | Android counterpart | Notes |
| --- | --- | --- |
| `src/protocol.js` | `data/protocol/Message.kt` (constants) | types + `#success`/`#failure` |
| `src/serverUrl.js` | `data/transport/ServerUrl.kt` | `validateServerUrl`, `resolveArtifactUrl` |
| `src/client.js` | `data/transport/PipelinesClient.kt` | one reused socket, id matching, backoff. DOM-free |
| `src/repository.js` | `data/PipelinesRepository.kt` | typed request builders |
| `src/app.js` | `ui/**` | DOM UI: pipeline list + run detail |
| `serve.mjs` | — | zero-dep static server |
| `test/*.test.mjs` | `app/src/test/**` | `node --test` |
| `test/smoke.mjs` | — | live end-to-end against a running server |
`client.js` is DOM-free on purpose, so the smoke test drives the **same**
transport module the page uses.
## Run it
```sh
cd web
node serve.mjs # http://127.0.0.1:8090/
node serve.mjs --host 0.0.0.0 # reachable from other devices (trusted LAN/VPN)
```
`serve.mjs` both serves the page and **proxies `/connect`** to the Pipelines
server (`--pipelines 127.0.0.1:8080` by default), so the page and the WebSocket
are one origin. The page defaults its URL field to `ws://<this page's host>/connect`
(the proxy) — just press **Connect**. Nothing is hardcoded: the default is derived
from wherever the page was loaded and can be overridden.
### Why the page cannot connect directly (`403`)
`internal/server/websocket.go` calls `websocket.Accept(w, r, nil)` —
`github.com/coder/websocket` — which **rejects an upgrade whose `Origin` host
does not match the request `Host`**. A browser page served from `:8090` opening
`ws://HOST:8080/connect` sends `Origin: http://HOST:8090` and is refused:
```
HTTP/1.1 403 Forbidden
request Origin "HOST:8090" is not authorized for Host "HOST:8080"
```
A Node or `curl` client sends no `Origin` and is accepted — which is why the
smoke test passes while a browser does not. The proxy sidesteps this by making
the page same-origin and dropping the `Origin` header on the way through (the
server has no authentication, so nothing is lost). Any web client that is served
from a different origin than the Pipelines server hits this same 403.
To open the page from another device, bind `--host 0.0.0.0` and use this
machine's Tailscale/LAN address for the page only, e.g.
`http://100.85.25.33:8090/`, then press Connect (the field already holds
`ws://100.85.25.33:8090/connect`). Both hops are plaintext, so there is no
mixed-content block; only do this on a trusted tailnet/VPN.
## Test it
```sh
cd web
node --test test/ # unit tests, no server
PIPELINES_WS_URL=ws://127.0.0.1:8080/connect node test/smoke.mjs # live
```
`node --test` covers the ported URL validation/artifact resolution and the
transport (id matching, serialization order, error replies, timeouts,
not-connected guard, reconnect). `smoke.mjs` connects to a real server and runs
`ping`, `list_pipelines`, `list_runs`, `get_pipeline`, `get_run`, and (when the
newest run has artifacts) an artifact `HEAD`.
## Verification status
Run on macOS with Node v26.9.0 against a live `pipelines` server on
`ws://127.0.0.1:8080/connect`:
- `node --test test/` → **20 tests, 0 failures.**
- `node test/smoke.mjs` → **SMOKE PASS (6 checks)**: websocket connected,
`ping -> pong`, `list_pipelines -> 14 pipelines`, `list_runs -> 189 runs`,
`get_pipeline #1`, `get_run #189`. No artifact fetch (that run had none).
- `node --check` parses every source and test file.
- `serve.mjs` serves `/`, `index.html`, `styles.css` and each `src/*.js` with the
right content type (200); `/favicon.ico` is 204; `/nope.js` is 404; with
`curl --path-as-is` no raw `..` path escapes `web/` (traversal attempts either
serve a file inside `web/` or 404).
The cross-origin `403` and the proxy fix were verified on macOS against the live
server (`ws://100.85.25.33:8080/connect`):
- Direct handshake with `Origin: http://100.85.25.33:8090` → `HTTP/1.1 403
Forbidden` (`request Origin "100.85.25.33:8090" is not authorized for Host
"100.85.25.33:8080"`); the same handshake without `Origin` → `101 Switching
Protocols`.
- Through the proxy (`:8090`) with the same browser `Origin` → `101 Switching
Protocols`.
- `PIPELINES_WS_URL=ws://100.85.25.33:8090/connect node test/smoke.mjs` →
**SMOKE PASS (6 checks)** — a full request/reply session over the tunnel.
**Not verified:** the rendered page itself. No desktop browser was connected to
this session, so the DOM UI was not opened, clicked or screenshotted. `app.js`
parses and its data path is exercised through the shared `client`/`repository`/
`serverUrl` modules, but its rendering and event wiring are unproven. Also
unverified: `wss://`/TLS (no TLS server was available) and multiple concurrent
browser tabs.
## Next step
Before committing to a route, open `http://127.0.0.1:8090/` in a browser, connect
to the running server, and confirm the list/detail flow. If Route A is chosen
instead, the `data/`-layer mapping in the table above is the port checklist; the
Android-API friction lives in the artifact viewer, navigation, lifecycle and
`SharedPreferences` touchpoints (`android/README.md` documents them).
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Pipelines — web spike</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<noscript>This spike needs JavaScript to open the WebSocket connection.</noscript>
<div id="noscript-hint" class="banner warn">
Trusted LAN/VPN only. The Pipelines server has no authentication and is not
internet-safe.
</div>
<script type="module" src="./src/app.js"></script>
</body>
</html>
+12
View File
@@ -0,0 +1,12 @@
{
"name": "pipelines-web-spike",
"version": "0.0.0",
"private": true,
"type": "module",
"description": "Throwaway browser-native spike proving the Pipelines WebSocket protocol works from a web client. No dependencies.",
"scripts": {
"serve": "node serve.mjs",
"test": "node --test test/",
"smoke": "node test/smoke.mjs"
}
}
+126
View File
@@ -0,0 +1,126 @@
// Zero-dependency static file server + WebSocket proxy for the spike.
// node serve.mjs [--port 8090] [--host 0.0.0.0] [--pipelines 127.0.0.1:8080]
//
// Serves this directory and proxies GET/Upgrade /connect to the Pipelines
// server, so the page and the WebSocket share one origin.
//
// Why the proxy exists: internal/server/websocket.go calls
// `websocket.Accept(w, r, nil)` (github.com/coder/websocket), which rejects an
// upgrade whose Origin host does not match the request Host — a browser would
// get 403 from a cross-origin page (a Node/curl client sends no Origin and is
// unaffected, which is why the smoke test passes). Proxying makes the page
// same-origin, and the Origin header is dropped on the way through because the
// server has no authentication and needs none.
//
// The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN.
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import { extname, join, normalize, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import net from "node:net";
const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url)));
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".map": "application/json; charset=utf-8",
};
function flag(argv, name, fallback) {
const i = argv.indexOf(name);
if (i !== -1 && argv[i + 1]) return argv[i + 1];
return fallback;
}
function parsePort(argv) {
return Number(flag(argv, "--port", process.env.PORT ?? 8090));
}
/** Resolve a request path to a file inside ROOT, or null if it escapes. */
function resolvePath(urlPath) {
const decoded = decodeURIComponent(urlPath.split("?")[0]);
const rel = normalize(decoded).replace(/^([/\\])+/, "");
const target = resolve(join(ROOT, rel || "index.html"));
if (target !== ROOT && !target.startsWith(ROOT + sep)) return null;
return target;
}
const server = createServer(async (req, res) => {
const pathname = (req.url ?? "/").split("?")[0];
if (pathname === "/favicon.ico") {
res.writeHead(204).end(); // no icon; keeps the console free of a 404
return;
}
const target = resolvePath(req.url ?? "/");
if (!target) {
res.writeHead(403).end("Forbidden");
return;
}
try {
let path = target;
const info = await stat(path).catch(() => null);
if (info?.isDirectory()) path = join(path, "index.html");
const body = await readFile(path);
res.writeHead(200, {
"Content-Type": MIME[extname(path)] ?? "application/octet-stream",
"Cache-Control": "no-store",
});
res.end(body);
} catch {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
}
});
// ---------------------------------------------------------------------------
// WebSocket proxy for /connect
// ---------------------------------------------------------------------------
const pipelinesTarget = flag(
process.argv,
"--pipelines",
process.env.PIPELINES_TARGET ?? "127.0.0.1:8080",
);
const targetPort = Number(pipelinesTarget.split(":").at(-1));
const targetHost = pipelinesTarget.slice(0, pipelinesTarget.lastIndexOf(":")) || "127.0.0.1";
function proxyUpgrade(req, clientSocket, clientHead) {
const upstream = net.connect(targetPort, targetHost, () => {
const headers = { ...req.headers };
delete headers.origin; // see the header comment: the server forbids a mismatched Origin
headers.host = `${targetHost}:${targetPort}`;
const block = Object.entries(headers)
.filter(([, v]) => v != null)
.map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : v}`)
.join("\r\n");
upstream.write(`GET ${req.url} HTTP/1.1\r\n${block}\r\n\r\n`);
if (clientHead?.length) upstream.write(clientHead);
upstream.pipe(clientSocket);
clientSocket.pipe(upstream);
});
upstream.on("error", () => clientSocket.destroy());
clientSocket.on("error", () => upstream.destroy());
}
server.on("upgrade", (req, clientSocket, clientHead) => {
const pathname = (req.url ?? "").split("?")[0];
if (pathname !== "/connect") {
clientSocket.destroy();
return;
}
proxyUpgrade(req, clientSocket, clientHead);
});
const port = parsePort(process.argv);
const host = flag(process.argv, "--host", "127.0.0.1");
server.listen(port, host, () => {
const shown = host === "0.0.0.0" ? "127.0.0.1" : host;
console.log(`web spike: http://${shown}:${port}/ (bound ${host}:${port})`);
console.log(`proxying /connect -> ws://${targetHost}:${targetPort}/connect`);
});
+522
View File
@@ -0,0 +1,522 @@
// Spike web UI: pipeline list + run detail over the live WebSocket protocol.
// Deliberately small and DOM-only (no framework, no build step). Every value
// that came from the server is set with textContent, never innerHTML.
import { PipelinesClient } from "./client.js";
import { PipelinesRepository } from "./repository.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
/**
* The page is normally served by serve.mjs, which also proxies /connect to the
* Pipelines server. Defaulting to this page's own origin therefore points at
* that proxy and keeps the page and the WebSocket same-origin — the server
* rejects a cross-origin upgrade with 403. Nothing is hardcoded: the value is
* derived from wherever the page was loaded, and the user can override it.
*/
function defaultServerUrl() {
if (typeof location === "undefined" || !location.host) return "";
const scheme = location.protocol === "https:" ? "wss" : "ws";
return `${scheme}://${location.host}/connect`;
}
const client = new PipelinesClient();
const repo = new PipelinesRepository(client);
const state = {
view: "pipelines",
url: localStorage.getItem(STORAGE_KEY) ?? defaultServerUrl(),
connection: client.state,
pipelines: [],
runs: [],
usage: null,
pipelineDetail: null,
runDetail: null,
selectedPipelineId: null,
selectedRunId: null,
loading: false,
error: "",
};
let runPoll = null;
// ---------------------------------------------------------------------------
// DOM helpers
// ---------------------------------------------------------------------------
function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value == null || value === false) continue;
if (key === "class") node.className = value;
else if (key === "text") node.textContent = value;
else if (key.startsWith("on") && typeof value === "function") {
node.addEventListener(key.slice(2).toLowerCase(), value);
} else node.setAttribute(key, value === true ? "" : String(value));
}
for (const child of children.flat()) {
if (child == null || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
function fmtSeconds(total) {
const s = Math.max(0, Math.round(total));
const hh = Math.floor(s / 3600);
const mm = Math.floor((s % 3600) / 60);
const ss = s % 60;
if (hh > 0) return `${hh}h ${mm}m ${ss}s`;
if (mm > 0) return `${mm}m ${ss}s`;
return `${ss}s`;
}
function fmtTime(iso) {
if (!iso) return "—";
const ms = Date.parse(iso);
return Number.isNaN(ms) ? iso : new Date(ms).toLocaleString();
}
function fmtDuration(startIso, finishIso) {
if (!startIso) return "—";
const start = Date.parse(startIso);
if (Number.isNaN(start)) return "—";
const end = finishIso ? Date.parse(finishIso) : Date.now();
if (Number.isNaN(end)) return "—";
// A future start (clock skew) reads as 0s, matching the Android client.
return fmtSeconds(Math.max(0, (end - start) / 1000));
}
function statusClass(status) {
return `chip chip-${String(status || "unknown").toLowerCase()}`;
}
function isExecuting(run) {
return Boolean(run && run.executing);
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
const header = h("header", { class: "topbar" });
const content = h("main", { id: "content" });
document.body.append(header, content);
function renderHeader() {
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()),
),
);
}
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");
}
}
function render() {
renderHeader();
renderContent();
}
function renderContent() {
const nodes = [];
if (state.error) {
nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error));
}
nodes.push(
h(
"nav",
{ class: "tabs" },
tabButton("pipelines", `Pipelines (${state.pipelines.length})`),
tabButton("runs", `Runs (${state.runs.length})`),
h("span", { class: "spacer" }),
h("button", { class: "ghost", text: "Refresh", onclick: () => loadCurrentView(true) }),
),
);
const split = h("div", { class: "split" });
if (state.view === "pipelines") {
split.append(renderPipelineList(), renderPipelineDetail());
} else {
split.append(renderRunList(), renderRunDetail());
}
nodes.push(split);
content.replaceChildren(...nodes);
}
function tabButton(view, label) {
return h("button", {
class: `tab${state.view === view ? " active" : ""}`,
text: label,
onclick: () => {
state.view = view;
state.error = "";
renderContent();
if (view === "runs" && !state.runs.length) loadCurrentView();
if (view === "pipelines" && !state.pipelines.length) loadCurrentView();
},
});
}
function renderPipelineList() {
const list = h("div", { class: "list" });
if (state.loading && !state.pipelines.length) {
list.append(h("div", { class: "muted pad", text: "Loading…" }));
return list;
}
if (!state.pipelines.length) {
list.append(h("div", { class: "muted pad", text: "No pipelines." }));
return list;
}
for (const p of state.pipelines) {
list.append(
h(
"button",
{
class: `row${state.selectedPipelineId === p.id ? " selected" : ""}`,
onclick: () => selectPipeline(p),
},
h("span", { class: "row-title", text: p.name || `pipeline ${p.id}` }),
h("span", { class: "row-meta", text: `#${p.id} · v${p.version} · ${p.stages} stage${p.stages === 1 ? "" : "s"}` }),
),
);
}
return list;
}
function renderPipelineDetail() {
const d = state.pipelineDetail;
const pane = h("div", { class: "detail" });
if (!d) {
pane.append(h("div", { class: "muted pad", text: "Select a pipeline." }));
return pane;
}
pane.append(
h("h2", { text: d.name || `pipeline ${d.id}` }),
h(
"div",
{ class: "kv" },
kv("ID / version", `#${d.id} · v${d.version}`),
kv("Stages", String(d.stages ?? (d.graph?.stages?.length ?? 0))),
kv("Content hash", d.content_hash || "—"),
kv("Created", fmtTime(d.created_at)),
kv("Updated", fmtTime(d.updated_at)),
kv("Latest version", d.latest_version ? String(d.latest_version) : "—"),
),
);
const stages = d.graph?.stages ?? [];
if (stages.length) {
pane.append(h("h3", { text: "Stages" }));
const ul = h("ul", { class: "stages" });
for (const s of stages) {
const outcomes = Object.keys(s.edges ?? {}).join(", ");
ul.append(
h(
"li",
{},
h("code", { text: s.key }),
s.type ? h("span", { class: "chip", text: s.type }) : null,
outcomes ? h("span", { class: "muted", text: `→ ${outcomes}` }) : null,
),
);
}
pane.append(ul);
}
return pane;
}
function renderRunList() {
const list = h("div", { class: "list" });
if (state.usage) {
list.append(
h(
"div",
{ class: "usage" },
h("span", { text: `${state.usage.total} total` }),
h("span", { class: "ok", text: `${state.usage.succeeded} succeeded` }),
h("span", { class: "bad", text: `${state.usage.failed} failed` }),
h("span", { class: "warn", text: `${state.usage.active} active` }),
),
);
}
if (state.loading && !state.runs.length) {
list.append(h("div", { class: "muted pad", text: "Loading…" }));
return list;
}
if (!state.runs.length) {
list.append(h("div", { class: "muted pad", text: "No runs." }));
return list;
}
for (const r of state.runs) {
list.append(
h(
"button",
{
class: `row${state.selectedRunId === r.id ? " selected" : ""}`,
onclick: () => selectRun(r.id),
},
h(
"span",
{ class: "row-head" },
h("span", { class: "row-title", text: r.title || r.name || `run ${r.id}` }),
h("span", { class: statusClass(r.status), text: r.status || "unknown" }),
),
h(
"span",
{ class: "row-meta" },
`#${r.id} · ${fmtTime(r.created_at)} · `,
isExecuting(r) ? h("em", { text: fmtDuration(r.created_at, "") }) : fmtDuration(r.created_at, r.finished_at),
),
r.diagnostic ? h("span", { class: "row-diag", text: r.diagnostic }) : null,
),
);
}
return list;
}
function renderRunDetail() {
const d = state.runDetail;
const pane = h("div", { class: "detail" });
if (!d) {
pane.append(h("div", { class: "muted pad", text: "Select a run." }));
return pane;
}
pane.append(
h(
"h2",
{},
d.title || d.name || `run ${d.id}`,
h("span", { class: statusClass(d.status), text: d.status || "unknown" }),
),
h(
"div",
{ class: "kv" },
kv("Run ID", `#${d.id}`),
kv("Pipeline", `#${d.pipeline_id} @ v${d.version}`),
kv("Outcome", d.outcome || "—"),
kv("Current stage", d.current_stage || "—"),
kv("Started", fmtTime(d.created_at)),
kv("Duration", isExecuting(d) ? `${fmtDuration(d.created_at, "")} (running)` : fmtDuration(d.created_at, d.finished_at)),
kv("Completed steps", String(d.completed_steps ?? 0)),
d.diagnostic ? kv("Diagnostic", d.diagnostic) : null,
),
);
const steps = d.steps ?? [];
pane.append(h("h3", { text: `Steps (${steps.length})` }));
if (!steps.length) {
pane.append(h("div", { class: "muted pad", text: "No steps recorded yet." }));
return pane;
}
const list = h("div", { class: "steps" });
for (const s of steps) {
list.append(
h(
"div",
{ class: "step" },
h(
"div",
{ class: "step-head" },
h("code", { text: `${s.sequence}. ${s.stage}` }),
h("span", { class: statusClass(s.status), text: s.status || "unknown" }),
s.outcome ? h("span", { class: "chip", text: s.outcome }) : null,
h("span", { class: "muted", text: fmtDuration(s.started_at, s.finished_at) }),
),
h(
"div",
{ class: "kv tight" },
kv("Target", s.target || "—"),
kv("Visit", s.control ? `${s.control.visit}/${s.control.max_visits}` : "—"),
kv("Session", s.session_id || "—"),
s.diagnostic ? kv("Diagnostic", s.diagnostic) : null,
),
renderArtifacts(s),
),
);
}
pane.append(list);
return pane;
}
function renderArtifacts(step) {
const artifacts = step.artifacts ?? [];
if (!artifacts.length) return null;
const wrap = h("div", { class: "artifacts" }, h("span", { class: "muted", text: "Artifacts: " }));
for (const a of artifacts) {
const href = resolveArtifactUrl(state.url, a.url);
if (href) {
wrap.append(h("a", { href, target: "_blank", rel: "noreferrer", text: a.name || a.url }));
} else {
wrap.append(h("span", { class: "muted", text: `${a.name || a.url} (no server URL)` }));
}
}
return wrap;
}
function kv(key, value) {
return h(
"div",
{ class: "kv-row" },
h("span", { class: "kv-key", text: key }),
h("span", { class: "kv-val", text: value }),
);
}
// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------
function setError(err) {
state.error = err instanceof Error ? err.message : String(err);
state.loading = false;
renderContent();
}
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);
// The `state` listener kicks off the initial load once connected.
}
async function onConnected() {
try {
await repo.ping();
} catch (err) {
setError(err);
return;
}
await loadCurrentView();
}
async function loadCurrentView(force = false) {
if (state.connection.kind !== "connected") {
state.error = "Connect to the server first.";
renderContent();
return;
}
state.loading = true;
state.error = "";
renderContent();
try {
if (state.view === "pipelines") {
state.pipelines = await repo.listPipelines();
} else {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
state.usage = usage;
}
state.loading = false;
renderContent();
// Keep the current selection fresh after a refresh.
if (force && state.view === "runs" && state.selectedRunId) {
await selectRun(state.selectedRunId, { silent: true });
}
} catch (err) {
setError(err);
}
}
async function selectPipeline(summary) {
state.selectedPipelineId = summary.id;
state.pipelineDetail = null;
renderContent();
try {
state.pipelineDetail = await repo.getPipeline(summary.id, summary.version);
renderContent();
} catch (err) {
setError(err);
}
}
async function selectRun(id, { silent = false } = {}) {
state.selectedRunId = id;
if (!silent) {
state.runDetail = null;
renderContent();
}
try {
state.runDetail = await repo.getRun(id);
renderContent();
updateRunPoll();
} catch (err) {
if (!silent) setError(err);
else stopRunPoll();
}
}
function updateRunPoll() {
stopRunPoll();
if (state.view === "runs" && state.selectedRunId && isExecuting(state.runDetail)) {
runPoll = setInterval(() => selectRun(state.selectedRunId, { silent: true }), 1000);
}
}
function stopRunPoll() {
if (runPoll) {
clearInterval(runPoll);
runPoll = null;
}
}
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
client.addEventListener("state", (event) => {
const next = event.detail;
const wasConnected = state.connection.kind === "connected";
const previousKind = state.connection.kind;
state.connection = next;
if (next.kind === "connected" && !wasConnected) {
onConnected();
}
if (next.kind !== "connected" && previousKind === "connected") {
stopRunPoll();
}
render();
});
// Prefill from a previous session only; the user still confirms with Connect.
render();
+233
View File
@@ -0,0 +1,233 @@
// A single, reused WebSocket connection to /connect, mirroring
// android/.../data/transport/PipelinesClient.kt: requests are serialized, each
// carries a client-generated stable id, replies are matched by id, and
// unsolicited envelopes are dropped. There is no authentication of any kind.
//
// DOM-free on purpose: the browser app and the Node smoke test share this exact
// module, so the smoke test exercises the real client, not a re-implementation.
import { Protocol } from "./protocol.js";
/** A server `type:"error"` reply, surfaced with the server's own text. */
export class ProtocolError extends Error {
constructor(message) {
super(message);
this.name = "ProtocolError";
}
}
/** No live WebSocket connection is available for the request. */
export class NotConnectedError extends Error {
constructor(message = "Not connected to the Pipelines server") {
super(message);
this.name = "NotConnectedError";
}
}
const IDLE = "idle";
const CONNECTING = "connecting";
const CONNECTED = "connected";
const DISCONNECTED = "disconnected";
const NORMAL_CLOSURE = 1000;
export class PipelinesClient extends EventTarget {
#WebSocketImpl;
#backoffBaseMs;
#backoffMaxMs;
#requestTimeoutMs;
#random;
#ws = null;
#endpoint = null;
#manualClose = false;
#attempt = 0;
#seq = 0;
#pending = new Map(); // id -> { resolve, reject, timer }
#queue = Promise.resolve();
#reconnectTimer = null;
#state = { kind: IDLE, attempt: 0, reason: "", retrying: false };
constructor({
WebSocketImpl = globalThis.WebSocket,
backoffBaseMs = 1000,
backoffMaxMs = 30000,
requestTimeoutMs = 30000,
random = Math.random,
} = {}) {
super();
if (typeof WebSocketImpl !== "function") {
throw new Error("No WebSocket implementation available");
}
this.#WebSocketImpl = WebSocketImpl;
this.#backoffBaseMs = backoffBaseMs;
this.#backoffMaxMs = backoffMaxMs;
this.#requestTimeoutMs = requestTimeoutMs;
this.#random = random;
}
get state() {
return { ...this.#state };
}
#setState(next) {
this.#state = next;
this.dispatchEvent(new CustomEvent("state", { detail: this.state }));
}
/** Opens (or re-opens) the connection to a validated server URL. */
connect(validated) {
if (!validated || !validated.valid) {
throw new Error("server URL is not valid");
}
this.#endpoint = validated.wsUrl;
this.#manualClose = false;
this.#attempt = 0;
this.#clearReconnect();
this.#open();
}
/** Explicit user disconnect: stops reconnection and closes the socket. */
disconnect() {
this.#manualClose = true;
this.#clearReconnect();
const socket = this.#ws;
this.#ws = null;
try {
socket?.close(NORMAL_CLOSURE, "client closing");
} catch {
/* already closed */
}
this.#failPending("Disconnected");
this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false });
}
/**
* Sends one request and awaits the reply with the matching id. Serialized by a
* promise chain so concurrent screens cannot interleave frames.
*/
async call(request) {
const run = this.#queue.then(() => this.#doCall(request));
// Keep the chain alive even when a call rejects.
this.#queue = run.then(
() => undefined,
() => undefined,
);
return run;
}
async #doCall(request) {
const socket = this.#ws;
if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError();
const id = `web-${++this.#seq}`;
const payload = JSON.stringify({ ...request, id });
const reply = new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.#pending.delete(id);
reject(new Error(`request timed out after ${this.#requestTimeoutMs}ms`));
}, this.#requestTimeoutMs);
this.#pending.set(id, { resolve, reject, timer });
});
try {
socket.send(payload);
const response = await reply;
if (response.type === Protocol.ERROR) {
throw new ProtocolError((response.error || "").trim() || "server error");
}
return response;
} finally {
const entry = this.#pending.get(id);
if (entry) {
clearTimeout(entry.timer);
this.#pending.delete(id);
}
}
}
#open() {
const current = this.#endpoint;
if (!current) return;
this.#attempt += 1;
this.#setState({
kind: CONNECTING,
attempt: this.#attempt,
reason: "",
retrying: false,
});
const socket = new this.#WebSocketImpl(current);
this.#ws = socket;
socket.onopen = () => {
this.#attempt = 0;
this.#setState({ kind: CONNECTED, attempt: 0, reason: "", retrying: false });
};
socket.onmessage = (event) => this.#onMessage(event.data);
socket.onclose = (event) => {
this.#handleClosed(`Connection closed (${event.code ?? "?"})`);
};
socket.onerror = () => {
// Browsers withhold detail here; onclose carries the outcome.
};
}
#onMessage(data) {
if (typeof data !== "string") return; // the server is text-only
let message;
try {
message = JSON.parse(data);
} catch {
return; // malformed frame: never misattribute it to a request
}
const entry = message.id ? this.#pending.get(message.id) : null;
if (entry) {
this.#pending.delete(message.id);
clearTimeout(entry.timer);
entry.resolve(message);
}
// Unsolicited envelopes (for example the connection's initial pipeline_list)
// have no matching id and are intentionally dropped.
}
#failPending(reason) {
for (const [id, entry] of this.#pending) {
this.#pending.delete(id);
clearTimeout(entry.timer);
entry.reject(new Error(reason));
}
}
#handleClosed(reason) {
this.#ws = null;
this.#failPending(reason);
if (this.#manualClose) {
this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false });
return;
}
this.#scheduleReconnect(reason);
}
#scheduleReconnect(reason) {
if (this.#reconnectTimer) return;
this.#setState({
kind: DISCONNECTED,
attempt: this.#attempt,
reason,
retrying: true,
});
const shift = Math.min(Math.max(this.#attempt - 1, 0), 6);
const backoff = Math.min(this.#backoffBaseMs << shift, this.#backoffMaxMs);
const jitter = Math.floor(this.#random() * 400);
this.#reconnectTimer = setTimeout(() => {
this.#reconnectTimer = null;
if (!this.#manualClose && this.#endpoint) this.#open();
}, backoff + jitter);
}
#clearReconnect() {
if (this.#reconnectTimer) {
clearTimeout(this.#reconnectTimer);
this.#reconnectTimer = null;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
// Protocol command/type constants. Mirrors the subset of
// android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt and
// internal/protocol/*.go used by this spike, so renames cannot drift silently.
export const Protocol = Object.freeze({
PING: "ping",
PONG: "pong",
ERROR: "error",
LIST: "list_pipelines",
PIPELINE_LIST: "pipelines",
GET_PIPELINE: "get_pipeline",
PIPELINE: "pipeline",
LIST_RUNS: "list_runs",
RUNS: "runs",
GET_RUN: "get_run",
RUN: "run",
SUCCESS_END: "#success",
FAILURE_END: "#failure",
});
export function isTerminal(target) {
return target === Protocol.SUCCESS_END || target === Protocol.FAILURE_END;
}
/** Mirrors protocol.ResolveTarget: preserve the # shorthand as an explicit terminal. */
export function resolveTarget(outcome, target) {
if (target !== "#") return target;
return outcome === "error" ? Protocol.FAILURE_END : Protocol.SUCCESS_END;
}
+61
View File
@@ -0,0 +1,61 @@
// Typed access to the existing WebSocket protocol. Request builders and id
// matching live here so the app never constructs frames by hand or invents
// divergent field names. Mirrors android/.../data/PipelinesRepository.kt.
import { Protocol } from "./protocol.js";
import { ProtocolError } from "./client.js";
export class PipelinesRepository {
#client;
constructor(client) {
this.#client = client;
}
get connectionState() {
return this.#client.state;
}
connect(validated) {
this.#client.connect(validated);
}
disconnect() {
this.#client.disconnect();
}
ping() {
return this.#client.call({ type: Protocol.PING });
}
async listPipelines() {
return (await this.#client.call({ type: Protocol.LIST })).pipelines ?? [];
}
async getPipeline(id, version) {
const response = await this.#client.call({
type: Protocol.GET_PIPELINE,
pipeline_id: id,
version,
});
if (!response.detail) {
throw new ProtocolError("The server returned no pipeline detail.");
}
return response.detail;
}
async listRuns() {
const response = await this.#client.call({ type: Protocol.LIST_RUNS });
return { runs: response.runs ?? [], usage: response.usage ?? null };
}
async getRun(id) {
const response = await this.#client.call({
type: Protocol.GET_RUN,
run_id: id,
});
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
}
+107
View File
@@ -0,0 +1,107 @@
// Server-URL validation mirroring android/.../data/transport/ServerUrl.kt and
// internal/client/config.go: only ws/wss with a non-empty hostname and no
// userinfo/fragment. The endpoint path defaults to /connect, matching
// internal/server/websocket.go `GET /connect`.
export const ServerUrlKind = Object.freeze({
EMPTY: "EMPTY",
MALFORMED: "MALFORMED",
UNSUPPORTED_SCHEME: "UNSUPPORTED_SCHEME",
MISSING_HOST: "MISSING_HOST",
USER_INFO: "USER_INFO",
FRAGMENT: "FRAGMENT",
});
/**
* @returns {{valid:true, wsUrl:string, httpUrl:string, host:string, port:number, secure:boolean}
* |{valid:false, kind:string, message:string}}
*/
export function validateServerUrl(raw) {
const trimmed = (raw ?? "").trim();
if (!trimmed) {
return {
valid: false,
kind: ServerUrlKind.EMPTY,
message:
"Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect",
};
}
let url;
try {
url = new URL(trimmed);
} catch {
return {
valid: false,
kind: ServerUrlKind.MALFORMED,
message: "That is not a valid URL.",
};
}
const scheme = url.protocol.replace(/:$/, "").toLowerCase();
if (scheme !== "ws" && scheme !== "wss") {
return {
valid: false,
kind: ServerUrlKind.UNSUPPORTED_SCHEME,
message: `Unsupported scheme "${scheme}"; use ws:// (trusted LAN/VPN) or wss://`,
};
}
if (url.username || url.password) {
return {
valid: false,
kind: ServerUrlKind.USER_INFO,
message:
"Credentials are not supported; the server has no authentication. Remove userinfo from the URL",
};
}
if (url.hash) {
return {
valid: false,
kind: ServerUrlKind.FRAGMENT,
message: "Remove the # fragment; it is not part of the server endpoint",
};
}
if (!url.hostname) {
return {
valid: false,
kind: ServerUrlKind.MISSING_HOST,
message:
"The URL is missing a host, for example ws://192.168.1.20:8081/connect",
};
}
const secure = scheme === "wss";
const port = url.port ? Number(url.port) : secure ? 443 : 80;
let path = url.pathname || "";
if (!path || path === "/") path = "/connect";
const authority = url.host; // host + explicit port only when present
const search = url.search || "";
const wsUrl = `${scheme}://${authority}${path}${search}`;
const httpUrl = `${secure ? "https" : "http"}://${authority}${path}${search}`;
return { valid: true, wsUrl, httpUrl, host: url.hostname, port, secure };
}
/**
* Resolves a server-relative artifact url (for example "/artifacts/55/4/shot.png")
* against the configured server URL by mapping ws/wss to http/https and dropping
* the /connect path. Never hardcodes a host: a blank or invalid configuration, or
* a blank path, yields null so the UI can disable actions. An already-absolute
* http(s) url is returned unchanged. Mirrors ServerUrl.resolveArtifactUrl.
*/
export function resolveArtifactUrl(configured, artifactUrl) {
const relative = (artifactUrl ?? "").trim();
if (!relative) return null;
if (relative.startsWith("http://") || relative.startsWith("https://")) {
return relative;
}
const validated = validateServerUrl(configured);
if (!validated.valid) return null;
const { secure, host, port } = validated;
const defaultPort = secure ? 443 : 80;
const authority = port && port !== defaultPort ? `${host}:${port}` : host;
const origin = `${secure ? "https" : "http"}://${authority}`;
const path = relative.startsWith("/") ? relative : `/${relative}`;
return origin + path;
}
+144
View File
@@ -0,0 +1,144 @@
/* Throwaway spike styling. Dark-first, echoing the Android client's theme. */
:root {
color-scheme: dark;
--bg: #0e1513;
--surface: #171f1d;
--surface-2: #1f2a27;
--border: #2c3a36;
--text: #e2e8e6;
--muted: #9db0ab;
--accent: #7fd1bb;
--ok: #6bd39a;
--warn: #e6c268;
--bad: #ef8a8a;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.topbar {
display: flex;
gap: 16px;
align-items: center;
justify-content: space-between;
padding: 10px 16px;
background: var(--surface);
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 2;
flex-wrap: wrap;
}
.brand { display: flex; gap: 8px; align-items: baseline; }
.brand strong { font-size: 16px; }
.connbar { display: flex; gap: 8px; align-items: center; flex: 1 1 420px; justify-content: flex-end; }
input[type="text"] {
flex: 1 1 260px;
min-width: 200px;
padding: 7px 10px;
background: var(--surface-2);
color: var(--text);
border: 1px solid var(--border);
border-radius: 8px;
font: inherit;
}
button {
font: inherit;
padding: 7px 12px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--surface-2);
color: var(--text);
cursor: pointer;
}
button:hover { border-color: var(--accent); }
button.ghost { background: transparent; }
.tabs { display: flex; gap: 4px; align-items: center; padding: 10px 16px 0; }
.tabs .spacer { flex: 1; }
.tab { border-color: transparent; background: transparent; }
.tab.active { background: var(--surface-2); border-color: var(--border); color: var(--accent); }
.split { display: grid; grid-template-columns: minmax(260px, 380px) 1fr; gap: 16px; padding: 16px; align-items: start; }
@media (max-width: 760px) { .split { grid-template-columns: 1fr; } }
.list, .detail {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
}
.row {
display: block;
width: 100%;
text-align: left;
border: 0;
border-bottom: 1px solid var(--border);
border-radius: 0;
background: transparent;
padding: 10px 12px;
}
.row:last-child { border-bottom: 0; }
.row:hover { background: var(--surface-2); }
.row.selected { background: var(--surface-2); box-shadow: inset 3px 0 0 var(--accent); }
.row-head { display: flex; gap: 8px; justify-content: space-between; align-items: center; }
.row-title { font-weight: 600; }
.row-meta { display: block; color: var(--muted); font-size: 12px; margin-top: 2px; }
.row-diag { display: block; color: var(--warn); font-size: 12px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.usage { display: flex; gap: 12px; padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 12px; }
.detail { padding: 16px; }
.detail h2 { margin: 0 0 12px; display: flex; gap: 10px; align-items: center; }
.detail h3 { margin: 18px 0 8px; font-size: 14px; color: var(--muted); text-transform: none; }
.kv { display: grid; gap: 4px; }
.kv.tight { margin-top: 6px; }
.kv-row { display: grid; grid-template-columns: 150px 1fr; gap: 10px; }
.kv-key { color: var(--muted); }
.kv-val { word-break: break-word; }
.stages { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
.stages li { display: flex; gap: 8px; align-items: center; }
.steps { display: grid; gap: 8px; }
.step { border: 1px solid var(--border); border-radius: 10px; padding: 10px; }
.step-head { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.artifacts { margin-top: 8px; font-size: 12px; }
.artifacts a { color: var(--accent); margin-right: 10px; }
.chip { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; border: 1px solid var(--border); color: var(--muted); }
.chip-running, .chip-queued { color: var(--warn); border-color: var(--warn); }
.chip-succeeded { color: var(--ok); border-color: var(--ok); }
.chip-failed { color: var(--bad); border-color: var(--bad); }
.dot::before { content: "●"; margin-right: 6px; }
.dot.ok::before { color: var(--ok); }
.dot.warn::before { color: var(--warn); }
.dot.bad::before { color: var(--bad); }
.dot.idle::before { color: var(--muted); }
.state { color: var(--muted); white-space: nowrap; }
.muted { color: var(--muted); }
.ok { color: var(--ok); }
.warn { color: var(--warn); }
.bad { color: var(--bad); }
.pad { padding: 12px; }
.banner { padding: 8px 16px; }
.banner.warn { background: #2a2410; color: var(--warn); }
.banner.error { background: #2c1616; color: var(--bad); }
code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-size: 12px; }
+163
View File
@@ -0,0 +1,163 @@
// Client transport tests against a fake WebSocket: id matching, serialization,
// error replies, timeouts and the not-connected guard. No server required.
import { test } from "node:test";
import assert from "node:assert/strict";
import { PipelinesClient, ProtocolError, NotConnectedError } from "../src/client.js";
import { validateServerUrl } from "../src/serverUrl.js";
const VALID = validateServerUrl("ws://host:8080/connect");
class FakeWebSocket {
static instances = [];
constructor(url) {
this.url = url;
this.sent = [];
this.closed = null;
this.onopen = null;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
/** @type {((frame: any) => any | undefined) | null} */
this.reply = null;
FakeWebSocket.instances.push(this);
}
send(data) {
const frame = JSON.parse(data);
this.sent.push(frame);
const response = this.reply?.(frame);
if (response !== undefined) {
this.onmessage?.({ data: JSON.stringify(response) });
}
}
close(code, reason) {
this.closed = { code, reason };
this.onclose?.({ code, reason });
}
// test hooks
open() {
this.onopen?.({});
}
push(obj) {
this.onmessage?.({ data: JSON.stringify(obj) });
}
drop(code = 1006) {
this.onclose?.({ code, reason: "test" });
}
}
/** Let the client's serialized call chain run to the point where it has sent. */
const flush = () => new Promise((resolve) => setImmediate(resolve));
function freshClient(options = {}) {
FakeWebSocket.instances = [];
return new PipelinesClient({ WebSocketImpl: FakeWebSocket, ...options });
}
function connectedClient(options = {}) {
const client = freshClient(options);
client.connect(VALID);
const ws = FakeWebSocket.instances.at(-1);
ws.open();
return { client, ws };
}
test("a call before connect is rejected as not connected", async () => {
const client = freshClient();
await assert.rejects(() => client.call({ type: "ping" }), NotConnectedError);
});
test("a call sends a JSON frame with a generated id and resolves the matching reply", async () => {
const { client, ws } = connectedClient();
ws.reply = (frame) => ({ id: frame.id, type: "pong" });
const reply = await client.call({ type: "ping" });
assert.equal(reply.type, "pong");
assert.equal(ws.sent.length, 1);
assert.equal(ws.sent[0].type, "ping");
assert.match(ws.sent[0].id, /^web-\d+$/);
});
test("an error reply surfaces the server text as a ProtocolError", async () => {
const { client, ws } = connectedClient();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "nope" });
await assert.rejects(() => client.call({ type: "get_run" }), ProtocolError);
});
test("an unsolicited envelope with no matching id is dropped, not misattributed", async () => {
const { client, ws } = connectedClient();
ws.reply = undefined;
const pending = client.call({ type: "ping" });
let settled = false;
pending.then(() => (settled = true), () => (settled = true));
await flush();
ws.push({ type: "pipelines", pipelines: [] }); // no id
await flush();
assert.equal(settled, false);
const frame = ws.sent.at(-1);
ws.push({ id: frame.id, type: "pong" });
assert.equal((await pending).type, "pong");
});
test("a malformed frame is ignored and does not reject a pending call", async () => {
const { client, ws } = connectedClient();
const pending = client.call({ type: "ping" });
await flush();
ws.onmessage?.({ data: "{not json" });
const frame = ws.sent.at(-1);
ws.push({ id: frame.id, type: "pong" });
assert.equal((await pending).type, "pong");
});
test("a missing reply times out with a clear error", async () => {
const { client } = connectedClient({ requestTimeoutMs: 20 });
await assert.rejects(() => client.call({ type: "ping" }), /timed out after 20ms/);
});
test("concurrent calls are serialized in submission order", async () => {
const { client, ws } = connectedClient();
const order = [];
ws.reply = (frame) => {
order.push(frame.type);
return { id: frame.id, type: "ok" };
};
await Promise.all([client.call({ type: "a" }), client.call({ type: "b" })]);
assert.deepEqual(order, ["a", "b"]);
});
test("the state flow reports connecting then connected", async () => {
const seen = [];
const client = freshClient();
client.addEventListener("state", (e) => seen.push(e.detail.kind));
client.connect(VALID);
FakeWebSocket.instances.at(-1).open();
assert.deepEqual(seen, ["connecting", "connected"]);
});
test("an unexpected close fails pending calls and schedules a reconnect", async () => {
const { client, ws } = connectedClient({ backoffBaseMs: 1, backoffMaxMs: 5 });
const pending = client.call({ type: "ping" }); // never answered
await flush(); // let the call reach the socket before it is dropped
ws.drop(1006);
await assert.rejects(() => pending, /Connection closed/);
assert.equal(client.state.kind, "disconnected");
assert.equal(client.state.retrying, true);
client.disconnect(); // stop the reconnect timer before the test ends
});
test("disconnect goes idle and does not schedule a reconnect", () => {
const { client, ws } = connectedClient();
client.disconnect();
assert.equal(client.state.kind, "idle");
assert.equal(client.state.retrying, false);
assert.deepEqual(ws.closed, { code: 1000, reason: "client closing" });
});
+85
View File
@@ -0,0 +1,85 @@
// Unit tests for the ported ServerUrl validation, run with `node --test`.
// Mirrors the cases in android/.../test/.../ServerUrlTest.kt.
import { test } from "node:test";
import assert from "node:assert/strict";
import { validateServerUrl, resolveArtifactUrl, ServerUrlKind } from "../src/serverUrl.js";
import { Protocol, resolveTarget, isTerminal } from "../src/protocol.js";
test("defaults a bare host to /connect over ws", () => {
const v = validateServerUrl("ws://192.168.1.20:8081");
assert.equal(v.valid, true);
assert.equal(v.wsUrl, "ws://192.168.1.20:8081/connect");
assert.equal(v.httpUrl, "http://192.168.1.20:8081/connect");
assert.equal(v.host, "192.168.1.20");
assert.equal(v.port, 8081);
assert.equal(v.secure, false);
});
test("treats a lone / as the default endpoint path", () => {
const v = validateServerUrl("ws://host:1234/");
assert.equal(v.valid, true);
assert.equal(v.wsUrl, "ws://host:1234/connect");
});
test("wss maps to https and defaults the port to 443", () => {
const v = validateServerUrl("wss://example.test/connect");
assert.equal(v.valid, true);
assert.equal(v.secure, true);
assert.equal(v.port, 443);
assert.equal(v.httpUrl, "https://example.test/connect");
});
test("rejects empty, non-ws schemes, userinfo and fragments", () => {
assert.equal(validateServerUrl("").kind, ServerUrlKind.EMPTY);
assert.equal(validateServerUrl(" ").kind, ServerUrlKind.EMPTY);
assert.equal(validateServerUrl("http://host:8080/connect").kind, ServerUrlKind.UNSUPPORTED_SCHEME);
assert.equal(validateServerUrl("ftp://host").kind, ServerUrlKind.UNSUPPORTED_SCHEME);
assert.equal(validateServerUrl("ws://user:pass@host:8080/connect").kind, ServerUrlKind.USER_INFO);
assert.equal(validateServerUrl("ws://host:8080/connect#frag").kind, ServerUrlKind.FRAGMENT);
});
test("rejects malformed and hostless input", () => {
assert.equal(validateServerUrl("not a url").kind, ServerUrlKind.MALFORMED);
const hostless = validateServerUrl("ws://");
assert.ok(hostless.kind === ServerUrlKind.MALFORMED || hostless.kind === ServerUrlKind.MISSING_HOST);
assert.equal(hostless.valid, false);
});
test("preserves a query string", () => {
const v = validateServerUrl("ws://host:8080/connect?token=abc");
assert.equal(v.valid, true);
assert.equal(v.wsUrl, "ws://host:8080/connect?token=abc");
});
test("resolveArtifactUrl maps ws to http and drops /connect", () => {
assert.equal(
resolveArtifactUrl("ws://10.0.0.249:8080/connect", "/artifacts/55/4/shot.png"),
"http://10.0.0.249:8080/artifacts/55/4/shot.png",
);
});
test("resolveArtifactUrl uses https and omits the default port for wss", () => {
assert.equal(
resolveArtifactUrl("wss://example.test/connect", "artifacts/1/1/a.png"),
"https://example.test/artifacts/1/1/a.png",
);
});
test("resolveArtifactUrl returns an absolute url unchanged and null when unconfigured", () => {
assert.equal(
resolveArtifactUrl("ws://host:8080/connect", "https://cdn.test/a.png"),
"https://cdn.test/a.png",
);
assert.equal(resolveArtifactUrl("", "/artifacts/1/1/a.png"), null);
assert.equal(resolveArtifactUrl("ws://host:8080/connect", " "), null);
});
test("protocol target resolution mirrors the server shorthand", () => {
assert.equal(resolveTarget("error", "#"), Protocol.FAILURE_END);
assert.equal(resolveTarget("success", "#"), Protocol.SUCCESS_END);
assert.equal(resolveTarget("error", "cleanup"), "cleanup");
assert.equal(isTerminal("#success"), true);
assert.equal(isTerminal("#failure"), true);
assert.equal(isTerminal("cleanup"), false);
});
+102
View File
@@ -0,0 +1,102 @@
// Live end-to-end smoke test: drives the *real* client (src/client.js) against a
// running Pipelines server. Opt-in, because it needs a server:
//
// PIPELINES_WS_URL=ws://127.0.0.1:8080/connect node test/smoke.mjs
//
// Uses Node's built-in global WebSocket and fetch (Node >= 22). Exits non-zero
// on the first failed assertion so it is usable in a check.
import assert from "node:assert/strict";
import { PipelinesClient } from "../src/client.js";
import { PipelinesRepository } from "../src/repository.js";
import { validateServerUrl, resolveArtifactUrl } from "../src/serverUrl.js";
const raw = process.env.PIPELINES_WS_URL ?? process.argv[2] ?? "";
if (!raw) {
console.error("PIPELINES_WS_URL is required, e.g. ws://127.0.0.1:8080/connect");
process.exit(2);
}
const validated = validateServerUrl(raw);
if (!validated.valid) {
console.error(`invalid server URL: ${validated.message}`);
process.exit(2);
}
const client = new PipelinesClient();
const repo = new PipelinesRepository(client);
const checks = [];
const pass = (name) => {
checks.push(name);
console.log(` ok ${name}`);
};
try {
await connectWithTimeout(client, validated, 5000);
pass("websocket connected");
const pong = await repo.ping();
assert.equal(pong.type, "pong");
pass("ping -> pong");
const pipelines = await repo.listPipelines();
assert.ok(Array.isArray(pipelines));
pass(`list_pipelines -> ${pipelines.length} pipeline(s)`);
const { runs, usage } = await repo.listRuns();
assert.ok(Array.isArray(runs));
pass(`list_runs -> ${runs.length} run(s), usage.total=${usage?.total ?? "n/a"}`);
if (pipelines.length) {
const detail = await repo.getPipeline(pipelines[0].id, pipelines[0].version);
assert.equal(detail.id, pipelines[0].id);
assert.ok(Array.isArray(detail.graph?.stages));
pass(`get_pipeline #${detail.id} -> ${detail.graph.stages.length} stage(s)`);
} else {
console.log(" -- no pipelines; skipped get_pipeline");
}
if (runs.length) {
const run = await repo.getRun(runs[0].id);
assert.equal(run.id, runs[0].id);
assert.ok(Array.isArray(run.steps));
pass(`get_run #${run.id} -> status=${run.status} steps=${run.steps.length}`);
const artifact = run.steps.flatMap((s) => s.artifacts ?? []).find((a) => a.url);
if (artifact) {
const url = resolveArtifactUrl(raw, artifact.url);
assert.ok(url?.startsWith("http"));
const res = await fetch(url, { method: "HEAD" });
pass(`artifact HEAD ${url} -> ${res.status} ${res.headers.get("content-type") ?? ""}`.trim());
assert.ok(res.ok, `artifact HEAD was ${res.status}`);
} else {
console.log(" -- newest run has no artifacts; skipped artifact fetch");
}
} else {
console.log(" -- no runs; skipped get_run");
}
console.log(`\nSMOKE PASS (${checks.length} checks) against ${validated.wsUrl}`);
client.disconnect();
process.exit(0);
} catch (err) {
console.error(`\nSMOKE FAIL: ${err?.message ?? err}`);
console.error(`against ${validated.wsUrl}`);
client.disconnect();
process.exit(1);
}
function connectWithTimeout(c, validatedUrl, ms) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`connect timed out after ${ms}ms`)), ms);
const onState = (event) => {
if (event.detail.kind === "connected") {
clearTimeout(timer);
c.removeEventListener("state", onState);
resolve();
}
};
c.addEventListener("state", onState);
c.connect(validatedUrl);
});
}