glass-browser 0.3.9

Local browser intelligence runtime with semantic memory, verified workflows, multi-surface understanding, CLI, TUI, MCP, and Rust APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Chrome user-data directory profile management.
//!
//! Manages named profiles backed by Chrome user-data directories. Profiles
//! persist cookies, localStorage, and all browser state across sessions.

use fs2::FileExt;
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use tracing::info;

/// Manages Chrome user-data directories used as named Glass profiles.
///
/// Chrome owns cookies, local storage, and all other persisted browser state.
/// Glass intentionally does not maintain a second JSON representation of that
/// state: the directory passed to `--user-data-dir` is the sole source of
/// truth.
pub struct ProfileManager {
    profiles_dir: PathBuf,
}

/// Process-held ownership of a profile by one named workspace.
#[derive(Debug)]
pub struct ProfileLock {
    _file: File,
    pub profile: String,
    pub workspace: String,
}

impl ProfileManager {
    pub fn new() -> Self {
        let chrome_path = super::chrome::resolve_chrome_path(None);
        Self::for_browser(chrome_path.as_deref())
    }

    /// Select a persistent profile root that the resolved browser can access.
    ///
    /// Snap Chromium cannot access Chrome user-data directories below the
    /// ordinary host configuration directory. When Glass discovered that
    /// confined browser without an explicit configuration override, keep the
    /// profile in Chromium's Snap-owned common directory instead.
    pub fn for_browser(chrome_path: Option<&Path>) -> Self {
        let explicit_config_home = std::env::var_os("GLASS_CONFIG_HOME").map(PathBuf::from);
        let profiles_dir = profile_root_for_browser(
            explicit_config_home.as_deref(),
            dirs::config_dir().as_deref(),
            dirs::home_dir().as_deref(),
            chrome_path,
            Path::new("/snap/bin/chromium").is_file(),
        );
        if is_snap_chromium(chrome_path, Path::new("/snap/bin/chromium").is_file())
            && explicit_config_home.is_none()
        {
            info!(
                path = %profiles_dir.display(),
                "using Snap-accessible Chromium profile root"
            );
        }
        Self { profiles_dir }
    }

    pub fn validate_name(name: &str) -> Result<(), Box<dyn std::error::Error>> {
        if name.is_empty()
            || name == "."
            || name == ".."
            || name.len() > 64
            || !name
                .chars()
                .all(|character| character.is_ascii_alphanumeric() || "-_".contains(character))
        {
            return Err(
                "profile names must be 1-64 characters of A-Z, a-z, 0-9, '-' or '_'".into(),
            );
        }
        Ok(())
    }

    /// Return the canonical Chrome user-data directory for a profile.
    pub fn profile_dir(&self, name: &str) -> PathBuf {
        self.profile_data_root().join(name)
    }

    /// Create (or return) a named profile's Chrome user-data directory.
    ///
    /// Older Glass versions stored Chrome data in `<name>_chrome` alongside a
    /// JSON metadata file. Move that existing browser data into the canonical
    /// directory before use so Chrome remains the authority for persistence.
    pub fn create_profile(&self, name: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
        Self::validate_name(name)?;
        std::fs::create_dir_all(self.profile_data_root())?;

        let profile_dir = self.profile_dir(name);
        let legacy_chrome_dir = self.legacy_chrome_data_dir(name);
        if !profile_dir.exists() && legacy_chrome_dir.is_dir() {
            std::fs::rename(&legacy_chrome_dir, &profile_dir)?;
            info!(%name, "migrated legacy Chrome profile directory");
        }
        std::fs::create_dir_all(&profile_dir)?;
        info!(%name, path = %profile_dir.display(), "ensured Chrome profile directory");
        Ok(profile_dir)
    }

    /// Ensure a named profile exists and return its Chrome user-data directory.
    pub fn ensure_profile_dir(&self, name: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
        self.create_profile(name)
    }

    pub fn list_profiles(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let mut profiles = Vec::new();
        let profile_data_root = self.profile_data_root();
        if profile_data_root.exists() {
            for entry in std::fs::read_dir(profile_data_root)? {
                let entry = entry?;
                if entry.path().is_dir()
                    && let Some(name) = entry.file_name().to_str()
                    && Self::validate_name(name).is_ok()
                {
                    profiles.push(name.to_string());
                }
            }
        }

        // Older releases stored profile data and metadata directly under the
        // profiles root. Include those names until they are migrated on use.
        if self.profiles_dir.exists() {
            for entry in std::fs::read_dir(&self.profiles_dir)? {
                let entry = entry?;
                let path = entry.path();
                let file_name = entry.file_name();
                let Some(file_name) = file_name.to_str() else {
                    continue;
                };

                let name = if path.is_dir() {
                    file_name.strip_suffix("_chrome").map(str::to_string)
                } else if path.extension().and_then(|extension| extension.to_str()) == Some("json")
                {
                    Some(file_name.trim_end_matches(".json").to_string())
                } else {
                    None
                };

                if let Some(name) = name
                    && Self::validate_name(&name).is_ok()
                {
                    profiles.push(name);
                }
            }
        }
        profiles.sort();
        profiles.dedup();
        Ok(profiles)
    }

