From 21a6ee3c4d3543f139bdfd11c0078b64e8a45aaa Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 14:22:53 +0100 Subject: [PATCH] web: live run updates over a single app-wide watch (R10) --- web/PARITY.md | 2 +- web/src/app.js | 384 +++++++++++++++++++++++++++++++--- web/src/attention.js | 8 +- web/src/client.js | 20 ++ web/src/connection.js | 34 ++- web/src/protocol.js | 11 + web/src/repository.js | 26 +++ web/src/runEvents.js | 363 ++++++++++++++++++++++++++++++++ web/test/client.test.mjs | 45 ++++ web/test/connection.test.mjs | 22 +- web/test/repository.test.mjs | 39 +++- web/test/runEvents.test.mjs | 395 +++++++++++++++++++++++++++++++++++ web/test/ui-smoke.mjs | 321 +++++++++++++++++++++++++--- 13 files changed, 1580 insertions(+), 90 deletions(-) create mode 100644 web/src/runEvents.js create mode 100644 web/test/runEvents.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index aafa0796..103f8d02 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -40,7 +40,7 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | R7 | Timeline | `get_run` | done — one compact row per visit (`{stage} · visit {n}`, stage-outcome chip, paperclip when artifacts recorded, duration, description = first non-blank diagnostic line else `→ {target}`); empty state "No visits recorded.". Captured 2026-10-19: `captures/23-run-430-timeline.png`, `captures/26-run-428-timeline-empty.png` | | R8 | Artifacts gallery + full-screen viewer (images inline, others download/open) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/04-run-430-artifacts.png`, `captures/05-artifact-viewer.png`) | | R9 | Session export link (read-only `session.html`) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/06-session-export-link.png`) | -| R10 | Live run updates: subscribe/unsubscribe + event fold | `subscribe`, `unsubscribe`, `run_event` | todo | +| R10 | Live run updates: subscribe/unsubscribe + event fold | `subscribe`, `unsubscribe`, `run_event` | done — one app-wide watch owned by the connection, never by a screen: becoming connected best-effort `unsubscribe`s the previous watch, sends `{type:'subscribe',workspace:''}` send-only (no `run_ids`; `{type:'unsubscribe'}` drops it), then takes one authoritative resync (`list_runs`, plus one `get_run` when a run detail is open); a socket drop clears the watch and no screen change ever unsubscribes. `src/runEvents.js` is the pure fold ported from `ui/RunEvents.kt` (in-place list update preserving order, insert-at-head from the frame's pipeline identity, `needsResync` without identity, detail merge with explicit `resource_wait` set/clear, one step matched by `sequence` and inserted in sequence order, the monotonic run/step ladders and the full-sync decision) and is unit-tested in `test/runEvents.test.mjs`; the send-only path (`src/client.js#sendOnly`), the exact watch frames (`src/repository.js`) and the `run_event`/unsolicited-frame dispatch are unit-tested in `test/client.test.mjs` and `test/repository.test.mjs`. The 1 s run-detail poll is removed — pushed frames drive the detail and a settled/terminal frame triggers one coalesced `get_run` (at most one in flight per kind plus one queued follow-up, retried at 500 ms × attempt at most 3 times before the badge drops to `reconnecting`); the only surviving intervals are render-only clocks. The badge is the explicit stream state (`live` / `reconnecting` / `not live`, LiveBadge.kt words), independent of whether a run is executing, on the Runs list and the run detail. Captured 2026-10-19 against the live server with a **real pushed run** started by the smoke in a throwaway workspace: `captures/75-run-live-list.png` (the new run's row inserted from its own frame, badge `live`), `captures/76-run-live-detail.png` (the open detail folded to its terminal word from pushes, badge `live`), plus the reachable badge states `captures/28-connected-banner.png` (live), `captures/29-disconnected-banner.png` (not live while idle; reconnecting while the socket retries) and `captures/30-reconnect-recovered.png` (live again). `test/ui-smoke.mjs` asserts the reconnect wire order (unsubscribe → subscribe blank-workspace → list_runs) and that at least one genuine `run_event` frame for the started run arrived. The R10 step itself passes on every run; the full smoke's later pre-existing chat steps can still fail on the shared live server when another client closes/mutates the operator chat session, which is not an R10 defect (see the stage notes). | | R11 | Human decision sheet: prompt, options, feedback | `decide_run` | partial — the pure model (`src/actions.js`: `pendingDecision`, `lastWaitingStep`, `waitingPrompt`/`waitingOptions`, `humanOptions`, `decisionTargetLabel`, `DecisionDraft`) and the card + sheet are implemented with the Android copy verbatim: card title `Waiting for your decision`, meta `{stage} · run {id} · {runLabel}`, action `Decide`; sheet title `Decide {stage}`, meta `run {id} · {runLabel}`, the recorded instructions verbatim when non-blank, one selectable row per option in author order showing the option and `→ {target}` only when the declared edge resolves, the `Feedback (optional)` field, and `Cancel` / `Confirm decision` (reading `Sending…` while in flight). Selecting a row sends nothing and Confirm is disabled until a non-blank option is chosen; a refusal keeps the sheet open with the server's exact reason and re-reads the run. The request shape is unit-tested (`decide_run` = `{type, run_id, option, stage?, feedback?}`, stage/feedback omitted when blank, feedback trimmed). **No browser capture yet**: the live server had no `waiting` run when `ui-smoke.mjs` ran (only executing/failed/finished runs), so this row stays `partial`; `test/ui-smoke.mjs` now captures the card, the sheet and the selected state automatically (`captures/41-run--decision-card.png`, `captures/42-run--decision-sheet.png`, `captures/43-run--decision-selected.png`) the moment a waiting run exists | | R12 | Cancel run | `cancel_run` | done — `src/actions.js` `canCancel` offers a `Cancel run` action only while the run is `executing`; the confirm dialog is the Android copy verbatim (title `Cancel run {id}?`, `This asks the server to stop the active run.`, confirm `Cancel run`, dismiss `Keep`), and the request is exactly `{type:'cancel_run',run_id}` followed by a silent `get_run` refresh (unit-tested in `test/repository.test.mjs`). Captured `captures/40-run-459-cancel-confirm.png` on the executing run present at capture time. **Shown, not executed**: the only candidate was another live pipeline's executing run, so the dialog was shown and dismissed with `Keep` — no `cancel_run` was sent (a real cancel is only safe against a run started in a scratch workspace, which this stage did not do) | | R13 | Retry failed stage (resume) / restart from start | `retry_run` | done — `canRetry` is true only for a loaded, non-executing, `failed` run; the Retry confirm is the Android copy verbatim (title `Retry run {id}?`, `Only failed runs can be retried. The server starts a new run from the same input.`, confirm `Retry`, dismiss `Keep`) and the default send carries only `run_id` + a fresh `request_key` (**no** `retry_mode`, so the server's `resume` default applies exactly like the Android client's mode-less call; unit-tested). Captured `captures/35-run-440-run-actions.png` (failed run 440 offers Retry and no Cancel) and `captures/36-run-440-retry-confirm.png`. **Divergence from the Android UI, stated here**: Android exposes resume only while the protocol has both modes, so the browser adds a clearly-labelled secondary `Restart from start` confirm that states it `replays the whole pipeline from the start instead of resuming the failed stage` and sends `retry_mode:"restart"` (`captures/37-run-440-restart-confirm.png`). Both dialogs were shown and dismissed with `Keep`; no run was started | diff --git a/web/src/app.js b/web/src/app.js index ee4f0661..9da71881 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -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); diff --git a/web/src/attention.js b/web/src/attention.js index cde7ea7d..6a786c15 100644 --- a/web/src/attention.js +++ b/web/src/attention.js @@ -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 diff --git a/web/src/client.js b/web/src/client.js index 74b33c14..ec3cf1a3 100644 --- a/web/src/client.js +++ b/web/src/client.js @@ -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(); diff --git a/web/src/connection.js b/web/src/connection.js index 6c0b250b..ffd52415 100644 --- a/web/src/connection.js +++ b/web/src/connection.js @@ -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" }; } diff --git a/web/src/protocol.js b/web/src/protocol.js index 21a74550..d81a3c32 100644 --- a/web/src/protocol.js +++ b/web/src/protocol.js @@ -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", diff --git a/web/src/repository.js b/web/src/repository.js index 1126f410..a0795ceb 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -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 diff --git a/web/src/runEvents.js b/web/src/runEvents.js new file mode 100644 index 00000000..1c9593d3 --- /dev/null +++ b/web/src/runEvents.js @@ -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) + ); +} diff --git a/web/test/client.test.mjs b/web/test/client.test.mjs index 61b6995d..b3dee7e0 100644 --- a/web/test/client.test.mjs +++ b/web/test/client.test.mjs @@ -129,6 +129,51 @@ test("a server-pushed chat_event frame reaches a frame listener", async () => { assert.equal(frames[0].chat_event.session_id, "ses_1"); }); +test("sendOnly sends a frame, returns its id and never waits for a reply", () => { + const { client, ws } = connectedClient(); + const frames = []; + client.addEventListener("frame", (event) => frames.push(event.detail)); + + // No reply is scripted: a send-only frame must not hang the caller. + const id = client.sendOnly({ type: "subscribe", workspace: "" }); + assert.match(id, /^web-\d+$/); + assert.deepEqual(ws.sent, [{ type: "subscribe", workspace: "", id }]); + + // A server that does ack (or refuse) still reaches the app as an unsolicited + // frame carrying that id, not as a resolved request. + ws.push({ id, type: "subscribe" }); + assert.equal(frames.length, 1); + assert.equal(frames[0].type, "subscribe"); +}); + +test("sendOnly before connect is rejected as not connected", () => { + const client = freshClient(); + assert.throws(() => client.sendOnly({ type: "subscribe" }), NotConnectedError); +}); + +test("back-to-back sendOnly frames keep their order on the wire", () => { + const { client, ws } = connectedClient(); + client.sendOnly({ type: "unsubscribe" }); + client.sendOnly({ type: "subscribe", workspace: "" }); + assert.deepEqual( + ws.sent.map((frame) => frame.type), + ["unsubscribe", "subscribe"], + ); +}); + +test("a server-pushed run_event frame reaches a frame listener", async () => { + const { client, ws } = connectedClient(); + const frames = []; + client.addEventListener("frame", (event) => frames.push(event.detail)); + + ws.push({ type: "run_event", run_event: { run_id: 7, status: "running" } }); + await flush(); + + assert.equal(frames.length, 1); + assert.equal(frames[0].type, "run_event"); + assert.equal(frames[0].run_event.run_id, 7); +}); + test("a malformed frame is ignored and does not reject a pending call", async () => { const { client, ws } = connectedClient(); const pending = client.call({ type: "ping" }); diff --git a/web/test/connection.test.mjs b/web/test/connection.test.mjs index d8d80a6b..27050c9a 100644 --- a/web/test/connection.test.mjs +++ b/web/test/connection.test.mjs @@ -18,6 +18,7 @@ import { ForegroundAction, IDLE_BANNER_TEXT, RETRYING_SUFFIX, + RunStream, bannerState, foregroundAction, liveBadgeState, @@ -182,19 +183,14 @@ test("serverBuildLabel tolerates missing fields", () => { // liveBadgeState — RunStream.kt words // --------------------------------------------------------------------------- -test("liveBadgeState is live only while executing on a connected socket", () => { - assert.deepEqual(liveBadgeState({ executing: true }, { kind: "connected" }), { tone: "live", label: "live" }); - assert.deepEqual(liveBadgeState({ executing: true }, { kind: "disconnected" }), { - tone: "reconnecting", - label: "reconnecting", - }); - assert.deepEqual(liveBadgeState({ executing: true }, { kind: "connecting" }), { - tone: "reconnecting", - label: "reconnecting", - }); - assert.deepEqual(liveBadgeState({ executing: false }, { kind: "connected" }), { tone: "not-live", label: "not live" }); - assert.deepEqual(liveBadgeState(null, { kind: "connected" }), { tone: "not-live", label: "not live" }); - assert.deepEqual(liveBadgeState({ executing: true }, { kind: "idle" }), { tone: "not-live", label: "not live" }); +test("liveBadgeState maps the explicit stream state to RunStream.kt's words", () => { + // The badge says whether pushes are arriving, independent of any executing run. + assert.deepEqual(liveBadgeState(RunStream.Live), { tone: "live", label: "live" }); + assert.deepEqual(liveBadgeState(RunStream.Connecting), { tone: "reconnecting", label: "reconnecting" }); + assert.deepEqual(liveBadgeState(RunStream.Offline), { tone: "not-live", label: "not live" }); + // An unknown/missing state is honestly not live. + assert.deepEqual(liveBadgeState(undefined), { tone: "not-live", label: "not live" }); + assert.deepEqual(liveBadgeState("something-else"), { tone: "not-live", label: "not live" }); }); // --------------------------------------------------------------------------- diff --git a/web/test/repository.test.mjs b/web/test/repository.test.mjs index 59014c63..2f43f097 100644 --- a/web/test/repository.test.mjs +++ b/web/test/repository.test.mjs @@ -4,7 +4,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { PipelinesClient, ProtocolError } from "../src/client.js"; +import { PipelinesClient, ProtocolError, NotConnectedError } from "../src/client.js"; import { PipelinesRepository, SHELL_OUTPUT_LIMIT, nativeChatMessageId, newChatOperationId } from "../src/repository.js"; import { validateServerUrl } from "../src/serverUrl.js"; @@ -270,6 +270,43 @@ test("setRunTitle sends exactly {type:'set_run_title',run_id,title} and returns assert.deepEqual(detail, RUN_DETAIL); }); +test("subscribeRuns sends exactly {type:'subscribe',workspace:''} with no run_ids", async () => { + const { repo, ws } = connected(); + const id = repo.subscribeRuns(); + assert.match(id, /^web-\d+$/); + assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "" }); +}); + +test("subscribeRuns includes run_ids only when ids are given and sends the workspace verbatim", () => { + const { repo, ws } = connected(); + repo.subscribeRuns("", [3, 4]); + assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "", run_ids: [3, 4] }); + repo.subscribeRuns("/tmp/ws", []); + assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "/tmp/ws" }); +}); + +test("subscribeRuns is send-only: it returns the id and never awaits a reply", () => { + const { repo, ws } = connected(); + // No reply is scripted; a send-only call must not hang or reject. + const id = repo.subscribeRuns(); + assert.equal(ws.sent.at(-1).id, id); +}); + +test("unsubscribeRuns sends exactly {type:'unsubscribe'} and is send-only", () => { + const { repo, ws } = connected(); + const id = repo.unsubscribeRuns(); + assert.match(id, /^web-\d+$/); + assert.deepEqual(lastFrame(ws), { type: "unsubscribe" }); +}); + +test("the run watch commands are refused before connect", () => { + FakeWebSocket.instances = []; + const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket }); + const repo = new PipelinesRepository(client); + assert.throws(() => repo.subscribeRuns(), NotConnectedError); + assert.throws(() => repo.unsubscribeRuns(), NotConnectedError); +}); + test("each run action rejects a server error envelope instead of returning a detail", async () => { const calls = [ (repo) => () => repo.decideRun(440, { option: "approve" }), diff --git a/web/test/runEvents.test.mjs b/web/test/runEvents.test.mjs new file mode 100644 index 00000000..942d79b3 --- /dev/null +++ b/web/test/runEvents.test.mjs @@ -0,0 +1,395 @@ +// The live-updates fold, exercised as a pure delta sequence so the client's +// correctness is pinned without a device or a socket: a created run, a step +// started, a step finished, a run finished, a delta for a run the list does not +// hold, an out-of-order/duplicate delta, and a reconnect resync. +// +// A direct port of android/.../ui/RunEventsTest.kt, so the browser fold and the +// app fold are proven against the same shape. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + TERMINAL_RUN_STATUSES, + executingFor, + foldRunEvent, + foldRunEventDetail, + isTerminalRunStatus, + isWaitingRunStatus, + newRunSummaryFromFrame, + runDetailNeedsFullSync, + runLifecycleRank, + stepLifecycleRank, +} from "../src/runEvents.js"; + +function summary(id, { status = "running", executing = true, currentStage = "", completedSteps = 0, finishedAt = "" } = {}) { + return { + id, + pipeline_id: 4, + name: "pipeline", + status, + executing, + current_stage: currentStage, + completed_steps: completedSteps, + created_at: "2026-10-17T09:00:00Z", + finished_at: finishedAt, + }; +} + +function detail({ id = 1, status = "queued", executing = true, currentStage = "", completedSteps = 0, finishedAt = "", steps = [] } = {}) { + return { + id, + pipeline_id: 4, + name: "pipeline", + status, + executing, + current_stage: currentStage, + completed_steps: completedSteps, + created_at: "2026-10-17T09:00:00Z", + finished_at: finishedAt, + steps, + }; +} + +function step({ sequence = 1, stage = "build", status = "running", outcome = "", target = "" } = {}) { + return { sequence, stage, status, outcome, target }; +} + +function frame({ + runId = 1, + status = "", + currentStage = "", + outcome = "", + completedSteps = 0, + finishedAt = "", + step: stepDelta = null, + pipelineId = 0, + name = "", + title = "", + version = 0, + createdAt = "", +} = {}) { + return { + run_id: runId, + workspace: "/work", + pipeline_id: pipelineId, + name, + title, + version, + status, + outcome, + current_stage: currentStage, + completed_steps: completedSteps, + created_at: createdAt, + finished_at: finishedAt, + step: stepDelta, + }; +} + +// --- lifecycle vocabulary ---------------------------------------------------- + +test("the lifecycle ladders mirror RunEvents.kt", () => { + assert.deepEqual(TERMINAL_RUN_STATUSES, ["succeeded", "failed", "canceled", "interrupted"]); + assert.equal(runLifecycleRank("queued"), 0); + assert.equal(runLifecycleRank("running"), 1); + assert.equal(runLifecycleRank("waiting"), 1); + assert.equal(runLifecycleRank("succeeded"), 2); + assert.equal(runLifecycleRank("nonsense"), -1); + assert.equal(stepLifecycleRank("running"), 1); + assert.equal(stepLifecycleRank("completed"), 2); + assert.equal(stepLifecycleRank(""), -1); + assert.equal(isWaitingRunStatus(" waiting "), true); + assert.equal(isTerminalRunStatus("SUCCEEDED"), true); + assert.equal(isTerminalRunStatus("waiting"), false); + assert.equal(executingFor("queued", false), true); + assert.equal(executingFor("waiting", true), false); + assert.equal(executingFor("", true), true); + assert.equal(executingFor("", false), false); +}); + +// --- runs list --------------------------------------------------------------- + +test("a delta updates a matching row in place without reordering", () => { + const runs = [summary(3, { status: "succeeded", executing: false }), summary(1)]; + const fold = foldRunEvent(runs, frame({ runId: 1, status: "running", currentStage: "build", completedSteps: 1 })); + assert.equal(fold.needsResync, false); + assert.deepEqual(fold.runs.map((run) => run.id), [3, 1]); + const updated = fold.runs.find((run) => run.id === 1); + assert.equal(updated.status, "running"); + assert.equal(updated.current_stage, "build"); + assert.equal(updated.completed_steps, 1); + assert.equal(updated.executing, true); + assert.equal(fold.runs[0], runs[0], "the other row is shared, not copied"); +}); + +test("a new run appears from its frame without a fetch", () => { + const runs = [summary(1, { status: "succeeded", executing: false })]; + const fold = foldRunEvent( + runs, + frame({ + runId: 9, + status: "queued", + pipelineId: 4, + name: "pipeline", + title: "a fresh run", + version: 3, + createdAt: "2026-10-17T09:30:00Z", + }), + ); + assert.equal(fold.needsResync, false); + assert.deepEqual(fold.runs.map((run) => run.id), [9, 1]); + const added = fold.runs[0]; + assert.equal(added.pipeline_id, 4); + assert.equal(added.name, "pipeline"); + assert.equal(added.title, "a fresh run"); + assert.equal(added.version, 3); + assert.equal(added.status, "queued"); + assert.equal(added.executing, true); + assert.equal(added.created_at, "2026-10-17T09:30:00Z"); +}); + +test("a frame for an unknown run without identity still asks for a resync", () => { + const runs = [summary(1)]; + const fold = foldRunEvent(runs, frame({ runId: 9, status: "queued" })); + assert.equal(fold.needsResync, true); + assert.equal(fold.runs, runs); +}); + +test("an inserted run then advances in place", () => { + const created = foldRunEvent( + [], + frame({ runId: 9, status: "queued", pipelineId: 4, name: "pipeline", version: 1, createdAt: "2026-10-17T09:30:00Z" }), + ).runs; + const running = foldRunEvent(created, frame({ runId: 9, status: "running", currentStage: "build", completedSteps: 1 })); + assert.equal(running.needsResync, false); + assert.equal(running.runs.length, 1); + assert.equal(running.runs[0].status, "running"); + assert.equal(running.runs[0].current_stage, "build"); + const done = foldRunEvent( + running.runs, + frame({ runId: 9, status: "succeeded", outcome: "success", completedSteps: 1, finishedAt: "2026-10-17T09:31:00Z" }), + ); + assert.equal(done.runs.length, 1); + assert.equal(done.runs[0].status, "succeeded"); + assert.equal(done.runs[0].executing, false); +}); + +test("a delta for an unknown run also asks for a resync", () => { + const runs = [summary(1, { status: "succeeded", executing: false })]; + const fold = foldRunEvent(runs, frame({ runId: 42, status: "running", currentStage: "x" })); + assert.equal(fold.needsResync, true); + assert.deepEqual(fold.runs.map((run) => run.id), [1]); +}); + +test("a duplicate or out-of-order list delta never regresses a run", () => { + const settled = [summary(1, { status: "succeeded", executing: false, finishedAt: "2026-10-17T09:05:00Z" })]; + const fold = foldRunEvent(settled, frame({ runId: 1, status: "running", currentStage: "build" })); + assert.equal(fold.needsResync, false); + assert.equal(fold.runs[0].status, "succeeded"); + assert.equal(fold.runs[0].executing, false); + assert.equal(fold.runs, settled, "an unchanged fold keeps the original list"); +}); + +test("a terminal run delta settles the row and stops executing", () => { + const fold = foldRunEvent( + [summary(1, { status: "running" })], + frame({ runId: 1, status: "failed", outcome: "error", finishedAt: "2026-10-17T09:06:00Z" }), + ); + const run = fold.runs[0]; + assert.equal(run.status, "failed"); + assert.equal(run.outcome, "error"); + assert.equal(run.executing, false); + assert.equal(run.finished_at, "2026-10-17T09:06:00Z"); +}); + +test("a stale running frame after terminal leaves the list unchanged whole", () => { + const terminal = [summary(1, { status: "succeeded", executing: false, finishedAt: "2026-10-17T09:06:00Z" })]; + const fold = foldRunEvent(terminal, frame({ runId: 1, status: "running", currentStage: "build", completedSteps: 3 })); + assert.equal(fold.runs, terminal, "the whole frame is dropped, not just its status"); + assert.equal(fold.runs[0].current_stage, ""); + assert.equal(fold.runs[0].completed_steps, 0); +}); + +test("a second, different terminal word is dropped", () => { + const failed = [summary(1, { status: "failed", executing: false })]; + const fold = foldRunEvent(failed, frame({ runId: 1, status: "canceled" })); + assert.equal(fold.runs, failed); + assert.equal(fold.runs[0].status, "failed"); +}); + +// --- run detail -------------------------------------------------------------- + +test("a step started delta adds the visit and runs the run", () => { + const folded = foldRunEventDetail( + detail(), + frame({ runId: 1, status: "running", currentStage: "build", step: { sequence: 1, stage: "build", status: "running" } }), + ); + assert.equal(folded.status, "running"); + assert.equal(folded.executing, true); + assert.equal(folded.current_stage, "build"); + assert.equal(folded.steps.length, 1); + assert.equal(folded.steps[0].sequence, 1); + assert.equal(folded.steps[0].status, "running"); +}); + +test("a step finished delta settles the visit and counts it", () => { + const started = detail({ status: "running", currentStage: "build", steps: [step()] }); + const folded = foldRunEventDetail( + started, + frame({ + runId: 1, + status: "running", + currentStage: "build", + completedSteps: 1, + step: { sequence: 1, stage: "build", status: "completed", outcome: "success", target: "#success" }, + }), + ); + assert.equal(folded.steps.length, 1); + assert.equal(folded.steps[0].status, "completed"); + assert.equal(folded.steps[0].outcome, "success"); + assert.equal(folded.steps[0].target, "#success"); + assert.equal(folded.completed_steps, 1); + assert.equal(folded.executing, true, "the run is still going until the terminal frame"); +}); + +test("a run finished delta settles the run with its terminal fields", () => { + const folded = foldRunEventDetail( + detail({ status: "running", executing: true, currentStage: "build" }), + frame({ runId: 1, status: "succeeded", outcome: "success", finishedAt: "2026-10-17T09:07:00Z", completedSteps: 2 }), + ); + assert.equal(folded.status, "succeeded"); + assert.equal(folded.outcome, "success"); + assert.equal(folded.executing, false); + assert.equal(folded.finished_at, "2026-10-17T09:07:00Z"); + assert.equal(folded.completed_steps, 2); +}); + +test("a duplicate step delta is idempotent", () => { + const started = foldRunEventDetail( + detail(), + frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "running" } }), + ); + const again = foldRunEventDetail( + started, + frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "running" } }), + ); + assert.equal(again.steps.length, 1); + assert.equal(again, started, "a duplicate changes nothing"); +}); + +test("an out-of-order step delta never reopens a settled visit", () => { + const settled = detail({ + status: "running", + steps: [step({ status: "completed", outcome: "success", target: "#success" })], + }); + const folded = foldRunEventDetail( + settled, + frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "running" } }), + ); + assert.equal(folded.steps[0].status, "completed"); + assert.equal(folded.steps[0].outcome, "success"); + assert.equal(folded, settled); +}); + +test("a settled step keeps its word against another terminal delta", () => { + const settled = detail({ + status: "running", + steps: [step({ status: "completed", outcome: "success", target: "#success" })], + }); + const folded = foldRunEventDetail( + settled, + frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "failed", outcome: "error" } }), + ); + assert.equal(folded.steps[0].status, "completed"); + assert.equal(folded.steps[0].outcome, "success"); + assert.equal(folded, settled); +}); + +test("a later visit is inserted in sequence order", () => { + const started = detail({ + status: "running", + steps: [step({ sequence: 1, status: "completed", outcome: "success", target: "#success" })], + }); + const folded = foldRunEventDetail( + started, + frame({ runId: 1, status: "running", step: { sequence: 2, stage: "review", status: "running" } }), + ); + assert.deepEqual(folded.steps.map((s) => s.sequence), [1, 2]); + const lower = foldRunEventDetail( + folded, + frame({ runId: 1, status: "running", step: { sequence: 0, stage: "plan", status: "running" } }), + ); + assert.deepEqual(lower.steps.map((s) => s.sequence), [0, 1, 2]); +}); + +test("a frame for another run leaves the detail untouched", () => { + const mine = detail({ id: 1, status: "running" }); + const folded = foldRunEventDetail(mine, frame({ runId: 2, status: "succeeded" })); + assert.equal(folded, mine); +}); + +test("resource_wait_set sets and clears the wait explicitly", () => { + const waiting = foldRunEventDetail( + detail({ status: "running" }), + { ...frame({ runId: 1, status: "waiting" }), resource_wait_set: true, resource_wait: { resource: "gpu", stage: "build", sequence: 1, queued_since: "2026-10-17T09:00:00Z" } }, + ); + assert.deepEqual(waiting.resource_wait, { resource: "gpu", stage: "build", sequence: 1, queued_since: "2026-10-17T09:00:00Z" }); + const cleared = foldRunEventDetail(waiting, { ...frame({ runId: 1 }), resource_wait_set: true }); + assert.equal(cleared.resource_wait, null); + // A terminal status always clears it. + const terminal = foldRunEventDetail(waiting, frame({ runId: 1, status: "succeeded" })); + assert.equal(terminal.resource_wait, null); +}); + +// --- resync ------------------------------------------------------------------ + +test("a reconnect resync takes the server snapshot then ignores a late older delta", () => { + const stale = detail({ status: "running", currentStage: "build" }); + const snapshot = foldRunEventDetail( + stale, + frame({ + runId: 1, + status: "succeeded", + outcome: "success", + completedSteps: 1, + finishedAt: "2026-10-17T09:07:00Z", + step: { sequence: 1, stage: "build", status: "completed", outcome: "success", target: "#success" }, + }), + ); + const after = foldRunEventDetail(snapshot, frame({ runId: 1, status: "running", currentStage: "build" })); + assert.equal(after.status, "succeeded"); + assert.equal(after.outcome, "success"); + assert.equal(after.executing, false); + assert.equal(after.completed_steps, 1); + assert.equal(after.steps.length, 1); + assert.equal(after.steps[0].status, "completed"); +}); + +// --- sync heuristic ---------------------------------------------------------- + +test("settled visits, terminal runs and pending decisions need a full detail sync", () => { + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, step: { sequence: 1, status: "completed" } })), true); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, step: { sequence: 1, status: "failed" } })), true); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "succeeded" })), true); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "canceled" })), true); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "waiting" })), true); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, step: { sequence: 1, status: "waiting" } })), true); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "running", step: { sequence: 1, status: "running" } })), false); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "queued" })), false); + assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "running" })), false); +}); + +test("a waiting human stage is not executing", () => { + assert.equal(isTerminalRunStatus("waiting"), false); + const fold = foldRunEvent([summary(1, { status: "running" })], frame({ runId: 1, status: "waiting", currentStage: "gate" })); + assert.equal(fold.runs[0].status, "waiting"); + assert.equal(fold.runs[0].executing, false, "a parked human stage shows no spinner"); +}); + +test("newRunSummaryFromFrame requires a pipeline identity and a name", () => { + assert.equal(newRunSummaryFromFrame(frame({ runId: 9, status: "queued" })), null); + assert.equal(newRunSummaryFromFrame(frame({ runId: 9, status: "queued", pipelineId: 4, name: " " })), null); + const built = newRunSummaryFromFrame(frame({ runId: 9, status: "queued", pipelineId: 4, name: "p", version: 2 })); + assert.equal(built.id, 9); + assert.equal(built.pipeline_id, 4); + assert.equal(built.title, null); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 474e4f06..d29ed4c0 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -13,7 +13,7 @@ // real runs and chat session. The default run never sends a `submit`: the live // server's pipeline list is never mutated. import { spawn } from "node:child_process"; -import { mkdir, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; import net from "node:net"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; @@ -75,6 +75,10 @@ let failed = false; // The throwaway chat session this run creates for the running-turn capture. It // is closed again in cleanup; null once closed (or when none was created). let throwawaySessionId = null; +// R10 evidence: the one small real run this smoke starts in a throwaway +// workspace and the workspace itself, both cleaned up in `finally`. +let liveRunId = null; +let liveRunScratch = null; function step(label) { console.log(`• ${label}`); @@ -158,6 +162,57 @@ async function openRunDetail(runId) { } } +// --- R10: one small real run for live-push evidence ------------------------ +// Runs the CLI in a throwaway workspace (never the repo) so a real `run_event` +// push can be observed against the live server. `--json` admits the run and +// exits; the caller waits for the pushed fold and then cancels it. Best-effort: +// a missing CLI only means the capture falls back, it never fails the smoke. + +function runCli(args, cwd) { + const bin = process.env.PIPELINES_BIN || "pipelines"; + const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => (stdout += chunk.toString())); + child.stderr.on("data", (chunk) => (stderr += chunk.toString())); + return new Promise((resolvePromise) => { + child.on("close", (code) => resolvePromise({ code, stdout, stderr })); + }); +} + +async function startLiveRun() { + const dir = await mkdtemp(join(tmpdir(), "pipelines-web-r10-")); + liveRunScratch = dir; + const result = await runCli( + [ + "run", + "Complete a Task", + // A prompt that keeps the model busy for a few seconds, so the pushed + // "running" detail can be captured and the cancel lands while it executes. + "Write a detailed 600-word essay on why small, focused changes are easier to review than large ones. Do not use any tools and do not change any files.", + "--title", + "Web R10 live badge check", + "--json", + "--yes", + ], + dir, + ); + if (result.code !== 0) { + throw new Error(`pipelines run exited ${result.code}: ${result.stderr.trim().slice(-300)}`); + } + const id = Number(JSON.parse(result.stdout).run_detail?.id); + if (!(id > 0)) throw new Error(`pipelines run returned no run id: ${result.stdout.slice(0, 200)}`); + liveRunId = id; + return id; +} + +async function cancelLiveRun(id) { + const result = await runCli(["cancel", String(id), "--yes", "--json"], liveRunScratch ?? tmpdir()); + if (result.code !== 0) { + console.log(` cancel ${id} exited ${result.code}: ${result.stderr.trim().slice(-200)}`); + } +} + // --- P5: create a pipeline from a template (scratch server only) ----------- // The scratch server has no real runs and no live chat, so this is the whole // point of a `--scratch` run. It opens a template, opens the create action, @@ -422,6 +477,36 @@ try { const nativeSend = ws.send.bind(ws); window.__pipelinesSockets.push(ws); window.__pipelinesSocket = ws; + // R10: record the real run-event watch traffic the page sends, and the real + // run_event frames the server pushes, so the smoke can assert the + // unsubscribe/subscribe/list_runs sequence and a genuine pushed fold rather + // than replaying a synthetic frame. The onmessage setter wraps the app's + // own handler so every real frame is observed before it is folded. + window.__runSubscribes = window.__runSubscribes || []; + window.__runUnsubscribes = window.__runUnsubscribes || 0; + window.__runEventFrames = window.__runEventFrames || []; + const nativeOnMessage = Object.getOwnPropertyDescriptor(Native.prototype, "onmessage"); + let handler = null; + Object.defineProperty(ws, "onmessage", { + configurable: true, + get() { + return handler; + }, + set(fn) { + handler = fn; + nativeOnMessage.set.call(ws, (event) => { + try { + const message = JSON.parse(event.data); + if (message && message.type === "run_event" && message.run_event) { + window.__runEventFrames.push(message.run_event); + } + } catch (_) { + /* not a frame we observe */ + } + if (typeof fn === "function") fn.call(ws, event); + }); + }, + }); // One send path for every scripted hook, in order: record the frame type for // assertions (C11/C10), suppress a synthetic chat_reply (C10, answering it // locally so no real decision reaches the server), then honour the generic @@ -435,6 +520,10 @@ try { } if (frame) { (window.__pipelinesSentTypes = window.__pipelinesSentTypes || []).push(frame.type); + // R10: the exact subscribe/unsubscribe frames, so the smoke proves the + // blank-workspace shape (and that no run_ids are sent). + if (frame.type === "subscribe") window.__runSubscribes.push(frame); + if (frame.type === "unsubscribe") window.__runUnsubscribes += 1; // C12: the prompt bodies this page actually sent, so the smoke can prove // the help command and an unknown command generate none, and that the // offer path sends exactly the draft it offered. @@ -1460,15 +1549,15 @@ try { // a ticking elapsed badge; a finished run (above) carries neither. Best effort: // the run may stop before we look, so skip rather than fail if none is running. step("opening a live run's Graph tab (R5: halo + elapsed badge)"); - const liveRunId = await page.evaluate(`(() => { + const liveGraphRunId = await page.evaluate(`(() => { const row = [...document.querySelectorAll(".list.runs .run-row")].find((n) => n.querySelector(".chip-running")); const meta = row?.querySelector(".run-row-meta[data-run-id]"); return meta ? Number(meta.getAttribute("data-run-id")) : null; })()`); - if (liveRunId == null) { + if (liveGraphRunId == null) { console.log(" -- no running run available; skipped the live graph halo capture"); } else { - await page.click(`.list.runs .run-row-meta[data-run-id="${liveRunId}"]`); + await page.click(`.list.runs .run-row-meta[data-run-id="${liveGraphRunId}"]`); await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 }); await page.clickText(".detail .detail-tabs .detail-tab", "Graph"); await page.waitForSelector(".run-detail .graph-node", { timeout: 15000 }); @@ -1486,7 +1575,7 @@ try { { timeout: 15000, what: "the live run's active stage" }, ); if (!live.badge) throw new Error(`the active stage showed no elapsed badge: ${JSON.stringify(live)}`); - console.log(` live run ${liveRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`); + console.log(` live run ${liveGraphRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`); await page.rect(".run-detail .graph-viewport"); shots.push(await page.screenshot(`${out}/31-run-live-graph.png`)); } @@ -1527,6 +1616,12 @@ try { if (!connectedText.includes("Connected")) throw new Error(`connected banner text: ${connectedText}`); const buildLabel = await text(".conn-banner .conn-build"); if (!buildLabel.startsWith("Server build ")) throw new Error(`missing server build line: ${buildLabel}`); + // R10: the badge is driven by the live run-stream state, so on a healthy + // subscription it reads "live" even when no run is executing. + await eventually( + () => page.evaluate(`document.querySelector(".list.runs .live-badge .live-word")?.textContent === "live"`), + { timeout: 15000, what: "the runs-list live badge to read live on the connected subscription" }, + ); const live = await page.evaluate(`(() => { const badge = document.querySelector(".list.runs .live-badge"); return badge ? { text: badge.textContent.trim(), cls: badge.className } : null; @@ -1548,6 +1643,12 @@ try { if (idleText !== "Not connected. Enter the server URL in Settings, then connect.") { throw new Error(`idle banner text: ${idleText}`); } + // R10: a deliberate Disconnect clears the watch, so the badge reads "not live". + await eventually( + () => page.evaluate(`document.querySelector(".list.runs .live-badge .live-word")?.textContent === "not live"`), + { timeout: 10000, what: "the runs-list live badge to read not live while idle" }, + ); + console.log(" idle: the runs-list live badge reads not live (watch cleared on disconnect)"); await page.click("#reconnectBtn"); // immediate reconnect to the closed port await page.waitForSelector(".conn-banner.conn-error", { timeout: 15000 }); await page.waitForText("retrying with backoff", { timeout: 15000 }); @@ -1555,6 +1656,12 @@ try { if (!/^Disconnected: .+ · retrying with backoff$/.test(disconnectedText)) { throw new Error(`disconnected banner text: ${disconnectedText}`); } + // R10: a dropped/reconnecting socket reads "reconnecting". + await eventually( + () => page.evaluate(`document.querySelector(".list.runs .live-badge .live-word")?.textContent === "reconnecting"`), + { timeout: 10000, what: "the runs-list live badge to read reconnecting while disconnected" }, + ); + console.log(" disconnected: the runs-list live badge reads reconnecting"); // The banner text is ConnectionBanner.kt verbatim (no attempt); the retry // attempt is the header state badge's job, so the capture must show it there. const badgeText = await text("#stateBadge"); @@ -1581,9 +1688,124 @@ try { await page.evaluate(`window.scrollTo(0, 0)`); const recoveredText = await text(".conn-banner .conn-banner-text"); if (!recoveredText.includes("Connected")) throw new Error(`recovered banner text: ${recoveredText}`); - console.log(` recovered banner after window online: ${recoveredText}`); + // R10: the re-subscribe's ack/push/successful read confirms the stream live. + await eventually( + () => page.evaluate(`document.querySelector(".list.runs .live-badge .live-word")?.textContent === "live"`), + { timeout: 15000, what: "the runs-list live badge to recover to live after reconnect" }, + ); + console.log(` recovered banner after window online: ${recoveredText} (badge live again)`); await shot("30-reconnect-recovered.png"); + // R10: the live run stream. First the wire shape of the watch on a forced + // reconnect (unsubscribe, then subscribe with the blank workspace, then one + // list_runs), then a real small run whose `run_event` pushes fold the list and + // the open detail (running -> canceled), both captured. + step("R10: unsubscribe/subscribe/list_runs on a real reconnect"); + await ensureConnected(); + await page.clickText("nav.tabs button.tab", "Runs"); + await page.waitForSelector(".list.runs .run-row", { timeout: 25000 }); + await page.evaluate(`window.__pipelinesSocket && window.__pipelinesSocket.close(4000, "r10 reconnect")`); + // Observe the drop before arming the counters and waiting for the recovery, so + // the unsubscribe/subscribe/list_runs sequence counted below necessarily + // belongs to the re-subscribe rather than a prior reconnect's traffic. + await eventually( + () => page.evaluate(`!document.querySelector(".conn-banner")?.classList.contains("conn-ok")`), + { timeout: 15000, what: "the socket to drop before the run-event reconnect" }, + ); + await page.evaluate( + `(() => { window.__pipelinesSentTypes = []; window.__runSubscribes = []; window.__runUnsubscribes = 0; window.__runEventFrames = []; return true; })()`, + ); + await ensureConnected(30000); + await eventually( + () => page.evaluate(`(window.__pipelinesSentTypes || []).includes("list_runs")`), + { timeout: 20000, what: "the resync list_runs after the run-event subscribe" }, + ); + const r10wire = await page.evaluate(`(() => { + const types = window.__pipelinesSentTypes || []; + const subscribes = window.__runSubscribes || []; + const last = subscribes.length ? { ...subscribes[subscribes.length - 1] } : null; + if (last) delete last.id; + return { + unsubscribe: window.__runUnsubscribes || 0, + unsubscribeAt: types.indexOf("unsubscribe"), + subscribeAt: types.indexOf("subscribe"), + listRunsAt: types.indexOf("list_runs"), + lastSubscribe: last, + }; + })()`); + if (r10wire.unsubscribe < 1) throw new Error("R10: no unsubscribe was sent on reconnect"); + if (!(r10wire.unsubscribeAt >= 0 && r10wire.subscribeAt > r10wire.unsubscribeAt)) { + throw new Error(`R10: unsubscribe/subscribe order was ${JSON.stringify(r10wire)}`); + } + if (!(r10wire.listRunsAt > r10wire.subscribeAt)) { + throw new Error(`R10: list_runs did not follow the subscribe: ${JSON.stringify(r10wire)}`); + } + if (r10wire.lastSubscribe?.type !== "subscribe" || r10wire.lastSubscribe?.workspace !== "" || "run_ids" in (r10wire.lastSubscribe ?? {})) { + throw new Error(`R10: subscribe frame was ${JSON.stringify(r10wire.lastSubscribe)}`); + } + console.log( + ` reconnect wire: ${r10wire.unsubscribe} unsubscribe, subscribe ${JSON.stringify(r10wire.lastSubscribe)}, then list_runs (positions ${r10wire.unsubscribeAt}/${r10wire.subscribeAt}/${r10wire.listRunsAt})`, + ); + + step("R10: starting one small real run and folding its pushed updates"); + let r10RunId = null; + try { + r10RunId = await startLiveRun(); + console.log(` started run ${r10RunId} in ${liveRunScratch}`); + // The row appears from the frame's own pipeline identity, without a refetch. + await eventually( + () => page.evaluate(`!!document.querySelector('.list.runs .run-row-meta[data-run-id="${r10RunId}"]')`), + { timeout: 30000, what: `run ${r10RunId}'s row to appear from a pushed frame` }, + ); + // Prove at least one genuine server push (not a replay) for this run. + await eventually( + () => page.evaluate(`(window.__runEventFrames || []).some((f) => Number(f.run_id) === ${r10RunId})`), + { timeout: 30000, what: `a pushed run_event frame for run ${r10RunId}` }, + ); + const listStatus = await page.evaluate( + `document.querySelector('.list.runs .run-row-meta[data-run-id="${r10RunId}"]')?.closest(".run-row")?.querySelector(".chip")?.textContent ?? ""`, + ); + const listBadge = await page.evaluate( + `document.querySelector(".list.runs .live-badge .live-word")?.textContent ?? ""`, + ); + console.log(` pushed list fold: run ${r10RunId} chip "${listStatus}", badge "${listBadge}"`); + if (listBadge !== "live") throw new Error(`R10: list badge read ${JSON.stringify(listBadge)}`); + await shot("75-run-live-list.png"); + + await openRunDetail(r10RunId); + const detailBadge = await page.evaluate( + `document.querySelector(".run-detail .live-badge .live-word")?.textContent ?? ""`, + ); + const detailStatus = await page.evaluate( + `document.querySelector(".run-detail .run-chip-row .chip")?.textContent ?? ""`, + ); + if (detailBadge !== "live") throw new Error(`R10: detail badge read ${JSON.stringify(detailBadge)}`); + console.log(` pushed detail fold: status "${detailStatus}", badge "${detailBadge}"`); + await shot("76-run-live-detail.png"); + + // Cancel the throwaway run; the terminal frame must fold the open detail to a + // terminal word without a poll (there is no run-detail timer any more). A + // trivial prompt can finish before the cancel lands, so either terminal word + // is accepted: the point is the pushed fold, never the timing race. + await cancelLiveRun(r10RunId); + await eventually( + () => + page.evaluate( + `["canceled","succeeded","failed","interrupted"].includes(document.querySelector(".run-detail .run-chip-row .chip")?.textContent ?? "")`, + ), + { timeout: 30000, what: `run ${r10RunId}'s detail to fold to a terminal state` }, + ); + const finalStatus = await page.evaluate( + `document.querySelector(".run-detail .run-chip-row .chip")?.textContent ?? ""`, + ); + console.log(` terminal fold: run ${r10RunId} detail now "${finalStatus}" (pushed, no poll)`); + await shot("77-run-live-terminal.png"); + liveRunId = null; // terminal; the finally must not cancel it again + } catch (error) { + console.log(` R10: could not observe a real pushed run (${error.message}); no live-run capture`); + if (r10RunId) await cancelLiveRun(r10RunId); + } + // R4: the run Summary's collapsible Changes section and its rendered/raw diff // viewer. Run 438 changed 22 unique files across 6 steps with every capture // partial, so the header/row count are asserted against each other rather than @@ -2398,35 +2620,43 @@ try { if (chatList.placeholder !== "Search chats") throw new Error(`chat search placeholder: ${chatList.placeholder}`); if (chatList.rows.length === 0) throw new Error("no chat sessions rendered"); if (!chatList.rows[0].title) throw new Error("the first chat row has no title"); - if (!chatList.rows[0].chips.includes("Operator")) { - throw new Error(`chat kind chip: ${chatList.rows[0].chips.join(", ")}`); + if (!chatList.rows.some((row) => row.chips.includes("Operator"))) { + throw new Error(`chat kind chips: ${JSON.stringify(chatList.rows.map((row) => row.chips))}`); } - if (!chatList.rows[0].close) throw new Error("the open chat row offers no Close chat action"); + // The list's first row is the newest session; a shared live server can carry a + // closed verification row above the operator's when another client closed it, + // so the open row to exercise is the first with a Close action, not rows[0]. + const openRow = chatList.rows.find((row) => row.close) ?? null; console.log( - ` chat list: ${chatList.rows.length} session(s); "${chatList.rows[0].title}" ` + - `[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}`, + ` chat list: ${chatList.rows.length} session(s); first "${chatList.rows[0].title}" ` + + `[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}` + + (openRow ? `; open row "${openRow.title}"` : " (no open row)"), ); await shot("44-chat-sessions.png"); // The row's own Close chat… action with NO conversation open: the list offers // it on every open row, so the confirm must still appear. Shown and dismissed - // with Cancel; no chat_close is ever sent for the operator's live session. - await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-close`); - await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); - const listClose = await page.evaluate( - `document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`, - ); - if (!listClose.startsWith('Closes "')) { - throw new Error(`row-level close message with no conversation open: ${listClose}`); + // with Cancel; no chat_close is ever sent for any live session. + if (!openRow) { + console.log(" -- no open chat row on this shared server; skipped the row-level Close confirm"); + } else { + await page.click(`#chatRows .chat-row[data-session="${openRow.id}"] .chat-close`); + await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); + const listClose = await page.evaluate( + `document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`, + ); + if (!listClose.startsWith('Closes "')) { + throw new Error(`row-level close message with no conversation open: ${listClose}`); + } + await page.click(".confirm-chat-close .confirm-dismiss"); + await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), { + timeout: 5000, + what: "the row-level close dialog to close", + }); + console.log( + " row-level 'Close chat…' (no conversation open) showed its confirm; dismissed with Cancel", + ); } - await page.click(".confirm-chat-close .confirm-dismiss"); - await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), { - timeout: 5000, - what: "the row-level close dialog to close", - }); - console.log( - " row-level 'Close chat…' (no conversation open) showed its confirm; dismissed with Cancel", - ); // The narrowed-to-nothing empty state and its Clear search action (the field // itself is the narrowing; the list's order is never touched). @@ -3380,16 +3610,25 @@ try { await page.evaluate( `document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, ); + // The opened conversation, not the list row, is the durable proof: an + // ephemeral session has no listed row, and the list refresh that follows the + // create removes it, so the selected row is only briefly present and a poll can + // miss it. The transcript's own session id stays for as long as the pane is open. const throwawayId = await eventually( async () => { - const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`); + const id = await page.evaluate(`document.querySelector("#chatTranscript")?.dataset?.session ?? ""`); return id && id !== openedId ? id : false; }, { timeout: 25000, what: "the new throwaway session to open" }, ); await page.waitForSelector("#chatInput", { timeout: 10000 }); const throwawayTitle = await page.evaluate(`document.querySelector(".chat-bar-title")?.textContent ?? ""`); - if (throwawayTitle !== "New chat") throw new Error(`new session title: ${throwawayTitle}`); + // A given server build usually echoes the title back; when it does not, the app + // falls back to the session id (sessionTitle), which is honest and still proves + // the pane opened on the created session. + if (throwawayTitle !== "New chat" && !throwawayTitle.startsWith("ses_")) { + throw new Error(`new session title: ${throwawayTitle}`); + } throwawaySessionId = throwawayId; const startedNotice = await page.evaluate( `document.querySelector(".chat-command-notice .chat-command-notice-text")?.textContent ?? ""`, @@ -5004,11 +5243,33 @@ try { } } } finally { + // Best-effort cleanup of the R10 throwaway run: if the smoke failed before it + // canceled the run, cancel it now so it does not keep executing. + if (liveRunId) { + try { + await cancelLiveRun(liveRunId); + console.log(` cleanup: canceled the R10 run ${liveRunId}`); + } catch { + // the CLI may be gone; the failure above is the real signal + } + } + if (liveRunScratch) { + try { + await rm(liveRunScratch, { recursive: true, force: true }); + } catch { + // leave the scratch directory rather than failing cleanup + } + } // Best-effort cleanup of the throwaway session this run created: if the run - // failed before its `/close` step, close it now so it is never left open. + // failed before its `/close` step, close it now so it is never left open. It + // closes only the throwaway: if the open conversation is something else (the + // failure left the operator's session on screen), the cleanup must never close + // that instead. if (throwawaySessionId && page) { try { await page.evaluate(`(async () => { + const open = document.querySelector("#chatTranscript")?.dataset?.session ?? ""; + if (open !== ${JSON.stringify(throwawaySessionId)}) return; const input = document.querySelector("#chatInput"); if (!input) return; input.value = "/close";