// 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 ); } // Execution origin is immutable. Sparse lifecycle frames (or older peers) // cannot turn a scheduled run into a manual run or retarget its schedule. function scheduleOriginFields(current, frame) { const oldId = Number.isSafeInteger(current.schedule_id) && current.schedule_id > 0 ? current.schedule_id : 0; const newId = Number.isSafeInteger(frame.schedule_id) && frame.schedule_id > 0 ? frame.schedule_id : 0; const known = Object.hasOwn(current, "scheduled") || Object.hasOwn(frame, "scheduled") || oldId > 0 || newId > 0; if (!known) return {}; const id = oldId > 0 ? oldId : newId > 0 ? newId : 0; const incomingName = oldId > 0 && newId > 0 && oldId !== newId ? "" : frame.schedule_name; const name = String(current.schedule_name || incomingName || ""); return { scheduled: current.scheduled === true || frame.scheduled === true || id > 0, ...(id > 0 ? { schedule_id: id } : {}), ...(name ? { schedule_name: name } : {}), }; } /** The run-state fields a frame advances, shared by the summary row and the detail. */ function runStateFields(current) { return { notify_mode: current.notify_mode ?? "auto", 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), cancel_requested: Boolean(current.cancel_requested), cleanup_unconfirmed: Boolean(current.cleanup_unconfirmed), export_pending_sequence: Number(current.export_pending_sequence) || 0, }; } /** * 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 origin = scheduleOriginFields(current, frame); const status = frame.resource_wait_set === true && frame.status === "queued" && !isTerminalRunStatus(before.status) ? "queued" : advanceRunStatus(before.status, frame.status); const merged = { ...origin, notify_mode: blank(frame.notify_mode) ? before.notify_mode : frame.notify_mode, resource_wait: isTerminalRunStatus(status) ? null : frame.resource_wait_set === true ? (frame.resource_wait ?? null) : before.resource_wait, status, ...(before.export_pending_sequence || Number(frame.export_pending_sequence) > 0 || Object.hasOwn(current, "export_pending_sequence") ? { export_pending_sequence: blank(frame.status) ? before.export_pending_sequence : status === "waiting" ? Number(frame.export_pending_sequence) || 0 : 0 } : {}), 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), cancel_requested: before.cancel_requested || frame.cancel_requested === true, cleanup_unconfirmed: before.cleanup_unconfirmed || frame.cleanup_unconfirmed === true, }; // Detail already maintains full visits below; compact evidence is list-only. const graphEvidence = Array.isArray(current.steps) ? current.graph_evidence : mergeGraphEvidence(current.graph_evidence, frame); const changed = Object.keys(origin).some((key) => current[key] !== origin[key]) || graphEvidence !== current.graph_evidence || merged.notify_mode !== before.notify_mode || !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 || merged.cancel_requested !== before.cancel_requested || merged.cleanup_unconfirmed !== before.cleanup_unconfirmed; const exportWaitChanged = (Number(merged.export_pending_sequence) || 0) !== before.export_pending_sequence; return changed || exportWaitChanged ? { ...current, ...merged, ...(graphEvidence ? { graph_evidence: graphEvidence } : {}) } : current; } // Reuse the detail's monotonic visit merge, then compact by last stage visit and // distinct route. Keep completeness separate: a delta from an older server or // a mid-run first frame cannot prove that earlier stages were never visited. function mergeGraphEvidence(current, frame) { if (!frame.graph_evidence && !frame.graph_visits?.length && !frame.step) return current; let visits = current?.visits ?? []; const incoming = [...(frame.graph_evidence?.visits ?? []), ...(frame.graph_visits ?? []), ...(frame.step ? [frame.step] : [])]; for (const step of incoming) { const { sequence, stage, status, outcome, target } = step; visits = upsertStep(visits, { sequence, stage, status, outcome, target }); } const latest = new Map(); const routes = new Map(); for (const visit of visits) { latest.set(visit.stage, visit.sequence); if (visit.outcome && visit.target) routes.set(JSON.stringify([visit.stage, visit.outcome, visit.target]), visit.sequence); } visits = visits.filter((visit) => latest.get(visit.stage) === visit.sequence || (visit.outcome && visit.target && routes.get(JSON.stringify([visit.stage, visit.outcome, visit.target])) === visit.sequence)); // Explicit allowlist: graph evidence never copies diagnostic/private fields. visits = visits.map(({ sequence, stage, status, outcome, target }) => ({ sequence, stage, status, outcome, target })); const result = { complete: Boolean(current?.complete || frame.graph_evidence?.complete), visits }; return JSON.stringify(result) === JSON.stringify(current) ? current : result; } /** * 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; const graphEvidence = mergeGraphEvidence(null, frame); return { ...scheduleOriginFields({}, frame), ...(graphEvidence ? { graph_evidence: graphEvidence } : {}), resource_wait: frame.resource_wait ?? null, id: Number(frame.run_id), pipeline_id: pipelineId, name, notify_mode: frame.notify_mode ?? "auto", title: blank(frame.title) ? null : frame.title, version: Number(frame.version) || 0, status: frame.status ?? "", ...(Number(frame.export_pending_sequence) > 0 ? { export_pending_sequence: Number(frame.export_pending_sequence) } : {}), executing: executingFor(frame.status, true), cancel_requested: frame.cancel_requested === true, cleanup_unconfirmed: frame.cleanup_unconfirmed === 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 || frame?.cancel_requested === true || frame?.cleanup_unconfirmed === true || isTerminalRunStatus(frame?.status) || isWaitingRunStatus(frame?.status) ); }