diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index f4406b9da..d0c18932c 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -77,6 +77,7 @@ pub fn run() { engine_restart, engine_stop, machines::machines_list, + machines::preview::machines_preview, machines::machines_discover, machines::machines_ask, machines::machines_pair, diff --git a/apps/desktop/src-tauri/src/machines.rs b/apps/desktop/src-tauri/src/machines.rs index 5d0139564..d7e763488 100644 --- a/apps/desktop/src-tauri/src/machines.rs +++ b/apps/desktop/src-tauri/src/machines.rs @@ -16,6 +16,8 @@ //! Names follow docs/terminology.md: a **machine** is a computer, Settings › //! Machines lists them, and the server is what runs on each one. +pub(crate) mod preview; + use crate::engine::EngineEvent; use anyhow::Error; use rustcode_client::machine::{machine_from_pairing, normalize_code, Connector}; diff --git a/apps/desktop/src-tauri/src/machines/preview.rs b/apps/desktop/src-tauri/src/machines/preview.rs new file mode 100644 index 000000000..3f2fefb52 --- /dev/null +++ b/apps/desktop/src-tauri/src/machines/preview.rs @@ -0,0 +1,282 @@ +//! A browser-facing loopback listener. Each accepted socket gets its own +//! authenticated ACP channel so preview traffic cannot delay chat requests. + +use super::{config_dir, Machines}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use rustcode_client::{AcpChannel, MachineRegistry}; +use serde_json::{json, Value}; +use std::{future::Future, sync::Arc, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + task::JoinSet, + time::{timeout, Instant}, +}; + +const METHOD: &str = "_rustcode/preview/connection"; +const CHUNK: usize = 32 * 1024; + +#[tauri::command] +pub async fn machines_preview( + machines: tauri::State<'_, Arc>, + host: String, + session_id: String, + port: u16, +) -> Result { + if port == 0 { + return Err("Choose a valid preview port.".into()); + } + let config = config_dir()?; + let machine = MachineRegistry::load(&config) + .map_err(super::chain)? + .get(&host) + .cloned() + .ok_or_else(|| "This machine is no longer paired.".to_owned())?; + let tokens = machines.inner().tokens(&config).await?; + let connector = Arc::new(Machines::connector(&config)?); + let machine = Arc::new(machine); + let session_id = Arc::new(session_id); + + let first = connector + .connect_raced(&machine, &tokens) + .await + .map_err(super::chain)?; + let mut first = first.session.acp().await.map_err(super::chain)?; + let id = open(&mut first, &session_id, port) + .await + .map_err(super::chain)?; + let _ = first + .request(3, METHOD, json!({"action": "close", "id": id})) + .await; + + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) + .await + .map_err(|error| error.to_string())?; + let address = listener + .local_addr() + .map_err(|error| error.to_string())? + .to_string(); + let expected_host = address.clone(); + tauri::async_runtime::spawn(async move { + let until = Instant::now() + Duration::from_secs(60 * 60); + let mut tasks = JoinSet::new(); + let mut first = Some(first); + while let Ok(Ok((socket, _))) = tokio::time::timeout_at(until, listener.accept()).await { + while tasks.try_join_next().is_some() {} + if tasks.len() >= 32 { + continue; + } + let connector = Arc::clone(&connector); + let tokens = Arc::clone(&tokens); + let machine = Arc::clone(&machine); + let session_id = Arc::clone(&session_id); + let expected_host = expected_host.clone(); + let first = first.take(); + tasks.spawn(async move { + let _ = serve(socket, first, &expected_host, &session_id, port, async { + connector + .connect_raced(&machine, &tokens) + .await? + .session + .acp() + .await + }) + .await; + }); + } + }); + Ok(format!("http://{address}/")) +} + +async fn open(channel: &mut AcpChannel, session_id: &str, port: u16) -> anyhow::Result { + channel + .request(1, "initialize", json!({"protocolVersion": 1})) + .await?; + let response = channel + .request( + 2, + METHOD, + json!({ + "action": "open", "sessionId": session_id, "port": port, + }), + ) + .await?; + response["result"]["id"] + .as_str() + .map(str::to_owned) + .ok_or_else(|| anyhow::anyhow!("The machine did not return a preview connection.")) +} + +async fn serve( + mut socket: TcpStream, + first: Option, + expected_host: &str, + session_id: &str, + port: u16, + connect: impl Future>, +) -> anyhow::Result<()> { + let mut request = Vec::with_capacity(CHUNK); + let mut buffer = vec![0; CHUNK]; + let header_end = timeout(Duration::from_secs(5), async { + loop { + let n = socket.read(&mut buffer).await?; + anyhow::ensure!(n > 0, "Browser disconnected"); + request.extend_from_slice(&buffer[..n]); + if let Some(end) = request.windows(4).position(|chunk| chunk == b"\r\n\r\n") { + return Ok::<_, anyhow::Error>(end); + } + anyhow::ensure!( + request.len() < CHUNK, + "Preview request headers are too large" + ); + } + }) + .await??; + let header = std::str::from_utf8(&request[..header_end])?; + if !allowed_request(header, expected_host) { + socket + .write_all(b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n") + .await?; + return Ok(()); + } + let initialized = first.is_some(); + let mut channel = match first { + Some(channel) => channel, + None => connect.await?, + }; + let id = if initialized { + stream_id( + &channel + .request( + 4, + METHOD, + json!({ + "action": "open", "sessionId": session_id, "port": port, + }), + ) + .await?, + )? + } else { + open(&mut channel, session_id, port).await? + }; + let result = relay(&mut channel, &id, &mut socket, &request).await; + let _ = channel + .request(u64::MAX / 2, METHOD, json!({"action": "close", "id": id})) + .await; + result +} + +fn stream_id(response: &Value) -> anyhow::Result { + response["result"]["id"] + .as_str() + .map(str::to_owned) + .ok_or_else(|| anyhow::anyhow!("The machine did not open the preview stream.")) +} + +fn allowed_request(header: &str, host: &str) -> bool { + let mut lines = header.split("\r\n"); + if !lines.next().is_some_and(|line| { + line.split_whitespace() + .nth(1) + .is_some_and(|target| target.starts_with('/') && !target.starts_with("//")) + }) { + return false; + } + let mut hosts = 0; + for line in lines { + let Some((name, value)) = line.split_once(':') else { + return false; + }; + if name.is_empty() || name.bytes().any(|byte| byte.is_ascii_whitespace()) { + return false; + } + let value = value.trim(); + if name.eq_ignore_ascii_case("host") { + if value != host { + return false; + } + hosts += 1; + } + if name.eq_ignore_ascii_case("origin") && value.strip_prefix("http://") != Some(host) { + return false; + } + if name.eq_ignore_ascii_case("sec-fetch-site") && !matches!(value, "none" | "same-origin") { + return false; + } + } + hosts == 1 +} + +async fn relay( + channel: &mut AcpChannel, + id: &str, + socket: &mut TcpStream, + initial: &[u8], +) -> anyhow::Result<()> { + let mut buffer = vec![0; CHUNK]; + let mut next_id = 5_u64; + let mut initial = initial.chunks(CHUNK); + let mut browser_eof = false; + loop { + let (data, eof) = if let Some(chunk) = initial.next() { + (chunk, false) + } else if browser_eof { + (&[][..], false) + } else { + match timeout(Duration::from_millis(5), socket.read(&mut buffer)).await { + Ok(Ok(0)) => { + browser_eof = true; + (&[][..], true) + } + Ok(Ok(n)) => (&buffer[..n], false), + Ok(Err(error)) => return Err(error.into()), + Err(_) => (&[][..], false), + } + }; + let response = channel + .request( + next_id, + METHOD, + json!({ + "action": "exchange", "id": id, "data": STANDARD.encode(data), "eof": eof, + }), + ) + .await?; + next_id += 1; + let response = &response["result"]; + let body = response["data"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("Preview response omitted data"))?; + socket.write_all(&STANDARD.decode(body)?).await?; + if response["eof"] == true { + return Ok(()); + } + } +} + +#[cfg(test)] +mod tests { + use super::allowed_request; + + #[test] + fn loopback_listener_rejects_foreign_hosts_and_origins() { + let host = "127.0.0.1:41000"; + assert!(allowed_request( + "GET / HTTP/1.1\r\nHost: 127.0.0.1:41000\r\nSec-Fetch-Site: none", + host, + )); + assert!(allowed_request( + "GET / HTTP/1.1\r\nHost: 127.0.0.1:41000\r\nOrigin: http://127.0.0.1:41000", + host, + )); + for bad in [ + "Host: example.test", + "Host: 127.0.0.1:41000\r\nHost: example.test", + "Host: 127.0.0.1:41000\r\nHost : example.test", + "Host: 127.0.0.1:41000\r\nOrigin: https://example.test", + "Host: 127.0.0.1:41000\r\nSec-Fetch-Site: cross-site", + ] { + assert!(!allowed_request(&format!("GET / HTTP/1.1\r\n{bad}"), host)); + } + } +} diff --git a/apps/desktop/src/ui/ChatView.tsx b/apps/desktop/src/ui/ChatView.tsx index e78f5cbbb..c5f27cef8 100644 --- a/apps/desktop/src/ui/ChatView.tsx +++ b/apps/desktop/src/ui/ChatView.tsx @@ -70,6 +70,7 @@ import { RightPanel } from "./RightPanel"; import { RollingNumber } from "./RollingNumber"; import { UserRow } from "./Rows"; import { useThreadStatus } from "./Status"; +import { ThreadPreview } from "./ThreadPreview"; import { ThreadTitle } from "./ThreadTitle"; import { FIRST_ROW_PAD, Transcript } from "./Transcript"; @@ -232,7 +233,7 @@ function Header({ } - right={right.length ? right : undefined} + right={thread ? [, ...right] : right} /> ); } diff --git a/apps/desktop/src/ui/ThreadPreview.tsx b/apps/desktop/src/ui/ThreadPreview.tsx new file mode 100644 index 000000000..147320469 --- /dev/null +++ b/apps/desktop/src/ui/ThreadPreview.tsx @@ -0,0 +1,219 @@ +import { Dialog } from "radix-ui"; +import { useEffect, useState } from "react"; +import { isTauri } from "../acp/transport"; +import { openExternal } from "../lib/native"; +import { shellCall } from "../lib/shell"; +import { errorText, toast, useApp } from "../state/store"; +import { splitThreadKey } from "../state/threadKeys"; +import { connectionFor, connectionForThread } from "../state/threadMachines"; + +const SHARE_METHOD = "_rustcode/preview/share"; +const action = "rounded-md bg-fill px-3 py-1.5 text-callout hover:bg-fill-strong disabled:opacity-50"; + +interface Link { + id: string; + url: string; + port: number; + expiresAt: string; +} + +type MachineLink = Link & { host: string }; + +export function ThreadPreview({ threadId }: { threadId: string }) { + const [open, setOpen] = useState(false); + return ( + + + Preview + + {open && } + + ); +} + +function PreviewDialog({ threadId }: { threadId: string }) { + const [port, setPort] = useState(""); + const [confirm, setConfirm] = useState(false); + const [busy, setBusy] = useState(false); + const [links, setLinks] = useState([]); + const [error, setError] = useState(""); + const { host, id: sessionId } = splitThreadKey(threadId); + const value = Number(port); + const validPort = /^[0-9]+$/.test(port) && value > 0 && value <= 65535; + const privateAvailable = isTauri(); + const hosts = useApp((state) => state.connectedHosts); + const names = useApp((state) => state.machineNames); + + useEffect(() => { + let closed = false; + const refresh = async () => { + const results = await Promise.allSettled( + ["", ...hosts].map(async (machine) => { + const connection = connectionFor(machine); + if (!connection) return []; + const result = await connection.request<{ links: Link[] }>( + SHARE_METHOD, + { action: "list" }, + 10_000, + ); + return result.links.map((link) => ({ ...link, host: machine })); + }), + ); + if (closed) return; + setLinks(results.flatMap((result) => (result.status === "fulfilled" ? result.value : []))); + }; + void refresh(); + const timer = setInterval(() => void refresh(), 5_000); + return () => { + closed = true; + clearInterval(timer); + }; + }, [hosts]); + + async function perform(work: () => Promise) { + setBusy(true); + setError(""); + try { + await work(); + } catch (reason) { + setError(errorText(reason)); + } finally { + setBusy(false); + } + } + + function openPrivate() { + void perform(async () => { + const url = host + ? await shellCall("machines_preview", { host, sessionId, port: value }) + : `http://127.0.0.1:${value}/`; + openExternal(url); + }); + } + + function share() { + setConfirm(false); + void perform(async () => { + const connection = connectionForThread(threadId); + if (!connection) throw new Error("The thread’s machine is offline."); + const link = await connection.request( + SHARE_METHOD, + { action: "start", sessionId, port: value, approved: true }, + 35_000, + ); + setLinks((current) => [...current.filter((entry) => entry.id !== link.id), { ...link, host }]); + }); + } + + function stop({ id, host }: MachineLink) { + void perform(async () => { + const connection = connectionFor(host); + if (!connection) throw new Error("The thread’s machine is offline."); + await connection.request(SHARE_METHOD, { action: "stop", id }, 5_000); + setLinks((current) => current.filter((entry) => entry.id !== id)); + }); + } + + return ( + + +
+ +
+ Preview + Close +
+ + Enter the port of the HTTP server running on this thread’s machine. + + +
+ {privateAvailable && ( + + )} + +
+ {confirm && ( +
+

+ Anyone with the link can access port {value} for one hour. Dev servers can expose source + files. Serve a static build if you only want to share build output. +

+
+ + +
+
+ )} + {error && ( +

+ {error} +

+ )} +
+

Active public links

+ {links.length === 0 &&

No active links

} + {links.map((link) => ( +
+ +

+ {link.host ? (names[link.host] ?? link.host) : "This computer"} · Port {link.port} · Expires{" "} + {new Date(link.expiresAt).toLocaleTimeString()} +

+
+ + +
+
+ ))} +
+
+
+
+ ); +} diff --git a/docs/preview.md b/docs/preview.md index d0d43d1a7..c25a9e5f5 100644 --- a/docs/preview.md +++ b/docs/preview.md @@ -155,3 +155,30 @@ the full app under Instruments for hours; the test window is not frontmost, so WebKit may already treat the "visible" page as occluded (CPU barely moves in either state); and it has no WebSocket/HMR server. Sustained use in the app itself remains to be checked. + +## Open a thread's preview from another desktop + +Start the app's HTTP server on the machine where the thread runs. In RustCode +desktop, open that thread, choose **Preview**, enter the server's IPv4 +loopback port and choose **Open privately**. A local thread opens its local +server directly. For a paired machine, RustCode opens a browser URL on this +computer's loopback and relays traffic over the saved machine's authenticated +gateway connection. It forwards HTTP and WebSocket traffic. The listener +expires after an hour or when you quit RustCode. The remote server has to be +reachable on `127.0.0.1`. + +## Share a public link + +In the same dialog, choose **Share preview** and confirm **Create public +link**. An agent can call `share_preview` with the port and RustCode shows a +one-time approval card naming the port and what will be exposed. The machine +running the server needs `cloudflared` in the engine's PATH. RustCode starts a +[Cloudflare Quick Tunnel](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/) +and presents the resulting link and its expiry. The tunnel uses the loopback +Host header so Vite accepts the request. + +Anyone with the link can reach the server. A dev server may expose source +files and development endpoints. Where possible, serve a static build from +its own loopback port and share that port. The preview dialog lists public +links with **Copy link** and **Stop**. Links expire after one hour and stop +when their thread is settled or the engine managing the tunnel exits. diff --git a/rustcode/engine/src/acp.rs b/rustcode/engine/src/acp.rs index 23efa2e08..b83de0fce 100644 --- a/rustcode/engine/src/acp.rs +++ b/rustcode/engine/src/acp.rs @@ -22,6 +22,8 @@ pub(crate) mod outside; mod permissions; mod presence; mod preview; +mod preview_connection; +pub(crate) mod preview_share; mod project_relocate; pub(crate) mod projects; mod prompt; @@ -1727,6 +1729,9 @@ async fn dispatch_request( .respond_with_error(agent_client_protocol::Error::invalid_params().data(error)), } } + "_rustcode/preview/share" | "_rustcode/preview/connection" => { + connection.spawn(preview_share::dispatch(method, params, responder)) + } "_rustcode/machine/exec" => { let request: machine_exec::MachineExecRequest = parse_params(params)?; diff --git a/rustcode/engine/src/acp/preview_connection.rs b/rustcode/engine/src/acp/preview_connection.rs new file mode 100644 index 000000000..91c9e2db7 --- /dev/null +++ b/rustcode/engine/src/acp/preview_connection.rs @@ -0,0 +1,120 @@ +//! A paired client relays a browser connection in bounded chunks over ACP. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::Duration; + +use base64::{Engine, engine::general_purpose::STANDARD}; +use serde::Deserialize; +use serde_json::{Value, json}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::time::{Instant, timeout}; + +const CHUNK: usize = 32 * 1024; +const IDLE: Duration = Duration::from_secs(15); + +struct Stream { + session_id: String, + socket: tokio::sync::Mutex, + used: Mutex, +} + +static STREAMS: LazyLock>>> = LazyLock::new(Default::default); + +#[derive(Deserialize)] +#[serde( + tag = "action", + rename_all = "camelCase", + rename_all_fields = "camelCase" +)] +pub(super) enum Request { + Open { session_id: String, port: u16 }, + Exchange { id: String, data: String, eof: bool }, + Close { id: String }, +} + +pub(super) async fn handle(request: Request) -> Result { + match request { + Request::Open { session_id, port } => { + super::preview_share::validate(&session_id, port)?; + let socket = timeout( + Duration::from_secs(3), + TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, port)), + ) + .await + .map_err(|_| "The preview server did not answer.".to_owned())? + .map_err(|error| format!("Could not connect to preview port {port}: {error}"))?; + let mut streams = STREAMS.lock().unwrap(); + if streams.len() >= 64 { + return Err("Too many active preview connections.".to_owned()); + } + let id = uuid::Uuid::new_v4().to_string(); + let stream = Arc::new(Stream { + session_id, + socket: tokio::sync::Mutex::new(socket), + used: Mutex::new(Instant::now()), + }); + streams.insert(id.clone(), Arc::clone(&stream)); + let key = id.clone(); + tokio::spawn(async move { + loop { + tokio::time::sleep(IDLE).await; + let mut streams = STREAMS.lock().unwrap(); + if !streams.contains_key(&key) { + break; + } + if stream.used.lock().unwrap().elapsed() >= IDLE { + streams.remove(&key); + break; + } + } + }); + Ok(json!({"id": id})) + } + Request::Close { id } => { + STREAMS.lock().unwrap().remove(&id); + Ok(json!({})) + } + Request::Exchange { id, data, eof } => { + if data.len() > CHUNK.div_ceil(3) * 4 { + return Err("Preview data chunk is too large.".to_owned()); + } + let data = STANDARD.decode(data).map_err(|error| error.to_string())?; + if data.len() > CHUNK { + return Err("Preview data chunk is too large.".to_owned()); + } + let stream = STREAMS + .lock() + .unwrap() + .get(&id) + .cloned() + .ok_or_else(|| "The preview connection ended.".to_owned())?; + if crate::thread_status::is_settled(&stream.session_id) { + STREAMS.lock().unwrap().remove(&id); + return Err("The preview thread is settled.".to_owned()); + } + *stream.used.lock().unwrap() = Instant::now(); + let mut socket = stream + .socket + .try_lock() + .map_err(|_| "Preview transfer already in progress.".to_owned())?; + timeout(Duration::from_secs(3), async { + socket.write_all(&data).await?; + if eof { + socket.shutdown().await?; + } + Ok::<_, std::io::Error>(()) + }) + .await + .map_err(|_| "Preview write timed out.".to_owned())? + .map_err(|error| error.to_string())?; + let mut buffer = vec![0; CHUNK]; + match timeout(Duration::from_millis(200), socket.read(&mut buffer)).await { + Ok(Ok(n)) => Ok(json!({"data": STANDARD.encode(&buffer[..n]), "eof": n == 0})), + Ok(Err(error)) => Err(error.to_string()), + Err(_) => Ok(json!({"data": "", "eof": false})), + } + } + } +} diff --git a/rustcode/engine/src/acp/preview_share.rs b/rustcode/engine/src/acp/preview_share.rs new file mode 100644 index 000000000..26c6727b2 --- /dev/null +++ b/rustcode/engine/src/acp/preview_share.rs @@ -0,0 +1,338 @@ +//! Temporary public links to explicitly selected loopback HTTP servers. + +use std::collections::HashMap; +use std::process::Stdio; +use std::sync::{LazyLock, Mutex}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::Command; +use tokio_util::sync::CancellationToken; + +const LIFETIME_MINUTES: i64 = 60; + +#[derive(Deserialize)] +#[serde( + tag = "action", + rename_all = "camelCase", + rename_all_fields = "camelCase" +)] +pub(super) enum Request { + List, + Start { + session_id: String, + port: u16, + approved: bool, + }, + Stop { + id: String, + }, +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct Link { + id: String, + session_id: String, + port: u16, + url: String, + expires_at: chrono::DateTime, +} + +struct Share { + link: Link, + cancel: CancellationToken, +} + +static SHARES: LazyLock>> = LazyLock::new(Default::default); + +pub(super) async fn handle(request: Request) -> Result { + match request { + Request::List => { + let shares = SHARES.lock().unwrap(); + let mut links: Vec<_> = shares + .values() + .filter(|share| !share.cancel.is_cancelled()) + .map(|share| &share.link) + .filter(|link| !link.url.is_empty()) + .collect(); + links.sort_by_key(|link| link.expires_at); + Ok(json!({"links": links})) + } + Request::Stop { id } => { + if let Some(share) = SHARES.lock().unwrap().get(&id) { + share.cancel.cancel(); + } + Ok(json!({})) + } + Request::Start { + session_id, + port, + approved, + } => { + if !approved { + return Err("Confirm public access for this preview first.".to_owned()); + } + start(session_id, port).await + } + } +} + +pub(super) fn validate(session_id: &str, port: u16) -> Result<(), String> { + if port == 0 + || !rustcode_session::valid_session_id(session_id) + || !crate::sessions::get_active_session_dir(session_id).is_some_and(|dir| dir.is_dir()) + || crate::thread_status::is_settled(session_id) + { + return Err("Choose an active thread and a valid local port.".to_owned()); + } + Ok(()) +} + +async fn start(session_id: String, port: u16) -> Result { + validate(&session_id, port)?; + + let address = format!("127.0.0.1:{port}"); + tokio::time::timeout( + Duration::from_secs(3), + tokio::net::TcpStream::connect(&address), + ) + .await + .map_err(|_| format!("Timed out connecting to {address}."))? + .map_err(|error| format!("Could not connect to {address}: {error}"))?; + + let id = uuid::Uuid::new_v4().to_string(); + let cancel = CancellationToken::new(); + let expires_at = chrono::Utc::now() + chrono::Duration::minutes(LIFETIME_MINUTES); + { + let mut shares = SHARES.lock().unwrap(); + if shares.len() >= 8 { + return Err("Stop an existing preview link before starting another.".to_owned()); + } + shares.insert( + id.clone(), + Share { + link: Link { + id: id.clone(), + session_id: session_id.clone(), + port, + url: String::new(), + expires_at, + }, + cancel: cancel.clone(), + }, + ); + } + let (ready, result) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + let outcome = run(&id, &session_id, &address, cancel, ready).await; + SHARES.lock().unwrap().remove(&id); + if let Err(error) = outcome { + crate::dbg_log!("preview tunnel stopped: {error}"); + } + }); + result + .await + .map_err(|_| "The preview tunnel stopped before it returned a URL.".to_owned())? +} + +async fn run( + id: &str, + session_id: &str, + address: &str, + cancel: CancellationToken, + ready: tokio::sync::oneshot::Sender>, +) -> Result<(), String> { + let config = match tempfile::NamedTempFile::new().and_then(|mut file| { + std::io::Write::write_all(&mut file, b"{}\n")?; + Ok(file) + }) { + Ok(config) => config, + Err(error) => { + let _ = ready.send(Err(format!( + "Could not prepare the preview tunnel: {error}" + ))); + return Ok(()); + } + }; + let mut command = Command::new("cloudflared"); + for (key, _) in std::env::vars_os() { + let name = key.to_string_lossy().to_ascii_uppercase(); + if name.starts_with("TUNNEL_") || name.starts_with("CLOUDFLARED_") { + command.env_remove(key); + } + } + let child = command + .args(["tunnel", "--config"]) + .arg(config.path()) + .args([ + "--no-autoupdate", + "--url", + &format!("http://{address}"), + "--http-host-header", + address, + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn(); + let mut child = match child { + Ok(child) => child, + Err(error) => { + let _ = ready.send(Err(format!("Could not start cloudflared: {error}"))); + return Ok(()); + } + }; + let mut lines = BufReader::new(child.stderr.take().expect("piped stderr")).lines(); + let mut ready = Some(ready); + let startup = tokio::time::sleep(Duration::from_secs(25)); + let expiry = tokio::time::sleep(Duration::from_secs((LIFETIME_MINUTES * 60) as u64)); + tokio::pin!(startup, expiry); + let mut status = tokio::time::interval(Duration::from_secs(1)); + loop { + tokio::select! { + _ = cancel.cancelled() => break, + _ = &mut expiry => break, + _ = &mut startup, if ready.is_some() => { + if let Some(ready) = ready.take() { + let _ = ready.send(Err("Cloudflare did not return a preview URL in time.".to_owned())); + } + break; + } + _ = status.tick() => { + if crate::thread_status::is_settled(session_id) { + break; + } + } + line = lines.next_line() => { + let Some(line) = line.map_err(|error| error.to_string())? else { break }; + if ready.is_some() && let Some(url) = tunnel_url(&line) { + let result = { + let mut shares = SHARES.lock().unwrap(); + let share = shares.get_mut(id).expect("share is removed after its task exits"); + share.link.url = url.to_owned(); + json!(share.link) + }; + if ready.take().expect("sender checked above").send(Ok(result)).is_err() { + break; + } + } + } + } + } + let _ = child.kill().await; + Ok(()) +} + +fn tunnel_url(line: &str) -> Option<&str> { + line.split_whitespace().find(|word| { + word.strip_prefix("https://") + .and_then(|host| host.strip_suffix(".trycloudflare.com")) + .is_some_and(|label| { + !label.is_empty() + && label + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }) + }) +} + +pub(crate) const TOOL_NAME: &str = "share_preview"; + +pub(crate) fn schema() -> Value { + json!({ + "type": "object", + "properties": { + "port": { "type": "integer", "minimum": 1, "maximum": 65535, + "description": "Loopback HTTP port on this thread's machine. Prefer a static build server." } + }, + "required": ["port"], + "additionalProperties": false + }) +} + +pub(crate) async fn answer( + session_id: &str, + args: &Value, + asker: Option, + cancel: &CancellationToken, +) -> Result { + let port = args["port"] + .as_u64() + .and_then(|port| u16::try_from(port).ok()) + .ok_or_else(|| "Choose a valid preview port.".to_owned())?; + validate(session_id, port)?; + let asker = + asker.ok_or_else(|| "Open this thread in RustCode to approve sharing.".to_owned())?; + let title = format!( + "Share port {port} publicly for one hour? Anyone with the link can open it. Dev servers can expose source files." + ); + if !crate::manage::approved(&asker, session_id, &title, args, cancel).await { + return Err("Public preview sharing was declined.".to_owned()); + } + if cancel.is_cancelled() { + return Err("Public preview sharing was cancelled.".to_owned()); + } + tokio::select! { + biased; + _ = cancel.cancelled() => Err("Public preview sharing was cancelled.".to_owned()), + result = start(session_id.to_owned(), port) => result, + } +} + +pub(crate) async fn execute( + state: &std::sync::Arc>, + args: &Value, + cancel: &CancellationToken, +) -> rustcode_tools::ToolExecutionOutput { + let (session_id, asker) = { + let state = state.lock().await; + (state.active_session_id.clone(), state.secret_asker.clone()) + }; + match answer(&session_id, args, asker, cancel).await { + Ok(value) => rustcode_tools::ToolExecutionOutput::success(value.to_string()), + Err(error) => rustcode_tools::ToolExecutionOutput::failure(error), + } +} + +pub(super) async fn dispatch( + method: String, + params: Value, + responder: agent_client_protocol::Responder, +) -> Result<(), agent_client_protocol::Error> { + let outcome = if method == "_rustcode/preview/share" { + handle(super::parse_params(params)?).await + } else { + super::preview_connection::handle(super::parse_params(params)?).await + }; + match outcome { + Ok(answer) => responder.respond(answer), + Err(error) => { + responder.respond_with_error(agent_client_protocol::Error::invalid_params().data(error)) + } + } +} + +#[cfg(test)] +mod tests { + use super::tunnel_url; + + #[test] + fn accepts_only_an_https_quick_tunnel_hostname() { + assert_eq!( + tunnel_url("INF | https://my-test-2.trycloudflare.com |"), + Some("https://my-test-2.trycloudflare.com"), + ); + for other in [ + "http://preview.trycloudflare.com", + "https://preview.trycloudflare.com.example.com", + "https://example.com@preview.trycloudflare.com", + "https://preview.trycloudflare.com/some/path", + ] { + assert_eq!(tunnel_url(other), None); + } + } +} diff --git a/rustcode/engine/src/network/tool_exec.rs b/rustcode/engine/src/network/tool_exec.rs index 2aa751474..ce7039a70 100644 --- a/rustcode/engine/src/network/tool_exec.rs +++ b/rustcode/engine/src/network/tool_exec.rs @@ -1511,6 +1511,12 @@ async fn execute_tool_batch_validated( None, std::time::Duration::ZERO, ) + } else if name_clone == crate::acp::preview_share::TOOL_NAME { + ( + crate::acp::preview_share::execute(&state_clone, &args_clone, &cancel_token_clone).await, + None, + std::time::Duration::ZERO, + ) } else if name_clone == crate::orchestration::secret::TOOL_NAME { (crate::orchestration::secret::execute(&state_clone, &cancel_token_clone, &args_clone).await, None, std::time::Duration::ZERO) } else if crate::workflow::is_tool(&name_clone) { diff --git a/rustcode/engine/src/orchestration/mcp_server.rs b/rustcode/engine/src/orchestration/mcp_server.rs index 0dc2158ce..33d26e53f 100644 --- a/rustcode/engine/src/orchestration/mcp_server.rs +++ b/rustcode/engine/src/orchestration/mcp_server.rs @@ -128,6 +128,7 @@ pub fn tools_with(version: u8, smart_ui: bool, ask_user: bool) -> Vec { // orchestration version gates it (#3369). std::iter::once(crate::pull_watch::LINK_TOOL_NAME) .chain(std::iter::once(super::secret::TOOL_NAME)) + .chain(std::iter::once(crate::acp::preview_share::TOOL_NAME)) // Managing RustCode itself (#3821): answered by the engine, which // asks the user before a write through the thread's own card. .chain(crate::manage::TOOL_NAMES) @@ -272,6 +273,11 @@ const LISTING: &[(&str, &str, Effect)] = &[ Effect::Adds, ), (super::ask_user::TOOL_NAME, "Ask the user", Effect::Adds), + ( + crate::acp::preview_share::TOOL_NAME, + "Share preview publicly", + Effect::Adds, + ), (super::COMPACT_SESSION, "Compact a thread", Effect::Adds), (super::UPDATE_SESSION, "Update a thread", Effect::Sets), (super::CONFIGURE_SESSION, "Configure a thread", Effect::Sets), @@ -731,7 +737,7 @@ async fn call_inside( } return forward.call(inside_request(identity, tool, args)).await; } - if tool == super::secret::TOOL_NAME { + if tool == super::secret::TOOL_NAME || tool == crate::acp::preview_share::TOOL_NAME { return forward.call(inside_request(identity, tool, args)).await; } // The engine asks the user through the thread's own channel; checked @@ -1694,6 +1700,7 @@ mod tests { // for every client and answered by this server (#3369). expected.push(crate::pull_watch::LINK_TOOL_NAME.to_owned()); expected.push(super::super::secret::TOOL_NAME.to_owned()); + expected.push(crate::acp::preview_share::TOOL_NAME.to_owned()); expected.extend(crate::manage::TOOL_NAMES.map(str::to_owned)); // The workflow tools follow it for a client that can start threads. expected.extend(crate::workflow::TOOL_NAMES.map(str::to_owned)); diff --git a/rustcode/engine/src/orchestration/tool_socket.rs b/rustcode/engine/src/orchestration/tool_socket.rs index b0cf59835..e68e50dac 100644 --- a/rustcode/engine/src/orchestration/tool_socket.rs +++ b/rustcode/engine/src/orchestration/tool_socket.rs @@ -461,6 +461,22 @@ impl Hub { return crate::computer_use::answer(&request, self.questions_for(&request), cancel) .await; } + if request.tool == crate::acp::preview_share::TOOL_NAME { + return match crate::acp::preview_share::answer( + &request.session_id, + &request.args, + self.questions_for(&request), + cancel, + ) + .await + { + Ok(value) => CallAnswer { + success: true, + content: value.to_string(), + }, + Err(error) => CallAnswer::failure(error), + }; + } if request.tool == super::secret::TOOL_NAME { let workspace = self .lock() diff --git a/rustcode/engine/src/remote_gateway/acp_relay.rs b/rustcode/engine/src/remote_gateway/acp_relay.rs index 9a721f0e4..a2814b00a 100644 --- a/rustcode/engine/src/remote_gateway/acp_relay.rs +++ b/rustcode/engine/src/remote_gateway/acp_relay.rs @@ -165,6 +165,8 @@ const EXACT_METHODS: &[&str] = &[ // Running a shell command on this machine for another machine in the fleet // (`acp/machine_exec.rs`), subject to this machine's command policy. "_rustcode/machine/exec", + "_rustcode/preview/share", + "_rustcode/preview/connection", // Updating RustCode here when a paired machine asks (Settings › Machines › // Update, `acp/machine_update.rs`): only the newest stable release, checked // as `rc --update` checks it, and restarted onto once no turn runs. @@ -511,6 +513,8 @@ mod tests { "_rustcode/worktrees/state", "_rustcode/environment/sync", "_rustcode/machine/exec", + "_rustcode/preview/share", + "_rustcode/preview/connection", "_rustcode/machine/update", "_rustcode/session/harness", "_rustcode/session/move", diff --git a/rustcode/engine/src/tools/misc.rs b/rustcode/engine/src/tools/misc.rs index 84e66cb95..51763f94b 100644 --- a/rustcode/engine/src/tools/misc.rs +++ b/rustcode/engine/src/tools/misc.rs @@ -268,6 +268,17 @@ pub const DESKTOP_CONTROL: Tool = Tool { safety: ToolSafety::Interactive, }; +pub const SHARE_PREVIEW: Tool = Tool { + name: crate::acp::preview_share::TOOL_NAME, + description: "Ask for one-time approval to share this thread's loopback HTTP server via a public link for one hour. Anyone with the link can access the server. Prefer a static build server to avoid exposing a dev server's source files.", + arguments: r#"{"port": 4173}"#, + handler: |_| Err("Preview sharing needs a thread and a RustCode approval window.".to_owned()), + requires_confirmation: false, + schema: crate::acp::preview_share::schema, + capabilities: &[ToolCapability::UserInteraction], + safety: ToolSafety::Interactive, +}; + fn localhost_preview_schema() -> Value { crate::preview::operation_schema() } diff --git a/rustcode/engine/src/tools/mod.rs b/rustcode/engine/src/tools/mod.rs index c16584bbe..72cf3c4f1 100644 --- a/rustcode/engine/src/tools/mod.rs +++ b/rustcode/engine/src/tools/mod.rs @@ -1452,6 +1452,7 @@ pub const TOOLS: &[Tool] = &[ misc::LOCALHOST_PREVIEW, misc::DESKTOP_CONTROL, misc::SMART_UI_PREVIEW, + misc::SHARE_PREVIEW, misc::SMART_UI_CHECK, misc::ASK_USER_QUESTION, misc::REQUEST_SECRET, diff --git a/rustcode/engine/src/tools/schema.rs b/rustcode/engine/src/tools/schema.rs index ff4c2952c..012f5145b 100644 --- a/rustcode/engine/src/tools/schema.rs +++ b/rustcode/engine/src/tools/schema.rs @@ -936,6 +936,7 @@ const BOOTSTRAP_SOURCE_FILE_LIMIT: usize = 3; /// title, goal and preview) or talk to the user directly. A child agent /// reports back to its parent instead. const ROOT_ONLY_TOOLS: &[&str] = &[ + crate::acp::preview_share::TOOL_NAME, "set_session_title", "complete_task", "ask_question", @@ -1005,7 +1006,8 @@ fn builtin_is_advertised(tool: &super::Tool, policy: ToolSchemaPolicy) -> bool { }; !((crate::computer_use::is_tool(tool.name) && !crate::computer_use::Settings::load().enabled) || (tool.name == "set_session_title" && !policy.include_session_title_tool) - || (tool.name == crate::preview::PREVIEW_TOOL_NAME && !policy.include_preview_tool) + || (matches!(tool.name, crate::preview::PREVIEW_TOOL_NAME | crate::acp::preview_share::TOOL_NAME) + && !policy.include_preview_tool) || (tool.name == crate::desktop_control::TOOL_NAME && !policy.include_desktop_tool) || (tool.name == crate::smart_ui::PREVIEW_TOOL_NAME && !policy.include_smart_ui_preview_tool)