Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2385,6 +2385,7 @@ mod tests {
model: None,
verbose: false,
quiet: false,
background: false,
}
}

Expand Down
4 changes: 4 additions & 0 deletions cli/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ pub struct DaemonOptions<'a> {
pub default_timeout: Option<u64>,
pub cdp: Option<&'a str>,
pub no_auto_dialog: bool,
pub background: bool,
}

fn apply_daemon_env(cmd: &mut Command, session: &str, opts: &DaemonOptions) {
Expand Down Expand Up @@ -314,6 +315,9 @@ fn apply_daemon_env(cmd: &mut Command, session: &str, opts: &DaemonOptions) {
if opts.no_auto_dialog {
cmd.env("AGENT_BROWSER_NO_AUTO_DIALOG", "1");
}
if opts.background {
cmd.env("AGENT_BROWSER_BACKGROUND", "1");
}
}

/// Check if the running daemon's version matches this CLI binary.
Expand Down
13 changes: 13 additions & 0 deletions cli/src/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub struct Config {
pub idle_timeout: Option<String>,
pub no_auto_dialog: Option<bool>,
pub model: Option<String>,
pub background: Option<bool>,
}

impl Config {
Expand Down Expand Up @@ -136,6 +137,7 @@ impl Config {
idle_timeout: other.idle_timeout.or(self.idle_timeout),
no_auto_dialog: other.no_auto_dialog.or(self.no_auto_dialog),
model: other.model.or(self.model),
background: other.background.or(self.background),
}
}
}
Expand Down Expand Up @@ -308,6 +310,7 @@ pub struct Flags {
pub model: Option<String>,
pub verbose: bool,
pub quiet: bool,
pub background: bool,

// Track which launch-time options were explicitly passed via CLI
// (as opposed to being set only via environment variables)
Expand Down Expand Up @@ -447,6 +450,8 @@ pub fn parse_flags(args: &[String]) -> Flags {
model: env::var("AI_GATEWAY_MODEL").ok().or(config.model),
verbose: false,
quiet: false,
background: env_var_is_truthy("AGENT_BROWSER_BACKGROUND")
|| config.background.unwrap_or(false),
cli_executable_path: false,
cli_extensions: false,
cli_profile: false,
Expand Down Expand Up @@ -728,6 +733,13 @@ pub fn parse_flags(args: &[String]) -> Flags {
i += 1;
}
}
"--background" => {
let (val, consumed) = parse_bool_arg(args, i);
flags.background = val;
if consumed {
i += 1;
}
}
"--model" => {
if let Some(s) = args.get(i + 1) {
flags.model = Some(s.clone());
Expand Down Expand Up @@ -767,6 +779,7 @@ pub fn clean_args(args: &[String]) -> Vec<String> {
"--content-boundaries",
"--confirm-interactive",
"--no-auto-dialog",
"--background",
"-v",
"--verbose",
"-q",
Expand Down
5 changes: 5 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,7 @@ fn main() {
default_timeout: flags.default_timeout,
cdp: flags.cdp.as_deref(),
no_auto_dialog: flags.no_auto_dialog,
background: flags.background,
};

let daemon_result = match ensure_daemon(&flags.session, &daemon_opts) {
Expand Down Expand Up @@ -1287,6 +1288,10 @@ fn main() {

let output_opts = OutputOptions::from_flags(&flags);

if flags.background {
cmd["background"] = json!(true);
}

match send_command(cmd.clone(), &flags.session) {
Ok(resp) => {
let success = resp.success;
Expand Down
46 changes: 33 additions & 13 deletions cli/src/native/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ pub struct DaemonState {
/// When true, automatically dismiss `beforeunload` dialogs and accept `alert`
/// dialogs so they never block the agent. Enabled by default.
pub auto_dialog: bool,
/// When true, new tabs are created in the background and tab switches skip
/// Page.bringToFront so the user's current browser tab is not disturbed.
pub background: bool,
/// Shared slot for stream server to receive CDP client when browser launches.
pub stream_client: Option<Arc<RwLock<Option<Arc<CdpClient>>>>>,
/// Stream server instance kept alive so the broadcast channel remains open.
Expand Down Expand Up @@ -293,6 +296,10 @@ impl DaemonState {
env::var("AGENT_BROWSER_NO_AUTO_DIALOG").as_deref(),
Ok("1" | "true" | "yes")
),
background: matches!(
env::var("AGENT_BROWSER_BACKGROUND").as_deref(),
Ok("1" | "true" | "yes")
),
stream_client: None,
stream_server: None,
launch_hash: None,
Expand Down Expand Up @@ -1479,14 +1486,16 @@ pub async fn execute_command(cmd: &Value, state: &mut DaemonState) -> Value {

/// Connect to a running Chrome via auto-discovery and open a fresh tab so
/// subsequent navigations don't hijack the user's existing tabs.
async fn connect_auto_with_fresh_tab() -> Result<BrowserManager, String> {
async fn connect_auto_with_fresh_tab(background: bool) -> Result<BrowserManager, String> {
let mut mgr = BrowserManager::connect_auto().await?;
mgr.tab_new(None).await?;
let session_id = mgr.active_session_id()?.to_string();
let _ = mgr
.client
.send_command("Page.bringToFront", None, Some(&session_id))
.await;
mgr.tab_new(None, background).await?;
if !background {
let session_id = mgr.active_session_id()?.to_string();
let _ = mgr
.client
.send_command("Page.bringToFront", None, Some(&session_id))
.await;
}
Ok(mgr)
}

Expand Down Expand Up @@ -1528,7 +1537,7 @@ async fn auto_launch(state: &mut DaemonState) -> Result<(), String> {

if env::var("AGENT_BROWSER_AUTO_CONNECT").is_ok() {
state.reset_input_state();
state.browser = Some(connect_auto_with_fresh_tab().await?);
state.browser = Some(connect_auto_with_fresh_tab(state.background).await?);
state.subscribe_to_browser_events();
state.start_fetch_handler();
state.start_dialog_handler();
Expand Down Expand Up @@ -1818,7 +1827,7 @@ async fn handle_launch(cmd: &Value, state: &mut DaemonState) -> Result<Value, St

if auto_connect {
state.reset_input_state();
state.browser = Some(connect_auto_with_fresh_tab().await?);
state.browser = Some(connect_auto_with_fresh_tab(state.background).await?);
state.subscribe_to_browser_events();
state.start_fetch_handler();
state.start_dialog_handler();
Expand Down Expand Up @@ -2122,7 +2131,18 @@ async fn handle_navigate(cmd: &Value, state: &mut DaemonState) -> Result<Value,
state.ref_map.clear();
state.iframe_sessions.clear();
state.active_frame_id = None;
mgr.navigate(url, wait_until).await
let result = mgr.navigate(url, wait_until).await?;

let bg = cmd.get("background").and_then(|v| v.as_bool()).unwrap_or(state.background);
if !bg {
let session_id = mgr.active_session_id()?.to_string();
let _ = mgr
.client
.send_command("Page.bringToFront", None, Some(&session_id))
.await;
}

Ok(result)
}

async fn handle_url(state: &DaemonState) -> Result<Value, String> {
Expand Down Expand Up @@ -2506,7 +2526,7 @@ async fn handle_click(cmd: &Value, state: &mut DaemonState) -> Result<Value, Str

let mgr = state.browser.as_mut().ok_or("Browser not launched")?;
state.ref_map.clear();
mgr.tab_new(Some(&href)).await?;
mgr.tab_new(Some(&href), state.background).await?;

return Ok(json!({ "clicked": selector, "newTab": true, "url": href }));
}
Expand Down Expand Up @@ -3558,7 +3578,7 @@ async fn handle_tab_new(cmd: &Value, state: &mut DaemonState) -> Result<Value, S
state.ref_map.clear();
state.iframe_sessions.clear();
state.active_frame_id = None;
mgr.tab_new(url).await
mgr.tab_new(url, state.background).await
}

async fn handle_tab_switch(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
Expand All @@ -3570,7 +3590,7 @@ async fn handle_tab_switch(cmd: &Value, state: &mut DaemonState) -> Result<Value
state.ref_map.clear();
state.iframe_sessions.clear();
state.active_frame_id = None;
let result = mgr.tab_switch(index).await?;
let result = mgr.tab_switch(index, state.background).await?;

if let Some(ref server) = state.stream_server {
if let Ok(dims) = mgr
Expand Down
18 changes: 11 additions & 7 deletions cli/src/native/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,7 @@ impl BrowserManager {
"Target.createTarget",
&CreateTargetParams {
url: "about:blank".to_string(),
background: None,
},
None,
)
Expand Down Expand Up @@ -784,6 +785,7 @@ impl BrowserManager {
"Target.createTarget",
&CreateTargetParams {
url: "about:blank".to_string(),
background: None,
},
None,
)
Expand Down Expand Up @@ -846,7 +848,7 @@ impl BrowserManager {
.collect()
}

pub async fn tab_new(&mut self, url: Option<&str>) -> Result<Value, String> {
pub async fn tab_new(&mut self, url: Option<&str>, background: bool) -> Result<Value, String> {
let target_url = url.unwrap_or("about:blank");

let result: CreateTargetResult = self
Expand All @@ -855,6 +857,7 @@ impl BrowserManager {
"Target.createTarget",
&CreateTargetParams {
url: target_url.to_string(),
background: if background { Some(true) } else { None },
},
None,
)
Expand Down Expand Up @@ -887,7 +890,7 @@ impl BrowserManager {
Ok(json!({ "index": index, "url": target_url }))
}

pub async fn tab_switch(&mut self, index: usize) -> Result<Value, String> {
pub async fn tab_switch(&mut self, index: usize, background: bool) -> Result<Value, String> {
if index >= self.pages.len() {
return Err(format!(
"Tab index {} out of range (0-{})",
Expand All @@ -900,11 +903,12 @@ impl BrowserManager {
let session_id = self.pages[index].session_id.clone();
self.enable_domains(&session_id).await?;

// Bring tab to front
let _ = self
.client
.send_command("Page.bringToFront", None, Some(&session_id))
.await;
if !background {
let _ = self
.client
.send_command("Page.bringToFront", None, Some(&session_id))
.await;
}

let url = self.get_url().await.unwrap_or_default();
let title = self.get_title().await.unwrap_or_default();
Expand Down
2 changes: 2 additions & 0 deletions cli/src/native/cdp/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ pub struct SetDiscoverTargetsParams {
#[serde(rename_all = "camelCase")]
pub struct CreateTargetParams {
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub background: Option<bool>,
}

#[derive(Debug, Deserialize)]
Expand Down
1 change: 1 addition & 0 deletions cli/src/native/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ async fn collect_storage_via_temp_target(
"Target.createTarget",
&CreateTargetParams {
url: "about:blank".to_string(),
background: None,
},
None,
)
Expand Down
1 change: 1 addition & 0 deletions cli/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2934,6 +2934,7 @@ Options:
--confirm-interactive Interactive confirmation prompts; auto-denies if stdin is not a TTY (or AGENT_BROWSER_CONFIRM_INTERACTIVE)
--engine <name> Browser engine: chrome (default), lightpanda (or AGENT_BROWSER_ENGINE)
--no-auto-dialog Disable automatic dismissal of alert/beforeunload dialogs (or AGENT_BROWSER_NO_AUTO_DIALOG)
--background Create new tabs in the background and skip focus switching (or AGENT_BROWSER_BACKGROUND)
--model <name> AI model for chat (or AI_GATEWAY_MODEL env)
-v, --verbose Show tool commands and their raw output
-q, --quiet Show only AI text responses (hide tool calls)
Expand Down