Skip to main content

agentmux_srv/server/
pane_openers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which agent opened which pane, for every pane an agent opens
5//! (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md ยง2.4).
6//!
7//! An agent places, resizes, moves, floats and docks only a pane it opened. The authority is this map,
8//! written by the routes agents open through after they check the caller's signed identity. It has the
9//! properties `browser_owner` has for a browser pane:
10//!
11//! - nothing a client writes into a block's meta enters it, since only srv's routes call [`record`];
12//! - a duplicated pane is a new block with a new id, which the map does not know;
13//! - deleting the block drops its entry (`browser_pane_gone`), and so does the person's Take over of a
14//!   browser pane (`browser_owner::forget_because`);
15//! - after an srv restart the map is filled again from a file in the config folder, for the panes whose
16//!   block is still there; the file alone grants nothing for a block that is gone.
17//!
18//! A browser pane is in both maps: `browser_owner` decides who may drive it, this decides who may place it.
19
20use std::collections::BTreeMap;
21use std::sync::{Mutex, OnceLock};
22
23use serde::{Deserialize, Serialize};
24
25use crate::backend::obj::Block;
26use crate::server::AppState;
27
28/// The file the map is kept in, in the config folder.
29const FILE_NAME: &str = "pane-openers.json";
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32struct Entry {
33    agent: String,
34    /// Whether the pane is a floating window now.
35    #[serde(default)]
36    floating: bool,
37    /// When it was opened, in Unix milliseconds (0 for a record from before this was kept).
38    #[serde(default)]
39    at_ms: u64,
40    /// A background browser session: a floating window kept off every screen
41    /// (docs/specs/SPEC_BACKGROUND_BROWSER_SESSIONS_2026_11_28.md).
42    #[serde(default)]
43    background: bool,
44    /// The agent's own pane that opened a background session: where the strip that tells the person of it is shown.
45    #[serde(default)]
46    from_block: Option<String>,
47}
48
49#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
50struct Records {
51    #[serde(default)]
52    panes: BTreeMap<String, Entry>,
53}
54
55fn map() -> &'static Mutex<BTreeMap<String, Entry>> {
56    static MAP: OnceLock<Mutex<BTreeMap<String, Entry>>> = OnceLock::new();
57    MAP.get_or_init(Default::default)
58}
59
60fn lock() -> std::sync::MutexGuard<'static, BTreeMap<String, Entry>> {
61    map().lock().unwrap_or_else(|p| p.into_inner())
62}
63
64/// The time to put on a record: Unix milliseconds, and never the same or lower than the one before, so records made in
65/// the same millisecond still have an order.
66fn stamp() -> u64 {
67    static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
68    let now = agentmux_common::time::now_ms_u64();
69    let mut last = LAST.load(std::sync::atomic::Ordering::Relaxed);
70    loop {
71        let next = now.max(last + 1);
72        match LAST.compare_exchange_weak(last, next, std::sync::atomic::Ordering::Relaxed, std::sync::atomic::Ordering::Relaxed) {
73            Ok(_) => return next,
74            Err(seen) => last = seen,
75        }
76    }
77}
78
79/// Record `agent` as the opener of `block_id`; `floating` says it opened as a floating window.
80pub(crate) fn record(block_id: &str, agent: &str, floating: bool) {
81    lock().insert(block_id.to_string(), Entry { agent: agent.to_string(), floating, at_ms: stamp(), background: false, from_block: None });
82    crate::server::browser_owner::changed().notify_one();
83}
84
85/// Record `agent` as the opener of `block_id`, a floating window: a background session when `background`, opened from
86/// the agent's pane `from` (where the person is told of it).
87pub(crate) fn record_floating(block_id: &str, agent: &str, background: bool, from: Option<&str>) {
88    match background {
89        true => record_background(block_id, agent),
90        false => record(block_id, agent, true),
91    }
92    if let Some(e) = lock().get_mut(block_id).filter(|e| e.background) {
93        e.from_block = from.map(str::to_string);
94        crate::server::browser_owner::changed().notify_one();
95    }
96}
97
98/// The background sessions of each agent pane that opened one: the pane, and its sessions sorted.
99pub(crate) fn background_by_block() -> BTreeMap<String, Vec<String>> {
100    let mut by_block: BTreeMap<String, Vec<String>> = BTreeMap::new();
101    for (pane, e) in lock().iter().filter(|(_, e)| e.background) {
102        if let Some(from) = &e.from_block {
103            by_block.entry(from.clone()).or_default().push(pane.clone());
104        }
105    }
106    by_block
107}
108
109/// A background browser session: its pane, the agent that holds it and the agent's own pane it was opened from.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub(crate) struct Session {
112    pub pane: String,
113    pub agent: String,
114    pub from_block: Option<String>,
115}
116
117/// Every background session, sorted by pane.
118pub(crate) fn background_sessions() -> Vec<Session> {
119    lock()
120        .iter()
121        .filter(|(_, e)| e.background)
122        .map(|(pane, e)| Session { pane: pane.clone(), agent: e.agent.clone(), from_block: e.from_block.clone() })
123        .collect()
124}
125
126/// Record `agent` as the opener of `block_id`, a background browser session.
127pub(crate) fn record_background(block_id: &str, agent: &str) {
128    lock().insert(block_id.to_string(), Entry { agent: agent.to_string(), floating: true, at_ms: stamp(), background: true, from_block: None });
129    crate::server::browser_owner::changed().notify_one();
130}
131
132/// The background sessions `agent` has open, sorted.
133pub(crate) fn background_of(agent: &str) -> Vec<String> {
134    lock().iter().filter(|(_, e)| e.background && e.agent.eq_ignore_ascii_case(agent)).map(|(b, _)| b.clone()).collect()
135}
136
137/// Every pane `agent` opened, sorted: the block, whether it is a floating window, whether it is a background session.
138pub(crate) fn opened_by_agent(agent: &str) -> Vec<(String, bool, bool)> {
139    lock().iter().filter(|(_, e)| e.agent.eq_ignore_ascii_case(agent)).map(|(b, e)| (b.clone(), e.floating, e.background)).collect()
140}
141
142/// Every background session, whoever opened it.
143pub(crate) fn all_background() -> Vec<String> {
144    lock().iter().filter(|(_, e)| e.background).map(|(b, _)| b.clone()).collect()
145}
146
147/// Whether `block_id` is a background session.
148pub(crate) fn is_background(block_id: &str) -> bool {
149    lock().get(block_id).is_some_and(|e| e.background)
150}
151
152/// A background session shown: it is a floating pane like any other from now on.
153pub(crate) fn clear_background(block_id: &str) {
154    if let Some(e) = lock().get_mut(block_id) {
155        e.background = false;
156    }
157    crate::server::browser_owner::changed().notify_one();
158}
159
160/// A pane the person sees put back in the background: it is a background session again, held by the agent pane `from`
161/// (where the person is told of it), which is kept if the pane was opened as a session from another.
162pub(crate) fn set_background(block_id: &str, from: &str) {
163    if let Some(e) = lock().get_mut(block_id) {
164        e.background = true;
165        e.from_block.get_or_insert_with(|| from.to_string());
166    }
167    crate::server::browser_owner::changed().notify_one();
168}
169
170/// Drop `block_id`'s opener: the pane was deleted, or the person took it over.
171pub(crate) fn forget(block_id: &str) {
172    if lock().remove(block_id).is_some() {
173        crate::server::browser_owner::changed().notify_one();
174    }
175}
176
177/// The agent that opened `block_id`, if one did.
178pub(crate) fn opener_of(block_id: &str) -> Option<String> {
179    lock().get(block_id).map(|e| e.agent.clone())
180}
181
182/// Whether `agent` opened `block_id` (agent ids compare without case).
183pub(crate) fn opened_by(block_id: &str, agent: &str) -> bool {
184    opener_of(block_id).is_some_and(|a| a.eq_ignore_ascii_case(agent))
185}
186
187/// A docked pane an agent made is the agent's to place later; a floating one was recorded as it was made.
188pub(crate) fn note_docked(opener: Option<&str>, result: &crate::backend::rpc_types::PaneOpenResult, floating: bool) {
189    if let (Some(agent), true, false) = (opener, result.created, floating) {
190        record(&result.block_id, agent, false);
191    }
192}
193
194/// The docked panes `agent` opened, the newest first: where its next open goes by default
195/// (`app_api::agent_tab_default`).
196pub(crate) fn docked_of(agent: &str) -> Vec<String> {
197    let mut mine: Vec<(u64, String)> =
198        lock().iter().filter(|(_, e)| !e.floating && e.agent.eq_ignore_ascii_case(agent)).map(|(b, e)| (e.at_ms, b.clone())).collect();
199    mine.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));
200    mine.into_iter().map(|(_, b)| b).collect()
201}
202
203/// The panes `agent` opened that are floating windows now, sorted.
204pub(crate) fn floaters_of(agent: &str) -> Vec<String> {
205    lock().iter().filter(|(_, e)| e.floating && !e.background && e.agent.eq_ignore_ascii_case(agent)).map(|(b, _)| b.clone()).collect()
206}
207
208/// Whether `block_id` is a floating window an agent opened (a pane docked later is not).
209pub(crate) fn is_floating(block_id: &str) -> bool {
210    lock().get(block_id).is_some_and(|e| e.floating)
211}
212
213/// Note whether `block_id` is a floating window now (a pane docked or floated later keeps its opener).
214pub(crate) fn set_floating(block_id: &str, floating: bool) {
215    if let Some(e) = lock().get_mut(block_id) {
216        e.floating = floating;
217    }
218}
219
220fn path() -> std::path::PathBuf {
221    crate::backend::base::get_mux_config_dir().join(FILE_NAME)
222}
223
224/// The part of `saved` that is still true: the panes whose block is still there. `block_of` reads a block by id.
225fn still_true(saved: Records, block_of: impl Fn(&str) -> Option<Block>) -> Records {
226    Records { panes: saved.panes.into_iter().filter(|(pane, _)| block_of(pane).is_some()).collect() }
227}
228
229/// Read the file and put back what is still true. Called once at startup, before anything can change the map,
230/// so the first save does not replace the file with an empty copy.
231pub(crate) fn restore(state: &AppState) {
232    let saved = match std::fs::read(path()) {
233        Ok(bytes) => serde_json::from_slice::<Records>(&bytes).unwrap_or_else(|e| {
234            tracing::warn!(error = %e, "[pane-openers] the saved records are unreadable; panes start with no opener");
235            Records::default()
236        }),
237        Err(_) => Records::default(),
238    };
239    let kept = still_true(saved, |pane| state.mstore.get::<Block>(pane).ok().flatten());
240    let n = kept.panes.len();
241    lock().extend(kept.panes);
242    tracing::info!(panes = n, "[pane-openers] restored");
243}
244
245/// Write the map to the file, unless it is what the last write left there.
246pub(crate) fn save() {
247    static LAST: OnceLock<Mutex<Option<Records>>> = OnceLock::new();
248    let now = Records { panes: lock().clone() };
249    let mut last = LAST.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
250    if last.as_ref() == Some(&now) {
251        return;
252    }
253    let bytes = match serde_json::to_vec_pretty(&now) {
254        Ok(b) => b,
255        Err(e) => {
256            tracing::warn!(error = %e, "[pane-openers] couldn't encode the records");
257            return;
258        }
259    };
260    match agentmux_common::settings_file::write_atomic(&path(), &bytes) {
261        Ok(()) => *last = Some(now),
262        Err(e) => tracing::warn!(error = %e, "[pane-openers] couldn't save the records"),
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn entry(agent: &str, floating: bool) -> Entry {
271        Entry { agent: agent.to_string(), floating, at_ms: 0, background: false, from_block: None }
272    }
273
274    #[test]
275    fn a_pane_is_the_openers_until_it_is_forgotten() {
276        record("po-a", "Lark", true);
277        assert_eq!(opener_of("po-a").as_deref(), Some("Lark"));
278        assert!(opened_by("po-a", "lark"), "agent ids compare without case");
279        assert!(!opened_by("po-a", "korp"), "another agent did not open it");
280        assert!(!opened_by("po-never", "lark"), "a pane nobody recorded has no opener");
281        forget("po-a");
282        assert_eq!(opener_of("po-a"), None);
283    }
284
285    #[test]
286    fn floaters_are_the_agents_floating_panes_only() {
287        record("po-f1", "fl-agent", true);
288        record("po-f2", "FL-AGENT", true);
289        record("po-d1", "fl-agent", false);
290        record("po-o1", "someone-else", true);
291        assert_eq!(floaters_of("fl-agent"), vec!["po-f1".to_string(), "po-f2".to_string()]);
292        assert!(is_floating("po-f2") && !is_floating("po-d1") && !is_floating("po-never"));
293        set_floating("po-f1", false);
294        assert_eq!(floaters_of("fl-agent"), vec!["po-f2".to_string()], "a docked pane no longer counts");
295        for b in ["po-f1", "po-f2", "po-d1", "po-o1"] {
296            forget(b);
297        }
298    }
299
300    #[test]
301    fn a_record_comes_back_only_for_a_pane_still_there() {
302        let saved = Records { panes: [("kept".to_string(), entry("lark", true)), ("gone".to_string(), entry("lark", false))].into() };
303        let back = still_true(saved, |p| (p == "kept").then(Block::default));
304        assert_eq!(back.panes.keys().collect::<Vec<_>>(), vec!["kept"]);
305        assert!(back.panes["kept"].floating, "the floating flag is kept");
306    }
307}