Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
codex_fresh.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents fresh` for a Codex or Gemini pane (`docs/specs/SPEC_AGENT_SELF_COMPACTION_2026_10_23.md` ยง3.3).
5//!
6//! A Codex pane runs one `codex exec` per turn and resumes its thread by id, and a Gemini pane one `gemini -p` per turn
7//! that resumes with `-r <id>` only when there is an id: so ending the thread is forgetting the id, and the next turn
8//! starts a new one.
9//! Three places hold the id, and all three must let go in one step:
10//!
11//! - the controller's `session_id` (cleared here, under `inner`);
12//! - the block's `agent:sessionid` meta (cleared right after; a message built
13//!   from the meta in between, or one already queued behind a turn, can still
14//!   carry the old id, so the id is also *retired*: `hydrate_session_id_from_config`
15//!   refuses it);
16//! - the queue itself: a queued message makes the pane busy, so it refuses.
17//!
18//! The idle test and the clearing are one `inner` acquisition, so a message
19//! either started its turn first (refused; the caller waits and tries again) or
20//! finds no thread to resume. The old thread stays in `$CODEX_HOME` and in
21//! AgentMux's record (`Agents search_history`).
22
23use std::sync::atomic::Ordering;
24
25use super::{SubprocessController, SUBPROCESS_OUTPUT_SUBJECT};
26
27/// Why a fresh session can't start yet; the caller waits and tries again.
28/// `server/app_api/agent_context.rs` retries on this text.
29pub(crate) const TURN_RUNNING: &str = "a turn is running";
30
31impl SubprocessController {
32    /// End the pane's Codex thread so the next message starts a new one, and
33    /// tell the pane (the `fresh` session-outcome frame: its divider, the meter
34    /// reset and the memory fallback follow from it). Only between turns.
35    /// Returns the old thread id.
36    pub fn start_fresh_session(&self) -> Result<Option<String>, &'static str> {
37        let old = {
38            let mut inner = self.inner.lock().unwrap();
39            if self.run_lock.load(Ordering::SeqCst) || !inner.pending_messages.is_empty() || self.health_monitor.is_active_turn() {
40                return Err(TURN_RUNNING);
41            }
42            let old = inner.session_id.take();
43            if let Some(sid) = &old {
44                inner.retired_sessions.push(sid.clone());
45            }
46            old
47        };
48        super::super::core::persist_session_id(&self.block_id, "", &self.mstore, &self.event_bus);
49        if let Some(broker) = &self.broker {
50            let zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
51            super::super::shell::handle_append_block_file(
52                broker,
53                &self.block_id,
54                SUBPROCESS_OUTPUT_SUBJECT,
55                super::super::persistent::outcome_line::fresh_by_choice_line().as_bytes(),
56                self.filestore.as_ref(),
57                zone.as_deref(),
58            );
59        }
60        Ok(old)
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::super::SubprocessSpawnConfig;
67    use super::*;
68    use std::sync::Arc;
69
70    fn controller() -> SubprocessController {
71        let c = SubprocessController::new("tab".into(), "block".into(), None, None, None, None, None, Arc::from("boot"));
72        c.inner.lock().unwrap().session_id = Some("old-thread".into());
73        c
74    }
75
76    #[test]
77    fn an_idle_pane_forgets_its_thread_and_never_resumes_it() {
78        let c = controller();
79        assert_eq!(c.start_fresh_session(), Ok(Some("old-thread".to_string())));
80        assert_eq!(c.session_id(), None);
81        // A message built from the meta before it was cleared still names the old thread.
82        c.hydrate_session_id_from_config(Some("old-thread"));
83        assert_eq!(c.session_id(), None, "the retired thread is not resumed");
84        c.hydrate_session_id_from_config(Some("other-thread"));
85        assert_eq!(c.session_id().as_deref(), Some("other-thread"), "another id still hydrates (a picker reattach)");
86        assert!(SubprocessController::record_captured_session_id_inner(&c.inner, "new-thread"));
87        assert_eq!(c.session_id().as_deref(), Some("new-thread"), "the new thread's own id is captured");
88    }
89
90    #[test]
91    fn a_turn_in_progress_refuses_and_keeps_the_thread() {
92        let c = controller();
93        assert!(c.try_lock_run());
94        assert_eq!(c.start_fresh_session(), Err(TURN_RUNNING));
95        assert_eq!(c.session_id().as_deref(), Some("old-thread"));
96        c.unlock_run();
97        assert!(c.start_fresh_session().is_ok());
98    }
99
100    #[test]
101    fn a_queued_message_refuses_so_it_cannot_resume_the_old_thread_behind_the_stop() {
102        let c = controller();
103        let queued = SubprocessSpawnConfig { session_id: Some("old-thread".into()), message: "hi".into(), ..Default::default() };
104        c.inner.lock().unwrap().pending_messages.push_back(queued);
105        assert_eq!(c.start_fresh_session(), Err(TURN_RUNNING), "the run lock is free but a message is about to run");
106        assert_eq!(c.session_id().as_deref(), Some("old-thread"));
107        c.inner.lock().unwrap().pending_messages.clear();
108        assert!(c.start_fresh_session().is_ok());
109    }
110
111    #[test]
112    fn an_active_turn_refuses() {
113        let c = controller();
114        c.health_monitor.set_active_turn(true);
115        assert_eq!(c.start_fresh_session(), Err(TURN_RUNNING));
116        c.health_monitor.set_active_turn(false);
117        assert!(c.start_fresh_session().is_ok());
118    }
119
120    #[test]
121    fn a_pane_with_no_thread_yet_starts_fresh_with_nothing_to_forget() {
122        let c = SubprocessController::new("tab".into(), "block".into(), None, None, None, None, None, Arc::from("boot"));
123        assert_eq!(c.start_fresh_session(), Ok(None));
124    }
125
126    #[test]
127    fn the_pane_is_told_it_is_a_fresh_session_with_a_handoff_on_its_way() {
128        let frame: serde_json::Value = serde_json::from_str(super::super::super::persistent::outcome_line::fresh_by_choice_line().trim()).unwrap();
129        assert_eq!(frame["subtype"], "agentmux_session_outcome");
130        assert_eq!(frame["outcome"], "fresh");
131        assert_eq!(frame["idle_start"], false);
132        assert_eq!(frame["attempted_sid"], "");
133    }
134}