Skip to main content

agentmux_srv/server/
agent_wanted_running.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent that starts a turn is wanted running. A stop records `agent:desired = stopped` on the
5//! agent's block (`agent_attach::set_desired`) and leaves its controller registered, so a message that
6//! comes later is taken by that controller, which runs a turn again with no start in between:
7//! nothing set the agent back to `running`, and its pane kept saying "This agent is stopped" over a
8//! turn that was working (`AgentStoppedBanner`). A start through `agent.start`, an open or `jekt_start`
9//! still sets it; this is the same rule for the path that has no start.
10//!
11//! Only a turn that began after the stop counts, judged by the two times and not by whether the turn
12//! is still running when the write happens (a short turn is over by then). A turn that was already
13//! running when the stop was recorded (an agent quitting itself records it first, then closes) began
14//! before it, so it never flips the agent back.
15
16use std::collections::HashMap;
17use std::sync::Arc;
18
19use serde_json::Value;
20
21use crate::backend::eventbus::EventBus;
22use crate::backend::mps::{Broker, MuxEvent, EVENT_AGENT_TURN};
23use crate::backend::obj::Block;
24use crate::backend::storage::store::Store;
25
26use super::app_api::agent_attach::{desired_of, set_running_unless_stopped_since, DESIRED_STOPPED};
27
28/// A turn that has begun: its block, its id and when it started (unix ms).
29type Turn = (String, u64, u64);
30
31/// The turn of an `agentturn` event whose turn is running.
32fn running_turn(event: &str, data: Option<&Value>) -> Option<Turn> {
33    if event != EVENT_AGENT_TURN {
34        return None;
35    }
36    let d = data?;
37    if d.get("end").is_some() || d.get("active").and_then(Value::as_bool) != Some(true) {
38        return None;
39    }
40    Some((d.get("block_id")?.as_str()?.to_string(), d.get("turn_id")?.as_u64()?, d.get("started_at_ms")?.as_u64()?))
41}
42
43/// True the first time `turn_id` is seen for `block_id`; a turn's later publishes, and an older id
44/// arriving late, are not new.
45fn is_new_turn(last: &mut HashMap<String, u64>, block_id: &str, turn_id: u64) -> bool {
46    if last.get(block_id).is_some_and(|seen| *seen >= turn_id) {
47        return false;
48    }
49    last.insert(block_id.to_string(), turn_id);
50    true
51}
52
53/// Record `block_id`'s agent as wanted running when it is recorded as stopped and the turn that began
54/// at `started_at_ms` began after that stop was decided (a `stopped` read from the database, with no
55/// time, is older than any turn of this run). Returns whether it changed. BLOCKING.
56fn wake(mstore: &Store, block_id: &str, started_at_ms: u64) -> bool {
57    let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return false };
58    if desired_of(&block).as_deref() != Some(DESIRED_STOPPED) {
59        return false;
60    }
61    // Not when it was stopped as, or after, this turn began (a quit in the middle of it, a stop that
62    // ended it): decided with the write, so a stop landing in between is kept.
63    let woke = set_running_unless_stopped_since(mstore, block_id, started_at_ms);
64    if woke {
65        tracing::info!(block_id, "a turn started on an agent recorded as stopped: it is wanted running again");
66    }
67    woke
68}
69
70/// Start listening. Called once, from `agent_lifecycle::install`. A change is told to the open
71/// windows (`event_bus`): the write alone reaches SQLite, not a pane showing the banner.
72pub(crate) fn install(broker: Arc<Broker>, mstore: Arc<Store>, event_bus: Arc<EventBus>) {
73    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Turn>();
74    // Observers run inside `Broker::publish`, under its locks: parse and hand off only.
75    broker.add_observer(Arc::new(move |ev: &MuxEvent| {
76        if let Some(turn) = running_turn(&ev.event, ev.data.as_ref()) {
77            let _ = tx.send(turn);
78        }
79    }));
80    tokio::spawn(async move {
81        let mut last = HashMap::new();
82        while let Some((block_id, turn_id, started_at_ms)) = rx.recv().await {
83            if !is_new_turn(&mut last, &block_id, turn_id) {
84                continue;
85            }
86            let (mstore, bus) = (Arc::clone(&mstore), Arc::clone(&event_bus));
87            let _ = tokio::task::spawn_blocking(move || {
88                if wake(&mstore, &block_id, started_at_ms) {
89                    crate::backend::blockcontroller::core::broadcast_block_update(&mstore, &bus, &block_id);
90                }
91            })
92            .await;
93        }
94    });
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use super::super::app_api::agent_attach::{set_desired, stopped_at_ms};
101    use serde_json::json;
102
103    fn block_with(store: &Store, desired: Option<&str>) -> String {
104        let mut block = Block::default();
105        block.oid = uuid::Uuid::new_v4().to_string();
106        if let Some(d) = desired {
107            block.meta.insert("agent:desired".into(), json!(d));
108        }
109        store.insert(&mut block).unwrap();
110        block.oid
111    }
112
113    fn desired(store: &Store, id: &str) -> Option<String> {
114        desired_of(&store.get::<Block>(id).unwrap().unwrap())
115    }
116
117    #[test]
118    fn only_a_running_turn_of_the_turn_event_counts() {
119        let turn = |end: Option<&str>, active: bool| {
120            let mut d = json!({ "block_id": "b1", "turn_id": 7, "started_at_ms": 100, "active": active });
121            if let Some(e) = end {
122                d["end"] = json!(e);
123            }
124            d
125        };
126        assert_eq!(running_turn("agentturn", Some(&turn(None, true))), Some(("b1".into(), 7, 100)));
127        assert_eq!(running_turn("agentturn", Some(&turn(None, false))), None, "between passes");
128        assert_eq!(running_turn("agentturn", Some(&turn(Some("completed"), false))), None, "ended");
129        assert_eq!(running_turn("agentstatus", Some(&turn(None, true))), None, "another event");
130    }
131
132    #[test]
133    fn a_turn_is_new_once_and_an_older_one_arriving_late_is_not() {
134        let mut last = HashMap::new();
135        assert!(is_new_turn(&mut last, "b", 5));
136        assert!(!is_new_turn(&mut last, "b", 5), "the same turn's next publish");
137        assert!(!is_new_turn(&mut last, "b", 4), "an older turn");
138        assert!(is_new_turn(&mut last, "b", 6), "the next turn");
139        assert!(is_new_turn(&mut last, "other", 1), "each block has its own");
140    }
141
142    /// The stopped banner over a working agent: a stop leaves the controller, a message runs a turn
143    /// in it, and the agent is wanted running again. Whether that turn is still running when this
144    /// happens does not matter (a short one is over); only which came first, the stop or the turn.
145    #[test]
146    fn a_turn_that_began_after_the_stop_records_the_agent_as_running() {
147        let store = Store::open_in_memory().unwrap();
148
149        let stopped = block_with(&store, Some("running"));
150        set_desired(&store, &stopped, DESIRED_STOPPED);
151        let at = stopped_at_ms(&stopped).unwrap();
152        assert!(wake(&store, &stopped, at + 1), "a turn began after the stop");
153        assert_eq!(desired(&store, &stopped).as_deref(), Some("running"));
154        assert!(stopped_at_ms(&stopped).is_none(), "the stop is no longer in force");
155
156        let quit_mid_turn = block_with(&store, Some("running"));
157        set_desired(&store, &quit_mid_turn, DESIRED_STOPPED);
158        let at = stopped_at_ms(&quit_mid_turn).unwrap();
159        assert!(!wake(&store, &quit_mid_turn, at.saturating_sub(5_000)), "the turn began before the stop was decided");
160        assert!(!wake(&store, &quit_mid_turn, at), "or as it was");
161        assert_eq!(desired(&store, &quit_mid_turn).as_deref(), Some("stopped"));
162
163        let stale = block_with(&store, Some("stopped"));
164        assert!(wake(&store, &stale, 1), "a stopped read from the database is older than any turn of this run");
165        assert_eq!(desired(&store, &stale).as_deref(), Some("running"));
166
167        let running = block_with(&store, Some("running"));
168        assert!(!wake(&store, &running, u64::MAX), "already wanted running");
169        assert!(!wake(&store, &block_with(&store, None), u64::MAX), "nothing recorded");
170    }
171}