Skip to main content

agentmux_srv/server/app_api/
browser_profiles.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `browser_profiles.list` / `.create` / `.update` / `.delete`: the named
5//! browser profiles (docs/specs/SPEC_BROWSER_PANE_PROFILES_MENU_2026_10_09.md
6//! §3, §6), a `shared_dir` file like the bookmarks. Deleting a profile closes
7//! its open tabs first, then the host drops its jar and its folder on the
8//! next owned-pane push. Only the window changes profiles: a connection
9//! registered as an agent may list them, never create, change or delete one.
10
11use super::*;
12use crate::backend::browser_profiles_store as store;
13
14pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
15    let st = state.clone();
16    engine.register_typed(COMMAND_BROWSER_PROFILES_LIST, move |_req: CommandBrowserProfilesListData, _ctx| {
17        let state = st.clone();
18        async move { Ok(result(&state, list()?, None).await) }
19    });
20
21    let st = state.clone();
22    engine.register_typed(COMMAND_BROWSER_PROFILES_CREATE, move |req: CommandBrowserProfileCreateData, ctx| {
23        let state = st.clone();
24        async move {
25            not_for_agents(&ctx)?;
26            let _writing = WRITING.lock().await;
27            let path = path()?;
28            let mut profiles = store::read_profiles(&path)?;
29            let created = store::add(&mut profiles, &req.name, req.color.as_deref(), agentmux_common::time::now_ms())?;
30            store::write_profiles(&path, &profiles)?;
31            state.broker.publish_event::<crate::backend::mps_events::BrowserProfilesChanged>(&(), vec![], 0);
32            Ok(result(&state, profiles, Some(created)).await)
33        }
34    });
35
36    let st = state.clone();
37    engine.register_typed(COMMAND_BROWSER_PROFILES_UPDATE, move |req: CommandBrowserProfileUpdateData, ctx| {
38        let state = st.clone();
39        async move {
40            not_for_agents(&ctx)?;
41            let _writing = WRITING.lock().await;
42            let path = path()?;
43            let mut profiles = store::read_profiles(&path)?;
44            store::update(&mut profiles, &req.id, req.name.as_deref(), req.color.as_deref(), req.agents_allowed)?;
45            store::write_profiles(&path, &profiles)?;
46            state.broker.publish_event::<crate::backend::mps_events::BrowserProfilesChanged>(&(), vec![], 0);
47            Ok(result(&state, profiles, None).await)
48        }
49    });
50
51    let st = state.clone();
52    engine.register_typed(COMMAND_BROWSER_PROFILES_DELETE, move |req: CommandBrowserProfileDeleteData, ctx| {
53        let state = st.clone();
54        async move {
55            not_for_agents(&ctx)?;
56            let path = path()?;
57            let Some((name, owner)) = store::read_profiles(&path)?.into_iter().find(|p| p.id == req.id).map(|p| (p.name, p.owner_agent)) else {
58                return Err(format!("no profile {:?}", req.id));
59            };
60            // Its tabs close first: they must not go on browsing in a jar
61            // that is about to be dropped.
62            close_tabs_of(&state, &req.id).await;
63            // Its saved sign-ins move to Personal, or go with it (Vault spec §9.4),
64            // before the profile does: if that fails, nothing is lost.
65            let (vault, id, keep) = (state.identity_store.clone(), req.id.clone(), !req.delete_signins.unwrap_or(false));
66            tokio::task::spawn_blocking(move || crate::backend::vault::signins::profile_deleted(&vault, &id, &name, keep, owner.as_deref()))
67                .await
68                .map_err(|e| e.to_string())??;
69            crate::server::vault_handlers::publish(&state);
70            // Read again: the list may have changed while the tabs closed.
71            let profiles = {
72                let _writing = WRITING.lock().await;
73                let mut profiles = store::read_profiles(&path)?;
74                store::remove(&mut profiles, &req.id)?;
75                store::write_profiles(&path, &profiles)?;
76                profiles
77            };
78            // The host drops the jar and its folder on this push.
79            crate::server::browser_host_sync::push(&state).await;
80            state.broker.publish_event::<crate::backend::mps_events::BrowserProfilesChanged>(&(), vec![], 0);
81            Ok(result(&state, profiles, None).await)
82        }
83    });
84}
85
86/// The answer to every profiles call: the profiles, and how many saved sign-ins
87/// each holds (none when the Vault can't be read).
88async fn result(state: &AppState, profiles: Vec<store::BrowserProfile>, created: Option<store::BrowserProfile>) -> BrowserProfilesResult {
89    let vault = state.identity_store.clone();
90    let signins = match tokio::task::spawn_blocking(move || crate::backend::vault::signins::counts(&vault)).await {
91        Ok(Ok(c)) => c,
92        Ok(Err(e)) => {
93            tracing::warn!(error = %e, "[browser-profiles] couldn't count the profiles' saved sign-ins");
94            Default::default()
95        }
96        Err(e) => {
97            tracing::warn!(error = %e, "[browser-profiles] couldn't count the profiles' saved sign-ins");
98            Default::default()
99        }
100    };
101    BrowserProfilesResult { profiles, created, signins }
102}
103
104/// Held across each read-change-write of the profiles file, so one change
105/// can't overwrite another.
106static WRITING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
107
108/// Only the operator's window, proven by the host, changes profiles.
109fn not_for_agents(ctx: &RpcContext) -> Result<(), String> {
110    ctx.operator_only("only the user creates, changes or deletes browser profiles")
111}
112
113fn path() -> Result<std::path::PathBuf, String> {
114    store::profiles_file_path().ok_or_else(|| "browser profiles: could not resolve the shared data directory".to_string())
115}
116
117/// The own profile of the agent `owner` (its uid), made the first time it is needed and named `name`, the agent's. This is the one
118/// place an agent makes a profile, and only its own: the calls above stay the user's
119/// (docs/specs/SPEC_AGENT_OWN_BROWSER_PROFILE_2026_11_04.md). The host makes its jar on first use.
120pub(crate) async fn ensure_agent_profile(state: &AppState, owner: &str, name: &str) -> Result<store::BrowserProfile, String> {
121    let (own, changed) = ensure_agent_profile_at(&path()?, owner, name).await?;
122    if changed {
123        // A pane's profile button follows this event: without it the button keeps the default colour until the
124        // person opens its menu.
125        state.broker.publish_event::<crate::backend::mps_events::BrowserProfilesChanged>(&(), vec![], 0);
126        crate::server::browser_host_sync::push(state).await;
127    }
128    Ok(own)
129}
130
131/// [`ensure_agent_profile`] on the profiles file at `path`; whether the file changed is the second part.
132async fn ensure_agent_profile_at(path: &std::path::Path, owner: &str, name: &str) -> Result<(store::BrowserProfile, bool), String> {
133    let _writing = WRITING.lock().await;
134    let mut profiles = store::read_profiles(path)?;
135    let (own, changed) = store::ensure_agent_profile(&mut profiles, owner, name, agentmux_common::time::now_ms());
136    if changed {
137        store::write_profiles(path, &profiles)?;
138    }
139    Ok((own, changed))
140}
141
142/// The profiles, or none when the shared folder can't be resolved.
143pub(crate) fn list() -> Result<Vec<store::BrowserProfile>, String> {
144    match store::profiles_file_path() {
145        Some(p) => store::read_profiles(&p),
146        None => Ok(Vec::new()),
147    }
148}
149
150/// Close every tab browsing as profile `id`.
151async fn close_tabs_of(state: &AppState, id: &str) {
152    let identity = format!("profile:{id}");
153    let blocks = state.mstore.get_all::<crate::backend::obj::Block>().unwrap_or_default();
154    for b in blocks.iter().filter(|b| {
155        b.meta.get(crate::server::browser_identity::IDENTITY_META_KEY).and_then(|v| v.as_str()) == Some(identity.as_str())
156    }) {
157        let tab = state.srv_state.lock().await.blocks.get(&b.oid).map(|r| r.tab_id.clone());
158        if let Some(tab) = tab {
159            if let Err(e) = crate::sagas::delete_block::run(state, tab, b.oid.clone()).await {
160                tracing::warn!(block = %b.oid, error = %e, "[browser-profiles] couldn't close a tab of a deleted profile");
161            }
162        }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    /// An agent's connection carries its id (`bus:register`). Only refusals are
171    /// exercised: they return before the profiles file is read or written.
172    async fn call_as_agent(command: &str, data: serde_json::Value) -> String {
173        call_with(command, data, RpcContext { agent_id: "AgentX".to_string(), ..Default::default() }).await
174    }
175
176    async fn call_with(command: &str, data: serde_json::Value, ctx: RpcContext) -> String {
177        let state = crate::server::tests::test_state();
178        let (engine, mut rx) = WshRpcEngine::new();
179        register(&engine, &state);
180        engine.set_rpc_context(ctx);
181        engine.handle_message(RpcMessage {
182            command: command.to_string(),
183            reqid: "req-1".to_string(),
184            data: Some(data),
185            ..Default::default()
186        });
187        let resp = tokio::time::timeout(std::time::Duration::from_secs(20), rx.recv()).await.unwrap().unwrap();
188        resp.error
189    }
190
191    #[tokio::test(flavor = "multi_thread")]
192    async fn an_agent_may_not_create_change_or_delete_a_profile() {
193        for (command, data) in [
194            (COMMAND_BROWSER_PROFILES_CREATE, json!({ "name": "Work" })),
195            (COMMAND_BROWSER_PROFILES_UPDATE, json!({ "id": "p-0123456789ab", "name": "Mine" })),
196            (COMMAND_BROWSER_PROFILES_DELETE, json!({ "id": "p-0123456789ab" })),
197        ] {
198            let err = call_as_agent(command, data.clone()).await;
199            assert!(err.contains("FORBIDDEN"), "{command}: {err}");
200            // Nor may a connection the host never proved is the window's.
201            let err = call_with(command, data, RpcContext::default()).await;
202            assert!(err.contains("FORBIDDEN") && err.contains("isn't the AgentMux window"), "{command}: {err}");
203        }
204    }
205
206    /// The one profile an agent makes is its own, made once however many panes ask at the same moment, and it is not
207    /// the user's to create from this call (the test above): the RPC still refuses an agent.
208    #[tokio::test]
209    async fn an_agent_makes_its_own_profile_once_even_when_two_panes_ask_together() {
210        let dir = tempfile::tempdir().unwrap();
211        let path = dir.path().join("browser-profiles.json");
212        let (a, b) = tokio::join!(ensure_agent_profile_at(&path, "uid-1", "camper-2"), ensure_agent_profile_at(&path, "uid-1", "camper-2"));
213        let (a, b) = (a.unwrap(), b.unwrap());
214        assert_eq!(a.0, b.0);
215        assert_eq!([a.1, b.1].iter().filter(|c| **c).count(), 1, "only one of them wrote it");
216        let profiles = store::read_profiles(&path).unwrap();
217        assert_eq!(profiles.len(), 1);
218        assert_eq!((profiles[0].id.clone(), profiles[0].owner_agent.as_deref()), (store::agent_profile_id("uid-1"), Some("uid-1")));
219        // A rename of the agent changes the name on the same row; another agent gets a row of its own.
220        let (renamed, _) = ensure_agent_profile_at(&path, "uid-1", "camper-9").await.unwrap();
221        assert_eq!((renamed.id.as_str(), renamed.name.as_str()), (profiles[0].id.as_str(), "camper-9"));
222        ensure_agent_profile_at(&path, "uid-2", "kcont").await.unwrap();
223        assert_eq!(store::read_profiles(&path).unwrap().len(), 2);
224    }
225}