    /// Delete all persisted state for a named profile.
    ///
    /// The canonical Chrome user-data directory is removed, as are the legacy
    /// browser directory and JSON metadata left by older Glass releases.
    pub fn delete_profile(&self, name: &str) -> Result<(), Box<dyn std::error::Error>> {
        Self::validate_name(name)?;
        let _ownership = self.acquire_profile_lock(name)?;

        remove_dir_if_exists(&self.profile_dir(name))?;
        remove_dir_if_exists(&self.legacy_chrome_data_dir(name))?;

        let legacy_metadata = self.legacy_metadata_path(name);
        if legacy_metadata.exists() {
            std::fs::remove_file(legacy_metadata)?;
        }
        info!(%name, "deleted persisted Chrome profile data");
        Ok(())
    }
    fn acquire_profile_lock(&self, profile: &str) -> Result<File, Box<dyn std::error::Error>> {
        std::fs::create_dir_all(&self.profiles_dir)?;
        let lock_path = self.profiles_dir.join(format!("{profile}.lock"));
        let file = OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(lock_path)?;
        file.try_lock_exclusive()
            .map_err(|error| -> Box<dyn std::error::Error> {
                format!("profile {profile} is already owned: {error}").into()
            })?;
        Ok(file)
    }

    /// Acquire an exclusive process lock tying this profile to one workspace.
    /// The guard must remain alive for the duration of browser ownership.
    pub fn lock_profile(
        &self,
        profile: &str,
        workspace: &str,
    ) -> Result<ProfileLock, Box<dyn std::error::Error>> {
        Self::validate_name(profile)?;
        Self::validate_name(workspace)?;
        let file = self.acquire_profile_lock(profile)?;
        self.create_profile(profile)?;
        Ok(ProfileLock {
            _file: file,
            profile: profile.to_owned(),
            workspace: workspace.to_owned(),
        })
    }

    fn legacy_chrome_data_dir(&self, name: &str) -> PathBuf {
        self.profiles_dir.join(format!("{name}_chrome"))
    }

    fn profile_data_root(&self) -> PathBuf {
        self.profiles_dir.join("data")
    }

    fn legacy_metadata_path(&self, name: &str) -> PathBuf {
        self.profiles_dir.join(format!("{name}.json"))
    }

    #[cfg(test)]
    fn with_profiles_dir(profiles_dir: PathBuf) -> Self {
        Self { profiles_dir }
    }
}

fn profile_root_for_browser(
    explicit_config_home: Option<&Path>,
    config_home: Option<&Path>,
    home: Option<&Path>,
    chrome_path: Option<&Path>,
    snap_chromium_available: bool,
) -> PathBuf {
    if let Some(root) = explicit_config_home {
        return root.join("glass").join("profiles");
    }
    if is_snap_chromium(chrome_path, snap_chromium_available)
        && let Some(home) = home
    {
        return home
            .join("snap")
            .join("chromium")
            .join("common")
            .join("glass")
            .join("profiles");
    }
    config_home
        .unwrap_or_else(|| Path::new("."))
        .join("glass")
        .join("profiles")
}

fn is_snap_chromium(chrome_path: Option<&Path>, snap_chromium_available: bool) -> bool {
    let Some(path) = chrome_path else {
        return false;
    };
    path.starts_with("/snap/")
        || (snap_chromium_available && path == Path::new("/usr/bin/chromium-browser"))
}

fn remove_dir_if_exists(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
    if path.exists() {
        std::fs::remove_dir_all(path)?;
    }
    Ok(())
}

