Skip to main content

agentmux_srv_core/backend/
browser_profiles_store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Named browser profiles: the list of them, in `shared_dir`
5//! (`~/.agentmux/shared/browser-profiles.json`), like the bookmarks
6//! (docs/specs/SPEC_BROWSER_PANE_PROFILES_MENU_2026_10_09.md §3, §6). A
7//! profile's cookie jar is a disk-backed CEF profile the host keeps at
8//! `<cef-cache>/profile-<id>`; this file only names and colours them.
9//! "Personal" (the shared jar every tab had before profiles) isn't listed:
10//! it always exists and can't be deleted.
11
12use std::path::{Path, PathBuf};
13
14use serde::{Deserialize, Serialize};
15
16use crate::backend::palette::farthest_free_slot;
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ts_rs::TS)]
19#[ts(export, export_to = "../../../frontend/types/rpc/")]
20pub struct BrowserProfile {
21    /// Stable id, `[a-z0-9-]`, used in `browser:identity` (`profile:<id>`)
22    /// and the host's profile folder. Never reused.
23    pub id: String,
24    pub name: String,
25    /// `#rrggbb`: the profile's colour on its button and tabs.
26    pub color: String,
27    #[serde(default)]
28    #[ts(type = "number")]
29    pub created_at: i64,
30    /// "Agents may use it" (Settings → Browser): an agent's `OpenBrowser` may browse as
31    /// it. Off until the user switches it on.
32    #[serde(default)]
33    pub agents_allowed: bool,
34    /// The agent (its id) this profile is the own browsing profile of: made by srv the first
35    /// time that agent opens a browser, never by the user. `None` for the user's profiles.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    #[ts(optional)]
38    pub owner_agent: Option<String>,
39}
40
41const PROFILES_FILE_NAME: &str = "browser-profiles.json";
42pub const MAX_PROFILES: usize = 20;
43pub const MAX_NAME_CHARS: usize = 40;
44
45pub fn profiles_file_path() -> Option<PathBuf> {
46    crate::registry::shared_guard::shared_dir().map(|dir| dir.join(PROFILES_FILE_NAME))
47}
48
49/// The list. A missing or empty file is "no profiles yet"; a present but
50/// unparseable one is an error, not an empty list that would look like the
51/// profiles vanished.
52pub fn read_profiles(path: &Path) -> Result<Vec<BrowserProfile>, String> {
53    if !path.exists() {
54        return Ok(Vec::new());
55    }
56    let content = std::fs::read_to_string(path).map_err(|e| format!("read browser profiles: {e}"))?;
57    if content.trim().is_empty() {
58        return Ok(Vec::new());
59    }
60    serde_json::from_str(&content).map_err(|e| format!("parse browser profiles: {e}"))
61}
62
63/// Replace the list, through a temp file and a rename, so a crash never
64/// leaves a half-written file.
65pub fn write_profiles(path: &Path, profiles: &[BrowserProfile]) -> Result<(), String> {
66    if let Some(parent) = path.parent() {
67        std::fs::create_dir_all(parent).map_err(|e| format!("mkdir: {e}"))?;
68    }
69    // A field a newer AgentMux put on a profile is carried over from the file as it is now, not dropped by this save.
70    let mut list = serde_json::to_value(profiles).map_err(|e| format!("serialize browser profiles: {e}"))?;
71    if let Some(old) = super::json_keep::read_old(path) {
72        super::json_keep::carry_unknown_keys_in_list(&old, &mut list, "id", &["id", "name", "color", "created_at", "agents_allowed", "owner_agent"]);
73    }
74    let json = serde_json::to_string_pretty(&list).map_err(|e| format!("serialize browser profiles: {e}"))?;
75    let tmp = path.with_file_name(format!(".{PROFILES_FILE_NAME}.{}.tmp", uuid::Uuid::new_v4()));
76    std::fs::write(&tmp, &json).map_err(|e| format!("write browser profiles: {e}"))?;
77    std::fs::rename(&tmp, path).map_err(|e| {
78        let _ = std::fs::remove_file(&tmp);
79        format!("rename browser profiles: {e}")
80    })
81}
82
83/// Is `id` a well-formed profile id?
84pub fn is_profile_id(id: &str) -> bool {
85    (1..=64).contains(&id.len()) && id.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
86}
87
88fn check_name(profiles: &[BrowserProfile], name: &str, except: Option<&str>) -> Result<String, String> {
89    let name = name.trim();
90    if name.is_empty() {
91        return Err("a profile needs a name".to_string());
92    }
93    if name.chars().count() > MAX_NAME_CHARS {
94        return Err(format!("a profile's name is at most {MAX_NAME_CHARS} characters"));
95    }
96    if ["personal", "incognito"].contains(&name.to_lowercase().as_str()) {
97        return Err(format!("{name:?} is taken: pick another name"));
98    }
99    if profiles.iter().any(|p| p.owner_agent.is_none() && Some(p.id.as_str()) != except && p.name.eq_ignore_ascii_case(name)) {
100        return Err(format!("there is already a profile called {name:?}"));
101    }
102    Ok(name.to_string())
103}
104
105fn check_color(color: &str) -> Result<String, String> {
106    let c = color.trim().to_lowercase();
107    let hex = c.strip_prefix('#').unwrap_or("");
108    if hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
109        Ok(c)
110    } else {
111        Err(format!("{color:?} isn't a colour (#rrggbb)"))
112    }
113}
114
115/// A new profile added to `profiles`: a fresh id, a checked name, and the
116/// given colour or the shared palette's hue farthest from the ones in use
117/// (`palette::farthest_free_slot`), so a deleted profile's colour is reused
118/// and nothing repeats until all 12 hues are taken. Black and White are never
119/// given: they are only ever someone's own choice.
120pub fn add(
121    profiles: &mut Vec<BrowserProfile>,
122    name: &str,
123    color: Option<&str>,
124    now_ms: i64,
125) -> Result<BrowserProfile, String> {
126    if profiles.iter().filter(|p| p.owner_agent.is_none()).count() >= MAX_PROFILES {
127        return Err(format!("at most {MAX_PROFILES} profiles"));
128    }
129    let name = check_name(profiles, name, None)?;
130    let color = match color {
131        Some(c) => check_color(c)?,
132        None => farthest_free_slot(profiles.iter().map(|p| p.color.as_str())).hex.clone(),
133    };
134    let id = format!("p-{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
135    let profile = BrowserProfile { id, name, color, created_at: now_ms, agents_allowed: false, owner_agent: None };
136    profiles.push(profile.clone());
137    Ok(profile)
138}
139
140/// The id of the own profile of the agent `owner` (its uid, which a rename keeps): `agent-`, a readable part of
141/// it, and a hash of all of it, so two owners never share an id however alike their names, in the characters a
142/// profile id has.
143pub fn agent_profile_id(owner: &str) -> String {
144    let readable: String = owner.to_lowercase().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).take(40).collect();
145    // FNV-1a, 32 bits: fixed for good, unlike the standard hasher.
146    let hash = owner.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193));
147    format!("agent-{readable}-{hash:08x}")
148}
149
150/// Agent `owner`'s own profile in `profiles`, made if it has none, its name kept to the
151/// agent's current `name` (so a rename shows and the data stays). Whether the list
152/// changed is the second part.
153pub fn ensure_agent_profile(profiles: &mut Vec<BrowserProfile>, owner: &str, name: &str, now_ms: i64) -> (BrowserProfile, bool) {
154    let name: String = name.trim().chars().take(MAX_NAME_CHARS).collect();
155    if let Some(p) = profiles.iter_mut().find(|p| p.owner_agent.as_deref() == Some(owner)) {
156        let changed = p.name != name;
157        p.name = name;
158        return (p.clone(), changed);
159    }
160    let color = farthest_free_slot(profiles.iter().map(|p| p.color.as_str())).hex.clone();
161    let mut id = agent_profile_id(owner);
162    while profiles.iter().any(|p| p.id == id) {
163        id.push('x');
164    }
165    let profile = BrowserProfile { id, name, color, created_at: now_ms, agents_allowed: false, owner_agent: Some(owner.to_string()) };
166    profiles.push(profile.clone());
167    (profile, true)
168}
169
170/// Rename or recolour profile `id`.
171pub fn update(
172    profiles: &mut [BrowserProfile],
173    id: &str,
174    name: Option<&str>,
175    color: Option<&str>,
176    agents_allowed: Option<bool>,
177) -> Result<(), String> {
178    let name = name.map(|n| check_name(profiles, n, Some(id))).transpose()?;
179    let color = color.map(check_color).transpose()?;
180    let p = profiles.iter_mut().find(|p| p.id == id).ok_or_else(|| format!("no profile {id:?}"))?;
181    if let Some(n) = name {
182        p.name = n;
183    }
184    if let Some(c) = color {
185        p.color = c;
186    }
187    if let Some(a) = agents_allowed {
188        p.agents_allowed = a;
189    }
190    Ok(())
191}
192
193/// Remove profile `id`. Its tabs and its jar are the caller's to close.
194pub fn remove(profiles: &mut Vec<BrowserProfile>, id: &str) -> Result<(), String> {
195    let before = profiles.len();
196    profiles.retain(|p| p.id != id);
197    if profiles.len() == before {
198        return Err(format!("no profile {id:?}"));
199    }
200    Ok(())
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::backend::palette::slots;
207
208    #[test]
209    fn profiles_are_added_named_and_coloured() {
210        let mut ps = Vec::new();
211        let work = add(&mut ps, "  Work ", None, 1).unwrap();
212        assert_eq!(work.name, "Work");
213        assert_eq!(work.color, slots()[0].hex);
214        assert!(is_profile_id(&work.id));
215        let client = add(&mut ps, "Client X", Some("#ABCDEF"), 2).unwrap();
216        assert_eq!(client.color, "#abcdef");
217        assert_ne!(work.id, client.id);
218    }
219
220    #[test]
221    fn a_new_profile_never_repeats_a_colour_in_use_even_after_a_delete() {
222        let mut ps = Vec::new();
223        for name in ["A", "B", "C", "D"] {
224            add(&mut ps, name, None, 1).unwrap();
225        }
226        let gone = ps.remove(1);
227        let fresh = add(&mut ps, "E", None, 2).unwrap();
228        assert!(ps.iter().filter(|p| p.id != fresh.id).all(|p| p.color != fresh.color));
229        // The freed colour is not necessarily the one taken, but it is a palette slot.
230        assert!(slots().iter().any(|s| s.hex == fresh.color), "{} (freed {})", fresh.color, gone.color);
231    }
232
233    #[test]
234    fn bad_names_and_colours_are_refused() {
235        let mut ps = Vec::new();
236        add(&mut ps, "Work", None, 1).unwrap();
237        for bad in ["", "   ", "work", "Personal", "incognito", &"x".repeat(MAX_NAME_CHARS + 1)] {
238            assert!(add(&mut ps, bad, None, 2).is_err(), "{bad:?}");
239        }
240        assert!(add(&mut ps, "Home", Some("blue"), 2).is_err());
241        assert!(add(&mut ps, "Home", Some("#12345"), 2).is_err());
242    }
243
244    #[test]
245    fn renaming_keeps_its_own_name_free_and_others_taken() {
246        let mut ps = Vec::new();
247        let a = add(&mut ps, "A", None, 1).unwrap();
248        add(&mut ps, "B", None, 1).unwrap();
249        update(&mut ps, &a.id, Some("a"), None, None).unwrap();
250        assert!(update(&mut ps, &a.id, Some("B"), None, None).is_err());
251        update(&mut ps, &a.id, None, Some("#000000"), None).unwrap();
252        assert_eq!(ps[0].color, "#000000");
253        assert!(update(&mut ps, "p-none", Some("C"), None, None).is_err());
254    }
255
256    #[test]
257    fn removing_and_the_cap() {
258        let mut ps = Vec::new();
259        for i in 0..MAX_PROFILES {
260            add(&mut ps, &format!("P{i}"), None, 1).unwrap();
261        }
262        assert!(add(&mut ps, "One more", None, 1).is_err());
263        let id = ps[0].id.clone();
264        remove(&mut ps, &id).unwrap();
265        assert!(remove(&mut ps, &id).is_err());
266        assert_eq!(ps.len(), MAX_PROFILES - 1);
267    }
268
269    #[test]
270    fn the_file_round_trips_and_a_missing_one_is_empty() {
271        let dir = tempfile::tempdir().unwrap();
272        let path = dir.path().join(PROFILES_FILE_NAME);
273        assert!(read_profiles(&path).unwrap().is_empty());
274        let mut ps = Vec::new();
275        add(&mut ps, "Work", None, 5).unwrap();
276        write_profiles(&path, &ps).unwrap();
277        assert_eq!(read_profiles(&path).unwrap(), ps);
278        std::fs::write(&path, "{not json").unwrap();
279        assert!(read_profiles(&path).is_err());
280    }
281
282    #[test]
283    fn an_agents_own_profile_is_made_once_keyed_by_its_id_and_outside_the_users_cap() {
284        let mut ps = Vec::new();
285        for i in 0..MAX_PROFILES {
286            add(&mut ps, &format!("P{i}"), None, 1).unwrap();
287        }
288        let (first, made) = ensure_agent_profile(&mut ps, "uid-1", "camper-2", 7);
289        assert!(made && is_profile_id(&first.id), "{first:?}");
290        assert_eq!((first.id.clone(), first.name.as_str(), first.owner_agent.as_deref()), (agent_profile_id("uid-1"), "camper-2", Some("uid-1")));
291        assert!(!first.agents_allowed);
292        let (again, made) = ensure_agent_profile(&mut ps, "uid-1", "camper-2", 9);
293        assert!(!made && again == first, "a second open reuses it");
294        // A rename keeps the data (the same row, the same id) and shows the new name.
295        let (renamed, changed) = ensure_agent_profile(&mut ps, "uid-1", "camper-9", 9);
296        assert!(changed && renamed.id == first.id && renamed.name == "camper-9");
297        assert_eq!(ps.len(), MAX_PROFILES + 1);
298        // The user's cap counts only the user's profiles, and an agent's name doesn't take theirs.
299        assert!(add(&mut ps, "One more", None, 1).is_err());
300        ensure_agent_profile(&mut ps, "uid-2", "Work", 1);
301        remove(&mut ps, "p-none").unwrap_err();
302        let id = ps[0].id.clone();
303        remove(&mut ps, &id).unwrap();
304        add(&mut ps, "Work", None, 1).unwrap();
305    }
306
307    #[test]
308    fn an_agent_profile_id_keeps_to_the_characters_and_length_of_a_profile_id() {
309        let (a, b) = (agent_profile_id("Naki_2"), agent_profile_id("naki-2"));
310        assert!(a.starts_with("agent-naki-2-") && b.starts_with("agent-naki-2-") && a != b, "{a} {b}");
311        let (long, longer) = (agent_profile_id(&"x".repeat(200)), agent_profile_id(&format!("{}y", "x".repeat(200))));
312        assert!(is_profile_id(&long) && is_profile_id(&longer) && long != longer, "{long}");
313        assert_eq!(agent_profile_id("uid-1"), agent_profile_id("uid-1"));
314    }
315
316    #[test]
317    fn a_profiles_file_from_before_agent_profiles_still_loads() {
318        let old = r##"[{"id":"p-1","name":"Work","color":"#3b82f6","created_at":1,"agents_allowed":true}]"##;
319        let ps: Vec<BrowserProfile> = serde_json::from_str(old).unwrap();
320        assert_eq!(ps[0].owner_agent, None);
321        assert!(!serde_json::to_string(&ps).unwrap().contains("owner_agent"));
322    }
323}