Skip to main content

agentmux_srv/server/
browser_chooser.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The page's file chooser, answered from the agent's workspace
5//! (docs/specs/SPEC_BROWSER_WEB_TERMINAL_TYPING_2026_10_23.md ยง6).
6//!
7//! A pane an agent drives never shows the OS file dialog: the host takes the
8//! chooser the page opens and asks here what to do with it. On a page a grant
9//! with the uploads power covers, the host keeps the chooser for 30 seconds,
10//! and `set_files` with `chooser: true` puts files in it. Everywhere else it is
11//! cancelled at once, as before, and the agent is told to use `set_files` on
12//! the control's own reference.
13//!
14//! The files come through the same door as any upload (`browser_uploads`): only
15//! files in the agent's own workspace, links and `..` resolved, never a
16//! directory, 25 MB in all. The grant lifts no part of that.
17
18use axum::http::StatusCode;
19use axum::response::Response;
20use serde_json::{json, Value};
21
22use super::browser_actions::{note, Kind};
23use super::browser_powers::Power;
24use super::ui_handlers::{banner_for, proxy_value};
25use super::AppState;
26
27/// How long the host keeps a chooser. Said to the agent; the host holds the clock.
28pub(crate) const HELD_SECONDS: u64 = 30;
29
30/// Should the host keep the chooser `agent`'s pane `target` just showed on `page`? Only when the
31/// agent holds the uploads power on that site and the pane isn't paused. A folder chooser never.
32pub(crate) fn holds(state: &AppState, target: &str, agent: &str, page: &str, ask: &str) -> bool {
33    ask != "choose a folder"
34        && !agent.is_empty()
35        && super::browser_actions::not_paused(target).is_ok()
36        && super::browser_press::grant(state, &banner_for(target).0, agent, page, Power::Uploads).is_some()
37}
38
39/// What the agent reads about a chooser the host is keeping.
40pub(crate) fn held_reason() -> String {
41    format!(
42        "AgentMux is keeping the page's file chooser for {HELD_SECONDS} seconds: call Browser set_files with chooser: true and paths (files in your workspace) to fill it. A page shows one chooser at a time, so a control you click that opens another one now shows it only after this is filled or has run out, with its own 30 seconds"
43    )
44}
45
46/// How long the person's notice about a cancelled chooser stays up if they don't dismiss it.
47const NOTICE_SECONDS: u64 = 120;
48
49/// What the pane's notice carries: the kind of chooser the page asked for. The words are the frontend's.
50fn notice_payload(ask: &str) -> Value {
51    json!({ "chooser": ask })
52}
53
54/// The host cancelled a chooser the page opened in a pane the agent drives, and nobody would see why:
55/// put a notice over the pane for the person (nothing waits on it), taken down after a while.
56pub(crate) fn tell_person(state: &AppState, block_id: &str, ask: &str) {
57    use super::browser_attention::{self, Kind};
58    match browser_attention::raise(state, block_id, "", Kind::Notice, notice_payload(ask)) {
59        Ok(raised) => {
60            tokio::spawn(async move {
61                let (_, waiting) = raised.answer(Some(std::time::Duration::from_secs(NOTICE_SECONDS))).await;
62                drop(waiting);
63            });
64        }
65        Err(e) => tracing::info!(pane = %block_id, error = %e, "[browser-chooser] couldn't tell the person a file chooser was cancelled"),
66    }
67}
68
69/// `set_files` with `chooser: true`: the files go into the chooser the page last opened in `block_id`.
70/// `own` is the calling agent's own block, whose workspace the files come from.
71pub(crate) async fn fill(state: &AppState, block_id: &str, own: &str, agent: &str, paths: Vec<String>) -> Response {
72    let log = |names: &str| note(block_id, agent, Kind::Upload).target("the page's file chooser").detail(names);
73    let page = match super::browser_bypass_routes::page_url(state, block_id).await {
74        Ok(p) => p,
75        Err(e) => return log("").fail(state, StatusCode::BAD_GATEWAY, e),
76    };
77    let Some(g) = super::browser_press::grant(state, &banner_for(block_id).0, agent, &page, Power::Uploads) else {
78        return log("").fail(
79            state,
80            StatusCode::FORBIDDEN,
81            "no file chooser was filled: that needs the uploads power on this site, and no grant gives it to you here. Ask for it with request_auto_approve (powers [\"uploads\"]), or use set_files with the ref of the control that opens the chooser".to_string(),
82        );
83    };
84    if let Err((code, e)) = super::browser_actions::not_paused(block_id) {
85        return log("").fail(state, code, e);
86    }
87    let files = match super::browser_uploads::files_for_agent(own, paths).await {
88        Ok(f) => f,
89        Err((code, e)) => return log("").fail(state, code, e),
90    };
91    let names: Vec<&str> = files.iter().filter_map(|f| f["name"].as_str()).collect();
92    tracing::info!(agent_id = %agent, block_id = %block_id, files = ?names, "[ui-automation] browser upload into the page's file chooser");
93    let sent = json!({ "block_id": block_id, "files": files, "allowed_origins": g.origins });
94    let done: Result<Value, _> = proxy_value(state, "chooser_files", sent, std::time::Duration::from_secs(60)).await;
95    log(&names.join(", ")).outcome(state, done)
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn the_person_s_notice_carries_the_kind_of_chooser_for_the_frontend_to_word() {
104        assert_eq!(notice_payload("choose a file"), json!({ "chooser": "choose a file" }));
105        assert_eq!(notice_payload("choose a folder")["chooser"], "choose a folder");
106    }
107
108    #[test]
109    fn the_agent_is_told_how_long_the_chooser_is_kept_and_how_to_fill_it() {
110        let r = held_reason();
111        assert!(r.contains("30 seconds") && r.contains("chooser: true") && r.contains("your workspace"), "{r}");
112    }
113}