Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat: drive Chromium apps through a verified DevTools endpoint from launch --cdp (#129)
Lahfir366d34803992
diff --git a/README.md b/README.mdindex 93177007e..33a49652b 100644--- a/README.md+++ b/README.md@@ -47,6 +47,7 @@- **Headless-by-default interactions**: Ref actions use accessibility APIs and block silent focus, cursor, keyboard, or pasteboard side effects- **Structured JSON output**: Machine-readable responses with error codes and recovery hints- **Works with any app**: Finder, Safari, System Settings, Xcode, Slack — anything with an accessibility tree+- **Chromium-app interop via CDP**: `launch --cdp` opens a verified DevTools port so any framework that speaks CDP — Playwright, Puppeteer, `chrome-remote-interface`, agent-browser — can drive the web contents, while native menus, dialogs, and windows stay on the accessibility path## Installation@@ -173,6 +174,28 @@ agent-desktop session end "$AGENT_DESKTOP_SESSION"agent-desktop session gc```+## Driving Chromium apps (CDP)++For a Chromium-based app (Slack, VS Code, Discord, Obsidian, Notion), `launch --cdp` opens a verified Chrome DevTools Protocol endpoint on the web contents. Any framework that speaks CDP can connect — Playwright, Puppeteer, `chrome-remote-interface`, agent-browser — with agent-browser preferred for its ref-based agent workflow and bundled `electron` skill. Native surfaces (menus, dialogs, windows, screenshots) stay on the accessibility path either way.++```bash+agent-desktop launch "Obsidian" --cdp+```++```json+{ "app": "Obsidian", "pid": 4821, "cdp": {+ "port": 9229,+ "http_endpoint": "http://127.0.0.1:9229",+ "websocket_url": "ws://127.0.0.1:9229/devtools/browser/<id>",+ "product": "Chrome/142.0.7444.265"+},+ "suggestion": "Next: run `agent-browser connect 9229` (preferred) or connect any CDP client such as Playwright or Puppeteer. ..." }+```++`--cdp` needs a fresh launch — an already-running target returns `ACTION_FAILED`. Run `close-app` first, confirm the process exited, then `launch --cdp` again.++The endpoint is pinned to `127.0.0.1`. Any local process running as your user can still reach it while it stays open; `close-app` ends the exposure along with the app.+## Commands### Observation@@ -240,6 +263,7 @@ agent-desktop --headed mouse-click --xy 500,300 # click at coordinates```bashagent-desktop launch Safari # launch app by nameagent-desktop launch com.apple.Safari # launch by bundle ID+agent-desktop launch "Obsidian" --cdp # fresh launch + verified CDP port for web contentsagent-desktop close-app Safari # quit appagent-desktop close-app Safari --force # force quit (SIGTERM, then SIGKILL if needed)agent-desktop list-apps # list running GUI appsdiff --git a/crates/core/src/app_info.rs b/crates/core/src/app_info.rsindex c686ee134..c87aa8501 100644--- a/crates/core/src/app_info.rs+++ b/crates/core/src/app_info.rs@@ -26,3 +26,56 @@ pub struct AppInfo {#[serde(default, skip_serializing_if = "Option::is_none")]pub presentation: Option<AppPresentation>,}++impl AppInfo {+ /// Whether `id` identifies this application, by exact case-insensitive+ /// name or bundle identifier. The one predicate every launch-target+ /// match uses, so a name match and a bundle match never drift apart.+ pub fn matches_identifier(&self, id: &str) -> bool {+ self.name.eq_ignore_ascii_case(id)+ || self+ .bundle_id+ .as_deref()+ .is_some_and(|bundle_id| bundle_id.eq_ignore_ascii_case(id))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn app(name: &str, bundle_id: Option<&str>) -> AppInfo {+ AppInfo {+ name: name.to_owned(),+ pid: ProcessId::new(1),+ bundle_id: bundle_id.map(str::to_owned),+ process_instance: None,+ presentation: None,+ }+ }++ #[test]+ fn matches_by_exact_name() {+ assert!(app("Fixture", None).matches_identifier("Fixture"));+ }++ #[test]+ fn matches_by_bundle_id() {+ assert!(+ app("Fixture", Some("com.example.fixture")).matches_identifier("com.example.fixture")+ );+ }++ #[test]+ fn matches_are_case_insensitive() {+ assert!(app("Fixture", None).matches_identifier("fixture"));+ assert!(+ app("Fixture", Some("com.example.Fixture")).matches_identifier("COM.EXAMPLE.FIXTURE")+ );+ }++ #[test]+ fn does_not_match_an_unrelated_identifier() {+ assert!(!app("Fixture", Some("com.example.fixture")).matches_identifier("Other"));+ }+}diff --git a/crates/core/src/cdp_endpoint.rs b/crates/core/src/cdp_endpoint.rsnew file mode 100644index 000000000..2c1b7d621--- /dev/null+++ b/crates/core/src/cdp_endpoint.rs@@ -0,0 +1,221 @@+use std::io::{Read, Write};+use std::net::{SocketAddr, TcpListener, TcpStream};+use std::time::{Duration, Instant};++use serde::{Deserialize, Serialize};++use crate::{AdapterError, AppError, Deadline, ErrorCode};++const MAX_ATTEMPT_TIMEOUT: Duration = Duration::from_millis(500);+const POLL_INTERVAL: Duration = Duration::from_millis(100);+const MAX_RESPONSE_BYTES: usize = 64 * 1024;++/// A DevTools protocol endpoint verified on a launched process, not merely+/// requested of it. `port` and `http_endpoint` come from the launch itself;+/// `websocket_url` and `product` come from a live `/json/version` read.+/// `probe` only succeeds once `websocket_url` is present in that read, so an+/// endpoint that answers HTTP without a parseable DevTools body is treated+/// as not yet verified rather than as a success missing one field.+/// The probe's Host header carries the port because Chromium builds the+/// reported websocket URL from it verbatim; without it the URL cannot be+/// dialed.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CdpEndpoint {+ pub port: u16,+ pub http_endpoint: String,+ pub websocket_url: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub product: Option<String>,+}++/// Binds an ephemeral port to learn one the OS considers free, then releases+/// it immediately. The gap between release and reuse is inherent to asking+/// the OS for a free port this way; the launched process claiming it first+/// is the expected outcome, not a race this function needs to close.+pub(crate) fn pick_free_port() -> Result<u16, AppError> {+ let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(bind_failed)?;+ let port = listener.local_addr().map_err(bind_failed)?.port();+ drop(listener);+ Ok(port)+}++pub(crate) fn port_is_free(port: u16) -> bool {+ TcpListener::bind(("127.0.0.1", port)).is_ok()+}++enum Attempt {+ Verified(CdpEndpoint),+ RespondedWithoutDevtoolsBody,+ NotYetListening,+}++/// Polls `/json/version` until it answers with a parseable DevTools body or+/// the deadline runs out. The port only exists once the launched process+/// opens it, so an endpoint that is not yet listening is the expected state+/// right after launch, not a failure — the loop is what turns "port+/// injected" into "port verified". A responder that answers HTTP but never+/// yields a `webSocketDebuggerUrl` keeps the loop going instead of returning+/// early, since the port may still be settling into its final DevTools state.+pub(crate) fn probe(port: u16, deadline: Deadline) -> Result<CdpEndpoint, AppError> {+ let mut saw_responder_without_body = false;+ loop {+ let attempt_timeout = deadline.remaining().min(MAX_ATTEMPT_TIMEOUT);+ match attempt(port, attempt_timeout.max(Duration::from_millis(1))) {+ Attempt::Verified(endpoint) => return Ok(endpoint),+ Attempt::RespondedWithoutDevtoolsBody => saw_responder_without_body = true,+ Attempt::NotYetListening => {}+ }+ if deadline.is_expired() {+ return Err(unavailable(port, deadline, saw_responder_without_body));+ }+ std::thread::sleep(POLL_INTERVAL.min(deadline.remaining()));+ }+}++fn attempt(port: u16, timeout: Duration) -> Attempt {+ let address = SocketAddr::from(([127, 0, 0, 1], port));+ let Ok(mut stream) = TcpStream::connect_timeout(&address, timeout) else {+ return Attempt::NotYetListening;+ };+ if stream.set_read_timeout(Some(timeout)).is_err()+ || stream.set_write_timeout(Some(timeout)).is_err()+ {+ return Attempt::NotYetListening;+ }+ let request = format!(+ "GET /json/version HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"+ );+ if stream.write_all(request.as_bytes()).is_err() {+ return Attempt::NotYetListening;+ }+ let Some(raw) = read_http_response(&mut stream, timeout) else {+ return Attempt::NotYetListening;+ };+ match parse_response(port, &raw) {+ Some(endpoint) => Attempt::Verified(endpoint),+ None => Attempt::RespondedWithoutDevtoolsBody,+ }+}++/// Chromium's DevTools server answers and then holds the connection open,+/// ignoring `Connection: close`, so reading to EOF waits for a close that+/// never comes and times out on every live endpoint. The response is done+/// once the headers' Content-Length bytes of body arrive; EOF and a+/// post-headers read timeout are accepted as a server's way of ending it.+/// The read timeout shrinks to the attempt's own remaining time on every+/// iteration, so a server that trickles a byte at a time can only ever cost+/// this attempt its allotted `timeout`, not one full read-timeout per byte.+fn read_http_response(stream: &mut TcpStream, timeout: Duration) -> Option<Vec<u8>> {+ let started = Instant::now();+ let mut raw = Vec::new();+ let mut chunk = [0_u8; 4096];+ loop {+ let elapsed = started.elapsed();+ if elapsed >= timeout || stream.set_read_timeout(Some(timeout - elapsed)).is_err() {+ break;+ }+ match stream.read(&mut chunk) {+ Ok(0) => break,+ Ok(received) => {+ raw.extend_from_slice(&chunk[..received]);+ if response_complete(&raw) || raw.len() > MAX_RESPONSE_BYTES {+ break;+ }+ }+ Err(_) => break,+ }+ }+ if raw.is_empty() { None } else { Some(raw) }+}++fn response_complete(raw: &[u8]) -> bool {+ let Some(header_end) = raw.windows(4).position(|window| window == b"\r\n\r\n") else {+ return false;+ };+ let body_received = raw.len() - (header_end + 4);+ content_length(&raw[..header_end]).is_some_and(|expected| body_received >= expected)+}++fn content_length(headers: &[u8]) -> Option<usize> {+ String::from_utf8_lossy(headers).lines().find_map(|line| {+ let (name, value) = line.split_once(':')?;+ name.trim()+ .eq_ignore_ascii_case("content-length")+ .then(|| value.trim().parse::<usize>().ok())+ .flatten()+ })+}++fn parse_response(port: u16, raw: &[u8]) -> Option<CdpEndpoint> {+ let text = String::from_utf8_lossy(raw);+ let body = text+ .split_once("\r\n\r\n")+ .map_or("", |(_, body)| body)+ .trim();+ let parsed: serde_json::Value = serde_json::from_str(body).ok()?;+ let websocket_url = parsed+ .get("webSocketDebuggerUrl")+ .and_then(serde_json::Value::as_str)?+ .to_owned();+ let product = parsed+ .get("Browser")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned);+ Some(CdpEndpoint {+ port,+ http_endpoint: format!("http://127.0.0.1:{port}"),+ websocket_url,+ product,+ })+}++fn bind_failed(error: std::io::Error) -> AppError {+ AppError::Adapter(+ AdapterError::new(+ ErrorCode::Internal,+ "Could not bind a local port to pick a free one",+ )+ .with_platform_detail(error.to_string()),+ )+}++fn unavailable(port: u16, deadline: Deadline, responder_without_devtools_body: bool) -> AppError {+ let mut details = serde_json::json!({+ "kind": "cdp_endpoint_unavailable",+ "port": port,+ "elapsed_ms": deadline.elapsed().as_millis(),+ });+ if responder_without_devtools_body {+ details["responder_without_devtools_body"] = serde_json::Value::Bool(true);+ }+ AppError::Adapter(+ AdapterError::new(+ ErrorCode::ActionFailed,+ format!("No DevTools endpoint answered on port {port} before the deadline"),+ )+ .with_details(details)+ .with_disposition(crate::DeliverySemantics::delivered_unverified()),+ )+}++/// Adds `extra`'s keys to `base`, favoring `extra` on collision. Used to+/// enrich a probe's error with launch-side context (pid, process instance,+/// probe budget) without discarding the probe's own message and evidence.+/// Non-object inputs pass `base` through unchanged, since there is nothing+/// sensible to merge.+pub(crate) fn merge_object_details(+ base: serde_json::Value,+ extra: serde_json::Value,+) -> serde_json::Value {+ match (base, extra) {+ (serde_json::Value::Object(mut base_map), serde_json::Value::Object(extra_map)) => {+ base_map.extend(extra_map);+ serde_json::Value::Object(base_map)+ }+ (base, _) => base,+ }+}++#[cfg(test)]+#[path = "cdp_endpoint_tests.rs"]+mod tests;diff --git a/crates/core/src/cdp_endpoint_tests.rs b/crates/core/src/cdp_endpoint_tests.rsnew file mode 100644index 000000000..48d9da22e--- /dev/null+++ b/crates/core/src/cdp_endpoint_tests.rs@@ -0,0 +1,182 @@+use super::*;++#[test]+fn pick_free_port_returns_a_port_that_is_immediately_bindable_again() {+ let port = pick_free_port().unwrap();++ assert!(port_is_free(port));+}++#[test]+fn port_is_free_reports_false_while_a_listener_holds_the_port_and_true_once_released() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();++ assert!(!port_is_free(port));+ drop(listener);+ assert!(port_is_free(port));+}++/// Serves a canned `/json/version` response over a real socket so the parse+/// path is exercised end to end, not just against an in-memory byte slice.+#[test]+fn probe_parses_websocket_url_and_product_from_a_live_http_response() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut buf = [0_u8; 1024];+ let received = stream.read(&mut buf).unwrap_or(0);+ let request = String::from_utf8_lossy(&buf[..received]).into_owned();+ let body = r#"{"Browser":"Chrome/120.0.0.0","webSocketDebuggerUrl":"ws://127.0.0.1/devtools/browser/abc"}"#;+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",+ body.len(),+ body+ );+ stream.write_all(response.as_bytes()).unwrap();+ request+ });++ let endpoint = probe(port, Deadline::after(2_000).unwrap()).unwrap();+ let request = server.join().unwrap();++ assert!(+ request.contains(&format!("Host: 127.0.0.1:{port}")),+ "Chromium echoes the Host header into webSocketDebuggerUrl, so the port must be in it; sent: {request}"+ );++ assert_eq!(endpoint.port, port);+ assert_eq!(endpoint.http_endpoint, format!("http://127.0.0.1:{port}"));+ assert_eq!(endpoint.product.as_deref(), Some("Chrome/120.0.0.0"));+ assert_eq!(+ endpoint.websocket_url,+ "ws://127.0.0.1/devtools/browser/abc"+ );+}++/// Chromium's real DevTools server never closes the connection, even when+/// asked to — the launch-blocking bug this pins was a probe that read to EOF+/// and timed out on every live endpoint. The server here answers and then+/// holds the socket open, so this test fails if the probe ever needs EOF.+#[test]+fn probe_completes_against_a_server_that_never_closes_the_connection() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut buf = [0_u8; 1024];+ let _ = stream.read(&mut buf);+ let body = r#"{"Browser":"Chrome/142.0.0.0","webSocketDebuggerUrl":"ws://127.0.0.1/devtools/browser/def"}"#;+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",+ body.len(),+ body+ );+ stream.write_all(response.as_bytes()).unwrap();+ let _ = done_rx.recv_timeout(Duration::from_secs(10));+ drop(stream);+ });++ let started = std::time::Instant::now();+ let endpoint = probe(port, Deadline::after(5_000).unwrap()).unwrap();+ let elapsed = started.elapsed();+ done_tx.send(()).unwrap();+ server.join().unwrap();++ assert!(elapsed < Duration::from_secs(2), "probe took {elapsed:?}");+ assert_eq!(endpoint.product.as_deref(), Some("Chrome/142.0.0.0"));+ assert_eq!(+ endpoint.websocket_url,+ "ws://127.0.0.1/devtools/browser/def"+ );+}++#[test]+fn probe_returns_the_unavailable_error_quickly_when_nothing_is_listening() {+ let port = pick_free_port().unwrap();+ let started = std::time::Instant::now();++ let error = probe(port, Deadline::after(300).unwrap()).unwrap_err();++ assert!(started.elapsed() < Duration::from_secs(2));+ match error {+ AppError::Adapter(inner) => {+ assert_eq!(inner.code, ErrorCode::ActionFailed);+ assert_eq!(+ inner.details.as_ref().and_then(|d| d.get("kind")),+ Some(&serde_json::json!("cdp_endpoint_unavailable"))+ );+ assert_eq!(+ inner+ .details+ .as_ref()+ .and_then(|d| d.get("responder_without_devtools_body")),+ None,+ "nothing answered at all, so the responder flag must not be set"+ );+ }+ other => panic!("expected an adapter error, got {other:?}"),+ }+}++/// A responder that answers HTTP with a body `serde_json` cannot parse into+/// `webSocketDebuggerUrl` must not be mistaken for success — the port may+/// still be settling into its DevTools state, so the probe keeps polling and+/// only reports it once the deadline runs out, with a detail flag distinguishing+/// this from a port nothing ever answered on.+#[test]+fn probe_keeps_polling_a_responder_without_a_devtools_body_and_flags_it_on_expiry() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ std::thread::spawn(move || {+ while let Ok((mut stream, _)) = listener.accept() {+ let mut buf = [0_u8; 1024];+ let _ = stream.read(&mut buf);+ let body = "not devtools json";+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{}",+ body.len(),+ body+ );+ let _ = stream.write_all(response.as_bytes());+ }+ });++ let error = probe(port, Deadline::after(300).unwrap()).unwrap_err();++ match error {+ AppError::Adapter(inner) => {+ assert_eq!(inner.code, ErrorCode::ActionFailed);+ assert_eq!(+ inner.details.as_ref().and_then(|d| d.get("kind")),+ Some(&serde_json::json!("cdp_endpoint_unavailable"))+ );+ assert_eq!(+ inner+ .details+ .as_ref()+ .and_then(|d| d.get("responder_without_devtools_body")),+ Some(&serde_json::json!(true))+ );+ }+ other => panic!("expected an adapter error, got {other:?}"),+ }+}++#[test]+fn merge_object_details_favors_extra_on_key_collision_and_passes_through_non_objects() {+ let merged = merge_object_details(+ serde_json::json!({ "kind": "cdp_endpoint_unavailable", "port": 9001 }),+ serde_json::json!({ "pid": 42, "port": 9002 }),+ );++ assert_eq!(+ merged,+ serde_json::json!({ "kind": "cdp_endpoint_unavailable", "port": 9002, "pid": 42 })+ );++ let unchanged = merge_object_details(serde_json::json!(null), serde_json::json!({ "pid": 1 }));+ assert_eq!(unchanged, serde_json::json!(null));+}diff --git a/crates/core/src/commands/launch.rs b/crates/core/src/commands/launch.rsindex eb21e3e16..fb9e6bd21 100644--- a/crates/core/src/commands/launch.rs+++ b/crates/core/src/commands/launch.rs@@ -1,23 +1,230 @@-use crate::{AppError, adapter::PlatformAdapter, launch_options::LaunchOptions};+use std::time::Duration;++use crate::{+ AdapterError, AppError, DeliverySemantics, ErrorCode, adapter::PlatformAdapter, cdp_endpoint,+ launch_options::LaunchOptions, launch_result::LaunchResult, renderer_kind::RendererKind,+};use serde_json::Value;+/// The largest slice of the overall deadline set aside for verifying the+/// DevTools endpoint once the process is launched.+const MAX_PROBE_RESERVE: Duration = Duration::from_millis(5_000);+pub struct LaunchArgs {pub app: String,pub options: LaunchOptions,}pub fn execute(args: LaunchArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- crate::wait_timeout_duration(args.options.timeout_ms)?;- let deadline = if args.options.timeout_ms == 0 {+ let LaunchArgs { app, mut options } = args;+ crate::wait_timeout_duration(options.timeout_ms)?;+ let deadline = if options.timeout_ms == 0 {crate::Deadline::standard()?} else {- crate::Deadline::after(args.options.timeout_ms)?+ crate::Deadline::after(options.timeout_ms)?};- let lease = adapter.acquire_interaction_lease(deadline)?;- let launched = adapter.launch_app(&args.app, &args.options, &lease)?;+ let requested_cdp_port = options.cdp_port;+ if let Some(requested_port) = requested_cdp_port {+ reject_conflicting_cdp_switch(&options)?;+ reject_if_already_running(&app, adapter, deadline)?;+ let resolved_port = resolve_cdp_port(requested_port)?;+ options+ .args+ .push(format!("--remote-debugging-port={resolved_port}"));+ options+ .args+ .push("--remote-debugging-address=127.0.0.1".to_owned());+ options.cdp_port = Some(resolved_port);+ }+ let probe_budget = requested_cdp_port.map(|_| probe_reserve(deadline.remaining()));+ let launch_deadline = probe_budget.map_or(deadline, |reserve| {+ deadline.capped(deadline.remaining().saturating_sub(reserve))+ });+ let lease = adapter.acquire_interaction_lease(launch_deadline)?;+ let mut launched = adapter.launch_app(&app, &options, &lease)?;+ if let Some(port) = options.cdp_port {+ let granted = deadline.remaining();+ launched.cdp = Some(verify_cdp_endpoint(port, deadline, granted, &launched)?);+ }+ launched.suggestion = launch_suggestion(requested_cdp_port.is_some(), &launched);Ok(serde_json::to_value(launched)?)}+/// The probe needs some of the overall deadline reserved for itself, or a+/// generous overall timeout would let the launch step spend it all and leave+/// nothing to verify the endpoint with. Reserving a quarter of the total,+/// capped at `MAX_PROBE_RESERVE`, keeps the split proportionate for short+/// deadlines and bounded for long ones.+fn probe_reserve(total: Duration) -> Duration {+ (total / 4).min(MAX_PROBE_RESERVE)+}++/// Guidance the calling agent reads at the moment of use, not prose it has+/// to infer: a Chromium app launched without `--cdp` is nudged toward the+/// flag that opens the web-content door, and a verified endpoint is handed+/// off to a CDP client instead of left for the caller to rediscover.+fn launch_suggestion(cdp_requested: bool, launched: &LaunchResult) -> Option<String> {+ if let Some(cdp) = &launched.cdp {+ return Some(format!(+ "Next: run `agent-browser connect {}` (preferred; `agent-browser skills get \+ electron` has the guide) or connect any CDP client such as Playwright or \+ Puppeteer. If neither is available, ask the user to install agent-browser or \+ continue with accessibility commands. Do not hand-roll raw CDP or call \+ app-internal APIs — that path is unverified and app-specific. Native menus, \+ dialogs, windows, and screenshots stay with agent-desktop.",+ cdp.port+ ));+ }+ if !cdp_requested && launched.renderer == Some(RendererKind::Chromium) {+ return Some(+ "Chromium app: for web-content work, run close-app and then launch --cdp, then \+ drive the web contents with agent-browser or any CDP client. Accessibility \+ commands still cover everything, including native menus and dialogs."+ .to_owned(),+ );+ }+ None+}++/// Our own `--remote-debugging-port`, `--remote-debugging-address`, and+/// `--remote-allow-origins` switches are how `--cdp` pins the DevTools+/// surface to loopback and works at all; a caller who also passes any of+/// them by hand would silently race or widen it, so this is rejected before+/// launch rather than left to whichever switch Launch Services keeps.+fn reject_conflicting_cdp_switch(options: &LaunchOptions) -> Result<(), AppError> {+ let conflicts = options.args.iter().any(|arg| {+ arg.starts_with("--remote-debugging-port")+ || arg == "--remote-debugging-pipe"+ || arg.starts_with("--remote-debugging-address")+ || arg.starts_with("--remote-allow-origins")+ });+ if !conflicts {+ return Ok(());+ }+ Err(AppError::Adapter(+ AdapterError::new(+ ErrorCode::InvalidArgs,+ "Launch already specifies a DevTools remote-debugging switch",+ )+ .with_details(serde_json::json!({ "kind": "cdp_switch_conflict" }))+ .with_suggestion(+ "--cdp owns the remote-debugging switches (port, address, allow-origins) — pass \+ --cdp instead of setting them yourself.",+ )+ .with_disposition(DeliverySemantics::not_delivered()),+ ))+}++/// The DevTools port only exists on the process that was launched with it;+/// attaching to an instance already running without it would report success+/// while the endpoint stays absent, so this is checked before launch instead+/// of discovered only once the endpoint fails to answer. Only workspace-+/// registered applications count: `list_apps` also returns ps-derived helper+/// processes with no bundle ID and no presentation, and the launch path can+/// never attach to one of those even when its name happens to match.+fn reject_if_already_running(+ id: &str,+ adapter: &dyn PlatformAdapter,+ deadline: crate::Deadline,+) -> Result<(), AppError> {+ let running = adapter.list_apps(deadline)?;+ let pids: Vec<_> = running+ .iter()+ .filter(|app| app.presentation.is_some() && app.matches_identifier(id))+ .map(|app| app.pid)+ .collect();+ if pids.is_empty() {+ return Ok(());+ }+ Err(AppError::Adapter(+ AdapterError::new(+ ErrorCode::ActionFailed,+ "The application is already running without the DevTools port",+ )+ .with_details(serde_json::json!({ "kind": "cdp_requires_fresh_launch", "pids": pids }))+ .with_suggestion(+ "The DevTools port only exists for a process launched with it. Quit the app with \+ close-app, then launch again with --cdp — or drive the running instance with \+ accessibility commands (snapshot/click).",+ )+ .with_disposition(DeliverySemantics::not_delivered()),+ ))+}++fn resolve_cdp_port(requested: u16) -> Result<u16, AppError> {+ if requested == 0 {+ return cdp_endpoint::pick_free_port();+ }+ if !cdp_endpoint::port_is_free(requested) {+ return Err(AppError::Adapter(+ AdapterError::new(+ ErrorCode::InvalidArgs,+ "Requested --cdp port is already in use",+ )+ .with_details(serde_json::json!({ "kind": "cdp_port_in_use", "port": requested }))+ .with_disposition(DeliverySemantics::not_delivered()),+ ));+ }+ Ok(requested)+}++/// Verifies the endpoint by observation instead of trusting the switch: the+/// app is left running either way, so a probe failure reports what exists+/// (pid, process instance, the budget the probe was given) layered onto the+/// probe's own message and evidence rather than a second, separately worded+/// error that could drift from what was actually observed.+/// `probe_budget` is the time the probe actually received: the deadline's+/// remainder at probe start, not the pre-launch reserve, which a fast launch+/// leaves far behind.+fn verify_cdp_endpoint(+ port: u16,+ deadline: crate::Deadline,+ probe_budget: Duration,+ launched: &LaunchResult,+) -> Result<cdp_endpoint::CdpEndpoint, AppError> {+ cdp_endpoint::probe(port, deadline)+ .map_err(|error| augment_probe_error(error, launched, probe_budget))+}++fn augment_probe_error(+ error: AppError,+ launched: &LaunchResult,+ probe_budget: Duration,+) -> AppError {+ let AppError::Adapter(inner) = error else {+ return error;+ };+ let extra = serde_json::json!({+ "pid": launched.pid,+ "process_instance": launched.process_instance,+ "probe_budget_ms": probe_budget.as_millis(),+ });+ let merged = cdp_endpoint::merge_object_details(+ inner+ .details+ .clone()+ .unwrap_or_else(|| serde_json::json!({})),+ extra,+ );+ AppError::Adapter(inner.with_details(merged).with_suggestion(+ "The app is running but no DevTools endpoint answered on this port. It may not be \+ Chromium-based, may strip debugging switches, or may still be starting. Drive it with \+ accessibility commands, or close-app it if it is unwanted.",+ ))+}+#[cfg(test)]#[path = "launch_tests.rs"]mod tests;++#[cfg(test)]+#[path = "launch_cdp_test_support.rs"]+mod cdp_test_support;++#[cfg(test)]+#[path = "launch_cdp_tests.rs"]+mod cdp_tests;++#[cfg(test)]+#[path = "launch_cdp_switch_tests.rs"]+mod cdp_switch_tests;diff --git a/crates/core/src/commands/launch_cdp_switch_tests.rs b/crates/core/src/commands/launch_cdp_switch_tests.rsnew file mode 100644index 000000000..67b510b32--- /dev/null+++ b/crates/core/src/commands/launch_cdp_switch_tests.rs@@ -0,0 +1,247 @@+use super::cdp_test_support::{CdpAdapter, adapter_error, empty_cdp_adapter};+use super::*;+use crate::launch_options::LaunchOptions;+use crate::{AppInfo, AppPresentation, ErrorCode, ProcessId};+use std::net::TcpListener;+use std::sync::atomic::Ordering;+use std::time::Duration;++#[test]+fn cdp_launch_injects_both_the_port_and_the_loopback_address_switch() {+ let adapter = empty_cdp_adapter(true);+ let options = LaunchOptions {+ cdp_port: Some(0),+ timeout_ms: 3_000,+ ..Default::default()+ };++ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap();++ let port = adapter+ .captured_cdp_port+ .lock()+ .unwrap()+ .expect("cdp_port resolved before launch_app ran");+ let captured_args = adapter.captured_args.lock().unwrap();+ assert!(captured_args.contains(&format!("--remote-debugging-port={port}")));+ assert!(captured_args.contains(&"--remote-debugging-address=127.0.0.1".to_owned()));+}++#[test]+fn cdp_launch_rejects_a_conflicting_remote_debugging_address_switch() {+ let adapter = empty_cdp_adapter(false);+ let options = LaunchOptions {+ args: vec!["--remote-debugging-address=0.0.0.0".into()],+ cdp_port: Some(0),+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::InvalidArgs);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_switch_conflict"))+ );+}++#[test]+fn cdp_launch_rejects_a_conflicting_remote_allow_origins_switch() {+ let adapter = empty_cdp_adapter(false);+ let options = LaunchOptions {+ args: vec!["--remote-allow-origins=*".into()],+ cdp_port: Some(0),+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::InvalidArgs);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_switch_conflict"))+ );+}++/// The running-app precheck must also catch a match by bundle id, not only+/// by display name — a later agent narrows this precheck to workspace+/// -registered apps, so `presentation` is set here rather than left absent.+#[test]+fn cdp_launch_rejects_an_already_running_instance_matched_by_bundle_id() {+ let adapter = CdpAdapter {+ running: vec![AppInfo {+ name: "Completely Different".into(),+ pid: ProcessId::new(9),+ bundle_id: Some("md.obsidian".into()),+ process_instance: Some("9:1".into()),+ presentation: Some(AppPresentation::Foreground),+ }],+ ..empty_cdp_adapter(false)+ };+ let options = LaunchOptions {+ cdp_port: Some(0),+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "md.obsidian".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_requires_fresh_launch"))+ );+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("pids")),+ Some(&serde_json::json!([9]))+ );+}++#[test]+fn cdp_launch_rejects_a_busy_requested_port_without_ever_calling_launch() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let adapter = empty_cdp_adapter(false);+ let options = LaunchOptions {+ cdp_port: Some(port),+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::InvalidArgs);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_port_in_use"))+ );+ assert_eq!(adapter.launch_app_calls.load(Ordering::SeqCst), 0);+ drop(listener);+}++/// The probe's own error already carries `kind`, `port`, and `elapsed_ms`;+/// verification must layer `pid`, `process_instance`, and `probe_budget_ms`+/// onto that same error rather than rebuild a second one, and the message+/// must report what was observed (no answer) rather than claim the app+/// never opened the endpoint, which cannot be known from the outside.+#[test]+fn cdp_launch_verification_failure_carries_the_probes_details_merged_with_launch_context() {+ let adapter = empty_cdp_adapter(false);+ let options = LaunchOptions {+ cdp_port: Some(0),+ timeout_ms: 200,+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert!(+ error+ .message+ .contains("No DevTools endpoint answered on port")+ );+ assert!(!error.message.contains("never opened"));+ let details = error.details.as_ref().expect("failure carries details");+ assert_eq!(+ details.get("kind"),+ Some(&serde_json::json!("cdp_endpoint_unavailable"))+ );+ assert!(details.get("port").is_some());+ assert!(details.get("elapsed_ms").is_some());+ assert_eq!(details.get("pid"), Some(&serde_json::json!(42)));+ assert_eq!(+ details.get("process_instance"),+ Some(&serde_json::json!("42:1"))+ );+ assert!(details.get("probe_budget_ms").is_some());+}++#[test]+fn probe_reserve_is_zero_for_a_zero_budget() {+ assert_eq!(+ probe_reserve(Duration::from_millis(0)),+ Duration::from_millis(0)+ );+}++#[test]+fn probe_reserve_is_a_quarter_of_a_small_budget() {+ assert_eq!(+ probe_reserve(Duration::from_millis(400)),+ Duration::from_millis(100)+ );+}++#[test]+fn probe_reserve_is_capped_at_five_seconds_for_a_large_budget() {+ assert_eq!(+ probe_reserve(Duration::from_secs(40)),+ Duration::from_millis(5_000)+ );+}diff --git a/crates/core/src/commands/launch_cdp_test_support.rs b/crates/core/src/commands/launch_cdp_test_support.rsnew file mode 100644index 000000000..77173d1c1--- /dev/null+++ b/crates/core/src/commands/launch_cdp_test_support.rs@@ -0,0 +1,100 @@+use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};+use crate::launch_options::LaunchOptions;+use crate::{AdapterError, AppError, AppInfo, InteractionLease, ProcessId, RendererKind};+use std::io::{Read, Write};+use std::net::TcpListener;+use std::sync::Mutex;+use std::sync::atomic::{AtomicUsize, Ordering};++/// Mock adapter for the `--cdp` wiring: records the options `launch_app`+/// actually received, and can optionally serve a canned `/json/version`+/// response on the requested port so the endpoint-verified path is testable+/// without a real Chromium-based application. Shared by every `--cdp` test+/// module in this file's family so the mock is defined once.+pub(super) struct CdpAdapter {+ pub(super) running: Vec<AppInfo>,+ pub(super) list_apps_calls: AtomicUsize,+ pub(super) launch_app_calls: AtomicUsize,+ pub(super) serve_cdp: bool,+ pub(super) renderer: Option<RendererKind>,+ pub(super) captured_args: Mutex<Vec<String>>,+ pub(super) captured_cdp_port: Mutex<Option<u16>>,+}++impl ObservationOps for CdpAdapter {+ fn list_apps(&self, _deadline: crate::Deadline) -> Result<Vec<AppInfo>, AdapterError> {+ self.list_apps_calls.fetch_add(1, Ordering::SeqCst);+ Ok(self.running.clone())+ }+}+impl ActionOps for CdpAdapter {}+impl InputOps for CdpAdapter {}++impl SystemOps for CdpAdapter {+ fn acquire_interaction_lease(+ &self,+ deadline: crate::Deadline,+ ) -> Result<InteractionLease, AdapterError> {+ InteractionLease::guarded(deadline, ())+ }++ fn launch_app(+ &self,+ _id: &str,+ options: &LaunchOptions,+ _lease: &InteractionLease,+ ) -> Result<crate::launch_result::LaunchResult, AdapterError> {+ self.launch_app_calls.fetch_add(1, Ordering::SeqCst);+ *self.captured_args.lock().unwrap() = options.args.clone();+ *self.captured_cdp_port.lock().unwrap() = options.cdp_port;+ if self.serve_cdp {+ let port = options.cdp_port.expect("cdp_port resolved before launch");+ serve_fake_cdp_endpoint(port);+ }+ Ok(crate::launch_result::LaunchResult {+ app: "Fixture".into(),+ pid: ProcessId::new(42),+ process_instance: Some("42:1".into()),+ window: None,+ cdp: None,+ renderer: self.renderer,+ suggestion: None,+ })+ }+}++fn serve_fake_cdp_endpoint(port: u16) {+ let listener = TcpListener::bind(("127.0.0.1", port)).expect("port was reserved by the caller");+ std::thread::spawn(move || {+ if let Ok((mut stream, _)) = listener.accept() {+ let mut buf = [0_u8; 1024];+ let _ = stream.read(&mut buf);+ let body = r#"{"Browser":"Fixture/1.0","webSocketDebuggerUrl":"ws://127.0.0.1/devtools/browser/fixture"}"#;+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",+ body.len(),+ body+ );+ let _ = stream.write_all(response.as_bytes());+ }+ });+}++pub(super) fn empty_cdp_adapter(serve_cdp: bool) -> CdpAdapter {+ CdpAdapter {+ running: Vec::new(),+ list_apps_calls: AtomicUsize::new(0),+ launch_app_calls: AtomicUsize::new(0),+ serve_cdp,+ renderer: None,+ captured_args: Mutex::new(Vec::new()),+ captured_cdp_port: Mutex::new(None),+ }+}++pub(super) fn adapter_error(error: AppError) -> AdapterError {+ match error {+ AppError::Adapter(inner) => inner,+ other => panic!("expected an adapter error, got {other:?}"),+ }+}diff --git a/crates/core/src/commands/launch_cdp_tests.rs b/crates/core/src/commands/launch_cdp_tests.rsnew file mode 100644index 000000000..a1a960b9f--- /dev/null+++ b/crates/core/src/commands/launch_cdp_tests.rs@@ -0,0 +1,259 @@+use super::cdp_test_support::{CdpAdapter, adapter_error, empty_cdp_adapter};+use super::*;+use crate::launch_options::LaunchOptions;+use crate::{AppInfo, AppPresentation, ErrorCode, ProcessId, RendererKind};+use std::sync::atomic::Ordering;++#[test]+fn cdp_launch_rejects_a_conflicting_remote_debugging_switch() {+ let adapter = empty_cdp_adapter(false);+ let options = LaunchOptions {+ args: vec!["--remote-debugging-port=1234".into()],+ cdp_port: Some(0),+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::InvalidArgs);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_switch_conflict"))+ );+ assert_eq!(+ adapter.list_apps_calls.load(Ordering::SeqCst),+ 0,+ "the switch conflict is rejected before the running-app precheck runs"+ );+}++#[test]+fn cdp_launch_rejects_an_already_running_instance() {+ let adapter = CdpAdapter {+ running: vec![AppInfo {+ name: "Fixture".into(),+ pid: ProcessId::new(7),+ bundle_id: None,+ process_instance: Some("7:1".into()),+ presentation: Some(AppPresentation::Foreground),+ }],+ ..empty_cdp_adapter(false)+ };+ let options = LaunchOptions {+ cdp_port: Some(0),+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_requires_fresh_launch"))+ );+ assert_eq!(adapter.list_apps_calls.load(Ordering::SeqCst), 1);+}++/// `list_apps` also returns ps-derived helper processes: no bundle ID, no+/// presentation, because the adapter can never attach a launch to one. A+/// helper sharing the requested app's name must not block the launch.+#[test]+fn cdp_launch_ignores_a_name_matching_helper_process_without_presentation() {+ let adapter = CdpAdapter {+ running: vec![AppInfo {+ name: "Fixture".into(),+ pid: ProcessId::new(7),+ bundle_id: None,+ process_instance: None,+ presentation: None,+ }],+ ..empty_cdp_adapter(true)+ };+ let options = LaunchOptions {+ cdp_port: Some(0),+ timeout_ms: 3_000,+ ..Default::default()+ };++ let value = execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .expect("a presentation-less helper process must not block the launch");++ assert!(value.get("cdp").is_some());+}++/// Even when the endpoint never answers, the switch was already appended+/// and the resolved port already recorded before `launch_app` ran — the+/// failure is in verification, not in requesting the port.+#[test]+fn cdp_launch_appends_the_switch_and_resolves_the_port_before_verification_fails() {+ let adapter = empty_cdp_adapter(false);+ let options = LaunchOptions {+ cdp_port: Some(0),+ timeout_ms: 200,+ ..Default::default()+ };++ let error = adapter_error(+ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap_err(),+ );++ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(+ error+ .details+ .as_ref()+ .and_then(|details| details.get("kind")),+ Some(&serde_json::json!("cdp_endpoint_unavailable"))+ );+ let captured_port = adapter+ .captured_cdp_port+ .lock()+ .unwrap()+ .expect("cdp_port was resolved before launch_app ran");+ let captured_args = adapter.captured_args.lock().unwrap();+ assert!(captured_args.contains(&format!("--remote-debugging-port={captured_port}")));+}++#[test]+fn cdp_launch_returns_a_verified_endpoint_when_the_process_answers() {+ let adapter = empty_cdp_adapter(true);+ let options = LaunchOptions {+ cdp_port: Some(0),+ timeout_ms: 3_000,+ ..Default::default()+ };++ let value = execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap();++ let cdp = value+ .get("cdp")+ .expect("cdp endpoint present in the envelope");+ assert_eq!(+ cdp.get("product").and_then(Value::as_str),+ Some("Fixture/1.0")+ );+ assert!(+ cdp.get("websocket_url")+ .and_then(Value::as_str)+ .unwrap()+ .contains("devtools/browser")+ );+}++/// A Chromium app launched without `--cdp` gets nudged toward the flag that+/// actually opens the web-content door, without repeating that door's name.+#[test]+fn chromium_renderer_without_cdp_gets_the_relaunch_suggestion() {+ let adapter = CdpAdapter {+ renderer: Some(RendererKind::Chromium),+ ..empty_cdp_adapter(false)+ };++ let value = execute(+ LaunchArgs {+ app: "Fixture".into(),+ options: LaunchOptions::default(),+ },+ &adapter,+ )+ .unwrap();++ assert_eq!(+ value.get("renderer").and_then(Value::as_str),+ Some("chromium")+ );+ assert!(value.get("cdp").is_none());+ let suggestion = value+ .get("suggestion")+ .and_then(Value::as_str)+ .expect("suggestion present for an undriven chromium renderer");+ assert!(suggestion.contains("--cdp"));+}++#[test]+fn cdp_success_gets_the_handoff_suggestion() {+ let adapter = empty_cdp_adapter(true);+ let options = LaunchOptions {+ cdp_port: Some(0),+ timeout_ms: 3_000,+ ..Default::default()+ };++ let value = execute(+ LaunchArgs {+ app: "Fixture".into(),+ options,+ },+ &adapter,+ )+ .unwrap();++ assert!(value.get("cdp").is_some());+ let suggestion = value+ .get("suggestion")+ .and_then(Value::as_str)+ .expect("suggestion present once the endpoint is verified");+ assert!(suggestion.contains("agent-browser connect"));+ assert!(suggestion.contains("Do not hand-roll raw CDP"));+}++#[test]+fn non_chromium_plain_launch_has_neither_renderer_nor_suggestion() {+ let adapter = empty_cdp_adapter(false);++ let value = execute(+ LaunchArgs {+ app: "Fixture".into(),+ options: LaunchOptions::default(),+ },+ &adapter,+ )+ .unwrap();++ assert!(value.get("renderer").is_none());+ assert!(value.get("suggestion").is_none());+}diff --git a/crates/core/src/commands/launch_tests.rs b/crates/core/src/commands/launch_tests.rsindex b5ad70169..f88064c51 100644--- a/crates/core/src/commands/launch_tests.rs+++ b/crates/core/src/commands/launch_tests.rs@@ -1,14 +1,20 @@use super::*;use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};use crate::launch_options::LaunchOptions;-use crate::{AdapterError, InteractionLease, ProcessId, WindowInfo, WindowState};-use std::sync::atomic::{AtomicU64, Ordering};+use crate::{AdapterError, AppInfo, InteractionLease, ProcessId, WindowInfo, WindowState};+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};struct LaunchAdapter {lease_timeout_ms: AtomicU64,+ list_apps_calls: AtomicUsize,}-impl ObservationOps for LaunchAdapter {}+impl ObservationOps for LaunchAdapter {+ fn list_apps(&self, _deadline: crate::Deadline) -> Result<Vec<AppInfo>, AdapterError> {+ self.list_apps_calls.fetch_add(1, Ordering::SeqCst);+ Ok(Vec::new())+ }+}impl ActionOps for LaunchAdapter {}impl InputOps for LaunchAdapter {}@@ -41,6 +47,9 @@ impl SystemOps for LaunchAdapter {bounds: None,state: WindowState::default(),}),+ cdp: None,+ renderer: None,+ suggestion: None,})}}@@ -49,6 +58,7 @@ impl SystemOps for LaunchAdapter {fn launch_lease_uses_the_requested_timeout() {let adapter = LaunchAdapter {lease_timeout_ms: AtomicU64::new(0),+ list_apps_calls: AtomicUsize::new(0),};let options = LaunchOptions {timeout_ms: 30_000,@@ -71,6 +81,7 @@ fn launch_lease_uses_the_requested_timeout() {fn zero_launch_timeout_keeps_a_bounded_lease_for_the_single_attempt() {let adapter = LaunchAdapter {lease_timeout_ms: AtomicU64::new(0),+ list_apps_calls: AtomicUsize::new(0),};execute(@@ -90,3 +101,25 @@ fn zero_launch_timeout_keeps_a_bounded_lease_for_the_single_attempt() {crate::Deadline::standard().unwrap().timeout_ms());}++/// A launch that never asks for `--cdp` must cost nothing extra: no+/// running-app lookup, no argument mutation. Regression guard against the+/// cdp precheck accidentally running unconditionally.+#[test]+fn plain_launch_without_cdp_never_calls_list_apps() {+ let adapter = LaunchAdapter {+ lease_timeout_ms: AtomicU64::new(0),+ list_apps_calls: AtomicUsize::new(0),+ };++ execute(+ LaunchArgs {+ app: "Fixture".into(),+ options: LaunchOptions::default(),+ },+ &adapter,+ )+ .unwrap();++ assert_eq!(adapter.list_apps_calls.load(Ordering::SeqCst), 0);+}diff --git a/crates/core/src/launch_options.rs b/crates/core/src/launch_options.rsindex 429c12254..46f9d90b5 100644--- a/crates/core/src/launch_options.rs+++ b/crates/core/src/launch_options.rs@@ -18,6 +18,10 @@ pub struct LaunchOptions {/// caller that needs a window has to ask for one; waiting without asking/// waits for an event that never fires.pub activate: bool,+ /// The resolved, concrete DevTools protocol port. Core resolves a+ /// requested `0` to a real free port before the adapter ever sees it, so+ /// by the time `launch_app` runs, this is either absent or one exact port.+ pub cdp_port: Option<u16>,}impl Default for LaunchOptions {@@ -29,6 +33,7 @@ impl Default for LaunchOptions {timeout_ms: 5_000,attach_if_running: true,activate: false,+ cdp_port: None,}}}diff --git a/crates/core/src/launch_result.rs b/crates/core/src/launch_result.rsindex d821a617b..4ead739b1 100644--- a/crates/core/src/launch_result.rs+++ b/crates/core/src/launch_result.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-use crate::{ProcessId, WindowInfo};+use crate::{ProcessId, WindowInfo, cdp_endpoint::CdpEndpoint, renderer_kind::RendererKind};/// What a launch can honestly report. The process starting and the application/// presenting a window are separate outcomes: a background application never@@ -16,4 +16,18 @@ pub struct LaunchResult {pub process_instance: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub window: Option<WindowInfo>,+ /// The verified DevTools endpoint, present only when `--cdp` was+ /// requested and the launched process answered `/json/version`.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cdp: Option<CdpEndpoint>,+ /// The application's renderer, detected best-effort from its bundle.+ /// `Chromium` means Electron or CEF; absent means undetected, not+ /// "not Chromium" — detection failure never fails the launch itself.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub renderer: Option<RendererKind>,+ /// Guidance for the calling agent on how to drive this application,+ /// set by core from `renderer` and whether `cdp` is present. Absent+ /// when there is nothing more useful to say than the fields already do.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub suggestion: Option<String>,}diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex c6bd53a71..d076eb84a 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -14,6 +14,7 @@ mod app_error;mod app_info;mod app_lookup;pub mod capability;+pub mod cdp_endpoint;mod clipboard_content;mod clipboard_format;pub mod commands;@@ -110,6 +111,7 @@ pub mod refs_store;mod refs_test_support;mod refs_validate;mod renderer_accessibility;+mod renderer_kind;mod resolve_attempt_outcome;mod retry_disposition;mod retryability;@@ -239,6 +241,7 @@ pub use ref_scope::RefScope;pub use ref_source::RefSource;pub use refs::RefMap;pub use refs_store::RefStore;+pub use renderer_kind::RendererKind;pub use retry_disposition::RetryDisposition;pub use role::Role;pub use screenshot_target::ScreenshotTarget;diff --git a/crates/core/src/renderer_kind.rs b/crates/core/src/renderer_kind.rsnew file mode 100644index 000000000..e20db6f1e--- /dev/null+++ b/crates/core/src/renderer_kind.rs@@ -0,0 +1,27 @@+use serde::{Deserialize, Serialize};++/// The renderer an application's window contents are drawn by, detected+/// best-effort from its bundle. `Chromium` covers both Electron and CEF —+/// no downstream consumer needs to tell them apart, only whether a CDP+/// client can attach to the window contents.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum RendererKind {+ Chromium,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn chromium_round_trips_through_the_lowercase_wire_string() {+ let wire = serde_json::to_string(&RendererKind::Chromium).unwrap();++ assert_eq!(wire, "\"chromium\"");+ assert_eq!(+ serde_json::from_str::<RendererKind>(&wire).unwrap(),+ RendererKind::Chromium+ );+ }+}diff --git a/crates/ffi/src/apps/launch.rs b/crates/ffi/src/apps/launch.rsindex f6336c66d..300293357 100644--- a/crates/ffi/src/apps/launch.rs+++ b/crates/ffi/src/apps/launch.rs@@ -221,6 +221,9 @@ mod tests {bounds: None,state: WindowState::default(),}),+ cdp: None,+ renderer: None,+ suggestion: None,})}}diff --git a/crates/macos/src/system/launch.rs b/crates/macos/src/system/launch.rsindex 39297df85..2259a9dc3 100644--- a/crates/macos/src/system/launch.rs+++ b/crates/macos/src/system/launch.rs@@ -133,11 +133,17 @@ fn launched_display_name(window: Option<&WindowInfo>, id: &str) -> String {#[cfg(target_os = "macos")]fn result_from_app(app: &AppInfo, window: Option<WindowInfo>) -> LaunchResult {+ let renderer = crate::system::process_identity::to_pid_t(app.pid)+ .ok()+ .and_then(crate::system::renderer_kind::detect_chromium);LaunchResult {app: app.name.clone(),pid: app.pid,process_instance: app.process_instance.clone(),window,+ cdp: None,+ renderer,+ suggestion: None,}}@@ -147,12 +153,16 @@ fn result_from_launched(window: Option<WindowInfo>,id: &str,) -> Result<LaunchResult, AdapterError> {+ let renderer = crate::system::renderer_kind::detect_chromium(launched.0);Ok(LaunchResult {app: launched_display_name(window.as_ref(), id),pid: agent_desktop_core::ProcessId::try_from(launched.0).map_err(|_| AdapterError::internal("Launched process identifier is out of range"))?,process_instance: Some(launched.1.clone()),window,+ cdp: None,+ renderer,+ suggestion: None,})}@@ -236,13 +246,7 @@ fn matching_apps(id: &str, deadline: Deadline) -> Result<Vec<AppInfo>, AdapterErOk(crate::system::workspace_apps::list_apps_until(deadline_instant(deadline)?)?.into_iter()- .filter(|app| {- app.name.eq_ignore_ascii_case(id)- || app- .bundle_id- .as_deref()- .is_some_and(|bundle_id| bundle_id.eq_ignore_ascii_case(id))- })+ .filter(|app| app.matches_identifier(id)).collect(),)}diff --git a/crates/macos/src/system/mod.rs b/crates/macos/src/system/mod.rsindex 0a0026bd3..1359a85d3 100644--- a/crates/macos/src/system/mod.rs+++ b/crates/macos/src/system/mod.rs@@ -21,6 +21,7 @@ pub(crate) mod process_apps;pub(crate) mod process_identity;pub(crate) mod process_state;pub(crate) mod renderer_activation;+pub(crate) mod renderer_kind;pub(crate) mod screenshot;pub(crate) mod signals;pub(crate) mod wait;diff --git a/crates/macos/src/system/renderer_kind.rs b/crates/macos/src/system/renderer_kind.rsnew file mode 100644index 000000000..151a6d7b4--- /dev/null+++ b/crates/macos/src/system/renderer_kind.rs@@ -0,0 +1,83 @@+use agent_desktop_core::RendererKind;+use std::ffi::CStr;+use std::path::{Path, PathBuf};++/// Exact framework bundle names that mark an app as Chromium-based. Matched+/// against `Contents/Frameworks` entries, not against the app name, so+/// nothing here hardcodes a particular application.+const CHROMIUM_FRAMEWORK_MARKERS: [&str; 2] = [+ "Electron Framework.framework",+ "Chromium Embedded Framework.framework",+];++/// Best-effort: any failure resolving the executable path, the bundle root,+/// or reading `Contents/Frameworks` reports "not detected" rather than+/// failing the launch that asked for it. Costs at most one `readdir`.+#[cfg(target_os = "macos")]+pub(crate) fn detect_chromium(pid: i32) -> Option<RendererKind> {+ let executable = executable_path(pid)?;+ let bundle_root = bundle_root_from_executable(&executable)?;+ chromium_marker_in_bundle(&bundle_root).then_some(RendererKind::Chromium)+}++/// Scans `Contents/Frameworks` under `bundle_root` for a Chromium marker+/// framework. Isolated from `detect_chromium` so the scan can be tested+/// directly against a fixture bundle instead of a live process.+fn chromium_marker_in_bundle(bundle_root: &Path) -> bool {+ let frameworks = bundle_root.join("Contents/Frameworks");+ let Ok(entries) = std::fs::read_dir(frameworks) else {+ return false;+ };+ entries+ .filter_map(Result::ok)+ .any(|entry| is_chromium_framework_marker(&entry.file_name().to_string_lossy()))+}++fn is_chromium_framework_marker(entry_name: &str) -> bool {+ CHROMIUM_FRAMEWORK_MARKERS.contains(&entry_name)+}++#[cfg(not(target_os = "macos"))]+pub(crate) fn detect_chromium(_pid: i32) -> Option<RendererKind> {+ None+}++#[cfg(target_os = "macos")]+fn executable_path(pid: i32) -> Option<PathBuf> {+ let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];+ let capacity = u32::try_from(buffer.len()).ok()?;+ let written = unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), capacity) };+ if written <= 0 {+ return None;+ }+ let bytes = &buffer[..usize::try_from(written).ok()?];+ let path = CStr::from_bytes_until_nul(bytes)+ .ok()+ .map(CStr::to_string_lossy)+ .unwrap_or_else(|| String::from_utf8_lossy(bytes));+ Some(PathBuf::from(path.into_owned()))+}++/// An app bundle's executable always lives at `<Name>.app/Contents/MacOS/<exe>`;+/// this walks back up exactly that shape and refuses anything looser, so a+/// non-bundled executable (a bare binary, a symlink farm) yields no root+/// rather than a guess.+fn bundle_root_from_executable(executable: &Path) -> Option<PathBuf> {+ let macos_dir = executable.parent()?;+ if macos_dir.file_name()?.to_str()? != "MacOS" {+ return None;+ }+ let contents_dir = macos_dir.parent()?;+ if contents_dir.file_name()?.to_str()? != "Contents" {+ return None;+ }+ let bundle_root = contents_dir.parent()?;+ if bundle_root.extension()?.to_str()? != "app" {+ return None;+ }+ Some(bundle_root.to_path_buf())+}++#[cfg(test)]+#[path = "renderer_kind_tests.rs"]+mod tests;diff --git a/crates/macos/src/system/renderer_kind_tests.rs b/crates/macos/src/system/renderer_kind_tests.rsnew file mode 100644index 000000000..999e60af1--- /dev/null+++ b/crates/macos/src/system/renderer_kind_tests.rs@@ -0,0 +1,113 @@+use super::*;+use std::sync::atomic::{AtomicU64, Ordering};++static NEXT_TEMP_ID: AtomicU64 = AtomicU64::new(0);++/// A throwaway `<Name>.app` fixture under the system temp directory, removed+/// on drop so a panicking test does not litter it behind.+struct FixtureBundle {+ root: PathBuf,+}++impl FixtureBundle {+ fn new() -> Self {+ let mut root = std::env::temp_dir();+ root.push(format!(+ "agent-desktop-renderer-kind-test-{}-{}",+ std::process::id(),+ NEXT_TEMP_ID.fetch_add(1, Ordering::Relaxed)+ ));+ root.push("Fixture.app");+ std::fs::create_dir_all(&root).unwrap();+ Self { root }+ }++ fn add_framework(&self, name: &str) {+ let frameworks = self.root.join("Contents/Frameworks");+ std::fs::create_dir_all(&frameworks).unwrap();+ std::fs::create_dir_all(frameworks.join(name)).unwrap();+ }++ fn add_empty_contents(&self) {+ std::fs::create_dir_all(self.root.join("Contents")).unwrap();+ }+}++impl Drop for FixtureBundle {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(self.root.parent().unwrap());+ }+}++#[test]+fn chromium_marker_in_bundle_is_true_for_an_electron_framework_entry() {+ let bundle = FixtureBundle::new();+ bundle.add_framework("Electron Framework.framework");++ assert!(chromium_marker_in_bundle(&bundle.root));+}++#[test]+fn chromium_marker_in_bundle_is_false_without_a_matching_framework() {+ let bundle = FixtureBundle::new();+ bundle.add_framework("Sparkle.framework");++ assert!(!chromium_marker_in_bundle(&bundle.root));+}++#[test]+fn chromium_marker_in_bundle_is_false_when_frameworks_dir_is_missing() {+ let bundle = FixtureBundle::new();+ bundle.add_empty_contents();++ assert!(!chromium_marker_in_bundle(&bundle.root));+}++#[test]+fn bundle_root_is_derived_from_the_conventional_executable_layout() {+ let executable = Path::new("/Applications/Fixture.app/Contents/MacOS/Fixture");++ assert_eq!(+ bundle_root_from_executable(executable),+ Some(PathBuf::from("/Applications/Fixture.app"))+ );+}++#[test]+fn bundle_root_is_none_for_a_bare_executable_outside_any_bundle() {+ assert_eq!(+ bundle_root_from_executable(Path::new("/usr/bin/fixture")),+ None+ );+}++#[test]+fn bundle_root_is_none_when_the_macos_directory_is_missing() {+ let executable = Path::new("/Applications/Fixture.app/Contents/Fixture");++ assert_eq!(bundle_root_from_executable(executable), None);+}++#[test]+fn bundle_root_is_none_when_the_containing_directory_is_not_an_app_bundle() {+ let executable = Path::new("/opt/Fixture/Contents/MacOS/Fixture");++ assert_eq!(bundle_root_from_executable(executable), None);+}++#[test]+fn electron_and_cef_framework_names_are_recognized_exactly() {+ assert!(is_chromium_framework_marker("Electron Framework.framework"));+ assert!(is_chromium_framework_marker(+ "Chromium Embedded Framework.framework"+ ));+}++#[test]+fn unrelated_or_partial_framework_names_are_not_recognized() {+ assert!(!is_chromium_framework_marker("Sparkle.framework"));+ assert!(!is_chromium_framework_marker("Electron Framework"));+ assert!(!is_chromium_framework_marker(+ "electron framework.framework"+ ));+}diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex 728a5b230..593dc0f21 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -44,8 +44,8 @@ Detailed documentation is split into focused reference files. Read them as neede|-----------|----------|| `references/commands-observation.md` | snapshot, find, get, is, screenshot, list-surfaces — all flags, output examples || `references/commands-interaction.md` | click, type, set-value, select, toggle, scroll, drag, keyboard, mouse — choosing the right command |-| `references/commands-system.md` | launch, close, windows, clipboard, wait, batch, session, status, permissions, version |-| `references/workflows.md` | 12 common patterns: forms, menus, dialogs, scroll-find, drag-drop, async wait, anti-patterns |+| `references/commands-system.md` | launch (including `--cdp` for Chromium web contents), close, windows, clipboard, wait, batch, session, status, permissions, version |+| `references/workflows.md` | 16 common patterns: forms, menus, dialogs, scroll-find, drag-drop, async wait, anti-patterns || `references/macos.md` | macOS permissions/TCC, AX API internals, smart activation chain, surfaces, Notification Center, troubleshooting |## The Observe-Act Loop (Progressive Skeleton Traversal)@@ -77,7 +77,7 @@ Use **progressive skeleton traversal** as the default approach. It reduces token- Surface snapshots (menus, sheets, alerts) — these are already focused**When skeleton shines:**-- Dense Electron apps (Slack, VS Code, Discord, Notion)+- Dense Electron apps (Slack, VS Code, Discord, Notion) that are **already running** — for one you are launching fresh, `launch --cdp` plus a CDP client (agent-browser preferred) reads the web contents faster than any skeleton walk (see principle 15)- Any app where full snapshot exceeds ~50 refs- Multi-region workflows (sidebar + main content + toolbar)@@ -188,6 +188,7 @@ agent-desktop --headed mouse-move --xy 100,200 # Move cursor```agent-desktop launch "System Settings" # Launch; returns once runningagent-desktop launch "TextEdit" --activate # Also bring it forward and wait for a window+agent-desktop launch "Obsidian" --cdp # Fresh launch + verified Chrome DevTools Protocol port for web contentsagent-desktop close-app "TextEdit" # Quit gracefullyagent-desktop close-app "TextEdit" --force # Force quit; SIGKILL if SIGTERM does not exitagent-desktop list-windows --app "Finder" # List windows@@ -256,7 +257,7 @@ agent-desktop skills get desktop --full # Load this skill + all referenc## Key Principles for Agents-1. **Skeleton first, drill second.** Start with `--skeleton -i --compact` for dense apps. Drill into regions with `--root @ref`. Full snapshot only for simple apps.+1. **Skeleton first, drill second.** Start with `--skeleton -i --compact` for dense apps. Drill into regions with `--root @ref`. Full snapshot only for simple apps. For a Chromium app you are launching fresh, prefer `launch --cdp` + a CDP client for the web contents instead (principle 15).2. **Use `-i --compact` flags.** Filters to interactive elements and collapses empty wrappers, minimizing tokens.3. **Refs are snapshot-scoped.** Keep `snapshot_id` for deterministic multi-step use; re-drill the affected region after any UI-changing action. Scoped invalidation keeps other refs intact.4. **Prefer refs over coordinates.** `click @s8f3k2p9:e5` > `agent-desktop --headed mouse-click --xy 500,300`.@@ -270,3 +271,4 @@ agent-desktop skills get desktop --full # Load this skill + all referenc12. **Headless by default.** Ref actions use semantic AX paths and block silent focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. Use `--headed` only when exact-window focus or physical delivery is intended; raw coordinates never imply focus.13. **Start a session once per run.** `session start` creates the manifest; pass its returned ID through `AGENT_DESKTOP_SESSION` for the run or `--session <id>` for one command. It does not activate later processes implicitly.14. **Trace hard failures.** With an active trace-enabled session, segments are written automatically. Add `--trace /tmp/agent-desktop.jsonl` only when you need a single override file (CI, one-offs). Check `status` when unsure whether tracing is active.+15. **Chromium-app strategy.** The accessibility path is the default, and the only option for already-running apps and for native surfaces (menus, dialogs, windows). `launch --cdp` plus a CDP client (agent-browser preferred; any CDP client works) is the opt-in fast path for a Chromium app's web contents, when a fresh launch is acceptable.diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.mdindex a4169b7d4..2ebdfecfe 100644--- a/skills/agent-desktop/references/commands-observation.md+++ b/skills/agent-desktop/references/commands-observation.md@@ -105,6 +105,7 @@ agent-desktop snapshot --root @e3 --snapshot <snapshot_id> -i- Combine `--max-depth 5` to limit deep trees (e.g., Xcode)- Use `--skeleton` first to get a high-level map, then `--root` to drill into specific regions- Combine `--skeleton` with `-i` and `--compact` for the most token-efficient initial overview+- For a Chromium-based app's web contents (Slack, VS Code, Discord, and similar), `launch --cdp` plus a CDP client is a faster alternative to skeleton traversal on a fresh launch — see `references/commands-system.md`- Keep `snapshot_id` when commands must resolve against a specific snapshot instead of the latest snapshot pointer## finddiff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex e307848af..bb1f0c07a 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -12,17 +12,20 @@ agent-desktop launch "TextEdit" --arg /tmp/notes.txtagent-desktop launch "MyTool" --arg --flag --arg value --env KEY=VALUE --cwd /tmpagent-desktop launch "MyTool" --no-attachagent-desktop launch "TextEdit" --activate+agent-desktop launch "Obsidian" --cdp+agent-desktop launch "Obsidian" --cdp 9229```Launches an application by name or bundle ID and returns once the process is running.| Flag | Default | Description ||------|---------|-------------|| `--timeout` | 30000 | Upper bound in ms for the whole launch |-| `--arg` | | Command-line argument passed to the launched app; repeatable, order preserved |+| `--arg` | | Command-line argument passed to the launched app; repeatable, order preserved. For a value that starts with `-`, use the equals form (`--arg=<value>`) — the space form swallows the next flag || `--env` | | `KEY=VALUE` environment variable for the launched process; repeatable || `--cwd` | | Working directory for the launched process || `--no-attach` | false | Require a fresh launch instead of the default attach-if-running behavior || `--activate` | false | Bring the app forward so it presents a window, and wait for that window |+| `--cdp` | | Launch fresh with a Chrome DevTools Protocol port, verified before return; optional `[PORT]`, `0` or omitted picks a free port |The process starting and the app presenting a window are separate outcomes, so the response reports them separately:@@ -33,6 +36,17 @@ The process starting and the app presenting a window are separate outcomes, so t`window` is present when the app already has one and **omitted when it does not**. Its absence is a fact, not a failure — `launch` still returns `ok: true`.+When the launched app's bundle is built on Chromium — detected from the bundle's frameworks, not the app's name — the response also carries `renderer: "chromium"` and a `suggestion` string:++```json+{ "app": "Slack", "pid": 2201, "process_instance": "macos-proc-v1:...",+ "window": { "id": "w-8891", "title": "Slack | general", "visible": true },+ "renderer": "chromium",+ "suggestion": "Chromium app: for web-content work, run close-app and then launch --cdp, then drive the web contents with agent-browser or any CDP client. Accessibility commands still cover everything, including native menus and dialogs." }+```++`renderer` and `suggestion` are both optional and omitted on a non-Chromium app. Read `suggestion` as a hint the response carries, not an instruction the command enforces — a plain `launch` still succeeds and the accessibility path still works on a Chromium app; the field only names the faster option for the web-content case. See "Driving the web contents of a Chromium app" below for the `--cdp` flow the suggestion points at.+A launch waits only for the windows the launch itself causes. It polls until the app reports that it finished starting up, plus a short grace for the first window to reach the window server. Most apps therefore return their window in one step. An app that opens its first window only when brought forward — any document-based app — returns without one instead of waiting out `--timeout`.A launch that finds its process gone before any window appears fails with `APP_UNRESPONSIVE` rather than reporting a windowless success.@@ -44,6 +58,59 @@ When you need the window:Windowless, menu-bar-only, and background apps simply report no `window`; use `list-apps` to observe those processes and read their `presentation`. `--no-attach` rejects an already-running app with `ACTION_FAILED` and starts a fresh instance.+### Driving the web contents of a Chromium app+```bash+agent-desktop launch "Obsidian" --cdp+agent-desktop launch "Obsidian" --cdp 9229+```+Use `--cdp` on Electron and other Chromium-based apps — Slack, VS Code, Discord, Obsidian, Notion, and similar — whose web contents are dense or slow to walk through the accessibility tree. It launches the app fresh with `--remote-debugging-port=<port>` and `--remote-debugging-address=127.0.0.1` (loopback pinned), then polls `http://127.0.0.1:<port>/json/version` until the endpoint answers with a parseable `webSocketDebuggerUrl`, before the command returns. Pass a port number for an explicit choice; omit it or pass `0` to let the OS pick a free one.++The port exists only for a fresh process, so `--cdp` requires a fresh launch. `launch` never quits a running app for you — a silent quit loses the user's state — so an already-running target returns `ACTION_FAILED` with `details.kind: "cdp_requires_fresh_launch"` instead. Run `close-app` first, confirm the process exited, then launch again with `--cdp`.++`--cdp` owns the remote-debugging switches. A user `--arg` naming `--remote-debugging-port`, `--remote-debugging-pipe`, `--remote-debugging-address`, or `--remote-allow-origins` is rejected before launch — see `cdp_switch_conflict` below.++On success, the response adds a `cdp` object and a `suggestion` string naming the next step. "Verified" means the endpoint answered `/json/version` with a parseable `webSocketDebuggerUrl`, so `cdp.websocket_url` is always present on success:++```json+{ "app": "Obsidian", "pid": 4821, "cdp": {+ "port": 9229,+ "http_endpoint": "http://127.0.0.1:9229",+ "websocket_url": "ws://127.0.0.1:9229/devtools/browser/<id>",+ "product": "Chrome/142.0.7444.265"+},+ "suggestion": "Next: run `agent-browser connect <port>` (preferred; `agent-browser skills get electron` has the guide) or connect any CDP client such as Playwright or Puppeteer. If neither is available, ask the user to install agent-browser or continue with accessibility commands. Do not hand-roll raw CDP or call app-internal APIs — that path is unverified and app-specific. Native menus, dialogs, windows, and screenshots stay with agent-desktop." }+```++`suggestion` is informational, the same way `data.cdp` itself is — read it, do not treat it as a command the process enforces.++The probe that verifies the endpoint has a reserved time budget so a slow launch cannot consume it: `reserve = min(5s, one quarter of the remaining launch budget)`, carved out of `--timeout` before the probe starts.++Errors:++| Code | `details.kind` | Meaning | Recovery |+|------|-----------------|---------|----------|+| `ACTION_FAILED` | `cdp_requires_fresh_launch` | The app was already running | `close-app`, confirm it exited, then `launch --cdp` again |+| `INVALID_ARGS` | `cdp_port_in_use` | The explicit port you named is already bound | Name a different port, or omit the number and let agent-desktop pick a free one |+| `INVALID_ARGS` | `cdp_switch_conflict` | `--arg` also carried `--remote-debugging-port`, `--remote-debugging-pipe`, `--remote-debugging-address`, or `--remote-allow-origins` | Drop that `--arg`; `--cdp` owns the remote-debugging switches |+| `ACTION_FAILED` | `cdp_endpoint_unavailable` | No DevTools endpoint answered on the port before the deadline — a non-Chromium app, one that strips debugging switches from its main process, or one still starting up | `details` carries `pid`, `port`, `elapsed_ms`, `probe_budget_ms`, `process_instance`, and `responder_without_devtools_body: true` when something answered over HTTP without a DevTools body. The app is left running; fall back to the accessibility path |++Security: `--remote-debugging-address=127.0.0.1` pins the endpoint to loopback and `--cdp` rejects `--arg` values that would widen it, but while the port is open, any local process running as your user can still reach it and gain full control of the app's web contents — that boundary belongs to the OS, not to agent-desktop. Request `--cdp` only for the step that needs it; `close-app` ends the exposure along with the app itself.++**Handoff:** once `data.cdp` is present, drive the app's web contents with a CDP client — agent-desktop never talks to that port itself. Any framework that speaks CDP can connect: `agent-browser` is preferred (it has the ref-based agent workflow and a bundled `electron` skill), but Playwright, Puppeteer, `chrome-remote-interface`, and other CDP clients work too. Check for `agent-browser` first (`command -v agent-browser`):++- If it is installed, connect with `agent-browser connect <port>`, then use its normal snapshot/click/type workflow. It ships an `electron` skill: `agent-browser skills get electron`.+- If it is not installed but another CDP client is available, connect with that instead.+- If neither is available, ask the user to run `npm install -g agent-browser`, or keep using agent-desktop's accessibility commands — those always work, on this app or any other.++agent-desktop never invokes `agent-browser` itself; the calling agent does. Even with CDP connected, these stay on the accessibility path, because CDP cannot reach them:++- The native menu bar (`snapshot --surface menubar`)+- File dialogs and sheets+- Window management (`list-windows`, `focus-window`, `resize-window`, and related commands)+- Notifications+- Screenshots+- Any app you did not launch yourself — CDP cannot attach to an already-running process, so the accessibility path is the only attach story there+### close-app```bashagent-desktop close-app "TextEdit"@@ -335,6 +402,7 @@ Transient errors (timeouts, element-not-found) are retried within the `--timeoutagent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}},{"command":"wait","args":{"ms":500}},{"command":"click","args":{"ref_id":"@e2","snapshot":"<snapshot_id>"}}]'agent-desktop batch '[...]' --stop-on-erroragent-desktop --session run-a batch '[{"command":"status","session":"run-b","args":{}}]'+agent-desktop batch '[{"command":"launch","args":{"app":"Obsidian","cdp":0}}]'```Execute multiple commands in sequence from a JSON array. Each entry has `command` (string) and `args` (object). Use `args`, not `params`. For ref-consuming commands, pass the output `snapshot_id` as the `snapshot` field.diff --git a/skills/agent-desktop/references/macos.md b/skills/agent-desktop/references/macos.mdindex deb1c1b71..78cef0f54 100644--- a/skills/agent-desktop/references/macos.md+++ b/skills/agent-desktop/references/macos.md@@ -179,6 +179,7 @@ Some apps don't expose full accessibility trees:- Remove `-i` flag to see all elements including non-interactive ones- Increase `--max-depth` to explore deeper- Use `screenshot` as a visual fallback+- For a Chromium-based app's web contents specifically, `launch --cdp` plus a CDP client is a faster path than a deep accessibility walk — see `references/commands-system.md`. Accessibility remains the only attach story for an app already running, and the only path to native surfaces even when `--cdp` is in use.### STALE_REF / SNAPSHOT_NOT_FOUNDdiff --git a/skills/agent-desktop/references/workflows.md b/skills/agent-desktop/references/workflows.mdindex 8fd09f0e1..a308c55d6 100644--- a/skills/agent-desktop/references/workflows.md+++ b/skills/agent-desktop/references/workflows.md@@ -83,6 +83,45 @@ agent-desktop snapshot --root @e1 --snapshot <snapshot_id> -i --compact- Re-drilling the same root replaces only that root's subtree refs- Interactive elements (buttons, textfields) within skeleton depth still get normal refs+## Pattern: Task in a Chromium App (Two Tools, Hand in Hand)++Task: open Slack and send a message to a person. Slack is Chromium-based, so this pattern hands the web-content step to a CDP client — any framework that speaks CDP works, agent-browser preferred — while agent-desktop keeps every native surface.++```bash+# 1. Launch normally first — no --cdp yet+agent-desktop launch "Slack"+# Response includes: "renderer": "chromium", "suggestion": "For web-content work: close-app, ..."+# The suggestion is a fact to read, not an order — the accessibility path still works here.++# 2. Decide the task needs web-content work (composing and sending a message+# lives in Slack's web contents, which are dense through the accessibility tree).+# A fresh launch is required for --cdp, so close the app first.+agent-desktop close-app "Slack"+agent-desktop wait --event app-terminated --app "Slack" --timeout 10000++# 3. Relaunch with a verified CDP port+agent-desktop launch "Slack" --cdp+# Response: data.cdp.port = 9231++# 4. Hand off to a CDP client — agent-browser preferred, any CDP client works+command -v agent-browser+# If present:+agent-browser connect 9231+# Then its normal workflow: snapshot, find the person, click, type the message, send.+# agent-browser skills get electron # Electron-specific guidance if needed+# If absent, connect with Playwright, Puppeteer, chrome-remote-interface, or another CDP client instead.++# 5. Anything native happens on agent-desktop meanwhile, over the same launch —+# a menu bar item, a file-attach dialog, or a delivered notification:+agent-desktop snapshot --app "Slack" --surface menubar -i+agent-desktop --headed list-notifications --app "Slack"++# 6. Cleanup: close-app ends the port along with the app when the task is done+agent-desktop close-app "Slack"+```++**Fallback when no CDP client is installed:** ask the user to run `npm install -g agent-browser`, or skip `--cdp` and keep working through agent-desktop's accessibility path — `snapshot --skeleton --app "Slack" -i --compact` and drill into the message composer the same way as any other dense app. Accessibility always works; `--cdp` is the opt-in fast path when a fresh launch is acceptable and a CDP client is available.+## Pattern: Fill a Form```bash@@ -309,3 +348,4 @@ agent-desktop batch '[8. **Snapshotting the full window when an overlay is open.** Use `--surface sheet/alert/popover/menu` instead. Never `--skeleton` for surfaces — they're already focused.9. **Re-snapshotting everything after one action.** Use scoped re-drill (`--root @ref`) to refresh only the affected region. Other refs stay valid.10. **Assuming headed and headless have the same side effects.** Headless ref actions block implicit focus/cursor input. Headed ref actions intentionally focus the exact source window when required, and headed pointer actions may move the cursor; raw coordinates never infer focus.+11. **Hand-rolling raw CDP for a Chromium app.** After `launch --cdp`, connect a real CDP client — `agent-browser connect <port>` (preferred), or Playwright, Puppeteer, `chrome-remote-interface`, and similar — never a hand-written WebSocket client, `Runtime.evaluate` DOM edits, or app-internal APIs (e.g. an app's own JS globals). Those bypass real input, verify nothing, and are app-specific; they break silently on the next app update. If no CDP client is available, ask the user to install agent-browser or stay on accessibility commands.diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rsindex b842481e8..82b99c03c 100644--- a/src/cli/contract_tests.rs+++ b/src/cli/contract_tests.rs@@ -10,6 +10,7 @@ const NON_COMMAND_MODULES: &[&str] = &["helpers","helpers_test_support","input_hold_policy",+ "launch_cdp_test_support","mod","notification_identity","notification_policy",diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex b195a0bc1..9ad095853 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -95,7 +95,7 @@ pub(crate) enum Commands {#[command(about = "Scroll the mouse wheel at absolute coordinates (requires --headed)")]MouseWheel(MouseWheelArgs),#[command(- about = "Launch application and return once its process is running; --activate waits for a window"+ about = "Launch application and return once its process is running; --activate waits for a window, --cdp verifies a DevTools endpoint")]Launch(LaunchArgs),#[command(about = "Quit an application gracefully (--force to terminate)")]diff --git a/src/cli_args/system.rs b/src/cli_args/system.rsindex 4d770b366..e4d0995ea 100644--- a/src/cli_args/system.rs+++ b/src/cli_args/system.rs@@ -25,7 +25,9 @@ pub(crate) struct LaunchArgs {pub timeout: u64,#[arg(long = "arg",- help = "Command-line argument passed to the launched app"+ allow_hyphen_values = true,+ help = "Command-line argument passed to the launched app; repeatable, order preserved. \+ For values starting with '-', use --arg=<value>")]#[serde(default)]pub args: Vec<String>,@@ -50,6 +52,15 @@ pub(crate) struct LaunchArgs {)]#[serde(default)]pub activate: bool,+ #[arg(+ long,+ value_name = "PORT",+ num_args = 0..=1,+ default_missing_value = "0",+ help = "Expose the app's DevTools protocol endpoint on this port (0 or omitted picks a free port)"+ )]+ #[serde(default)]+ pub cdp: Option<u16>,}#[derive(Parser, Debug, Deserialize)]diff --git a/src/cli_args/system_tests.rs b/src/cli_args/system_tests.rsindex 0652b86e1..20163ad5f 100644--- a/src/cli_args/system_tests.rs+++ b/src/cli_args/system_tests.rs@@ -1,5 +1,53 @@use super::*;+/// Chromium switches all start with `--`, and `--arg` passthrough exists+/// specifically to forward them; clap rejects a hyphen-leading value on a+/// plain option unless `allow_hyphen_values` says otherwise.+#[test]+fn launch_arg_passthrough_accepts_a_hyphen_leading_value() {+ let args = LaunchArgs::try_parse_from(["launch", "X", "--arg", "--remote-debugging-port=9229"])+ .unwrap();++ assert_eq!(args.args, vec!["--remote-debugging-port=9229"]);+}++/// `num_args(0..=1)` with `default_missing_value` makes `--cdp` alone mean+/// "auto-pick a port" (represented as the sentinel `Some(0)`) so callers+/// are not forced to invent a port number just to ask for the endpoint.+#[test]+fn launch_cdp_flag_defaults_to_auto_pick_when_bare() {+ let args = LaunchArgs::try_parse_from(["launch", "X", "--cdp"]).unwrap();++ assert_eq!(args.cdp, Some(0));+}++#[test]+fn launch_cdp_flag_accepts_an_explicit_port() {+ let args = LaunchArgs::try_parse_from(["launch", "X", "--cdp", "9229"]).unwrap();++ assert_eq!(args.cdp, Some(9229));+}++#[test]+fn launch_cdp_flag_is_absent_when_not_given() {+ let args = LaunchArgs::try_parse_from(["launch", "X"]).unwrap();++ assert_eq!(args.cdp, None);+}++#[test]+fn launch_cdp_batch_json_parses_an_explicit_zero_and_an_absent_field() {+ let auto: LaunchArgs = serde_json::from_value(serde_json::json!({+ "app": "X",+ "cdp": 0+ }))+ .unwrap();+ let absent: LaunchArgs = serde_json::from_value(serde_json::json!({ "app": "X" })).unwrap();++ assert_eq!(auto.cdp, Some(0));+ assert_eq!(absent.cdp, None);+}+/// God-object regression: `WaitModeArgs` used to carry 9 flat fields;/// `event`/`window_id` now live in `WaitEventArgs`, flattened onto/// `WaitArgs` as a sibling of `mode`/`predicate` (nesting it insidediff --git a/src/dispatch/parse.rs b/src/dispatch/parse.rsindex b0ed5361e..3b4cfc796 100644--- a/src/dispatch/parse.rs+++ b/src/dispatch/parse.rs@@ -150,6 +150,7 @@ pub(crate) fn build_launch_options(timeout_ms: launch.timeout,attach_if_running: !launch.no_attach,activate: launch.activate,+ cdp_port: launch.cdp,})}diff --git a/src/dispatch/parse_tests.rs b/src/dispatch/parse_tests.rsindex 3b668c13f..8cf354f61 100644--- a/src/dispatch/parse_tests.rs+++ b/src/dispatch/parse_tests.rs@@ -109,5 +109,6 @@ fn launch_args(args: &[String], env: &[String]) -> crate::cli_args::system::Launcwd: None,no_attach: false,activate: false,+ cdp: None,}}