diff --git a/android/README.md b/android/README.md index 108db232..22e209a6 100644 --- a/android/README.md +++ b/android/README.md @@ -5268,3 +5268,88 @@ measured grid at `wm size 2000x2244` — and that each card opens a Summary / Gr language. The empty, loading, error and unparseable-source states were built from the app's shared state components but could not be produced live without mutating the operator's server. + +### Live run updates from the socket (17 Oct 2026) + +`android/` only. The runs list, each pipeline row's last-run line, the run header +and the run detail (status, timeline, stages, artifacts) now advance from the +server's pushes; the one-second poll is gone. + +- **Wire.** `data/protocol/Message.kt` mirrors `internal/protocol/runevents.go`: + the `subscribe`/`unsubscribe`/`run_event` types, the optional `run_ids` scope + and the `run_event` payload (`RunEventFrame`/`RunStepDelta`). The frames are + unsolicited (no request id), so they already flowed through the client's + `events` stream; `PipelinesRepository.subscribeRuns`/`unsubscribeRuns` add the + typed command. `subscribe` is sent with `PipelinesClient.sendOnly` (it does not + hold the send lock waiting for the ack) because the running server does not + reliably ack it; any ack/error still lands on `events` with the request id. +- **One pure fold.** `ui/RunEvents.kt` folds one frame into the runs list (in + place, order preserved) and into the open run detail (status, timestamps, + current stage, completed count, and at most one step by sequence). It is + monotonic: a stale `running` delta after a settled run, or a late step delta, + is dropped whole, so an out-of-order or duplicate frame never regresses or + duplicates a visit. A frame for a run the list does not hold reports + `needsResync` rather than inventing a row the compact delta cannot describe. + The row and the detail share one run-field merge and one status ladder + (`RunStateFields`/`advanceStatus`), so their monotonic rules cannot drift. +- **Wiring.** `AppViewModel` subscribes once per (re)connect and per workspace + (a reconnect clears the watch and re-subscribes). Every (re)subscribe then + re-reads the list — and the open run, if any — *once*, because the running + server's subscribe snapshot is not guaranteed complete; the pushes that follow + fold on top of that authoritative read. `applyRunEvent` folds the frame into + `runs` and `runDetail`; an unknown run or a terminal transition triggers one + coalesced `list_runs` re-read, and a settled step or terminal run triggers one + coalesced full `get_run` so the artifacts/output the compact delta omits fill + in. Both re-reads are push/connect-driven, coalesced and loop only if a newer + frame arrives while the read is in flight (the open detail discards and retries + a fetch that a newer frame overtook, keyed by run id so switching runs mid-fetch + is not dropped), so nothing is stale and no timer polls. +- **Honest status.** `RunStreamState` (live/reconnecting/not live) is confirmed + by the subscribe ack, the first push, or a successful (re)connect read (the + running server's ack is unreliable, so a push and the connect read also confirm + it) and shown by the small `LiveBadge` in the runs list and the run detail. A + failed list/detail read is *not* swallowed: it drops the badge to + reconnecting and retries with a bounded backoff, so the badge never keeps + saying "live" over state that failed to update. A manual refresh stays but is + never required. +- **No fighting the operator.** Rows update in place under stable LazyColumn + keys, so scroll, the selected row and an open pane do not jump and the list + does not reshuffle while it is read. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--no-daemon --offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle --no-daemon --offline :app:assembleDebug :app:testDebugUnitTest` → + `BUILD SUCCESSFUL`; the JUnit XML totals **446 tests, 0 failures, 0 errors, 0 + skipped**. New `RunEventsTest` (16 cases) pins the delta sequence: a created run + not in the list (resync), a step started, a step finished (with completed + count), a run finished, a delta for an unknown run (resync), a + duplicate/out-of-order list and step delta (no regression, no duplicate visit), + a settled step keeping its word against a later terminal delta, a reconnect + resync that ignores a later older delta, and the full-sync heuristic. +- **The push path was confirmed on the running server** (`ws://10.0.0.75:8080`, + build `v0.0.0-20261017013542-7875762b9a2c`, i.e. this tree's `7875762`) by + dialling `/connect`, sending `list_runs` (241 runs) then + `subscribe {workspace:/Users/alan/repos/pipelines}`, and reading back + `run_event` frames (`run_id=239 … status=failed finished=…`, + `run_id=230 … succeeded`). Server-side push is a separate lane and is present; + no client-side stream was invented. **Observed limitation of that running + (dirty) server:** its subscribe snapshot was partial and its `subscribe` ack + did not arrive within 30s. The client therefore does not depend on the ack to + read live or to update: pushes confirm the stream and a delta for a run the + list does not hold re-reads `list_runs`. This is the server lane's to fix; the + client is correct against both the acked snapshot defined in + `internal/protocol/runevents.go` and the deployed behaviour. +- **APK publish.** `app-debug.apk` (18,754,221 bytes, sha256 + `dbddf756b5eb26f87ba4e2083fb979829b5d349d9cf1b114941e9ceeb137ddf1`) copied to + `~/.local/share/pipelines/data/artifacts/240/3/pipelines-debug-wip-7875762.apk`; + `curl -I` (to `http://10.0.0.75:8080/artifacts/240/3/pipelines-debug-wip-7875762.apk`) + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18754221`. This republishes the artifact with its actual hash: + the earlier `240/1` copy's recorded sha256 did not reproduce from this tree. + +Not verified in this pass (device work belongs to the visual-review stage, which +owns the operator's Pixel 9 Pro XL): the on-device status change with no refresh +and the live/reconnecting badge rendering. The captures and the phone's +main-revision restore are that stage's evidence. + diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index a2e17268..07265731 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -125,6 +125,32 @@ class PipelinesRepository( suspend fun getRunEvidence(id: Long): List = client.call(Message(type = Protocol.GET_RUN_EVIDENCE, runId = id)).evidence ?: emptyList() + /** + * Subscribes this connection to the workspace's run-state pushes. The server + * first sends the current state of every matching run as `run_event` frames + * (which arrive on [events]), then a compact delta on each transition, so a + * reconnecting client re-syncs before it applies deltas. [runIds] narrows the + * watch; an empty list watches the whole workspace. + * + * Returns the request id and does not wait for the ack: a server that never + * acks must not block the send lock, and the pushes themselves confirm the + * watch (see `AppViewModel.observeRunEvents`). Any ack or error reply lands on + * [events] with this id. + */ + suspend fun subscribeRuns(workspace: String, runIds: List = emptyList()): String = + client.sendOnly( + Message( + type = Protocol.SUBSCRIBE, + workspace = workspace, + runIds = runIds.ifEmpty { null }, + ), + ) + + /** Stops this connection's run-state pushes (best effort; a disconnect also drops them). */ + suspend fun unsubscribeRuns() { + client.sendOnly(Message(type = Protocol.UNSUBSCRIBE)) + } + /** * Sends one omni-search query over the shared transport and returns the raw * reply envelope. The server command is still landing, so the reply is diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt index 5d2c57c7..fb4a586d 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt @@ -37,6 +37,11 @@ object Protocol { const val GET_RUN_EVIDENCE = "get_run_evidence" const val RUN_EVIDENCE = "run_evidence" + // runevents.go: the workspace-scoped run-state push subscription. + const val SUBSCRIBE = "subscribe" + const val UNSUBSCRIBE = "unsubscribe" + const val RUN_EVENT = "run_event" + // status.go const val GET_STATUS = "get_status" const val STATUS = "status" @@ -352,6 +357,49 @@ data class RunDetail( val steps: List = emptyList(), ) +/** + * The server-pushed `run_event` delta (internal/protocol/runevents.go + * RunEventFrame). It carries only the values that changed, never the whole run: + * the run's identity, status, outcome, current stage, completed-step count and + * timestamps, plus at most one changed step. Every field is optional so a client + * folds the frame into its cached run rather than replacing it. + */ +@Serializable +data class RunEventFrame( + @SerialName("run_id") val runId: Long = 0, + val workspace: String = "", + val status: String = "", + val outcome: String = "", + @SerialName("current_stage") val currentStage: String = "", + @SerialName("completed_steps") val completedSteps: Int = 0, + @SerialName("created_at") val createdAt: String = "", + @SerialName("finished_at") val finishedAt: String = "", + // Protocol-mirror field (runevents.go `artifacts`): carried for wire parity, + // not read by the fold. Artifact capture surfaces through the full `get_run` + // the fold requests for a settled step, not from this count. + val artifacts: Int = 0, + val step: RunStepDelta? = null, +) + +/** + * The compact change of one step within a [RunEventFrame] + * (internal/protocol/runevents.go RunStepDelta): a delta, not a RunStep, so it + * omits the input/output, transcript, file changes and artifact list a full step + * carries. + */ +@Serializable +data class RunStepDelta( + val sequence: Int = 0, + val stage: String = "", + val status: String = "", + val outcome: String = "", + val target: String = "", + val diagnostic: String = "", + // Protocol-mirror field, like RunEventFrame.artifacts: mirrored for wire + // parity and not read by the fold. + val artifacts: Int = 0, +) + @Serializable data class RunCounts( val total: Int = 0, @@ -565,6 +613,10 @@ data class Message( @SerialName("run_id") val runId: Long = 0, @SerialName("run_detail") val runDetail: RunDetail? = null, val runs: List? = null, + // The workspace-scoped run-state push subscription: `run_ids` is the optional + // subscribe scope and `run_event` the server-pushed delta (runevents.go). + @SerialName("run_ids") val runIds: List? = null, + @SerialName("run_event") val runEvent: RunEventFrame? = null, val search: SearchRequest? = null, @SerialName("search_results") val searchResults: SearchResponse? = null, val input: Map? = null, diff --git a/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt b/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt index 89a5892e..886d99e3 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt @@ -134,6 +134,25 @@ class PipelinesClient( } } + /** + * Sends one request and returns its generated id without awaiting a matching + * reply. For a command whose reply is optional (the run-event `subscribe` ack) + * or whose effect is observed through the push stream instead, so a server + * that never acks cannot hold the send lock for the whole request timeout. The + * command still carries a stable id, so any reply lands on [events] and can be + * matched there. + */ + suspend fun sendOnly(request: Message): String = withContext(ioDispatcher) { + sendLock.withLock { + val socket = webSocket ?: throw NotConnectedException() + if (_state.value !is ConnectionState.Connected) throw NotConnectedException() + val id = "android-" + sequence.incrementAndGet() + val payload = json.encodeToString(Message.serializer(), request.copy(id = id)) + if (!socket.send(payload)) throw IOException("websocket send failed") + id + } + } + /** * Fetches raw bytes for a resolved artifact url over the existing OkHttp * client on the IO dispatcher. Used for image previews; never part of the diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index d5662ce5..95c97523 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -11,6 +11,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch @@ -27,6 +29,7 @@ import net.awan.pipelines.data.protocol.PipelineDetail import net.awan.pipelines.data.protocol.PipelineSummary import net.awan.pipelines.data.protocol.Protocol import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.RunEventFrame import net.awan.pipelines.data.protocol.SearchResponse import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.protocol.Template @@ -102,6 +105,14 @@ class AppViewModel( private val _evidence = MutableStateFlow(LoadState>()) val evidence: StateFlow>> = _evidence.asStateFlow() + /** + * Whether the live run stream is delivering pushes. Shown as the small + * "live"/"reconnecting" badge in the runs list and the run detail so a view + * that has stopped updating is never mistaken for current. + */ + private val _runStream = MutableStateFlow(RunStreamState.Offline) + val runStream: StateFlow = _runStream.asStateFlow() + private val _search = MutableStateFlow(SearchUiState()) /** The omni-search panel state: query, last results, loading and any error. */ @@ -122,6 +133,32 @@ class AppViewModel( private val chatStore = ChatStore() val chat: StateFlow = chatStore.state + // The live run subscription: the workspace currently watched, the job that + // established it, and the coalescing jobs that re-sync on a push. One + // subscription per connection; a reconnect (which clears this watch, not the + // saved workspace) re-subscribes, and every (re)subscribe re-reads the list so + // the gap re-syncs from the server's current state. No timer is involved: + // every refresh here is driven by a push, a (re)connect or an operator action. + private var subscribedWorkspace: String? = null + private var subscriptionJob: Job? = null + // The id of the last subscribe we sent, so its optional ack or error reply + // (which lands on `events`) can be matched. The running server may never ack, + // so a push also confirms the watch. + private var subscriptionId: String? = null + + private var runsResyncJob: Job? = null + private var runsResyncQueued = false + + private var detailSyncJob: Job? = null + // The run whose full detail the active sync must fetch next. Keyed by run id + // and set while a sync is in flight, so opening run B during a sync for run A + // fetches B rather than re-fetching A and dropping B's request. + private var detailSyncRequestedRunId: Long? = null + // Advances on every frame folded into the open run detail. A full fetch that + // started before a newer frame is discarded and retried, so the compact delta + // (which can beat the fetch's own write) never lets the fetch regress the view. + private var detailDeltaCount = 0L + init { // Connect on launch when a server URL is already saved, reusing the shared // client and its bounded backoff (no new client, DI or polling). init runs @@ -133,6 +170,7 @@ class AppViewModel( reconnect() } observeChatEvents() + observeRunEvents() observeConnection() } @@ -176,6 +214,247 @@ class AppViewModel( connected = isConnected } } + // The run stream is live only while connected to the right workspace: the + // pair (connected, workspace) drives a single subscribe. A reconnect drops + // the socket, so the pair emits (false, workspace) — which clears the watch + // — then (true, workspace), which re-subscribes; a subscribe re-reads the + // list first so the gap is re-synced before any later delta applies. + viewModelScope.launch { + combine(connectionState, settings.workspace) { state, workspace -> + (state is ConnectionState.Connected) to workspace + } + .distinctUntilChanged() + .collect { (live, workspace) -> + if (live && workspace.isNotBlank()) subscribeRuns(workspace) else streamDown() + } + } + } + + /** + * Routes the server-pushed run frames into the local run state. The frames + * arrive with no request id: the subscribe snapshot first (one frame per run + * in the workspace), then a compact delta per transition. + */ + private fun observeRunEvents() { + viewModelScope.launch { + repository.events.collect { message -> + val frame = message.runEvent + if (frame != null) { + // A push only reaches us as a subscriber: it confirms the watch + // even when the server never sends its subscribe ack. + confirmStreamLive() + applyRunEvent(frame) + } + // A server that does ack, or refuses, answers with our subscribe id. + if (message.id != null && message.id == subscriptionId) { + when (message.type) { + Protocol.SUBSCRIBE -> confirmStreamLive() + Protocol.ERROR -> { + subscribedWorkspace = null + subscriptionId = null + _runStream.value = RunStreamState.Offline + } + } + } + } + } + } + + /** A subscription ack, a push, or a successful watch read proves the stream is live. */ + private fun confirmStreamLive() { + if (subscribedWorkspace != null) _runStream.value = RunStreamState.Live + } + + /** + * Folds one pushed frame into whatever local state it names: the runs list + * (and so the pipeline rows' last-run line) in place, and the open run detail. + * A frame for a run the list does not hold re-syncs the list once, and a + * settled step or terminal run also fetches the full detail so the heavy + * fields the compact delta omits (artifacts, output) fill in. + */ + private fun applyRunEvent(frame: RunEventFrame) { + val history = _runs.value.data + if (history != null) { + val fold = foldRunEvent(history.runs, frame) + if (fold.needsResync) { + scheduleRunsResync() + } else if (fold.runs !== history.runs) { + _runs.value = _runs.value.copy(data = history.copy(runs = fold.runs), loaded = true) + // 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 such read. + if (frame.step == null && isTerminalRunStatus(frame.status)) { + scheduleRunsResync() + } + } + } + val detail = _runDetail.value.data + if (detail != null && detail.id == frame.runId) { + detailDeltaCount++ + val folded = foldRunEvent(detail, frame) + // A stale or non-applicable frame leaves the detail identical; do not + // emit unchanged state just to recompose the open screen. + if (folded !== detail) { + _runDetail.value = _runDetail.value.copy(data = folded, loaded = true) + } + if (runDetailNeedsFullSync(frame)) scheduleRunDetailSync(frame.runId) + } + } + + /** + * Establishes the one watch over [workspace]. A workspace switch drops the + * previous watch first (the server caps subscriptions per connection), and + * the watch is confirmed live by its ack, its first push or the read that + * follows (see [observeRunEvents]) rather than assumed: if the server cannot + * subscribe, the stream reads as not live instead of silently stale. + */ + private fun subscribeRuns(workspace: String) { + if (subscribedWorkspace == workspace) return + subscriptionJob?.cancel() + _runStream.value = RunStreamState.Connecting + subscriptionJob = viewModelScope.launch { + try { + // Drop any previous watch so a workspace switch never stacks + // subscriptions (the server caps them per connection). A failed + // drop must not stop the new subscribe, but it is not swallowed: + // the badge stays not-live until a push confirms the new watch. + try { + repository.unsubscribeRuns() + } catch (t: Throwable) { + if (t is CancellationException) throw t + markStreamDegraded() + } + // Mark the watch before sending so a push that races the send is + // still attributed to this subscription. + subscribedWorkspace = workspace + subscriptionId = repository.subscribeRuns(workspace) + // The server's subscribe snapshot is not guaranteed complete (the + // running server's can be partial), so take an authoritative read + // of the watched state once per (re)connect; later pushes then fold + // on top of the server's current state. + resyncWatchedState() + } catch (t: Throwable) { + if (t is CancellationException) throw t + subscribedWorkspace = null + subscriptionId = null + _runStream.value = RunStreamState.Offline + } + } + } + + /** + * Re-reads the watched workspace's list and, when a run is open, its detail, + * once on every (re)subscribe. The pushes that follow fold on top, so the view + * never depends on the server's subscribe snapshot being complete. + */ + private fun resyncWatchedState() { + scheduleRunsResync() + _runDetail.value.data?.let { scheduleRunDetailSync(it.id) } + } + + /** Nothing is watched: reflect the connection's own state in the live badge. */ + private fun streamDown() { + subscribedWorkspace = null + subscriptionId = null + subscriptionJob?.cancel() + subscriptionJob = null + _runStream.value = when (repository.connectionState.value) { + is ConnectionState.Connecting, is ConnectionState.Disconnected -> RunStreamState.Connecting + else -> RunStreamState.Offline + } + } + + /** + * 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, and loops when a frame arrived while the read was + * in flight, so no push is ever dropped. A failed read is surfaced — the badge + * stops claiming live — and retried with a bounded backoff before giving up. + */ + private fun scheduleRunsResync() { + if (runsResyncJob?.isActive == true) { + runsResyncQueued = true + return + } + runsResyncJob = viewModelScope.launch { + var attempt = 0 + do { + runsResyncQueued = false + try { + _runs.value = _runs.value.copy(data = repository.listRuns(), loaded = true) + // A read that succeeds over the connected socket is a live + // round-trip: it recovers the badge after a transient failure. + confirmStreamLive() + attempt = 0 + } catch (t: Throwable) { + if (t is CancellationException) throw t + // The push that asked for this read already saw the stream + // live, so a failed read must not leave "live" over a list that + // did not update; retry a bounded number of times, then stay + // not-live until a later push or read confirms it. + markStreamDegraded() + if (++attempt > RESYNC_RETRY_LIMIT) return@launch + delay(RESYNC_RETRY_BASE_MILLIS * attempt) + runsResyncQueued = true + } + } while (runsResyncQueued) + } + } + + /** + * 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. + */ + private fun scheduleRunDetailSync(runId: Long) { + if (detailSyncJob?.isActive == true) { + detailSyncRequestedRunId = runId + return + } + detailSyncJob = viewModelScope.launch { + var target = runId + var attempt = 0 + while (true) { + detailSyncRequestedRunId = null + val deltaCount = detailDeltaCount + try { + val run = repository.getRun(target) + attempt = 0 + if (_runDetail.value.data?.id == target) { + if (detailDeltaCount == deltaCount) { + _runDetail.value = LoadState(loading = false, data = run, loaded = true) + } else { + // A newer frame overtook the fetch; re-read rather than + // write the older run over it. + detailSyncRequestedRunId = target + } + } + // else: the operator left this run; its detail is no longer shown. + } catch (t: Throwable) { + if (t is CancellationException) throw t + markStreamDegraded() + if (++attempt > RESYNC_RETRY_LIMIT) return@launch + delay(RESYNC_RETRY_BASE_MILLIS * attempt) + // A run opened meanwhile wins over retrying this one. + if (detailSyncRequestedRunId == null) detailSyncRequestedRunId = target + } + target = detailSyncRequestedRunId ?: return@launch + } + } + } + + /** + * Drops the live badge to not-live after a push-driven read or a watch change + * failed. The operator must not keep seeing "live" over state that stopped + * updating; a later push, ack or successful read confirms it again. + */ + private fun markStreamDegraded() { + if (subscribedWorkspace != null) _runStream.value = RunStreamState.Connecting } fun updateServerUrlDraft(value: String) { @@ -412,8 +691,10 @@ class AppViewModel( } /** - * Loads a run. [silent] is used by the bounded poll while a run is executing - * so the screen does not flash a spinner on every tick. + * Loads a run on demand (opening it, or after a manual cancel/retry). + * [silent] keeps the current content without a loading flash while it is + * re-read. Live pushes are folded separately by [applyRunEvent]; this is not + * a poll. */ fun loadRun(id: Long, silent: Boolean = false) { viewModelScope.launch { @@ -604,6 +885,10 @@ class AppViewModel( companion object { private const val CONNECT_TIMEOUT_MILLIS = 20_000L + /** Bounded backoff retries for a push-driven list/detail read that failed. */ + private const val RESYNC_RETRY_LIMIT = 3 + private const val RESYNC_RETRY_BASE_MILLIS = 500L + /** How long the field waits after the last keystroke before issuing one request. */ const val SEARCH_DEBOUNCE_MILLIS = 250L /** Bounds one history fetch; the server applies its own cap too. */ diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt new file mode 100644 index 00000000..cfd68435 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt @@ -0,0 +1,273 @@ +package net.awan.pipelines.ui + +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.RunEventFrame +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.RunStepDelta +import net.awan.pipelines.data.protocol.RunSummary + +/** + * The pure fold from a server-pushed [RunEventFrame] into the client's cached + * run state. The app never polls: every value on the runs list, the pipeline + * rows' last-run line, the run detail (status, timeline, stages, completed + * count) is advanced here from the pushes. + * + * The fold is deliberately monotonic so an out-of-order or duplicated delta can + * never move a run or a step backwards, and a delta that names a run the list + * does not hold reports [RunListFold.needsResync] rather than inventing a row: + * a brand-new run's summary (name, pipeline id, version) is not in the compact + * delta, so the caller re-reads the server's current list once instead. + */ + +/** Run statuses from which a run never transitions again. */ +internal val TERMINAL_RUN_STATUSES = setOf("succeeded", "failed", "canceled", "interrupted") + +/** The lifecycle rank at which a status is settled: a later status never rewrites it. */ +private const val SETTLED_RANK = 2 + +/** Whether [status] is a settled run status (no further transitions expected). */ +internal fun isTerminalRunStatus(status: String): Boolean = + status.trim().lowercase() in TERMINAL_RUN_STATUSES + +/** + * 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. + */ +internal fun runLifecycleRank(status: String): Int = when (status.trim().lowercase()) { + "queued" -> 0 + "running", "waiting" -> 1 + "succeeded", "failed", "canceled", "interrupted" -> 2 + else -> -1 +} + +/** + * The step lifecycle as an ordinal so a settled visit is never reopened: + * in-flight running/waiting (1) < finished completed/failed/canceled (2). + */ +internal fun stepLifecycleRank(status: String): Int = when (status.trim().lowercase()) { + "running", "waiting" -> 1 + "completed", "failed", "canceled", "interrupted" -> 2 + else -> -1 +} + +/** + * The outcome of folding one frame into the runs list: the list with the matching + * run updated in place (same order, so a read never reshuffles), or + * [needsResync] when the frame names a run the list does not hold. + */ +internal data class RunListFold(val runs: List, val needsResync: Boolean) + +/** Folds one pushed frame into the runs list, in place and without reordering. */ +internal fun foldRunEvent(runs: List, frame: RunEventFrame): RunListFold { + if (frame.runId <= 0) return RunListFold(runs, needsResync = false) + val index = runs.indexOfFirst { it.id == frame.runId } + if (index < 0) return RunListFold(runs, needsResync = true) + val current = runs[index] + val updated = current.applying(frame) + if (updated == current) return RunListFold(runs, needsResync = false) + val next = runs.toMutableList() + next[index] = updated + return RunListFold(next, needsResync = false) +} + +/** + * 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. + */ +internal fun foldRunEvent(detail: RunDetail, frame: RunEventFrame): RunDetail { + if (frame.runId != detail.id) return detail + if (isStaleRunFrame(detail.status, frame.status)) return detail + val merged = detail.fields().applying(frame) + val steps = frame.step?.let { upsertStep(detail.steps, it) } ?: detail.steps + val updated = detail.copy( + status = merged.status, + outcome = merged.outcome, + currentStage = merged.currentStage, + completedSteps = merged.completedSteps, + createdAt = merged.createdAt, + finishedAt = merged.finishedAt, + executing = merged.executing, + steps = steps, + ) + return if (updated == detail) detail else updated +} + +/** + * 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. + */ +internal fun runDetailNeedsFullSync(frame: RunEventFrame): Boolean { + val step = frame.step + val stepSettled = step != null && stepLifecycleRank(step.status) >= 2 + return stepSettled || isTerminalRunStatus(frame.status) +} + +/** + * Advances a run status forward only. A same-or-lower rank never wins, and once + * both words are terminal the settled one is kept, so a late `running` delta + * cannot resurrect a finished run. + */ +private fun advanceRunStatus(current: String, incoming: String): String = + advanceStatus(current, incoming, ::runLifecycleRank) + +/** + * Whether a frame is a stale transition that must be dropped whole: its run + * status is behind the local one, or it is a different terminal word after the + * run already settled. Dropping every field (not just the status) is what keeps + * a late `running` delta from also rewriting the stage or step of a settled run. + */ +private fun isStaleRunFrame(current: String, incoming: String): Boolean = + isStaleTransition(current, incoming, ::runLifecycleRank) + +/** The step counterpart of [isStaleRunFrame]: a settled visit drops a stale delta whole. */ +private fun isStaleStepDelta(current: String, incoming: String): Boolean = + isStaleTransition(current, incoming, ::stepLifecycleRank) + +/** + * 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. + */ +private fun isStaleTransition(current: String, incoming: String, rank: (String) -> Int): Boolean { + if (incoming.isBlank()) return false + val cur = rank(current) + val inc = rank(incoming) + if (cur < 0 || inc < 0) return false + return inc < cur || (cur >= SETTLED_RANK && inc >= SETTLED_RANK && incoming != current) +} + +/** Advances a step status forward only, never reopening a settled visit. */ +private fun advanceStepStatus(current: String, incoming: String): String = + advanceStatus(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. + */ +private fun advanceStatus(current: String, incoming: String, rank: (String) -> Int): String { + if (incoming.isBlank() || incoming == current) return current + val cur = rank(current) + val inc = rank(incoming) + return when { + cur < 0 -> incoming + inc < 0 -> current + inc > cur -> incoming + cur >= SETTLED_RANK -> current + else -> incoming + } +} + +/** The run-state fields a frame advances, shared by the summary row and the detail. */ +private data class RunStateFields( + val status: String, + val outcome: String, + val currentStage: String, + val completedSteps: Int, + val createdAt: String, + val finishedAt: String, + val executing: Boolean, +) { + /** + * The single run-field merge: every value advances forward, so the row and the + * detail can never apply a frame differently. + */ + fun applying(frame: RunEventFrame): RunStateFields { + val status = advanceRunStatus(status, frame.status) + return RunStateFields( + status = status, + outcome = frame.outcome.ifBlank { outcome }, + currentStage = frame.currentStage.ifBlank { currentStage }, + completedSteps = maxOf(completedSteps, frame.completedSteps), + createdAt = frame.createdAt.ifBlank { createdAt }, + finishedAt = frame.finishedAt.ifBlank { finishedAt }, + executing = executingFor(status, executing), + ) + } +} + +private fun RunSummary.fields() = RunStateFields( + status = status, + outcome = outcome, + currentStage = currentStage, + completedSteps = completedSteps, + createdAt = createdAt, + finishedAt = finishedAt, + executing = executing, +) + +private fun RunDetail.fields() = RunStateFields( + status = status, + outcome = outcome, + currentStage = currentStage, + completedSteps = completedSteps, + createdAt = createdAt, + finishedAt = finishedAt, + executing = executing, +) + +/** The client's best knowledge of `executing`: queued/running only; unknown keeps [current]. */ +private fun executingFor(status: String, current: Boolean): Boolean = when (status.trim().lowercase()) { + "queued", "running" -> true + "waiting", "succeeded", "failed", "canceled", "interrupted" -> false + else -> current +} + +private fun RunSummary.applying(frame: RunEventFrame): RunSummary { + if (isStaleRunFrame(status, frame.status)) return this + val current = fields() + val merged = current.applying(frame) + if (merged == current) return this + return copy( + status = merged.status, + outcome = merged.outcome, + currentStage = merged.currentStage, + completedSteps = merged.completedSteps, + createdAt = merged.createdAt, + finishedAt = merged.finishedAt, + executing = merged.executing, + ) +} + +/** + * 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. + */ +private fun upsertStep(steps: List, delta: RunStepDelta): List { + val index = steps.indexOfFirst { it.sequence == delta.sequence } + if (index >= 0) { + val current = steps[index] + val updated = current.applying(delta) + if (updated == current) return steps + val next = steps.toMutableList() + next[index] = updated + return next + } + val added = RunStep( + sequence = delta.sequence, + stage = delta.stage, + status = advanceStepStatus("", delta.status), + outcome = delta.outcome, + target = delta.target, + diagnostic = delta.diagnostic, + ) + val next = steps.toMutableList() + val at = next.indexOfFirst { it.sequence > delta.sequence } + if (at < 0) next.add(added) else next.add(at, added) + return next +} + +private fun RunStep.applying(delta: RunStepDelta): RunStep { + if (isStaleStepDelta(status, delta.status)) return this + return copy( + stage = delta.stage.ifBlank { stage }, + status = advanceStepStatus(status, delta.status), + outcome = delta.outcome.ifBlank { outcome }, + target = delta.target.ifBlank { target }, + diagnostic = delta.diagnostic.ifBlank { diagnostic }, + ) +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunStream.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunStream.kt new file mode 100644 index 00000000..553e5e4a --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunStream.kt @@ -0,0 +1,17 @@ +package net.awan.pipelines.ui + +/** + * Whether the live run stream is delivering pushes, so the runs list and the run + * detail can say so honestly instead of leaving the operator to trust a view that + * may have silently stopped updating. [label] is the short word the badge shows. + */ +enum class RunStreamState(val label: String) { + /** Subscribed and receiving the server's run-state pushes. */ + Live("live"), + + /** Connecting, or re-subscribing after a drop: pushes are paused in the gap. */ + Connecting("reconnecting"), + + /** No connection, or the server refused the subscription. */ + Offline("not live"), +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/LiveBadge.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/LiveBadge.kt new file mode 100644 index 00000000..9963633b --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/LiveBadge.kt @@ -0,0 +1,57 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import net.awan.pipelines.ui.RunStreamState +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * A small, honest statement of whether the live run stream is delivering pushes, + * shown in the runs list and the run detail so the operator can trust what is on + * screen instead of assuming it is current. Colour is never the only signal: the + * accompanying word ("live"/"reconnecting"/"not live") says it too. + * + * Geometry reuses the shared spacing tokens (the dot is one [SPACING_S] square) + * rather than new literals. + */ +@Composable +fun LiveBadge(state: RunStreamState, modifier: Modifier = Modifier) { + val text = pipelinesText() + val color: Color = when (state) { + RunStreamState.Live -> MaterialTheme.colorScheme.primary + RunStreamState.Connecting -> MaterialTheme.colorScheme.tertiary + RunStreamState.Offline -> MaterialTheme.colorScheme.onSurfaceVariant + } + // A live stream gets a solid dot; a paused one a dimmed dot, so the two read + // apart at a glance as well as by the label. + val dotColor = if (state == RunStreamState.Live) color else color.copy(alpha = PAUSED_DOT_ALPHA) + Row( + modifier = modifier, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + Box( + modifier = Modifier + .size(SPACING_S) + .clip(CircleShape) + .background(dotColor), + ) + Text(state.label, style = text.label, color = color) + } +} + +/** How faint the dot is while reconnecting or offline. */ +private const val PAUSED_DOT_ALPHA = 0.4f diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt index 97a566f4..c98f40ca 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt @@ -43,7 +43,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle -import kotlinx.coroutines.delay import kotlinx.serialization.json.JsonElement import java.time.OffsetDateTime import net.awan.pipelines.data.ErrorMessages @@ -60,6 +59,7 @@ import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.DetailTabs import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.KeyValueRow +import net.awan.pipelines.ui.components.LiveBadge import net.awan.pipelines.ui.components.LoadPhase import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity @@ -116,6 +116,7 @@ fun RunDetailScreen( val runsState by vm.runs.collectAsStateWithLifecycle() val evidenceState by vm.evidence.collectAsStateWithLifecycle() val configuredServerUrl by vm.configuredServerUrl.collectAsStateWithLifecycle() + val runStream by vm.runStream.collectAsStateWithLifecycle() var confirmCancel by remember { mutableStateOf(false) } var confirmRetry by remember { mutableStateOf(false) } var actionError by remember { mutableStateOf(null) } @@ -127,7 +128,7 @@ fun RunDetailScreen( LaunchedEffect(runId) { // Scope evidence to this run: drop the previous run's records, then fetch - // this run's evidence once (on demand; never part of the 1s poll). + // this run's evidence once (on demand; live pushes carry no evidence). vm.resetEvidence() vm.loadRun(runId) vm.loadEvidence(runId) @@ -143,15 +144,9 @@ fun RunDetailScreen( // reseeded per run id, so a stale candidate set is never selectable. val shownRun = rememberPaneContent(run) - // Bounded polling: only while the run is executing, stopped on terminal status. - LaunchedEffect(runId, executing) { - if (executing) { - while (true) { - delay(POLL_INTERVAL_MILLIS) - vm.loadRun(runId, silent = true) - } - } - } + // The run updates from the server's pushes (see AppViewModel.applyRunEvent); + // there is no per-second poll. A manual refresh stays in the app bar for when + // it helps, but nothing requires it. // Aggregated once per step-list change; it drives the grid and the // selection's copy/share actions, never recomputed per recomposition. @@ -223,6 +218,7 @@ fun RunDetailScreen( }, windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), actions = { + LiveBadge(runStream, Modifier.padding(end = SPACING_S)) IconButton(onClick = { vm.loadRun(runId) }) { Icon(Icons.Default.Refresh, contentDescription = "Refresh run") } @@ -816,5 +812,3 @@ private fun EvidenceDetails(evidence: SessionEvidence, modifier: Modifier = Modi // is remembered consistently (it is namespaced under the summary tab's saved // state and reseeded by run id). private const val SUMMARY_ARTIFACTS_KEY = "artifacts" - -private const val POLL_INTERVAL_MILLIS = 1_000L diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt index edbc9c02..4cd57055 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt @@ -54,6 +54,7 @@ import net.awan.pipelines.ui.components.FilterCheckItem import net.awan.pipelines.ui.components.FilterMenu import net.awan.pipelines.ui.components.FilterSectionHeader import net.awan.pipelines.ui.components.ListRow +import net.awan.pipelines.ui.components.LiveBadge import net.awan.pipelines.ui.components.LoadPhase import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity @@ -94,6 +95,7 @@ fun RunHistoryScreen( listState: LazyListState, ) { val state by vm.runs.collectAsStateWithLifecycle() + val runStream by vm.runStream.collectAsStateWithLifecycle() val sortKey by vm.runSort.collectAsStateWithLifecycle() val sort = RunSort.fromStorage(sortKey) val statusFilterKey by vm.runFilterStatuses.collectAsStateWithLifecycle() @@ -165,6 +167,7 @@ fun RunHistoryScreen( IconButton(onClick = vm::refreshRuns) { Icon(Icons.Default.Refresh, contentDescription = "Refresh runs") } + LiveBadge(runStream, Modifier.padding(end = SPACING_S)) }, ) }, diff --git a/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt new file mode 100644 index 00000000..560af136 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt @@ -0,0 +1,323 @@ +package net.awan.pipelines.ui + +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.RunEventFrame +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.RunStepDelta +import net.awan.pipelines.data.protocol.RunSummary +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 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. + */ +class RunEventsTest { + + private fun summary( + id: Long, + status: String = "running", + executing: Boolean = true, + currentStage: String = "", + completedSteps: Int = 0, + finishedAt: String = "", + ) = RunSummary( + id = id, + pipelineId = 4, + name = "pipeline", + status = status, + executing = executing, + currentStage = currentStage, + completedSteps = completedSteps, + createdAt = "2026-10-17T09:00:00Z", + finishedAt = finishedAt, + ) + + private fun detail( + id: Long = 1, + status: String = "queued", + executing: Boolean = true, + currentStage: String = "", + completedSteps: Int = 0, + finishedAt: String = "", + steps: List = emptyList(), + ) = RunDetail( + id = id, + pipelineId = 4, + name = "pipeline", + status = status, + executing = executing, + currentStage = currentStage, + completedSteps = completedSteps, + createdAt = "2026-10-17T09:00:00Z", + finishedAt = finishedAt, + steps = steps, + ) + + private fun step( + sequence: Int = 1, + stage: String = "build", + status: String = "running", + outcome: String = "", + target: String = "", + ) = RunStep(sequence = sequence, stage = stage, status = status, outcome = outcome, target = target) + + private fun frame( + runId: Long = 1, + status: String = "", + currentStage: String = "", + outcome: String = "", + completedSteps: Int = 0, + finishedAt: String = "", + step: RunStepDelta? = null, + ) = RunEventFrame( + runId = runId, + workspace = "/work", + status = status, + outcome = outcome, + currentStage = currentStage, + completedSteps = completedSteps, + finishedAt = finishedAt, + step = step, + ) + + // --- runs list -------------------------------------------------------------- + + @Test + fun aDeltaUpdatesAMatchingRowInPlaceWithoutReordering() { + val runs = listOf(summary(3, status = "succeeded", executing = false), summary(1)) + val fold = foldRunEvent( + runs, + frame(runId = 1, status = "running", currentStage = "build", completedSteps = 1), + ) + assertFalse(fold.needsResync) + // Order is untouched; only the matching row advanced. + assertEquals(listOf(3L, 1L), fold.runs.map { it.id }) + val updated = fold.runs.single { it.id == 1L } + assertEquals("running", updated.status) + assertEquals("build", updated.currentStage) + assertEquals(1, updated.completedSteps) + assertTrue(updated.executing) + assertSame("the other row is shared, not copied", runs[0], fold.runs[0]) + } + + @Test + fun aCreatedRunNotInTheListAsksForAResyncInsteadOfInventingARow() { + val runs = listOf(summary(1)) + // A brand-new run's compact delta carries no name/pipeline/version, so the + // list cannot render it and must re-read the server's current state. + val fold = foldRunEvent(runs, frame(runId = 9, status = "queued")) + assertTrue(fold.needsResync) + assertSame(runs, fold.runs) + } + + @Test + fun aDeltaForAnUnknownRunAlsoAsksForAResync() { + val runs = listOf(summary(1, status = "succeeded", executing = false)) + val fold = foldRunEvent(runs, frame(runId = 42, status = "running", currentStage = "x")) + assertTrue(fold.needsResync) + assertEquals(listOf(1L), fold.runs.map { it.id }) + } + + @Test + fun aDuplicateOrOutOfOrderListDeltaNeverRegressesARun() { + val settled = listOf(summary(1, status = "succeeded", executing = false, finishedAt = "2026-10-17T09:05:00Z")) + // A late `running` delta after the terminal one must not resurrect the run. + val fold = foldRunEvent(settled, frame(runId = 1, status = "running", currentStage = "build")) + assertFalse(fold.needsResync) + assertEquals("succeeded", fold.runs[0].status) + assertFalse(fold.runs[0].executing) + assertSame("an unchanged fold keeps the original list", settled, fold.runs) + } + + @Test + fun aTerminalRunDeltaSettlesTheRowAndStopsExecuting() { + val fold = foldRunEvent( + listOf(summary(1, status = "running")), + frame(runId = 1, status = "failed", outcome = "error", finishedAt = "2026-10-17T09:06:00Z"), + ) + val run = fold.runs.single() + assertEquals("failed", run.status) + assertEquals("error", run.outcome) + assertFalse(run.executing) + assertEquals("2026-10-17T09:06:00Z", run.finishedAt) + } + + // --- run detail ------------------------------------------------------------- + + @Test + fun aStepStartedDeltaAddsTheVisitAndRunsTheRun() { + val folded = foldRunEvent( + detail(), + frame(runId = 1, status = "running", currentStage = "build", step = RunStepDelta(sequence = 1, stage = "build", status = "running")), + ) + assertEquals("running", folded.status) + assertTrue(folded.executing) + assertEquals("build", folded.currentStage) + assertEquals(1, folded.steps.size) + assertEquals(1, folded.steps[0].sequence) + assertEquals("running", folded.steps[0].status) + } + + @Test + fun aStepFinishedDeltaSettlesTheVisitAndCountsIt() { + val started = detail(status = "running", currentStage = "build", steps = listOf(step())) + val folded = foldRunEvent( + started, + frame( + runId = 1, + status = "running", + currentStage = "build", + completedSteps = 1, + step = RunStepDelta(sequence = 1, stage = "build", status = "completed", outcome = "success", target = "#success"), + ), + ) + assertEquals(1, folded.steps.size) + assertEquals("completed", folded.steps[0].status) + assertEquals("success", folded.steps[0].outcome) + assertEquals("#success", folded.steps[0].target) + assertEquals(1, folded.completedSteps) + assertTrue("the run is still going until the terminal frame", folded.executing) + } + + @Test + fun aRunFinishedDeltaSettlesTheRunWithItsTerminalFields() { + val folded = foldRunEvent( + detail(status = "running", executing = true, currentStage = "build"), + frame(runId = 1, status = "succeeded", outcome = "success", finishedAt = "2026-10-17T09:07:00Z", completedSteps = 2), + ) + assertEquals("succeeded", folded.status) + assertEquals("success", folded.outcome) + assertFalse(folded.executing) + assertEquals("2026-10-17T09:07:00Z", folded.finishedAt) + assertEquals(2, folded.completedSteps) + } + + @Test + fun aDuplicateStepDeltaIsIdempotent() { + val started = foldRunEvent( + detail(), + frame(runId = 1, status = "running", step = RunStepDelta(sequence = 1, stage = "build", status = "running")), + ) + val again = foldRunEvent( + started, + frame(runId = 1, status = "running", step = RunStepDelta(sequence = 1, stage = "build", status = "running")), + ) + assertEquals(1, again.steps.size) + assertEquals(started.steps, again.steps) + assertSame("a duplicate changes nothing", started, again) + } + + @Test + fun anOutOfOrderStepDeltaNeverReopensASettledVisit() { + val settled = detail( + status = "running", + steps = listOf(step(status = "completed", outcome = "success", target = "#success")), + ) + val folded = foldRunEvent( + settled, + frame(runId = 1, status = "running", step = RunStepDelta(sequence = 1, stage = "build", status = "running")), + ) + assertEquals("completed", folded.steps[0].status) + assertEquals("success", folded.steps[0].outcome) + assertSame(settled, folded) + } + + @Test + fun aSettledStepKeepsItsWordAgainstAnotherTerminalDelta() { + // The run and step ladders share one rule: once a step settles, a later + // terminal word must not rewrite it (so the two cannot drift apart). + val settled = detail( + status = "running", + steps = listOf(step(status = "completed", outcome = "success", target = "#success")), + ) + val folded = foldRunEvent( + settled, + frame(runId = 1, status = "running", step = RunStepDelta(sequence = 1, stage = "build", status = "failed", outcome = "error")), + ) + assertEquals("completed", folded.steps[0].status) + assertEquals("success", folded.steps[0].outcome) + assertSame(settled, folded) + } + + @Test + fun aLaterVisitIsInsertedInSequenceOrder() { + val started = detail( + status = "running", + steps = listOf(step(sequence = 1, status = "completed", outcome = "success", target = "#success")), + ) + // A delta for a lower sequence that was not seen yet must not jump the queue. + val folded = foldRunEvent( + started, + frame(runId = 1, status = "running", step = RunStepDelta(sequence = 2, stage = "review", status = "running")), + ) + assertEquals(listOf(1, 2), folded.steps.map { it.sequence }) + val lower = foldRunEvent( + folded, + frame(runId = 1, status = "running", step = RunStepDelta(sequence = 0, stage = "plan", status = "running")), + ) + assertEquals(listOf(0, 1, 2), lower.steps.map { it.sequence }) + } + + @Test + fun aFrameForAnotherRunLeavesTheDetailUntouched() { + val mine = detail(id = 1, status = "running") + val folded = foldRunEvent(mine, frame(runId = 2, status = "succeeded")) + assertSame(mine, folded) + } + + // --- resync ----------------------------------------------------------------- + + @Test + fun aReconnectResyncTakesTheServerSnapshotThenIgnoresALateOlderDelta() { + // Left stale before the reconnect: the client thought the run was still + // running with no visits. + val stale = detail(status = "running", currentStage = "build") + // The server's current state arrives first (its snapshot frame order), + // then a later delta that was already superseded by it. + val snapshot = foldRunEvent( + stale, + frame( + runId = 1, + status = "succeeded", + outcome = "success", + completedSteps = 1, + finishedAt = "2026-10-17T09:07:00Z", + step = RunStepDelta(sequence = 1, stage = "build", status = "completed", outcome = "success", target = "#success"), + ), + ) + val after = foldRunEvent(snapshot, frame(runId = 1, status = "running", currentStage = "build")) + + assertEquals("succeeded", after.status) + assertEquals("success", after.outcome) + assertFalse(after.executing) + assertEquals(1, after.completedSteps) + assertEquals(1, after.steps.size) + assertEquals("completed", after.steps[0].status) + } + + // --- sync heuristic --------------------------------------------------------- + + @Test + fun onlySettledVisitsAndTerminalRunsNeedAFullDetailSync() { + assertTrue(runDetailNeedsFullSync(frame(runId = 1, step = RunStepDelta(sequence = 1, status = "completed")))) + assertTrue(runDetailNeedsFullSync(frame(runId = 1, step = RunStepDelta(sequence = 1, status = "failed")))) + assertTrue(runDetailNeedsFullSync(frame(runId = 1, status = "succeeded"))) + assertTrue(runDetailNeedsFullSync(frame(runId = 1, status = "canceled"))) + assertFalse(runDetailNeedsFullSync(frame(runId = 1, status = "running", step = RunStepDelta(sequence = 1, status = "running")))) + assertFalse(runDetailNeedsFullSync(frame(runId = 1, status = "queued"))) + } + + @Test + fun aWaitingHumanStageIsNotExecuting() { + assertFalse(isTerminalRunStatus("waiting")) + val folded = foldRunEvent(listOf(summary(1, status = "running")), frame(runId = 1, status = "waiting", currentStage = "gate")) + assertEquals("waiting", folded.runs[0].status) + assertFalse("a parked human stage shows no spinner", folded.runs[0].executing) + } +} diff --git a/docs/cli.md b/docs/cli.md index f5f8bb95..65dc5aac 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -396,7 +396,8 @@ count and timestamps, and, when a single step changed, that step's sequence, sta status, outcome, target and diagnostic. It is a delta, never the whole run, and rapid changes are coalesced to at most a few frames per second per run. `unsubscribe` or disconnecting stops the frames. This lets a client drop the -once-per-second poll; the TUI and Android app still poll in this release. +once-per-second poll: the Android app consumes these pushes instead, while the +TUI still polls in this release. In the run inspector, `n`/`p` select the next/previous recorded execution visit, including repeated visits in loops, from any pane. Selection stops at the last