Skip to main content

agent_hub_runtime/core/preview/
profiles.rs

1//! Persistent and temporary browser profile management.
2use super::{
3    super::error::AppError,
4    browser::Browsers,
5    runtime::{self, BrowserProfile},
6};
7use std::fs;
8impl Browsers {
9    pub fn profiles(&self) -> Result<Vec<BrowserProfile>, AppError> {
10        let path = self.root.join("profiles.json");
11        if !path.exists() {
12            return Ok(vec![BrowserProfile::default(), BrowserProfile::guest()]);
13        }
14        let bytes = fs::read(path)?;
15        if bytes.len() > 128 * 1024 {
16            return Err(AppError::invalid_input(
17                "Profile configuration exceeds limit",
18            ));
19        }
20        let mut profiles: Vec<BrowserProfile> =
21            serde_json::from_slice(&bytes).map_err(AppError::io)?;
22        if profiles
23            .iter()
24            .filter(|profile| !matches!(profile.id.as_str(), "default" | "guest"))
25            .count()
26            > 20
27        {
28            return Err(AppError::invalid_input("Profile limit reached"));
29        }
30        let mut seen = std::collections::HashSet::new();
31        for profile in &mut profiles {
32            runtime::validate_profile(profile)?;
33            if !seen.insert(profile.id.to_ascii_lowercase()) {
34                return Err(AppError::invalid_input("Duplicate browser profile"));
35            }
36            if profile.id == "guest" {
37                profile.ephemeral = true;
38            }
39        }
40        if !seen.contains("default") {
41            profiles.insert(0, BrowserProfile::default());
42        }
43        if !seen.contains("guest") {
44            profiles.push(BrowserProfile::guest());
45        }
46        Ok(profiles)
47    }
48    pub fn save_profile(&self, mut profile: BrowserProfile) -> Result<(), AppError> {
49        if profile.id == "guest" {
50            profile.ephemeral = true;
51        }
52        runtime::validate_profile(&profile)?;
53        let state = self
54            .state
55            .lock()
56            .map_err(|_| AppError::internal("Browser state unavailable"))?;
57        if state
58            .transfers
59            .iter()
60            .any(|(key, job)| key.starts_with(&format!("{}:", profile.id)) && job.active())
61        {
62            return Err(AppError::invalid_input(
63                "Wait for the profile transfer to finish",
64            ));
65        }
66        if state.closing
67            || state.reopening_profiles.contains_key(&profile.id)
68            || state.runtimes.contains_key(&profile.id)
69            || state.pending.values().any(|id| id == &profile.id)
70        {
71            return Err(AppError::invalid_input(
72                "Close the profile's pages and wait for downloads before changing its settings",
73            ));
74        }
75        let mut profiles = self.profiles()?;
76        if profiles.iter().any(|existing| {
77            existing.id != profile.id && existing.id.eq_ignore_ascii_case(&profile.id)
78        }) {
79            return Err(AppError::invalid_input(
80                "Profile identifiers must be unique regardless of case",
81            ));
82        }
83        if profile.deleting
84            || profiles
85                .iter()
86                .any(|existing| existing.id == profile.id && existing.deleting)
87        {
88            return Err(AppError::invalid_input(
89                "Retry the pending profile deletion before changing its settings",
90            ));
91        }
92        profiles.retain(|existing| existing.id != profile.id);
93        if !matches!(profile.id.as_str(), "default" | "guest")
94            && profiles
95                .iter()
96                .filter(|profile| !matches!(profile.id.as_str(), "default" | "guest"))
97                .count()
98                >= 20
99        {
100            return Err(AppError::invalid_input("Profile limit reached"));
101        }
102        profiles.push(profile);
103        self.write_profiles(&profiles)
104    }
105
106    fn write_profiles(&self, profiles: &[BrowserProfile]) -> Result<(), AppError> {
107        fs::create_dir_all(&self.root)?;
108        let mut file = tempfile::NamedTempFile::new_in(&self.root)?;
109        use std::io::Write;
110        let bytes = serde_json::to_vec_pretty(profiles).map_err(AppError::io)?;
111        if bytes.len() > 128 * 1024 {
112            return Err(AppError::invalid_input(
113                "Profile configuration exceeds limit",
114            ));
115        }
116        file.write_all(&bytes)?;
117        file.persist(self.root.join("profiles.json"))
118            .map_err(|error| AppError::io(error.error))?;
119        Ok(())
120    }
121    pub fn delete_profile(&self, id: &str) -> Result<(), AppError> {
122        self.delete_profile_with(id, |path| fs::remove_dir_all(path))
123    }
124    fn delete_profile_with(
125        &self,
126        id: &str,
127        cleanup: impl FnOnce(&std::path::Path) -> std::io::Result<()>,
128    ) -> Result<(), AppError> {
129        if matches!(id, "default" | "guest") {
130            return Err(AppError::invalid_input(
131                "Built-in browser profiles cannot be deleted",
132            ));
133        }
134        let state = self
135            .state
136            .lock()
137            .map_err(|_| AppError::internal("Browser state unavailable"))?;
138        if state
139            .transfers
140            .iter()
141            .any(|(key, job)| key.starts_with(&format!("{id}:")) && job.active())
142        {
143            return Err(AppError::invalid_input(
144                "Wait for the profile transfer to finish",
145            ));
146        }
147        if state.closing
148            || state.reopening_profiles.contains_key(id)
149            || state.runtimes.contains_key(id)
150            || state.pages.values().any(|page| page.profile == id)
151            || state.pending.values().any(|profile| profile == id)
152        {
153            return Err(AppError::invalid_input(
154                "Close the profile's pages and wait for downloads before deleting it",
155            ));
156        }
157        let mut profiles = self.profiles()?;
158        let Some(index) = profiles.iter().position(|profile| profile.id == id) else {
159            return Ok(());
160        };
161        runtime::validate_profile(&profiles[index])?;
162        let parent = self.root.join("profiles");
163        let directory = parent.join(id);
164        let recovery = parent.join(format!(".deleting-{id}"));
165        for path in [&directory, &recovery] {
166            match fs::symlink_metadata(path) {
167                Ok(metadata) => {
168                    if metadata.file_type().is_symlink()
169                        || !metadata.is_dir()
170                        || parent.canonicalize()? != self.root.canonicalize()?.join("profiles")
171                    {
172                        return Err(AppError::invalid_input(
173                            "Profile data is outside the owned directory",
174                        ));
175                    }
176                }
177                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
178                Err(error) => return Err(AppError::io(error)),
179            }
180        }
181        if recovery.exists() && (!profiles[index].deleting || directory.exists()) {
182            return Err(AppError::invalid_input(
183                "Profile recovery directory is already occupied",
184            ));
185        }
186        // Record the intent before moving or removing data. A failed cleanup remains visible and retryable.
187        if !profiles[index].deleting {
188            profiles[index].deleting = true;
189            self.write_profiles(&profiles)?;
190        }
191        if directory.exists() {
192            fs::rename(&directory,&recovery).map_err(|error|AppError::io(format!("Profile deletion pending; close applications using its files and retry: {error}")))?;
193        }
194        if recovery.exists() {
195            cleanup(&recovery).map_err(|error|AppError::io(format!("Profile deletion pending; close applications using its files and retry: {error}")))?;
196        }
197        profiles.remove(index);
198        self.write_profiles(&profiles)
199    }
200}
201
202#[cfg(test)]
203#[path = "profiles/tests.rs"]
204mod tests;