Skip to main content

agentmux_srv/server/app_api/
pane_open_tab.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! Which tab a `pane.open` lands in (`REPORT_ACTION_RESULTS_ALWAYS_VISIBLE_ACROSS_WINDOWS_2026_10_31.md` ยง4, step 2).
4//!
5//! The order is: the `tab_id` the caller names, the tab of the `split_reference_block_id` it names, the
6//! `origin_tab_id` (the tab of the window the person acted in), and only then "the first workspace's active
7//! tab". A window that sends none of them is refused, so a click can't open its pane in another window.
8
9use super::*;
10
11/// The tab a `pane.open` with these fields opens in.
12pub(super) fn resolve_open_tab(
13    mstore: &Store,
14    tab_id: Option<&str>,
15    split_reference_block_id: Option<&str>,
16    origin_tab_id: Option<&str>,
17) -> Result<String, String> {
18    if let Some(explicit) = tab_id {
19        return Ok(explicit.to_string());
20    }
21    if let Some(derived) = split_reference_block_id.and_then(|id| resolve_tab_id_for_block(mstore, id).ok()) {
22        return Ok(derived);
23    }
24    if let Some(origin) = origin_tab_id.filter(|t| !t.is_empty()) {
25        // A tab that is gone is an error, not a reason to open the pane in whichever tab is first.
26        return match mstore.get::<Tab>(origin) {
27            Ok(Some(_)) => Ok(origin.to_string()),
28            _ => Err(format!("TAB_NOT_FOUND: the tab {origin} this was opened from is gone")),
29        };
30    }
31    resolve_tab_id(mstore, None)
32}
33
34/// A window's `pane.open` must say where it was asked from. An agent may leave it out (srv then picks its
35/// own tab); a window may not, because "the first workspace" need not be the window the person clicked in.
36pub(super) fn window_open_names_a_tab(cmd: &CommandPaneOpenData) -> Result<(), String> {
37    let names = |t: &Option<String>| t.as_deref().is_some_and(|t| !t.is_empty());
38    if names(&cmd.tab_id) || names(&cmd.split_reference_block_id) || names(&cmd.origin_tab_id) || names(&cmd.stack_onto_block_id) {
39        return Ok(());
40    }
41    Err("INVALID_ARG: pane.open from a window needs origin_tab_id (the tab the person acted in), tab_id or split_reference_block_id".to_string())
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47    use crate::server::tests::test_state;
48    use agentmux_common::ipc::{Command, Event};
49
50    async fn new_tab(state: &AppState, name: &str) -> String {
51        let mut tab = None;
52        for cmd in [Command::CreateWorkspace { name: name.into() }] {
53            let evs = crate::server::service::dispatch_to_reducer(state, cmd).await;
54            for ev in &evs {
55                crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
56            }
57            let ws = evs.iter().find_map(|e| match e {
58                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
59                _ => None,
60            });
61            let evs = crate::server::service::dispatch_to_reducer(state, Command::CreateTab { workspace_id: ws.unwrap(), name: name.into() }).await;
62            for ev in &evs {
63                crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
64            }
65            tab = evs.iter().find_map(|e| match e {
66                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
67                _ => None,
68            });
69        }
70        tab.unwrap()
71    }
72
73    fn open(origin: Option<&str>, tab: Option<&str>) -> CommandPaneOpenData {
74        CommandPaneOpenData {
75            view: "sysinfo".into(),
76            origin_tab_id: origin.map(str::to_string),
77            tab_id: tab.map(str::to_string),
78            ..Default::default()
79        }
80    }
81
82    fn holds(state: &AppState, tab_id: &str, block_id: &str) -> bool {
83        state.mstore.must_get::<Tab>(tab_id).unwrap().blockids.iter().any(|b| b == block_id)
84    }
85
86    #[tokio::test]
87    async fn the_tab_a_window_acted_in_gets_the_pane_not_the_first_workspaces() {
88        let state = test_state();
89        let seeded = resolve_tab_id(&state.mstore, None).expect("the seeded workspace has a tab");
90        let acted_in = new_tab(&state, "second").await;
91        assert_ne!(seeded, acted_in);
92        let res = open_pane(&state, open(Some(&acted_in), None)).await.expect("open from the second window");
93        assert!(holds(&state, &acted_in, &res.block_id), "the pane is in the tab the person acted in");
94        assert!(!holds(&state, &seeded, &res.block_id), "and not in the first workspace's tab");
95    }
96
97    #[tokio::test]
98    async fn a_named_tab_still_beats_the_origin_and_a_gone_origin_is_an_error() {
99        let state = test_state();
100        let (named, origin) = (new_tab(&state, "named").await, new_tab(&state, "origin").await);
101        let res = open_pane(&state, open(Some(&origin), Some(&named))).await.expect("open with both");
102        assert!(holds(&state, &named, &res.block_id), "tab_id is the more exact answer");
103        let err = open_pane(&state, open(Some("no-such-tab"), None)).await.unwrap_err();
104        assert!(err.starts_with("TAB_NOT_FOUND"), "{err}");
105    }
106
107    /// `resolve_tab_id` falls back to the first workspace's active tab when it is given none, which may be
108    /// another window's. Only these files may call it: `pane.open`'s tab choice (after the caller's own tab
109    /// and the origin), and the agent-open paths, where the caller is an agent with no window of its own.
110    /// A new caller has to come through `resolve_open_tab`, or be added here on purpose.
111    #[test]
112    fn nothing_else_asks_for_the_first_workspaces_tab() {
113        // By path under `src`, so a file of the same name elsewhere is not let through.
114        const ALLOWED: [&str; 4] = [
115            "server/app_api/pane_open_tab.rs",
116            "server/app_api/agent_block.rs",
117            "server/app_api/agent_attach.rs",
118            "server/app_api/mod.rs",
119        ];
120        fn walk(root: &std::path::Path, dir: &std::path::Path, hits: &mut Vec<String>) {
121            for entry in std::fs::read_dir(dir).unwrap().flatten() {
122                let path = entry.path();
123                if path.is_dir() {
124                    walk(root, &path, hits);
125                    continue;
126                }
127                let name = path.file_name().unwrap().to_string_lossy().to_string();
128                let relative = path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
129                let in_tests = name.ends_with("_tests.rs") || path.components().any(|c| c.as_os_str() == "tests");
130                if !name.ends_with(".rs") || in_tests || ALLOWED.contains(&relative.as_str()) {
131                    continue;
132                }
133                // The text without line comments (a `//` that starts the line or follows a space, not one inside
134                // a URL), so a call split over lines or with any argument counts.
135                let code: String = std::fs::read_to_string(&path)
136                    .unwrap()
137                    .lines()
138                    .map(|l| match l.find("//") {
139                        Some(at) if l[..at].trim().is_empty() || l[..at].ends_with(char::is_whitespace) => &l[..at],
140                        _ => l,
141                    })
142                    .collect::<Vec<_>>()
143                    .join(" ");
144                let mut at = 0;
145                while let Some(i) = code[at..].find("resolve_tab_id") {
146                    let start = at + i;
147                    let rest = code[start + "resolve_tab_id".len()..].trim_start();
148                    let before = code[..start].trim_end();
149                    let is_call = rest.starts_with('(') && !before.ends_with("fn");
150                    let own_ident = code[..start].chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_');
151                    if is_call && !own_ident {
152                        hits.push(format!("{relative} (byte {start})"));
153                    }
154                    at = start + "resolve_tab_id".len();
155                }
156            }
157        }
158        let mut hits = Vec::new();
159        for root in crate::test_support::server_src_roots() {
160            walk(&root, &root, &mut hits);
161        }
162        assert!(
163            hits.is_empty(),
164            "resolve_tab_id picks the first workspace's tab when it is given none, which may be another window's. Use pane_open_tab::resolve_open_tab, or name the tab. Found: {hits:?}"
165        );
166    }
167
168    #[test]
169    fn a_window_open_must_say_where_it_was_asked_from() {
170        assert!(window_open_names_a_tab(&open(None, None)).is_err(), "nothing named: refused");
171        assert!(window_open_names_a_tab(&open(Some(""), None)).is_err(), "an empty id names nothing");
172        assert!(window_open_names_a_tab(&open(Some("t1"), None)).is_ok());
173        assert!(window_open_names_a_tab(&open(None, Some("t1"))).is_ok());
174        let beside = CommandPaneOpenData { split_reference_block_id: Some("b1".into()), ..open(None, None) };
175        assert!(window_open_names_a_tab(&beside).is_ok());
176        let stacked = CommandPaneOpenData { stack_onto_block_id: Some("b1".into()), ..open(None, None) };
177        assert!(window_open_names_a_tab(&stacked).is_ok());
178    }
179}