agentmux_srv_core/backend/blockcontroller/persistent/status.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runtime status: the `BlockControllerRuntimeStatus` snapshot, its publication
5//! to the frontend, the status heartbeat, and turn-activity marking.
6
7use super::*;
8
9impl PersistentSubprocessController {
10 pub(super) fn set_status(inner: &mut PersistentInner, status: &str) {
11 inner.proc_status = status.to_string();
12 inner.status_version += 1;
13 // The argv belongs to a live process; once it is gone there is nothing
14 // to compare a selection against.
15 if status != STATUS_RUNNING {
16 inner.spawn_runtime = None;
17 inner.effective_runtime = None;
18 }
19 }
20
21 pub(super) fn get_status_snapshot(&self) -> BlockControllerRuntimeStatus {
22 let inner = self.inner.lock().unwrap();
23 super::super::agent_runtime_status(
24 &self.block_id,
25 inner.status_version,
26 &inner.proc_status,
27 inner.proc_exit_code,
28 self.health_monitor.is_active_turn(),
29 )
30 .spawned_at(self.health_monitor.spawned_at_ms())
31 }
32
33 pub(super) fn publish_status(&self) {
34 if let Some(ref broker) = self.broker {
35 let status = self.get_status_snapshot();
36 super::super::publish_controller_status(broker, &status);
37 // Alongside every status change, so the two cannot disagree about
38 // whether a process is running: what it was spawned with, and
39 // whether a restart is already on its way.
40 publish_runtime_event(&self.inner, broker, &self.block_id);
41 }
42 }
43
44 /// Announce only what the process runs (or that none does), without
45 /// repeating the controller status. For the paths that move the status off
46 /// "running" without publishing it themselves (`stop`).
47 pub(super) fn publish_runtime(&self) {
48 if let Some(ref broker) = self.broker {
49 publish_runtime_event(&self.inner, broker, &self.block_id);
50 }
51 }
52
53 /// Periodic (low-frequency) republish of the current controllerstatus
54 /// while a turn is active — a self-healing backstop independent of
55 /// `publish_controller_status`'s `persist: 1` (which only helps a
56 /// reconnecting subscriber) and the frontend's focus-triggered reconcile
57 /// (which only fires on a background→foreground transition). If a single
58 /// live push is missed for some other reason (e.g. a throttled/backgrounded
59 /// renderer coalescing WS messages) while the window stays foregrounded
60 /// and connected the whole time, nothing else corrects it until the turn
61 /// actually ends. This shrinks that window from "forever" to at most one
62 /// heartbeat interval. `HEARTBEAT_SECS` is well below the frontend's own
63 /// `STUCK_THRESHOLD_MS` (45s, diagnostic-only) and `LIVENESS_RECOVERY_MS`
64 /// (180s, force-recovery) so a missed push self-heals long before either
65 /// of those fire. See REPORT_LOGIN_PERSIST_FAILURE_AND_STUCK_WORKING_2026_07_27.md
66 /// §4 item 5. Builds the snapshot with `agent_runtime_status` rather than
67 /// `get_status_snapshot`, since the spawned task only holds cloned `Arc`s,
68 /// not `&self`.
69 ///
70 /// A latent duplicate-loop race is an existing, already-accepted
71 /// contract (reagent P2 on the PR that introduced this function): if a
72 /// turn ends and a new one starts again within one
73 /// `HEARTBEAT_SECS` window, the old loop hasn't yet woken up to observe
74 /// `is_active_turn() == false` and break, so both the old and new loop
75 /// can run concurrently for that window. Harmless — `publish_status`
76 /// republishing the same (or a slightly stale) snapshot twice is
77 /// idempotent from the frontend's point of view — so this is accepted
78 /// rather than fixed, matching the pre-existing pattern.
79 pub(super) fn spawn_status_heartbeat(&self) {
80 const HEARTBEAT_SECS: u64 = 20;
81 self.spawn_status_heartbeat_with_interval(tokio::time::Duration::from_secs(HEARTBEAT_SECS));
82 }
83
84 /// Interval parameterized out of `spawn_status_heartbeat` so a test can
85 /// drive it with a short interval instead of waiting out `HEARTBEAT_SECS`.
86 pub(super) fn spawn_status_heartbeat_with_interval(&self, heartbeat_interval: tokio::time::Duration) {
87 let inner = Arc::clone(&self.inner);
88 let block_id = self.block_id.clone();
89 let broker = self.broker.clone();
90 let health_monitor = Arc::clone(&self.health_monitor);
91 tokio::spawn(async move {
92 let Some(broker) = broker else { return };
93 let mut interval = tokio::time::interval(heartbeat_interval);
94 interval.tick().await; // first tick is immediate; publish_status() already ran at turn start
95 loop {
96 interval.tick().await;
97 let still_active = health_monitor.is_active_turn();
98 let status = {
99 let g = inner.lock().unwrap();
100 super::super::agent_runtime_status(
101 &block_id,
102 g.status_version,
103 &g.proc_status,
104 g.proc_exit_code,
105 still_active,
106 )
107 .spawned_at(health_monitor.spawned_at_ms())
108 };
109 super::super::publish_controller_status(&broker, &status);
110 // Publish the final `turn_active: false` snapshot BEFORE
111 // exiting, not just break silently — reagent P1: this
112 // heartbeat exists specifically to backstop a missed live
113 // turn-end push (the exact stuck-"Working"-forever bug this
114 // PR fixes). Breaking without this last publish meant the
115 // one case it's most needed for — the terminal push being
116 // the one that got dropped — was the one case it didn't
117 // help.
118 if !still_active {
119 break;
120 }
121 }
122 });
123 }
124
125 /// The CLI started a pass by itself and the tracker has marked it active
126 /// (`mark_turn_active_from_cli`): publish the flip and keep the status
127 /// heartbeat going for it, as for a pass srv started.
128 pub(super) fn cli_started_pass(&self) {
129 self.spawn_status_heartbeat();
130 self.publish_status();
131 }
132
133 /// Marks a turn active (re-arming the status heartbeat only if it was
134 /// previously idle) and publishes the resulting status flip. Shared by
135 /// `send_message` and `retry_after_resume_failure` — both represent "a
136 /// user message is about to be delivered," just via different spawn
137 /// paths. The heartbeat is re-armed conditionally: a mid-turn steering
138 /// send already has one running, so re-spawning on every call would
139 /// leak duplicate heartbeat tasks.
140 pub(super) fn mark_turn_active_and_publish(&self) {
141 let was_active = self.health_monitor.mark_turn_active_for_queued();
142 if !was_active {
143 self.spawn_status_heartbeat();
144 }
145 self.publish_status();
146 }
147}
148
149/// Announce what the process runs, from state the caller already holds locked.
150/// `restart_pending` covers both a restart deferred to the end of the turn and
151/// one already committed.
152pub(super) fn announce_runtime(broker: &crate::backend::mps::Broker, block_id: &str, inner: &PersistentInner) {
153 crate::backend::agent_runtime::publish_agent_runtime(
154 broker,
155 block_id,
156 inner.spawn_runtime.as_ref(),
157 inner.restart_when_idle || inner.restart_pending,
158 inner.effective_runtime.as_ref(),
159 );
160}
161
162/// [`announce_runtime`], taking the lock itself. EVERY path that moves the
163/// status off "running" must call one of the two: the menu judges its
164/// selection against the LAST announcement, so a process that ended without
165/// one would go on being judged (ReAgent P1 on #4149).
166pub(super) fn publish_runtime_event(
167 inner: &Mutex<PersistentInner>,
168 broker: &crate::backend::mps::Broker,
169 block_id: &str,
170) {
171 announce_runtime(broker, block_id, &inner.lock().unwrap());
172}
173
174#[cfg(any(test, feature = "test-support"))]
175pub mod lease_hooks;