Skip to main content

agentmux_srv_core/backend/blockcontroller/
acp_spawn.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of [`AcpController::spawn_process`], one function each, in the order they ran: launch
5//! the child, drain its stderr, mark it running, start the stdin writer, the stdout reader and the
6//! process waiter, then send `initialize`. Moved out of `spawn_process` without a change in
7//! behaviour.
8
9use super::*;
10
11/// The stdout reader task's captures, and the handling of one line of the agent's output.
12struct AcpStdoutReader {
13    block_id_stdout: String,
14    broker_clone: Option<Arc<mps::Broker>>,
15    filestore_clone: Option<Arc<FileStore>>,
16    inner_clone: Arc<Mutex<AcpInner>>,
17    health_clone: Arc<TurnActivityTracker>,
18    rpc_id_clone: Arc<AtomicU64>,
19    outstanding_prompt_ids_clone: Arc<Mutex<HashSet<u64>>>,
20    mstore_clone: Option<Arc<Store>>,
21    event_bus_clone: Option<Arc<EventBus>>,
22    global_output_zone: Option<String>,
23    /// What the brakes have seen of this process's output.
24    watch: Mutex<Brakes>,
25}
26
27/// The agent's context size, in tokens, at which its leader is told how much each call now reads. Once per level and process.
28const CONTEXT_NOTICES: [u64; 2] = [300_000, 600_000];
29
30/// The brakes' state for one ACP process (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` sections 5 and 12).
31#[derive(Default)]
32struct Brakes {
33    loop_guard: crate::agents::loop_guard::LoopGuard,
34    /// The guard ended this turn with `session/cancel`; it sees the turn's end before it looks again.
35    ended_by_guard: bool,
36    /// How many of [`CONTEXT_NOTICES`] the leader has been told.
37    context_told: usize,
38}
39
40/// What one line of output turned out to be, for how it is written to the pane.
41#[derive(Default)]
42struct LineState {
43    /// A failed `session/load` the handshake recovers from (it opens a new session): not shown,
44    /// or the pane reads it as an error that ended a turn.
45    recovered_error: bool,
46    /// A line the agent sends while it replays a loaded session.
47    replaying: bool,
48    /// An error that ended the turn: a turn end follows it, since the error itself doesn't say
49    /// whether other prompts are still running.
50    turn_ended_by_error: bool,
51    /// The line answered the last prompt still running: the turn is over. A rejected steering prompt sent while an
52    /// earlier one runs is an answer too, but the turn goes on.
53    turn_over: bool,
54}
55
56impl AcpController {
57    /// Start the child with its three pipes; it is in the block's process tracker before it runs.
58    pub(super) fn launch_child(
59        &self,
60        cli_command: &str,
61        cli_args: &[String],
62        working_dir: &str,
63        env_vars: &HashMap<String, String>,
64    ) -> Result<(tokio::process::Child, u32), String> {
65        let mut cmd = crate::backend::pane_env::make_cli_cmd(cli_command);
66        cmd.args(cli_args);
67
68        core::apply_working_dir(&mut cmd, &self.block_id, working_dir, env_vars);
69        // Identity M4a: record what this process is actually given.
70        crate::backend::identity_spawn::record_process_spawn(
71            &self.block_id,
72            crate::backend::identity_spawn::SpawnPath::Acp,
73            env_vars,
74        );
75        // On Windows: suppress console-window allocation. Without CREATE_NO_WINDOW,
76        // node.exe spawned from a windowless sidecar may try to create/attach to a
77        // console, causing stdout to go to that console rather than the pipe.
78        #[cfg(windows)]
79        {
80            cmd.no_window();
81        }
82
83        cmd.stdin(std::process::Stdio::piped());
84        cmd.stdout(std::process::Stdio::piped());
85        cmd.stderr(std::process::Stdio::piped());
86
87        // In the block's tracker before it runs (`spawn_tracked`); closes the
88        // Process Broker Phase B gap for ACP agent panes
89        // (SPEC_PROCESS_BROKER_PHASE_B_SHELL_ACP_REGISTRATION_2026_07_31.md).
90        let child = crate::backend::process_tracker::registry::spawn_tracked(&self.block_id, &mut cmd, crate::backend::process_tracker::registry::Join::Agent).map_err(|e| {
91            tracing::error!(block_id = %self.block_id, error = %e, "ACP process spawn failed");
92            format!("failed to spawn ACP process: {e}")
93        })?;
94
95        let pid = child.id().unwrap_or(0);
96
97        tracing::info!(
98            block_id = %self.block_id,
99            pid = pid,
100            cmd = %cli_command,
101            args = ?cli_args,
102            "ACP agent process spawned"
103        );
104        Ok((child, pid))
105    }
106
107    /// Drain stderr with explicit error/EOF logging.
108    pub(super) fn spawn_stderr_drain(&self, stderr_pipe: tokio::process::ChildStderr) {
109        let block_id_stderr = self.block_id.clone();
110        tokio::spawn(async move {
111            let mut reader = BufReader::new(stderr_pipe).lines();
112            loop {
113                match reader.next_line().await {
114                    Err(e) => {
115                        tracing::warn!(block_id = %block_id_stderr, error = %e, "ACP stderr read error");
116                        break;
117                    }
118                    Ok(None) => break,
119                    Ok(Some(line)) => {
120                        if !line.trim().is_empty() {
121                            crate::backend::blockcontroller::stderr_log::log_stderr_line(&block_id_stderr, "ACP agent", &line, true);
122                        }
123                    }
124                }
125            }
126        });
127    }
128
129    /// Mark the process running and open the stdin channel; returns its receiving end.
130    pub(super) fn register_running(&self, pid: u32, kill_tx: tokio::sync::oneshot::Sender<bool>) -> mpsc::Receiver<String> {
131        let (msg_tx, msg_rx) = mpsc::channel::<String>(32);
132
133        {
134            let mut inner = self.inner.lock().unwrap();
135            inner.current_pid = Some(pid);
136            inner.kill_tx = Some(kill_tx);
137            inner.stdin_tx = Some(msg_tx.clone());
138            Self::set_status(&mut inner, STATUS_RUNNING);
139        }
140        self.health_monitor.note_spawned();
141        self.publish_status();
142        msg_rx
143    }
144
145    pub(super) fn spawn_stdin_writer(&self, stdin: tokio::process::ChildStdin, mut msg_rx: mpsc::Receiver<String>) {
146        let block_id_stdin = self.block_id.clone();
147        tokio::spawn(async move {
148            let mut stdin = tokio::io::BufWriter::new(stdin);
149            while let Some(line) = msg_rx.recv().await {
150                if let Err(e) = stdin.write_all(line.as_bytes()).await {
151                    tracing::error!(block_id = %block_id_stdin, error = %e, "ACP stdin write error");
152                    break;
153                }
154                if let Err(e) = stdin.write_all(b"\n").await {
155                    tracing::error!(block_id = %block_id_stdin, error = %e, "ACP stdin newline error");
156                    break;
157                }
158                if let Err(e) = stdin.flush().await {
159                    tracing::error!(block_id = %block_id_stdin, error = %e, "ACP stdin flush error");
160                    break;
161                }
162            }
163        });
164    }
165
166    /// Reads NDJSON lines from the agent and broadcasts them via MPS.
167    pub(super) fn spawn_stdout_reader(&self, stdout: tokio::process::ChildStdout) {
168        let block_id_stdout = self.block_id.clone();
169        let broker_clone = self.broker.clone();
170        let filestore_clone = self.filestore.clone();
171        let inner_clone = self.inner.clone();
172        let health_clone = self.health_monitor.clone();
173        let rpc_id_clone = self.next_rpc_id.clone();
174        let outstanding_prompt_ids_clone = self.outstanding_prompt_ids.clone();
175        let mstore_clone = self.mstore.clone();
176        let event_bus_clone = self.event_bus.clone();
177        // Resolve the agent's GLOBAL transcript zone once (see persistent/spawn.rs).
178        let global_output_zone =
179            crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
180        let reader_state = AcpStdoutReader {
181            block_id_stdout,
182            broker_clone,
183            filestore_clone,
184            inner_clone,
185            health_clone,
186            rpc_id_clone,
187            outstanding_prompt_ids_clone,
188            mstore_clone,
189            event_bus_clone,
190            global_output_zone,
191            watch: Default::default(),
192        };
193        tokio::spawn(async move {
194            let mut reader = BufReader::new(stdout).lines();
195            tracing::info!(block_id = %reader_state.block_id_stdout, "ACP stdout_reader started");
196
197            loop {
198                let line = match reader.next_line().await {
199                    Err(e) => {
200                        tracing::warn!(block_id = %reader_state.block_id_stdout, error = %e, "ACP stdout read error");
201                        break;
202                    }
203                    Ok(None) => {
204                        tracing::info!(block_id = %reader_state.block_id_stdout, "ACP stdout EOF");
205                        break;
206                    }
207                    Ok(Some(l)) => l,
208                };
209                reader_state.handle_line(line);
210            }
211        });
212    }
213
214    pub(super) fn spawn_process_waiter(&self, mut child: tokio::process::Child, kill_rx: tokio::sync::oneshot::Receiver<bool>) {
215        let generation = self.begin_process();
216        let block_id_wait = self.block_id.clone();
217        let inner_wait = self.inner.clone();
218        let broker_wait = self.broker.clone();
219        let health_wait = self.health_monitor.clone();
220        let outstanding_prompt_ids_wait = self.outstanding_prompt_ids.clone();
221        tokio::spawn(async move {
222            tokio::select! {
223                _ = kill_rx => {
224                    let _ = agentmux_common::process::kill_child_and_group(&mut child).await;
225                    tracing::info!(block_id = %block_id_wait, "ACP process killed");
226
227                    let mut inner = inner_wait.lock().unwrap();
228                    if inner.generation != generation {
229                        // A newer process owns the controller now.
230                        return;
231                    }
232                    inner.stdin_tx = None;
233                    inner.current_pid = None;
234                    AcpController::set_status(&mut inner, STATUS_DONE);
235                    drop(inner);
236
237                    health_wait.set_active_turn(false);
238                    // resync_controller (mod.rs) can REUSE this exact
239                    // AcpController instance across a kill+restart cycle
240                    // (needs_replace false, status STATUS_DONE — the
241                    // non-forced pane-reopen path, or after watchdog.rs's
242                    // max-runtime/idle-timeout stop) — outstanding_prompt_ids
243                    // is the SAME Arc across that reuse. Any prompt ids still
244                    // outstanding at kill time will never get a response (no
245                    // process left to answer), so without clearing here they
246                    // would linger forever: the NEXT turn's own prompt id
247                    // resolving would never empty the set, permanently
248                    // stranding turn_active at true for the rest of this
249                    // instance's lifetime. reagentx P1 on PR #2338
250                    // (thirty-third re-review).
251                    outstanding_prompt_ids_wait.lock().unwrap().clear();
252                    // A compaction in progress died with the process: nothing will end its turn.
253                    crate::backend::context_reading::cancel_acp_compaction(&block_id_wait);
254
255                    if let Some(ref broker) = broker_wait {
256                        let status = agent_runtime_status(&block_id_wait, 0, STATUS_DONE, -1, false);
257                        super::super::publish_controller_status(broker, &status);
258                    }
259                }
260                status = child.wait() => {
261                    let exit_code = status.map(|s| s.code().unwrap_or(-1)).unwrap_or(-1);
262                    tracing::info!(
263                        block_id = %block_id_wait,
264                        exit_code = exit_code,
265                        "ACP process exited"
266                    );
267                    let mut inner = inner_wait.lock().unwrap();
268                    if inner.generation != generation {
269                        // A newer process owns the controller now.
270                        return;
271                    }
272                    inner.proc_exit_code = exit_code;
273                    inner.stdin_tx = None;
274                    AcpController::set_status(&mut inner, STATUS_DONE);
275                    drop(inner);
276
277                    health_wait.set_active_turn(false);
278                    // See the matching comment in the kill_rx branch above —
279                    // same reasoning applies to a natural process exit.
280                    outstanding_prompt_ids_wait.lock().unwrap().clear();
281                    // A compaction in progress died with the process: nothing will end its turn.
282                    crate::backend::context_reading::cancel_acp_compaction(&block_id_wait);
283
284                    if let Some(ref broker) = broker_wait {
285                        let status = agent_runtime_status(&block_id_wait, 0, STATUS_DONE, exit_code, false);
286                        super::super::publish_controller_status(broker, &status);
287                    }
288                }
289            }
290        });
291    }
292
293    /// ACP v1 handshake: `initialize` only. Its result decides between
294    /// `session/new` and `session/load`; the stdout reader sends that.
295    pub(super) fn send_initialize(&self, working_dir: &str) {
296        let init_id = self.next_id();
297        let init_req = serde_json::json!({
298            "jsonrpc": "2.0",
299            "id": init_id,
300            "method": "initialize",
301            "params": initialize_params(),
302        })
303        .to_string();
304        let mut inner = self.inner.lock().unwrap();
305        inner.init_request_id = Some(init_id);
306        inner.session_cwd = session_cwd(working_dir);
307        if let Some(ref tx) = inner.stdin_tx {
308            if tx.try_send(init_req).is_err() {
309                tracing::error!(block_id = %self.block_id, "[acp] initialize dropped — channel full or closed; agent will not start");
310            }
311        }
312    }
313}
314
315impl AcpStdoutReader {
316    fn handle_line(&self, line: String) {
317        if line.is_empty() {
318            return;
319        }
320        self.health_clone.note_output();
321        let mut state = LineState::default();
322        // Parse as JSON to check for session/update notifications
323        if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
324            self.reply_to_agent_request(&json);
325            let loaded = self.advance_handshake(&json, &mut state);
326            self.on_session(&json, loaded);
327            self.on_prompt_resolved(&json, &mut state);
328            // What the harness can do is not history: its commands count while it replays a session it loads.
329            self.watch_commands(&json);
330            if !state.replaying && !state.recovered_error {
331                self.watch_for_loops(&json, &state);
332                self.watch_context(&json);
333            }
334        }
335
336        self.append_line(&line, &state);
337    }
338
339    /// Feeds the line to the loop guard and ends the turn with `session/cancel` when it says the agent is stuck (the same
340    /// brake the Claude controller has: `blockcontroller/loop_stop.rs`).
341    fn watch_for_loops(&self, json: &serde_json::Value, state: &LineState) {
342        let mut brakes = self.watch.lock().unwrap();
343        let is_answer = json.get("id").is_some() && (json.pointer("/result/stopReason").is_some() || json.get("error").is_some());
344        if is_answer {
345            // Only the answer to the last prompt running ends the turn: the guard's count and its cancel survive a
346            // steering prompt the agent rejects while an earlier one goes on.
347            if state.turn_over {
348                brakes.loop_guard.observe_acp(json);
349                brakes.ended_by_guard = false;
350            }
351            return;
352        }
353        if brakes.ended_by_guard {
354            return;
355        }
356        if let Some(stuck) = brakes.loop_guard.observe_acp(json) {
357            brakes.ended_by_guard = self.cancel_turn();
358            if brakes.ended_by_guard {
359                crate::backend::blockcontroller::loop_stop::after_ending(&self.block_id_stdout, self.mstore_clone.as_ref(), &stuck);
360            }
361        }
362    }
363
364    /// `session/cancel` for the open session. `false` when there is none or the agent's stdin is gone or full.
365    fn cancel_turn(&self) -> bool {
366        let inner = self.inner_clone.lock().unwrap();
367        let (Some(tx), Some(session_id)) = (inner.stdin_tx.as_ref(), inner.session_id.as_ref()) else { return false };
368        let cancel = serde_json::json!({ "jsonrpc": "2.0", "method": "session/cancel", "params": { "sessionId": session_id } });
369        tx.try_send(cancel.to_string()).is_ok()
370    }
371
372    /// The commands the agent announces (`available_commands_update`): compaction is offered when `compact` is one.
373    fn watch_commands(&self, json: &serde_json::Value) {
374        let Some(update) = json.pointer("/params/update").filter(|u| u.get("sessionUpdate").and_then(|k| k.as_str()) == Some("available_commands_update")) else { return };
375        let commands = update.get("availableCommands").and_then(|c| c.as_array()).map(|list| {
376            list.iter()
377                .filter_map(|c| {
378                    let name = c.get("name").and_then(|n| n.as_str())?.trim_start_matches('/').to_string();
379                    Some(AnnouncedCommand { name, takes_input: c.get("input").is_some_and(|i| !i.is_null()) })
380                })
381                .collect::<Vec<_>>()
382        });
383        self.inner_clone.lock().unwrap().announced_commands = Some(commands.unwrap_or_default());
384    }
385
386    /// Whether this agent offers compaction: it has announced a `compact` command.
387    fn offers_compaction(&self) -> bool {
388        self.inner_clone.lock().unwrap().announced_commands.as_ref().is_some_and(|cmds| cmds.iter().any(|c| c.name == "compact"))
389    }
390
391    /// The agent's `usage_update` says how much its conversation holds. An ACP harness has no knob AgentMux can set for
392    /// it, so its leader is told, held and never waking it, when it passes a level.
393    fn watch_context(&self, json: &serde_json::Value) {
394        let Some(update) = json.pointer("/params/update").filter(|u| u.get("sessionUpdate").and_then(|k| k.as_str()) == Some("usage_update")) else { return };
395        let Some(used) = update.get("used").and_then(|u| u.as_u64()) else { return };
396        crate::backend::context_reading::observe_acp(&self.block_id_stdout, used, update.get("size").and_then(|s| s.as_u64()));
397        let level = CONTEXT_NOTICES.iter().filter(|at| used >= **at).count();
398        {
399            let mut brakes = self.watch.lock().unwrap();
400            if level <= brakes.context_told {
401                return;
402            }
403            brakes.context_told = level;
404        }
405        let Some(mstore) = self.mstore_clone.clone() else { return };
406        let (block_id, size) = (self.block_id_stdout.clone(), update.get("size").and_then(|s| s.as_u64()));
407        tokio::task::spawn_blocking(move || {
408            let Some(agent) = crate::identity::resolver::block_agent_id(&mstore, &block_id) else { return };
409            let name = mstore.agent_def_get(&agent).ok().flatten().map(|d| d.name).unwrap_or_else(|| agent.clone());
410            let window = size.map(|s| format!(" of its {}K window", s / 1000)).unwrap_or_default();
411            let note = format!("{name}'s conversation holds {}K tokens{window}; every call reads all of it. The agent is told at its turn ends.", used / 1000);
412            crate::backend::worker_notes::tell_leader_held(&mstore, &agent, &note, &format!("acp-context-{block_id}"));
413        });
414    }
415
416    fn reply_to_agent_request(&self, json: &serde_json::Value) {
417        // A request from the agent (permission, fs, terminal):
418        // answer it, or the agent waits forever.
419        if let Some(reply) = reply_to_agent_request(json) {
420            let inner = self.inner_clone.lock().unwrap();
421            if let Some(ref tx) = inner.stdin_tx {
422                if tx.try_send(reply.to_string()).is_err() {
423                    tracing::warn!(block_id = %self.block_id_stdout, "[acp] reply to an agent request dropped — channel full or closed");
424                }
425            }
426        }
427    }
428
429    /// Handshake: `initialize` answered → open or load the session; a failed `session/load` → open
430    /// a new one. Returns the session a successful `session/load` loaded.
431    fn advance_handshake(&self, json: &serde_json::Value, state: &mut LineState) -> Option<String> {
432        // A loaded session's result carries no id: it is the one we asked for.
433        let msg_id = json.get("id").and_then(|v| v.as_u64());
434        let mut loaded: Option<String> = None;
435        {
436            let mut inner = self.inner_clone.lock().unwrap();
437            let is = |id: Option<u64>| msg_id.is_some() && msg_id == id;
438            state.replaying = is_session_replay(inner.loading_session.is_some(), is(inner.session_request_id));
439            let next = if is(inner.init_request_id) && json.get("result").is_some() {
440                inner.init_request_id = None;
441                let can_load = json
442                    .pointer("/result/agentCapabilities/loadSession")
443                    .and_then(|v| v.as_bool())
444                    .unwrap_or(false);
445                // dsh offers `session/resume` (sessionCapabilities.resume, an object or true) and no load.
446                let can_resume = json
447                    .pointer("/result/agentCapabilities/sessionCapabilities/resume")
448                    .is_some_and(|v| !v.is_null() && v.as_bool() != Some(false));
449                let restore = SessionRestore::of(can_load, can_resume);
450                let takes = |t: &str| {
451                    json.pointer(&format!("/result/agentCapabilities/mcpCapabilities/{t}"))
452                        .and_then(|v| v.as_bool())
453                        .unwrap_or(false)
454                };
455                let env = &inner.mcp_env;
456                let lookup = |k: &str| env.get(k).cloned().or_else(|| std::env::var(k).ok());
457                let servers = inner.mcp_json.as_deref().map_or_else(Vec::new, |raw| {
458                    let (http, sse) = (takes("http"), takes("sse"));
459                    let path = env.get("PATH").map(String::as_str);
460                    let resolve = |c: &str| super::super::acp_mcp::resolve_command(c, path);
461                    let mut servers = super::super::acp_mcp::acp_mcp_servers(raw, http, sse, resolve, lookup);
462                    // dsh starts the MCP server with only the env listed here, not the agent's own.
463                    super::super::acp_mcp::carry_agentmux_env(&mut servers, env);
464                    servers
465                });
466                inner.mcp_servers = servers;
467                let resume = inner.resume_session_id.clone();
468                let loading = if restore != SessionRestore::No { resume.clone() } else { None };
469                let req = session_request(resume.as_deref(), restore, &inner.session_cwd, &inner.mcp_servers);
470                Some((req, loading))
471            } else if is(inner.session_request_id) && json.get("error").is_some() && inner.loading_session.is_some() {
472                inner.loading_session = None;
473                state.recovered_error = true;
474                Some((session_request(None, SessionRestore::No, &inner.session_cwd, &inner.mcp_servers), None))
475            } else {
476                None
477            };
478            if is(inner.session_request_id) && json.get("result").is_some() {
479                loaded = inner.loading_session.take();
480            }
481            if next.is_none() && is(inner.init_request_id) && json.get("error").is_some() {
482                // initialize refused (an unsupported protocol
483                // version): no session will ever open.
484                inner.init_request_id = None;
485                inner.pending_prompt = None;
486                inner.session_failed = true;
487                state.turn_ended_by_error = true;
488            }
489            if next.is_none() && is(inner.session_request_id) && json.get("error").is_some() {
490                // session/new refused (pi: "Authentication
491                // required"): the queued prompt can't run.
492                inner.pending_prompt = None;
493                inner.session_failed = true;
494                state.turn_ended_by_error = true;
495            }
496            if let Some(((method, params), loading)) = next {
497                let id = self.rpc_id_clone.fetch_add(1, Ordering::Relaxed);
498                inner.session_request_id = Some(id);
499                inner.loading_session = loading;
500                let req = serde_json::json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }).to_string();
501                if let Some(ref tx) = inner.stdin_tx {
502                    if tx.try_send(req).is_err() {
503                        tracing::error!(block_id = %self.block_id_stdout, method, "[acp] session request dropped — channel full or closed; agent will not start");
504                    }
505                }
506            }
507        }
508        loaded
509    }
510
511    fn on_session(&self, json: &serde_json::Value, loaded: Option<String>) {
512        let session = json
513            .pointer("/result/sessionId")
514            .and_then(|v| v.as_str())
515            .map(str::to_string)
516            .or(loaded);
517        if let Some(sid_owned) = session {
518            {
519                let sid = sid_owned.as_str();
520                {
521                    let mut inner = self.inner_clone.lock().unwrap();
522                    inner.session_id = Some(sid_owned.clone());
523                    // Flush pending prompt now that session is ready.
524                    self.flush_pending_prompt(&mut inner, sid);
525                }
526                tracing::info!(
527                    block_id = %self.block_id_stdout,
528                    session_id = %sid_owned,
529                    "ACP session established"
530                );
531                // Persist to block metadata and broadcast so the frontend's
532                // "My Agents" reattach path can read agent:sessionid from
533                // block.meta. ACP previously captured the ID in memory only —
534                // this mirrors the careful path from persistent/stdout_reader.rs /
535                // subprocess/host_spawn.rs.
536                core::persist_session_id(&self.block_id_stdout, &sid_owned, &self.mstore_clone, &self.event_bus_clone);
537            }
538        }
539    }
540
541    /// Send the prompt queued before the session was ready.
542    fn flush_pending_prompt(&self, inner: &mut AcpInner, sid: &str) {
543        if let Some(prompt) = inner.pending_prompt.take() {
544            let id = self.rpc_id_clone.fetch_add(1, Ordering::Relaxed);
545            self.outstanding_prompt_ids_clone.lock().unwrap().insert(id);
546            // Mark the turn active + publish, mirroring
547            // send_input's identical pattern — without
548            // this, a prompt flushed here (queued before
549            // the controller finished starting) is
550            // invisible to is_active_turn()/wasTurnActive:
551            // a concurrently-deferred /login controller
552            // refresh could then read
553            // isBackendTurnConfirmedIdle() as true and
554            // force-restart the controller while this
555            // flushed prompt is genuinely in flight.
556            // reagentx P2 on PR #2338 (thirty-first
557            // re-review).
558            self.health_clone.mark_turn_active_returning_was_active();
559            if let Some(ref broker) = self.broker_clone {
560                let status = agent_runtime_status(
561                    &self.block_id_stdout,
562                    inner.status_version,
563                    &inner.proc_status,
564                    inner.proc_exit_code,
565                    true,
566                );
567                super::super::publish_controller_status(broker, &status);
568            }
569            let req = serde_json::json!({
570                "jsonrpc": "2.0",
571                "id": id,
572                "method": "session/prompt",
573                "params": prompt_params(sid, &prompt),
574            }).to_string();
575            if let Some(ref tx) = inner.stdin_tx {
576                if tx.try_send(req).is_err() {
577                    tracing::warn!(block_id = %self.block_id_stdout, "[acp] session/prompt send failed — channel full or closed");
578                    // The text goes back to the head of the queue: the sender was told it would be sent, and the next turn end
579                    // or the next start sends it.
580                    inner.pending_prompt = Some(match inner.pending_prompt.take() {
581                        Some(later) => format!("{prompt}\n\n{later}"),
582                        None => prompt,
583                    });
584                    // Mirror send_input's enqueue-failure
585                    // rollback: this prompt was never
586                    // really sent, so it must not be
587                    // left occupying the outstanding set
588                    // or leave the turn marked active
589                    // when nothing else is genuinely
590                    // outstanding.
591                    let now_empty = {
592                        let mut outstanding = self.outstanding_prompt_ids_clone.lock().unwrap();
593                        outstanding.remove(&id);
594                        outstanding.is_empty()
595                    };
596                    if now_empty {
597                        self.health_clone.set_active_turn(false);
598                        if let Some(ref broker) = self.broker_clone {
599                            let status = agent_runtime_status(
600                                &self.block_id_stdout,
601                                inner.status_version,
602                                &inner.proc_status,
603                                inner.proc_exit_code,
604                                false,
605                            );
606                            super::super::publish_controller_status(broker, &status);
607                        }
608                    }
609                }
610            }
611        }
612    }
613
614    fn on_prompt_resolved(&self, json: &serde_json::Value, state: &mut LineState) {
615        // A prompt is RESOLVED — one way or another — by either
616        // a real `stopReason` completion or a JSON-RPC `error`
617        // rejection (mid-turn prompt acceptance is agent-
618        // dependent; some agents reject a steering prompt sent
619        // while an earlier one is still being processed).
620        // Either way, remove it from the outstanding set and
621        // only declare the turn genuinely over once NOTHING is
622        // left outstanding — never based on "was this the most
623        // recently sent prompt," which breaks under steering:
624        // an earlier prompt's completion can arrive after a
625        // newer one was sent, or a newer prompt's rejection can
626        // arrive after an earlier one already completed. codex
627        // P2 on PR #2338 (twenty-seventh through thirtieth
628        // re-reviews).
629        let resolved_id = if json.get("id").is_some()
630            && json.get("result").and_then(|r| r.get("stopReason")).is_some()
631        {
632            json.get("id").and_then(|v| v.as_u64())
633        } else if json.get("id").is_some() && json.get("error").is_some() {
634            json.get("id").and_then(|v| v.as_u64())
635        } else {
636            None
637        };
638        if let Some(resolved_id) = resolved_id {
639            let turn_is_over = {
640                let mut outstanding = self.outstanding_prompt_ids_clone.lock().unwrap();
641                resolve_prompt_and_check_idle(&mut outstanding, resolved_id)
642            };
643            if turn_is_over && json.get("error").is_some() {
644                state.turn_ended_by_error = true;
645            }
646            state.turn_over = turn_is_over;
647            if turn_is_over {
648                self.health_clone.set_active_turn(false);
649                // Publish the flip so live controllerstatus
650                // subscribers see "turn ended" immediately,
651                // mirroring persistent/stdout_reader.rs's matching publish
652                // on its own normal (non-kill, non-exit)
653                // turn-end path. Without this, nothing
654                // publishes turn_active: false for an ACP
655                // controller (OpenClaw/Copilot/Pi in
656                // catalog.ts) until kill or process exit —
657                // a normal turn-end here left the frontend's
658                // `wasTurnActive` signal (fed only by live
659                // controllerstatus events, never local
660                // state) stuck at its last-seen value,
661                // stranding useAgentCommands.ts's
662                // flushPendingControllerRefresh (which
663                // requires isBackendTurnConfirmedIdle —
664                // wasTurnActive === false — before running a
665                // /login-deferred controller restart) until
666                // an unrelated event happened to republish
667                // status (#2338).
668                if let Some(ref broker) = self.broker_clone {
669                    let status = {
670                        let locked = self.inner_clone.lock().unwrap();
671                        agent_runtime_status(
672                            &self.block_id_stdout,
673                            locked.status_version,
674                            &locked.proc_status,
675                            locked.proc_exit_code,
676                            false,
677                        )
678                    };
679                    super::super::publish_controller_status(broker, &status);
680                }
681                let clean = json.get("error").is_none();
682                if let Some(note) = crate::backend::context_reading::acp_compaction_turn_ended(&self.block_id_stdout, resolved_id, clean) {
683                    crate::backend::reactive::held_notes::hold(&self.block_id_stdout, crate::backend::context_reading::COMPACTION_NOTE_KEY, &note);
684                }
685                if clean {
686                    crate::backend::context_reading::hold_hint_for_kind(&self.block_id_stdout, crate::backend::context_reading::HintFor::acp(self.offers_compaction()));
687                }
688                self.flush_queued_prompt();
689            }
690        }
691    }
692
693    /// The turn is over: send the messages that arrived during it (`AcpController::submit_input` queues them in
694    /// `pending_prompt`) as the next prompt. Left queued when the process is gone: the next start sends it.
695    fn flush_queued_prompt(&self) {
696        let mut inner = self.inner_clone.lock().unwrap();
697        if inner.pending_prompt.is_none() || inner.stdin_tx.is_none() {
698            return;
699        }
700        // A message that arrived after the turn ended started the next one and took the queue with it; if another
701        // prompt is in flight now, what is queued waits for that turn's end.
702        if !self.outstanding_prompt_ids_clone.lock().unwrap().is_empty() {
703            return;
704        }
705        if let Some(sid) = inner.session_id.clone() {
706            self.flush_pending_prompt(&mut inner, &sid);
707        }
708    }
709
710    /// Persist + broadcast via the shared helper (same as subprocess/host_spawn.rs).
711    fn append_line(&self, line: &str, state: &LineState) {
712        if state.recovered_error {
713            tracing::info!(block_id = %self.block_id_stdout, "[acp] session/load refused; opening a new session");
714        } else if state.replaying {
715            // Earlier turns the agent replays while loading: the pane
716            // already has them, and their tool-call ids would collide.
717        } else if let Some(ref broker) = self.broker_clone {
718            let line_with_newline = format!("{}\n", line);
719            super::super::shell::handle_append_block_file(
720                broker,
721                &self.block_id_stdout,
722                ACP_OUTPUT_SUBJECT,
723                line_with_newline.as_bytes(),
724                self.filestore_clone.as_ref(),
725                self.global_output_zone.as_deref(),
726            );
727            if state.turn_ended_by_error {
728                let end = format!("{}\n", TURN_ENDED_BY_ERROR);
729                super::super::shell::handle_append_block_file(
730                    broker,
731                    &self.block_id_stdout,
732                    ACP_OUTPUT_SUBJECT,
733                    end.as_bytes(),
734                    self.filestore_clone.as_ref(),
735                    self.global_output_zone.as_deref(),
736                );
737            }
738        }
739    }
740}
741
742#[cfg(test)]
743mod brake_tests {
744    use super::*;
745    use serde_json::json;
746
747    fn reader_of(c: &AcpController) -> AcpStdoutReader {
748        AcpStdoutReader {
749            block_id_stdout: "brake-block".into(),
750            broker_clone: None,
751            filestore_clone: None,
752            inner_clone: c.inner.clone(),
753            health_clone: c.health_monitor.clone(),
754            rpc_id_clone: c.next_rpc_id.clone(),
755            outstanding_prompt_ids_clone: c.outstanding_prompt_ids.clone(),
756            mstore_clone: None,
757            event_bus_clone: None,
758            global_output_zone: None,
759            watch: Default::default(),
760        }
761    }
762
763    fn reader() -> (AcpStdoutReader, mpsc::Receiver<String>) {
764        let c = AcpController::new("tab".into(), "brake-block".into(), None, None, None, None);
765        let (tx, rx) = mpsc::channel(32);
766        {
767            let mut inner = c.inner.lock().unwrap();
768            inner.stdin_tx = Some(tx);
769            inner.session_id = Some("sess-1".into());
770        }
771        (reader_of(&c), rx)
772    }
773
774    fn failing_round(r: &AcpStdoutReader, n: usize) {
775        let call = json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "update": { "sessionUpdate": "tool_call", "toolCallId": format!("c{n}"), "title": "web_fetch", "status": "in_progress", "rawInput": { "url": "https://x.test" } } } });
776        let ended = json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "update": { "sessionUpdate": "tool_call_update", "toolCallId": format!("c{n}"), "status": "failed" } } });
777        r.handle_line(call.to_string());
778        r.handle_line(ended.to_string());
779    }
780
781    #[tokio::test]
782    async fn the_fifth_identical_failing_call_cancels_the_turn_once_and_the_next_turn_is_watched_again() {
783        let (r, mut rx) = reader();
784        for n in 1..=4 {
785            failing_round(&r, n);
786        }
787        assert!(rx.try_recv().is_err(), "four failures are not a loop");
788        failing_round(&r, 5);
789        let cancel: serde_json::Value = serde_json::from_str(&rx.try_recv().expect("session/cancel")).unwrap();
790        assert_eq!((cancel["method"].as_str(), cancel["params"]["sessionId"].as_str(), cancel.get("id")), (Some("session/cancel"), Some("sess-1"), None), "a notification for the open session");
791        for n in 6..=9 {
792            failing_round(&r, n);
793        }
794        assert!(rx.try_recv().is_err(), "once per turn, not at every failure after it");
795        // The agent answers the prompt with `cancelled`: the turn is over and the guard looks again.
796        r.handle_line(json!({ "jsonrpc": "2.0", "id": 3, "result": { "stopReason": "cancelled" } }).to_string());
797        for n in 10..=14 {
798            failing_round(&r, n);
799        }
800        assert!(rx.try_recv().is_ok(), "the next turn's loop is cut too");
801    }
802
803    /// A steering prompt the agent rejects while an earlier prompt still runs answers a prompt, but the turn goes on: the
804    /// guard keeps what it counted, and a turn it already cancelled is not cancelled again (#47457).
805    #[tokio::test]
806    async fn a_rejected_steering_prompt_does_not_reset_the_guard_while_the_turn_goes_on() {
807        let (r, mut rx) = reader();
808        r.outstanding_prompt_ids_clone.lock().unwrap().extend([3, 4]);
809        for n in 1..=4 {
810            failing_round(&r, n);
811        }
812        r.handle_line(json!({ "jsonrpc": "2.0", "id": 4, "error": { "code": -32000, "message": "busy" } }).to_string());
813        assert!(rx.try_recv().is_err(), "four failures are not a loop");
814        failing_round(&r, 5);
815        assert!(rx.try_recv().is_ok(), "the four counted before the rejection still count");
816        r.outstanding_prompt_ids_clone.lock().unwrap().insert(5);
817        r.handle_line(json!({ "jsonrpc": "2.0", "id": 5, "error": { "code": -32000, "message": "busy" } }).to_string());
818        for n in 6..=10 {
819            failing_round(&r, n);
820        }
821        assert!(rx.try_recv().is_err(), "the turn was cancelled once and a rejected prompt does not cancel it again");
822        // The last prompt running answers: the turn is over and the guard looks again.
823        r.handle_line(json!({ "jsonrpc": "2.0", "id": 3, "result": { "stopReason": "cancelled" } }).to_string());
824        for n in 11..=15 {
825            failing_round(&r, n);
826        }
827        assert!(rx.try_recv().is_ok(), "the next turn is watched");
828    }
829
830    #[tokio::test]
831    async fn nothing_is_watched_while_a_loaded_session_replays() {
832        let (r, mut rx) = reader();
833        r.inner_clone.lock().unwrap().loading_session = Some("old".into());
834        for n in 1..=6 {
835            failing_round(&r, n);
836        }
837        assert!(rx.try_recv().is_err(), "an earlier conversation's failures are history, not a loop");
838    }
839
840    fn prompt_sent(rx: &mut mpsc::Receiver<String>) -> (u64, String) {
841        let sent: serde_json::Value = serde_json::from_str(&rx.try_recv().expect("a session/prompt")).unwrap();
842        assert_eq!(sent["method"], "session/prompt");
843        (sent["id"].as_u64().unwrap(), sent["params"]["prompt"][0]["text"].as_str().unwrap().to_string())
844    }
845
846    /// An agent that takes one prompt at a time (dsh) refuses a second with "a prompt is already in flight", and the
847    /// message was lost while the sender was told it was delivered: it waits for the turn's end instead (#49083).
848    #[tokio::test]
849    async fn a_message_sent_during_a_turn_waits_for_its_end_and_goes_then_as_the_next_prompt() {
850        let c = AcpController::new("tab".into(), "brake-block".into(), None, None, None, None);
851        let (tx, mut rx) = mpsc::channel(32);
852        {
853            let mut inner = c.inner.lock().unwrap();
854            inner.stdin_tx = Some(tx);
855            inner.session_id = Some("sess-1".into());
856        }
857        let r = reader_of(&c);
858        assert_eq!(c.submit_input(BlockInputUnion::data(b"first".to_vec())).unwrap(), SendOutcome::Sent);
859        let (first_id, text) = prompt_sent(&mut rx);
860        assert_eq!(text, "first");
861
862        assert_eq!(c.submit_input(BlockInputUnion::data(b"second".to_vec())).unwrap(), SendOutcome::Deferred, "the answer says it waits");
863        assert_eq!(c.submit_input(BlockInputUnion::data(b"third".to_vec())).unwrap(), SendOutcome::Deferred);
864        assert!(rx.try_recv().is_err(), "nothing is sent while the first prompt is in flight");
865
866        r.handle_line(json!({ "jsonrpc": "2.0", "id": first_id, "result": { "stopReason": "end_turn" } }).to_string());
867        let (next_id, text) = prompt_sent(&mut rx);
868        assert_eq!(text, "second\n\nthird", "what arrived during the turn goes as one prompt");
869        assert_ne!(next_id, first_id);
870        assert!(c.health_monitor.is_active_turn(), "the queued prompt starts the next turn");
871        assert_eq!(*c.outstanding_prompt_ids.lock().unwrap(), HashSet::from([next_id]));
872        assert!(c.inner.lock().unwrap().pending_prompt.is_none());
873
874        r.handle_line(json!({ "jsonrpc": "2.0", "id": next_id, "result": { "stopReason": "end_turn" } }).to_string());
875        assert!(rx.try_recv().is_err(), "nothing more is waiting");
876        assert!(!c.health_monitor.is_active_turn());
877        assert_eq!(c.submit_input(BlockInputUnion::data(b"after".to_vec())).unwrap(), SendOutcome::Sent, "an idle agent gets it at once");
878    }
879
880    /// The turn ends by an error (the agent refused the prompt): a message queued behind it still goes.
881    #[tokio::test]
882    async fn a_message_queued_behind_a_turn_that_ends_in_an_error_still_goes() {
883        let c = AcpController::new("tab".into(), "brake-block".into(), None, None, None, None);
884        let (tx, mut rx) = mpsc::channel(32);
885        {
886            let mut inner = c.inner.lock().unwrap();
887            inner.stdin_tx = Some(tx);
888            inner.session_id = Some("sess-1".into());
889        }
890        let r = reader_of(&c);
891        c.submit_input(BlockInputUnion::data(b"first".to_vec())).unwrap();
892        let (first_id, _) = prompt_sent(&mut rx);
893        c.submit_input(BlockInputUnion::data(b"second".to_vec())).unwrap();
894        r.handle_line(json!({ "jsonrpc": "2.0", "id": first_id, "error": { "code": -32000, "message": "model error" } }).to_string());
895        assert_eq!(prompt_sent(&mut rx).1, "second");
896    }
897
898    /// The process is gone when the turn ends: the message stays queued for the next start, which sends it.
899    #[tokio::test]
900    async fn a_queued_message_stays_queued_when_the_process_is_gone_at_the_turns_end() {
901        let c = AcpController::new("tab".into(), "brake-block".into(), None, None, None, None);
902        let (tx, mut rx) = mpsc::channel(32);
903        {
904            let mut inner = c.inner.lock().unwrap();
905            inner.stdin_tx = Some(tx);
906            inner.session_id = Some("sess-1".into());
907        }
908        let r = reader_of(&c);
909        c.submit_input(BlockInputUnion::data(b"first".to_vec())).unwrap();
910        let (first_id, _) = prompt_sent(&mut rx);
911        c.submit_input(BlockInputUnion::data(b"second".to_vec())).unwrap();
912        c.inner.lock().unwrap().stdin_tx = None;
913        r.handle_line(json!({ "jsonrpc": "2.0", "id": first_id, "result": { "stopReason": "end_turn" } }).to_string());
914        assert_eq!(c.inner.lock().unwrap().pending_prompt.as_deref(), Some("second"));
915        assert!(c.outstanding_prompt_ids.lock().unwrap().is_empty());
916        assert!(!c.health_monitor.is_active_turn());
917    }
918
919    /// A message that arrives after the turn ended, before the queue was flushed, goes first with what waited, in one
920    /// prompt; the flush then finds a turn in flight and sends nothing (a second prompt would be refused).
921    #[tokio::test]
922    async fn a_message_between_the_turns_end_and_the_flush_takes_the_queue_with_it() {
923        let c = AcpController::new("tab".into(), "brake-block".into(), None, None, None, None);
924        let (tx, mut rx) = mpsc::channel(32);
925        {
926            let mut inner = c.inner.lock().unwrap();
927            inner.stdin_tx = Some(tx);
928            inner.session_id = Some("sess-1".into());
929        }
930        let r = reader_of(&c);
931        c.submit_input(BlockInputUnion::data(b"first".to_vec())).unwrap();
932        let (first_id, _) = prompt_sent(&mut rx);
933        c.submit_input(BlockInputUnion::data(b"queued".to_vec())).unwrap();
934        // The reader has emptied the outstanding set and not yet flushed.
935        c.outstanding_prompt_ids.lock().unwrap().remove(&first_id);
936        assert_eq!(c.submit_input(BlockInputUnion::data(b"late".to_vec())).unwrap(), SendOutcome::Sent);
937        assert_eq!(prompt_sent(&mut rx).1, "queued\n\nlate");
938        r.flush_queued_prompt();
939        assert!(rx.try_recv().is_err(), "nothing is sent while that prompt is in flight");
940        assert!(c.inner.lock().unwrap().pending_prompt.is_none());
941    }
942
943    /// The flush leaves the queue alone while a prompt is in flight.
944    #[tokio::test]
945    async fn the_flush_waits_while_a_prompt_is_in_flight() {
946        let c = AcpController::new("tab".into(), "brake-block".into(), None, None, None, None);
947        let (tx, mut rx) = mpsc::channel(32);
948        {
949            let mut inner = c.inner.lock().unwrap();
950            inner.stdin_tx = Some(tx);
951            inner.session_id = Some("sess-1".into());
952            inner.pending_prompt = Some("queued".into());
953        }
954        c.outstanding_prompt_ids.lock().unwrap().insert(9);
955        reader_of(&c).flush_queued_prompt();
956        assert!(rx.try_recv().is_err());
957        assert_eq!(c.inner.lock().unwrap().pending_prompt.as_deref(), Some("queued"));
958    }
959
960    fn controller_in_session(block: &str) -> (AcpController, mpsc::Receiver<String>) {
961        let c = AcpController::new("tab".into(), block.into(), None, None, None, None);
962        let (tx, rx) = mpsc::channel(32);
963        c.set_session_for_test(tx, "sess-1");
964        (c, rx)
965    }
966
967    fn reader_for(c: &AcpController, block: &str) -> AcpStdoutReader {
968        let mut r = reader_of(c);
969        r.block_id_stdout = block.into();
970        r
971    }
972
973    fn usage(used: u64) -> String {
974        json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "update": { "sessionUpdate": "usage_update", "used": used, "size": 256_000 } } }).to_string()
975    }
976
977    fn end_turn(id: u64) -> String {
978        json!({ "jsonrpc": "2.0", "id": id, "result": { "stopReason": "end_turn" } }).to_string()
979    }
980
981    fn announce(names: &[&str]) -> String {
982        let cmds: Vec<_> = names.iter().map(|n| json!({ "name": n, "description": "x" })).collect();
983        json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "update": { "sessionUpdate": "available_commands_update", "availableCommands": cmds } } }).to_string()
984    }
985
986    /// The agent's usage feeds the reading, and the turn's clean end holds the note naming what its harness can do.
987    #[tokio::test]
988    async fn a_turn_end_over_the_hint_size_holds_the_note_for_what_the_harness_offers() {
989        for (names, expect_compact) in [(vec!["init", "review"], false), (vec!["init", "compact"], true)] {
990            let block = format!("acp-hint-{}", uuid::Uuid::new_v4());
991            let (c, mut rx) = controller_in_session(&block);
992            let r = reader_for(&c, &block);
993            r.handle_line(announce(&names));
994            c.submit_input(BlockInputUnion::data(b"work".to_vec())).unwrap();
995            let (id, _) = prompt_sent(&mut rx);
996            r.handle_line(usage(130_000));
997            assert_eq!(crate::backend::context_reading::get(&block).and_then(|x| x.tokens), Some(130_000));
998            r.handle_line(end_turn(id));
999            let (message, _held) = crate::backend::reactive::held_notes::attach(&block, "next");
1000            assert!(message.contains("Your context is 130K of 256K tokens."), "{message}");
1001            assert_eq!(message.contains("Agents compact"), expect_compact, "{message}");
1002            crate::backend::context_reading::forget(&block);
1003        }
1004    }
1005
1006    /// A turn that ends in an error gives no hint.
1007    #[tokio::test]
1008    async fn a_turn_that_ends_in_an_error_holds_no_note() {
1009        let block = format!("acp-hint-{}", uuid::Uuid::new_v4());
1010        let (c, mut rx) = controller_in_session(&block);
1011        let r = reader_for(&c, &block);
1012        c.submit_input(BlockInputUnion::data(b"work".to_vec())).unwrap();
1013        let (id, _) = prompt_sent(&mut rx);
1014        r.handle_line(usage(130_000));
1015        r.handle_line(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32603, "message": "model error" } }).to_string());
1016        let (message, _held) = crate::backend::reactive::held_notes::attach(&block, "next");
1017        assert_eq!(message, "next");
1018        crate::backend::context_reading::forget(&block);
1019    }
1020
1021    /// A new process has announced nothing yet: the commands of the old one don't count for it.
1022    #[tokio::test]
1023    async fn the_announced_commands_are_forgotten_when_the_agent_starts_again() {
1024        let block = format!("acp-cmds-{}", uuid::Uuid::new_v4());
1025        let (c, _rx) = controller_in_session(&block);
1026        let r = reader_for(&c, &block);
1027        r.handle_line(announce(&["/compact"]));
1028        assert!(r.offers_compaction(), "a leading slash is not part of the name");
1029        c.inner.lock().unwrap().announced_commands = None;
1030        assert!(!r.offers_compaction());
1031    }
1032
1033    /// The flush cannot enqueue (the writer has gone): what was queued stays queued for the next start.
1034    #[tokio::test]
1035    async fn a_queue_the_flush_cannot_enqueue_stays_queued() {
1036        let block = format!("acp-flush-{}", uuid::Uuid::new_v4());
1037        let (c, rx) = controller_in_session(&block);
1038        let r = reader_for(&c, &block);
1039        c.inner.lock().unwrap().pending_prompt = Some("queued".into());
1040        drop(rx);
1041        r.flush_queued_prompt();
1042        assert_eq!(c.inner.lock().unwrap().pending_prompt.as_deref(), Some("queued"));
1043        assert!(c.outstanding_prompt_ids.lock().unwrap().is_empty());
1044        assert!(!c.health_monitor.is_active_turn());
1045    }
1046
1047    /// What each pinned harness announced in a recorded signed-out probe, and so whether AgentMux offers its agents
1048    /// compaction: only OpenCode answers `session/new` signed out, with commands that do not include `compact`; the
1049    /// others announce nothing there (dsh) or need a sign-in first (Pi, Copilot, Grok), so nothing is offered yet.
1050    #[tokio::test]
1051    async fn the_recorded_harness_answers_say_what_each_announces() {
1052        let fixtures: [(&str, &str, Option<Vec<&str>>); 5] = [
1053            ("dsh", include_str!("acp_fixtures/dsh-0.2.2-rc.5-signed-out.jsonl"), None),
1054            ("pi", include_str!("acp_fixtures/pi-acp-0.0.35-signed-out.jsonl"), None),
1055            ("grok", include_str!("acp_fixtures/grok-1.0.92-signed-out.jsonl"), None),
1056            ("copilot", include_str!("acp_fixtures/copilot-1.0.115-signed-out.jsonl"), None),
1057            ("opencode", include_str!("acp_fixtures/opencode-1.19.6-signed-out.jsonl"), Some(vec!["customize-opencode", "init", "review"])),
1058        ];
1059        for (name, lines, announced) in fixtures {
1060            let c = AcpController::new("tab".into(), format!("acp-fixture-{name}"), None, None, None, None);
1061            let r = reader_of(&c);
1062            for line in lines.lines() {
1063                r.handle_line(line.to_string());
1064            }
1065            assert_eq!(c.inner.lock().unwrap().announced_commands.as_ref().map(|v| v.iter().map(|c| c.name.as_str()).collect::<Vec<_>>()), announced, "{name}");
1066            assert!(!r.offers_compaction(), "{name} offers no compaction");
1067        }
1068    }
1069
1070    /// A harness announces what it can do before it answers `session/load`: those commands count, because a restored agent
1071    /// would otherwise refuse `Agents compact` until the harness happened to announce them again (#8943).
1072    #[tokio::test]
1073    async fn commands_announced_while_a_session_loads_are_kept() {
1074        let c = AcpController::new("tab".into(), "acp-load".into(), None, None, None, None);
1075        let r = reader_of(&c);
1076        {
1077            let mut inner = c.inner.lock().unwrap();
1078            inner.loading_session = Some("old-sid".into());
1079            inner.session_request_id = Some(5);
1080        }
1081        r.handle_line(announce(&["compact"]));
1082        assert!(r.offers_compaction(), "announced during the replay");
1083    }
1084
1085    /// The compaction is the `/compact` prompt's, and only that prompt's end finishes it: an error answering another prompt
1086    /// while it runs neither drops it nor ends it (#8943).
1087    #[tokio::test]
1088    async fn a_compaction_belongs_to_the_prompt_that_carried_it() {
1089        let block = format!("acp-compact-{}", uuid::Uuid::new_v4());
1090        let (c, mut rx) = controller_in_session(&block);
1091        let r = reader_for(&c, &block);
1092        r.handle_line(usage(400_000));
1093        crate::backend::context_reading::begin_acp_compaction(&block);
1094        c.submit_input(BlockInputUnion::data(b"/compact".to_vec())).unwrap();
1095        let (id, text) = prompt_sent(&mut rx);
1096        assert_eq!(text, "/compact");
1097        r.handle_line(json!({ "jsonrpc": "2.0", "id": id + 100, "error": { "code": -32603, "message": "an earlier prompt" } }).to_string());
1098        assert!(crate::backend::context_reading::get(&block).is_some_and(|x| x.compacting), "still compacting");
1099        r.handle_line(usage(390_000));
1100        r.handle_line(end_turn(id));
1101        r.handle_line(usage(60_000));
1102        let (message, _held) = crate::backend::reactive::held_notes::attach(&block, "next");
1103        assert!(message.contains("Compacted: 400K to 60K tokens."), "{message}");
1104        crate::backend::context_reading::forget(&block);
1105    }
1106
1107    /// `Agents fresh` forgets the saved session, so the launch that follows asks every harness for `session/new` and not
1108    /// `session/resume` of the old one: checked against each harness's recorded `initialize` answer, where the same answer
1109    /// with a saved session asks to load or resume it.
1110    #[tokio::test]
1111    async fn after_a_fresh_start_every_recorded_harness_is_asked_for_a_new_session() {
1112        let fixtures = [
1113            ("dsh", include_str!("acp_fixtures/dsh-0.2.2-rc.5-signed-out.jsonl")),
1114            ("pi", include_str!("acp_fixtures/pi-acp-0.0.35-signed-out.jsonl")),
1115            ("grok", include_str!("acp_fixtures/grok-1.0.92-signed-out.jsonl")),
1116            ("copilot", include_str!("acp_fixtures/copilot-1.0.115-signed-out.jsonl")),
1117            ("opencode", include_str!("acp_fixtures/opencode-1.19.6-signed-out.jsonl")),
1118        ];
1119        for (name, lines) in fixtures {
1120            let initialized = lines.lines().find(|l| l.contains("\"agentCapabilities\"")).expect("the initialize answer");
1121            let method_after = |saved: Option<&str>| {
1122                let c = AcpController::new("tab".into(), format!("acp-fresh-{name}"), None, None, None, None);
1123                let (tx, mut rx) = mpsc::channel(8);
1124                {
1125                    let mut inner = c.inner.lock().unwrap();
1126                    inner.stdin_tx = Some(tx);
1127                    inner.init_request_id = Some(1);
1128                    inner.resume_session_id = saved.map(str::to_string);
1129                }
1130                reader_of(&c).handle_line(initialized.to_string());
1131                serde_json::from_str::<serde_json::Value>(&rx.try_recv().expect("a session request")).unwrap()["method"].as_str().unwrap().to_string()
1132            };
1133            assert_eq!(method_after(None), "session/new", "{name}: a fresh start opens a new session");
1134            assert_ne!(method_after(Some("old-sid")), "session/new", "{name}: a saved session would be taken back");
1135        }
1136    }
1137
1138    /// `Agents compact` is offered by what the harness announced: a `compact` with an input hint takes a focus, one
1139    /// without takes none, and a harness that announced no `compact` is refused with what to do instead.
1140    #[tokio::test]
1141    async fn the_compaction_request_follows_what_the_harness_announced() {
1142        let c = AcpController::new("tab".into(), "acp-request".into(), None, None, None, None);
1143        let r = reader_of(&c);
1144        assert!(c.compaction_request().unwrap_err().contains("Agents fresh"), "nothing announced yet");
1145        r.handle_line(announce(&["init", "review"]));
1146        assert!(c.compaction_request().unwrap_err().contains("announced no compaction command"));
1147        r.handle_line(announce(&["compact"]));
1148        assert_eq!(c.compaction_request(), Ok(false));
1149        r.handle_line(json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "update": { "sessionUpdate": "available_commands_update", "availableCommands": [{ "name": "compact", "description": "x", "input": { "hint": "instructions" } }] } } }).to_string());
1150        assert_eq!(c.compaction_request(), Ok(true));
1151    }
1152}