Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
codex_compact.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `/compact` for a Codex pane.
5//!
6//! A Codex pane runs one `codex exec` per turn, and `exec` can't compact a
7//! thread. `codex app-server` can (`thread/compact/start`), and it reads the
8//! same threads from `$CODEX_HOME`. So a `/compact` sent to a Codex pane (the
9//! composer's Compact button sends exactly that) starts no `exec` turn: srv
10//! runs a short-lived app-server with the turn's own command, environment and
11//! working directory, resumes the thread, compacts it, and stops it.
12//!
13//! The pane sees what it sees for Claude Code: `compaction_started` when it
14//! begins, then a `compact_boundary` frame in the stream (the context-compacted
15//! card, which also ends "Compacting…"), or Claude's compaction-failed notice.
16//!
17//! Verified against codex-cli 0.154.0 on 2026-10-22: a 12,595-token thread
18//! that `codex exec` made came back at 4,706 in about 2 s, and
19//! `codex exec resume` carried on from it, remembering the earlier turn.
20
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::Arc;
23use std::time::{Duration, Instant};
24
25use serde_json::{json, Value};
26
27use crate::backend::blockcontroller::app_server::{AppServerIncoming, AppServerLimits, AppServerProcess};
28use crate::backend::blockcontroller::app_server_protocol::CodexAppServerSession;
29use crate::backend::blockcontroller::{core, STATUS_DONE, STATUS_RUNNING};
30
31use super::{SubprocessController, SubprocessSpawnConfig, SUBPROCESS_OUTPUT_SUBJECT};
32
33const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(20);
34const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
35/// How long compacting may take, from the request: one model call over the thread.
36const COMPACT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
37
38/// Whether this turn is a Codex `/compact`.
39pub(super) fn is_compact_request(config: &SubprocessSpawnConfig) -> bool {
40    config.resume_strategy == "codex-exec" && config.message.trim() == "/compact"
41}
42
43/// The context before and after compacting, in tokens.
44#[derive(Debug, PartialEq)]
45struct Compacted {
46    pre_tokens: u64,
47    post_tokens: u64,
48}
49
50impl SubprocessController {
51    /// Compact the pane's Codex thread instead of running `/compact` as a turn.
52    /// Called from `spawn_turn` holding the run lock, which it keeps until the
53    /// compaction ends, so a message sent meanwhile is queued and sent after.
54    /// Like a turn it holds the session's cross-process lease, and Stop
55    /// (`stop_subprocess`, through `kill_tx`) cancels it.
56    pub(super) fn compact_codex_thread(
57        &self,
58        config: SubprocessSpawnConfig,
59        thread_id: Option<String>,
60    ) -> Result<(), String> {
61        let Some(thread_id) = thread_id.filter(|t| !t.is_empty()) else {
62            self.unlock_run();
63            return Err("Nothing to compact yet: this Codex agent hasn't run a turn.".to_string());
64        };
65        let lease = match self.claim_compact_lease(&config, &thread_id) {
66            Ok(lease) => lease,
67            Err(e) => {
68                self.unlock_run();
69                return Err(e);
70            }
71        };
72        self.emit_message_accepted(&config);
73        // In the transcript like any delivered turn's message, so it is still
74        // there after a reload and in History.
75        self.user_record_sink(config.message_id.is_some(), config.record.clone()).write(&config.message);
76        let (kill_tx, mut kill_rx) = tokio::sync::oneshot::channel::<bool>();
77        {
78            let mut inner = self.inner.lock().unwrap();
79            Self::set_status(&mut inner, STATUS_RUNNING);
80            inner.kill_tx = Some(kill_tx);
81        }
82        self.health_monitor.set_active_turn(true);
83        self.health_monitor.note_spawned();
84        self.publish_status();
85        if let Some(broker) = &self.broker {
86            let started = agentmux_common::client_events::CompactionStarted {
87                trigger: agentmux_common::client_events::CompactionTrigger::Manual,
88                session_id: thread_id.clone(),
89                started_at: chrono::Utc::now().to_rfc3339(),
90            };
91            // Live only, like the PreCompact hook's (`persist: 0`, #2378).
92            broker.publish_event::<crate::backend::mps_events::CompactionStarted>(
93                &started,
94                vec![format!("block:{}", self.block_id)],
95                0,
96            );
97        }
98        let done = Arc::new(AtomicBool::new(false));
99        self.renew_compact_lease(lease.clone(), Arc::clone(&done));
100        let weak = self.self_ref.lock().unwrap().clone().unwrap_or_default();
101        let block_id = self.block_id.clone();
102        tokio::spawn(async move {
103            let started = Instant::now();
104            // Stop sends on `kill_tx`. Dropping `run` then drops its App Server
105            // process, which `kill_on_drop` stops.
106            let outcome = tokio::select! {
107                outcome = run(&block_id, &config, &thread_id) => Some(outcome),
108                Ok(_) = &mut kill_rx => None,
109            };
110            done.store(true, Ordering::SeqCst);
111            if let Some(ctrl) = weak.upgrade() {
112                ctrl.finish_codex_compact(outcome, started.elapsed(), lease);
113            }
114        });
115        Ok(())
116    }
117
118    /// The session lease a turn claims (`host_spawn::spawn_turn`), so a
119    /// compaction never changes a thread another AgentMux process is running a
120    /// turn on. `None` when leasing is off for this pane or its store failed.
121    fn claim_compact_lease(&self, config: &SubprocessSpawnConfig, thread_id: &str) -> Result<Option<crate::registry::Lease>, String> {
122        if config.instance_id.is_empty() {
123            return Ok(None);
124        }
125        let Some(store) = &self.lease_store else { return Ok(None) };
126        match store.claim(&config.instance_id, &self.boot_id, &self.block_id, Some(thread_id)) {
127            Ok(lease) => Ok(Some(lease)),
128            Err(crate::registry::LeaseError::HeldByOther { owner_boot_id, age_ms, .. }) => Err(format!(
129                "session '{}' is already owned by another AgentMux process (boot {owner_boot_id}, renewed {age_ms}ms ago): \
130                 refusing to compact it from two processes at once",
131                config.instance_id
132            )),
133            Err(crate::registry::LeaseError::Io(e)) => {
134                tracing::warn!(block_id = %self.block_id, error = %e, "lease claim failed (io); compacting without a lease");
135                Ok(None)
136            }
137        }
138    }
139
140    /// Renew the lease while the compaction runs, as a turn's renewal task does.
141    fn renew_compact_lease(&self, lease: Option<crate::registry::Lease>, done: Arc<AtomicBool>) {
142        let (Some(store), Some(lease)) = (self.lease_store.clone(), lease) else { return };
143        let block_id = self.block_id.clone();
144        tokio::spawn(async move {
145            let mut interval = tokio::time::interval(Duration::from_millis(crate::registry::RENEW_INTERVAL_MS));
146            loop {
147                interval.tick().await;
148                if done.load(Ordering::SeqCst) {
149                    break;
150                }
151                let (s, l) = (Arc::clone(&store), lease.clone());
152                let renewed = tokio::task::spawn_blocking(move || s.renew(&l).map_err(|e| e.to_string()))
153                    .await
154                    .unwrap_or_else(|e| Err(format!("renew task failed: {e}")));
155                if let Err(e) = renewed {
156                    tracing::warn!(block_id = %block_id, error = %e, "lease renew failed during a codex compact");
157                    break;
158                }
159            }
160        });
161    }
162
163    /// Tell the pane how it went, release the lease and end the "turn". After
164    /// a finished compaction, send what was queued; after Stop (`None`), leave
165    /// the status Stop set and send nothing: the user stopped the agent.
166    fn finish_codex_compact(&self, outcome: Option<Result<Compacted, String>>, took: Duration, lease: Option<crate::registry::Lease>) {
167        let now = chrono::Utc::now().to_rfc3339();
168        let uuid = uuid::Uuid::new_v4().to_string();
169        let frame = match &outcome {
170            Some(Ok(c)) => {
171                tracing::info!(block_id = %self.block_id, pre = c.pre_tokens, post = c.post_tokens, "codex thread compacted");
172                boundary_frame(c, took, &uuid, &now)
173            }
174            Some(Err(error)) => {
175                tracing::warn!(block_id = %self.block_id, error = %error, "codex compact failed");
176                failed_frame(error, &uuid, &now)
177            }
178            None => {
179                // Stopped: what was queued behind the compaction is dropped, or
180                // the next turn's drain would send it after the user stopped.
181                let dropped = std::mem::take(&mut self.inner.lock().unwrap().pending_messages).len();
182                tracing::info!(block_id = %self.block_id, dropped, "codex compact stopped");
183                let note = match dropped {
184                    0 => "stopped before it finished".to_string(),
185                    1 => "stopped before it finished; the message queued behind it was not sent".to_string(),
186                    n => format!("stopped before it finished; the {n} messages queued behind it were not sent"),
187                };
188                failed_frame(&note, &uuid, &now)
189            }
190        };
191        if let Some(broker) = &self.broker {
192            let global_zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
193            crate::backend::blockcontroller::shell::handle_append_block_file(
194                broker,
195                &self.block_id,
196                SUBPROCESS_OUTPUT_SUBJECT,
197                format!("{frame}\n").as_bytes(),
198                self.filestore.as_ref(),
199                global_zone.as_deref(),
200            );
201        }
202        if let (Some(store), Some(lease)) = (&self.lease_store, &lease) {
203            if let Err(e) = crate::backend::blocking::off_async_worker(|| store.release(lease)) {
204                tracing::warn!(block_id = %self.block_id, error = %e, "lease release failed after a codex compact (self-heals via TTL expiry)");
205            }
206        }
207        let Some(outcome) = outcome else {
208            self.health_monitor.set_active_turn(false);
209            self.publish_status();
210            self.unlock_run();
211            return;
212        };
213        let exit_code = if outcome.is_ok() { 0 } else { 1 };
214        {
215            let mut inner = self.inner.lock().unwrap();
216            inner.proc_exit_code = exit_code;
217            inner.kill_tx = None;
218            Self::set_status(&mut inner, STATUS_DONE);
219        }
220        self.health_monitor.set_exited(exit_code);
221        self.health_monitor.set_active_turn(false);
222        self.publish_status();
223        self.unlock_run();
224        let next = self.inner.lock().unwrap().pending_messages.pop_front();
225        if let Some(config) = next {
226            if let Err(e) = self.spawn_turn(config) {
227                tracing::warn!(block_id = %self.block_id, error = %e, "failed to spawn the turn queued behind a compact");
228            }
229        }
230    }
231}
232
233/// Start an app-server like the pane's own turns, compact, and stop it.
234async fn run(block_id: &str, config: &SubprocessSpawnConfig, thread_id: &str) -> Result<Compacted, String> {
235    let mut command = crate::backend::pane_env::make_cli_cmd(&config.cli_command);
236    command.args(["app-server", "--listen", "stdio://"]);
237    core::apply_working_dir(&mut command, block_id, &config.working_dir, &config.env_vars);
238    #[cfg(windows)]
239    {
240        use agentmux_common::win32::NoWindow;
241        command.no_window();
242    }
243    crate::backend::process_tracker::registry::place_spawn(block_id, &mut command, true);
244    let process = AppServerProcess::spawn(command, AppServerLimits::default())
245        .map_err(|e| format!("couldn't start the Codex App Server: {e}"))?;
246    if let Some(pid) = process.pid() {
247        crate::backend::process_tracker::registry::track_spawned_agent(block_id, pid);
248    }
249    let outcome = compact(&process, thread_id, &config.working_dir).await;
250    let _ = process.shutdown(Duration::from_secs(2)).await;
251    outcome
252}
253
254async fn compact(process: &AppServerProcess, thread_id: &str, cwd: &str) -> Result<Compacted, String> {
255    process
256        .transport
257        .initialize(INITIALIZE_TIMEOUT)
258        .await
259        .map_err(|e| format!("the Codex App Server didn't start: {e}"))?;
260    let session = CodexAppServerSession::new(process.transport.clone());
261    session
262        .resume_thread(thread_id.to_string(), None, (!cwd.is_empty()).then(|| cwd.to_string()), REQUEST_TIMEOUT)
263        .await
264        .map_err(|e| format!("couldn't open the thread: {e}"))?;
265    session.compact_thread(REQUEST_TIMEOUT).await.map_err(|e| format!("couldn't start compacting: {e}"))?;
266    let deadline = tokio::time::Instant::now() + COMPACT_TIMEOUT;
267    let mut progress = Progress::default();
268    loop {
269        let incoming = tokio::time::timeout_at(deadline, process.transport.next_incoming())
270            .await
271            .map_err(|_| "compacting took longer than 10 minutes".to_string())?
272            .ok_or_else(|| "the Codex App Server stopped before compacting finished".to_string())?;
273        if let AppServerIncoming::Notification { method, params } = incoming {
274            if let Some(done) = progress.note(&method, &params) {
275                return done;
276            }
277        }
278    }
279}
280
281/// What the app-server's notifications say about one compaction. Their order
282/// (codex-cli 0.154.0): the resume's `thread/tokenUsage/updated` (the context
283/// before), `item/started` of a `contextCompaction`, a token update (the
284/// context after), `item/completed`, then `turn/completed`.
285#[derive(Default)]
286struct Progress {
287    pre: Option<u64>,
288    post: Option<u64>,
289    started: bool,
290    compacted: bool,
291}
292
293impl Progress {
294    fn note(&mut self, method: &str, params: &Value) -> Option<Result<Compacted, String>> {
295        let item_is_compaction = || params.pointer("/item/type").and_then(Value::as_str) == Some("contextCompaction");
296        match method {
297            "thread/tokenUsage/updated" => {
298                let tokens = params.pointer("/tokenUsage/last/totalTokens").and_then(Value::as_u64);
299                if self.started {
300                    self.post = tokens.or(self.post);
301                } else {
302                    self.pre = tokens.or(self.pre);
303                }
304            }
305            "item/started" if item_is_compaction() => self.started = true,
306            "item/completed" if item_is_compaction() => self.compacted = true,
307            "turn/completed" => {
308                let status = params.pointer("/turn/status").and_then(Value::as_str).unwrap_or("");
309                if status != "completed" || !self.compacted {
310                    let why = params
311                        .pointer("/turn/error/message")
312                        .and_then(Value::as_str)
313                        .map(str::to_string)
314                        .unwrap_or_else(|| match status {
315                            "" | "completed" => "compacting ended without compacting".to_string(),
316                            other => format!("compacting was {other}"),
317                        });
318                    return Some(Err(why));
319                }
320                return Some(Ok(Compacted { pre_tokens: self.pre.unwrap_or(0), post_tokens: self.post.unwrap_or(0) }));
321            }
322            _ => {}
323        }
324        None
325    }
326}
327
328/// Claude Code's `compact_boundary` frame, which the pane reads for any
329/// provider (`frontend/app/view/agent/frame-intercepts.ts`).
330fn boundary_frame(c: &Compacted, took: Duration, uuid: &str, now: &str) -> Value {
331    json!({
332        "type": "system",
333        "subtype": "compact_boundary",
334        "uuid": uuid,
335        "timestamp": now,
336        "compact_metadata": {
337            "trigger": "manual",
338            "pre_tokens": c.pre_tokens,
339            "post_tokens": c.post_tokens,
340            "duration_ms": took.as_millis() as u64,
341        },
342    })
343}
344
345/// Claude Code's compaction-failed status frame, naming Codex
346/// (`frontend/app/view/agent/cli-notice.ts`).
347fn failed_frame(error: &str, uuid: &str, now: &str) -> Value {
348    json!({
349        "type": "system",
350        "subtype": "status",
351        "compact_result": "failed",
352        "compact_error": error,
353        "provider": "codex",
354        "uuid": uuid,
355        "timestamp": now,
356    })
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    fn config(strategy: &str, message: &str) -> SubprocessSpawnConfig {
364        SubprocessSpawnConfig { resume_strategy: strategy.into(), message: message.into(), ..Default::default() }
365    }
366
367    #[test]
368    fn only_a_codex_slash_compact_is_caught() {
369        assert!(is_compact_request(&config("codex-exec", "/compact")));
370        assert!(is_compact_request(&config("codex-exec", "  /compact\n")));
371        assert!(!is_compact_request(&config("codex-exec", "/compact the logs please")));
372        assert!(!is_compact_request(&config("flag", "/compact")), "Claude's /compact goes to its CLI");
373    }
374
375    /// The order codex-cli 0.154.0 sent, recorded 2026-10-22.
376    #[test]
377    fn reads_the_context_before_and_after_from_the_notifications() {
378        let mut p = Progress::default();
379        let usage = |n: u64| json!({ "tokenUsage": { "last": { "totalTokens": n } } });
380        let item = |t: &str| json!({ "item": { "type": t } });
381        assert!(p.note("thread/tokenUsage/updated", &usage(12_595)).is_none());
382        assert!(p.note("item/started", &item("contextCompaction")).is_none());
383        assert!(p.note("thread/tokenUsage/updated", &usage(4_706)).is_none());
384        assert!(p.note("item/completed", &item("contextCompaction")).is_none());
385        let done = p.note("turn/completed", &json!({ "turn": { "status": "completed" } }));
386        assert_eq!(done, Some(Ok(Compacted { pre_tokens: 12_595, post_tokens: 4_706 })));
387    }
388
389    #[test]
390    fn a_turn_that_ends_without_compacting_is_a_failure() {
391        let mut p = Progress::default();
392        let failed = p.note("turn/completed", &json!({ "turn": { "status": "failed", "error": { "message": "usage limit reached" } } }));
393        assert_eq!(failed, Some(Err("usage limit reached".to_string())));
394        let mut p = Progress::default();
395        let interrupted = p.note("turn/completed", &json!({ "turn": { "status": "interrupted" } }));
396        assert_eq!(interrupted, Some(Err("compacting was interrupted".to_string())));
397    }
398
399    /// The frames are the ones the pane already parses for Claude Code.
400    #[test]
401    fn the_frames_are_claude_codes_shapes() {
402        let b = boundary_frame(&Compacted { pre_tokens: 10, post_tokens: 4 }, Duration::from_millis(2_157), "u1", "t");
403        assert_eq!(b["subtype"], "compact_boundary");
404        assert_eq!(b["compact_metadata"], json!({ "trigger": "manual", "pre_tokens": 10, "post_tokens": 4, "duration_ms": 2_157 }));
405        let f = failed_frame("boom", "u2", "t");
406        assert_eq!((f["subtype"].as_str(), f["compact_result"].as_str(), f["provider"].as_str()), (Some("status"), Some("failed"), Some("codex")));
407    }
408}