impl Default for ProfileManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_TEST_DIRECTORY: AtomicU64 = AtomicU64::new(0);

    fn test_directory() -> PathBuf {
        let id = NEXT_TEST_DIRECTORY.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("glass-profile-test-{}-{id}", std::process::id()))
    }

    #[test]
    fn validates_profile_names() {
        assert!(ProfileManager::validate_name("work").is_ok());
        assert!(ProfileManager::validate_name("personal_2026").is_ok());
        assert!(ProfileManager::validate_name("../escape").is_err());
        assert!(ProfileManager::validate_name("with space").is_err());
    }

    #[test]
    fn profiles_are_chrome_data_directories_and_delete_removes_legacy_data() {
        let profiles_dir = test_directory();
        let manager = ProfileManager::with_profiles_dir(profiles_dir.clone());
        let profile_dir = manager.create_profile("work").unwrap();
        std::fs::write(profile_dir.join("Cookies"), "persisted-by-chrome").unwrap();
        std::fs::create_dir_all(manager.legacy_chrome_data_dir("work")).unwrap();
        std::fs::write(
            manager.legacy_chrome_data_dir("work").join("History"),
            "legacy",
        )
        .unwrap();
        std::fs::write(manager.legacy_metadata_path("work"), "{}\n").unwrap();

        assert_eq!(manager.list_profiles().unwrap(), vec!["work"]);
        manager.delete_profile("work").unwrap();

        assert!(!profile_dir.exists());

        assert!(!manager.legacy_chrome_data_dir("work").exists());
        assert!(!manager.legacy_metadata_path("work").exists());
        assert!(manager.list_profiles().unwrap().is_empty());
        let _ = std::fs::remove_dir_all(profiles_dir);
    }
    #[test]
    fn delete_profile_rejects_an_active_workspace_owner() {
        let profiles_dir = test_directory();
        let manager = ProfileManager::with_profiles_dir(profiles_dir.clone());
        let _owner = manager.lock_profile("work", "workspace").unwrap();
        assert!(manager.delete_profile("work").is_err());
        let _ = std::fs::remove_dir_all(profiles_dir);
    }
    #[test]
    fn profile_lock_rejects_second_owner() {
        let profiles_dir = test_directory();
        let first = ProfileManager::with_profiles_dir(profiles_dir.clone());
        let second = ProfileManager::with_profiles_dir(profiles_dir.clone());
        let _owner = first.lock_profile("work", "first").unwrap();
        assert!(second.lock_profile("work", "second").is_err());
        let _ = std::fs::remove_dir_all(profiles_dir);
    }

    #[test]
    fn create_profile_migrates_legacy_chrome_data() {
        let profiles_dir = test_directory();
        let manager = ProfileManager::with_profiles_dir(profiles_dir.clone());
        std::fs::create_dir_all(manager.legacy_chrome_data_dir("work")).unwrap();
        std::fs::write(
            manager.legacy_chrome_data_dir("work").join("Cookies"),
            "legacy",
        )
        .unwrap();

        let profile_dir = manager.create_profile("work").unwrap();

        assert!(profile_dir.join("Cookies").exists());
        assert!(!manager.legacy_chrome_data_dir("work").exists());
        let _ = std::fs::remove_dir_all(profiles_dir);
    }

    #[test]
    fn profile_names_ending_in_chrome_are_not_confused_with_legacy_directories() {
        let profiles_dir = test_directory();
        let manager = ProfileManager::with_profiles_dir(profiles_dir.clone());

        manager.create_profile("work_chrome").unwrap();

        assert_eq!(manager.list_profiles().unwrap(), vec!["work_chrome"]);
        let _ = std::fs::remove_dir_all(profiles_dir);
    }

    #[test]
    fn snap_chromium_uses_its_accessible_common_directory_by_default() {
        let root = profile_root_for_browser(
            None,
            Some(Path::new("/home/user/.config")),
            Some(Path::new("/home/user")),
            Some(Path::new("/snap/bin/chromium")),
            true,
        );

        assert_eq!(
            root,
            Path::new("/home/user/snap/chromium/common/glass/profiles")
        );
    }

    #[test]
    fn explicit_config_home_wins_over_confined_browser_detection() {
        let root = profile_root_for_browser(
            Some(Path::new("/configured")),
            Some(Path::new("/home/user/.config")),
            Some(Path::new("/home/user")),
            Some(Path::new("/usr/bin/chromium-browser")),
            true,
        );

        assert_eq!(root, Path::new("/configured/glass/profiles"));
    }

    #[test]
    fn unconfined_chromium_keeps_the_standard_profile_root() {
        let root = profile_root_for_browser(
            None,
            Some(Path::new("/home/user/.config")),
            Some(Path::new("/home/user")),
            Some(Path::new("/usr/bin/chromium")),
            false,
        );

        assert_eq!(root, Path::new("/home/user/.config/glass/profiles"));
    }
}