Skip to main content

agentmux_srv_core/backend/blockcontroller/
app_server_controller.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! First-class controller shell for a Codex App Server process.
5//!
6//! The protocol implementation lives in [`super::app_server`] and
7//! [`super::app_server_protocol`]. This module owns the AgentMux controller
8//! lifecycle: command construction, process/thread startup, turn dispatch,
9//! block output publication, and shutdown. Codex remains opt-in until the
10//! provider registry flips its controller type.
11
12use crate::backend::message_origin::RecordOrigin;
13#[cfg(windows)]
14use agentmux_common::win32::NoWindow;
15use std::collections::VecDeque;
16use std::sync::{Arc, Mutex, Weak};
17use std::time::Duration;
18
19use tokio::process::Command;
20
21use super::app_server::{AppServerExit, AppServerIncoming, AppServerLimits, AppServerProcess};
22use super::app_server_protocol::{
23    CodexAppServerEvent, CodexAppServerProtocolError, CodexAppServerSession, ThreadStartOptions,
24};
25use super::core;
26use super::health::{PassStats, TurnActivityTracker};
27use super::{
28    BlockControllerRuntimeStatus, BlockInputUnion, Controller, STATUS_DONE, STATUS_INIT,
29    STATUS_RUNNING,
30};
31use crate::backend::eventbus::EventBus;
32use crate::backend::storage::filestore::FileStore;
33use crate::backend::storage::store::Store;
34use crate::backend::mps;
35
36const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(10);
37const OPERATION_TIMEOUT: Duration = Duration::from_secs(10);
38
39/// A message waiting for its turn: the words, and the pictures that go with them (paths of files on this machine).
40#[derive(Debug, Clone, PartialEq, Eq)]
41struct QueuedMessage {
42    text: String,
43    images: Vec<String>,
44}
45
46impl From<String> for QueuedMessage {
47    fn from(text: String) -> Self {
48        Self { text, images: Vec::new() }
49    }
50}
51
52struct AppServerInner {
53    proc_status: String,
54    proc_exit_code: i32,
55    status_version: i32,
56    process: Option<Arc<AppServerProcess>>,
57    session: Option<Arc<CodexAppServerSession>>,
58    pending_messages: VecDeque<QueuedMessage>,
59}
60
61/// Controller for one isolated `codex app-server --listen stdio://` child.
62pub struct AppServerController {
63    block_id: String,
64    inner: Arc<Mutex<AppServerInner>>,
65    broker: Option<Arc<mps::Broker>>,
66    event_bus: Option<Arc<EventBus>>,
67    mstore: Option<Arc<Store>>,
68    filestore: Option<Arc<FileStore>>,
69    health_monitor: Arc<TurnActivityTracker>,
70    self_ref: Mutex<Option<Weak<Self>>>,
71}
72
73impl AppServerController {
74    pub fn new(
75        block_id: String,
76        broker: Option<Arc<mps::Broker>>,
77        event_bus: Option<Arc<EventBus>>,
78        mstore: Option<Arc<Store>>,
79        filestore: Option<Arc<FileStore>>,
80    ) -> Self {
81        let broker_for_turns = broker.clone();
82        Self {
83            block_id: block_id.clone(),
84            inner: Arc::new(Mutex::new(AppServerInner {
85                proc_status: STATUS_INIT.to_string(),
86                proc_exit_code: 0,
87                status_version: 0,
88                process: None,
89                session: None,
90                pending_messages: VecDeque::new(),
91            })),
92            broker,
93            event_bus,
94            mstore,
95            filestore,
96            health_monitor: Arc::new(TurnActivityTracker::for_block(block_id, broker_for_turns.as_ref())),
97            self_ref: Mutex::new(None),
98        }
99    }
100
101    pub fn set_self_ref(self: &Arc<Self>) {
102        *self.self_ref.lock().unwrap() = Some(Arc::downgrade(self));
103    }
104
105    fn set_status(&self, status: &str) {
106        // Scoped: `publish_status` -> `get_runtime_status` re-locks `self.inner`.
107        // Holding this guard across that call deadlocks (std::sync::Mutex isn't
108        // reentrant) — masked in the existing unit tests because they all
109        // construct the controller with `broker: None`, which short-circuits
110        // `publish_status` before it ever re-locks. Any real controller (always
111        // built with `Some(broker)`) would hang the instant `start()` calls
112        // `set_status(STATUS_RUNNING)`.
113        {
114            let mut inner = self.inner.lock().unwrap();
115            inner.proc_status = status.to_string();
116            inner.status_version += 1;
117        }
118        self.publish_status();
119    }
120
121    fn publish_status(&self) {
122        if let Some(broker) = &self.broker {
123            super::publish_controller_status(broker, &self.get_runtime_status());
124        }
125    }
126
127    fn command_from_meta(
128        &self,
129        block_meta: &crate::backend::obj::MetaMapType,
130    ) -> Result<Command, String> {
131        let executable = crate::backend::obj::meta_get_string(block_meta, "cmd", "codex");
132        let args = match block_meta.get("cmd:args") {
133            Some(serde_json::Value::Array(values)) => values
134                .iter()
135                .filter_map(|value| value.as_str().map(str::to_string))
136                .collect::<Vec<_>>(),
137            _ => vec![
138                "app-server".to_string(),
139                "--listen".to_string(),
140                "stdio://".to_string(),
141            ],
142        };
143        if args.is_empty() {
144            return Err("App Server command must include app-server arguments".to_string());
145        }
146        let working_dir = crate::backend::obj::meta_get_string(block_meta, "cmd:cwd", "");
147        let mut env_vars = super::cmd_env_of(block_meta);
148        // Identity M4b-2 (spec §6.5.8): carry the block's row UID + token.
149        // Buys no attribution today — no provider maps to App Server, and
150        // codex is not given agentmux-mcp — but keeps the counters true.
151        if let Some(mstore) = &self.mstore {
152            crate::backend::spawn_env::block_identity::carry_block_identity_env(
153                mstore,
154                &self.block_id,
155                &mut env_vars,
156            );
157        }
158        // The workspace the "Your workspace" Operator Config entry points at.
159        crate::backend::spawn_env::block_identity::carry_agent_workdir_env(&mut env_vars, block_meta);
160        crate::backend::spawn_env::workspaces::record_launch_workspace(&self.block_id, &env_vars);
161        crate::backend::gh_guard::apply_gh_guard(&mut env_vars);
162        crate::backend::git_program_settings::apply_for_spawn(&mut env_vars, block_meta);
163        crate::backend::account_login_guard::strip_account_login(&mut env_vars);
164        // Identity M4a: record what this process is actually given.
165        crate::backend::identity_spawn::record_process_spawn(
166            &self.block_id,
167            crate::backend::identity_spawn::SpawnPath::AppServer,
168            &env_vars,
169        );
170        let mut command = crate::backend::pane_env::make_cli_cmd(&executable);
171        command.args(args);
172        core::apply_working_dir(&mut command, &self.block_id, &working_dir, &env_vars);
173        #[cfg(windows)]
174        {
175            command.no_window();
176        }
177        Ok(command)
178    }
179
180    /// `global_zone` is resolved once per process by `spawn_event_loop`, not
181    /// per frame: resolving reads the block from the store, and frames arrive
182    /// many times a second while a turn streams.
183    fn publish_protocol_frame(&self, frame: serde_json::Value, global_zone: Option<&str>) {
184        let line = format!("{}\n", frame);
185        if let Some(broker) = &self.broker {
186            broker.publish_event::<crate::backend::mps_events::AppServerOutput>(&crate::backend::mps_events::ProtocolFrame(frame.clone()), vec![format!("block:{}", self.block_id)], 1);
187        }
188        if let (Some(filestore), Some(broker)) = (&self.filestore, &self.broker) {
189            // Mirrored into the agent's global zone like every other agent's
190            // output (Phase 5a-3c): a pane reads the global zone when the
191            // block has an agentId, so frames written only to the block file
192            // were missing from its history.
193            super::shell::handle_append_block_file(
194                broker,
195                &self.block_id,
196                "output",
197                line.as_bytes(),
198                Some(filestore),
199                global_zone,
200            );
201        }
202    }
203
204    fn spawn_event_loop(
205        &self,
206        process: Arc<AppServerProcess>,
207        session: Arc<CodexAppServerSession>,
208    ) {
209        let weak = self.self_ref.lock().unwrap().clone();
210        // The agent's global transcript zone, resolved once for this process
211        // (as the host and container spawn paths do), not per frame.
212        let global_zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
213        tokio::spawn(async move {
214            // The running turn's figures, for its ledger: summed over its model
215            // calls, reset when a call reports a different turn.
216            let mut turn_usage = CodexTurnUsage::default();
217            while let Some(incoming) = process.transport.next_incoming().await {
218                if let AppServerIncoming::Notification { method, params } = &incoming {
219                    turn_usage.note(method, params);
220                }
221                // KNOWN GAP (ReAgent P1, PR #3215, tracked for a follow-up PR, not
222                // fixed here): frontend/app/view/agent/providers/codex-translator.ts
223                // (selected for outputFormat "codex-json") only understands the
224                // dotted `codex exec --json` event shapes (e.g. `item.completed`) —
225                // it has no branch for either envelope type below, so this frame is
226                // persisted/broadcast but never rendered in the pane. Fixing this is
227                // a frontend rendering-pipeline change (needs its own dev-server
228                // verification per this repo's UI-change policy), not a mechanical
229                // backend patch, so it's deliberately left for a follow-up PR rather
230                // than rushed in alongside this one's already-large fix history.
231                let frame = match &incoming {
232                    AppServerIncoming::Notification { method, params } => {
233                        serde_json::json!({"type":"codex_app_server","method":method,"params":params})
234                    }
235                    AppServerIncoming::Request {
236                        id: _,
237                        method,
238                        params,
239                    } => {
240                        serde_json::json!({"type":"codex_app_server_request","method":method,"params":params})
241                    }
242                };
243                if let Some(controller) = weak.as_ref().and_then(Weak::upgrade) {
244                    controller.health_monitor.note_output();
245                    controller.publish_protocol_frame(frame, global_zone.as_deref());
246                    match incoming {
247                        notification @ AppServerIncoming::Notification { .. } => {
248                            if let Ok(event) = session.apply_incoming(notification) {
249                                if matches!(event, CodexAppServerEvent::TurnCompleted { .. }) {
250                                    controller.health_monitor.end_pass(turn_usage.take());
251                                    controller.set_status(STATUS_RUNNING);
252                                    // Send the next queued message (if any) now that
253                                    // the turn it collided with has finished — one at
254                                    // a time, since only one turn can be active. Any
255                                    // remainder stays queued for the NEXT completion.
256                                    let next_message =
257                                        controller.inner.lock().unwrap().pending_messages.pop_front();
258                                    if let Some(next_message) = next_message {
259                                        controller.spawn_turn(session.clone(), next_message);
260                                    }
261                                }
262                            }
263                        }
264                        request @ AppServerIncoming::Request { .. } => {
265                            if let Err(error) = session.accept_server_request(request) {
266                                tracing::warn!(block_id = %controller.block_id, error = %error, "Codex App Server request rejected");
267                            }
268                        }
269                    }
270                }
271            }
272            // The transport closed (EOF/crash/shutdown). Reap the child for its
273            // real exit status instead of hardcoding one, and clear the process/
274            // session so a subsequent `start()` (resync) doesn't see a stale
275            // `process.is_some()` and wrongly no-op on a controller that is, from
276            // here on, actually done.
277            let exit_code = match process.wait_for_exit().await {
278                Ok(AppServerExit::Clean { code, .. })
279                | Ok(AppServerExit::BeforeInitialize { code, .. })
280                | Ok(AppServerExit::NonZero { code, .. }) => code.unwrap_or(1),
281                _ => 1,
282            };
283            if let Some(controller) = weak.as_ref().and_then(Weak::upgrade) {
284                // Only report/clear state for OUR OWN process. stop_process()
285                // (from stop() or a signal-triggered kill) synchronously takes
286                // inner.process out and can be followed by a resync's start()
287                // installing a brand-new one, all before this event loop's own
288                // process notices EOF (which can take up to the shutdown grace
289                // period). Without this check, that stale EOF firing here would
290                // wipe out the new, live process/session and stamp STATUS_DONE
291                // with the OLD process's exit code over an actually-running
292                // block (ReAgent P0, PR #3215).
293                let mut inner = controller.inner.lock().unwrap();
294                let is_still_ours = inner
295                    .process
296                    .as_ref()
297                    .is_some_and(|current| Arc::ptr_eq(current, &process));
298                if is_still_ours {
299                    inner.process = None;
300                    inner.session = None;
301                    inner.proc_exit_code = exit_code;
302                    drop(inner);
303                    controller.health_monitor.set_exited(exit_code);
304                    controller.set_status(STATUS_DONE);
305                }
306            }
307        });
308    }
309
310    fn spawn_turn(&self, session: Arc<CodexAppServerSession>, message: QueuedMessage) {
311        let health = self.health_monitor.clone();
312        let weak = self.self_ref.lock().unwrap().clone();
313        health.set_active_turn(true);
314        self.set_status(STATUS_RUNNING);
315        // Kept alongside `message` (which `start_turn` consumes) so a
316        // `TurnAlreadyActive` rejection can be requeued instead of lost.
317        let requeue_message = message.clone();
318        tokio::spawn(async move {
319            if let Err(error) = session.start_turn(message.text, message.images, OPERATION_TIMEOUT).await {
320                // `TurnAlreadyActive` means a DIFFERENT turn is still running —
321                // this attempt (queued via `send_message`, which already returned
322                // `Ok` to its caller) was rejected, but the original turn and the
323                // process behind it are still very much alive. Treating that the
324                // same as a real failure marked a live controller STATUS_DONE and
325                // health inactive out from under its own running turn.
326                let turn_already_active =
327                    matches!(error, CodexAppServerProtocolError::TurnAlreadyActive(_));
328                if !turn_already_active {
329                    health.set_active_turn(false);
330                }
331                if let Some(controller) = weak.and_then(|weak| Weak::upgrade(&weak)) {
332                    if turn_already_active {
333                        // ReAgent P1 on PR #3215's second review: don't just log and
334                        // drop it — `send_message` already told its caller `Ok`, so
335                        // this is the only chance to actually deliver it. Queue it
336                        // for `spawn_event_loop`'s `TurnCompleted` handler to send
337                        // once the turn that's currently active finishes.
338                        controller
339                            .inner
340                            .lock()
341                            .unwrap()
342                            .pending_messages
343                            .push_back(requeue_message);
344                    } else {
345                        controller.set_status(STATUS_DONE);
346                    }
347                    tracing::warn!(
348                        block_id = %controller.block_id,
349                        error = %error,
350                        turn_already_active,
351                        "Codex App Server turn failed to start"
352                    );
353                }
354            }
355        });
356    }
357
358    pub fn send_message(&self, message: String) -> Result<(), String> {
359        self.send_message_from(message, Vec::new(), false, None)
360    }
361
362    /// [`send_message`](Self::send_message), saying where the message came from. The App Server puts
363    /// the user's words in no frame of its own, so srv stores them as a user record with that origin
364    /// (`prompt_record`) once the controller has them; with no `record` nothing is stored. `shown_by_pane`:
365    /// the pane typed it and already shows it.
366    /// `images`: the pictures the message carries, as paths of files on this machine; the App Server's model
367    /// sees each one (`localImage`), besides the numbered path list the words already hold.
368    pub fn send_message_from(&self, message: String, images: Vec<String>, shown_by_pane: bool, record: Option<&RecordOrigin>) -> Result<(), String> {
369        let words = record.map(|_| message.clone());
370        self.queue_or_start_turn(QueuedMessage { text: message, images })?;
371        if let Some(words) = words {
372            let records = super::prompt_record::PromptRecords { broker: self.broker.clone(), filestore: self.filestore.clone(), mstore: self.mstore.clone() };
373            records.write(&self.block_id, &words, shown_by_pane, record);
374        }
375        Ok(())
376    }
377
378    fn queue_or_start_turn(&self, message: QueuedMessage) -> Result<(), String> {
379        let session = {
380            let mut inner = self.inner.lock().unwrap();
381            match inner.session.clone() {
382                Some(session) => Some(session),
383                None if inner.process.is_some() => {
384                    inner.pending_messages.push_back(message.clone());
385                    None
386                }
387                None => return Err("Codex App Server is not initialized".to_string()),
388            }
389        };
390        if let Some(session) = session {
391            self.spawn_turn(session, message);
392        }
393        Ok(())
394    }
395
396    /// Clear a dead process/session so a later `start()` (resync) doesn't see
397    /// its own stale `process.is_some()` guard and wrongly no-op instead of
398    /// respawning. ReAgent P1 on PR #3215's third review: `start()`'s own
399    /// initialize/thread-setup failure branches set STATUS_DONE and shut the
400    /// process down without this, unlike the analogous EOF path in
401    /// `spawn_event_loop` — a handshake failure permanently bricked the block
402    /// with no recovery short of replacing the controller entirely.
403    fn clear_process_and_session(&self) {
404        let mut inner = self.inner.lock().unwrap();
405        inner.process = None;
406        inner.session = None;
407    }
408
409    fn stop_process(&self) {
410        // Cleared SYNCHRONOUSLY, before the async shutdown even starts —
411        // not after it completes. ReAgent P1, PR 3215 (3rd review): stop()
412        // sets the caller's new_status synchronously right after calling
413        // this, but the old version only cleared inner.process/session
414        // inside the spawned task, after up to the 2s shutdown grace
415        // period. A resync_controller call landing in that window saw the
416        // new terminal status, called start(), but start()'s
417        // process.is_some() guard was still true from the stale handle —
418        // silently no-op'd instead of respawning. Taking the process out
419        // of `inner` here (not just cloning it) means start()'s guard sees
420        // the truth immediately; the actual OS-level kill still happens in
421        // the background using this locally-owned handle.
422        let process = {
423            let mut inner = self.inner.lock().unwrap();
424            inner.session = None;
425            inner.process.take()
426        };
427        let weak = self.self_ref.lock().unwrap().clone();
428        if let Some(process) = process {
429            tokio::spawn(async move {
430                let exit = process.shutdown(Duration::from_secs(2)).await;
431                let exit_code = match exit {
432                    Ok(AppServerExit::Clean { code, .. })
433                    | Ok(AppServerExit::BeforeInitialize { code, .. })
434                    | Ok(AppServerExit::NonZero { code, .. }) => code.unwrap_or(0),
435                    _ => 0,
436                };
437                if let Some(controller) = weak.and_then(|weak| Weak::upgrade(&weak)) {
438                    controller.health_monitor.set_exited(exit_code);
439                    controller.inner.lock().unwrap().proc_exit_code = exit_code;
440                }
441            });
442        }
443    }
444}
445
446impl Controller for AppServerController {
447    fn start(
448        &self,
449        block_meta: crate::backend::obj::MetaMapType,
450        _rt_opts: Option<serde_json::Value>,
451        _force: bool,
452    ) -> Result<(), String> {
453        if self.inner.lock().unwrap().process.is_some() {
454            return Ok(());
455        }
456        crate::backend::mcp_folder_rule::not_refused(&block_meta)?;
457        let mut command = self.command_from_meta(&block_meta)?;
458        crate::backend::process_tracker::registry::place_spawn(&self.block_id, &mut command, true);
459        let process = Arc::new(
460            AppServerProcess::spawn(command, AppServerLimits::default())
461                .map_err(|error| error.to_string())?,
462        );
463        if let Some(pid) = process.pid() {
464            crate::backend::process_tracker::registry::track_spawned_agent(&self.block_id, pid);
465        }
466        let process_for_task = process.clone();
467        let weak = self.self_ref.lock().unwrap().clone();
468        self.inner.lock().unwrap().process = Some(process.clone());
469        self.health_monitor.note_spawned();
470        self.set_status(STATUS_RUNNING);
471        tokio::spawn(async move {
472            let Some(controller) = weak.and_then(|weak| Weak::upgrade(&weak)) else {
473                return;
474            };
475            if let Err(error) = process_for_task
476                .transport
477                .initialize(INITIALIZE_TIMEOUT)
478                .await
479            {
480                tracing::warn!(block_id = %controller.block_id, error = %error, "Codex App Server initialize failed");
481                controller.set_status(STATUS_DONE);
482                controller.clear_process_and_session();
483                let _ = process_for_task.shutdown(Duration::from_secs(1)).await;
484                return;
485            }
486            let transport = process_for_task.transport.clone();
487            let session = Arc::new(CodexAppServerSession::new(transport));
488            let cwd = crate::backend::obj::meta_get_string(&block_meta, "cmd:cwd", "");
489            let model = crate::backend::obj::meta_get_string(&block_meta, "agent:model", "");
490            let stored_thread =
491                crate::backend::obj::meta_get_string(&block_meta, "agent:sessionid", "");
492            let thread = if stored_thread.is_empty() {
493                session
494                    .start_thread(
495                        ThreadStartOptions {
496                            model: (!model.is_empty()).then_some(model),
497                            cwd: (!cwd.is_empty()).then_some(cwd),
498                            ..Default::default()
499                        },
500                        OPERATION_TIMEOUT,
501                    )
502                    .await
503            } else {
504                session
505                    .resume_thread(
506                        stored_thread,
507                        (!model.is_empty()).then_some(model),
508                        (!cwd.is_empty()).then_some(cwd),
509                        OPERATION_TIMEOUT,
510                    )
511                    .await
512            };
513            let thread_id = match thread {
514                Ok(thread_id) => thread_id,
515                Err(error) => {
516                    tracing::warn!(block_id = %controller.block_id, error = %error, "Codex App Server thread setup failed");
517                    controller.set_status(STATUS_DONE);
518                    controller.clear_process_and_session();
519                    let _ = process_for_task.shutdown(Duration::from_secs(1)).await;
520                    return;
521                }
522            };
523            if let (Some(store), Some(event_bus)) = (&controller.mstore, &controller.event_bus) {
524                core::persist_session_id(
525                    &controller.block_id,
526                    &thread_id,
527                    &Some(store.clone()),
528                    &Some(event_bus.clone()),
529                );
530            }
531            controller.inner.lock().unwrap().session = Some(session.clone());
532            controller.set_status(STATUS_RUNNING);
533            // Only one turn can be active at a time — start just the first
534            // queued message now; the rest stay queued and are sent one at a
535            // time as each turn completes (spawn_event_loop's `TurnCompleted`
536            // handler). Draining and spawning all of them here concurrently
537            // meant every message but the first immediately hit
538            // `TurnAlreadyActive` and was silently lost (ReAgent P1, PR #3215).
539            let first_pending_message = controller.inner.lock().unwrap().pending_messages.pop_front();
540            if let Some(first_pending_message) = first_pending_message {
541                controller.spawn_turn(session.clone(), first_pending_message);
542            }
543            controller.spawn_event_loop(process_for_task, session);
544        });
545        Ok(())
546    }
547
548    fn stop(&self, _graceful: bool, new_status: &str) -> Result<(), String> {
549        self.stop_process();
550        self.set_status(new_status);
551        Ok(())
552    }
553
554    fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
555        let inner = self.inner.lock().unwrap();
556        super::agent_runtime_status(
557            &self.block_id,
558            inner.status_version,
559            &inner.proc_status,
560            inner.proc_exit_code,
561            self.health_monitor.is_active_turn(),
562        )
563        .spawned_at(self.health_monitor.spawned_at_ms())
564    }
565
566    fn send_input(&self, input: BlockInputUnion, _seq: Option<u64>) -> Result<(), String> {
567        if let Some(signal) = input.sig_name.as_deref() {
568            if signal == "SIGINT" || signal == "SIGTERM" {
569                self.stop_process();
570                // ReAgent P1, PR 3215 (3rd review): stop_process() alone
571                // never updates inner.proc_status -- its spawned task only
572                // clears inner.process/session once the kill actually
573                // completes. Without this, get_runtime_status kept
574                // reporting the pre-signal status (e.g. "running") forever
575                // after a signal-triggered kill, since nothing else updates
576                // it for this path (unlike Controller::stop(), which
577                // already sets a caller-provided status synchronously).
578                self.set_status(STATUS_DONE);
579                return Ok(());
580            }
581            return Err(format!("unsupported App Server signal {signal}"));
582        }
583        if let Some(data) = input.input_data {
584            let message =
585                String::from_utf8(data).map_err(|error| format!("input is not UTF-8: {error}"))?;
586            return self.send_message(message);
587        }
588        Ok(())
589    }
590
591    fn turn_tracker(&self) -> Option<Arc<TurnActivityTracker>> {
592        Some(Arc::clone(&self.health_monitor))
593    }
594
595    /// An approval or user-input request the App Server queued and nobody has
596    /// answered yet.
597    fn awaiting_user_reply(&self) -> bool {
598        // Cloned out, so the inner lock isn't held across the session's own.
599        let session = self.inner.lock().unwrap().session.clone();
600        session.is_some_and(|s| !s.pending_server_requests().is_empty())
601    }
602
603    /// The first request the App Server queued for the user, by the item it is about (else its own id), and the
604    /// messages waiting for their turn.
605    fn pending_for_devices(&self) -> super::PendingFacts {
606        use super::app_server::RpcId;
607        use super::app_server_protocol::ServerRequestKind;
608        let (session, queued) = {
609            let inner = self.inner.lock().unwrap();
610            (inner.session.clone(), inner.pending_messages.len())
611        };
612        let open = session.and_then(|s| s.pending_server_requests().into_iter().next()).map(|request| {
613            let id = request.item_id.unwrap_or(match request.id {
614                RpcId::Number(id) | RpcId::String(id) => id,
615                RpcId::Null => String::new(),
616            });
617            let kind = match request.kind {
618                ServerRequestKind::UserInput | ServerRequestKind::McpElicitation => "question",
619                _ => "approval",
620            };
621            super::PendingRequest { id, kind }
622        });
623        super::PendingFacts { open, queued }
624    }
625
626    fn controller_type(&self) -> &str {
627        super::BLOCK_CONTROLLER_APP_SERVER
628    }
629
630    fn block_id(&self) -> &str {
631        &self.block_id
632    }
633
634    fn as_any(&self) -> &dyn std::any::Any {
635        self
636    }
637}
638
639/// A Codex turn's figures for the turn ledger (`PassStats`), from
640/// `thread/tokenUsage/updated`: one per model call, whose `tokenUsage.last`
641/// is that call's usage (`total` is the whole thread's). Codex reports no
642/// cost or API time, so those stay zero.
643#[derive(Default)]
644struct CodexTurnUsage {
645    turn_id: Option<String>,
646    stats: PassStats,
647}
648
649impl CodexTurnUsage {
650    fn note(&mut self, method: &str, params: &serde_json::Value) {
651        if method != "thread/tokenUsage/updated" {
652            return;
653        }
654        let Some(output) = params.pointer("/tokenUsage/last/outputTokens").and_then(|v| v.as_u64()) else {
655            return;
656        };
657        let turn_id = params.get("turnId").and_then(|v| v.as_str()).map(str::to_string);
658        if turn_id != self.turn_id {
659            *self = CodexTurnUsage { turn_id, stats: PassStats::default() };
660        }
661        self.stats.output_tokens += output;
662        self.stats.steps += 1;
663    }
664
665    /// The finished turn's figures, if any call reported usage; starts over.
666    fn take(&mut self) -> Option<PassStats> {
667        let stats = std::mem::take(self).stats;
668        (stats.steps > 0).then_some(stats)
669    }
670}
671
672#[cfg(test)]
673mod tests {
674
675    /// Identity M4b-2 wiring (spec §6.5.8): with a store, the App Server
676    /// command for a row-backed block carries the row's UID + token.
677    #[test]
678    fn an_app_server_command_carries_the_rows_identity() {
679        use crate::backend::storage::agents::test_agent_def;
680        let store = Arc::new(Store::open_in_memory().unwrap());
681        let mut def = test_agent_def("uid-appsrv", "AppSrv", "codex", "agent", 1, "");
682        store.agent_def_insert(&mut def).unwrap();
683        let mut meta = crate::backend::obj::MetaMapType::new();
684        meta.insert("agentId".to_string(), serde_json::json!("uid-appsrv"));
685        let mut block = crate::backend::obj::Block {
686            oid: "block-appsrv".to_string(),
687            parentoref: String::new(),
688            version: 0,
689            runtimeopts: None,
690            stickers: None,
691            meta: meta.clone(),
692            subblockids: None,
693        };
694        store.insert(&mut block).unwrap();
695        let ctrl = AppServerController::new(
696            "block-appsrv".to_string(),
697            None,
698            None,
699            Some(store.clone()),
700            None,
701        );
702        let command = ctrl.command_from_meta(&meta).unwrap();
703        let env: std::collections::HashMap<String, String> = command
704            .as_std()
705            .get_envs()
706            .filter_map(|(k, v)| Some((k.to_str()?.to_string(), v?.to_str()?.to_string())))
707            .collect();
708        assert_eq!(
709            env.get("AGENTMUX_AGENT_UID").map(String::as_str),
710            Some("uid-appsrv")
711        );
712        assert_eq!(
713            env.get("AGENTMUX_AGENT_TOKEN"),
714            store.agent_token_load("uid-appsrv").unwrap().as_ref()
715        );
716    }
717
718    use super::*;
719    use crate::backend::obj::MetaMapType;
720
721    fn controller() -> AppServerController {
722        AppServerController::new(
723            "block-1".to_string(),
724            None,
725            None,
726            None,
727            None,
728        )
729    }
730
731    #[test]
732    fn starts_idle_and_reports_the_app_server_controller_type() {
733        let controller = controller();
734        let status = controller.get_runtime_status();
735        assert_eq!(status.shellprocstatus, STATUS_INIT);
736        assert_eq!(status.blockid, "block-1");
737        assert!(status.is_agent_pane);
738        assert_eq!(
739            controller.controller_type(),
740            super::super::BLOCK_CONTROLLER_APP_SERVER
741        );
742    }
743
744    #[test]
745    fn rejects_empty_app_server_arguments_before_spawning() {
746        let controller = controller();
747        let mut meta = MetaMapType::new();
748        meta.insert("cmd".to_string(), serde_json::json!("codex"));
749        meta.insert("cmd:args".to_string(), serde_json::json!([]));
750        let error = controller.command_from_meta(&meta).unwrap_err();
751        assert!(error.contains("must include app-server arguments"));
752    }
753
754    #[tokio::test]
755    async fn input_requires_a_completed_handshake() {
756        let controller = controller();
757        let error = controller
758            .send_input(BlockInputUnion::data(b"hello".to_vec()), None)
759            .unwrap_err();
760        assert!(error.contains("not initialized"));
761    }
762
763    // ── Regression coverage for ReAgent's PR #3215 review ────────────────────
764    // Four bugs: (1) `spawn_turn`'s error path couldn't tell "a second turn
765    // was rejected because one is already running" from "the process is
766    // actually dead", (2) `spawn_event_loop`'s EOF branch never reaped the
767    // child or cleared stale process/session state, (3) `deliver_agent_message`
768    // had no route to this controller at all (covered in blockcontroller/mod.rs's
769    // own tests), (4) `agent_open.rs`'s cli_args selection never looked at
770    // `provider.app_server` (covered in agent_open.rs's own tests). Plus one
771    // deadlock this investigation found independently: `set_status` re-locks
772    // its own mutex from inside the guard it's still holding, masked in every
773    // pre-existing test here because they all use `broker: None`.
774
775    fn controller_with_broker() -> (Arc<AppServerController>, Arc<mps::Broker>) {
776        let broker = Arc::new(mps::Broker::new());
777        let controller = Arc::new(AppServerController::new(
778            "block-1".to_string(),
779            Some(broker.clone()),
780            None,
781            None,
782            None,
783        ));
784        controller.set_self_ref();
785        (controller, broker)
786    }
787
788    #[test]
789    fn set_status_with_a_broker_does_not_deadlock_locking_its_own_mutex() {
790        let (controller, _broker) = controller_with_broker();
791        let for_thread = controller.clone();
792        let (tx, rx) = std::sync::mpsc::channel();
793        std::thread::spawn(move || {
794            for_thread.stop(false, STATUS_DONE).unwrap();
795            let _ = tx.send(());
796        });
797        rx.recv_timeout(Duration::from_secs(2)).expect(
798            "set_status must not deadlock re-locking its own mutex once a broker is configured \
799             — every production controller has one",
800        );
801        assert_eq!(controller.get_runtime_status().shellprocstatus, STATUS_DONE);
802    }
803
804    fn fake_server_binary() -> &'static std::path::PathBuf {
805        crate::test_support::fake_app_server_binary()
806    }
807
808    fn app_server_meta(mode: &str) -> MetaMapType {
809        let mut meta = MetaMapType::new();
810        meta.insert(
811            "cmd".to_string(),
812            serde_json::json!(fake_server_binary().to_string_lossy()),
813        );
814        meta.insert(
815            "cmd:env".to_string(),
816            serde_json::json!({"AGENTMUX_FAKE_APP_SERVER_MODE": mode}),
817        );
818        meta
819    }
820
821    async fn wait_until(predicate: impl Fn() -> bool, timeout: Duration) -> bool {
822        let deadline = tokio::time::Instant::now() + timeout;
823        loop {
824            if predicate() {
825                return true;
826            }
827            if tokio::time::Instant::now() >= deadline {
828                return false;
829            }
830            tokio::time::sleep(Duration::from_millis(20)).await;
831        }
832    }
833
834    /// The session's own `turn_id`, straight from `CodexAppServerSession`'s
835    /// state — unlike `health_monitor.is_active_turn()` (which flips to
836    /// `true` synchronously in `spawn_turn`, BEFORE the `turn/start` request
837    /// even goes out), this only becomes `Some` once the round-trip actually
838    /// completes. Tests that need to guarantee a SECOND `send_message` hits
839    /// `start_turn`'s local `TurnAlreadyActive` check (rather than racing it
840    /// and sending its own concurrent `turn/start`) must synchronize on this,
841    /// not on `is_active_turn()`.
842    fn session_turn_id(controller: &AppServerController) -> Option<String> {
843        controller
844            .inner
845            .lock()
846            .unwrap()
847            .session
848            .as_ref()
849            .and_then(|session| session.snapshot().turn_id)
850    }
851
852    #[tokio::test]
853    async fn spawn_event_loop_reaps_the_process_and_clears_stale_state_on_exit() {
854        let (controller, _broker) = controller_with_broker();
855        controller
856            .start(app_server_meta("exit-after-thread-start"), None, false)
857            .unwrap();
858
859        let reached_done = wait_until(
860            || controller.get_runtime_status().shellprocstatus == STATUS_DONE,
861            Duration::from_secs(5),
862        )
863        .await;
864        assert!(
865            reached_done,
866            "controller never reached STATUS_DONE after the fake server exited"
867        );
868
869        let status = controller.get_runtime_status();
870        assert_eq!(
871            status.shellprocexitcode, 42,
872            "must report the process's real exit code instead of a hardcoded stale one"
873        );
874        assert!(!status.turn_active);
875
876        let error = controller
877            .send_message("too late".to_string())
878            .unwrap_err();
879        assert!(
880            error.contains("not initialized"),
881            "process/session must be cleared on exit so a post-exit message is rejected \
882             instead of silently accepted by a session bound to a dead transport, got {error:?}",
883        );
884    }
885
886    #[tokio::test]
887    async fn a_second_message_while_a_turn_is_active_does_not_kill_the_controller() {
888        let (controller, _broker) = controller_with_broker();
889        controller
890            .start(app_server_meta("ready-for-turn"), None, false)
891            .unwrap();
892
893        // `start()` only completes the handshake/thread setup — it does not
894        // start a turn on its own. Wait for the session to actually exist
895        // before sending the first message.
896        let session_ready = wait_until(
897            || controller.inner.lock().unwrap().session.is_some(),
898            Duration::from_secs(5),
899        )
900        .await;
901        assert!(session_ready, "controller session was never established");
902
903        controller
904            .send_message("first message".to_string())
905            .unwrap();
906
907        // Wait for the ACTUAL turn/start round-trip to finish (not just
908        // `is_active_turn()`, which flips true before the request is even
909        // sent) so the second message below is guaranteed to hit the local
910        // `TurnAlreadyActive` check instead of racing it.
911        let turn_id_set =
912            wait_until(|| session_turn_id(&controller).is_some(), Duration::from_secs(5)).await;
913        assert!(turn_id_set, "first turn's turn/start round-trip never completed");
914        assert!(controller.health_monitor.is_active_turn());
915        assert_eq!(controller.get_runtime_status().shellprocstatus, STATUS_RUNNING);
916
917        // `start_turn`'s `TurnAlreadyActive` check is local (state.turn_id is
918        // already Some from the first turn) — this never touches the network,
919        // so no fixture response is needed for it to fire.
920        controller
921            .send_message("second message while the first turn is still running".to_string())
922            .unwrap();
923
924        // Give the rejected turn's spawned task a moment to run (and, pre-fix,
925        // wrongly tear down the controller out from under the live first turn).
926        tokio::time::sleep(Duration::from_millis(200)).await;
927
928        assert!(
929            controller.health_monitor.is_active_turn(),
930            "the ORIGINAL turn is still active; a rejected second turn must not clear that"
931        );
932        assert_eq!(
933            controller.get_runtime_status().shellprocstatus,
934            STATUS_RUNNING,
935            "a rejected second turn must not mark a live controller done"
936        );
937        assert_eq!(
938            controller.inner.lock().unwrap().pending_messages.len(),
939            1,
940            "the rejected message must be queued, not dropped (ReAgent P1, PR #3215 2nd review)"
941        );
942
943        // Cleanup: this fixture mode idles forever rather than exiting on its
944        // own, and the event loop task holds its own Arc<AppServerProcess> for
945        // as long as it's reading — `kill_on_drop` never fires without an
946        // explicit stop, which would otherwise leak the child for the rest of
947        // this test binary's run.
948        controller.stop(true, STATUS_DONE).unwrap();
949    }
950
951    /// The watchdog's inputs: the status carries the spawn time (max-runtime
952    /// limit) and each protocol frame stamps the last output (idle limit).
953    #[tokio::test]
954    async fn the_status_carries_the_spawn_time_and_frames_stamp_the_last_output() {
955        let (controller, _broker) = controller_with_broker();
956        assert_eq!(controller.get_runtime_status().spawn_ts_ms, None, "not spawned yet");
957        controller
958            .start(app_server_meta("requeue-after-turn-completes"), None, false)
959            .unwrap();
960        assert!(controller.get_runtime_status().spawn_ts_ms.is_some());
961
962        let session_ready = wait_until(
963            || controller.inner.lock().unwrap().session.is_some(),
964            Duration::from_secs(5),
965        )
966        .await;
967        assert!(session_ready, "controller session was never established");
968        controller.send_message("first message".to_string()).unwrap();
969        // The fixture answers the turn with a `turn/completed` notification.
970        let stamped = wait_until(|| controller.last_output_ms().is_some(), Duration::from_secs(5)).await;
971        assert!(stamped, "a protocol frame never stamped the last output");
972
973        controller.stop(true, STATUS_DONE).unwrap();
974    }
975
976    /// An approval or input request the App Server queued is srv's own record
977    /// that the agent waits for the user: the watchdog never counts it idle.
978    #[tokio::test]
979    async fn a_queued_server_request_awaits_the_user() {
980        let (controller, _broker) = controller_with_broker();
981        assert!(!controller.awaiting_user_reply(), "no session yet");
982        controller
983            .start(app_server_meta("requeue-after-turn-completes"), None, false)
984            .unwrap();
985        let ready = wait_until(|| controller.inner.lock().unwrap().session.is_some(), Duration::from_secs(5)).await;
986        assert!(ready, "controller session was never established");
987        assert!(!controller.awaiting_user_reply());
988        let session = controller.inner.lock().unwrap().session.clone().unwrap();
989        session
990            .accept_server_request(AppServerIncoming::Request {
991                id: super::super::app_server::RpcId::String("elicit-1".to_string()),
992                method: "mcpServer/elicitation/request".to_string(),
993                params: serde_json::json!({}),
994            })
995            .unwrap();
996        assert!(controller.awaiting_user_reply());
997
998        controller.stop(true, STATUS_DONE).unwrap();
999    }
1000
1001    /// End-to-end version of the test above: the queued message must actually
1002    /// get SENT once the turn it collided with completes, not just survive in
1003    /// the queue forever. ReAgent P1 on PR #3215's second review.
1004    #[tokio::test]
1005    async fn a_queued_message_is_sent_once_the_active_turn_completes() {
1006        let (controller, _broker) = controller_with_broker();
1007        controller
1008            .start(app_server_meta("requeue-after-turn-completes"), None, false)
1009            .unwrap();
1010
1011        let session_ready = wait_until(
1012            || controller.inner.lock().unwrap().session.is_some(),
1013            Duration::from_secs(5),
1014        )
1015        .await;
1016        assert!(session_ready, "controller session was never established");
1017
1018        controller
1019            .send_message("first message".to_string())
1020            .unwrap();
1021        let turn_id_set =
1022            wait_until(|| session_turn_id(&controller).is_some(), Duration::from_secs(5)).await;
1023        assert!(turn_id_set, "first turn's turn/start round-trip never completed");
1024
1025        // The fixture waits 300ms after responding to turn/start before
1026        // sending turn/completed specifically so this has time to land while
1027        // state.turn_id is still Some — i.e. the rejection-and-queue path,
1028        // not a normal second turn started after the first already finished.
1029        controller
1030            .send_message("queued while turn 1 is active".to_string())
1031            .unwrap();
1032        let queued = wait_until(
1033            || controller.inner.lock().unwrap().pending_messages.len() == 1,
1034            Duration::from_secs(1),
1035        )
1036        .await;
1037        assert!(queued, "second message was not queued — test is racing the fixture's notification");
1038
1039        // Once turn/completed arrives, the event loop must drain the queue
1040        // and start the second turn — the fixture only responds to a SECOND
1041        // turn/start if the controller actually sends one.
1042        let requeued_message_was_sent = wait_until(
1043            || controller.inner.lock().unwrap().pending_messages.is_empty(),
1044            Duration::from_secs(5),
1045        )
1046        .await;
1047        assert!(
1048            requeued_message_was_sent,
1049            "queued message was never drained after the active turn completed"
1050        );
1051        let second_turn_active = wait_until(
1052            || controller.health_monitor.is_active_turn(),
1053            Duration::from_secs(5),
1054        )
1055        .await;
1056        assert!(
1057            second_turn_active,
1058            "the requeued message's turn never became active — it was drained but never actually sent"
1059        );
1060
1061        controller.stop(true, STATUS_DONE).unwrap();
1062    }
1063
1064    /// ReAgent P1 on PR #3215's third review: a handshake failure (here,
1065    /// the child dying before `initialize` completes) must not permanently
1066    /// brick the block. `start()`'s own guard (`process.is_some()`) means a
1067    /// stale process/session left behind by a failed handshake makes every
1068    /// later resync a silent no-op instead of a real respawn.
1069    #[tokio::test]
1070    async fn a_failed_handshake_clears_state_so_a_later_start_can_actually_respawn() {
1071        let (controller, _broker) = controller_with_broker();
1072        controller
1073            .start(app_server_meta("exit-before-init"), None, false)
1074            .unwrap();
1075
1076        let reached_done = wait_until(
1077            || controller.get_runtime_status().shellprocstatus == STATUS_DONE,
1078            Duration::from_secs(5),
1079        )
1080        .await;
1081        assert!(reached_done, "controller never reached STATUS_DONE after the failed handshake");
1082        assert!(
1083            controller.inner.lock().unwrap().process.is_none(),
1084            "a failed handshake must clear the dead process, not leave start()'s guard permanently tripped"
1085        );
1086        assert!(controller.inner.lock().unwrap().session.is_none());
1087
1088        // If the bug were still present, this would silently no-op (the old
1089        // `process.is_some()` guard still passing) instead of actually
1090        // spawning a new child — and the assertions below would time out.
1091        controller
1092            .start(app_server_meta("ready-for-turn"), None, false)
1093            .unwrap();
1094        let respawned_session_ready = wait_until(
1095            || controller.inner.lock().unwrap().session.is_some(),
1096            Duration::from_secs(5),
1097        )
1098        .await;
1099        assert!(
1100            respawned_session_ready,
1101            "start() after a failed handshake never respawned — the block is permanently bricked"
1102        );
1103
1104        controller.stop(true, STATUS_DONE).unwrap();
1105    }
1106
1107    /// ReAgent P1, PR 3215 (3rd review): stop() sets new_status
1108    /// synchronously, but the process/session used to only get cleared
1109    /// once stop_process()'s spawned shutdown task finished (up to a 2s
1110    /// grace period later). A resync landing in that window saw the new
1111    /// terminal status, called start(), but start()'s process.is_some()
1112    /// guard was still true from the stale handle -- silently no-op'd
1113    /// instead of respawning. This asserts the fix synchronously, with no
1114    /// wait_until/sleep at all: process/session must already be cleared
1115    /// the instant stop() returns, and a start() called immediately after
1116    /// (not once some background task gets around to it) must actually
1117    /// respawn.
1118    #[tokio::test]
1119    async fn stop_clears_process_and_session_synchronously_so_an_immediate_restart_actually_respawns()
1120    {
1121        let (controller, _broker) = controller_with_broker();
1122        controller
1123            .start(app_server_meta("ready-for-turn"), None, false)
1124            .unwrap();
1125        let session_ready = wait_until(
1126            || controller.inner.lock().unwrap().session.is_some(),
1127            Duration::from_secs(5),
1128        )
1129        .await;
1130        assert!(session_ready, "controller session was never established");
1131
1132        controller.stop(true, STATUS_DONE).unwrap();
1133
1134        // No wait_until here on purpose -- this must already be true the
1135        // instant stop() returns, not eventually.
1136        {
1137            let inner = controller.inner.lock().unwrap();
1138            assert!(
1139                inner.process.is_none(),
1140                "stop() must clear the process handle synchronously, not after the async shutdown completes"
1141            );
1142            assert!(inner.session.is_none());
1143        }
1144
1145        // Immediately, not after any delay: a resync landing right after
1146        // stop() must see a clean slate and actually respawn.
1147        controller
1148            .start(app_server_meta("ready-for-turn"), None, false)
1149            .unwrap();
1150        let respawned = wait_until(
1151            || controller.inner.lock().unwrap().session.is_some(),
1152            Duration::from_secs(5),
1153        )
1154        .await;
1155        assert!(
1156            respawned,
1157            "start() called immediately after stop() never respawned -- the stale process.is_some() guard silently no-op'd"
1158        );
1159
1160        controller.stop(true, STATUS_DONE).unwrap();
1161    }
1162
1163    /// ReAgent P2, PR #3215 (re-review): the send_input SIGINT/SIGTERM
1164    /// status-update fix (flagged in three prior review rounds) had no
1165    /// dedicated regression test, unlike every other fix in this file.
1166    /// stop_process() alone only clears inner.process/session once the
1167    /// spawned shutdown task completes; without the explicit
1168    /// set_status(STATUS_DONE) call, get_runtime_status kept reporting the
1169    /// pre-signal status forever after a signal-triggered kill.
1170    #[tokio::test]
1171    async fn send_input_with_a_kill_signal_updates_status_to_done() {
1172        let (controller, _broker) = controller_with_broker();
1173        controller
1174            .start(app_server_meta("ready-for-turn"), None, false)
1175            .unwrap();
1176        let session_ready = wait_until(
1177            || controller.inner.lock().unwrap().session.is_some(),
1178            Duration::from_secs(5),
1179        )
1180        .await;
1181        assert!(session_ready, "controller session was never established");
1182        assert_eq!(controller.get_runtime_status().shellprocstatus, STATUS_RUNNING);
1183
1184        controller
1185            .send_input(BlockInputUnion::signal("SIGTERM"), None)
1186            .unwrap();
1187
1188        assert_eq!(
1189            controller.get_runtime_status().shellprocstatus,
1190            STATUS_DONE,
1191            "a signal-triggered kill must update proc_status the same way stop() does -- \
1192             nothing else updates it for this path"
1193        );
1194    }
1195
1196    /// ReAgent P0, PR #3215 (re-review): spawn_event_loop's EOF/reap branch
1197    /// unconditionally overwrote inner.process/session/proc_exit_code and
1198    /// forced STATUS_DONE, without checking it was still reaping ITS OWN
1199    /// process. stop_process() (from stop()/a signal-triggered kill)
1200    /// synchronously takes inner.process out -- possibly followed by a
1201    /// resync's start() installing a brand-new one -- well before the OLD
1202    /// event loop notices its own process's EOF, which can take up to the
1203    /// shutdown grace period. When that stale EOF finally fired, it wiped
1204    /// out the new, live process/session and stamped STATUS_DONE with the
1205    /// OLD exit code over an actually-running block.
1206    #[tokio::test]
1207    async fn a_stale_event_loop_does_not_clobber_a_respawned_process() {
1208        let (controller, _broker) = controller_with_broker();
1209        controller
1210            .start(app_server_meta("ready-for-turn"), None, false)
1211            .unwrap();
1212        let session_ready = wait_until(
1213            || controller.inner.lock().unwrap().session.is_some(),
1214            Duration::from_secs(5),
1215        )
1216        .await;
1217        assert!(session_ready, "controller session was never established");
1218        let old_process = controller.inner.lock().unwrap().process.clone().unwrap();
1219
1220        // Simulates stop()/a signal-triggered kill: takes inner.process out
1221        // synchronously and starts the real (2s-timeout) shutdown in the
1222        // background -- exactly what stop_process() does.
1223        controller.stop_process();
1224
1225        // Respawn immediately, well before the old process's real OS-level
1226        // kill + EOF can complete. This is the race window.
1227        controller
1228            .start(app_server_meta("ready-for-turn"), None, false)
1229            .unwrap();
1230        let respawned = wait_until(
1231            || controller.inner.lock().unwrap().session.is_some(),
1232            Duration::from_secs(5),
1233        )
1234        .await;
1235        assert!(
1236            respawned,
1237            "the respawn immediately after stop_process() never installed a new session"
1238        );
1239        let new_process_ptr =
1240            Arc::as_ptr(controller.inner.lock().unwrap().process.as_ref().unwrap());
1241
1242        // Wait for the OLD process to actually finish exiting at the OS
1243        // level -- the old event loop awaits this same call internally, so
1244        // once this resolves its post-await reap logic is about to run (or
1245        // already has). A bounded number of scheduling turns afterward lets
1246        // it actually complete before asserting.
1247        let _ = old_process.wait_for_exit().await;
1248        for _ in 0..100 {
1249            tokio::task::yield_now().await;
1250        }
1251
1252        assert_ne!(
1253            controller.get_runtime_status().shellprocstatus,
1254            STATUS_DONE,
1255            "the stale old event loop must not stamp STATUS_DONE over the respawned process"
1256        );
1257        let inner = controller.inner.lock().unwrap();
1258        assert!(
1259            inner.session.is_some(),
1260            "the stale old event loop must not clear the respawned session"
1261        );
1262        assert_eq!(
1263            Arc::as_ptr(inner.process.as_ref().unwrap()),
1264            new_process_ptr,
1265            "inner.process must still be the respawned process, not cleared by the stale old event loop"
1266        );
1267    }
1268
1269    fn usage(turn: &str, output: u64) -> serde_json::Value {
1270        serde_json::json!({
1271            "threadId": "t",
1272            "turnId": turn,
1273            "tokenUsage": {
1274                "total": { "outputTokens": 9_999 },
1275                "last": { "outputTokens": output },
1276                "modelContextWindow": null,
1277            },
1278        })
1279    }
1280
1281    #[test]
1282    fn a_codex_turn_s_figures_sum_its_calls_and_start_over_per_turn() {
1283        let mut u = CodexTurnUsage::default();
1284        assert_eq!(u.take(), None, "no call reported usage");
1285        u.note("thread/tokenUsage/updated", &usage("turn-1", 120));
1286        u.note("item/completed", &usage("turn-1", 5_000));
1287        u.note("thread/tokenUsage/updated", &usage("turn-1", 30));
1288        let stats = u.take().unwrap();
1289        assert_eq!((stats.output_tokens, stats.steps), (150, 2), "each call's last, not the thread total");
1290        assert_eq!(u.take(), None, "taken once");
1291
1292        // Usage left from a turn that never completed is not the next turn's.
1293        u.note("thread/tokenUsage/updated", &usage("turn-2", 70));
1294        u.note("thread/tokenUsage/updated", &usage("turn-3", 40));
1295        let stats = u.take().unwrap();
1296        assert_eq!((stats.output_tokens, stats.steps), (40, 1));
1297        assert_eq!(stats.cost_usd, 0.0);
1298    }
1299}