Skip to main content

agentmux_srv/server/service/
introspect.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent-facing introspection: `AgentContext` resolution plus the read-only
5//! window → workspace → tab → pane snapshots that back `/api/v1/self`,
6//! `/api/v1/layout`, and the naming verbs. Pure mstore reads — no reducer.
7
8use serde_json::json;
9
10use crate::backend::obj::*;
11use crate::backend::storage::store::Store;
12
13/// The agent pane's place in the object tree, resolved from its block id.
14/// Powers `GET /api/v1/self` and lets naming verbs default to "my own X".
15#[derive(Debug, serde::Serialize)]
16pub(crate) struct AgentContext {
17    pub block_id: String,
18    pub block_title: String,
19    pub tab_id: String,
20    pub tab_name: String,
21    pub window_id: Option<String>,
22    pub window_name: String,
23    pub workspace_id: Option<String>,
24    pub workspace_name: String,
25    /// The pane is pinned to its window: every tab shows it, and `tab_id` is its own tab.
26    #[serde(skip_serializing_if = "std::ops::Not::not")]
27    pub pinned: bool,
28}
29
30/// Find the id of the workspace that owns `tab_id` (in `tabids` or
31/// `pinnedtabids`), or `None` if no workspace references it.
32pub(crate) fn workspace_id_for_tab(store: &Store, tab_id: &str) -> Option<String> {
33    store
34        .get_all::<Workspace>()
35        .unwrap_or_default()
36        .into_iter()
37        .find(|w| {
38            w.tabids.iter().any(|t| t == tab_id) || w.pinnedtabids.iter().any(|t| t == tab_id)
39        })
40        .map(|w| w.oid)
41}
42
43/// Read-only snapshot of the window → workspace → tab → pane tree, for agent
44/// introspection (`GET /api/v1/layout`). Pure mstore reads — no reducer, so
45/// it's hermetic and safe. Lookups use linear scans (a handful of objects).
46pub(crate) fn agent_layout(store: &Store) -> serde_json::Value {
47    let windows = store.get_all::<Window>().unwrap_or_default();
48    let workspaces = store.get_all::<Workspace>().unwrap_or_default();
49    let tabs = store.get_all::<Tab>().unwrap_or_default();
50    let blocks = store.get_all::<Block>().unwrap_or_default();
51
52    let panes_of = |tab: &Tab| -> Vec<serde_json::Value> {
53        // What fraction of the tab each docked pane has (`pane_share`).
54        let shares = store
55            .get::<LayoutState>(&tab.layoutstate)
56            .ok()
57            .flatten()
58            .and_then(|l| l.rootnode)
59            .map(|root| super::pane_share::shares(&root))
60            .unwrap_or_default();
61        tab.blockids
62            .iter()
63            .filter_map(|bid| blocks.iter().find(|b| &b.oid == bid))
64            .map(|b| {
65                let mut pane = json!({
66                    "block_id": b.oid,
67                    "view": meta_get_string(&b.meta, "view", ""),
68                    "title": meta_get_string(&b.meta, "frame:title", ""),
69                });
70                if let Some(share) = shares.get(&b.oid) {
71                    pane["share"] = json!(super::pane_share::rounded(*share));
72                }
73                // A hibernated browser pane: its page reloads on the next
74                // Browser call (SPEC_BROWSER_PANE_HIBERNATION_2026_10_20.md).
75                if b
76                    .meta
77                    .get(crate::server::browser_hibernation::SLEEP_META_KEY)
78                    .is_some_and(|v| v.is_object())
79                {
80                    pane["hibernated"] = json!(true);
81                }
82                // Who drives a browser pane: an agent's id, or `person` (docs/specs/SPEC_BROWSER_RETAKE_AND_COMMANDEER_2026_11_04.md §2.1).
83                if b.meta.get("view").and_then(|v| v.as_str()) == Some("browser") {
84                    if let Some(driver) = crate::server::browser_owner::driver_of(&b.meta) {
85                        pane["driver"] = json!(driver);
86                    }
87                }
88                pane
89            })
90            .collect()
91    };
92
93    let windows_json: Vec<serde_json::Value> = windows
94        .iter()
95        .map(|w| {
96            let ws = workspaces.iter().find(|x| x.oid == w.workspaceid);
97            let tabs_json: Vec<serde_json::Value> = ws
98                .map(|ws| {
99                    // Pinned tabs render first, then the regular tab order.
100                    ws.pinnedtabids
101                        .iter()
102                        .chain(ws.tabids.iter())
103                        .filter_map(|tid| tabs.iter().find(|t| &t.oid == tid))
104                        .map(|t| {
105                            json!({
106                                "tab_id": t.oid,
107                                "name": t.name,
108                                "active": ws.activetabid == t.oid,
109                                "panes": panes_of(t),
110                            })
111                        })
112                        .collect()
113                })
114                .unwrap_or_default();
115            let mut window = json!({
116                "window_id": w.oid,
117                "name": meta_get_string(&w.meta, "window:displayname", ""),
118                "workspace_id": w.workspaceid,
119                "workspace_name": ws.map(|x| x.name.clone()).unwrap_or_default(),
120                "tabs": tabs_json,
121            });
122            // The pane pinned to the window shows in every tab: it is a pane of its own tab, and is named here too.
123            let pinned = ws.map(|ws| pinned_panes(ws, &blocks)).unwrap_or_default();
124            if !pinned.is_empty() {
125                window["pinned"] = json!(pinned);
126            }
127            window
128        })
129        .collect();
130
131    json!({ "windows": windows_json })
132}
133
134/// The window's pinned panes: the pane, its view and its own tab.
135fn pinned_panes(ws: &Workspace, blocks: &[Block]) -> Vec<serde_json::Value> {
136    let mut pins: Vec<&agentmux_common::PinRecord> = ws.pins.iter().collect();
137    pins.sort_by_key(|p| p.order);
138    pins.iter()
139        .map(|p| {
140            let block = blocks.iter().find(|b| b.oid == p.block_id);
141            let view = block.map(|b| meta_get_string(&b.meta, "view", "")).unwrap_or_default();
142            let tab = block.and_then(|b| b.parentoref.strip_prefix("tab:")).unwrap_or_default();
143            json!({ "pane": p.block_id, "view": view, "tab_id": tab })
144        })
145        .collect()
146}
147
148/// Flat list of all windows (id, display name, assigned workspace).
149pub(crate) fn agent_windows(store: &Store) -> serde_json::Value {
150    let workspaces = store.get_all::<Workspace>().unwrap_or_default();
151    let windows: Vec<serde_json::Value> = store
152        .get_all::<Window>()
153        .unwrap_or_default()
154        .iter()
155        .map(|w| {
156            let ws_name = workspaces
157                .iter()
158                .find(|x| x.oid == w.workspaceid)
159                .map(|x| x.name.clone())
160                .unwrap_or_default();
161            json!({
162                "window_id": w.oid,
163                "name": meta_get_string(&w.meta, "window:displayname", ""),
164                "workspace_id": w.workspaceid,
165                "workspace_name": ws_name,
166            })
167        })
168        .collect();
169    json!({ "windows": windows })
170}
171
172/// Flat list of all workspaces (id, name, tab count, active tab).
173pub(crate) fn agent_workspaces(store: &Store) -> serde_json::Value {
174    let workspaces: Vec<serde_json::Value> = store
175        .get_all::<Workspace>()
176        .unwrap_or_default()
177        .iter()
178        .map(|w| {
179            json!({
180                "workspace_id": w.oid,
181                "name": w.name,
182                "tab_count": w.tabids.len() + w.pinnedtabids.len(),
183                "active_tab_id": w.activetabid,
184            })
185        })
186        .collect();
187    json!({ "workspaces": workspaces })
188}
189
190/// Flat list of tabs (id, name, pane count). When `workspace_id` is given,
191/// only that workspace's tabs are returned.
192pub(crate) fn agent_tabs(store: &Store, workspace_id: Option<&str>) -> serde_json::Value {
193    let workspaces = store.get_all::<Workspace>().unwrap_or_default();
194    let scope: Option<Vec<String>> = workspace_id.map(|wid| {
195        workspaces
196            .iter()
197            .find(|w| w.oid == wid)
198            .map(|w| w.pinnedtabids.iter().chain(w.tabids.iter()).cloned().collect())
199            .unwrap_or_default()
200    });
201    let tabs: Vec<serde_json::Value> = store
202        .get_all::<Tab>()
203        .unwrap_or_default()
204        .iter()
205        .filter(|t| scope.as_ref().map(|ids| ids.contains(&t.oid)).unwrap_or(true))
206        .map(|t| {
207            json!({
208                "tab_id": t.oid,
209                "name": t.name,
210                "pane_count": t.blockids.len(),
211            })
212        })
213        .collect();
214    json!({ "tabs": tabs })
215}
216
217/// Whether the pane that holds `block_id` is pinned in `ws`: a pin names one block, and covers every tab of its pane's stack.
218fn pin_covers(store: &Store, tab: &Tab, ws: &Workspace, block_id: &str) -> bool {
219    if ws.pins.iter().any(|p| p.block_id == block_id) {
220        return true;
221    }
222    let members = store
223        .get::<LayoutState>(&tab.layoutstate)
224        .ok()
225        .flatten()
226        .and_then(|l| l.rootnode)
227        .and_then(|root| crate::backend::layout::find_leaf_containing_block(&root, block_id).and_then(|leaf| leaf.data.as_ref().map(crate::backend::layout::leaf_members)))
228        .unwrap_or_default();
229    ws.pins.iter().any(|p| members.contains(&p.block_id))
230}
231
232/// Walk block → tab → workspace → window from an agent pane's block id.
233///
234/// Tabs carry no parent reference, so the workspace and window are found by
235/// reverse lookup: the workspace whose `tabids`/`pinnedtabids` contains the
236/// tab, then the window assigned that workspace. `window_id`/`workspace_id`
237/// are `None` when the tab isn't attached to a live window (e.g. a torn-off
238/// tab mid-transition) — callers should treat that as "no window to name".
239pub(crate) fn resolve_agent_context(store: &Store, block_id: &str) -> Result<AgentContext, String> {
240    let block = store
241        .get::<Block>(block_id)
242        .map_err(|e| e.to_string())?
243        .ok_or_else(|| format!("block not found: {block_id}"))?;
244    let block_title = meta_get_string(&block.meta, "frame:title", "");
245    let tab_id = block.parentoref.strip_prefix("tab:").unwrap_or("").to_string();
246    let tab = store
247        .get::<Tab>(&tab_id)
248        .map_err(|e| e.to_string())?
249        .ok_or_else(|| format!("tab not found for block {block_id}"))?;
250    let mut pinned = false;
251
252    let mut workspace_id = None;
253    let mut workspace_name = String::new();
254    let mut window_id = None;
255    let mut window_name = String::new();
256
257    if let Ok(workspaces) = store.get_all::<Workspace>() {
258        if let Some(ws) = workspaces
259            .into_iter()
260            .find(|w| w.tabids.contains(&tab_id) || w.pinnedtabids.contains(&tab_id))
261        {
262            workspace_name = ws.name.clone();
263            workspace_id = Some(ws.oid.clone());
264            pinned = pin_covers(store, &tab, &ws, block_id);
265            if let Ok(windows) = store.get_all::<Window>() {
266                if let Some(win) = windows.into_iter().find(|w| w.workspaceid == ws.oid) {
267                    window_name = meta_get_string(&win.meta, "window:displayname", "");
268                    window_id = Some(win.oid);
269                }
270            }
271        }
272    }
273
274    Ok(AgentContext {
275        block_id: block_id.to_string(),
276        block_title,
277        tab_id,
278        tab_name: tab.name,
279        window_id,
280        window_name,
281        workspace_id,
282        workspace_name,
283        pinned,
284    })
285}
286
287#[cfg(test)]
288mod agent_context_tests {
289    use super::{resolve_agent_context, workspace_id_for_tab};
290    use crate::backend::obj::Tab;
291    use crate::backend::storage::store::Store;
292    use crate::backend::wcore;
293
294    #[test]
295    fn workspace_id_for_tab_finds_owner_and_misses_cleanly() {
296        let store = Store::open_in_memory().unwrap();
297        wcore::ensure_initial_data(&store).unwrap();
298        let tab = store
299            .get_all::<Tab>()
300            .unwrap()
301            .into_iter()
302            .next()
303            .expect("seeded tab");
304        assert!(workspace_id_for_tab(&store, &tab.oid).is_some(), "owner found");
305        assert!(workspace_id_for_tab(&store, "nope").is_none(), "miss is None");
306    }
307
308    // `ensure_initial_data` seeds one workspace ("Starter workspace") with a
309    // window and an initial tab holding a default agent block. The resolver
310    // must walk that agent block back up to its tab, workspace, and window.
311    #[test]
312    fn resolves_block_to_tab_workspace_and_window() {
313        let store = Store::open_in_memory().unwrap();
314        wcore::ensure_initial_data(&store).unwrap();
315
316        let tab = store
317            .get_all::<Tab>()
318            .unwrap()
319            .into_iter()
320            .next()
321            .expect("seeded tab");
322        let block_id = tab.blockids.first().expect("seeded agent block").clone();
323
324        let ctx = resolve_agent_context(&store, &block_id).expect("resolves context");
325        assert_eq!(ctx.tab_id, tab.oid);
326        assert_eq!(ctx.workspace_name, "Starter workspace");
327        assert!(ctx.workspace_id.is_some(), "workspace should resolve");
328        assert!(ctx.window_id.is_some(), "window should resolve via reverse lookup");
329    }
330
331    #[test]
332    fn unknown_block_errors() {
333        let store = Store::open_in_memory().unwrap();
334        wcore::ensure_initial_data(&store).unwrap();
335        let err = resolve_agent_context(&store, "does-not-exist").unwrap_err();
336        assert!(err.contains("block not found"), "unexpected error: {err}");
337    }
338}
339
340#[cfg(test)]
341mod pinned_tests {
342    use super::{agent_layout, resolve_agent_context};
343    use crate::backend::obj::*;
344    use crate::backend::storage::store::Store;
345
346    /// A window of tabs `t1` and `t2` (showing `t2`), with `bp`, a pane of `t1`, pinned.
347    fn pinned_window(store: &Store) {
348        let mut block = Block { oid: "bp".into(), parentoref: "tab:t1".into(), ..Default::default() };
349        block.meta.insert("view".into(), serde_json::json!("term"));
350        store.insert(&mut block).unwrap();
351        for (id, name, blocks) in [("t1", "One", vec!["bp".to_string()]), ("t2", "Two", vec![])] {
352            let mut t = Tab { oid: id.into(), name: name.into(), blockids: blocks, ..Default::default() };
353            store.insert(&mut t).unwrap();
354        }
355        let pin = agentmux_common::PinRecord { block_id: "bp".into(), order: 0 };
356        let mut ws = Workspace { oid: "ws1".into(), tabids: vec!["t1".into(), "t2".into()], activetabid: "t2".into(), pins: vec![pin], ..Default::default() };
357        store.insert(&mut ws).unwrap();
358        let mut w = Window { oid: "w1".into(), workspaceid: "ws1".into(), ..Default::default() };
359        store.insert(&mut w).unwrap();
360    }
361
362    #[test]
363    fn a_pinned_pane_knows_its_window_and_stays_in_its_own_tab() {
364        let store = Store::open_in_memory().unwrap();
365        pinned_window(&store);
366        let ctx = resolve_agent_context(&store, "bp").unwrap();
367        assert!(ctx.pinned);
368        assert_eq!(ctx.tab_id, "t1", "its own tab, whichever is showing");
369        assert_eq!(ctx.tab_name, "One");
370        assert_eq!(ctx.workspace_id.as_deref(), Some("ws1"));
371        assert_eq!(ctx.window_id.as_deref(), Some("w1"));
372        assert_eq!(serde_json::to_value(&ctx).unwrap()["pinned"], true);
373    }
374
375    #[test]
376    fn every_tab_of_a_pinned_panes_stack_is_pinned() {
377        let store = Store::open_in_memory().unwrap();
378        pinned_window(&store);
379        // `bq` is a second tab of the pane `bp` leads: the pin names `bp`, and covers the whole stack.
380        let mut stacked = Block { oid: "bq".into(), parentoref: "tab:t1".into(), ..Default::default() };
381        store.insert(&mut stacked).unwrap();
382        let mut other = Block { oid: "bo".into(), parentoref: "tab:t1".into(), ..Default::default() };
383        store.insert(&mut other).unwrap();
384        let leaf = |id: &str, stack: Vec<&str>| agentmux_common::LayoutNode {
385            id: id.into(),
386            size: 10.0,
387            data: Some(agentmux_common::LayoutNodeData {
388                block_id: stack.first().copied().unwrap_or(id).into(),
389                active_block_id: stack.first().map(|s| s.to_string()).unwrap_or_default(),
390                block_stack: stack.iter().map(|s| s.to_string()).collect(),
391                ..Default::default()
392            }),
393            ..Default::default()
394        };
395        let root = agentmux_common::LayoutNode {
396            id: "root".into(),
397            size: 10.0,
398            children: vec![leaf("n1", vec!["bp", "bq"]), leaf("n2", vec!["bo"])],
399            ..Default::default()
400        };
401        let mut layout = LayoutState { oid: "l1".into(), rootnode: Some(root), ..Default::default() };
402        store.insert(&mut layout).unwrap();
403        let mut t = store.get::<Tab>("t1").unwrap().unwrap();
404        t.layoutstate = "l1".into();
405        t.blockids = vec!["bp".into(), "bq".into(), "bo".into()];
406        store.update(&mut t).unwrap();
407        assert!(resolve_agent_context(&store, "bp").unwrap().pinned, "the block the pin names");
408        assert!(resolve_agent_context(&store, "bq").unwrap().pinned, "another tab of its stack");
409        assert!(!resolve_agent_context(&store, "bo").unwrap().pinned, "a pane beside it is not");
410    }
411
412    #[test]
413    fn a_docked_pane_is_not_pinned_and_says_nothing_of_it() {
414        let store = Store::open_in_memory().unwrap();
415        pinned_window(&store);
416        let mut b = Block { oid: "bd".into(), parentoref: "tab:t2".into(), ..Default::default() };
417        store.insert(&mut b).unwrap();
418        let mut t = store.get::<Tab>("t2").unwrap().unwrap();
419        t.blockids.push("bd".into());
420        store.update(&mut t).unwrap();
421        let ctx = resolve_agent_context(&store, "bd").unwrap();
422        assert!(!ctx.pinned);
423        assert!(serde_json::to_value(&ctx).unwrap().get("pinned").is_none());
424    }
425
426    #[test]
427    fn the_layout_names_the_pinned_pane_under_the_window_and_lists_it_in_its_tab() {
428        let store = Store::open_in_memory().unwrap();
429        pinned_window(&store);
430        let layout = agent_layout(&store);
431        let window = &layout["windows"][0];
432        assert_eq!(window["pinned"][0], serde_json::json!({ "pane": "bp", "view": "term", "tab_id": "t1" }));
433        let in_tabs = window["tabs"].as_array().unwrap().iter().flat_map(|t| t["panes"].as_array().unwrap().clone()).count();
434        assert_eq!(in_tabs, 1, "it is a pane of its own tab, listed there once");
435    }
436}