Skip to main content

agentmux_srv/server/app_api/
agent_attach.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// An agent that already has a block, when it is opened or started
5// (docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md §3.1, §5.1, §9 P1 PR C): `agent.open` gives
6// it a pane by attaching its parked block, or focuses the pane that shows it, instead of making a
7// second block; a start with no pane runs it as a parked block. The agent's desired state, whether
8// it should be running, is block meta (`agent:desired`), the agent's own state while it has one block.
9
10use super::agent_open::record_agent_open_launch;
11use super::*;
12use crate::server::AppState;
13use agentmux_common::ipc::{Command, Event};
14
15/// Block meta: whether the agent should be running, `running` or `stopped`. Open, start and a
16/// message that starts it set `running`; an explicit stop sets `stopped`.
17pub(crate) const META_DESIRED: &str = "agent:desired";
18pub(crate) const DESIRED_RUNNING: &str = "running";
19pub(crate) const DESIRED_STOPPED: &str = "stopped";
20
21/// Marks an open that is a start: the block it makes is parked, not placed in a layout.
22pub(super) const START_PARKED: &str = "agent:start_parked";
23
24/// The blocks whose agent was set to stopped since this srv started and not started again, and when
25/// (unix ms). A recorded `stopped` read from the database at startup is not in it: it may be stale
26/// (something started the agent without recording it), while one in here was decided in this run, so
27/// it is binding.
28static STOPPED_THIS_RUN: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, u64>>> = std::sync::LazyLock::new(Default::default);
29
30/// Whether `block_id`'s agent was set to stopped in this run and not started since.
31pub(crate) fn stopped_this_run(block_id: &str) -> bool {
32    stopped_at_ms(block_id).is_some()
33}
34
35/// When `block_id`'s agent was set to stopped in this run (unix ms), if it was and has not been started since.
36pub(crate) fn stopped_at_ms(block_id: &str) -> Option<u64> {
37    STOPPED_THIS_RUN.lock().unwrap_or_else(|e| e.into_inner()).get(block_id).copied()
38}
39
40/// Held while a desired state is decided and written, so the record in `STOPPED_THIS_RUN` and the
41/// block's meta change together: a conditional start ([`set_running_unless_stopped_since`]) cannot
42/// overwrite a stop that lands between its check and its write. Never held across a store
43/// transaction's own work (nothing inside one calls these).
44static DESIRED_WRITE: std::sync::Mutex<()> = std::sync::Mutex::new(());
45
46/// Record the agent's desired state on its block. Best effort: a failed write costs a restart's
47/// resume, not the start or stop itself. A `stopped` is logged with the caller that decided it: an
48/// agent that comes back from a restart stopped has to be traceable to the code that stopped it.
49#[track_caller]
50pub(crate) fn set_desired(mstore: &Store, block_id: &str, desired: &str) {
51    let _deciding = DESIRED_WRITE.lock().unwrap_or_else(|e| e.into_inner());
52    {
53        let mut stopped = STOPPED_THIS_RUN.lock().unwrap_or_else(|e| e.into_inner());
54        if desired == DESIRED_STOPPED {
55            let at = std::panic::Location::caller();
56            tracing::info!(block_id, caller = %format!("{}:{}", at.file(), at.line()), "agent desired state set to stopped");
57            stopped.insert(block_id.to_string(), agentmux_common::time::now_ms_u64());
58        } else {
59            stopped.remove(block_id);
60        }
61    }
62    write_desired(mstore, block_id, desired);
63}
64
65fn write_desired(mstore: &Store, block_id: &str, desired: &str) {
66    let mut meta = obj::MetaMapType::new();
67    meta.insert(META_DESIRED.to_string(), json!(desired));
68    if let Err(e) = crate::server::service::update_object_meta(mstore, &format!("block:{block_id}"), &meta) {
69        tracing::warn!(block_id, desired, "could not record the agent's desired state: {e}");
70    }
71}
72
73/// Record the agent as wanted running, unless a stop was decided as, or after, `started_at_ms`: the
74/// turn that began then is the one the stop ended or the agent quit in. The check and the write are one
75/// step against [`set_desired`], so a stop that lands in between is not undone. Returns whether it wrote.
76pub(crate) fn set_running_unless_stopped_since(mstore: &Store, block_id: &str, started_at_ms: u64) -> bool {
77    let _deciding = DESIRED_WRITE.lock().unwrap_or_else(|e| e.into_inner());
78    {
79        let mut stopped = STOPPED_THIS_RUN.lock().unwrap_or_else(|e| e.into_inner());
80        if stopped.get(block_id).is_some_and(|at| *at >= started_at_ms) {
81            return false;
82        }
83        stopped.remove(block_id);
84    }
85    write_desired(mstore, block_id, DESIRED_RUNNING);
86    true
87}
88
89/// The desired state a block records, if any.
90pub(crate) fn desired_of(block: &Block) -> Option<String> {
91    let v = obj::meta_get_string(&block.meta, META_DESIRED, "");
92    (!v.is_empty()).then_some(v)
93}
94
95/// Dispatch to the reducer, mirror to SQLite and publish: what `agent.open` does for a block.
96async fn dispatch_all(state: &AppState, cmd: Command) -> Result<Vec<Event>, String> {
97    let events = crate::server::service::dispatch_to_reducer(state, cmd).await;
98    if let Some(msg) = events.iter().find_map(|e| match e {
99        Event::Error { message, .. } => Some(message.clone()),
100        _ => None,
101    }) {
102        return Err(msg);
103    }
104    for ev in &events {
105        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
106            tracing::warn!("agent attach: mstore apply failed: {e}");
107        }
108    }
109    crate::server::service::publish_events(state, &events);
110    Ok(events)
111}
112
113/// The controller an agent's pane runs. A container agent's turns are `docker exec`s of a subprocess
114/// controller, whatever its provider defaults to (claude's is persistent, which skips the container exec).
115pub(super) fn controller_type_of(agent: &crate::backend::storage::agents::AgentDefinition, provider: &providers::ProviderConfig) -> &'static str {
116    if agent.runtime().is_container() {
117        "subprocess"
118    } else {
119        provider.controller_type_str()
120    }
121}
122
123/// Register the block's controller when it has none (a pane the frontend made, or a parked block
124/// after a restart), resuming the agent's session. With `revive`, a controller whose process has
125/// ended is resynced too, which resumes it (a start, or an open with the setting on). `tab_id` is
126/// empty for a parked block.
127fn ensure_controller(
128    state: &AppState,
129    agent: &crate::backend::storage::agents::AgentDefinition,
130    provider: &providers::ProviderConfig,
131    block_id: &str,
132    tab_id: &str,
133    revive: bool,
134) -> Result<(), String> {
135    let ended = revive
136        && blockcontroller::get_block_controller_status(block_id)
137            .is_some_and(|s| s.shellprocstatus == blockcontroller::STATUS_DONE);
138    if blockcontroller::get_controller(block_id).is_some() && !ended {
139        return Ok(());
140    }
141    let mstore = &state.mstore;
142    let controller_type = controller_type_of(agent, provider);
143    let mut meta_update = obj::MetaMapType::new();
144    meta_update.insert("controller".to_string(), json!(controller_type));
145    meta_update.insert("agentProvider".to_string(), json!(&agent.provider));
146    let _ = crate::server::service::update_object_meta(mstore, &format!("block:{block_id}"), &meta_update);
147    // The launch is recorded before the resync: a controller can report its session id during it,
148    // and that capture finds the row by block (#3584).
149    record_agent_open_launch(mstore, &agent.id, block_id)?;
150    let block = mstore.must_get::<Block>(block_id).map_err(|e| format!("agent.open: reload block: {e}"))?;
151    let _ = blockcontroller::resync_controller(
152        &block,
153        tab_id,
154        None,
155        true,
156        true,
157        Some(state.broker.clone()),
158        Some(state.event_bus.clone()),
159        Some(mstore.clone()),
160        Some(state.filestore.clone()),
161        Some(state.id_store.clone()),
162        Some(state.identity_store.clone()),
163        mstore.shared_agent_registry(),
164        state.boot_id.clone(),
165        &state.auth_key,
166        Some(state.config_watcher.clone()),
167    );
168    Ok(())
169}
170
171/// Bring the window to the pane that shows `block_id` in `tab_id`: `block.reveal` makes it its pane's
172/// visible member and tells its window to restore, un-magnify and focus it; where that finds no open
173/// window, its tab is made active and its pane focused here.
174async fn focus_shown(state: &AppState, tab_id: &str, block_id: &str) {
175    let router = crate::server::notify_handlers::router_for(state);
176    if matches!(crate::server::notify_handlers::reveal_block(state, &router, block_id.to_string(), false).await, Ok(r) if r.found) {
177        return;
178    }
179    let (workspace_id, node_id) = {
180        let s = state.srv_state.lock().await;
181        let ws = s.workspaces.iter().find(|(_, w)| w.tab_ids.iter().any(|t| t == tab_id)).map(|(id, _)| id.clone());
182        let node = s
183            .tabs
184            .get(tab_id)
185            .and_then(|t| t.rootnode.as_ref())
186            .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, block_id))
187            .map(|n| n.id.clone());
188        (ws, node)
189    };
190    if let Some(workspace_id) = workspace_id {
191        if let Err(e) = dispatch_all(state, Command::SetActiveTab { workspace_id, tab_id: tab_id.to_string() }).await {
192            tracing::warn!(tab_id, "agent.open: could not activate the tab of the open agent: {e}");
193        }
194    }
195    if let Some(node_id) = node_id {
196        if let Err(e) = dispatch_all(state, Command::SetFocusedNode { tab_id: tab_id.to_string(), node_id }).await {
197            tracing::warn!(tab_id, block_id, "agent.open: could not focus the open agent's pane: {e}");
198        }
199    }
200}
201
202/// A new block made by a start: out of its tab at once, so it is the agent's parked block.
203pub(super) async fn park_new(state: &AppState, tab_id: &str, block_id: &str) -> Result<(), String> {
204    dispatch_all(state, Command::ParkBlock { tab_id: tab_id.to_string(), block_id: block_id.to_string() })
205        .await
206        .map(|_| ())
207        .map_err(|e| format!("agent.open: ParkBlock: {e}"))
208}
209
210/// What `agent.open` (or a start, `headless`) does when the agent already has a block. The agent has one
211/// pane: [`super::agent_block::decide_agent_pane`] says which, and every path that would add one asks it,
212/// so no open makes a second (task #5419):
213///   - in `tab_id`: that pane, as before (a start leaves it as it is);
214///   - parked: attach it to `tab_id` and place its pane, no new block (a start leaves it parked);
215///   - shown in another tab, window or not running: that pane, focused and restarted in place, no second one.
216///
217/// A pane being filled in (`into_block`, a layout import) never takes another's agent: the placeholder is
218/// left as a picker and the agent's pane is returned, when a window shows it (or it is parked).
219///
220/// `None`: nothing to reuse, the caller makes the block.
221pub(super) async fn reuse_existing_pane(
222    state: &AppState,
223    agent: &crate::backend::storage::agents::AgentDefinition,
224    provider: &providers::ProviderConfig,
225    cmd: &CommandAgentOpenData,
226    tab_id: &str,
227    headless: bool,
228    into_block: Option<&str>,
229) -> Result<Option<AgentOpenResult>, String> {
230    let mstore = &state.mstore;
231    let result = |block_id: &str, tab: &str, created_provider: &str| {
232        let status = blockcontroller::get_block_controller_status(block_id)
233            .map(|s| s.shellprocstatus)
234            .unwrap_or_else(|| "init".to_string());
235        AgentOpenResult {
236            block_id: block_id.to_string(),
237            tab_id: tab.to_string(),
238            agent_id: cmd.agent_id.clone(),
239            provider: created_provider.to_string(),
240            controller_type: controller_type_of(agent, provider).to_string(),
241            status,
242            created: false,
243        }
244    };
245
246    let found = match super::agent_block::decide_agent_pane(mstore, &agent.id)? {
247        super::agent_block::AgentPanePlan::Reuse(found) => found,
248        super::agent_block::AgentPanePlan::Create => return Ok(None),
249    };
250    let block_id = found.block.oid.clone();
251    // An open is a start: a pane whose process has ended is restarted in place.
252    let revive = true;
253    match found.tab_id {
254        Some(shown_in) if !tab_id.is_empty() && shown_in == tab_id => {
255            ensure_controller(state, agent, provider, &block_id, tab_id, revive)?;
256            set_desired(mstore, &block_id, DESIRED_RUNNING);
257            Ok(Some(result(&block_id, tab_id, &agent.provider)))
258        }
259        // A layout import fills a placeholder; it does not move or start an agent that is somewhere else.
260        // A pane in a workspace no window shows is saved contents, not a pane to keep: the import is the agent's pane now.
261        Some(shown_in) if into_block.is_some() => {
262            if super::agent_block::shown_tabs(mstore).contains(&shown_in) {
263                Ok(Some(result(&block_id, &shown_in, &agent.provider)))
264            } else {
265                Ok(None)
266            }
267        }
268        None if into_block.is_some() => Ok(Some(result(&block_id, "", &agent.provider))),
269        None => {
270            if headless {
271                ensure_controller(state, agent, provider, &block_id, "", true)?;
272                set_desired(mstore, &block_id, DESIRED_RUNNING);
273                return Ok(Some(result(&block_id, "", &agent.provider)));
274            }
275            dispatch_all(state, Command::AttachBlock { block_id: block_id.clone(), dst_tab_id: tab_id.to_string(), dst_index: u32::MAX })
276                .await
277                .map_err(|e| format!("agent.open: AttachBlock: {e}"))?;
278            let placement = super::pane::resolve_placement(
279                cmd.split_direction.as_deref(),
280                cmd.split_reference_block_id.as_deref(),
281                cmd.focus.unwrap_or(true),
282            );
283            if let Err(e) = crate::server::service::layout_intents::place_block(state, tab_id, &block_id, placement).await {
284                tracing::warn!("agent.open: placing the attached pane failed: {e}");
285            }
286            ensure_controller(state, agent, provider, &block_id, tab_id, true)?;
287            set_desired(mstore, &block_id, DESIRED_RUNNING);
288            Ok(Some(result(&block_id, tab_id, &agent.provider)))
289        }
290        Some(shown_in) => {
291            tracing::info!(agent = %agent.id, block_id = %block_id, tab_id = %shown_in, "agent.open: the agent already has a pane in another tab: reusing it");
292            ensure_controller(state, agent, provider, &block_id, &shown_in, revive)?;
293            set_desired(mstore, &block_id, DESIRED_RUNNING);
294            if !headless && cmd.focus.unwrap_or(true) {
295                focus_shown(state, &shown_in, &block_id).await;
296            }
297            Ok(Some(result(&block_id, &shown_in, &agent.provider)))
298        }
299    }
300}
301
302/// The tab `agent.open` works in, or the agent's existing pane when it has one (`Err`: nothing more to
303/// do). A start of a terminal-tier CLI is refused: its term view starts it, and a start
304/// has none. A start needs no tab to run an agent that already has a block, so with no tab left it only
305/// reuses that block; a first block still needs a tab.
306pub(super) async fn tab_or_reuse(
307    state: &AppState,
308    agent: &crate::backend::storage::agents::AgentDefinition,
309    provider: &providers::ProviderConfig,
310    cmd: &CommandAgentOpenData,
311    headless: bool,
312    into_block: Option<&str>,
313) -> Result<Result<String, AgentOpenResult>, String> {
314    if headless && provider.controller_type == providers::ControllerType::Terminal {
315        return Err(format!("agent.start: {} runs in a terminal pane and has no headless mode", agent.provider));
316    }
317    let tab_id = match super::resolve_tab_id(&state.mstore, cmd.tab_id.as_deref()) {
318        Ok(tab_id) => tab_id,
319        Err(e) if headless => return reuse_existing_pane(state, agent, provider, cmd, "", true, into_block).await?.map(Err).ok_or(e),
320        Err(e) => return Err(e),
321    };
322    Ok(match reuse_existing_pane(state, agent, provider, cmd, &tab_id, headless, into_block).await? {
323        Some(done) => Err(done),
324        None => Ok(tab_id),
325    })
326}
327
328/// Start the agent with no pane: its block (made and parked if it has none) with its process running
329/// and its session resumed. Returns the block. Admission, the spawn gate and the lease apply as for
330/// `agent.open`. Needs an active tab to create a first block in.
331pub(crate) async fn start_agent(state: &AppState, agent_id: &str) -> Result<String, String> {
332    // A start over the cap (or the host's commit limit) stops an idle agent with no view, or is refused.
333    crate::server::agent_lifecycle::admit_start(state, agent_id).await?;
334    start_admitted(state, agent_id).await
335}
336
337/// [`start_agent`] that never stops another agent to make room: over the cap or the commit limit it is
338/// refused (`Err("capacity: ...")`). Restart resume starts the agents that were running this way.
339pub(crate) async fn start_agent_without_eviction(state: &AppState, agent_id: &str) -> Result<String, String> {
340    crate::server::agent_lifecycle::admit_start_without_eviction(state, agent_id).await?;
341    start_admitted(state, agent_id).await
342}
343
344/// What a start tells `agent.open`: it makes no pane.
345pub(super) fn start_markers() -> obj::MetaMapType {
346    let mut marker = obj::MetaMapType::new();
347    marker.insert(START_PARKED.to_string(), json!(true));
348    marker
349}
350
351/// The start itself, once admitted: a failure gives the admission's room back.
352async fn start_admitted(state: &AppState, agent_id: &str) -> Result<String, String> {
353    let marker = start_markers();
354    let opened = super::agent_open::open_agent_inner(
355        state,
356        CommandAgentOpenData {
357            agent_id: agent_id.to_string(),
358            tab_id: None,
359            split_direction: None,
360            split_reference_block_id: None,
361            focus: Some(false),
362            into_block_id: None,
363        },
364        None,
365        marker,
366    )
367    .await
368    .map_err(|e| {
369        crate::server::agent_lifecycle::release_start(state, agent_id);
370        e
371    })?;
372    Ok(opened.block_id)
373}