Skip to main content

agentmux_srv/server/app_api/
agent_block.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's block, found by the agent and not by a tab
5//! (`docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md` §3.1, §3.3 rule 1): one block per
6//! agent, in a tab or parked in none. Everything that wants "the agent's pane" asks here
7//! instead of scanning one tab, so a pane in another window, or none, is still found.
8
9use crate::backend::blockcontroller;
10use crate::backend::obj::{self, Block, Tab, Window, Workspace};
11use crate::backend::storage::store::Store;
12
13use super::{resolve_tab_id, resolve_tab_id_for_block};
14
15/// An agent's block and the tab it is in. `tab_id` is `None` for a parked block.
16#[derive(Debug, Clone)]
17pub(crate) struct AgentBlock {
18    pub block: Block,
19    pub tab_id: Option<String>,
20}
21
22/// A block launched from a template keeps the template's id in `agentId` and binds its agent through
23/// `agentInstanceId`, so the bound instance counts too.
24fn is_agent_block_of(mstore: &Store, block: &Block, agent_uid: &str) -> bool {
25    !obj::is_history_reader(&block.meta)
26        && (["agentId", "agent:id"].iter().any(|key| obj::meta_get_string(&block.meta, key, "") == agent_uid)
27            || (obj::meta_get_string(&block.meta, "view", "") == "agent"
28                && mstore.instance_get_by_block_id(&block.oid).ok().flatten().is_some_and(|i| i.id == agent_uid)))
29}
30
31fn is_parked(block: &Block) -> bool {
32    obj::meta_get_bool(&block.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false)
33}
34
35/// Whether the block failed to open because the agent's conversation is open in another pane
36/// (`open_in_other_pane`): it is not the one that holds the conversation.
37fn lost_the_conversation(block: &Block) -> bool {
38    block.meta.get(blockcontroller::core::META_LAST_FAILURE).and_then(|f| f.get("code")).and_then(|c| c.as_str()) == Some("open_in_other_pane")
39}
40
41/// Whether the block runs its agent now: a controller that has not ended. A stopped one stays
42/// registered, so presence alone would not tell it from a running one.
43fn controller_is_live(block_id: &str) -> bool {
44    blockcontroller::get_controller(block_id)
45        .is_some_and(|c| c.get_runtime_status().shellprocstatus != blockcontroller::STATUS_DONE)
46}
47
48/// The block of the agent with this UID, in any tab or parked. `None` when it has none.
49///
50/// Only a block that is in a tab or marked parked counts: an unmarked block in no tab is an
51/// orphan boot drops (`persist.rs`), which `AttachBlock` could not attach. An agent should have
52/// one block; [`agent_blocks_by_uid`] ranks them when old layouts left several, and this is its first.
53pub(crate) fn find_agent_block_by_uid(mstore: &Store, agent_uid: &str) -> Result<Option<AgentBlock>, String> {
54    Ok(agent_blocks_by_uid(mstore, agent_uid)?.into_iter().next())
55}
56
57/// Every block of the agent with this UID that is in a tab or parked, the one that keeps the agent
58/// first. One that was refused for a conversation open in another pane comes last (another block holds
59/// it), then the one with a live controller wins, then one in a tab over a parked one, one in a tab a
60/// window shows over one in a closed workspace, then the one the agent last launched (its newest), then
61/// the lowest id (so the answer is stable).
62pub(crate) fn agent_blocks_by_uid(mstore: &Store, agent_uid: &str) -> Result<Vec<AgentBlock>, String> {
63    let agent_uid = agent_uid.trim();
64    if agent_uid.is_empty() {
65        return Ok(Vec::new());
66    }
67    let mut found: Vec<Block> = mstore
68        .get_all::<Block>()
69        .map_err(|e| format!("find_agent_block_by_uid: list blocks: {e}"))?
70        .into_iter()
71        .filter(|b| is_agent_block_of(mstore, b, agent_uid))
72        .collect();
73    if found.is_empty() {
74        return Ok(Vec::new());
75    }
76    let tabs: Vec<Tab> = mstore.get_all::<Tab>().map_err(|e| format!("find_agent_block_by_uid: list tabs: {e}"))?;
77    let tab_of = |block: &Block| tabs.iter().find(|t| t.blockids.iter().any(|id| id == &block.oid)).map(|t| t.oid.clone());
78    found.retain(|b| is_parked(b) || tab_of(b).is_some());
79    let last_launched = mstore.instance_get(agent_uid).ok().flatten().map(|i| i.block_id).unwrap_or_default();
80    let shown = shown_tabs(mstore);
81    let hidden = |b: &Block| tab_of(b).is_some_and(|t| !shown.contains(&t));
82    found.sort_by_key(|b| (lost_the_conversation(b), !controller_is_live(&b.oid), tab_of(b).is_none(), hidden(b), b.oid != last_launched, b.oid.clone()));
83    Ok(found
84        .into_iter()
85        .map(|block| {
86            let tab_id = tab_of(&block);
87            AgentBlock { block, tab_id }
88        })
89        .collect())
90}
91
92/// The tabs windows show now (and those restored windows have waiting to open). A tab of a workspace no
93/// window shows is saved contents: it comes back only by opening that workspace.
94pub(crate) fn shown_tabs(mstore: &Store) -> std::collections::HashSet<String> {
95    let mut shown = crate::server::service::session_closed::open_workspaces(mstore);
96    shown.extend(crate::server::service::session_windows::waiting_workspaces(mstore));
97    shown
98        .iter()
99        .filter_map(|ws| mstore.get::<Workspace>(ws).ok().flatten())
100        .flat_map(|ws| ws.pinnedtabids.into_iter().chain(ws.tabids))
101        .collect()
102}
103
104/// What an agent's open does about its pane: the one rule for every path that would add an agent pane
105/// (`agent.open`, a start, a layout import, a restore), so none of them makes a second.
106pub(crate) enum AgentPanePlan {
107    /// The agent has a pane (or a parked block): use it, running or not.
108    Reuse(AgentBlock),
109    /// It has none: make one, in the caller's own tab.
110    Create,
111}
112
113/// Where the agent's pane goes: its existing block, wherever it is, else a new one.
114pub(crate) fn decide_agent_pane(mstore: &Store, agent_uid: &str) -> Result<AgentPanePlan, String> {
115    Ok(match find_agent_block_by_uid(mstore, agent_uid)? {
116        Some(found) => AgentPanePlan::Reuse(found),
117        None => AgentPanePlan::Create,
118    })
119}
120
121/// An open by an agent that names no tab goes to the tab that agent is in (a parked one, its home tab), not
122/// to whichever tab the person has active: the seat rule has a leader open agents into its own tab.
123pub(crate) fn default_to_callers_tab(mstore: &Store, caller: Option<&crate::server::caller::Caller>, cmd: &mut crate::backend::rpc_types::CommandAgentOpenData) {
124    if cmd.tab_id.is_some() {
125        return;
126    }
127    let Some(uid) = caller.and_then(crate::server::caller::Caller::uid) else { return };
128    let Ok(Some(own)) = find_agent_block_by_uid(mstore, uid) else { return };
129    cmd.tab_id = own.tab_id.or_else(|| resolve_tab_id_or_active(mstore, &own.block.oid).ok());
130}
131
132/// Where a tab is, for a person: "Window name > Tab name" (the window by its name, else its number).
133pub(crate) fn describe_tab(mstore: &Store, tab_id: &str) -> String {
134    let tab_name = mstore.get::<Tab>(tab_id).ok().flatten().map(|t| t.name).filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "a tab".to_string());
135    let workspace = mstore
136        .get_all::<Workspace>()
137        .ok()
138        .and_then(|all| all.into_iter().find(|w| w.tabids.iter().any(|t| t == tab_id)));
139    let window = workspace.and_then(|w| {
140        let windows = mstore.get_all::<Window>().ok()?;
141        let index = windows.iter().position(|win| win.workspaceid == w.oid)?;
142        Some(crate::server::service::session_windows::window_name(&windows[index]).unwrap_or_else(|| format!("Window {}", index + 1)))
143    });
144    match window {
145        Some(window) => format!("{window} > {tab_name}"),
146        None => tab_name,
147    }
148}
149
150/// Every block that is in a tab or parked, each with its tab (`None` when parked). The agent readers
151/// that used to walk tabs' `blockids` use this, so a headless agent's parked block is not missing
152/// from them. An unmarked block in no tab is an orphan and is left out.
153pub(crate) fn blocks_in_tabs_or_parked(mstore: &Store) -> Result<Vec<(Block, Option<String>)>, String> {
154    let tabs: Vec<Tab> = mstore.get_all::<Tab>().map_err(|e| format!("list tabs: {e}"))?;
155    let mut seen = std::collections::HashSet::new();
156    let mut out = Vec::new();
157    for tab in &tabs {
158        for block_id in &tab.blockids {
159            if let Ok(Some(block)) = mstore.get::<Block>(block_id) {
160                if !obj::is_history_reader(&block.meta) && seen.insert(block.oid.clone()) {
161                    out.push((block, Some(tab.oid.clone())));
162                }
163            }
164        }
165    }
166    for block in mstore.get_all::<Block>().map_err(|e| format!("list blocks: {e}"))? {
167        if is_parked(&block) && !obj::is_history_reader(&block.meta) && seen.insert(block.oid.clone()) {
168            out.push((block, None));
169        }
170    }
171    Ok(out)
172}
173
174/// [`resolve_tab_id_for_block`], and for a parked block, which no tab holds, its agent's home tab
175/// ([`parked_agents_tab`]) and only then the active tab: a headless agent that spawns or opens panes
176/// has no tab of its own to use.
177pub(crate) fn resolve_tab_id_or_active(mstore: &Store, block_id: &str) -> Result<String, String> {
178    match resolve_tab_id_for_block(mstore, block_id) {
179        Ok(tab_id) => Ok(tab_id),
180        Err(e) => match mstore.get::<Block>(block_id) {
181            Ok(Some(block)) if is_parked(&block) => match parked_agents_tab(mstore, &block) {
182                Some(tab_id) => Ok(tab_id),
183                None => resolve_tab_id(mstore, None),
184            },
185            _ => Err(e),
186        },
187    }
188}
189
190/// The tab a parked agent works from, so its workers open beside it and not in whatever tab the user
191/// is looking at: the tab its pane was parked from, else a tab one of its open workers is in.
192fn parked_agents_tab(mstore: &Store, block: &Block) -> Option<String> {
193    let from = obj::meta_get_string(&block.meta, crate::persist_subscriber::parked::PARKED_FROM_TAB_META_KEY, "");
194    if !from.is_empty() && mstore.get::<Tab>(&from).ok().flatten().is_some() {
195        return Some(from);
196    }
197    let agent = obj::meta_get_string(&block.meta, "agentId", "");
198    super::agent_spawn::workers_of(mstore, &agent).iter().find_map(|w| resolve_tab_id_for_block(mstore, &w.block_id).ok())
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::backend::obj::{MetaMapType, Workspace};
205
206    fn insert_tab(store: &Store, blocks: &[&str]) -> String {
207        let mut tab = Tab { oid: uuid::Uuid::new_v4().to_string(), blockids: blocks.iter().map(|b| b.to_string()).collect(), ..Default::default() };
208        store.insert(&mut tab).unwrap();
209        tab.oid
210    }
211
212    fn insert_block(store: &Store, agent: &str, parked: bool) -> String {
213        let mut meta = MetaMapType::new();
214        meta.insert("agentId".to_string(), serde_json::json!(agent));
215        if parked {
216            meta.insert(crate::persist_subscriber::parked::PARKED_META_KEY.to_string(), serde_json::json!(true));
217        }
218        let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
219        store.insert(&mut block).unwrap();
220        block.oid
221    }
222
223    #[test]
224    fn finds_the_agents_block_in_any_tab_or_parked_and_only_its_own() {
225        let store = Store::open_in_memory().unwrap();
226        let (shown, parked, other) = (insert_block(&store, "ann", false), insert_block(&store, "bob", true), insert_block(&store, "cy", false));
227        let tab = insert_tab(&store, &[&shown, &other]);
228        let ann = find_agent_block_by_uid(&store, "ann").unwrap().unwrap();
229        assert_eq!((ann.block.oid.as_str(), ann.tab_id.as_deref()), (shown.as_str(), Some(tab.as_str())));
230        let bob = find_agent_block_by_uid(&store, "bob").unwrap().unwrap();
231        assert_eq!((bob.block.oid.as_str(), bob.tab_id), (parked.as_str(), None));
232        assert!(find_agent_block_by_uid(&store, "nobody").unwrap().is_none());
233        assert!(find_agent_block_by_uid(&store, "  ").unwrap().is_none());
234    }
235
236    /// A block launched from a template keeps the template's id in `agentId`; its agent is the bound instance.
237    #[test]
238    fn a_template_launched_agents_block_is_found_through_its_binding() {
239        use crate::backend::storage::agents::AgentInstance;
240        let store = Store::open_in_memory().unwrap();
241        let mut meta = MetaMapType::new();
242        meta.insert("view".to_string(), serde_json::json!("agent"));
243        meta.insert("agentId".to_string(), serde_json::json!("tmpl"));
244        meta.insert("agentInstanceId".to_string(), serde_json::json!("inst"));
245        let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
246        store.insert(&mut block).unwrap();
247        let tab = insert_tab(&store, &[&block.oid]);
248        assert!(find_agent_block_by_uid(&store, "inst").unwrap().is_none(), "no agent is bound yet");
249
250        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
251            "id": "inst", "slug": "inst", "name": "inst", "icon": "robot", "provider": "claude", "description": "", "created_at": 1,
252        }))
253        .unwrap();
254        store.agent_def_insert(&mut def).unwrap();
255        store
256            .instance_create(&AgentInstance {
257                session_id: "sess".to_string(),
258                ..crate::backend::storage::agents::test_agent_instance("inst", "inst", &block.oid, 1000)
259            })
260            .unwrap();
261        let found = find_agent_block_by_uid(&store, "inst").unwrap().unwrap();
262        assert_eq!((found.block.oid.as_str(), found.tab_id.as_deref()), (block.oid.as_str(), Some(tab.as_str())));
263    }
264
265    #[test]
266    fn the_blocks_in_tabs_or_parked_leave_out_an_unmarked_orphan() {
267        let store = Store::open_in_memory().unwrap();
268        let (shown, parked, orphan) = (insert_block(&store, "ann", false), insert_block(&store, "bob", true), insert_block(&store, "cy", false));
269        let tab = insert_tab(&store, &[&shown]);
270        let mut all = blocks_in_tabs_or_parked(&store).unwrap();
271        all.sort_by(|a, b| a.0.oid.cmp(&b.0.oid));
272        let mut want = vec![(shown, Some(tab)), (parked, None)];
273        want.sort_by(|a, b| a.0.cmp(&b.0));
274        assert_eq!(all.iter().map(|(b, t)| (b.oid.clone(), t.clone())).collect::<Vec<_>>(), want);
275        assert!(all.iter().all(|(b, _)| b.oid != orphan));
276    }
277
278    /// Two blocks of one agent (an old layout): the one refused for a conversation open in another pane does
279    /// not hold it, so a start resumes the other. The refused block's id sorts first, so without the rule the
280    /// last tie-break (the id) would pick it.
281    #[test]
282    fn a_block_refused_for_an_open_conversation_is_not_picked_over_the_holder() {
283        let store = Store::open_in_memory().unwrap();
284        let with_id = |oid: &str| {
285            let mut meta = MetaMapType::new();
286            meta.insert("agentId".to_string(), serde_json::json!("ann"));
287            let mut block = Block { oid: oid.to_string(), meta, ..Default::default() };
288            store.insert(&mut block).unwrap();
289            block
290        };
291        let holder = with_id("b-holder").oid;
292        let mut refused = with_id("a-refused");
293        refused.meta.insert(blockcontroller::core::META_LAST_FAILURE.to_string(), serde_json::json!({ "code": "open_in_other_pane", "holderBlockId": holder }));
294        store.update(&mut refused).unwrap();
295        insert_tab(&store, &[&holder, &refused.oid]);
296        let found = find_agent_block_by_uid(&store, "ann").unwrap().unwrap();
297        assert_eq!(found.block.oid, holder);
298    }
299
300    /// The history reader carries the agent's id like its pane does, and is not the pane: with the agent
301    /// parked, a reader in a tab must not be taken for it.
302    #[test]
303    fn a_history_reader_is_not_the_agents_block() {
304        let store = Store::open_in_memory().unwrap();
305        let parked = insert_block(&store, "ann", true);
306        let mut meta = MetaMapType::new();
307        meta.insert("view".to_string(), serde_json::json!("agent"));
308        meta.insert("agentId".to_string(), serde_json::json!("ann"));
309        meta.insert(obj::HISTORY_READER_META_KEY.to_string(), serde_json::json!("ann"));
310        let mut reader = Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
311        store.insert(&mut reader).unwrap();
312        insert_tab(&store, &[&reader.oid]);
313        let found = find_agent_block_by_uid(&store, "ann").unwrap().unwrap();
314        assert_eq!((found.block.oid.as_str(), found.tab_id), (parked.as_str(), None), "the parked block, not the reader in the tab");
315        assert!(blocks_in_tabs_or_parked(&store).unwrap().iter().all(|(b, _)| b.oid != reader.oid));
316        assert!(obj::is_history_reader(&reader.meta));
317        assert!(!obj::is_history_reader(&MetaMapType::new()));
318    }
319
320    /// `find_agent_block` (the open path's "this tab already has the agent's pane") skips a reader of
321    /// the agent too, and still finds the live pane beside it.
322    #[test]
323    fn the_tab_lookup_does_not_take_a_history_reader_for_the_agents_pane() {
324        let store = Store::open_in_memory().unwrap();
325        let mut meta = MetaMapType::new();
326        meta.insert("view".to_string(), serde_json::json!("agent"));
327        meta.insert("agentId".to_string(), serde_json::json!("ann"));
328        meta.insert(obj::HISTORY_READER_META_KEY.to_string(), serde_json::json!("ann"));
329        let mut reader = Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
330        store.insert(&mut reader).unwrap();
331        let tab = insert_tab(&store, &[&reader.oid]);
332        assert!(super::super::find_agent_block(&store, &tab, "ann").unwrap().is_none(), "a reader alone is no pane");
333        let pane = insert_block(&store, "ann", false);
334        let tab = insert_tab(&store, &[&reader.oid, &pane]);
335        assert_eq!(super::super::find_agent_block(&store, &tab, "ann").unwrap().unwrap().oid, pane);
336    }
337
338    #[test]
339    fn an_unmarked_block_in_no_tab_is_not_the_agents_block() {
340        let store = Store::open_in_memory().unwrap();
341        let orphan = insert_block(&store, "ann", false);
342        assert!(find_agent_block_by_uid(&store, "ann").unwrap().is_none(), "{orphan} is an orphan boot drops");
343        let parked = insert_block(&store, "ann", true);
344        let found = find_agent_block_by_uid(&store, "ann").unwrap().unwrap();
345        assert_eq!(found.block.oid, parked);
346    }
347
348    #[test]
349    fn of_two_blocks_for_one_agent_the_one_in_a_tab_wins_over_a_parked_one() {
350        let store = Store::open_in_memory().unwrap();
351        let (parked, shown) = (insert_block(&store, "ann", true), insert_block(&store, "ann", false));
352        insert_tab(&store, &[&shown]);
353        let found = find_agent_block_by_uid(&store, "ann").unwrap().unwrap();
354        assert_eq!(found.block.oid, shown);
355        assert_ne!(found.block.oid, parked);
356    }
357
358    #[test]
359    fn a_parked_agent_works_from_the_tab_it_was_parked_from_not_the_active_one() {
360        let store = Store::open_in_memory().unwrap();
361        let (team, active) = (insert_tab(&store, &[]), insert_tab(&store, &[]));
362        let mut ws = Workspace { oid: uuid::Uuid::new_v4().to_string(), tabids: vec![team.clone(), active.clone()], activetabid: active.clone(), ..Default::default() };
363        store.insert(&mut ws).unwrap();
364        let parked = insert_block(&store, "ann", true);
365        assert_eq!(resolve_tab_id_or_active(&store, &parked).unwrap(), active, "no home tab recorded: the active one");
366        let mut block = store.get::<Block>(&parked).unwrap().unwrap();
367        block.meta.insert(crate::persist_subscriber::parked::PARKED_FROM_TAB_META_KEY.to_string(), serde_json::json!(team));
368        store.update(&mut block).unwrap();
369        assert_eq!(resolve_tab_id_or_active(&store, &parked).unwrap(), team);
370        block.meta.insert(crate::persist_subscriber::parked::PARKED_FROM_TAB_META_KEY.to_string(), serde_json::json!("gone"));
371        store.update(&mut block).unwrap();
372        assert_eq!(resolve_tab_id_or_active(&store, &parked).unwrap(), active, "a tab that is gone is not a home");
373    }
374
375    #[test]
376    fn a_parked_agent_with_no_recorded_tab_works_from_the_tab_of_its_open_worker() {
377        let store = Store::open_in_memory().unwrap();
378        let (team, active) = (insert_tab(&store, &[]), insert_tab(&store, &[]));
379        let mut ws = Workspace { oid: uuid::Uuid::new_v4().to_string(), tabids: vec![team.clone(), active.clone()], activetabid: active, ..Default::default() };
380        store.insert(&mut ws).unwrap();
381        let parked = insert_block(&store, "lead", true);
382        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
383            "id": "wrk", "slug": "wrk", "name": "Wrk", "icon": "robot", "provider": "claude", "description": "", "created_at": 1,
384        }))
385        .unwrap();
386        store.agent_def_insert(&mut def).unwrap();
387        let mut worker = Block { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
388        worker.meta.insert("agentId".to_string(), serde_json::json!("wrk"));
389        worker.meta.insert(crate::server::app_api::agent_spawn::COACHED_BY_META_KEY.to_string(), serde_json::json!({ "id": "lead" }));
390        store.insert(&mut worker).unwrap();
391        let mut tab = store.get::<Tab>(&team).unwrap().unwrap();
392        tab.blockids.push(worker.oid.clone());
393        store.update(&mut tab).unwrap();
394        assert_eq!(resolve_tab_id_or_active(&store, &parked).unwrap(), team);
395    }
396
397    #[test]
398    fn a_parked_block_resolves_to_the_active_tab_and_an_unmarked_orphan_does_not() {
399        let store = Store::open_in_memory().unwrap();
400        let tab = insert_tab(&store, &[]);
401        let mut ws = Workspace { oid: uuid::Uuid::new_v4().to_string(), tabids: vec![tab.clone()], activetabid: tab.clone(), ..Default::default() };
402        store.insert(&mut ws).unwrap();
403        let (parked, orphan) = (insert_block(&store, "ann", true), insert_block(&store, "bob", false));
404        assert_eq!(resolve_tab_id_or_active(&store, &parked).unwrap(), tab);
405        assert!(resolve_tab_id_or_active(&store, &orphan).is_err());
406    }
407}