1use agentmux_common::ipc::Command;
11
12use super::SagaCtx;
13use crate::backend::obj::{self, Block};
14use crate::server::AppState;
15
16pub(crate) fn enabled(state: &AppState) -> bool {
18 crate::backend::always_available::enabled(&state.config_watcher.get_full_config().settings.extra)
19}
20
21pub(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
34pub(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
45pub(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
76fn 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
91fn 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
105pub(crate) fn keeps_block(state: &AppState, block_id: &str) -> bool {
107 enabled(state) && is_parkable(state, block_id)
108}
109
110pub(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 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
146pub(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
165pub(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 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 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
230pub(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
259pub(crate) fn not_parked(block_ids: &[String], parked: &[String]) -> Vec<String> {
261 block_ids.iter().filter(|b| !parked.contains(b)).cloned().collect()
262}