web: live run updates over a single app-wide watch (R10)

This commit is contained in:
2026-10-19 14:22:53 +01:00
parent 2fe63012f9
commit 21a6ee3c4d
13 changed files with 1580 additions and 90 deletions
+354 -30
View File
@@ -7,6 +7,7 @@ import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
import {
ForegroundAction,
RunStream,
bannerState,
foregroundAction,
liveBadgeState,
@@ -14,6 +15,12 @@ import {
serverBuildLabel,
stateBadge,
} from "./connection.js";
import {
foldRunEvent,
foldRunEventDetail,
isTerminalRunStatus,
runDetailNeedsFullSync,
} from "./runEvents.js";
import {
SERVER_URL_HELPER,
SERVER_URL_PLACEHOLDER,
@@ -400,6 +407,12 @@ const state = {
workspace: initialWorkspace,
workspaceDraft: initialWorkspace,
connection: client.state,
// The live run-stream state (R10), independent of any screen: Offline until a
// watch is established, Connecting while subscribing/re-subscribing after a
// drop, Live once an ack, the first pushed frame or a successful watch read
// proves pushes are arriving. The runs list and the run detail render it as the
// LiveBadge.kt words.
runStream: RunStream.Offline,
// 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,
@@ -540,7 +553,28 @@ const state = {
chatSubscriptions: new Set(),
};
let runPoll = null;
// The app-wide run-event watch (R10), owned by the connection rather than any
// screen. `workspace` is the blank string while a watch is established (the
// server-wide "any" scope) and null when nothing is watched; `subscriptionId` is
// the send-only subscribe frame's id so an ack or refusal can be attributed.
// `generation` is bumped on every (re)subscribe and every drop, so an in-flight
// read from a superseded watch can neither write its result nor clear the badge.
const runWatch = {
workspace: null,
subscriptionId: null,
generation: 0,
runsResyncJob: null,
runsResyncQueued: false,
detailSyncJob: null,
detailSyncRequestedRunId: null,
detailDeltaCount: 0,
};
// The coalesced resync retry bound, mirroring AppViewModel: at most three
// retries (four attempts) at 500 ms x attempt, then the badge drops to
// "reconnecting" until a later push or read confirms the stream again.
const RUN_SYNC_RETRY_LIMIT = 3;
const RUN_SYNC_RETRY_BASE_MS = 500;
// One shared live clock for the runs list: it ticks only while a shown run is
// executing, and each running row reads its elapsed from it rather than starting
@@ -586,6 +620,11 @@ function isExecuting(run) {
return Boolean(run && run.executing);
}
/** Await one delay; used only by the bounded resync retry backoff. */
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
@@ -1221,7 +1260,6 @@ function runConnectionAction(label) {
const kind = connectionActionKind(label);
if (kind === "disconnect") {
repo.disconnect();
stopRunPoll();
return;
}
if (kind === "reconnect") {
@@ -2227,7 +2265,7 @@ function renderRunToolbar() {
state.openMenu === "sort" ? renderSortMenu() : null,
),
h("span", { class: "spacer" }),
renderLiveBadge(liveBadgeState({ executing: state.runs.some((run) => run.executing) }, state.connection)),
renderLiveBadge(liveBadgeState(state.runStream)),
);
return toolbar;
}
@@ -2463,7 +2501,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)));
chips.append(renderLiveBadge(liveBadgeState(state.runStream)));
wrap.append(chips);
wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) }));
@@ -6597,7 +6635,6 @@ function openConfiguredEndpoint({ surfaceError = true } = {}) {
function onConnectClicked() {
if (state.connection.kind === "connected") {
repo.disconnect();
stopRunPoll();
return;
}
openConfiguredEndpoint();
@@ -6630,6 +6667,13 @@ function onForegroundActive() {
}
async function onConnected() {
// Establish the run-event watch immediately once the socket is up (R10): the
// unsubscribe/subscribe pair is sent before anything else is read, and its
// authoritative `list_runs` resync is the one the view then reuses, so a
// connection never stacks two initial history reads. The watch is
// send-only/best-effort; a failure leaves the badge "reconnecting" and the
// ordinary view load proceeds.
const watched = startRunWatch();
let reply;
try {
reply = await repo.ping();
@@ -6648,10 +6692,11 @@ async function onConnected() {
// the Settings card is the one `loadCurrentView` already performs (Settings is
// local, so that path is a single render and nothing is fetched twice).
renderBanner();
await loadCurrentView();
const runsFresh = await watched;
await loadCurrentView(false, { runsFresh });
}
async function loadCurrentView(force = false) {
async function loadCurrentView(force = false, { runsFresh = false } = {}) {
// Settings is local: it has no server-backed list to (re)load, so switching to
// or refreshing it must never raise the "connect first" error.
if (state.view === "settings") {
@@ -6680,12 +6725,15 @@ async function loadCurrentView(force = false) {
state.pipelinesLoaded = true;
// The last-run line joins list_runs onto the pipelines, so the history is
// fetched alongside them; runsLoaded distinguishes a genuinely empty
// history from one that has not arrived yet.
const { runs, usage } = await repo.listRuns();
state.runs = runs;
if (usage) state.usage = usage;
state.runsLoaded = true;
} else {
// history from one that has not arrived yet. On connect that history has
// just been read by the run watch's own resync, so it is not read twice.
if (!runsFresh) {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
if (usage) state.usage = usage;
state.runsLoaded = true;
}
} else if (!runsFresh) {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
state.usage = usage;
@@ -6705,6 +6753,269 @@ async function loadCurrentView(force = false) {
}
}
// ---------------------------------------------------------------------------
// The live run stream (R10)
// ---------------------------------------------------------------------------
/** Render whatever a run-state change touched, without re-reading anything. */
function renderRunState() {
if (state.view === "runs" || state.view === "pipelines") renderContent();
refreshAttentionBell();
}
/** Record the explicit stream state and repaint the badge when it changed. */
function setRunStream(next) {
if (state.runStream === next) return;
state.runStream = next;
renderRunState();
}
/**
* Drop the watch bookkeeping and invalidate any in-flight read. Called on every
* socket drop and before a new subscribe, so a superseded read can neither write
* its result over newer state nor confirm a stream that is gone. The stream's own
* state is set by the caller (streamDown / startRunWatch).
*/
function clearRunWatch() {
runWatch.workspace = null;
runWatch.subscriptionId = null;
runWatch.generation += 1;
runWatch.runsResyncQueued = false;
}
/** Nothing is watched: reflect the connection's own state in the live badge. */
function streamDown() {
clearRunWatch();
state.runStream =
state.connection.kind === "connecting" || state.connection.kind === "disconnected"
? RunStream.Connecting
: RunStream.Offline;
}
/** A subscription ack, a push, or a successful watch read proves the stream is live. */
function confirmStreamLive() {
if (runWatch.workspace === null) return;
setRunStream(RunStream.Live);
}
/** A push-driven read failed: stop claiming live until something confirms it again. */
function markStreamDegraded() {
if (runWatch.workspace !== null) setRunStream(RunStream.Connecting);
}
/**
* Establish the one watch over every workspace the client displays (the blank
* scope, which the server treats as "any"): the runs list is server-wide, so the
* client asks for the runs it shows rather than the one workspace the operator
* configured. It best-effort drops the previous watch first (the server caps
* subscriptions per connection), marks the watch before sending so a push that
* races the send is still attributed to it, then takes one authoritative resync
* of the watched state. Resolves true when that resync succeeded, so the caller
* knows the runs list is already fresh.
*/
async function startRunWatch() {
const generation = ++runWatch.generation;
runWatch.workspace = null;
runWatch.subscriptionId = null;
state.runStream = RunStream.Connecting;
try {
repo.unsubscribeRuns();
} catch {
// The drop failed; the new subscribe is still attempted, but the badge stays
// "reconnecting" until an ack, push or successful read confirms the new watch.
state.runStream = RunStream.Connecting;
}
if (generation !== runWatch.generation || state.connection.kind !== "connected") return false;
runWatch.workspace = "";
try {
runWatch.subscriptionId = repo.subscribeRuns("", []);
} catch {
clearRunWatch();
setRunStream(RunStream.Offline);
return false;
}
const resynced = await scheduleRunsResync();
if (generation !== runWatch.generation) return false;
if (state.runDetail?.id != null) scheduleRunDetailSync(state.runDetail.id);
return resynced;
}
/**
* Re-reads the runs list once for a burst of frames the list could not fold (a
* created run whose summary is not in the compact delta, or a terminal
* transition that changes the usage aggregate) and once after every
* (re)subscribe. Coalesced — at most one in flight with one queued follow-up —
* and it loops while a frame arrived, so no push is ever dropped. A failed read
* stops claiming live and is retried with a bounded backoff before giving up.
* Resolves true when the last read succeeded.
*/
function scheduleRunsResync() {
if (runWatch.runsResyncJob) {
runWatch.runsResyncQueued = true;
return runWatch.runsResyncJob;
}
const job = (async () => {
let attempt = 0;
let ok = true;
for (;;) {
runWatch.runsResyncQueued = false;
const generation = runWatch.generation;
try {
const { runs, usage } = await repo.listRuns();
if (generation !== runWatch.generation) {
// The watch was re-established (or dropped) while this read was in
// flight; its result is superseded, so re-read under the new watch
// instead of writing stale state or clearing the badge.
runWatch.runsResyncQueued = true;
continue;
}
state.runs = runs;
if (usage) state.usage = usage;
state.runsLoaded = true;
attempt = 0;
ok = true;
confirmStreamLive();
renderRunState();
} catch {
if (generation !== runWatch.generation) {
runWatch.runsResyncQueued = true;
continue;
}
markStreamDegraded();
attempt += 1;
if (attempt > RUN_SYNC_RETRY_LIMIT) {
ok = false;
break;
}
await delay(RUN_SYNC_RETRY_BASE_MS * attempt);
if (generation !== runWatch.generation) {
runWatch.runsResyncQueued = true;
continue;
}
runWatch.runsResyncQueued = true;
ok = false;
}
if (!runWatch.runsResyncQueued) break;
}
return ok;
})();
runWatch.runsResyncJob = job;
job.finally(() => {
if (runWatch.runsResyncJob === job) runWatch.runsResyncJob = null;
});
return job;
}
/**
* Fetches the full run detail once for a burst of settled-step/terminal pushes,
* so the artifacts and output the compact delta omits appear without a timer. A
* response is dropped and retried when a newer frame landed while the fetch was
* in flight, so the fetch can never regress the fold. The queued request is keyed
* by run id, so opening another run mid-fetch fetches that run instead of
* discarding the request; a run the operator has left is never written over.
*/
function scheduleRunDetailSync(runId) {
const targetId = Number(runId);
if (!(targetId > 0)) return null;
if (runWatch.detailSyncJob) {
runWatch.detailSyncRequestedRunId = targetId;
return runWatch.detailSyncJob;
}
const job = (async () => {
let target = targetId;
let attempt = 0;
while (target != null) {
runWatch.detailSyncRequestedRunId = null;
const generation = runWatch.generation;
const deltaCount = runWatch.detailDeltaCount;
try {
const run = await repo.getRun(target);
attempt = 0;
if (generation !== runWatch.generation) {
// A drop/re-subscribe superseded this read; re-read for the new watch
// rather than writing a result from the old one.
runWatch.detailSyncRequestedRunId = target;
continue;
}
if (state.runDetail?.id === target) {
if (runWatch.detailDeltaCount === deltaCount) {
state.runDetail = run;
renderRunState();
} else {
// A newer frame overtook the fetch; re-read rather than write the
// older run over it.
runWatch.detailSyncRequestedRunId = target;
}
}
// else: the operator left this run; its detail is no longer shown.
} catch {
if (generation !== runWatch.generation) {
runWatch.detailSyncRequestedRunId = target;
continue;
}
markStreamDegraded();
attempt += 1;
if (attempt > RUN_SYNC_RETRY_LIMIT) return;
await delay(RUN_SYNC_RETRY_BASE_MS * attempt);
if (generation !== runWatch.generation) {
runWatch.detailSyncRequestedRunId = target;
continue;
}
// A run opened meanwhile wins over retrying this one.
if (runWatch.detailSyncRequestedRunId == null) runWatch.detailSyncRequestedRunId = target;
}
target = runWatch.detailSyncRequestedRunId;
}
})();
runWatch.detailSyncJob = job;
job.finally(() => {
if (runWatch.detailSyncJob === job) runWatch.detailSyncJob = null;
});
return job;
}
/**
* Fold one pushed `run_event` frame into whatever local state it names: the runs
* list (and so the pipeline rows' last-run line and the attention bell) in
* place, and the open run detail. A frame for a run the list does not hold
* re-syncs the list once; a frame that changed the detail and carries a settled
* step, a waiting step/run or a terminal run also fetches the full detail once.
*/
function applyRunEvent(frame) {
const runId = Number(frame?.run_id);
if (!(runId > 0)) return;
let listChanged = false;
if (state.runsLoaded) {
const fold = foldRunEvent(state.runs, frame);
if (fold.needsResync) {
scheduleRunsResync();
} else if (fold.runs !== state.runs) {
state.runs = fold.runs;
listChanged = true;
renderRunState();
// A terminal transition also settles the usage aggregate (the active
// count), which the delta does not carry; one server read refreshes it. A
// duplicate terminal frame changes nothing above, so it triggers no read.
if (frame.step == null && isTerminalRunStatus(frame.status)) scheduleRunsResync();
}
}
const detail = state.runDetail;
if (detail && Number(detail.id) === runId) {
runWatch.detailDeltaCount += 1;
const folded = foldRunEventDetail(detail, frame);
const detailChanged = folded !== detail;
if (detailChanged) {
state.runDetail = folded;
renderRunState();
}
if (runDetailNeedsFullSync(frame) && (detailChanged || listChanged)) {
scheduleRunDetailSync(runId);
}
}
// A list-only change with the detail open is still a fold; if the run list was
// not in hand, the resync above covers the new row.
}
/**
* Loads the template catalogue, then validates each template's source once and
* caches the parsed graph (null when it did not parse) so a card's stage count
@@ -6786,24 +7097,11 @@ async function selectRun(id, { silent = false } = {}) {
try {
state.runDetail = await repo.getRun(id);
renderContent();
updateRunPoll();
// The run detail is no longer polled: the watch's pushed `run_event` frames
// advance it live (R10), and a settled/terminal frame triggers one full
// `get_run` for the heavy fields the compact delta omits.
} 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;
}
}
@@ -6922,7 +7220,6 @@ client.addEventListener("state", (event) => {
onConnected();
}
if (next.kind !== "connected" && previousKind === "connected") {
stopRunPoll();
stopListClock();
stopDetailClock();
stopChatClock();
@@ -6932,6 +7229,11 @@ client.addEventListener("state", (event) => {
clearChatSubscriptions();
settleChatThreads();
}
if (next.kind !== "connected") {
// Nothing is watched while the socket is down; an in-flight read is
// invalidated and the badge falls back to Connecting (or Offline when idle).
streamDown();
}
// A reconnect (not a first connect): re-attach the open chat's stream and
// refresh its history wholesale, so a gap that swallowed the end of a turn is
// repaired rather than shown stale.
@@ -6949,6 +7251,28 @@ client.addEventListener("state", (event) => {
client.addEventListener("frame", (event) => {
const message = event.detail;
if (!message) return;
// The live run stream (R10). A pushed `run_event` only reaches a subscriber, so
// it confirms the watch even when the server never acks the subscribe. A reply
// carrying our subscribe id is the optional ack (live) or a refusal (offline).
if (message.type === Protocol.RUN_EVENT) {
const frame = message.run_event;
if (frame) {
confirmStreamLive();
applyRunEvent(frame);
}
return;
}
if (message.id != null && message.id === runWatch.subscriptionId) {
if (message.type === Protocol.SUBSCRIBE) {
confirmStreamLive();
return;
}
if (message.type === Protocol.ERROR) {
clearRunWatch();
setRunStream(RunStream.Offline);
return;
}
}
if (message.type === Protocol.CHAT_PERMISSION) {
const permission = message[ChatKeys.PERMISSION];
if (permission) onChatPermission(permission);
+4 -4
View File
@@ -4,10 +4,10 @@
// sheet read exactly what the app reads.
//
// The surface is derived here from the same `list_runs` summaries the runs list
// is folded from (and from any run state already in the page). R10, the live
// `run_event` fold, is a separate item: when it lands it will feed these same
// pure functions the pushed summaries, and neither the ordering nor the wording
// will change.
// is folded from (and from any run state already in the page). R10's live
// `run_event` fold feeds these same pure functions the pushed summaries, so the
// ordering and the wording are identical whether a row arrived from a read or a
// push.
//
// Everything in this file is pure: no DOM, no clock, no storage. app.js keeps the
// wiring; a malformed stored value can never throw into the page because decode
+20
View File
@@ -118,6 +118,26 @@ export class PipelinesClient extends EventTarget {
return run;
}
/**
* Sends one request without awaiting a reply, returning the generated id
* (mirrors the Android `PipelinesClient.sendOnly`). Used for the run-event
* watch: `subscribe` may never be acknowledged, so registering a pending entry
* would leave it to time out, and `unsubscribe` has nothing to read back.
*
* The send is synchronous so back-to-back frames (`unsubscribe` then
* `subscribe`) keep their order on the wire; the id is still available so a
* server that does ack (or refuses) has its reply surface as an unsolicited
* `frame` event with that id. A call before the socket is connected is refused
* with `NotConnectedError`, exactly like `call`.
*/
sendOnly(request) {
const socket = this.#ws;
if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError();
const id = `web-${++this.#seq}`;
socket.send(JSON.stringify({ ...request, id }));
return id;
}
async #doCall(request) {
const socket = this.#ws;
if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError();
+23 -11
View File
@@ -167,17 +167,29 @@ export function serverBuildLabel(build) {
}
/**
* 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.
* The live-stream states, exactly RunStream.kt's three words. The page tracks
* this itself (it owns the subscription), so the badge says whether the pushes
* are arriving rather than guessing from whether a run happens to be executing.
*/
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" };
export const RunStream = Object.freeze({
Live: "live",
Connecting: "connecting",
Offline: "offline",
});
/**
* The live-stream badge, mirroring LiveBadge.kt / RunStream.kt: the explicit
* stream state maps to the app's own word and dot ("live" / "reconnecting" /
* "not live"). The word always carries the meaning, so colour is never the only
* signal, and the badge is independent of whether any run is executing.
*/
export function liveBadgeState(streamState) {
switch (streamState) {
case RunStream.Live:
return { tone: "live", label: "live" };
case RunStream.Connecting:
return { tone: "reconnecting", label: "reconnecting" };
default:
return { tone: "not-live", label: "not live" };
}
return { tone: "not-live", label: "not live" };
}
+11
View File
@@ -27,6 +27,17 @@ export const Protocol = Object.freeze({
GET_RUN: "get_run",
RUN: "run",
// Live run state (internal/protocol/runevents.go, Message.kt; R10). `subscribe`
// scopes the watch to a workspace (the blank string means "any") and may carry
// explicit `run_ids`; `unsubscribe` drops the connection's watch; `run_event` is
// the server-pushed compact delta, which arrives without a matching request id
// and is therefore surfaced by client.js as a `frame` event. Both commands are
// send-only: the server may not ack `subscribe` and the Android client never
// awaits a reply.
SUBSCRIBE: "subscribe",
UNSUBSCRIBE: "unsubscribe",
RUN_EVENT: "run_event",
// Omni-search (internal/protocol/search.go): the command and its reply type.
// The per-kind payloads and the kind/limit vocabulary live in src/search.js.
SEARCH: "search",
+26
View File
@@ -115,6 +115,32 @@ export class PipelinesRepository {
return response.run_detail;
}
/**
* Asks the server to push this connection the live run state it displays
* (R10). Send-only, mirroring `PipelinesRepository.subscribeRuns`: it returns
* the generated frame id and never waits for a reply, because the server may
* not acknowledge a `subscribe`. The body is exactly `{type:'subscribe',
* workspace}`; `run_ids` rides only when ids are given, so a blank workspace
* with no ids asks for the server-wide "any workspace" scope — the same
* `runIds.ifEmpty { null }` shape the Android client sends. The pushed state
* arrives as unsolicited `run_event` frames (client.js surfaces them as
* `frame` events).
*/
subscribeRuns(workspace = "", runIds = []) {
const request = { type: Protocol.SUBSCRIBE, workspace: String(workspace ?? "") };
if (Array.isArray(runIds) && runIds.length > 0) request.run_ids = runIds;
return this.#client.sendOnly(request);
}
/**
* Drops this connection's run-event watch (R10). Send-only like `subscribe`:
* the server may ack it, but nothing is awaited. It stops the pushes; a later
* `subscribe` re-reads the current state.
*/
unsubscribeRuns() {
return this.#client.sendOnly({ type: Protocol.UNSUBSCRIBE });
}
/**
* Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from
* internal/protocol/search.go: `kind` is the empty string for every kind, and
+363
View File
@@ -0,0 +1,363 @@
// The pure fold from a server-pushed `run_event` into the client's cached run
// state. The app never polls: every value on the runs list, the pipeline rows'
// last-run line and the run detail (status, timeline, stages, completed count)
// is advanced here from the pushes.
//
// This is a direct port of android/.../ui/RunEvents.kt so the browser says and
// shows exactly what the app does. It is deliberately DOM-free: every rule is
// unit-testable under `node --test` with no browser and no server, and app.js
// keeps the wiring.
//
// The fold is monotonic so an out-of-order or duplicated delta can never move a
// run or a step backwards. A delta that names a run the list does not hold is
// inserted as a new row from the frame's own identity (pipeline id, name, title,
// version), so a run started after the screen loaded appears without a fetch;
// only a frame with no such identity (an older server) reports `needsResync`, and
// the caller re-reads the server's current list once instead.
//
// Field names stay snake_case exactly as they are on the wire
// (internal/protocol/runevents.go RunEventFrame / RunStepDelta). Every
// server-provided string is only ever compared or rendered, never parsed as
// markup; the caller sets it with textContent.
/** Run statuses from which a run never transitions again. */
export const TERMINAL_RUN_STATUSES = Object.freeze([
"succeeded",
"failed",
"canceled",
"interrupted",
]);
/** The lifecycle rank at which a status is settled: a later status never rewrites it. */
const SETTLED_RANK = 2;
/**
* Whether `status` is the human-stage status a run (or its waiting step) parks
* on: it is not terminal and it is not executing, but it still needs the full
* detail (the compact delta carries no options/prompt), so a pending decision is
* surfaced live.
*/
export function isWaitingRunStatus(status) {
return String(status ?? "").trim().toLowerCase() === "waiting";
}
/** Whether `status` is a settled run status (no further transitions expected). */
export function isTerminalRunStatus(status) {
return TERMINAL_RUN_STATUSES.includes(String(status ?? "").trim().toLowerCase());
}
/**
* The run lifecycle as an ordinal so a delta can only advance it:
* queued (0) < running/waiting (1) < terminal (2). A blank or unknown word is -1.
*/
export function runLifecycleRank(status) {
switch (String(status ?? "").trim().toLowerCase()) {
case "queued":
return 0;
case "running":
case "waiting":
return 1;
case "succeeded":
case "failed":
case "canceled":
case "interrupted":
return 2;
default:
return -1;
}
}
/**
* The step lifecycle as an ordinal so a settled visit is never reopened:
* in-flight running/waiting (1) < finished completed/failed/canceled (2).
*/
export function stepLifecycleRank(status) {
switch (String(status ?? "").trim().toLowerCase()) {
case "running":
case "waiting":
return 1;
case "completed":
case "failed":
case "canceled":
case "interrupted":
return 2;
default:
return -1;
}
}
/**
* The one staleness rule, shared by the run and step ladders so they cannot
* drift: a status behind the current rank, or a different settled word after the
* state already settled, marks the whole delta stale.
*/
function isStaleTransition(current, incoming, rank) {
if (String(incoming ?? "").trim() === "") return false;
const cur = rank(current);
const inc = rank(incoming);
if (cur < 0 || inc < 0) return false;
return inc < cur || (cur >= SETTLED_RANK && inc >= SETTLED_RANK && incoming !== current);
}
/** Whether the run frame is a stale transition that must be dropped whole. */
export function isStaleRunFrame(current, incoming, resourceWaitSet = false) {
if (resourceWaitSet && incoming === "queued" && !isTerminalRunStatus(current)) return false;
return isStaleTransition(current, incoming, runLifecycleRank);
}
/** The step counterpart of `isStaleRunFrame`: a settled visit drops a stale delta whole. */
export function isStaleStepDelta(current, incoming) {
return isStaleTransition(current, incoming, stepLifecycleRank);
}
/**
* The one monotonic status rule, shared by the run and step ladders so they
* cannot drift: a blank or unknown word never wins, a higher rank always does,
* and once a settled rank is reached its word is kept forever.
*/
function advanceStatus(current, incoming, rank) {
if (String(incoming ?? "").trim() === "" || incoming === current) return current;
const cur = rank(current);
const inc = rank(incoming);
if (cur < 0) return incoming;
if (inc < 0) return current;
if (inc > cur) return incoming;
if (cur >= SETTLED_RANK) return current;
return incoming;
}
function advanceRunStatus(current, incoming) {
return advanceStatus(current, incoming, runLifecycleRank);
}
function advanceStepStatus(current, incoming) {
return advanceStatus(current, incoming, stepLifecycleRank);
}
/**
* The client's best knowledge of `executing`: queued/running only; unknown keeps
* `current`.
*/
export function executingFor(status, current) {
switch (String(status ?? "").trim().toLowerCase()) {
case "queued":
case "running":
return true;
case "waiting":
case "succeeded":
case "failed":
case "canceled":
case "interrupted":
return false;
default:
return Boolean(current);
}
}
function blank(value) {
return String(value ?? "").trim() === "";
}
function sameResourceWait(a, b) {
if (a === b) return true;
if (!a || !b) return false;
return (
a.resource === b.resource &&
a.stage === b.stage &&
a.sequence === b.sequence &&
a.queued_since === b.queued_since
);
}
/** The run-state fields a frame advances, shared by the summary row and the detail. */
function runStateFields(current) {
return {
resource_wait: current.resource_wait ?? null,
status: current.status ?? "",
outcome: current.outcome ?? "",
current_stage: current.current_stage ?? "",
completed_steps: Number(current.completed_steps) || 0,
created_at: current.created_at ?? "",
finished_at: current.finished_at ?? "",
executing: Boolean(current.executing),
};
}
/**
* The single run-field merge: every value advances forward, so the row and the
* detail can never apply a frame differently. Returns the current object when
* nothing changed, so a no-op frame keeps the same reference.
*/
function applyRunStateFields(current, frame) {
if (isStaleRunFrame(current.status, frame.status, frame.resource_wait_set === true)) return current;
const before = runStateFields(current);
const status =
frame.resource_wait_set === true && frame.status === "queued" && !isTerminalRunStatus(before.status)
? "queued"
: advanceRunStatus(before.status, frame.status);
const merged = {
resource_wait: isTerminalRunStatus(status)
? null
: frame.resource_wait_set === true
? (frame.resource_wait ?? null)
: before.resource_wait,
status,
outcome: blank(frame.outcome) ? before.outcome : frame.outcome,
current_stage: blank(frame.current_stage) ? before.current_stage : frame.current_stage,
completed_steps: Math.max(before.completed_steps, Number(frame.completed_steps) || 0),
created_at: blank(frame.created_at) ? before.created_at : frame.created_at,
finished_at: blank(frame.finished_at) ? before.finished_at : frame.finished_at,
executing: executingFor(status, before.executing),
};
const changed =
!sameResourceWait(merged.resource_wait, before.resource_wait) ||
merged.status !== before.status ||
merged.outcome !== before.outcome ||
merged.current_stage !== before.current_stage ||
merged.completed_steps !== before.completed_steps ||
merged.created_at !== before.created_at ||
merged.finished_at !== before.finished_at ||
merged.executing !== before.executing;
return changed ? { ...current, ...merged } : current;
}
/**
* The row a frame for a run the list has never held describes, or null when the
* frame lacks the pipeline identity a row needs (an older server), in which case
* the caller resyncs instead of inventing an incomplete row. The frame already
* carries everything the row shows, so no field is guessed from cached state.
*/
export function newRunSummaryFromFrame(frame) {
const pipelineId = Number(frame?.pipeline_id);
const name = String(frame?.name ?? "");
if (!(pipelineId > 0) || blank(name)) return null;
return {
resource_wait: frame.resource_wait ?? null,
id: Number(frame.run_id),
pipeline_id: pipelineId,
name,
title: blank(frame.title) ? null : frame.title,
version: Number(frame.version) || 0,
status: frame.status ?? "",
executing: executingFor(frame.status, true),
outcome: frame.outcome ?? "",
current_stage: frame.current_stage ?? "",
created_at: frame.created_at ?? "",
finished_at: frame.finished_at ?? "",
completed_steps: Number(frame.completed_steps) || 0,
};
}
/**
* Folds one pushed frame into the runs list, in place and without reordering. A
* run the list has never held is inserted as a new row at the head (newest
* first, matching the server's own order) when the frame carries its pipeline
* identity, so a run started after the screen loaded appears while the operator
* watches without a fetch; a frame with no identity (an older server) still
* reports `needsResync` so the caller re-reads once instead.
*
* Returns `{ runs, needsResync }`; `runs` is the same array reference when
* nothing changed.
*/
export function foldRunEvent(runs, frame) {
const list = Array.isArray(runs) ? runs : [];
const runId = Number(frame?.run_id);
if (!(runId > 0)) return { runs: list, needsResync: false };
const index = list.findIndex((run) => Number(run?.id) === runId);
if (index < 0) {
const added = newRunSummaryFromFrame(frame);
if (!added) return { runs: list, needsResync: true };
return { runs: [added, ...list], needsResync: false };
}
const current = list[index];
const updated = applyRunStateFields(current, frame);
if (updated === current) return { runs: list, needsResync: false };
const next = list.slice();
next[index] = updated;
return { runs: next, needsResync: false };
}
/**
* Upserts one step delta, matched by sequence: an existing visit has only its
* non-blank fields advanced, and a new visit is inserted in sequence order so a
* late delta for an earlier step cannot reorder the timeline.
*/
function upsertStep(steps, delta) {
const list = Array.isArray(steps) ? steps : [];
const sequence = Number(delta?.sequence) || 0;
const index = list.findIndex((step) => Number(step?.sequence) === sequence);
if (index >= 0) {
const current = list[index];
const updated = applyStepDelta(current, delta);
if (updated === current) return list;
const next = list.slice();
next[index] = updated;
return next;
}
const added = {
sequence,
stage: delta.stage ?? "",
status: advanceStepStatus("", delta.status),
outcome: delta.outcome ?? "",
target: delta.target ?? "",
diagnostic: delta.diagnostic ?? "",
};
const next = list.slice();
const at = next.findIndex((step) => Number(step?.sequence) > sequence);
if (at < 0) next.push(added);
else next.splice(at, 0, added);
return next;
}
function applyStepDelta(current, delta) {
if (isStaleStepDelta(current.status, delta.status)) return current;
const merged = {
stage: blank(delta.stage) ? current.stage : delta.stage,
status: advanceStepStatus(current.status, delta.status),
outcome: blank(delta.outcome) ? current.outcome : delta.outcome,
target: blank(delta.target) ? current.target : delta.target,
diagnostic: blank(delta.diagnostic) ? current.diagnostic : delta.diagnostic,
};
const changed =
merged.stage !== current.stage ||
merged.status !== current.status ||
merged.outcome !== current.outcome ||
merged.target !== current.target ||
merged.diagnostic !== current.diagnostic;
return changed ? { ...current, ...merged } : current;
}
/**
* Folds one pushed frame into a cached run detail: the run's own status/outcome/
* stage/timestamps plus at most one step, matched by sequence so a duplicate or
* out-of-order step delta is idempotent and never adds a second visit. A frame
* for another run is ignored unchanged, as is a stale one (dropped whole).
*/
export function foldRunEventDetail(detail, frame) {
if (!detail || Number(detail.id) !== Number(frame?.run_id)) return detail;
if (isStaleRunFrame(detail.status, frame.status, frame.resource_wait_set === true)) return detail;
const merged = applyRunStateFields(detail, frame);
const steps = frame.step ? upsertStep(detail.steps ?? [], frame.step) : (detail.steps ?? []);
if (merged === detail && steps === (detail.steps ?? [])) return detail;
return { ...detail, ...runStateFields(merged), steps };
}
/**
* Whether a frame carries data the compact delta cannot express (recorded
* artifacts, output, a settled visit's diagnostic), so the caller fetches the
* full run once to fill those in rather than showing a stale gallery. A waiting
* run or step is included: its options and prompt live in the waiting step's
* `output`, which the compact delta deliberately omits, so the fetch is what
* surfaces a pending decision without a manual refresh.
*/
export function runDetailNeedsFullSync(frame) {
const step = frame?.step;
const stepSettled = step != null && stepLifecycleRank(step.status) >= SETTLED_RANK;
const stepWaiting = step != null && isWaitingRunStatus(step.status);
return (
stepSettled ||
stepWaiting ||
isTerminalRunStatus(frame?.status) ||
isWaitingRunStatus(frame?.status)
);
}