Skip to main content

agentmux_srv/server/
browser_pane_records.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The browser panes an agent drives, and the sites a limited one may go to, kept across an srv
5//! restart (docs/specs/SPEC_BROWSER_PANE_RECORDS_SURVIVE_RESTART_2026_11_04.md).
6//!
7//! Who owns a pane (`browser_owner`) and which sites its chain is limited to (`browser_allowlist`)
8//! are srv's own records, held in memory. Without a copy on disk a restart leaves a limited,
9//! agent-owned pane unlimited and unowned while its block still shows both. A file in the config
10//! folder holds the copy: written whenever either record changes, read once at startup.
11//!
12//! The file is keyed by block id, and a duplicated pane is a new block with a new id, so a copy of a
13//! pane never inherits anything. A record is taken back only for a block that is still a browser
14//! pane whose `browser:owner_agent` (which only srv writes, and a person's Take over clears) names
15//! the same agent: the file alone grants nothing.
16
17use std::collections::BTreeMap;
18use std::path::PathBuf;
19use std::sync::{Mutex, OnceLock};
20
21use serde::{Deserialize, Serialize};
22
23use crate::backend::obj::Block;
24use crate::server::{browser_allowlist, browser_owner, AppState};
25
26/// The file the records are kept in, in the config folder.
27const FILE_NAME: &str = "browser-pane-records.json";
28
29#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub(crate) struct Records {
31    /// Pane → the agent that owns it.
32    #[serde(default)]
33    pub owners: BTreeMap<String, String>,
34    /// Limited pane → the root pane of its chain.
35    #[serde(default)]
36    pub members: BTreeMap<String, String>,
37    /// Root pane → the chain's site list.
38    #[serde(default)]
39    pub lists: BTreeMap<String, Vec<String>>,
40}
41
42fn path() -> PathBuf {
43    crate::backend::base::get_mux_config_dir().join(FILE_NAME)
44}
45
46/// What srv holds now.
47fn current() -> Records {
48    let (members, lists) = browser_allowlist::chains();
49    Records { owners: browser_owner::all_owners(), members, lists }
50}
51
52/// The part of `saved` that is still true: a pane that is still there as a browser pane its agent
53/// still drives, and the limits of the panes that remain. `block_of` reads a block by id.
54fn still_true(saved: Records, block_of: impl Fn(&str) -> Option<Block>) -> Records {
55    let owners: BTreeMap<String, String> = saved
56        .owners
57        .into_iter()
58        .filter(|(pane, agent)| {
59            block_of(pane).is_some_and(|b| {
60                let meta_str = |k: &str| b.meta.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
61                meta_str("view") == "browser" && meta_str(browser_owner::OWNER_META_KEY).eq_ignore_ascii_case(agent)
62            })
63        })
64        .collect();
65    let members: BTreeMap<String, String> = saved.members.into_iter().filter(|(pane, _)| owners.contains_key(pane)).collect();
66    let lists = saved.lists.into_iter().filter(|(root, _)| members.values().any(|r| r == root)).collect();
67    Records { owners, members, lists }
68}
69
70/// Read the file and put back what is still true. Called once at startup, before anything
71/// changes the records, so the first save doesn't replace the file with an empty copy.
72pub(crate) fn restore(state: &AppState) {
73    let saved = match std::fs::read(path()) {
74        Ok(bytes) => serde_json::from_slice::<Records>(&bytes).unwrap_or_else(|e| {
75            tracing::warn!(error = %e, "[browser-records] the saved records are unreadable; panes start unowned and unlimited");
76            Records::default()
77        }),
78        Err(_) => Records::default(),
79    };
80    let kept = still_true(saved, |pane| state.mstore.get::<Block>(pane).ok().flatten());
81    for (pane, agent) in &kept.owners {
82        browser_owner::restore(pane, agent);
83    }
84    for (pane, root) in &kept.members {
85        if let Some(list) = kept.lists.get(root) {
86            browser_allowlist::restore(pane, root, list.clone());
87        }
88    }
89    tracing::info!(owned = kept.owners.len(), limited = kept.members.len(), "[browser-records] restored");
90}
91
92/// Write the records to the file, unless they are what the last write left there.
93pub(crate) fn save() {
94    static LAST: OnceLock<Mutex<Option<Records>>> = OnceLock::new();
95    let now = current();
96    let mut last = LAST.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
97    if last.as_ref() == Some(&now) {
98        return;
99    }
100    let bytes = match serde_json::to_vec_pretty(&now) {
101        Ok(b) => b,
102        Err(e) => {
103            tracing::warn!(error = %e, "[browser-records] couldn't encode the records");
104            return;
105        }
106    };
107    match agentmux_common::settings_file::write_atomic(&path(), &bytes) {
108        Ok(()) => *last = Some(now),
109        Err(e) => tracing::warn!(error = %e, "[browser-records] couldn't save the records"),
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use serde_json::json;
117
118    fn block(view: &str, owner: Option<&str>) -> Block {
119        let mut b = Block::default();
120        b.meta.insert("view".to_string(), json!(view));
121        if let Some(o) = owner {
122            b.meta.insert(browser_owner::OWNER_META_KEY.to_string(), json!(o));
123        }
124        b
125    }
126
127    fn pair(a: &str, b: &str) -> (String, String) {
128        (a.to_string(), b.to_string())
129    }
130
131    #[test]
132    fn a_record_comes_back_only_for_a_pane_still_there_and_still_the_agents() {
133        let saved = Records {
134            owners: [pair("kept", "lark"), pair("taken-over", "lark"), pair("gone", "lark"), pair("other-agent", "lark"), pair("not-a-browser", "lark")].into(),
135            members: [pair("kept", "root"), pair("taken-over", "root2"), pair("gone", "root3")].into(),
136            lists: [("root".to_string(), vec!["https://a.example".to_string()]), ("root2".to_string(), vec![]), ("root3".to_string(), vec![])].into(),
137        };
138        let blocks: BTreeMap<&str, Block> = [
139            ("kept", block("browser", Some("Lark"))),
140            ("taken-over", block("browser", None)),
141            ("other-agent", block("browser", Some("korp"))),
142            ("not-a-browser", block("term", Some("lark"))),
143        ]
144        .into();
145        let back = still_true(saved, |p| blocks.get(p).cloned());
146        assert_eq!(back.owners, [pair("kept", "lark")].into());
147        assert_eq!(back.members, [pair("kept", "root")].into());
148        assert_eq!(back.lists.keys().collect::<Vec<_>>(), vec!["root"]);
149    }
150
151    #[test]
152    fn a_copy_of_a_pane_has_its_meta_but_no_record() {
153        let saved = Records { owners: [pair("original", "lark")].into(), ..Default::default() };
154        // The copy carries the same meta under a new id; only the original has a record.
155        let blocks: BTreeMap<&str, Block> = [("original", block("browser", Some("lark"))), ("copy", block("browser", Some("lark")))].into();
156        let back = still_true(saved, |p| blocks.get(p).cloned());
157        assert!(back.owners.contains_key("original") && !back.owners.contains_key("copy"));
158    }
159
160    #[test]
161    fn a_limited_popup_outlives_its_root_across_a_restart() {
162        let saved = Records {
163            owners: [pair("popup", "lark")].into(),
164            members: [pair("popup", "root-closed")].into(),
165            lists: [("root-closed".to_string(), vec!["https://a.example".to_string()])].into(),
166        };
167        let back = still_true(saved, |p| (p == "popup").then(|| block("browser", Some("lark"))));
168        assert_eq!(back.lists.get("root-closed").map(Vec::len), Some(1));
169    }
170
171    #[test]
172    fn restored_records_drive_the_owner_and_the_site_list() {
173        browser_owner::restore("rec-popup", "lark");
174        browser_allowlist::restore("rec-popup", "rec-root", vec!["https://a.example".to_string()]);
175        assert_eq!(browser_owner::owner_of("rec-popup").as_deref(), Some("lark"));
176        assert_eq!(browser_allowlist::list_for("rec-popup"), Some(vec!["https://a.example".to_string()]));
177        assert!(browser_allowlist::refuse_agent_navigation("rec-popup", "https://b.example/x").is_some());
178        let now = current();
179        assert_eq!(now.owners.get("rec-popup").map(String::as_str), Some("lark"));
180        assert_eq!(now.members.get("rec-popup").map(String::as_str), Some("rec-root"));
181        // A Take over or a closed pane ends both.
182        browser_owner::forget("rec-popup");
183        assert!(browser_allowlist::drop_pane("rec-popup"));
184        assert!(browser_owner::owner_of("rec-popup").is_none() && browser_allowlist::list_for("rec-popup").is_none());
185        assert!(!current().lists.contains_key("rec-root"));
186    }
187
188    #[test]
189    fn the_records_survive_the_file() {
190        let r = Records {
191            owners: [pair("a", "lark")].into(),
192            members: [pair("a", "r")].into(),
193            lists: [("r".to_string(), vec!["https://a.example".to_string()])].into(),
194        };
195        let back: Records = serde_json::from_slice(&serde_json::to_vec_pretty(&r).unwrap()).unwrap();
196        assert_eq!(back, r);
197        // An older or partial file reads as what it has.
198        assert_eq!(serde_json::from_str::<Records>("{}").unwrap(), Records::default());
199    }
200}