Skip to main content

agent_hub_runtime/core/preview/
automation.rs

1//! Authenticated loopback bridge for agents to operate the same pages as the UI.
2use super::{
3    super::error::AppError,
4    browser::{Action, Browsers},
5};
6use serde::{Deserialize, Serialize};
7use serde_json::{json, Value};
8use std::{
9    io::{Read, Write},
10    net::{TcpListener, TcpStream},
11    path::PathBuf,
12    sync::{
13        atomic::{AtomicBool, AtomicUsize, Ordering},
14        Arc, Weak,
15    },
16    thread::JoinHandle,
17    time::Duration,
18};
19
20#[derive(Serialize, Deserialize)]
21pub struct ControlEndpoint {
22    pub url: String,
23    pub token: String,
24}
25#[derive(Deserialize)]
26#[serde(tag = "kind", rename_all = "snake_case")]
27enum Request {
28    List,
29    Open { url: String, profile: String },
30    OpenFile { path: String },
31    Action { id: String, action: Action },
32    Close { id: String },
33    Reconnect { id: String },
34    Reopen { id: String },
35    Frame { id: String },
36    Downloads,
37    FetchDownload { profile: String, id: String },
38    CancelTransfer { profile: String, id: String },
39    CancelDownload { profile: String, id: String },
40    ForgetDownload { profile: String, id: String },
41}
42pub struct Automation {
43    stop: Arc<AtomicBool>,
44    thread: Option<JoinHandle<()>>,
45    path: PathBuf,
46    token: String,
47}
48/// Product-specific route to the live desktop, independent of shared browser data.
49pub fn control_path() -> PathBuf {
50    crate::core::central_repo::product_home_base_dir().join("preview/control.json")
51}
52
53impl Automation {
54    pub fn start(browsers: Arc<Browsers>) -> Result<Self, AppError> {
55        let path = browsers.root.join("control.json");
56        Self::start_inner(browsers, Weak::new(), path)
57    }
58    pub(super) fn start_for_preview(
59        preview: &Arc<super::Preview>,
60        control_file: PathBuf,
61    ) -> Result<Self, AppError> {
62        Self::start_inner(
63            preview.browsers.clone(),
64            Arc::downgrade(preview),
65            control_file,
66        )
67    }
68    fn start_inner(
69        browsers: Arc<Browsers>,
70        preview: Weak<super::Preview>,
71        path: PathBuf,
72    ) -> Result<Self, AppError> {
73        let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
74        listener.set_nonblocking(true)?;
75        let token = uuid::Uuid::new_v4().to_string();
76        let endpoint = ControlEndpoint {
77            url: format!("http://127.0.0.1:{}", listener.local_addr()?.port()),
78            token: token.clone(),
79        };
80        let control_dir = path.parent().expect("preview control path has a parent");
81        std::fs::create_dir_all(&browsers.root)?;
82        std::fs::create_dir_all(control_dir)?;
83        #[cfg(unix)]
84        {
85            use std::os::unix::fs::PermissionsExt;
86            let private = std::fs::Permissions::from_mode(0o700);
87            std::fs::set_permissions(&browsers.root, private.clone())?;
88            if control_dir != browsers.root {
89                std::fs::set_permissions(control_dir, private)?;
90            }
91        }
92        let mut file = tempfile::NamedTempFile::new_in(control_dir)?;
93        file.write_all(&serde_json::to_vec(&endpoint).map_err(AppError::io)?)?;
94        file.persist(&path)
95            .map_err(|error| AppError::io(error.error))?;
96        let stop = Arc::new(AtomicBool::new(false));
97        let shutdown = stop.clone();
98        let key = token.clone();
99        let count = Arc::new(AtomicUsize::new(0));
100        let thread = std::thread::spawn(move || {
101            while !shutdown.load(Ordering::Relaxed) {
102                match listener.accept() {
103                    Ok((stream, _)) => {
104                        if count.load(Ordering::Relaxed) >= 8 {
105                            drop(stream);
106                            continue;
107                        }
108                        count.fetch_add(1, Ordering::Relaxed);
109                        let browsers = browsers.clone();
110                        let key = key.clone();
111                        let count = count.clone();
112                        let preview = preview.clone();
113                        std::thread::spawn(move || {
114                            let _ = serve(stream, &key, &browsers, &preview);
115                            count.fetch_sub(1, Ordering::Relaxed);
116                        });
117                    }
118                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
119                        std::thread::sleep(Duration::from_millis(20))
120                    }
121                    Err(_) => break,
122                }
123            }
124        });
125        Ok(Self {
126            stop,
127            thread: Some(thread),
128            path,
129            token,
130        })
131    }
132}
133impl Drop for Automation {
134    fn drop(&mut self) {
135        self.stop.store(true, Ordering::Relaxed);
136        if let Some(thread) = self.thread.take() {
137            let _ = thread.join();
138        }
139        if std::fs::read(&self.path)
140            .ok()
141            .and_then(|bytes| serde_json::from_slice::<ControlEndpoint>(&bytes).ok())
142            .is_some_and(|value| value.token == self.token)
143        {
144            let _ = std::fs::remove_file(&self.path);
145        }
146    }
147}
148fn response(stream: &mut TcpStream, status: u16, value: Value) -> std::io::Result<()> {
149    let data = serde_json::to_vec(&value)?;
150    write!(stream,"HTTP/1.1 {status} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",if status==200{"OK"}else{"Error"},data.len())?;
151    stream.write_all(&data)
152}
153fn serve(
154    mut stream: TcpStream,
155    token: &str,
156    browsers: &Arc<Browsers>,
157    preview: &Weak<super::Preview>,
158) -> std::io::Result<()> {
159    stream.set_nonblocking(false)?;
160    stream.set_read_timeout(Some(Duration::from_secs(3)))?;
161    stream.set_write_timeout(Some(Duration::from_secs(5)))?;
162    let mut bytes = Vec::new();
163    let mut buffer = [0; 4096];
164    let header_end = loop {
165        if let Some(index) = bytes.windows(4).position(|item| item == b"\r\n\r\n") {
166            break index + 4;
167        }
168        if bytes.len() > 8192 {
169            return response(
170                &mut stream,
171                431,
172                json!({"ok":false,"error":"Header exceeds limit"}),
173            );
174        }
175        let size = stream.read(&mut buffer)?;
176        if size == 0 {
177            return Ok(());
178        }
179        bytes.extend_from_slice(&buffer[..size]);
180    };
181    let headers = String::from_utf8_lossy(&bytes[..header_end]);
182    if headers.lines().next() != Some("POST / HTTP/1.1") {
183        return response(
184            &mut stream,
185            405,
186            json!({"ok":false,"error":"Only authenticated POST requests are supported"}),
187        );
188    }
189    let authorization = headers.lines().find_map(|line| {
190        line.split_once(':')
191            .filter(|(name, _)| name.eq_ignore_ascii_case("authorization"))
192            .map(|(_, value)| value.trim())
193    });
194    let expected = format!("Bearer {token}");
195    let authenticated = authorization.is_some_and(|value| {
196        value.len() == expected.len()
197            && value
198                .bytes()
199                .zip(expected.bytes())
200                .fold(0u8, |difference, (a, b)| difference | (a ^ b))
201                == 0
202    });
203    if !authenticated {
204        return response(&mut stream, 403, json!({"ok":false,"error":"Unauthorized"}));
205    }
206    let length = headers.lines().find_map(|line| {
207        line.split_once(':')
208            .filter(|(name, _)| name.eq_ignore_ascii_case("content-length"))
209            .and_then(|(_, value)| value.trim().parse::<usize>().ok())
210    });
211    let Some(length) = length.filter(|length| *length <= 2 * 1024 * 1024) else {
212        return response(
213            &mut stream,
214            413,
215            json!({"ok":false,"error":"Body exceeds limit or has no length"}),
216        );
217    };
218    while bytes.len() < header_end + length {
219        let size = stream.read(&mut buffer)?;
220        if size == 0 {
221            return Ok(());
222        }
223        bytes.extend_from_slice(&buffer[..size]);
224    }
225    let request = serde_json::from_slice::<Request>(&bytes[header_end..header_end + length]);
226    let result = match request {
227        Ok(Request::OpenFile { path }) => preview
228            .upgrade()
229            .ok_or_else(|| AppError::not_found("Desktop file opening is unavailable"))
230            .and_then(|preview| preview.queue_external_document(&path))
231            .and_then(|receipt| serde_json::to_value(receipt).map_err(AppError::io)),
232        Ok(Request::FetchDownload { profile, id }) => {
233            browsers.fetch_download(&profile, &id).map(|_| Value::Null)
234        }
235        Ok(Request::CancelTransfer { profile, id }) => {
236            browsers.cancel_transfer(&profile, &id).map(|_| Value::Null)
237        }
238        Ok(Request::Downloads) => browsers
239            .downloads()
240            .and_then(|value| serde_json::to_value(value).map_err(AppError::io)),
241        Ok(Request::CancelDownload { profile, id }) => {
242            browsers.cancel_download(&profile, &id).map(|_| Value::Null)
243        }
244        Ok(Request::ForgetDownload { profile, id }) => {
245            browsers.forget_download(&profile, &id).map(|_| Value::Null)
246        }
247        Ok(Request::List) => browsers
248            .list()
249            .and_then(|value| serde_json::to_value(value).map_err(AppError::io)),
250        Ok(Request::Open { url, profile }) => browsers.create(&profile, &url).map(Value::String),
251        Ok(Request::Action { id, action }) => browsers.action(&id, action),
252        Ok(Request::Reopen { id }) => browsers.reopen(&id).map(|_| Value::Null),
253        Ok(Request::Reconnect { id }) => browsers.reconnect(&id).map(|_| Value::Null),
254        Ok(Request::Close { id }) => browsers.close(&id).map(|_| Value::Null),
255        Ok(Request::Frame { id }) => browsers
256            .frame(&id)
257            .and_then(|value| serde_json::to_value(value).map_err(AppError::io)),
258        Err(error) => Err(AppError::invalid_input(error.to_string())),
259    };
260    match result {
261        Ok(value) => response(&mut stream, 200, json!({"ok":true,"value":value})),
262        Err(error) => response(&mut stream, 400, json!({"ok":false,"error":error})),
263    }
264}
265
266/// Public client boundary shared by the CLI and transport-level acceptance tests.
267pub fn call(endpoint: &ControlEndpoint, body: Value) -> Result<Value, AppError> {
268    let url = super::runtime::validate_endpoint(&endpoint.url)?;
269    let response = reqwest::blocking::Client::builder()
270        .no_proxy()
271        .timeout(Duration::from_secs(25))
272        .build()
273        .map_err(AppError::network)?
274        .post(url)
275        .bearer_auth(&endpoint.token)
276        .json(&body)
277        .send()
278        .map_err(AppError::network)?;
279    let mut bytes = Vec::new();
280    response
281        .take(32 * 1024 * 1024 + 1)
282        .read_to_end(&mut bytes)?;
283    if bytes.len() > 32 * 1024 * 1024 {
284        return Err(AppError::network("Preview response exceeds limit"));
285    }
286    let result: Value = serde_json::from_slice(&bytes).map_err(AppError::network)?;
287    if result["ok"] != true {
288        return Err(AppError::network(
289            result["error"]["message"]
290                .as_str()
291                .or_else(|| result["error"].as_str())
292                .unwrap_or("Preview request failed"),
293        ));
294    }
295    Ok(result["value"].clone())
296}
297#[cfg(test)]
298#[path = "automation/tests.rs"]
299mod tests;