Skip to main content

agentmux_srv/server/app_api/
agent_context.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents context` and `Agents compact`
5//! (`docs/specs/SPEC_AGENT_SELF_COMPACTION_2026_10_23.md` ยง3.3): an agent reads
6//! how full its own context is, and compacts itself when its turn ends.
7//!
8//! Both act on the caller's own pane only, resolved from its agent token's UID
9//! (`actor::own_pane_by_token`), never from a name: there is no target.
10
11use std::time::Duration;
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::json;
19
20use crate::backend::context_reading;
21use crate::server::caller::Caller;
22use crate::server::state::AppState;
23
24/// The longest a self-compaction waits for the caller's turn to end.
25const TURN_END_WAIT: Duration = Duration::from_secs(30 * 60);
26const TURN_END_POLL: Duration = Duration::from_millis(250);
27/// The most focus text sent with `/compact`.
28pub(crate) const FOCUS_MAX_CHARS: usize = 2_000;
29
30#[derive(Debug, Deserialize)]
31pub(crate) struct SelfContextRequest {
32    /// The caller's slug, which its token must name.
33    agent: String,
34    /// `compact`: what to keep, for the summary.
35    #[serde(default)]
36    focus: Option<String>,
37}
38
39fn no_pane() -> Response {
40    let error = "no pane for this agent token: Agents context and compact act only on the calling agent's own pane";
41    (StatusCode::UNAUTHORIZED, Json(json!({ "error": error }))).into_response()
42}
43
44/// `claude` or `codex` for a pane that can compact, with whether it runs in a container.
45fn provider_of(state: &AppState, block_id: &str) -> Option<(String, bool)> {
46    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok()??;
47    let raw = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "");
48    let provider = crate::backend::providers::resolve_provider_alias(&raw).to_string();
49    let container = crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container();
50    Some((provider, container))
51}
52
53/// Which hint rules `block_id`'s agent gets: an ACP harness has its window's sizes and offers compaction only when it
54/// announced it (the same the turn-end note uses), every other agent the settings' own.
55fn hint_kind(block_id: &str) -> context_reading::HintFor {
56    use crate::backend::blockcontroller::acp::AcpController;
57    let ctrl = crate::backend::blockcontroller::get_controller(block_id);
58    match ctrl.as_ref().and_then(|c| c.as_any().downcast_ref::<AcpController>()) {
59        Some(acp) => context_reading::HintFor::acp(acp.offers_compaction()),
60        None => context_reading::HintFor::NATIVE,
61    }
62}
63
64/// `POST /api/v1/agent/self/context`
65pub(crate) async fn handle_context_self(
66    State(state): State<AppState>,
67    caller: Option<Extension<Caller>>,
68    Json(req): Json<SelfContextRequest>,
69) -> Response {
70    let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
71        return no_pane();
72    };
73    let provider = provider_of(&state, &block_id).map(|(p, _)| p);
74    let reading = context_reading::get(&block_id).unwrap_or_default();
75    let why_none = reading.tokens.is_none().then_some(
76        "no reading yet: srv reads it from the agent's calls (Claude), after each turn (Codex) or from its usage updates (an ACP harness)",
77    );
78    Json(json!({
79        "provider": provider,
80        "model": reading.model,
81        "tokens": reading.tokens,
82        "window": reading.window,
83        "auto_compact_at": reading.auto_compact_at,
84        "compacting": reading.compacting,
85        "calls_since_compaction": reading.calls_since_compaction,
86        "last_compaction_ms": reading.last_compaction_ms,
87        "hint": context_reading::hint_for(&block_id, hint_kind(&block_id)),
88        "note": why_none,
89    }))
90    .into_response()
91}
92
93/// The message that compacts a `provider` agent, or why it can't be: a Claude agent takes `/compact`
94/// (with its focus) as a turn wherever it runs, and a container's turn is that same message on its
95/// per-turn exec controller.
96fn compact_request(provider: &str, container: bool, focus: Option<&str>) -> Result<String, &'static str> {
97    match (provider, container) {
98        ("claude", _) => Ok(compact_message(focus)),
99        // Codex compacts through a short-lived App Server on the host (`codex_compact`); a
100        // container's turn would take "/compact" as a prompt.
101        ("codex", true) => Err("unsupported: a Codex agent in a container can't compact yet"),
102        ("codex", false) => Ok("/compact".to_string()),
103        _ if speaks_acp(provider) => Err("unsupported: this harness has no compaction AgentMux can start; call Agents fresh with a handoff to start a new session instead"),
104        ("gemini", _) => Err("unsupported: Gemini's /compress does not run in the headless mode AgentMux drives it in (it starts the compression without waiting for it and sends the text to the model); call Agents fresh with a handoff to start a new session instead"),
105        ("muse", _) => Err("unsupported: this harness has no compaction AgentMux can start; call Agents fresh with a handoff to start a new session instead"),
106        _ => Err("unsupported: only Claude and Codex agents can compact"),
107    }
108}
109
110/// The message that compacts the ACP agent in `block_id`, by what its harness announced: `/compact` with the focus when the
111/// command takes one, alone when it doesn't, a refusal when the harness announced no compaction command. `None` when the
112/// pane is not an ACP agent.
113fn acp_compact_message(block_id: &str, focus: Option<&str>) -> Option<Result<String, &'static str>> {
114    use crate::backend::blockcontroller::acp::AcpController;
115    let ctrl = crate::backend::blockcontroller::get_controller(block_id)?;
116    let acp = ctrl.as_any().downcast_ref::<AcpController>()?;
117    Some(acp.compaction_request().map(|takes_input| if takes_input { compact_message(focus) } else { "/compact".to_string() }))
118}
119
120/// Whether `provider` is an Agent Client Protocol harness (dsh, Gemini, Copilot, ...): every one can open a new session.
121fn speaks_acp(provider: &str) -> bool {
122    crate::backend::providers::get_provider(provider).is_some_and(|p| p.controller_type_str() == "acp")
123}
124
125/// Whether an agent of `provider` can start a fresh session, and why not. A container's Claude or Codex agent runs one
126/// `exec` per turn on the same controller a host Codex agent does, so ending its session is forgetting its id, as
127/// there (`blockcontroller/subprocess/codex_fresh.rs`); the harnesses that speak ACP have no such controller in a container.
128fn fresh_supported(provider: &str, container: bool) -> Result<(), &'static str> {
129    match (provider, container) {
130        ("claude" | "codex", _) => Ok(()),
131        (_, true) => Err("unsupported in containers: only Claude and Codex agents can start fresh there"),
132        ("gemini" | "muse", false) => Ok(()),
133        _ if speaks_acp(provider) => Ok(()),
134        _ => Err("unsupported: only Claude, Codex, Gemini, Muse and ACP agents can start fresh"),
135    }
136}
137
138/// `POST /api/v1/agent/self/compact`: `scheduled` (runs when the caller's turn
139/// ends) or `refused` with why.
140pub(crate) async fn handle_compact_self(
141    State(state): State<AppState>,
142    caller: Option<Extension<Caller>>,
143    Json(req): Json<SelfContextRequest>,
144) -> Response {
145    let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
146        return no_pane();
147    };
148    let refused = |why: &str| Json(json!({ "status": "refused", "reason": why })).into_response();
149    let Some((provider, container)) = provider_of(&state, &block_id) else {
150        return refused("the pane can't be read");
151    };
152    let message = match acp_compact_message(&block_id, req.focus.as_deref()).unwrap_or_else(|| compact_request(&provider, container, req.focus.as_deref())) {
153        Ok(message) => message,
154        Err(why) => return refused(why),
155    };
156    if let Err(why) = context_reading::schedule_compact(&block_id, agentmux_common::time::now_ms_u64()) {
157        return refused(&why);
158    }
159    let focus_note = (message == "/compact" && req.focus.as_deref().is_some_and(|f| !f.trim().is_empty()))
160        .then_some("this harness takes no focus: it compacts with its own prompt");
161    tracing::info!(block_id = %block_id, provider = %provider, tokens = context_reading::tokens_now(&block_id), focus_chars = req.focus.as_deref().map_or(0, str::len), "self-compaction scheduled");
162    tokio::spawn(compact_when_turn_ends(state, block_id, message, container));
163    Json(json!({ "status": "scheduled", "runs": "when your current turn ends", "note": focus_note })).into_response()
164}
165
166/// The most handoff text a fresh session carries.
167pub(crate) const HANDOFF_MAX_CHARS: usize = 4_000;
168/// The longest a fresh session waits for the old CLI to exit.
169const EXIT_WAIT: Duration = Duration::from_secs(30);
170
171/// `POST /api/v1/agent/self/fresh`: `scheduled` (when the caller's turn ends,
172/// its session ends and a new one starts with the handoff) or `refused`.
173/// `focus` carries the handoff here.
174pub(crate) async fn handle_fresh_self(
175    State(state): State<AppState>,
176    caller: Option<Extension<Caller>>,
177    Json(req): Json<SelfContextRequest>,
178) -> Response {
179    let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
180        return no_pane();
181    };
182    let refused = |why: &str| Json(json!({ "status": "refused", "reason": why })).into_response();
183    let handoff = req.focus.as_deref().unwrap_or_default().trim().to_string();
184    if handoff.is_empty() {
185        return refused("a handoff is required: what your next session must know");
186    }
187    if handoff.chars().count() > HANDOFF_MAX_CHARS {
188        return refused("the handoff is over 4,000 characters: shorten it, with the next step in it");
189    }
190    let Some((provider, container)) = provider_of(&state, &block_id) else {
191        return refused("the pane can't be read");
192    };
193    if let Err(why) = fresh_supported(&provider, container) {
194        return refused(why);
195    }
196    if let Err(why) = context_reading::schedule_compact(&block_id, agentmux_common::time::now_ms_u64()) {
197        return refused(&why);
198    }
199    tracing::info!(block_id = %block_id, provider = %provider, handoff_chars = handoff.len(), "fresh session scheduled");
200    tokio::spawn(fresh_when_turn_ends(state, block_id, handoff_message(&handoff)));
201    Json(json!({ "status": "scheduled", "runs": "when your current turn ends" })).into_response()
202}
203
204/// The new session's first message from AgentMux: the agent's own handoff and
205/// a pointer to the old session. Nothing else of the conversation comes with it.
206pub(crate) fn handoff_message(handoff: &str) -> String {
207    format!(
208        "[AgentMux] This is the fresh session you asked for. Nothing of the previous conversation is in your \
209         context; it is in your record (Agents search_history finds it). Your handoff:\n\n{handoff}"
210    )
211}
212
213/// The first message of the fresh session a model change starts (`agent.model.switch` and `Agents update` with
214/// `fresh`): where the agent was moved to, that the earlier conversation is in its record and not in its context, and
215/// what the caller said its next session must know (none: where to look for what it was doing).
216pub(crate) fn switch_message(place: &str, handoff: &str) -> String {
217    let said = match handoff.trim() {
218        "" => "Read your task list (Tasks list) and your last status to see what you were doing, then carry on.",
219        h => h,
220    };
221    format!(
222        "[AgentMux] You were moved to {place} and this is a fresh session: nothing of the earlier conversation is in your \
223         context, because a model that did not write a long conversation can read it badly. It is in your record \
224         (Agents search_history finds it).\n\n{said}"
225    )
226}
227
228/// `first_message`, naming the session it replaces when the harness had one, so a person can take it back from the harness.
229fn with_previous_session(first_message: String, old: Option<&str>) -> String {
230    match old {
231        Some(id) => format!("{first_message}\n\n(The session before this one had the harness's session id {id}.)"),
232        None => first_message,
233    }
234}
235
236/// Why the pane of a model change can't start a fresh session, or nothing: the test `Agents fresh` applies to its own pane.
237pub(crate) fn fresh_refusal(state: &AppState, block_id: &str) -> Result<(), &'static str> {
238    let (provider, container) = provider_of(state, block_id).ok_or("the pane can't be read")?;
239    fresh_supported(&provider, container)
240}
241
242/// Start `block_id`'s fresh session after a model change: when its turn ends its session ends, and `first_message`
243/// starts the new one on the model the agent is set to now. `false` when there is no async runtime to run it on.
244pub(crate) fn start_fresh_after_switch(state: &AppState, block_id: &str, first_message: String) -> bool {
245    let Ok(runtime) = tokio::runtime::Handle::try_current() else {
246        return false;
247    };
248    runtime.spawn(fresh_when_turn_ends(state.clone(), block_id.to_string(), first_message));
249    true
250}
251
252/// Tries a fresh session makes when a message queued behind the turn starts
253/// the next one before the old session can be ended.
254const FRESH_ATTEMPTS: usize = 5;
255/// Held for the agent's next turn when its fresh session couldn't start.
256const FRESH_FAILED_NOTE_KEY: &str = "fresh-failed";
257/// What `start_fresh_session` says when the turn hasn't ended, or the CLI is
258/// already being stopped: the two it is worth trying again after.
259const TURN_RUNNING: &str = "a turn is running";
260const STOP_PENDING: &str = "the agent's process is already stopping or restarting";
261
262/// End `block_id`'s provider session, so the next message starts a new one. An ACP agent's old session id comes back, so
263/// the new session's first message can name it.
264fn end_session(block_id: &str) -> Result<Option<String>, &'static str> {
265    use crate::backend::blockcontroller::acp::AcpController;
266    use crate::backend::blockcontroller::msp::MspController;
267    use crate::backend::blockcontroller::persistent::PersistentSubprocessController;
268    use crate::backend::blockcontroller::subprocess::SubprocessController;
269    let ctrl = crate::backend::blockcontroller::get_controller(block_id).ok_or("no controller for the pane")?;
270    // An ACP pane: the process ends and its saved session id is forgotten, so the handoff opens a new session.
271    if let Some(acp) = ctrl.as_any().downcast_ref::<AcpController>() {
272        return acp.start_fresh_session();
273    }
274    // A Muse pane: the process ends and its saved session id is forgotten, as for an ACP one.
275    if let Some(muse) = ctrl.as_any().downcast_ref::<MspController>() {
276        return muse.start_fresh_session();
277    }
278    // A Codex or Gemini pane: one process per turn, so ending the thread is forgetting its id.
279    if let Some(codex) = ctrl.as_any().downcast_ref::<SubprocessController>() {
280        return codex.start_fresh_session().map(|_| None);
281    }
282    let p = ctrl.as_any().downcast_ref::<PersistentSubprocessController>().ok_or("the agent's controller can't start fresh")?;
283    context_reading::mark_fresh_by_choice(block_id);
284    p.start_fresh_session().map(|_| None).inspect_err(|_| {
285        context_reading::take_fresh_by_choice(block_id);
286    })
287}
288
289/// Wait for the turn to end, end the session, then send `first_message` as
290/// AgentMux's own turn, which starts the new session.
291async fn fresh_when_turn_ends(state: AppState, block_id: String, first_message: String) {
292    let mut ended: Result<Option<String>, &str> = Err("the turn didn't end within 30 minutes");
293    // A message queued behind the turn can start the next one between the wait
294    // and the stop: wait again, a few times, before giving up.
295    for _ in 0..FRESH_ATTEMPTS {
296        if !wait_for_turn_end(&block_id).await {
297            break;
298        }
299        ended = end_session(&block_id);
300        if !matches!(ended, Err(TURN_RUNNING | STOP_PENDING)) {
301            break;
302        }
303        tokio::time::sleep(TURN_END_POLL).await;
304    }
305    if let Err(why) = &ended {
306        tracing::warn!(block_id = %block_id, reason = *why, "fresh session given up");
307        context_reading::fresh_sent(&block_id, false);
308        crate::backend::reactive::held_notes::hold(
309            &block_id,
310            FRESH_FAILED_NOTE_KEY,
311            &format!("[AgentMux] Your fresh session did not start ({why}); this session continues. Call Agents fresh again when you want it."),
312        );
313        return;
314    }
315    let old_session = ended.ok().flatten();
316    if let Some(old) = &old_session {
317        tracing::info!(block_id = %block_id, old_session = %old, "fresh session: the old session ended, the next message opens a new one");
318    }
319    let first_message = with_previous_session(first_message, old_session.as_deref());
320    // The old CLI exits before the handoff spawns the new one.
321    let deadline = tokio::time::Instant::now() + EXIT_WAIT;
322    while crate::backend::blockcontroller::get_block_controller_status(&block_id)
323        .is_some_and(|s| s.shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING)
324        && tokio::time::Instant::now() < deadline
325    {
326        tokio::time::sleep(TURN_END_POLL).await;
327    }
328    let deps = crate::server::agent_handlers::AgentTurnDeps::from_state(&state);
329    let outcome = crate::server::agent_handlers::run_agent_turn(
330        &deps,
331        block_id.clone(),
332        first_message,
333        None,
334        crate::server::agent_handlers::TurnRegistration::Register,
335        crate::backend::message_origin::MessageOrigin::system(),
336        Vec::new(),
337    )
338    .await;
339    context_reading::fresh_sent(&block_id, outcome.is_ok());
340    match outcome {
341        Ok(()) => tracing::info!(block_id = %block_id, "fresh session started"),
342        Err(e) => tracing::warn!(block_id = %block_id, error = %e, "fresh session's handoff could not be sent"),
343    }
344}
345
346/// Wait until `block_id` has no turn running; `false` after [`TURN_END_WAIT`].
347async fn wait_for_turn_end(block_id: &str) -> bool {
348    let deadline = tokio::time::Instant::now() + TURN_END_WAIT;
349    while crate::backend::blockcontroller::get_block_controller_status(block_id).is_some_and(|s| s.turn_active) {
350        if tokio::time::Instant::now() >= deadline {
351            return false;
352        }
353        tokio::time::sleep(TURN_END_POLL).await;
354    }
355    true
356}
357
358/// `/compact` with the focus, trimmed to [`FOCUS_MAX_CHARS`] and to one
359/// paragraph's worth of whitespace.
360pub(crate) fn compact_message(focus: Option<&str>) -> String {
361    let focus: String = focus.unwrap_or_default().split_whitespace().collect::<Vec<_>>().join(" ").chars().take(FOCUS_MAX_CHARS).collect();
362    if focus.is_empty() { "/compact".to_string() } else { format!("/compact {focus}") }
363}
364
365/// srv's own compaction of a route agent whose context is far over its budget: the compaction `Agents compact` schedules,
366/// without a focus (the harness's summarizer decides what to keep). `Err(why)` when it can't be sent now.
367pub(crate) fn compact_for_backstop(state: &AppState, block_id: &str) -> Result<(), String> {
368    let (provider, container) = provider_of(state, block_id).ok_or("the pane can't be read")?;
369    let message = compact_request(&provider, container, None)?;
370    context_reading::schedule_compact(block_id, agentmux_common::time::now_ms_u64())?;
371    tokio::runtime::Handle::current().spawn(compact_when_turn_ends(state.clone(), block_id.to_string(), message, container));
372    Ok(())
373}
374
375/// Send `message` as AgentMux's own turn once `block_id`'s turn has ended. A container agent's turn is not waited for: it
376/// runs one turn at a time from a queue, and the compaction is placed at the head of that queue, so it starts the moment
377/// the turn in flight ends and ahead of the messages already waiting. Waiting for a moment with no turn running could
378/// take as long as the queue stays full, and the compaction would then go behind it (the queue is never empty for a busy
379/// agent: the next waiting message starts the moment a turn ends).
380async fn compact_when_turn_ends(state: AppState, block_id: String, message: String, container: bool) {
381    let deps = crate::server::agent_handlers::AgentTurnDeps::from_state(&state);
382    let acp = crate::backend::blockcontroller::get_controller(&block_id).is_some_and(|c| c.as_any().is::<crate::backend::blockcontroller::acp::AcpController>());
383    let mut outcome = Err(TURN_RUNNING.to_string());
384    // A message that starts the next turn between the wait and the send makes an ACP harness refuse `/compact` (it takes
385    // it only between turns): wait again, a few times, before giving up.
386    for _ in 0..FRESH_ATTEMPTS {
387        if !container && !wait_for_turn_end(&block_id).await {
388            tracing::warn!(block_id = %block_id, "self-compaction given up: the turn didn't end within 30 minutes");
389            context_reading::compact_sent(&block_id, false);
390            return;
391        }
392        if acp {
393            context_reading::begin_acp_compaction(&block_id);
394        }
395        outcome = crate::server::agent_handlers::run_agent_turn(
396            &deps,
397            block_id.clone(),
398            message.clone(),
399            None,
400            crate::server::agent_handlers::TurnRegistration::Register,
401            crate::backend::message_origin::MessageOrigin::system(),
402            Vec::new(),
403        )
404        .await;
405        if acp && outcome.is_err() {
406            context_reading::cancel_acp_compaction(&block_id);
407        }
408        if !(acp && outcome.as_ref().err().is_some_and(|e| e.to_string().contains(crate::backend::blockcontroller::acp::TURN_RUNNING))) {
409            break;
410        }
411    }
412    context_reading::compact_sent(&block_id, outcome.is_ok());
413    match outcome {
414        Ok(()) => tracing::info!(block_id = %block_id, tokens = context_reading::tokens_now(&block_id), "self-compaction sent"),
415        Err(e) => tracing::warn!(block_id = %block_id, error = %e, "self-compaction could not be sent"),
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    #[test]
424    fn the_first_message_names_the_session_it_replaces() {
425        assert_eq!(with_previous_session("hello".to_string(), None), "hello");
426        let m = with_previous_session("hello".to_string(), Some("sess-42"));
427        assert!(m.starts_with("hello") && m.contains("session id sess-42"), "{m}");
428    }
429
430    #[test]
431    fn a_pane_without_an_acp_controller_gets_the_settings_own_hint_rules() {
432        assert_eq!(hint_kind("no-such-block"), context_reading::HintFor::NATIVE);
433    }
434
435    #[test]
436    fn the_handoff_is_the_new_sessions_first_message_from_agentmux() {
437        let m = handoff_message("Task #1791: PR 3 open as #5410; next: wait for review.");
438        assert!(m.starts_with("[AgentMux] This is the fresh session you asked for."));
439        assert!(m.contains("search_history"), "it points at the old session");
440        assert!(m.ends_with("Task #1791: PR 3 open as #5410; next: wait for review."));
441    }
442
443    #[test]
444    fn a_claude_agent_compacts_in_a_container_as_on_the_host() {
445        assert_eq!(compact_request("claude", true, None), Ok("/compact".to_string()));
446        assert_eq!(compact_request("claude", true, Some("keep: PR #1")), compact_request("claude", false, Some("keep: PR #1")));
447        assert_eq!(compact_request("codex", false, None), Ok("/compact".to_string()));
448        assert!(compact_request("codex", true, None).is_err_and(|why| why.contains("container")));
449        assert!(compact_request("copilot", false, None).is_err_and(|why| why.contains("Agents fresh")), "an ACP harness is told what to do instead");
450        assert!(compact_request("dsh", false, None).is_err_and(|why| why.contains("no compaction AgentMux can start")));
451        assert!(compact_request("nonesuch", false, None).is_err_and(|why| why.contains("only Claude and Codex")));
452        assert!(compact_request("gemini", false, None).is_err_and(|why| why.contains("/compress") && why.contains("Agents fresh")), "Gemini is told why and what to do instead");
453        assert!(compact_request("muse", false, None).is_err_and(|why| why.contains("Agents fresh")));
454    }
455
456    #[test]
457    fn gemini_and_muse_start_fresh_on_the_host_and_not_in_a_container() {
458        for provider in ["gemini", "muse"] {
459            assert_eq!(fresh_supported(provider, false), Ok(()), "{provider}");
460            assert!(fresh_supported(provider, true).is_err_and(|why| why.contains("containers")), "{provider}");
461        }
462    }
463
464    #[test]
465    fn fresh_is_offered_to_claude_codex_and_every_acp_harness_and_in_a_container_to_claude_and_codex() {
466        for provider in ["claude", "codex", "dsh", "copilot"] {
467            assert_eq!(fresh_supported(provider, false), Ok(()), "{provider}");
468        }
469        for provider in ["claude", "codex"] {
470            assert_eq!(fresh_supported(provider, true), Ok(()), "a container's {provider} agent starts fresh as a host's does");
471        }
472        for provider in ["dsh", "copilot"] {
473            assert!(fresh_supported(provider, true).is_err_and(|why| why.contains("containers") && why.contains("Claude and Codex")), "{provider}");
474        }
475        assert!(fresh_supported("nonesuch", false).is_err_and(|why| why.contains("ACP")));
476    }
477
478    #[test]
479    fn the_focus_rides_after_compact_on_one_line_within_its_limit() {
480        assert_eq!(compact_message(None), "/compact");
481        assert_eq!(compact_message(Some("   ")), "/compact");
482        assert_eq!(compact_message(Some("keep: PR #5401\n\nthe failing test")), "/compact keep: PR #5401 the failing test");
483        let long = "x".repeat(FOCUS_MAX_CHARS + 50);
484        assert_eq!(compact_message(Some(&long)).chars().count(), "/compact ".len() + FOCUS_MAX_CHARS);
485    }
486}