Skip to main content

agentmux_srv/sagas/
park_agents.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Agents that outlive their pane (docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md §8, §9 P1):
5// with `agents:always_available` on, closing a pane, a tab or a workspace parks each agent's block
6// (`Command::ParkBlock`) before the close tears anything down, and the close then skips it: its
7// process keeps running and its block, with the transcript and session, stays for the next open.
8// Off, nothing here does anything and every close deletes the block as it always has.
9
10use agentmux_common::ipc::Command;
11
12use super::SagaCtx;
13use crate::backend::obj::{self, Block};
14use crate::server::AppState;
15
16/// Whether closing parks an agent's block (the `agents:always_available` setting).
17pub(crate) fn enabled(state: &AppState) -> bool {
18    crate::backend::always_available::enabled(&state.config_watcher.get_full_config().settings.extra)
19}
20
21/// The agent a block belongs to: the instance bound to the block (a block launched from a template
22/// keeps the template's id in `agentId` and binds its agent that way), else the agent `agentId` names.
23pub(crate) fn agent_of_block(state: &AppState, block_id: &str, block: &Block) -> Option<crate::backend::storage::agents::AgentInstance> {
24    if let Ok(Some(bound)) = state.mstore.instance_get_by_block_id(block_id) {
25        return Some(bound);
26    }
27    let named = obj::meta_get_string(&block.meta, "agentId", "");
28    if named.is_empty() {
29        return None;
30    }
31    state.mstore.instance_get(&named).ok().flatten()
32}
33
34/// An agent's pane block of an agent that still exists. A terminal, a browser or a drawer is not
35/// one, and neither is the block of a deleted agent: nothing would ever open it again.
36pub(crate) fn is_parkable(state: &AppState, block_id: &str) -> bool {
37    let Ok(Some(block)) = state.mstore.get::<Block>(block_id) else {
38        return false;
39    };
40    obj::meta_get_string(&block.meta, "view", "") == "agent"
41        && !obj::is_history_reader(&block.meta)
42        && agent_of_block(state, block_id, &block).is_some()
43}
44
45/// Of the blocks being closed, the ones that are extra blocks of their agent and so are closed, not
46/// parked. `batch` is each closing parkable block with its agent; `all` every agent block in a tab or
47/// parked with its agent; `runs` says whether a block has the agent's live process.
48///
49/// Layouts from before one block per agent can hold two blocks for an agent, and parking both would
50/// leave it two parked blocks. One block per agent survives the close: the one that runs the agent's
51/// process, else the first of them. A block of the agent outside this close stays, so when one runs it
52/// is the survivor and every closing block of that agent is extra, and when none runs the closing block
53/// that runs is parked beside it. Decided once for the whole close, so a tab or workspace close that
54/// covers both blocks keeps one of them.
55pub(super) fn extras_to_close(batch: &[(String, String)], all: &[(String, String)], runs: &dyn Fn(&str) -> bool) -> std::collections::HashSet<String> {
56    let mut extras = std::collections::HashSet::new();
57    let mut decided = std::collections::HashSet::new();
58    for (_, agent) in batch {
59        if !decided.insert(agent.as_str()) {
60            continue;
61        }
62        let closing: Vec<&str> = batch.iter().filter(|(_, a)| a == agent).map(|(b, _)| b.as_str()).collect();
63        let outside: Vec<&str> = all.iter().filter(|(b, a)| a == agent && !closing.contains(&b.as_str())).map(|(b, _)| b.as_str()).collect();
64        let keeper = if outside.is_empty() {
65            closing.iter().copied().find(|b| runs(b)).or_else(|| closing.first().copied())
66        } else if outside.iter().any(|b| runs(b)) {
67            None
68        } else {
69            closing.iter().copied().find(|b| runs(b))
70        };
71        extras.extend(closing.into_iter().filter(|b| Some(*b) != keeper).map(str::to_string));
72    }
73    extras
74}
75
76/// The closing blocks among `block_ids` that [`extras_to_close`] drops.
77fn extra_blocks(state: &AppState, block_ids: &[String]) -> std::collections::HashSet<String> {
78    let Ok(all_blocks) = crate::server::app_api::agent_block::blocks_in_tabs_or_parked(&state.mstore) else {
79        return std::collections::HashSet::new();
80    };
81    let agent_of = |block: &Block| agent_of_block(state, &block.oid, block).map(|i| i.id);
82    let all: Vec<(String, String)> = all_blocks.iter().filter_map(|(b, _)| Some((b.oid.clone(), agent_of(b)?))).collect();
83    let batch: Vec<(String, String)> = block_ids.iter().filter(|id| is_parkable(state, id)).filter_map(|id| all.iter().find(|(b, _)| b == id).cloned()).collect();
84    let runs = |id: &str| {
85        crate::backend::blockcontroller::get_controller(id)
86            .is_some_and(|c| c.get_runtime_status().shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING)
87    };
88    extras_to_close(&batch, &all, &runs)
89}
90
91/// An agent that is running when its pane closes is wanted running, so a restart brings it back
92/// (`restart_resume`); a block from before desired states has no record of it.
93fn record_running_as_desired(state: &AppState, block_id: &str) {
94    use crate::server::app_api::agent_attach::{desired_of, set_desired, DESIRED_RUNNING};
95    let Ok(Some(block)) = state.mstore.get::<Block>(block_id) else {
96        return;
97    };
98    let running = crate::backend::blockcontroller::get_controller(block_id)
99        .is_some_and(|c| c.get_runtime_status().shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING);
100    if running && desired_of(&block).is_none() {
101        set_desired(&state.mstore, block_id, DESIRED_RUNNING);
102    }
103}
104
105/// Whether a block that is closing now is kept: parkable, with the setting on.
106pub(crate) fn keeps_block(state: &AppState, block_id: &str) -> bool {
107    enabled(state) && is_parkable(state, block_id)
108}
109
110/// Park the agent blocks among `block_ids` (each in the tab the reducer has it in) and return the ids
111/// parked. A park the reducer refuses leaves that block to the close, which deletes it as before.
112/// `force` parks with the setting off too: an explicit detach.
113pub(crate) async fn park_agent_blocks(ctx: &SagaCtx<'_>, block_ids: &[String], force: bool) -> Vec<String> {
114    if !force && !enabled(ctx.state) {
115        return Vec::new();
116    }
117    let extras = if force { Default::default() } else { extra_blocks(ctx.state, block_ids) };
118    let mut parked = Vec::new();
119    for block_id in block_ids {
120        if !is_parkable(ctx.state, block_id) {
121            continue;
122        }
123        // An explicit detach parks whatever it is asked to; a close drops the extra block of an agent.
124        if extras.contains(block_id) {
125            tracing::info!(block_id = %block_id, "closing a second block of the same agent: it is closed, not parked");
126            continue;
127        }
128        record_running_as_desired(ctx.state, block_id);
129        let tab_id = match ctx.state.srv_state.lock().await.blocks.get(block_id) {
130            Some(b) if !b.tab_id.is_empty() => b.tab_id.clone(),
131            _ => continue,
132        };
133        match ctx.dispatch(Command::ParkBlock { tab_id: tab_id.clone(), block_id: block_id.clone() }).await {
134            Ok(_) => parked.push(block_id.clone()),
135            Err(reason) => tracing::warn!(
136                tab_id = %tab_id,
137                block_id = %block_id,
138                "[saga] park of an agent's block failed — it is closed instead: {}",
139                reason
140            ),
141        }
142    }
143    parked
144}
145
146/// A window that closes and is kept (a closed window of the workspace): park the agent blocks of its tabs
147/// (`block_ids`) so the close stops only what isn't an agent. A parked block keeps its layout leaf: parking
148/// leaves the tab's tree alone, and the tree prunes only blocks that are gone, so the window reopens with
149/// its agents where they were (`reattach_window_agents`). Returns the ids parked.
150pub(crate) async fn park_window_agents(state: &AppState, workspace_id: &str, block_ids: &[String]) -> Vec<String> {
151    if !enabled(state) {
152        return Vec::new();
153    }
154    let saga_id = super::alloc_saga_id(state);
155    let input = serde_json::json!({ "workspace_id": workspace_id, "block_count": block_ids.len() });
156    if super::emit_saga_started(state, saga_id, "close_window_park", input).await.is_err() {
157        return Vec::new();
158    }
159    let ctx = SagaCtx::new(state, saga_id);
160    let parked = park_agent_blocks(&ctx, block_ids, false).await;
161    super::emit_terminal(state, saga_id, super::SagaTerminal::Completed).await;
162    parked
163}
164
165/// A closed window reopening: the agent blocks it parked at its close (`parked`, from its closed-window
166/// record) go back into the tab they were parked from, where their layout leaf still is. A block that is
167/// not parked any more (its agent was opened elsewhere, or deleted) is not brought back, and its leaf is
168/// removed from the window's layout so the window doesn't show the agent twice. A block already back in
169/// one of its tabs (the reopen is tried again until the window shows) is left as it is. Returns how many
170/// came back.
171pub(crate) async fn reattach_window_agents(state: &AppState, workspace_id: &str, parked: &[String]) -> usize {
172    use crate::persist_subscriber::parked::{PARKED_FROM_TAB_META_KEY, PARKED_META_KEY};
173    if parked.is_empty() {
174        return 0;
175    }
176    let Ok(Some(ws)) = state.mstore.get::<obj::Workspace>(workspace_id) else {
177        return 0;
178    };
179    let tabs: Vec<String> = ws.tabids.iter().chain(ws.pinnedtabids.iter()).cloned().collect();
180    let saga_id = super::alloc_saga_id(state);
181    let input = serde_json::json!({ "workspace_id": workspace_id, "parked": parked });
182    if super::emit_saga_started(state, saga_id, "reopen_window_attach", input).await.is_err() {
183        return 0;
184    }
185    let ctx = SagaCtx::new(state, saga_id);
186    let mut back = 0;
187    for block_id in parked {
188        let home = match state.mstore.get::<Block>(block_id) {
189            Ok(Some(b)) if obj::meta_get_bool(&b.meta, PARKED_META_KEY, false) => {
190                Some(obj::meta_get_string(&b.meta, PARKED_FROM_TAB_META_KEY, "")).filter(|t| tabs.contains(t))
191            }
192            _ => None,
193        };
194        if let Some(tab_id) = home {
195            match ctx.dispatch(Command::AttachBlock { block_id: block_id.clone(), dst_tab_id: tab_id.clone(), dst_index: u32::MAX }).await {
196                Ok(_) => {
197                    back += 1;
198                    continue;
199                }
200                Err(reason) => tracing::warn!(block_id = %block_id, tab_id = %tab_id, "reopen window: attaching a parked agent failed: {reason}"),
201            }
202        }
203        // Already back in one of the window's tabs (a reopen that is tried again): it keeps its leaf.
204        let in_window = state.srv_state.lock().await.blocks.get(block_id).is_some_and(|b| tabs.contains(&b.tab_id));
205        if in_window {
206            continue;
207        }
208        // Not coming back: its leaf must not stay in the window's tabs.
209        for tab_id in &tabs {
210            let has_leaf = state
211                .srv_state
212                .lock()
213                .await
214                .tabs
215                .get(tab_id)
216                .and_then(|t| t.rootnode.as_ref())
217                .is_some_and(|root| crate::backend::layout::find_leaf_containing_block(root, block_id).is_some());
218            if has_leaf {
219                let cmd = Command::LayoutDeleteNodeByBlock { tab_id: tab_id.clone(), block_id: block_id.clone(), correlation_id: String::new() };
220                if let Err(reason) = ctx.dispatch(cmd).await {
221                    tracing::warn!(block_id = %block_id, tab_id = %tab_id, "reopen window: removing a stale agent leaf failed: {reason}");
222                }
223            }
224        }
225    }
226    super::emit_terminal(state, saga_id, super::SagaTerminal::Completed).await;
227    back
228}
229
230/// Delete every parked block of the agent `agent_id`, stopping its process first: deleting the agent
231/// is the one thing that deletes its block. A block is the agent's through `agent_of_block`, so
232/// deleting a template leaves the blocks of the agents launched from it. Returns how many went. A block that is shown in a tab is
233/// not touched, as before.
234pub(crate) async fn delete_parked_blocks_of(state: &AppState, agent_id: &str) -> usize {
235    let parked: Vec<String> = match state.mstore.get_all::<Block>() {
236        Ok(blocks) => blocks
237            .into_iter()
238            .filter(|b| {
239                obj::meta_get_bool(&b.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false)
240                    && agent_of_block(state, &b.oid, b).is_some_and(|i| i.id == agent_id)
241            })
242            .map(|b| b.oid)
243            .collect(),
244        Err(e) => {
245            tracing::warn!(agent_id, "delete agent: could not list its parked blocks: {e}");
246            return 0;
247        }
248    };
249    let mut deleted = 0;
250    for block_id in parked {
251        match super::delete_block::run(state, String::new(), block_id.clone()).await {
252            Ok(_) => deleted += 1,
253            Err(e) => tracing::warn!(agent_id, block_id = %block_id, "delete agent: its parked block stays: {e}"),
254        }
255    }
256    deleted
257}
258
259/// `block_ids` without the parked ones: what the close still stops and deletes.
260pub(crate) fn not_parked(block_ids: &[String], parked: &[String]) -> Vec<String> {
261    block_ids.iter().filter(|b| !parked.contains(b)).cloned().collect()
262}