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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Browser launching functionality.
mod chromium_args;
mod fs_utils;
mod user_data;
use std::env;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
use tracing::{debug, info, instrument, trace, warn};
use viewpoint_cdp::CdpConnection;
use super::Browser;
use crate::error::BrowserError;
pub use user_data::UserDataDir;
use chromium_args::{CHROMIUM_PATHS, STABILITY_ARGS};
use fs_utils::copy_dir_recursive;
/// Default timeout for browser launch.
const DEFAULT_LAUNCH_TIMEOUT: Duration = Duration::from_secs(30);
/// Builder for launching a browser.
#[derive(Debug, Clone)]
pub struct BrowserBuilder {
/// Path to Chromium executable.
executable_path: Option<PathBuf>,
/// Whether to run in headless mode.
headless: bool,
/// Additional command line arguments.
args: Vec<String>,
/// Launch timeout.
timeout: Duration,
/// User data directory configuration.
user_data_dir: UserDataDir,
}
impl Default for BrowserBuilder {
fn default() -> Self {
Self::new()
}
}
impl BrowserBuilder {
/// Create a new browser builder with default settings.
///
/// By default, the browser uses an isolated temporary directory for user data.
/// This prevents conflicts when running multiple browser instances and ensures
/// clean sessions for automation.
pub fn new() -> Self {
Self {
executable_path: None,
headless: true,
args: Vec::new(),
timeout: DEFAULT_LAUNCH_TIMEOUT,
user_data_dir: UserDataDir::Temp,
}
}
/// Set the path to the Chromium executable.
///
/// If not set, the launcher will search common paths and
/// check the `CHROMIUM_PATH` environment variable.
#[must_use]
pub fn executable_path(mut self, path: impl Into<PathBuf>) -> Self {
self.executable_path = Some(path.into());
self
}
/// Set whether to run in headless mode.
///
/// Default is `true`.
#[must_use]
pub fn headless(mut self, headless: bool) -> Self {
self.headless = headless;
self
}
/// Add additional command line arguments.
#[must_use]
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.args.extend(args.into_iter().map(Into::into));
self
}
/// Set the launch timeout.
///
/// Default is 30 seconds.
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
/// Set a persistent user data directory for browser profile.
///
/// When set, browser state (cookies, localStorage, settings) persists
/// in the specified directory across browser restarts. The directory
/// is NOT cleaned up when the browser closes.
///
/// **Note**: Using the same directory for multiple concurrent browser
/// instances will cause profile lock conflicts.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Browser;
///
/// # async fn example() -> Result<(), viewpoint_core::CoreError> {
/// let browser = Browser::launch()
/// .user_data_dir("/path/to/profile")
/// .launch()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn user_data_dir(mut self, path: impl Into<PathBuf>) -> Self {
self.user_data_dir = UserDataDir::Persist(path.into());
self
}
/// Use the system default profile directory.
///
/// On Linux, this is typically `~/.config/chromium/`.
/// No `--user-data-dir` flag is passed to Chromium.
///
/// **Warning**: This can cause conflicts if another Chromium instance is running,
/// or if a previous session crashed without proper cleanup. Prefer the default
/// isolated temp profile for automation scenarios.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Browser;
///
/// # async fn example() -> Result<(), viewpoint_core::CoreError> {
/// let browser = Browser::launch()
/// .user_data_dir_system()
/// .launch()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn user_data_dir_system(mut self) -> Self {
self.user_data_dir = UserDataDir::System;
self
}
/// Use a template profile copied to a temporary directory.
///
/// The contents of the template directory are copied to a new temporary
/// directory. This allows starting with pre-configured settings, extensions,
/// or cookies while maintaining isolation between sessions.
///
/// The temporary directory is automatically cleaned up when the browser
/// closes or is dropped. The original template directory is unchanged.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Browser;
///
/// # async fn example() -> Result<(), viewpoint_core::CoreError> {
/// // Create a browser with extensions from a template profile
/// let browser = Browser::launch()
/// .user_data_dir_template_from("/path/to/template-profile")
/// .launch()
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Loading Extensions
///
/// Extensions can also be loaded at runtime without a template profile:
///
/// ```no_run
/// use viewpoint_core::Browser;
///
/// # async fn example() -> Result<(), viewpoint_core::CoreError> {
/// let browser = Browser::launch()
/// .args(["--load-extension=/path/to/unpacked-extension"])
/// .launch()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn user_data_dir_template_from(mut self, template_path: impl Into<PathBuf>) -> Self {
self.user_data_dir = UserDataDir::TempFromTemplate(template_path.into());
self
}
/// Launch the browser.
///
/// # Errors
///
/// Returns an error if:
/// - Chromium is not found
/// - The process fails to spawn
/// - The browser doesn't start within the timeout
/// - Template directory doesn't exist or can't be copied
#[instrument(level = "info", skip(self), fields(headless = self.headless, timeout_ms = self.timeout.as_millis()))]
pub async fn launch(self) -> Result<Browser, BrowserError> {
info!("Launching browser");
let executable = self.find_executable()?;
info!(executable = %executable.display(), "Found Chromium executable");
// Handle user data directory configuration
let (user_data_path, temp_dir) = self.prepare_user_data_dir()?;
let mut cmd = Command::new(&executable);
// Add default arguments
cmd.arg("--remote-debugging-port=0");
if self.headless {
cmd.arg("--headless=new");
debug!("Running in headless mode");
} else {
debug!("Running in headed mode");
}
// Add common stability flags
cmd.args(STABILITY_ARGS);
trace!(arg_count = STABILITY_ARGS.len(), "Added stability flags");
// Add user data directory if we have one
if let Some(ref user_data_dir) = user_data_path {
cmd.arg(format!("--user-data-dir={}", user_data_dir.display()));
debug!(user_data_dir = %user_data_dir.display(), "Using user data directory");
} else {
debug!("Using system default user data directory");
}
// Add user arguments
if !self.args.is_empty() {
cmd.args(&self.args);
debug!(user_args = ?self.args, "Added user arguments");
}
// Capture stderr for the WebSocket URL
cmd.stderr(Stdio::piped());
cmd.stdout(Stdio::null());
info!("Spawning Chromium process");
let mut child = cmd.spawn().map_err(|e| {
warn!(error = %e, "Failed to spawn Chromium process");
BrowserError::LaunchFailed(e.to_string())
})?;
let pid = child.id();
info!(pid = pid, "Chromium process spawned");
// Read the WebSocket URL from stderr
debug!("Waiting for DevTools WebSocket URL");
let ws_url = timeout(self.timeout, Self::read_ws_url(&mut child))
.await
.map_err(|_| {
warn!(
timeout_ms = self.timeout.as_millis(),
"Browser launch timed out"
);
BrowserError::LaunchTimeout(self.timeout)
})??;
info!(ws_url = %ws_url, "Got DevTools WebSocket URL");
// Connect to the browser
debug!("Connecting to browser via CDP");
let connection = CdpConnection::connect(&ws_url).await?;
// Enable target discovery to receive Target.targetCreated events
// This is required for automatic page tracking (popups, target="_blank" links)
debug!("Enabling target discovery");
connection
.send_command::<_, serde_json::Value>(
"Target.setDiscoverTargets",
Some(
viewpoint_cdp::protocol::target_domain::SetDiscoverTargetsParams {
discover: true,
},
),
None,
)
.await
.map_err(|e| {
BrowserError::LaunchFailed(format!("Failed to enable target discovery: {e}"))
})?;
info!(pid = pid, "Browser launched and connected successfully");
Ok(Browser::from_launch(connection, child, temp_dir))
}
/// Prepare the user data directory based on configuration.
///
/// Returns the path to use for `--user-data-dir` (if any) and an optional
/// `TempDir` handle that should be stored in the `Browser` struct to ensure
/// cleanup on drop.
fn prepare_user_data_dir(&self) -> Result<(Option<PathBuf>, Option<TempDir>), BrowserError> {
match &self.user_data_dir {
UserDataDir::Temp => {
// Create a unique temporary directory
let temp_dir = TempDir::with_prefix("viewpoint-browser-").map_err(|e| {
BrowserError::LaunchFailed(format!(
"Failed to create temporary user data directory: {e}"
))
})?;
let path = temp_dir.path().to_path_buf();
debug!(path = %path.display(), "Created temporary user data directory");
Ok((Some(path), Some(temp_dir)))
}
UserDataDir::TempFromTemplate(template_path) => {
// Validate template exists
if !template_path.exists() {
return Err(BrowserError::LaunchFailed(format!(
"Template profile directory does not exist: {}",
template_path.display()
)));
}
if !template_path.is_dir() {
return Err(BrowserError::LaunchFailed(format!(
"Template profile path is not a directory: {}",
template_path.display()
)));
}
// Create temporary directory
let temp_dir = TempDir::with_prefix("viewpoint-browser-").map_err(|e| {
BrowserError::LaunchFailed(format!(
"Failed to create temporary user data directory: {e}"
))
})?;
let dest_path = temp_dir.path().to_path_buf();
// Copy template contents to temp directory
debug!(
template = %template_path.display(),
dest = %dest_path.display(),
"Copying template profile to temporary directory"
);
copy_dir_recursive(template_path, &dest_path).map_err(|e| {
BrowserError::LaunchFailed(format!("Failed to copy template profile: {e}"))
})?;
info!(
template = %template_path.display(),
dest = %dest_path.display(),
"Template profile copied to temporary directory"
);
Ok((Some(dest_path), Some(temp_dir)))
}
UserDataDir::Persist(path) => {
// Use the specified path, no cleanup
debug!(path = %path.display(), "Using persistent user data directory");
Ok((Some(path.clone()), None))
}
UserDataDir::System => {
// No --user-data-dir flag, use system default
debug!("Using system default user data directory");
Ok((None, None))
}
}
}
/// Find the Chromium executable.
#[instrument(level = "debug", skip(self))]
fn find_executable(&self) -> Result<PathBuf, BrowserError> {
// Check if explicitly set
if let Some(ref path) = self.executable_path {
debug!(path = %path.display(), "Checking explicit executable path");
if path.exists() {
info!(path = %path.display(), "Using explicit executable path");
return Ok(path.clone());
}
warn!(path = %path.display(), "Explicit executable path does not exist");
return Err(BrowserError::ChromiumNotFound);
}
// Check environment variable
if let Ok(path_str) = env::var("CHROMIUM_PATH") {
let path = PathBuf::from(&path_str);
debug!(path = %path.display(), "Checking CHROMIUM_PATH environment variable");
if path.exists() {
info!(path = %path.display(), "Using CHROMIUM_PATH");
return Ok(path);
}
warn!(path = %path.display(), "CHROMIUM_PATH does not exist");
}
// Search common paths
debug!("Searching common Chromium paths");
for path_str in CHROMIUM_PATHS {
let path = PathBuf::from(path_str);
if path.exists() {
info!(path = %path.display(), "Found Chromium at common path");
return Ok(path);
}
// Also try which/where
if let Ok(output) = Command::new("which").arg(path_str).output() {
if output.status.success() {
let found = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !found.is_empty() {
let found_path = PathBuf::from(&found);
info!(path = %found_path.display(), "Found Chromium via 'which'");
return Ok(found_path);
}
}
}
}
warn!("Chromium not found in any expected location");
Err(BrowserError::ChromiumNotFound)
}
/// Read the WebSocket URL from the browser's stderr.
async fn read_ws_url(child: &mut Child) -> Result<String, BrowserError> {
let stderr = child
.stderr
.take()
.ok_or_else(|| BrowserError::LaunchFailed("failed to capture stderr".into()))?;
// Spawn blocking read in a separate task
let handle = tokio::task::spawn_blocking(move || {
let reader = BufReader::new(stderr);
for line in reader.lines() {
let Ok(line) = line else { continue };
trace!(line = %line, "Read line from Chromium stderr");
// Look for "DevTools listening on ws://..."
if let Some(pos) = line.find("DevTools listening on ") {
let url = &line[pos + 22..];
return Some(url.trim().to_string());
}
}
None
});
handle
.await
.map_err(|e| BrowserError::LaunchFailed(e.to_string()))?
.ok_or(BrowserError::LaunchFailed(
"failed to find WebSocket URL in browser output".into(),
))
}
}