Skip to main content

agentmux_srv/server/
ui_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent-facing UI automation (`UIScreenshot` / `UIClick` / `UIQuery`, and
5//! the browser-pane deep-control tools `BrowserNavigate` / `BrowserBack` /
6//! `BrowserForward` / `BrowserReload` / `BrowserEval` / `BrowserDispatchKey`
7//! / `BrowserFocusElement` / `BrowserFocusInfo`) — proxies to the paired CEF
8//! host's `/agentmux/browser/*` CDP routes (`crates/cef/src/browser_api/`).
9//! See docs/specs/SPEC_AGENT_BROWSER_PANE_DEEP_CONTROL_2026_09_20.md for the
10//! browser-pane tools' own design (they additionally require the caller's
11//! own pane to be a dedicated browser pane — enforced host-side, not here).
12//!
13//! **`block_id` is never a client-supplied field on any request here**
14//! (2026-08-19, reagent + Codex review, PR #2662 — a bare client-supplied
15//! `block_id` was a real cross-agent content-disclosure vulnerability:
16//! `/api/v1/ui/*` shares the same instance-wide `X-AuthKey` every App-API
17//! route trusts, and any agent can read that key from its own environment,
18//! so no amount of "the MCP schema never exposes it" convention actually
19//! stopped a bypassing agent from supplying a different pane's real
20//! `block_id`). Every request instead carries `UiAutomationAuth` — an
21//! HMAC-SHA256 signature over the caller's own agent_id, using that
22//! agent's own `AGENTMUX_JEKT_KEY` (the same per-agent key already used
23//! for jekt sender authentication, see `agentmux_common::jekt_sign`).
24//! [`verified_block_id`] verifies that signature against the claimed
25//! agent's key on file, and — only once verification succeeds — looks up
26//! that agent's actual current block_id server-side via the global
27//! `ReactiveHandler` registry. The block_id a call actually operates on is
28//! never taken from the client at all, so there's nothing left to spoof:
29//! an agent without a valid signature for identity X cannot act as X, full
30//! stop, regardless of what it claims in the request body.
31//!
32//! See `agentmux_common::api_types`'s "UI automation" section and
33//! `docs/specs/SPEC_AGENT_UI_AUTOMATION_CLICK_SCREENSHOT_2026_08_18.md`.
34
35use axum::extract::State;
36use axum::http::StatusCode;
37use axum::response::{IntoResponse, Response};
38use axum::Json;
39use base64::Engine as _;
40use serde_json::json;
41
42use agentmux_common::api_types::{
43    UiAutomationAuth, UiBrowserDispatchKeyRequest, UiBrowserEvalRequest, UiBrowserFocusElementRequest,
44    UiBrowserFocusInfoRequest, UiBrowserHistoryRequest, UiBrowserNavigateRequest, UiBrowserOpenRequest, UiClickRequest,
45    UiQueryRequest, UiScreenshotRequest, UiScreenshotResponse,
46};
47
48use super::{AppState, HostIpc};
49use crate::server::browser_actions::{note, How, Kind, Note};
50
51/// Signatures older than this are rejected — bounds replay of a leaked/
52/// logged signature to a short window. Mirrors `server/reactive.rs`'s
53/// `JEKT_SIG_MAX_AGE_SECS` (same threat model: a host-tier HMAC signature
54/// verified locally, not a one-time nonce scheme).
55const UI_AUTOMATION_SIG_MAX_AGE_SECS: i64 = 300;
56
57use agentmux_common::time::now_secs as now_unix_secs;
58
59/// Verify `auth` proves the caller genuinely is `auth.agent_id` (via that
60/// agent's own jekt key — an attacker without agent_id's key cannot
61/// produce a valid signature no matter what it claims), then derive that
62/// agent's ACTUAL current block_id server-side. Never trusts a block_id
63/// from the client — there isn't one to trust. See this module's own doc
64/// comment for the full rationale.
65/// `pub(crate)`: also reused by `app_api::pane::handle_close_pane` (and any
66/// future own-pane-resolving handler) — the identity-verification mechanism
67/// isn't UI-automation-specific, just first built for it. See
68/// docs/specs/SPEC_AGENT_PANE_LIFECYCLE_CONTROL_2026_09_10.md §5.0.
69///
70/// Identity M4a-2: `caller` is the request's [`Caller`](crate::server::caller::Caller);
71/// `auth.agent_id` is counted against it (`m4.actor_*.ui_auth`), never refused
72/// on it — M4d moves this check onto `Caller` (spec §6.5.4).
73pub(crate) fn verified_block_id(
74    state: &AppState,
75    caller: Option<&crate::server::caller::Caller>,
76    auth: &UiAutomationAuth,
77) -> Result<String, String> {
78    crate::server::actor::check_actor(
79        state,
80        caller,
81        crate::server::actor::ActorSite::UiAuth,
82        Some(&auth.agent_id),
83    );
84    if let Some(block) = crate::server::actor::own_pane_by_token(&state.mstore, caller, &auth.agent_id) {
85        return Ok(block); // identity M4d-4
86    }
87    crate::backend::agent_resolve::record_uid_fallback("m4d.ui_auth_by_name");
88    if auth.ts_secs <= 0 || (now_unix_secs() - auth.ts_secs).abs() > UI_AUTOMATION_SIG_MAX_AGE_SECS
89    {
90        return Err("signature timestamp missing or outside the freshness window".to_string());
91    }
92    // Refused for a former slug, even with a key still filed under it.
93    let key = super::reactive::former_slug::signing_key(state, &auth.agent_id)?;
94    let ok = agentmux_common::jekt_sign::verify_jekt(
95        &key,
96        "ui-automation-identity",
97        &auth.agent_id,
98        "__srv__",
99        auth.ts_secs,
100        "",
101        &auth.sig,
102    );
103    if !ok {
104        tracing::warn!(
105            agent_id = %auth.agent_id,
106            "[ui-automation] REJECTED an invalid identity signature — either a forged \
107             request or a stale/corrupted key"
108        );
109        return Err("identity signature verification failed".to_string());
110    }
111
112    crate::backend::reactive::handler::get_global_handler()
113        .get_agent(&auth.agent_id)
114        .map(|reg| reg.block_id)
115        .ok_or_else(|| {
116            format!(
117                "agent_id={:?} verified but is not currently registered with a pane \
118                 (not spawned via AgentMux, or not yet registered)",
119                auth.agent_id
120            )
121        })
122}
123
124/// The block a UI-automation request acts on: the caller's own pane, or,
125/// when `pane` is given, a browser pane the caller opened with `OpenBrowser`
126/// (docs/specs/SPEC_AGENT_DRIVEN_BROWSER_PANES_2026_10_07.md §3). The caller's
127/// identity is verified first either way; `pane` is then checked against
128/// `browser_owner`'s map, never trusted on its own. Every agent browser call
129/// comes through here, so a target it may drive counts as its activity there
130/// (`browser_bypass::touch`: a quiet agent's Auto-approve ends).
131pub(crate) fn target_block_id(
132    state: &AppState,
133    caller: Option<&crate::server::caller::Caller>,
134    auth: &UiAutomationAuth,
135    pane: Option<&str>,
136) -> Result<String, (StatusCode, String)> {
137    let target = resolve_target(state, caller, auth, pane)?;
138    crate::server::browser_bypass::touch(&target, &auth.agent_id);
139    crate::server::browser_agent_calls::note(&banner_for(&target).0);
140    Ok(target)
141}
142
143fn resolve_target(
144    state: &AppState,
145    caller: Option<&crate::server::caller::Caller>,
146    auth: &UiAutomationAuth,
147    pane: Option<&str>,
148) -> Result<String, (StatusCode, String)> {
149    let own = verified_block_id(state, caller, auth).map_err(|e| (StatusCode::UNAUTHORIZED, e))?;
150    target_for(state, &own, &auth.agent_id, pane)
151}
152
153/// The pane a call acts on, once its auth gave the agent's own pane `own`:
154/// `pane` when the agent may act on it, else `own`, refused while paused or
155/// waiting on the person. A call that waited (a sign-in's approval) checks
156/// again with this, not with its auth, whose freshness window is shorter.
157pub(crate) fn target_for(state: &AppState, own: &str, agent_id: &str, pane: Option<&str>) -> Result<String, (StatusCode, String)> {
158    use crate::server::browser_owner::{self, Denied};
159    let own = own.to_string();
160    let Some(pane) = pane.map(str::trim).filter(|p| !p.is_empty()) else {
161        return not_waiting_on_user(&own).map(|()| own);
162    };
163    if crate::server::browser_popup::is_window_id(pane) {
164        return popup_window_target(state, pane, agent_id);
165    }
166    let block = state
167        .mstore
168        .get::<crate::backend::obj::Block>(pane)
169        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("load pane {pane:?}: {e}")))?;
170    match browser_owner::check(block.as_ref(), browser_owner::owner_of(pane).as_deref(), agent_id, pane) {
171        Ok(()) => {
172            opener_allows(state, block.as_ref(), agent_id, pane)?;
173            not_waiting_on_user(pane).map(|()| pane.to_string())
174        }
175        Err(Denied::NotFound(m)) => {
176            // The pane is gone: drop any owner entry it left behind.
177            browser_owner::forget(pane);
178            Err((StatusCode::NOT_FOUND, m))
179        }
180        Err(Denied::Forbidden(m)) => Err((StatusCode::FORBIDDEN, m)),
181    }
182}
183
184pub(crate) async fn get_host_ipc(state: &AppState) -> Result<HostIpc, String> {
185    state.host_ipc.lock().await.clone().ok_or_else(|| {
186        "this AgentMux instance's CEF host has not registered its UI-automation \
187         credentials yet (host_ipc.Register) — try again in a moment"
188            .to_string()
189    })
190}
191
192/// POST `body` to `/agentmux/browser/{route}` on the paired host and return
193/// its parsed JSON response (the host's own `{ok, data}` / `{ok, error}`
194/// envelope — see `browser_api::types::ApiResponse`).
195async fn proxy_to_host(
196    state: &AppState,
197    host: &HostIpc,
198    route: &str,
199    body: serde_json::Value,
200) -> Result<serde_json::Value, String> {
201    proxy_to_host_timeout(state, host, route, body, None).await
202}
203
204/// `proxy_to_host` with a request timeout of its own, for host routes that
205/// legitimately take longer than the shared client's default (a snapshot of
206/// a large page, `wait_for`).
207pub(crate) async fn proxy_to_host_timeout(
208    state: &AppState,
209    host: &HostIpc,
210    route: &str,
211    body: serde_json::Value,
212    timeout: Option<std::time::Duration>,
213) -> Result<serde_json::Value, String> {
214    super::browser_hibernation::post_to_host_awake(state, host, route, body, timeout).await
215}
216
217pub(crate) fn err_response(status: StatusCode, e: String) -> Response {
218    (status, Json(json!({ "ok": false, "error": e }))).into_response()
219}
220
221/// Delete `*.png` files in `dir` older than [`SCREENSHOT_RETENTION`]. Called
222/// on every `UIScreenshot` write since this directory only ever grows
223/// otherwise (reagent P2, PR #2662) — no background scheduler needed for a
224/// directory nothing else writes to. Best-effort: any I/O error for an
225/// individual entry (permissions, a concurrent delete, a non-UTF8 name) is
226/// skipped rather than failing the screenshot request that triggered it.
227const SCREENSHOT_RETENTION: std::time::Duration = std::time::Duration::from_secs(60 * 60);
228
229fn prune_old_screenshots(dir: &std::path::Path) {
230    let Ok(entries) = std::fs::read_dir(dir) else {
231        return;
232    };
233    let now = std::time::SystemTime::now();
234    for entry in entries.flatten() {
235        let path = entry.path();
236        if path.extension().and_then(|e| e.to_str()) != Some("png") {
237            continue;
238        }
239        let Ok(metadata) = entry.metadata() else { continue };
240        let Ok(modified) = metadata.modified() else { continue };
241        let Ok(age) = now.duration_since(modified) else { continue };
242        if age > SCREENSHOT_RETENTION {
243            let _ = std::fs::remove_file(&path);
244        }
245    }
246}
247
248/// `POST /api/v1/ui/screenshot` — backs the `UIScreenshot` MCP tool.
249/// Captures a PNG clipped to the caller's own pane, writes it to
250/// `<mux_data_dir>/tmp/ui-screenshots/<uuid>.png`, and returns both the
251/// path (openable in the Editor) and the base64 bytes inline.
252pub(crate) async fn handle_ui_screenshot(
253    State(state): State<AppState>,
254    caller: Option<axum::Extension<crate::server::caller::Caller>>,
255    Json(req): Json<UiScreenshotRequest>,
256) -> impl IntoResponse {
257    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
258        Ok(b) => b,
259        Err((code, e)) => return err_response(code, e),
260    };
261    let host = match get_host_ipc(&state).await {
262        Ok(h) => h,
263        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
264    };
265
266    let host_resp = match proxy_to_host(&state, &host, "screenshot", json!({ "block_id": block_id, "full_page": req.full_page, "region": req.region, "canvas": req.canvas, "scale": req.scale })).await {
267        Ok(v) => v,
268        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
269    };
270    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
271        let err = host_resp
272            .get("error")
273            .and_then(|v| v.as_str())
274            .unwrap_or("unknown host error")
275            .to_string();
276        return err_response(StatusCode::BAD_REQUEST, err);
277    }
278    let png_base64 = host_resp
279        .get("data")
280        .and_then(|d| d.get("png_base64"))
281        .and_then(|v| v.as_str())
282        .unwrap_or("")
283        .to_string();
284    if png_base64.is_empty() {
285        return err_response(
286            StatusCode::BAD_GATEWAY,
287            "host returned no png_base64".to_string(),
288        );
289    }
290
291    let bytes = match base64::engine::general_purpose::STANDARD.decode(&png_base64) {
292        Ok(b) => b,
293        Err(e) => {
294            return err_response(StatusCode::BAD_GATEWAY, format!("decode png_base64: {e}"))
295        }
296    };
297    let (bytes, png_base64) = match crate::server::screenshot_redact::redact_host_screenshot(&host_resp, bytes, png_base64) {
298        Ok(v) => v, // a browser pane's secret fields blacked out, or none on the page
299        Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, e),
300    };
301
302    let dir = crate::backend::base::get_mux_data_dir().join("tmp/ui-screenshots");
303    if let Err(e) = std::fs::create_dir_all(&dir) {
304        return err_response(
305            StatusCode::INTERNAL_SERVER_ERROR,
306            format!("create screenshots dir: {e}"),
307        );
308    }
309    let path = dir.join(format!("{}.png", uuid::Uuid::new_v4()));
310    if let Err(e) = std::fs::write(&path, &bytes) {
311        return err_response(
312            StatusCode::INTERNAL_SERVER_ERROR,
313            format!("write screenshot: {e}"),
314        );
315    }
316    // Unbounded growth over repeated/looped verification calls otherwise
317    // (reagent P2, PR #2662, 2026-08-19) — no expiry mechanism existed at
318    // all. Best-effort, on the write path rather than a background task:
319    // simple and sufficient for a directory that's only ever written here.
320    prune_old_screenshots(&dir);
321
322    tracing::info!(
323        agent_id = %req.auth.agent_id,
324        block_id = %block_id,
325        path = %path.display(),
326        "[ui-automation] screenshot"
327    );
328
329    (
330        StatusCode::OK,
331        Json(UiScreenshotResponse {
332            path: path.to_string_lossy().to_string(),
333            png_base64,
334            note: host_resp.pointer("/data/note").and_then(|v| v.as_str()).map(str::to_string),
335        }),
336    )
337        .into_response()
338}
339
340/// `POST /api/v1/ui/click` — backs the `UIClick` MCP tool. Synthesizes a
341/// real mouse click at the first `selector` match within the caller's own
342/// pane subtree.
343pub(crate) async fn handle_ui_click(
344    State(state): State<AppState>,
345    caller: Option<axum::Extension<crate::server::caller::Caller>>,
346    Json(req): Json<UiClickRequest>,
347) -> impl IntoResponse {
348    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
349        Ok(b) => b,
350        Err((code, e)) => return err_response(code, e),
351    };
352    if let Err(resp) = refuse_on_driven_pane(&state, note(&block_id, &req.auth.agent_id, Kind::Click).target(&req.selector), &block_id, "UI's click action", "Browser's snapshot action, then its click action on a ref") {
353        return resp;
354    }
355    let host = match get_host_ipc(&state).await {
356        Ok(h) => h,
357        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
358    };
359
360    let host_resp = match proxy_to_host(
361        &state,
362        &host,
363        "click_element",
364        json!({ "block_id": block_id, "selector": req.selector }),
365    )
366    .await
367    {
368        Ok(v) => v,
369        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
370    };
371    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
372        let err = host_resp
373            .get("error")
374            .and_then(|v| v.as_str())
375            .unwrap_or("unknown host error")
376            .to_string();
377        return err_response(StatusCode::BAD_REQUEST, err);
378    }
379
380    tracing::info!(
381        agent_id = %req.auth.agent_id,
382        block_id = %block_id,
383        selector = %req.selector,
384        "[ui-automation] click"
385    );
386    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
387}
388
389/// `POST /api/v1/ui/query` — backs the `UIQuery` MCP tool. Returns matched
390/// elements (tag/text/attrs/rect/focused) within the caller's own pane
391/// subtree — the same shape `browser_api::types::QueryData` returns.
392pub(crate) async fn handle_ui_query(
393    State(state): State<AppState>,
394    caller: Option<axum::Extension<crate::server::caller::Caller>>,
395    Json(req): Json<UiQueryRequest>,
396) -> impl IntoResponse {
397    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
398        Ok(b) => b,
399        Err((code, e)) => return err_response(code, e),
400    };
401    let host = match get_host_ipc(&state).await {
402        Ok(h) => h,
403        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
404    };
405
406    let host_resp = match proxy_to_host(
407        &state,
408        &host,
409        "query",
410        json!({ "block_id": block_id, "selector": req.selector, "limit": req.limit }),
411    )
412    .await
413    {
414        Ok(v) => v,
415        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
416    };
417    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
418        let err = host_resp
419            .get("error")
420            .and_then(|v| v.as_str())
421            .unwrap_or("unknown host error")
422            .to_string();
423        return err_response(StatusCode::BAD_REQUEST, err);
424    }
425
426    tracing::info!(
427        agent_id = %req.auth.agent_id,
428        block_id = %block_id,
429        selector = %req.selector,
430        "[ui-automation] query"
431    );
432    let data = host_resp.get("data").cloned().unwrap_or(json!({ "matches": [] }));
433    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
434}
435
436/// Proxies `route` with `body` and checks the host's `{ok, ...}` envelope.
437/// Shared by the write-only browser-pane tools (navigate/back/forward/
438/// reload/focus_element/dispatch_key) — they differ only in which
439/// route/body they send, not in how they interpret an ack-only reply.
440pub(crate) async fn proxy_ack(
441    state: &AppState,
442    host: &HostIpc,
443    route: &str,
444    body: serde_json::Value,
445) -> Result<(), Response> {
446    let host_resp = proxy_to_host(state, host, route, body)
447        .await
448        .map_err(|e| err_response(StatusCode::BAD_GATEWAY, e))?;
449    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
450        let err = host_resp
451            .get("error")
452            .and_then(|v| v.as_str())
453            .unwrap_or("unknown host error")
454            .to_string();
455        return Err(err_response(StatusCode::BAD_REQUEST, err));
456    }
457    Ok(())
458}
459
460/// `POST /api/v1/ui/browser/navigate` — backs `BrowserNavigate`. Own pane
461/// only, and only when it's a dedicated browser pane (checked host-side).
462pub(crate) async fn handle_ui_browser_navigate(
463    State(state): State<AppState>,
464    caller: Option<axum::Extension<crate::server::caller::Caller>>,
465    Json(req): Json<UiBrowserNavigateRequest>,
466) -> impl IntoResponse {
467    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
468        Ok(b) => b,
469        Err((code, e)) => return err_response(code, e),
470    };
471    // Off the pane's site list: refused outright, without asking the person.
472    let log = || note(&block_id, &req.auth.agent_id, Kind::Navigate).url(&req.url);
473    if let Some(e) = crate::server::browser_allowlist::refuse_agent_navigation(&banner_for(&block_id).0, &req.url) {
474        return log().fail(&state, StatusCode::FORBIDDEN, e);
475    }
476    let host = match get_host_ipc(&state).await {
477        Ok(h) => h,
478        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
479    };
480    if let Err(resp) = proxy_ack(&state, &host, "navigate", json!({ "block_id": block_id, "url": req.url })).await {
481        return resp;
482    }
483    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, url = %req.url, "[ui-automation] browser navigate");
484    log().record(&state);
485    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
486}
487
488/// `POST /api/v1/ui/browser/back` — backs `BrowserBack`.
489pub(crate) async fn handle_ui_browser_back(
490    State(state): State<AppState>,
491    caller: Option<axum::Extension<crate::server::caller::Caller>>,
492    Json(req): Json<UiBrowserHistoryRequest>,
493) -> impl IntoResponse {
494    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
495        Ok(b) => b,
496        Err((code, e)) => return err_response(code, e),
497    };
498    let host = match get_host_ipc(&state).await {
499        Ok(h) => h,
500        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
501    };
502    if let Err(resp) = proxy_ack(&state, &host, "back", json!({ "block_id": block_id })).await {
503        return resp;
504    }
505    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser back");
506    note(&block_id, &req.auth.agent_id, Kind::Back).record(&state);
507    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
508}
509
510/// `POST /api/v1/ui/browser/forward` — backs `BrowserForward`.
511pub(crate) async fn handle_ui_browser_forward(
512    State(state): State<AppState>,
513    caller: Option<axum::Extension<crate::server::caller::Caller>>,
514    Json(req): Json<UiBrowserHistoryRequest>,
515) -> impl IntoResponse {
516    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
517        Ok(b) => b,
518        Err((code, e)) => return err_response(code, e),
519    };
520    let host = match get_host_ipc(&state).await {
521        Ok(h) => h,
522        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
523    };
524    if let Err(resp) = proxy_ack(&state, &host, "forward", json!({ "block_id": block_id })).await {
525        return resp;
526    }
527    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser forward");
528    note(&block_id, &req.auth.agent_id, Kind::Forward).record(&state);
529    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
530}
531
532/// `POST /api/v1/ui/browser/reload` — backs `BrowserReload`.
533pub(crate) async fn handle_ui_browser_reload(
534    State(state): State<AppState>,
535    caller: Option<axum::Extension<crate::server::caller::Caller>>,
536    Json(req): Json<UiBrowserHistoryRequest>,
537) -> impl IntoResponse {
538    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
539        Ok(b) => b,
540        Err((code, e)) => return err_response(code, e),
541    };
542    let host = match get_host_ipc(&state).await {
543        Ok(h) => h,
544        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
545    };
546    let body = json!({ "block_id": block_id, "ignore_cache": req.ignore_cache.unwrap_or(false) });
547    if let Err(resp) = proxy_ack(&state, &host, "reload", body).await {
548        return resp;
549    }
550    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser reload");
551    note(&block_id, &req.auth.agent_id, Kind::Reload).record(&state);
552    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
553}
554
555/// `POST /api/v1/ui/browser/eval` — backs `BrowserEval`. Returns the
556/// host's `{result, type, exception}` shape verbatim under `data`, same
557/// passthrough pattern `handle_ui_query` uses for `matches`.
558pub(crate) async fn handle_ui_browser_eval(
559    State(state): State<AppState>,
560    caller: Option<axum::Extension<crate::server::caller::Caller>>,
561    Json(req): Json<UiBrowserEvalRequest>,
562) -> impl IntoResponse {
563    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
564        Ok(b) => b,
565        Err((code, e)) => return err_response(code, e),
566    };
567    if let Err(resp) = refuse_on_driven_pane(
568        &state, note(&block_id, &req.auth.agent_id, Kind::Eval), &block_id,
569        "Browser's eval action",
570        "Browser's snapshot action to read the page, and its click, fill, select and check actions to act on it",
571    ) {
572        return resp;
573    }
574    let host = match get_host_ipc(&state).await {
575        Ok(h) => h,
576        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
577    };
578    let host_resp = match proxy_to_host(
579        &state,
580        &host,
581        "eval",
582        json!({
583            "block_id": block_id,
584            "script": req.script,
585            "await_promise": req.await_promise.unwrap_or(false),
586        }),
587    )
588    .await
589    {
590        Ok(v) => v,
591        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
592    };
593    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
594        let err = host_resp
595            .get("error")
596            .and_then(|v| v.as_str())
597            .unwrap_or("unknown host error")
598            .to_string();
599        return err_response(StatusCode::BAD_REQUEST, err);
600    }
601    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser eval");
602    let data = host_resp
603        .get("data")
604        .cloned()
605        .unwrap_or(json!({ "result": null, "type": "undefined", "exception": null }));
606    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
607}
608
609/// `POST /api/v1/ui/browser/dispatch_key` — backs `BrowserDispatchKey`.
610pub(crate) async fn handle_ui_browser_dispatch_key(
611    State(state): State<AppState>,
612    caller: Option<axum::Extension<crate::server::caller::Caller>>,
613    Json(req): Json<UiBrowserDispatchKeyRequest>,
614) -> impl IntoResponse {
615    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
616        Ok(b) => b,
617        Err((code, e)) => return err_response(code, e),
618    };
619    // Enter submits a form and Space presses the focused button: neither
620    // would pass the approval banner, so on a driven pane they're refused.
621    let presses = matches!(req.key.as_deref(), Some("Enter") | Some("NumpadEnter") | Some("Space"))
622        || req.text.as_deref().is_some_and(|t| t.contains('\n') || t.contains('\r'));
623    // The key's name, never the text typed: it can be anything the agent was given.
624    let log = || note(&block_id, &req.auth.agent_id, Kind::Key).target(req.selector.as_deref().unwrap_or("")).detail(req.key.as_deref().unwrap_or("typed text (not logged)"));
625    if presses {
626        // A grant with the Enter and Space power takes the key as the click it is (spec §5).
627        if let Some(resp) = crate::server::browser_press::press_or_refuse(&state, &block_id, &req, log).await {
628            return resp;
629        }
630    }
631    let data = match proxy_value(&state, "dispatch_key", json!({ "block_id": block_id, "selector": req.selector, "text": req.text, "key": req.key }), std::time::Duration::from_secs(20)).await {
632        Ok(d) => d, // on a browser pane, what has focus after the keys
633        Err((code, e)) => return err_response(code, e),
634    };
635    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser dispatch_key");
636    log().record(&state);
637    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
638}
639
640/// `POST /api/v1/ui/browser/focus_element` — backs `BrowserFocusElement`.
641pub(crate) async fn handle_ui_browser_focus_element(
642    State(state): State<AppState>,
643    caller: Option<axum::Extension<crate::server::caller::Caller>>,
644    Json(req): Json<UiBrowserFocusElementRequest>,
645) -> impl IntoResponse {
646    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
647        Ok(b) => b,
648        Err((code, e)) => return err_response(code, e),
649    };
650    let host = match get_host_ipc(&state).await {
651        Ok(h) => h,
652        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
653    };
654    if let Err(resp) = proxy_ack(
655        &state,
656        &host,
657        "focus_element",
658        json!({ "block_id": block_id, "selector": req.selector }),
659    )
660    .await
661    {
662        return resp;
663    }
664    tracing::info!(
665        agent_id = %req.auth.agent_id, block_id = %block_id, selector = %req.selector,
666        "[ui-automation] browser focus_element"
667    );
668    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
669}
670
671/// `POST /api/v1/ui/browser/focus_info` — backs `BrowserFocusInfo`. Returns
672/// the host's `{focused}` shape verbatim under `data`.
673pub(crate) async fn handle_ui_browser_focus_info(
674    State(state): State<AppState>,
675    caller: Option<axum::Extension<crate::server::caller::Caller>>,
676    Json(req): Json<UiBrowserFocusInfoRequest>,
677) -> impl IntoResponse {
678    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
679        Ok(b) => b,
680        Err((code, e)) => return err_response(code, e),
681    };
682    let host = match get_host_ipc(&state).await {
683        Ok(h) => h,
684        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
685    };
686    let host_resp = match proxy_to_host(&state, &host, "focus_info", json!({ "block_id": block_id })).await {
687        Ok(v) => v,
688        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
689    };
690    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
691        let err = host_resp
692            .get("error")
693            .and_then(|v| v.as_str())
694            .unwrap_or("unknown host error")
695            .to_string();
696        return err_response(StatusCode::BAD_REQUEST, err);
697    }
698    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser focus_info");
699    let data = host_resp.get("data").cloned().unwrap_or(json!({ "focused": null }));
700    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
701}
702
703/// `POST /api/v1/ui/browser/open` — backs `OpenBrowser`. Opens a browser pane
704/// below the caller's own pane (or where it asks) and records the caller as its owner, so the
705/// `Browser*`/`UI*` tools accept it as `pane`
706/// (docs/specs/SPEC_AGENT_DRIVEN_BROWSER_PANES_2026_10_07.md §3).
707pub(crate) async fn handle_ui_browser_open(
708    State(state): State<AppState>,
709    caller: Option<axum::Extension<crate::server::caller::Caller>>,
710    grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
711    Json(req): Json<UiBrowserOpenRequest>,
712) -> impl IntoResponse {
713    let own = match crate::server::browser_pause_all::open_block_id(&state, caller.as_deref(), &req.auth) {
714        Ok(b) => b,
715        Err((code, e)) => return err_response(code, e),
716    };
717    let url = req.url.trim();
718    if !(url.starts_with("https://") || url.starts_with("http://")) {
719        return err_response(
720            StatusCode::BAD_REQUEST,
721            format!("Browser's open action takes an http:// or https:// URL, not {url:?}"),
722        );
723    }
724    // With no placement asked for, the browser is a tab of the agent's own pane group (`agent_tab_default`).
725    let split = match req.split.as_deref() {
726        None => None,
727        Some(s @ ("right" | "left" | "up" | "down")) => Some(s),
728        Some(other) => {
729            return err_response(StatusCode::BAD_REQUEST, format!("split must be right, left, up or down, not {other:?}"));
730        }
731    };
732    let allowed = match crate::server::browser_allowlist::list_for_open(req.allowed_origins.as_deref(), url) {
733        Ok(a) => a,
734        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
735    };
736    let mut cmd = crate::backend::rpc_types::CommandPaneOpenData {
737        view: "browser".to_string(),
738        url: Some(url.to_string()),
739        title: req.title.clone(),
740        split_direction: split.map(str::to_string),
741        split_reference_block_id: Some(own.clone()),
742        focus: Some(false),
743        ..Default::default()
744    };
745    // Floating, its size and place, and who opened it (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md).
746    if let Err(e) = crate::server::app_api::floater_place::for_browser(&mut cmd, &req, caller.as_ref().map(|c| &c.0)) {
747        return err_response(StatusCode::BAD_REQUEST, e);
748    }
749    if let Err(e) = crate::server::app_api::floater_place::float_by_setting(&state, &mut cmd, req.floating).await { return err_response(StatusCode::TOO_MANY_REQUESTS, e); }
750    let opener = cmd.opener.clone();
751    crate::server::app_api::agent_tab_default::apply(&state, true, opener.as_deref(), &mut cmd);
752    let mut meta = match crate::server::app_api::pane::build_pane_meta(&cmd) {
753        Ok(m) => m,
754        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
755    };
756    let profile = crate::server::browser_identity::requested_or_own(&state, &req.auth.agent_id, req.profile.as_deref()).await;
757    let opened = (req.auth.agent_id.as_str(), allowed.as_deref(), profile.as_deref(), grant.is_some() || crate::server::browser_identity::in_container(&state, &own));
758    let browsing_as = match crate::server::browser_identity::for_agent_pane(&state, &mut meta, opened) {
759        Ok(b) => b,
760        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
761    };
762    cmd.meta = Some(meta);
763    let already = crate::server::browser_same_site::owned_on_site(&state, &req.auth.agent_id, url).await;
764    let (floating, opener) = (cmd.floating == Some(true), cmd.opener.clone());
765    let result = match crate::server::app_api::open_pane(&state, cmd).await {
766        Ok(r) => r,
767        Err(e) => return err_response(super::http_open::pane_open_error_status(&e), e),
768    };
769    crate::server::browser_allowlist::limit_new_pane(&state, &result.block_id, allowed).await;
770    crate::server::browser_owner::record(&result.block_id, &req.auth.agent_id);
771    crate::server::pane_openers::note_docked(opener.as_deref(), &result, floating);
772    tracing::info!(
773        agent_id = %req.auth.agent_id, own_block = %own, pane = %result.block_id, url = %url, browsing_as = %browsing_as, from_container = grant.is_some(),
774        "[ui-automation] browser open (agent-owned)"
775    );
776    let mut data = crate::server::app_api::floater_place::open_answer(&result, &browsing_as);
777    if let (false, Some(o)) = (already.is_empty(), data.as_object_mut()) {
778        o.insert("already_on_site".to_string(), json!(already));
779    }
780    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
781}
782
783/// Proxy a browser-pane request to the host and pass its `data` through:
784/// the shared tail of the snapshot and act handlers.
785pub(crate) async fn proxy_value(
786    state: &AppState,
787    route: &str,
788    body: serde_json::Value,
789    timeout: std::time::Duration,
790) -> Result<serde_json::Value, (StatusCode, String)> {
791    let host = get_host_ipc(state).await.map_err(|e| (StatusCode::SERVICE_UNAVAILABLE, e))?;
792    // Noted again as the input goes out: a click that waited for the person's approval
793    // opens its popup long after the call resolved its pane (browser_agent_calls.rs).
794    if let Some(pane) = body.get("block_id").and_then(|v| v.as_str()) {
795        crate::server::browser_agent_calls::note(&banner_for(pane).0);
796    }
797    let host_resp = proxy_to_host_timeout(state, &host, route, body, Some(timeout))
798        .await
799        .map_err(|e| (StatusCode::BAD_GATEWAY, e))?;
800    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
801        let err = host_resp
802            .get("error")
803            .and_then(|v| v.as_str())
804            .unwrap_or("unknown host error")
805            .to_string();
806        return Err((StatusCode::BAD_REQUEST, err));
807    }
808    Ok(host_resp.get("data").cloned().unwrap_or(serde_json::Value::Null))
809}
810
811pub(crate) async fn proxy_data(
812    state: &AppState,
813    route: &str,
814    body: serde_json::Value,
815    timeout: std::time::Duration,
816) -> axum::response::Response {
817    match proxy_value(state, route, body, timeout).await {
818        Ok(data) => (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response(),
819        Err((code, e)) => err_response(code, e),
820    }
821}
822
823/// `POST /api/v1/ui/browser/snapshot` — backs `BrowserSnapshot`
824/// (docs/specs/SPEC_AGENT_DRIVEN_BROWSER_PANES_2026_10_07.md §4.1).
825pub(crate) async fn handle_ui_browser_snapshot(
826    State(state): State<AppState>,
827    caller: Option<axum::Extension<crate::server::caller::Caller>>,
828    Json(req): Json<agentmux_common::api_types::UiBrowserSnapshotRequest>,
829) -> impl IntoResponse {
830    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
831        Ok(b) => b,
832        Err((code, e)) => return err_response(code, e),
833    };
834    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser snapshot");
835    let mut data = match proxy_value(
836        &state,
837        "snapshot",
838        json!({ "block_id": block_id, "scope": req.scope, "scope_match": req.scope_match, "max_text": req.max_text, "include_hidden": req.include_hidden }),
839        std::time::Duration::from_secs(30),
840    )
841    .await
842    {
843        Ok(d) => d,
844        Err((code, e)) => return err_response(code, e),
845    };
846    // The popups this page opened, which an agent finds no other way
847    // (SPEC_BROWSER_PANE_POPUPS_ADOPTED_2026_10_08.md §3.4).
848    let popups = popup_listing(&state, &block_id, &req.auth.agent_id);
849    if let Some(obj) = data.as_object_mut() {
850        obj.insert("popups".to_string(), json!(popups));
851    }
852    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
853}
854
855/// `opener`'s open popups for its snapshot: each one's pane id, address, and
856/// whether `agent_id` may drive it (not if the person took it over).
857pub(crate) fn popup_listing(state: &AppState, opener: &str, agent_id: &str) -> Vec<serde_json::Value> {
858    use crate::backend::obj::Block;
859    let load = |id: &str| state.mstore.get::<Block>(id).ok().flatten();
860    crate::server::browser_popup::open_popups(opener, |id| load(id).is_some())
861        .into_iter()
862        .filter_map(|pane| {
863            let block = load(&pane)?;
864            let url = block.meta.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string();
865            let yours = owning_agent(&block, &pane).is_some_and(|a| a.eq_ignore_ascii_case(agent_id));
866            Some(json!({ "pane": pane, "url": url, "yours": yours, "kind": "pane" }))
867        })
868        .chain(crate::server::browser_popup::windows_of(opener).into_iter().map(|(id, w)| {
869            let yours = popup_window_target(state, &id, agent_id).is_ok();
870            json!({ "pane": id, "url": w.url, "yours": yours, "kind": "window" })
871        }))
872        .collect()
873}
874
875/// `POST /api/v1/ui/browser/set_files` — backs `BrowserSetFiles`. Only files
876/// inside the calling agent's own workspace are allowed (spec §5.3): its launch
877/// directory for a host agent, the folder mounted at `/workspace` for a
878/// container agent.
879pub(crate) async fn handle_ui_browser_set_files(
880    State(state): State<AppState>,
881    caller: Option<axum::Extension<crate::server::caller::Caller>>,
882    Json(req): Json<agentmux_common::api_types::UiBrowserSetFilesRequest>,
883) -> impl IntoResponse {
884    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
885        Ok(b) => b,
886        Err((code, e)) => return err_response(code, e),
887    };
888    let own = match verified_block_id(&state, caller.as_deref(), &req.auth) {
889        Ok(b) => b,
890        Err(e) => return err_response(StatusCode::UNAUTHORIZED, e),
891    };
892    if req.chooser {
893        return crate::server::browser_chooser::fill(&state, &block_id, &own, &req.auth.agent_id, req.paths).await;
894    }
895    let files = match crate::server::browser_uploads::files_for_agent(&own, req.paths.clone()).await {
896        Ok(f) => f,
897        Err((code, e)) => return err_response(code, e),
898    };
899    let names: Vec<&str> = files.iter().filter_map(|f| f["name"].as_str()).collect();
900    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, r#ref = %req.ref_, files = ?names, "[ui-automation] browser upload");
901    let log = note(&block_id, &req.auth.agent_id, Kind::Upload).target(&req.ref_).detail(&names.join(", "));
902    let sent = json!({ "block_id": block_id, "ref": req.ref_, "files": files });
903    log.outcome(&state, proxy_value(&state, "set_files", sent, std::time::Duration::from_secs(60)).await)
904}
905
906/// `POST /api/v1/ui/browser/wait_for` — backs `BrowserWaitFor`.
907pub(crate) async fn handle_ui_browser_wait_for(
908    State(state): State<AppState>,
909    caller: Option<axum::Extension<crate::server::caller::Caller>>,
910    Json(req): Json<agentmux_common::api_types::UiBrowserWaitForRequest>,
911) -> impl IntoResponse {
912    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
913        Ok(b) => b,
914        Err((code, e)) => return err_response(code, e),
915    };
916    let timeout_ms = req.timeout_ms.unwrap_or(10_000).clamp(250, 60_000);
917    proxy_data(
918        &state,
919        "wait_for",
920        json!({
921            "block_id": block_id,
922            "text": req.text,
923            "url_contains": req.url_contains,
924            "gone": req.gone,
925            "state": req.state,
926            "timeout_ms": timeout_ms,
927        }),
928        std::time::Duration::from_millis(timeout_ms + 10_000),
929    )
930    .await
931}
932
933/// On a browser pane an agent drives (opened with `OpenBrowser`), refuse the
934/// general-purpose routes that could submit, send or delete without the
935/// approval banner (spec §5.4): arbitrary script, clicks by CSS selector,
936/// and the keys that press buttons. The reference tools do the same work
937/// with the approval check in front of committing clicks.
938/// A refusal goes in the pane's action log as `log`.
939#[allow(clippy::result_large_err)]
940pub(crate) fn refuse_on_driven_pane(state: &AppState, log: Note, block_id: &str, what: &str, instead: &str) -> Result<(), axum::response::Response> {
941    // A popup window has no owner record of its own (it is driven through the
942    // pane that opened it), and it is always driven: the same refusal holds.
943    let on = if crate::server::browser_popup::is_window_id(block_id) {
944        "a popup window"
945    } else if crate::server::browser_owner::owner_of(block_id).is_some() {
946        "a browser pane you opened with Browser's open action"
947    } else {
948        return Ok(());
949    };
950    let msg = format!("{what} isn't allowed on {on}: it could submit a form without the user's approval. Use {instead}.");
951    Err(log.fail(state, StatusCode::FORBIDDEN, msg))
952}
953
954/// A popup pane (`browser:popup_of`) is driven as part of its opener: while
955/// the opener exists, the agent must still own it (the person's Take over on
956/// the opener ends its hold on the popups it opened too), and the opener
957/// must not be waiting on the person (a hand-off there pauses its popups).
958/// A popup whose opener was closed stands on its own.
959fn opener_allows(
960    state: &AppState,
961    block: Option<&crate::backend::obj::Block>,
962    agent_id: &str,
963    pane: &str,
964) -> Result<(), (StatusCode, String)> {
965    // Every pane up the chain, not just the one that opened this popup: a
966    // popup opened by a popup is still driven as part of the pane the chain
967    // started in, so Take over or a hand-off anywhere above stops it.
968    let mut next = block.and_then(popup_of);
969    for _ in 0..POPUP_CHAIN_LIMIT {
970        let Some(opener) = next else {
971            return Ok(());
972        };
973        let Ok(Some(opener_block)) = state.mstore.get::<crate::backend::obj::Block>(&opener) else {
974            // The rest of the chain was closed: from here the popup stands on its own.
975            return Ok(());
976        };
977        if !owning_agent(&opener_block, &opener).is_some_and(|a| a.eq_ignore_ascii_case(agent_id)) {
978            return Err((
979                StatusCode::FORBIDDEN,
980                format!(
981                    "the user took over pane {opener:?}, which opened popup {pane:?} (directly or \
982                     through other popups); open a new pane with Browser's open action if you still need a browser"
983                ),
984            ));
985        }
986        not_waiting_on_user(&opener)?;
987        next = popup_of(&opener_block);
988    }
989    if next.is_none() {
990        return Ok(());
991    }
992    Err((StatusCode::FORBIDDEN, format!("popup {pane:?} is too many popups deep to drive")))
993}
994
995/// How many openers up a popup's chain the checks follow. A chain this deep
996/// is a page opening popups from popups on purpose; driving stops there.
997const POPUP_CHAIN_LIMIT: usize = 8;
998
999/// The pane that opened `block` as a popup pane, if it is one.
1000fn popup_of(block: &crate::backend::obj::Block) -> Option<String> {
1001    block
1002        .meta
1003        .get(crate::server::browser_popup::POPUP_OF_META_KEY)
1004        .and_then(|v| v.as_str())
1005        .filter(|o| !o.is_empty())
1006        .map(str::to_string)
1007}
1008
1009/// The pane a chain of popups started in: `pane` itself unless it is a popup
1010/// pane, else its opener's root, as far up as the panes still exist. Popups
1011/// are counted over its whole tree, so a popup opening popups shares its
1012/// root's cap rather than getting its own.
1013fn chain_root(state: &AppState, pane: &str) -> String {
1014    let mut root = pane.to_string();
1015    for _ in 0..POPUP_CHAIN_LIMIT {
1016        let Some(up) = state.mstore.get::<crate::backend::obj::Block>(&root).ok().flatten().as_ref().and_then(popup_of) else {
1017            break;
1018        };
1019        if !matches!(state.mstore.get::<crate::backend::obj::Block>(&up), Ok(Some(_))) {
1020            break;
1021        }
1022        root = up;
1023    }
1024    root
1025}
1026
1027/// A popup window (a native window a pane's page opened, id `popup-…`) may be
1028/// driven by the agent recorded when it opened, while that agent still owns
1029/// the pane that opened it and that pane isn't waiting on the person
1030/// (SPEC_BROWSER_PANE_NATIVE_POPUPS_AGENT_DRIVEN_2026_10_08.md §5).
1031fn popup_window_target(state: &AppState, id: &str, agent_id: &str) -> Result<String, (StatusCode, String)> {
1032    let Some(w) = crate::server::browser_popup::window(id) else {
1033        return Err((StatusCode::NOT_FOUND, format!("no popup window {id:?} (it may have been closed)")));
1034    };
1035    if !w.owner.as_deref().is_some_and(|o| o.eq_ignore_ascii_case(agent_id)) {
1036        return Err((
1037            StatusCode::FORBIDDEN,
1038            format!(
1039                "popup window {id:?} isn't yours: a popup window belongs to the agent that owned \
1040                 the pane that opened it"
1041            ),
1042        ));
1043    }
1044    let Ok(Some(opener)) = state.mstore.get::<crate::backend::obj::Block>(&w.opener) else {
1045        return Err((StatusCode::NOT_FOUND, format!("the pane that opened popup window {id:?} is gone")));
1046    };
1047    if !owning_agent(&opener, &w.opener).is_some_and(|a| a.eq_ignore_ascii_case(agent_id)) {
1048        return Err((
1049            StatusCode::FORBIDDEN,
1050            format!(
1051                "the user took over pane {:?}, which opened popup window {id:?}; open a new pane \
1052                 with Browser's open action if you still need a browser",
1053                w.opener
1054            ),
1055        ));
1056    }
1057    not_waiting_on_user(&w.opener)?;
1058    // The opener may itself be a popup pane: the whole chain above it counts.
1059    opener_allows(state, Some(&opener), agent_id, id)?;
1060    Ok(id.to_string())
1061}
1062
1063/// Where a request to the person about `target` shows: in its own banner,
1064/// or, for a popup window (which has no AgentMux header), in its opener's,
1065/// with the window's address so the banner can say which window it means.
1066pub(crate) fn banner_for(target: &str) -> (String, Option<String>) {
1067    if crate::server::browser_popup::is_window_id(target) {
1068        if let Some(w) = crate::server::browser_popup::window(target) {
1069            return (w.opener, Some(w.url));
1070        }
1071    }
1072    (target.to_string(), None)
1073}
1074
1075/// Refuse a tool call on a pane that is waiting for the user: a hand-off
1076/// (they're working in it), an approval (they're reading the form the
1077/// approved click will send, which mustn't change under them), or a question.
1078pub(crate) fn not_waiting_on_user(pane: &str) -> Result<(), (StatusCode, String)> {
1079    crate::server::browser_actions::not_paused(pane)?;
1080    match crate::server::browser_attention::waiting_on_user(pane) {
1081        None => Ok(()),
1082        Some(kind) => Err((StatusCode::CONFLICT, crate::server::browser_waiting::paused_text(pane, kind.tools_paused(pane)))),
1083    }
1084}
1085
1086/// `POST /api/v1/ui/browser/handoff` — backs `BrowserHandoff` (spec §5.2):
1087/// a banner in the pane asks the user to do something the agent mustn't
1088/// (sign in, a CAPTCHA), and the call waits for their Done or Cancel. The
1089/// agent's tools on that pane are refused meanwhile (`target_block_id`).
1090pub(crate) async fn handle_ui_browser_handoff(
1091    State(state): State<AppState>,
1092    caller: Option<axum::Extension<crate::server::caller::Caller>>,
1093    Json(req): Json<agentmux_common::api_types::UiBrowserHandoffRequest>,
1094) -> impl IntoResponse {
1095    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
1096        Ok(b) => b,
1097        Err((code, e)) => return err_response(code, e),
1098    };
1099    // A popup window's request shows on its opener's banner.
1100    let (banner_at, in_window) = banner_for(&block_id);
1101    // Only a browser pane shows the banner; anywhere else the request would
1102    // lock the agent's own tools with nothing for the user to click.
1103    let is_browser = state
1104        .mstore
1105        .get::<crate::backend::obj::Block>(&banner_at)
1106        .ok()
1107        .flatten()
1108        .is_some_and(|b| b.meta.get("view").and_then(|v| v.as_str()) == Some("browser"));
1109    if !is_browser {
1110        return err_response(
1111            StatusCode::BAD_REQUEST,
1112            "Browser's handoff action needs a browser pane: pass the `pane` its open action returned".to_string(),
1113        );
1114    }
1115    let reason = match crate::server::browser_handoff_reason::handoff_reason(req.reason.trim()) {
1116        Ok(r) => r,
1117        Err(why) => return err_response(StatusCode::BAD_REQUEST, why),
1118    };
1119    // Only the host relays the user's Done or Cancel (`/api/v1/host/browser_attention`).
1120    // With none connected nobody can answer: refuse now rather than hold the
1121    // agent's tools on this pane until the timeout.
1122    if let Err(e) = crate::server::app_api::connections::host_to_ask_user(&state).await {
1123        return err_response(StatusCode::SERVICE_UNAVAILABLE, e);
1124    }
1125    let minutes = req.timeout_minutes.unwrap_or(15).clamp(1, 60);
1126    let floated = match crate::server::browser_sessions::handoff_float(&state, req.floating, caller.as_ref().and_then(|c| c.0.uid()), &banner_at, in_window.is_some()).await { Ok(f) => f, Err(why) => return err_response(StatusCode::CONFLICT, why) };
1127    let watch = crate::server::browser_attached::Watch::begin(&state, &block_id).await;
1128    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser hand-off");
1129    let raised = match crate::server::browser_attention::raise(
1130        &state,
1131        &banner_at,
1132        &req.auth.agent_id,
1133        crate::server::browser_attention::Kind::Handoff,
1134        json!({ "reason": reason, "window": in_window }),
1135    ) {
1136        Ok(r) => r,
1137        Err(e) => return err_response(e.status(), e.to_string()),
1138    };
1139    let handoff_id = raised.id().to_string();
1140    // If this call ends before the person answers, the hand-off reads as abandoned.
1141    let tracked = crate::server::browser_handoffs::Tracked::start(&handoff_id, &block_id, &req.auth.agent_id);
1142    let (wait, started) = (std::time::Duration::from_secs(minutes * 60), std::time::Instant::now());
1143    // The person's answer if it comes soon; else "waiting", and the agent ends its turn (`browser_waiting`).
1144    let (answer, waiting) = match raised.answer_within(crate::server::browser_waiting::grace()).await {
1145        Ok(answered) => answered,
1146        Err(raised) => {
1147            let who = crate::server::browser_waiting::Handoff { agent: &req.auth.agent_id, block_id: &block_id, banner_at: &banner_at, reason: &reason, watch, float: floated.clone() };
1148            return crate::server::browser_waiting::detach_handoff(&state, who, raised, tracked, wait, started);
1149        }
1150    };
1151    drop(waiting);
1152    let open = started.elapsed();
1153    tracked.finish(crate::server::browser_handoffs::State::of_answer(answer));
1154    note(&block_id, &req.auth.agent_id, Kind::Handoff)
1155        .target(&reason)
1156        .how(How::from_answer(answer))
1157        .detail(&crate::server::browser_handoffs::ended_words(answer.into(), open))
1158        .record(&state);
1159    let done = matches!(answer, crate::server::browser_attention::Answer::Yes | crate::server::browser_attention::Answer::YesAlways | crate::server::browser_attention::Answer::YesAsking);
1160    let attached = if done { Some(watch.sentence(&state, &block_id).await) } else { None };
1161    let answer = match answer {
1162        crate::server::browser_attention::Answer::Yes | crate::server::browser_attention::Answer::YesAlways | crate::server::browser_attention::Answer::YesAsking => "done",
1163        crate::server::browser_attention::Answer::Cancelled => "cancelled",
1164        crate::server::browser_attention::Answer::TimedOut => "timed_out",
1165    };
1166    (StatusCode::OK, Json(json!({ "ok": true, "data": { "answer": answer, "handoff_id": handoff_id, "open_secs": open.as_secs(), "attached": attached, "float": floated } }))).into_response()
1167}
1168
1169/// `POST /api/v1/host/browser_attention` — the user's answer to a hand-off
1170/// or approval banner, relayed by the CEF host. Only the host can call it:
1171/// `X-Host-Token` must be the IPC token the host registered with
1172/// (`host_ipc.Register`), which agents never see; the instance auth key
1173/// alone, which every agent has, isn't enough.
1174pub(crate) async fn handle_host_browser_attention(
1175    State(state): State<AppState>,
1176    headers: axum::http::HeaderMap,
1177    Json(body): Json<serde_json::Value>,
1178) -> impl IntoResponse {
1179    if !from_host(&state, &headers).await {
1180        return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can answer a pane's request".to_string());
1181    }
1182    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
1183    let (block_id, id, decision) = (s("block_id"), s("id"), s("decision"));
1184    if decision == "give_back" {
1185        return crate::server::browser_retake::give_back(&state, &block_id);
1186    }
1187    let Some(answer) = crate::server::browser_attention::Answer::parse(&decision) else {
1188        return err_response(StatusCode::BAD_REQUEST, format!("unknown decision {decision:?}"));
1189    };
1190    match crate::server::browser_attention::resolve(&id, &block_id, answer) {
1191        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))).into_response(),
1192        Err(e) => {
1193            // Nothing waits on that banner any more: take it down.
1194            crate::server::browser_attention::clear_stale(&state, &block_id, &id);
1195            err_response(StatusCode::NOT_FOUND, e)
1196        }
1197    }
1198}
1199
1200/// Is this request from the CEF host? `X-Host-Token` must be the IPC token
1201/// the host registered with (`host_ipc.Register`), which agents never see;
1202/// the instance auth key alone, which every agent has, isn't enough.
1203pub(crate) async fn from_host(state: &AppState, headers: &axum::http::HeaderMap) -> bool {
1204    let presented = headers.get("x-host-token").and_then(|v| v.to_str().ok()).unwrap_or("");
1205    let registered = state.host_ipc.lock().await.clone().map(|h| h.token).unwrap_or_default();
1206    !registered.is_empty()
1207        && !presented.is_empty()
1208        && agentmux_common::secret_eq::secret_eq(presented.as_bytes(), registered.as_bytes())
1209}
1210
1211/// The agent that owns `block_id`, if one does and the person hasn't taken
1212/// the pane over: the same test every `pane` argument passes.
1213pub(crate) fn owning_agent(block: &crate::backend::obj::Block, block_id: &str) -> Option<String> {
1214    let agent = crate::server::browser_owner::owner_of(block_id)?;
1215    crate::server::browser_owner::check(Some(block), Some(agent.as_str()), &agent, block_id)
1216        .ok()
1217        .map(|()| agent)
1218}
1219
1220/// Give the popup pane `popup` to `agent` (the opener's owner, if any), if the
1221/// opener is still that agent's; if the person took it over meanwhile, clear
1222/// the owner `popup` was created with. Returns who drives the popup.
1223fn record_popup_owner(state: &AppState, opener: &str, popup: &str, agent: Option<String>) -> Option<String> {
1224    let agent = agent?;
1225    let still = state
1226        .mstore
1227        .get::<crate::backend::obj::Block>(opener)
1228        .ok()
1229        .flatten()
1230        .and_then(|b| owning_agent(&b, opener))
1231        .is_some_and(|a| a.eq_ignore_ascii_case(&agent));
1232    if still {
1233        crate::server::browser_owner::record(popup, &agent);
1234        return Some(agent);
1235    }
1236    let mut clear = crate::backend::obj::MetaMapType::new();
1237    clear.insert(crate::server::browser_owner::OWNER_META_KEY.to_string(), serde_json::Value::Null);
1238    if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, popup, &clear) {
1239        tracing::warn!(pane = %popup, error = %e, "[browser-popup] couldn't clear the popup's owner");
1240    }
1241    None
1242}
1243
1244/// `POST /api/v1/host/browser_popup` — a browser pane's page opened a popup
1245/// (docs/specs/SPEC_BROWSER_PANE_POPUPS_ADOPTED_2026_10_08.md). Only the host
1246/// calls it, from `on_before_popup`. Answers `{admitted: true, pane}` when
1247/// srv opened the popup as a pane tab (a window: beside its opener), or `{admitted: false,
1248/// reason}`, and the host opens it in the system browser as it always did.
1249pub(crate) async fn handle_host_browser_popup(
1250    State(state): State<AppState>,
1251    headers: axum::http::HeaderMap,
1252    Json(body): Json<serde_json::Value>,
1253) -> impl IntoResponse {
1254    use crate::server::browser_popup as popup;
1255    if !from_host(&state, &headers).await {
1256        return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can report a popup".to_string());
1257    }
1258    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
1259    let (opener, url, opener_url, as_window) = (s("opener"), s("url"), s("opener_url"), s("asked") == "window");
1260    let user_gesture = body.get("user_gesture").and_then(|v| v.as_bool()).unwrap_or(false);
1261    let refused = |reason: &str| {
1262        (StatusCode::OK, Json(json!({ "ok": true, "data": { "admitted": false, "reason": reason } }))).into_response()
1263    };
1264    let block = match state.mstore.get::<crate::backend::obj::Block>(&opener) {
1265        Ok(Some(b)) => b,
1266        Ok(None) => return refused("the pane that opened it is gone"),
1267        Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, format!("load pane {opener:?}: {e}")),
1268    };
1269    if block.meta.get("view").and_then(|v| v.as_str()) != Some("browser") {
1270        return refused("it was not opened by a browser pane");
1271    }
1272    // The opener's owner, if the whole chain above it (when the opener is a
1273    // popup pane itself) is still that agent's: a popup from a popup of a pane
1274    // the person took over belongs to nobody.
1275    let owner = owning_agent(&block, &opener)
1276        .filter(|agent| opener_allows(&state, Some(&block), agent, &opener).is_ok());
1277    // The person's own click, while the agent has been quiet on the pane, opens
1278    // the person's pane: no site limit and no agent (browser_agent_calls.rs).
1279    let by_person = crate::server::browser_agent_calls::person_clicked(&opener, user_gesture);
1280    let drive = owner.clone().filter(|_| !by_person);
1281    if !by_person {
1282        if let Some(why) = crate::server::browser_allowlist::refuse_popup(&opener, &url) { return refused(why); }
1283    }
1284    // The count and the slot are taken together: two popups reported at once
1285    // can't both fit under the cap. The slot is given back if the pane
1286    // doesn't open.
1287    let root = chain_root(&state, &opener);
1288    let reservation = match popup::reserve(
1289        &opener,
1290        &root,
1291        |id| matches!(state.mstore.get::<crate::backend::obj::Block>(id), Ok(Some(_))),
1292        |taken| popup::decide(&url, &opener_url, user_gesture, owner.is_some(), taken),
1293    ) {
1294        Ok(r) => r,
1295        Err(r) => {
1296            tracing::info!(opener = %opener, url = %url, reason = r.reason(), "[browser-popup] not opened as a pane");
1297            return refused(r.reason());
1298        }
1299    };
1300
1301    let mut cmd = crate::backend::rpc_types::CommandPaneOpenData {
1302        view: "browser".to_string(),
1303        file: None,
1304        url: Some(url.clone()),
1305        cwd: None,
1306        title: None,
1307        tab_id: None,
1308        split_direction: as_window.then(|| "right".to_string()),
1309        split_reference_block_id: as_window.then(|| opener.clone()),
1310        // The person clicked: show them the popup. An agent's popup opens
1311        // without taking the person's focus, like OpenBrowser.
1312        focus: Some(drive.is_none()),
1313        tree_expanded: None,
1314        floating: None,
1315        meta: None,
1316        skip_placement: None,
1317        stack_onto_block_id: (!as_window).then(|| opener.clone()),
1318        connection: None,
1319        auth: None,
1320        ..Default::default()
1321    };
1322    let mut meta = match crate::server::app_api::pane::build_pane_meta(&cmd) {
1323        Ok(m) => m,
1324        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
1325    };
1326    popup::mark_popup_meta(&mut meta, &opener, &opener_url);
1327    crate::server::browser_identity::inherit(&mut meta, &block);
1328    // On the new pane from the start, so the host has it before the first load.
1329    let chain = crate::server::browser_allowlist::list_for(&opener).filter(|_| !by_person);
1330    crate::server::browser_allowlist::mirror(&mut meta, chain.as_deref());
1331    if let Some(agent) = &drive {
1332        meta.extend(crate::server::browser_owner::driver_meta(agent));
1333    }
1334    cmd.meta = Some(meta);
1335    let result = match crate::server::app_api::open_pane(&state, cmd).await {
1336        Ok(r) => r,
1337        Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, e),
1338    };
1339    let joined = chain.and_then(|_| crate::server::browser_allowlist::join(&result.block_id, &opener));
1340    // The opener's owner owns its popup, from srv's own record, never from the
1341    // page or a client. Checked again now the pane is open: the person may have
1342    // taken the opener over meanwhile, and then the agent gets neither.
1343    let owner = record_popup_owner(&state, &opener, &result.block_id, drive);
1344    reservation.commit(&result.block_id);
1345    crate::server::browser_allowlist::settle_popup_pane(&state, &result.block_id, joined, owner.is_some()).await;
1346    tracing::info!(
1347        opener = %opener, pane = %result.block_id, url = %url, owner = ?owner,
1348        "[browser-popup] popup opened as a pane"
1349    );
1350    (
1351        StatusCode::OK,
1352        Json(json!({ "ok": true, "data": { "admitted": true, "pane": result.block_id } })),
1353    )
1354        .into_response()
1355}
1356
1357/// `POST /api/v1/host/browser_popup_window` — the host created, navigated
1358/// or closed a popup window (a native window a browser pane's page opened;
1359/// SPEC_BROWSER_PANE_NATIVE_POPUPS_AGENT_DRIVEN_2026_10_08.md §4). Body
1360/// `{event: "opened"|"navigated"|"closed", popup, opener, url}`. Only the
1361/// host can call it. The window's owner is the opener's, from srv's own
1362/// record; the opener's popup-windows strip is kept current.
1363pub(crate) async fn handle_host_browser_popup_window(
1364    State(state): State<AppState>,
1365    headers: axum::http::HeaderMap,
1366    Json(body): Json<serde_json::Value>,
1367) -> impl IntoResponse {
1368    use crate::server::browser_popup as popup;
1369    if !from_host(&state, &headers).await {
1370        return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can report a popup window".to_string());
1371    }
1372    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
1373    let (event, id, opener, url) = (s("event"), s("popup"), s("opener"), s("url"));
1374    if !popup::is_window_id(&id) {
1375        return err_response(StatusCode::BAD_REQUEST, format!("not a popup window id: {id:?}"));
1376    }
1377    let touched = match event.as_str() {
1378        "opened" => {
1379            let block = match state.mstore.get::<crate::backend::obj::Block>(&opener) {
1380                Ok(Some(b)) if b.meta.get("view").and_then(|v| v.as_str()) == Some("browser") => b,
1381                // Not from a browser pane srv knows: nobody drives it.
1382                _ => return (StatusCode::OK, Json(json!({ "ok": true }))).into_response(),
1383            };
1384            let owner = owning_agent(&block, &opener)
1385                .filter(|agent| opener_allows(&state, Some(&block), agent, &opener).is_ok());
1386            tracing::info!(popup = %id, opener = %opener, url = %url, owner = ?owner, "[browser-popup] popup window opened");
1387            popup::window_opened(&id, &opener, &url, owner);
1388            Some(opener)
1389        }
1390        "navigated" => popup::window_navigated(&id, &url),
1391        "closed" => {
1392            tracing::info!(popup = %id, "[browser-popup] popup window closed");
1393            popup::window_closed(&id)
1394        }
1395        other => return err_response(StatusCode::BAD_REQUEST, format!("unknown event {other:?}")),
1396    };
1397    if let Some(opener) = touched {
1398        update_popup_windows_strip(&state, &opener);
1399    }
1400    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
1401}
1402
1403/// Forget every popup window and clear every opener's strip. Called when the
1404/// host registers: after either side restarts, the windows srv knew of are
1405/// gone or no longer known, and the strip, which is saved with the pane, must
1406/// not keep listing them.
1407pub(crate) fn reset_popup_windows(state: &AppState) {
1408    use crate::server::browser_popup as popup;
1409    // The windows opened from this srv's panes (in a test, other srvs share
1410    // the record).
1411    popup::clear_windows(|opener| matches!(state.mstore.get::<crate::backend::obj::Block>(opener), Ok(Some(_))));
1412    let blocks = match state.mstore.get_all::<crate::backend::obj::Block>() {
1413        Ok(b) => b,
1414        Err(e) => {
1415            tracing::warn!(error = %e, "[browser-popup] couldn't list panes to clear popup-window strips");
1416            return;
1417        }
1418    };
1419    for b in blocks.into_iter().filter(|b| b.meta.get(popup::POPUP_WINDOWS_META_KEY).is_some_and(|v| !v.is_null())) {
1420        let mut meta = crate::backend::obj::MetaMapType::new();
1421        meta.insert(popup::POPUP_WINDOWS_META_KEY.to_string(), serde_json::Value::Null);
1422        if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, &b.oid, &meta) {
1423            tracing::debug!(block = %b.oid, error = %e, "[browser-popup] stale popup-window strip not cleared");
1424        }
1425    }
1426}
1427
1428/// Rewrite `opener`'s popup-windows strip (`browser:popup_windows`). The
1429/// opener may be closing; then there's nothing to update.
1430fn update_popup_windows_strip(state: &AppState, opener: &str) {
1431    use crate::server::browser_popup as popup;
1432    let value = popup::strip_value(opener);
1433    let value = if value.as_array().is_some_and(|a| a.is_empty()) { serde_json::Value::Null } else { value };
1434    let mut meta = crate::backend::obj::MetaMapType::new();
1435    meta.insert(popup::POPUP_WINDOWS_META_KEY.to_string(), value);
1436    if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, opener, &meta) {
1437        tracing::debug!(opener = %opener, error = %e, "[browser-popup] popup-windows strip not updated");
1438    }
1439}
1440
1441/// `POST /api/v1/ui/browser/act` — backs `BrowserClick`, `BrowserFill`,
1442/// `BrowserSelect` and `BrowserCheck` (spec §4.2).
1443pub(crate) async fn handle_ui_browser_act(
1444    State(state): State<AppState>,
1445    caller: Option<axum::Extension<crate::server::caller::Caller>>,
1446    Json(req): Json<agentmux_common::api_types::UiBrowserActRequest>,
1447) -> impl IntoResponse {
1448    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
1449        Ok(b) => b,
1450        Err((code, e)) => return err_response(code, e),
1451    };
1452    // The typed text isn't logged: it can be anything the agent was given.
1453    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, action = %req.action, r#ref = %req.ref_, "[ui-automation] browser act");
1454    let log = || Note::act(&block_id, &req);
1455    // `approved` carries what the user was shown: the host checks the form
1456    // still matches it before clicking (the page's own script could have
1457    // changed it while they read the banner).
1458    let body = |approved: Option<&serde_json::Value>| {
1459        json!({
1460            "block_id": block_id,
1461            "ref": req.ref_,
1462            "action": req.action,
1463            "text": req.text,
1464            "option": req.option,
1465            "checked": req.checked,
1466            "approved": approved.is_some(),
1467            "approved_as": approved,
1468            "point": req.point,
1469        })
1470    };
1471    let first = match proxy_value(&state, "act", body(None), std::time::Duration::from_secs(20)).await {
1472        Ok(d) => d,
1473        Err(e) => return log().outcome(&state, Err(e)),
1474    };
1475    // A committing click (submit, send, pay, delete, ...) waits for the
1476    // user's approval in the pane; only their click there lets it through
1477    // (spec §5.4).
1478    let Some(ask) = first.pointer("/after/needs_approval").cloned() else {
1479        // A fill into a secret field says which kind in the Log (never the value).
1480        return log().secret_fill(&first).outcome(&state, Ok(first));
1481    };
1482    // A canvas's question carries its picture, marked with the point (spec §4.4).
1483    let ask = match crate::server::browser_canvas_card::with_card(&first, ask) {
1484        Ok(ask) => ask,
1485        Err(e) => return log().outcome(&state, Err(e)),
1486    };
1487    // Bypass (bypass spec §4.1): the person let this agent click without
1488    // asking on this page's site.
1489    if let Some(resp) =
1490        crate::server::browser_bypass_routes::bypassed_click(&state, &block_id, &req.auth.agent_id, &ask, body(Some(&ask)), "act", log()).await
1491    {
1492        return resp;
1493    }
1494    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser act waits for approval");
1495    crate::server::browser_click_approval::ask_then_click(&state, &block_id, &req.auth.agent_id, "act", &ask, body(Some(&ask)), log).await
1496}
1497
1498#[cfg(test)]
1499#[path = "ui_handlers_tests.rs"]
1500mod tests;