1use 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 pub id: String,
24 pub name: String,
25 pub color: String,
27 #[serde(default)]
28 #[ts(type = "number")]
29 pub created_at: i64,
30 #[serde(default)]
33 pub agents_allowed: bool,
34 #[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
49pub 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
63pub 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 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
83pub 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
115pub 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
140pub 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 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
150pub 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
170pub 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
193pub 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 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 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 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}