From 36de0aace794adba932a78d77c5fc95a560b3dd1 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Sat, 28 Nov 2026 11:24:57 +0100 Subject: [PATCH] feat: add static previews to the room pane The preview tool could only name a port, so a static build needed a server the terminal had to keep alive. `preview` now accepts a path: the app reads the file or folder over the room's ssh sandbox and serves it from a signed host, with `..` and dotfiles refused and a 16 MiB cap. The target is stored with the room and replayed as a durable event. The pane shows a static path with a reload control and keeps the port field as a local fallback. --- AGENTS.md | 19 +- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 50 ++- specs/rhema-together.md | 64 +-- src/api/files.rs | 17 +- src/api/rooms.rs | 26 +- src/db.rs | 10 + src/models.rs | 19 + src/preview.rs | 643 +++++++++++++++++++++++++++-- src/room/agent.rs | 8 +- src/room/mod.rs | 1 + src/room/preview_tool.rs | 110 +++++ src/room/prompt.md | 13 + src/util.rs | 35 ++ web/app/assets/css/main.css | 9 + web/app/components/PreviewPane.vue | 143 +++++-- web/app/components/RightPane.vue | 5 +- web/app/pages/room/[id].vue | 11 +- web/app/types.ts | 6 + 20 files changed, 1046 insertions(+), 145 deletions(-) create mode 100644 src/room/preview_tool.rs diff --git a/AGENTS.md b/AGENTS.md index 71d22bf..304741b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,9 +50,10 @@ src/state.rs AppState: db, hub, secrets, runner, tunnels src/api/ routes: auth, settings, rooms, messages, files src/room/agent.rs per-turn config, ssh sandbox, HostAgent assembly src/room/runner.rs one task per room; mention -> turn; steering -src/room/message_tool.rs the agent's only voice +src/room/message_tool.rs the agent's voice in the room +src/room/preview_tool.rs the agent's preview target src/ssh.rs russh client, PTY terminal, direct-tcpip -src/preview.rs signed preview hosts and the ssh HTTP proxy +src/preview.rs signed preview hosts, ssh proxy, static reads web/app/ Nuxt 4 SPA (no SSR) ``` @@ -66,17 +67,19 @@ web/app/ Nuxt 4 SPA (no SSR) - Guests may join and chat. Only `kind = "user"` accounts create rooms or add providers and sandbox targets. - Room log events are append-only. `seq` is the ordering. Durable - events (`message`, `notice`, `turn_start`, `turn_end`, `tool_result`) - are stored and replay from `?since=`; deltas are broadcast only and - may leave gaps. + events (`message`, `notice`, `turn_start`, `turn_end`, `tool_result`, + `preview`) are stored and replay from `?since=`; deltas are broadcast + only and may leave gaps. - The agent speaks through `message` only. It must always send one before the turn ends. `message` is `ReplaySafety::Unsafe`. - Turns are serialized per room. A new mention while a turn runs drops the turn future (turn-level steering) and starts a new turn over the committed session. Do not drop the room task. -- The preview host label is `r-p-.`. - The HMAC covers `room:port` with a key derived from the master key. - The preview origin must be a wildcard DNS zone for subdomains to +- The preview host label is `r-p--.` for a port, or `r-s--.` + for a static target. The HMAC covers the target and expiry with a key + derived from the master key. The static hash covers the root and entry + file. The preview origin must be a wildcard DNS zone for subdomains to resolve. ## Testing diff --git a/Cargo.lock b/Cargo.lock index 05b19fb..51f07ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3689,6 +3689,7 @@ dependencies = [ "hyper", "hyper-util", "mime_guess", + "percent-encoding", "rand 0.8.8", "rhema-bash", "rhema-core", diff --git a/Cargo.toml b/Cargo.toml index a02fd43..c38547f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ hmac = "0.12" hyper = { version = "1", features = ["client", "http1"] } hyper-util = { version = "0.1", features = ["tokio"] } mime_guess = "2" +percent-encoding = "2" rand = "0.8" rhema-bash = { path = "../rhema/crates/rhema-bash" } rhema-core = { path = "../rhema/crates/rhema-core" } diff --git a/README.md b/README.md index 7bf43ec..991a15a 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ The room is a browser workspace: - **Chat** with the room and with `@rhema`. Human messages carry their author's name; the agent speaks through a `message` tool so that its private reasoning never leaks into the room. -- **Preview** iframe for a dev server running inside the sandbox. +- **Preview** iframe for a dev server or a static build, set from the + chat by the agent's `preview` tool. - **Files** pane: the tree, a read-only file view, `git status`, and `git diff`. - **Terminal**: a real PTY in the sandbox, same target and key as the @@ -120,6 +121,17 @@ boundary. ## Preview +The preview shows one target per room. It is either a port inside the +sandbox, or a static HTML file or folder read over ssh and served by the +app. The agent sets it with the `preview` tool, and the choice is stored +with the room, so a later visitor sees the same target. + +A static target does not start a process. Point it at a build folder +(`dist`, `web/.output/public`) or a single HTML file. The app reads files +over the same ssh target the agent uses, refuses `..` and dotfiles, and +stops at 16 MiB per file. Point it at a build folder rather than the +repository root unless the whole tree is meant to be public. + The preview host is a signed subdomain of `TOGETHER_PREVIEW_ORIGIN`: ``` @@ -127,19 +139,24 @@ http://preview.localhost:7800 local development https://preview.together.example.com production ``` -Each preview is served from -`://r-p--./`. The HMAC -covers the room, port, and expiry and is derived from the server's -master key, so a room id alone is not enough to reach a preview. The -address expires after 24 hours; reloading the pane mints a new one. DNS -must resolve every subdomain of the preview host to the server (a -wildcard `*.preview` record), and TLS must cover the wildcard. A copied -preview URL works for anyone who has it until it expires; treat it as a -read capability for that port. +A port is served from +`://r-p--./`. +A static target is served from +`://r-s--./`, where +`hash` covers the target's root and entry file. A link minted for one +static target stops working when the preview moves. The HMAC covers the +target and expiry and is derived from the server's master key, so a room +id alone is not enough to reach a preview. The address expires after 24 +hours; loading the pane mints a new one. DNS must resolve every subdomain +of the preview host to the server (a wildcard `*.preview` record), and +TLS must cover the wildcard. A copied preview URL works for anyone who +has it until it expires; treat it as a read capability for that target. -The proxy forwards ordinary HTTP through an ssh `direct-tcpip` channel -to `127.0.0.1:` inside the sandbox. WebSocket upgrades (Vite HMR) -are not forwarded in v1; reload the pane after an edit. +For a port, the proxy forwards ordinary HTTP through an ssh +`direct-tcpip` channel to `127.0.0.1:` inside the sandbox. For a +static target, each request runs one short read over ssh. WebSocket +upgrades (Vite HMR) are not forwarded in v1; reload the pane after an +edit, and disable HMR for the preview when a dev server insists on it. ### Caddy @@ -190,9 +207,10 @@ Every field can be set in the YAML file (`TOGETHER_CONFIG`, default to a host it names, so open signup also makes the server reachable from anywhere as a port scanner. Turn it on only when you trust everyone who can reach `/register`. -- A preview host is a signed capability for one room and port. It - expires after 24 hours, and preview responses carry - `Referrer-Policy: no-referrer`. A copied URL works until it expires. +- A preview host is a signed capability for one room and one target, + either a port or a static tree. It expires after 24 hours, and preview + responses carry `Referrer-Policy: no-referrer`. A copied URL works + until it expires. - Removing a member or archiving a room ends that account's event feed, presence socket, and terminal within a few seconds. The terminal and preview proxy pin the SSH host key on first login and refuse a diff --git a/specs/rhema-together.md b/specs/rhema-together.md index d084963..7639b1d 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -328,48 +328,62 @@ cost. The footer is per turn, not per message. ### Preview -Iframe at a preview URL. Discovery is a manual port field plus a scrape -of `bash` output for `localhost:` and `127.0.0.1:` shown as -suggestions. No heuristics beyond that. +The pane shows one target per room, either a port inside the sandbox or a +static file or folder. The agent sets it with the `preview` tool. The target +is stored and written to the room log as a durable `preview` event, so every +open pane updates and a reconnecting viewer gets it with the room detail. +The port field remains as a local fallback. -Serving: the app's listener recognizes preview hosts and tunnels each -request over ssh `direct-tcpip` to the sandbox. The ssh connection is -opened once per sandbox target and reused by every room and port on it. -TLS and DNS happen in the reverse proxy. +Port targets tunnel each request over ssh `direct-tcpip` to the sandbox. The +ssh connection is opened once per sandbox target and reused by every room and +port on it. + +Static targets are read over ssh and served by the app. No server process is +started, so a preview does not depend on what a terminal is doing. A static +path is workspace-relative. A folder must contain `index.html`; a file is +served as itself and its parent becomes the asset root. Requests map onto that +root, and `/` serves the entry file. `..`, NUL bytes, and dotfiles are refused +in requests, and a target path that names a hidden file or folder is refused. +Files above 16 MiB are refused. The read uses the same ssh target as the +agent, so it adds no network path or permission. Layout, one wildcard record: ``` app https://together./room// preview https://r-p--.preview./ + https://r-s--.preview./ ``` -The room, port, expiry, and a 24-hex HMAC signature form the first -label. The signature is minted by the app when the pane opens and -checked by the proxy, so the URL is not guessable from a room id. It -expires after 24 hours, and loading the room mints a fresh one. Treat a -copied preview URL as a read capability for that port until it expires. +`hash` is 12 hex characters over the static root and entry file. A link +minted for one static target stops matching when the agent points the preview +somewhere else. The room, target, expiry, and a 24-hex HMAC signature form +the first label. The signature is minted by the app when the pane requests a +URL and checked by the proxy, so the URL is not guessable from a room id. It +expires after 24 hours, and loading the room mints a fresh one. Treat a copied +preview URL as a read capability for that target until it expires. -The preview needs its own hostname. It is repo code, and on the app's -origin it could call the API with the viewer's cookie, which turns every -opened preview into an account-stealer for the other members. A separate -`preview.` host has no app cookie (the cookie is `__Host-`, no `Domain`), -and preview responses carry +The preview needs its own hostname. It is repo code, and on the app's origin +it could call the API with the viewer's cookie, which turns every opened +preview into an account-stealer for the other members. A separate `preview.` +host has no app cookie (the cookie is `__Host-`, no `Domain`), and preview +responses carry `Content-Security-Policy: frame-ancestors https://together.`. The iframe carries `sandbox="allow-scripts allow-same-origin allow-forms allow-popups"`. -Each room+port gets its own hostname, so root-absolute asset URLs +Each room and target gets its own hostname, so root-absolute asset URLs (`/assets/app.js`), JS-constructed URLs, and `Location` headers need no -rewriting. Vite's HMR WebSocket is not proxied in v1; reload with the -button after an edit, or disable HMR in the previewed server. +rewriting. Vite's HMR WebSocket is not proxied in v1. Static previews ignore +HMR; port previews can disable it and use the reload button. -Auth: the preview host carries no app cookie, and the signed label is -the whole capability. Preview responses carry `Referrer-Policy: -no-referrer` so the signed host does not leak to third-party resources. -The app's CSP names `*.` in `frame-src`. +Auth: the preview host carries no app cookie, and the signed label is the +whole capability. Preview responses carry `Referrer-Policy: no-referrer` so +the signed host does not leak to third-party resources. The app's CSP names +`*.` in `frame-src`. -Refresh: a button and a reload when a turn ends. +Refresh: the pane reloads when a `preview` event arrives, and the button +reloads the current target. ### Terminal diff --git a/src/api/files.rs b/src/api/files.rs index 288a10a..0fde998 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -18,6 +18,7 @@ use crate::error::{AppError, AppResult}; use crate::models::FileEntry; use crate::room::agent; use crate::state::Shared; +use crate::util::safe_rel_path; use super::rooms::member_of; @@ -35,21 +36,7 @@ fn room_workspace(state: &Shared, room: &str) -> AppResult<(String, agent::Targe /// Validates a workspace-relative path. fn safe_rel(path: &str) -> AppResult { - let trimmed = path.trim(); - if trimmed.starts_with('/') { - return Err(AppError::bad_request( - "path must be relative to the workspace", - )); - } - let normalized = trimmed.trim_matches('/'); - if normalized.split('/').any(|part| part == "..") { - return Err(AppError::bad_request("path escapes the workspace")); - } - Ok(if normalized.is_empty() { - ".".to_owned() - } else { - normalized.to_owned() - }) + safe_rel_path(path).map_err(AppError::bad_request) } async fn run( diff --git a/src/api/rooms.rs b/src/api/rooms.rs index f7528d2..a144645 100644 --- a/src/api/rooms.rs +++ b/src/api/rooms.rs @@ -273,9 +273,11 @@ pub async fn detail( let membership = member_of(&state, &id, &user.user.id)?; let room = load_room(&state, &id)?; let members = load_members(&state, &id)?; + let preview = crate::preview::load_target(&state, &id)?; Ok(Json(json!({ "room": room, "members": members, + "preview": preview, "me": { "id": membership.id, "display_name": membership.display_name, @@ -375,7 +377,8 @@ pub struct PreviewQuery { pub port: Option, } -/// The signed iframe URL for one port inside this room's sandbox. +/// The signed iframe URL for the room's preview, or for one port when +/// the caller names one. pub async fn preview( user: AuthUser, State(state): State, @@ -383,12 +386,21 @@ pub async fn preview( axum::extract::Query(query): axum::extract::Query, ) -> AppResult> { member_of(&state, &room, &user.user.id)?; - let port = query.port.unwrap_or(3000); - if port == 0 { - return Err(AppError::bad_request("port must be between 1 and 65535")); - } - let url = crate::preview::url(&state.config, &state.secrets, &room, port)?; - Ok(Json(json!({ "url": url, "port": port }))) + let target = match query.port { + Some(0) => { + return Err(AppError::bad_request("port must be between 1 and 65535")); + } + Some(port) => crate::models::PreviewTarget::Port { port }, + None => crate::preview::load_target(&state, &room)? + .ok_or_else(|| AppError::bad_request("the room has no preview yet"))?, + }; + let url = match &target { + crate::models::PreviewTarget::Port { port } => { + crate::preview::url(&state.config, &state.secrets, &room, *port)? + } + _ => crate::preview::url_for_target(&state.config, &state.secrets, &room, &target)?, + }; + Ok(Json(json!({ "url": url, "target": target }))) } /// Removes a member. The owner cannot be removed. diff --git a/src/db.rs b/src/db.rs index 191ae52..3d280a1 100644 --- a/src/db.rs +++ b/src/db.rs @@ -120,6 +120,16 @@ CREATE TABLE IF NOT EXISTS rooms ( archived_at INTEGER ) STRICT; +CREATE TABLE IF NOT EXISTS room_previews ( + room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + port INTEGER, + path TEXT, + root TEXT, + entry TEXT, + updated_at INTEGER NOT NULL +) STRICT; + CREATE TABLE IF NOT EXISTS members ( id TEXT PRIMARY KEY, room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE, diff --git a/src/models.rs b/src/models.rs index 44403ea..0f17a37 100644 --- a/src/models.rs +++ b/src/models.rs @@ -67,6 +67,25 @@ pub struct User { pub avatar_updated_at: Option, } +/// What the room's preview pane shows: a port inside the sandbox, or +/// a static file or folder served by the app. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum PreviewTarget { + /// A listener inside the sandbox. + Port { port: u16 }, + /// A file, or a folder with an `index.html`, read over ssh and + /// served from the signed preview host. + Static { + /// The workspace-relative path the agent named. + path: String, + /// The workspace-relative directory the URL paths resolve in. + root: String, + /// The workspace-relative file a request for `/` serves. + entry: String, + }, +} + /// One server-sent event. Durable events are also rows in `events`; /// deltas are live only. #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/src/preview.rs b/src/preview.rs index 5be0164..210b094 100644 --- a/src/preview.rs +++ b/src/preview.rs @@ -1,24 +1,33 @@ -//! The preview proxy: a room's dev server, served under a signed -//! subdomain of the preview origin. +//! The preview proxy: a room's dev server or static build, served under +//! a signed subdomain of the preview origin. //! -//! `r-p-.` routes to 127.0.0.1: -//! inside the room's sandbox over the same ssh connection settings the -//! agent uses. Paths and the origin stay stable, so a dev server's -//! absolute asset URLs keep working; the host is per room and port. +//! `r-p--.` routes to +//! 127.0.0.1: inside the room's sandbox over the same ssh connection +//! settings the agent uses. `r-s--.` +//! serves a file or folder with `index.html` read over ssh. Paths and the +//! origin stay stable, so absolute asset URLs keep working. use std::collections::HashMap; +use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex}; +use std::time::Duration; use axum::body::Body; -use axum::http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode, Uri, header}; +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode, Uri, header}; use axum::response::{IntoResponse, Response}; use hyper_util::rt::TokioIo; +use percent_encoding::percent_decode_str; +use rhema_sandbox::Sandbox; +use rhema_sandbox::exec_util::shquote; +use rusqlite::OptionalExtension; use crate::config::Config; use crate::crypto::Secrets; -use crate::error::AppResult; -use crate::room::agent; +use crate::error::{AppError, AppResult}; +use crate::models::PreviewTarget; +use crate::room::agent::{self, TargetRow}; use crate::state::Shared; +use crate::util::safe_rel_path; /// One ssh connection per sandbox, opened lazily by the first preview /// request and reused by the channels after it. @@ -81,13 +90,25 @@ const PREVIEW_TTL_SECONDS: i64 = 24 * 60 * 60; /// The signed URL for one room and port. pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult { + url_for_target(config, secrets, room, &PreviewTarget::Port { port }) +} + +/// The signed URL for the room's current target. +pub fn url_for_target( + config: &Config, + secrets: &Secrets, + room: &str, + target: &PreviewTarget, +) -> AppResult { let Some((scheme, domain)) = domain(config) else { - return Err(crate::error::AppError::bad_request( - "the preview proxy is not configured", - )); + return Err(AppError::bad_request("the preview proxy is not configured")); }; let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS; - let signature = secrets.sign(&format!("{room}:{port}:{expires}")); + let (kind, value) = match target { + PreviewTarget::Port { port } => ('p', port.to_string()), + PreviewTarget::Static { root, entry, .. } => ('s', static_key(root, entry)), + }; + let signature = secrets.sign(&signature_text(room, kind, &value, expires)); let port_part = config .preview_origin .split_once("://") @@ -98,25 +119,248 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu .map(|(_, value)| format!(":{value}")) .unwrap_or_default(); Ok(format!( - "{scheme}://r{room}-p{port}-{expires}-{signature}.{domain}{port_part}/" + "{scheme}://r{room}-{kind}{value}-{expires}-{signature}.{domain}{port_part}/" )) } -/// Splits `r-p--` from the Host header. -fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, String)> { +/// A short identity for a static target. The signed link names it, so a +/// link minted for one path stops matching after the agent points the +/// preview somewhere else. +fn static_key(root: &str, entry: &str) -> String { + crate::util::sha256_hex(format!("{root}\n{entry}").as_bytes())[..12].to_owned() +} + +/// What a preview host label names. +#[derive(Debug, Clone, PartialEq, Eq)] +enum HostTarget { + Port(u16), + Static(String), +} + +/// One parsed preview host label. +struct HostClaim { + room: String, + target: HostTarget, + expires: i64, + signature: String, +} + +/// Splits `r-p--` or +/// `r-s--` from the Host header. +fn target_of_host(config: &Config, host: &str) -> Option { let (_, domain) = domain(config)?; let name = host.split(':').next().unwrap_or(host); let label = name.strip_suffix(&format!(".{domain}"))?; let rest = label.strip_prefix('r')?; - let (room, rest) = rest.rsplit_once("-p")?; - let mut fields = rest.split('-'); - let port: u16 = fields.next()?.parse().ok()?; - let expires: i64 = fields.next()?.parse().ok()?; - let signature = fields.next()?; - if room.is_empty() || signature.is_empty() || fields.next().is_some() { + let (room, rest) = rest.split_once('-')?; + let (target, rest) = rest.split_once('-')?; + let (expires, signature) = rest.split_once('-')?; + if room.is_empty() + || signature.is_empty() + || signature.contains('-') + || !expires.chars().all(|c| c.is_ascii_digit()) + { return None; } - Some((room.to_owned(), port, expires, signature.to_owned())) + let expires: i64 = expires.parse().ok()?; + let kind = target.chars().next()?; + let value = &target[kind.len_utf8()..]; + if value.is_empty() { + return None; + } + let target = match kind { + 'p' => HostTarget::Port(value.parse().ok()?), + 's' if value.chars().all(|c| c.is_ascii_hexdigit()) => HostTarget::Static(value.to_owned()), + _ => return None, + }; + Some(HostClaim { + room: room.to_owned(), + target, + expires, + signature: signature.to_owned(), + }) +} + +fn signature_text(room: &str, kind: char, value: &str, expires: i64) -> String { + match kind { + 'p' => format!("{room}:{value}:{expires}"), + _ => format!("{room}:static:{value}:{expires}"), + } +} + +/// The stored columns of one preview row. +type PreviewRow = ( + String, + Option, + Option, + Option, + Option, +); + +/// The room's current preview target, if one is set. +pub fn load_target(state: &Shared, room: &str) -> AppResult> { + let row: Option = state + .db + .conn() + .query_row( + "SELECT kind, port, path, root, entry FROM room_previews WHERE room_id = ?1", + rusqlite::params![room], + |row| { + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + )) + }, + ) + .optional()?; + let Some((kind, port, path, root, entry)) = row else { + return Ok(None); + }; + let target = match kind.as_str() { + "port" => PreviewTarget::Port { + port: u16::try_from(port.unwrap_or(0)) + .map_err(|_| AppError::internal("the saved preview port is invalid"))?, + }, + "static" => PreviewTarget::Static { + path: path.ok_or_else(|| AppError::internal("the saved preview has no path"))?, + root: root.ok_or_else(|| AppError::internal("the saved preview has no root"))?, + entry: entry.ok_or_else(|| AppError::internal("the saved preview has no entry"))?, + }, + _ => return Err(AppError::internal("the saved preview kind is unknown")), + }; + Ok(Some(target)) +} + +/// Stores a target without announcing it. +pub fn store_target(state: &Shared, room: &str, target: &PreviewTarget) -> AppResult<()> { + let (kind, port, path, root, entry) = match target { + PreviewTarget::Port { port } => ("port", Some(i64::from(*port)), None, None, None), + PreviewTarget::Static { path, root, entry } => ( + "static", + None, + Some(path.as_str()), + Some(root.as_str()), + Some(entry.as_str()), + ), + }; + state.db.conn().execute( + "INSERT INTO room_previews (room_id, kind, port, path, root, entry, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) + ON CONFLICT(room_id) DO UPDATE SET + kind = excluded.kind, + port = excluded.port, + path = excluded.path, + root = excluded.root, + entry = excluded.entry, + updated_at = excluded.updated_at", + rusqlite::params![room, kind, port, path, root, entry, crate::util::now_ms()], + )?; + Ok(()) +} + +/// Stores a target and adds it to the room log, so every open pane and +/// every later reconnect learns about it. +pub fn publish(state: &Shared, room: &str, target: &PreviewTarget) -> AppResult<()> { + store_target(state, room, target)?; + state + .hub + .durable(&state.db, room, "preview", serde_json::to_value(target)?)?; + Ok(()) +} + +/// Validates a workspace path for the static preview and answers the +/// target to store. A folder must have an `index.html`; a file is served +/// as itself and its parent becomes the asset root. +pub async fn static_target( + state: &Shared, + workspace: &str, + sandbox_target: &TargetRow, + path: &str, +) -> Result { + let rel = visible_rel_path(path)?; + let abs = workspace_path(workspace, &rel); + let index = if rel == "." { + format!("{}/index.html", workspace.trim_end_matches('/')) + } else { + format!("{}/{rel}/index.html", workspace.trim_end_matches('/')) + }; + let command = format!( + "if [ -d {p} ]; then \ + if [ -f {i} ]; then printf 'dir'; else printf 'noindex'; fi; \ + elif [ -f {p} ]; then printf 'file'; else printf 'missing'; fi", + p = shquote(&abs), + i = shquote(&index) + ); + let sandbox = agent::sandbox_for(state, workspace, sandbox_target).map_err(|e| e.message)?; + let cancelled = AtomicBool::new(false); + let mut progress = rhema_sandbox::OutputOnly(|_| {}); + let outcome = sandbox + .run( + rhema_sandbox::RunRequest { + command, + cwd: workspace.into(), + timeout: Duration::from_secs(15), + env: Default::default(), + }, + &cancelled, + &mut progress, + ) + .await + .map_err(|err| err.to_string())?; + let kind = String::from_utf8_lossy(&outcome.stdout).trim().to_owned(); + match kind.as_str() { + "dir" => { + let entry = if rel == "." { + "index.html".to_owned() + } else { + format!("{rel}/index.html") + }; + Ok(PreviewTarget::Static { + path: rel.clone(), + root: rel, + entry, + }) + } + "file" => { + let root = rel + .rsplit_once('/') + .map(|(parent, _)| parent.to_owned()) + .unwrap_or_else(|| ".".to_owned()); + Ok(PreviewTarget::Static { + path: rel.clone(), + root, + entry: rel, + }) + } + "noindex" => Err(format!("{rel} has no index.html to serve")), + "missing" => Err(format!("{rel} does not exist in the workspace")), + _ => Err(format!("could not inspect {rel} in the workspace")), + } +} + +/// A static target must not name a hidden file or folder. The request +/// side refuses dotfiles too, but checking here stops a model from +/// publishing `.env` or `.git` as the entry. +fn visible_rel_path(path: &str) -> Result { + let rel = safe_rel_path(path)?; + if rel + .split('/') + .any(|part| part != "." && part.starts_with('.') && part != ".well-known") + { + return Err("the preview cannot point at a hidden file or folder".into()); + } + Ok(rel) +} + +fn workspace_path(workspace: &str, rel: &str) -> String { + if rel == "." { + workspace.trim_end_matches('/').to_owned() + } else { + format!("{}/{}", workspace.trim_end_matches('/'), rel) + } } fn signatures_match(a: &str, b: &str) -> bool { @@ -130,6 +374,18 @@ fn signatures_match(a: &str, b: &str) -> bool { diff == 0 } +fn frame_ancestors(config: &Config, mut response: Response) -> Response { + if let Ok(value) = HeaderValue::from_str(&format!( + "frame-ancestors {}", + config.public_url.trim_end_matches('/') + )) { + response + .headers_mut() + .insert(header::CONTENT_SECURITY_POLICY, value); + } + response +} + fn no_referrer(mut response: Response) -> Response { response.headers_mut().insert( header::REFERRER_POLICY, @@ -138,8 +394,8 @@ fn no_referrer(mut response: Response) -> Response { response } -/// Verifies the signature in the Host header against the room and port -/// it names, then proxies the request. +/// Verifies the signed label against the target it names, then serves +/// that target. pub async fn proxy(state: Shared, request: Request) -> Response { let host = request .headers() @@ -147,25 +403,37 @@ pub async fn proxy(state: Shared, request: Request) -> Response { .and_then(|value| value.to_str().ok()) .unwrap_or("") .to_owned(); - let Some((room, port, expires, signature)) = target_of_host(&state.config, &host) else { + let Some(claim) = target_of_host(&state.config, &host) else { return (StatusCode::NOT_FOUND, "not a preview host").into_response(); }; - if expires < crate::util::now_ms() / 1000 { + if claim.expires < crate::util::now_ms() / 1000 { return (StatusCode::NOT_FOUND, "this preview link has expired").into_response(); } - let expected = state.secrets.sign(&format!("{room}:{port}:{expires}")); - if !signatures_match(&signature, &expected) { + let (kind, value) = match &claim.target { + HostTarget::Port(port) => ('p', port.to_string()), + HostTarget::Static(key) => ('s', key.clone()), + }; + let expected = state + .secrets + .sign(&signature_text(&claim.room, kind, &value, claim.expires)); + if !signatures_match(&claim.signature, &expected) { return (StatusCode::NOT_FOUND, "not a preview host").into_response(); } - match try_proxy(&state, &room, port, request).await { - Ok(response) => no_referrer(response), - Err(message) => no_referrer( - ( - StatusCode::BAD_GATEWAY, - format!("the preview did not answer: {message}"), - ) - .into_response(), - ), + match claim.target { + HostTarget::Port(port) => match try_proxy(&state, &claim.room, port, request).await { + Ok(response) => no_referrer(frame_ancestors(&state.config, response)), + Err(message) => no_referrer( + ( + StatusCode::BAD_GATEWAY, + format!("the preview did not answer: {message}"), + ) + .into_response(), + ), + }, + HostTarget::Static(key) => match try_static(&state, &claim.room, &key, request).await { + Ok(response) => no_referrer(response), + Err((status, message)) => no_referrer((status, message).into_response()), + }, } } @@ -246,6 +514,187 @@ async fn try_proxy( Ok(no_referrer(out)) } +/// The largest static file the preview serves. The sandbox read caps at +/// 32 MiB; this leaves room for the status line and keeps one request +/// from holding a whole build artifact in memory. +const STATIC_MAX_BYTES: usize = 16 * 1024 * 1024; + +/// Serves one request from a static target over the room's ssh sandbox. +async fn try_static( + state: &Shared, + room: &str, + key: &str, + request: Request, +) -> Result { + let target = load_target(state, room) + .map_err(|err| (StatusCode::BAD_GATEWAY, err.message))? + .ok_or_else(|| (StatusCode::NOT_FOUND, "this room has no preview".to_owned()))?; + let PreviewTarget::Static { root, entry, .. } = target else { + return Err(( + StatusCode::NOT_FOUND, + "this preview link no longer matches the room".to_owned(), + )); + }; + if static_key(&root, &entry) != key { + return Err(( + StatusCode::NOT_FOUND, + "this preview link no longer matches the room".to_owned(), + )); + } + let method = request.method(); + if method != Method::GET && method != Method::HEAD { + return Err(( + StatusCode::METHOD_NOT_ALLOWED, + "the static preview only answers GET and HEAD".to_owned(), + )); + } + let rel = static_request_path(request.uri(), &root, &entry)?; + let (workspace, sandbox_target) = agent::load_room_target(state, room) + .map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?; + let abs = workspace_path(&workspace, &rel); + let sandbox = agent::sandbox_for(state, &workspace, &sandbox_target) + .map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?; + let cancelled = AtomicBool::new(false); + let mut progress = rhema_sandbox::OutputOnly(|_| {}); + let outcome = sandbox + .run( + rhema_sandbox::RunRequest { + command: static_read_command(&abs), + cwd: workspace.into(), + timeout: Duration::from_secs(20), + env: Default::default(), + }, + &cancelled, + &mut progress, + ) + .await + .map_err(|err| (StatusCode::BAD_GATEWAY, err.to_string()))?; + let read = parse_static_output(outcome.stdout).ok_or_else(|| { + ( + StatusCode::BAD_GATEWAY, + "the static preview returned no status".to_owned(), + ) + })?; + let body = match read { + StaticRead::Body(body) => body, + StaticRead::Missing => { + return Err((StatusCode::NOT_FOUND, "file not found".to_owned())); + } + StaticRead::Large => { + return Err(( + StatusCode::PAYLOAD_TOO_LARGE, + "this file is too large for the static preview".to_owned(), + )); + } + }; + let length = body.len(); + let body = if method == Method::HEAD { + Body::empty() + } else { + Body::from(body) + }; + let frame_ancestors = format!( + "frame-ancestors {}", + state.config.public_url.trim_end_matches('/') + ); + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type(&rel)) + .header(header::CONTENT_LENGTH, length) + .header(header::CACHE_CONTROL, "no-store") + .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff") + .header(header::CONTENT_SECURITY_POLICY, frame_ancestors) + .body(body) + .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())) +} + +/// Maps a request path onto the static root, refusing escapes and +/// dotfiles. A trailing slash asks for that directory's `index.html`. +fn static_request_path(uri: &Uri, root: &str, entry: &str) -> Result { + let decoded = percent_decode_str(uri.path()) + .decode_utf8() + .map_err(|_| (StatusCode::NOT_FOUND, "file not found".to_owned()))?; + let raw = decoded.trim_start_matches('/'); + if raw.is_empty() { + return Ok(entry.to_owned()); + } + if raw.contains('\0') { + return Err((StatusCode::NOT_FOUND, "file not found".to_owned())); + } + let trailing = raw.ends_with('/'); + let mut parts = Vec::new(); + for part in raw.split('/') { + if part.is_empty() || part == "." { + continue; + } + if part == ".." { + return Err((StatusCode::NOT_FOUND, "file not found".to_owned())); + } + if part.starts_with('.') && part != ".well-known" { + return Err((StatusCode::NOT_FOUND, "file not found".to_owned())); + } + parts.push(part); + } + if trailing { + parts.push("index.html"); + } + let rel = parts.join("/"); + if rel.is_empty() { + return Ok(entry.to_owned()); + } + Ok(if root == "." { + rel + } else { + format!("{root}/{rel}") + }) +} + +fn static_read_command(path: &str) -> String { + format!( + "p={q}; if [ ! -f \"$p\" ]; then printf 'missing'; exit 0; fi; \ + s=$(stat -c %s -- \"$p\" 2>/dev/null) || {{ printf 'missing'; exit 0; }}; \ + if [ \"$s\" -gt {max} ]; then printf 'large'; exit 0; fi; \ + printf 'ok\\n'; cat -- \"$p\"", + q = shquote(path), + max = STATIC_MAX_BYTES + ) +} + +enum StaticRead { + Body(Vec), + Missing, + Large, +} + +fn parse_static_output(stdout: Vec) -> Option { + let boundary = stdout.iter().position(|byte| *byte == b'\n'); + let (head, body) = match boundary { + Some(index) => (&stdout[..index], stdout[index + 1..].to_vec()), + None => (&stdout[..], Vec::new()), + }; + match head { + b"ok" => Some(StaticRead::Body(body)), + b"missing" => Some(StaticRead::Missing), + b"large" => Some(StaticRead::Large), + _ => None, + } +} + +fn content_type(path: &str) -> HeaderValue { + let mime = mime_guess::from_path(path).first_or_octet_stream(); + let mut value = mime.to_string(); + if value.starts_with("text/") + || matches!( + value.as_str(), + "application/javascript" | "application/json" | "application/xml" | "image/svg+xml" + ) + { + value.push_str("; charset=utf-8"); + } + HeaderValue::from_str(&value) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")) +} + fn strip_hop_by_hop(headers: &mut HeaderMap) { for name in [ header::CONNECTION, @@ -288,11 +737,56 @@ mod tests { .split('/') .next() .expect("host"); - let (room, port, expires, signature) = target_of_host(&config, host).expect("parsed host"); - assert_eq!(room, "room123"); - assert_eq!(port, 5173); - assert!(expires >= crate::util::now_ms() / 1000); - assert_eq!(signature, secrets.sign(&format!("room123:5173:{expires}"))); + let claim = target_of_host(&config, host).expect("parsed host"); + assert_eq!(claim.room, "room123"); + assert_eq!(claim.target, HostTarget::Port(5173)); + assert!(claim.expires >= crate::util::now_ms() / 1000); + assert_eq!( + claim.signature, + secrets.sign(&format!("room123:5173:{}", claim.expires)) + ); + let _ = std::fs::remove_file(path); + } + + #[test] + fn a_static_target_refuses_hidden_paths() { + assert!(visible_rel_path(".env").is_err()); + assert!(visible_rel_path(".git/config").is_err()); + assert!(visible_rel_path("dist/../.env").is_err()); + assert_eq!(visible_rel_path("dist").unwrap(), "dist"); + assert_eq!(visible_rel_path(".").unwrap(), "."); + assert_eq!(visible_rel_path(".well-known").unwrap(), ".well-known"); + } + + #[test] + fn a_static_host_carries_the_target_and_signature() { + let config = Config { + preview_origin: "https://preview.example.com".into(), + ..Default::default() + }; + let (secrets, path) = secrets(); + let target = PreviewTarget::Static { + path: "web/dist".into(), + root: "web/dist".into(), + entry: "web/dist/index.html".into(), + }; + let url = url_for_target(&config, &secrets, "room123", &target).expect("url"); + let host = url + .trim_start_matches("https://") + .split('/') + .next() + .expect("host"); + let claim = target_of_host(&config, host).expect("parsed host"); + assert_eq!(claim.room, "room123"); + assert_eq!( + claim.signature, + secrets.sign(&format!( + "room123:static:{}:{}", + static_key("web/dist", "web/dist/index.html"), + claim.expires + )) + ); + assert!(matches!(claim.target, HostTarget::Static(_))); let _ = std::fs::remove_file(path); } @@ -311,6 +805,69 @@ mod tests { ); } + #[test] + fn static_paths_stay_inside_the_root() { + let uri: Uri = "/assets/app.js?version=2".parse().unwrap(); + assert_eq!( + static_request_path(&uri, "dist", "dist/index.html").unwrap(), + "dist/assets/app.js" + ); + let uri: Uri = "/".parse().unwrap(); + assert_eq!( + static_request_path(&uri, "dist", "dist/index.html").unwrap(), + "dist/index.html" + ); + let uri: Uri = "/docs/".parse().unwrap(); + assert_eq!( + static_request_path(&uri, "dist", "dist/index.html").unwrap(), + "dist/docs/index.html" + ); + let uri: Uri = "/../secret".parse().unwrap(); + assert!(static_request_path(&uri, "dist", "dist/index.html").is_err()); + let uri: Uri = "/%2e%2e/secret".parse().unwrap(); + assert!(static_request_path(&uri, "dist", "dist/index.html").is_err()); + let uri: Uri = "/.env".parse().unwrap(); + assert!(static_request_path(&uri, "dist", "dist/index.html").is_err()); + } + + #[test] + fn a_single_file_uses_its_parent_as_the_root() { + let uri: Uri = "/".parse().unwrap(); + assert_eq!( + static_request_path(&uri, ".", "index.html").unwrap(), + "index.html" + ); + let uri: Uri = "/style.css".parse().unwrap(); + assert_eq!( + static_request_path(&uri, ".", "index.html").unwrap(), + "style.css" + ); + } + + #[test] + fn static_reads_split_the_status_from_the_body() { + assert!(matches!( + parse_static_output(b"ok\n".to_vec()), + Some(StaticRead::Body(body)) if body == b"" + )); + assert!(matches!( + parse_static_output(b"missing".to_vec()), + Some(StaticRead::Missing) + )); + assert!(matches!( + parse_static_output(b"large".to_vec()), + Some(StaticRead::Large) + )); + assert!(parse_static_output(Vec::new()).is_none()); + } + + #[test] + fn text_types_get_a_charset() { + assert_eq!(content_type("index.html"), "text/html; charset=utf-8"); + assert_eq!(content_type("app.js"), "text/javascript; charset=utf-8"); + assert_eq!(content_type("logo.png"), "image/png"); + } + #[test] fn signatures_compare_by_value() { assert!(signatures_match("abcd", "abcd")); diff --git a/src/room/agent.rs b/src/room/agent.rs index e171da6..f11caa8 100644 --- a/src/room/agent.rs +++ b/src/room/agent.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use base64::Engine; use rhema_bash::{AllowAll, ShellTools}; use rhema_core::request::ThinkingEffort; -use rhema_core::{Session, ToolResolver}; +use rhema_core::{Overlay, Session, ToolResolver}; use rhema_host_agent::{HostAgent, HostAgentConfig}; use rhema_sandbox::WorkspaceSeed; use rhema_sandbox::{Sandbox, ShellSandbox}; @@ -18,6 +18,7 @@ use crate::error::{AppError, AppResult}; use crate::state::Shared; use super::message_tool::MessageTool; +use super::preview_tool::PreviewTool; /// The room and its configuration, read fresh for every turn. pub struct TurnConfig { @@ -310,6 +311,9 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App .map_err(|err| AppError::bad_request(format!("provider: {err}")))?; let message_tool: Arc = Arc::new(MessageTool::new(state.clone(), config.room_id.clone())); + let preview_tool: Arc = + Arc::new(PreviewTool::new(state.clone(), config.room_id.clone())); + let extra_tools: Arc = Arc::new(Overlay::new(message_tool, preview_tool)); let max_turn_steps = NonZeroU32::new(config.max_turn_steps).unwrap_or(NonZeroU32::new(48).unwrap()); let mut sections = BTreeMap::new(); @@ -330,7 +334,7 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App max_turn_steps, thinking: ThinkingEffort::Default, tools: Some(shell), - extra_resolver: Some(message_tool), + extra_resolver: Some(extra_tools), shell_env: Default::default(), transcript: Some(Default::default()), summary_worker: None, diff --git a/src/room/mod.rs b/src/room/mod.rs index ff033eb..125d61c 100644 --- a/src/room/mod.rs +++ b/src/room/mod.rs @@ -79,4 +79,5 @@ impl RoomRunner { pub mod agent; pub mod message_tool; +pub mod preview_tool; pub mod runner; diff --git a/src/room/preview_tool.rs b/src/room/preview_tool.rs new file mode 100644 index 0000000..4702e6d --- /dev/null +++ b/src/room/preview_tool.rs @@ -0,0 +1,110 @@ +//! The `preview` tool: point the room's pane at a port or a static build. + +use async_trait::async_trait; +use rhema_core::request::ToolSpec; +use rhema_core::tool::{ReplaySafety, ToolCall, ToolContext, ToolResolver, ToolResult}; +use serde_json::json; + +use crate::models::PreviewTarget; +use crate::state::Shared; + +use super::agent; + +/// The resolver handed to the agent beside `message`. +pub struct PreviewTool { + state: Shared, + room: String, +} + +impl PreviewTool { + /// A tool pointing `room`'s preview. + pub fn new(state: Shared, room: String) -> Self { + Self { state, room } + } +} + +#[async_trait] +impl ToolResolver for PreviewTool { + fn specs(&self) -> Vec { + vec![ToolSpec::new( + "preview", + "Point the room's preview pane at what you changed. Use `path` for a \ + static page (an HTML file, or a folder with index.html): the app reads \ + it over ssh and serves it, no server needed. Use `port` for a dev server \ + already listening in the sandbox. Set exactly one. Point a static preview \ + at a build folder, not the repository root, unless the whole tree is meant \ + to be public.", + json!({ + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "A workspace-relative HTML file or folder with index.html." + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "description": "A port listening on 127.0.0.1 inside the sandbox." + } + } + }), + )] + } + + fn replay_safety(&self, _name: &str) -> ReplaySafety { + ReplaySafety::Unsafe + } + + async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult { + let port = match call.args.get("port") { + None | Some(serde_json::Value::Null) => None, + Some(value) => match value.as_u64().and_then(|port| u16::try_from(port).ok()) { + Some(port) if port > 0 => Some(port), + _ => return ToolResult::failure(call.id, "`port` must be between 1 and 65535"), + }, + }; + let path = match call.args.get("path") { + None | Some(serde_json::Value::Null) => None, + Some(value) => match value.as_str() { + Some(text) if !text.trim().is_empty() => Some(text.trim().to_owned()), + _ => return ToolResult::failure(call.id, "`path` must be a non-empty string"), + }, + }; + let target = match (port, path) { + (Some(port), None) => PreviewTarget::Port { port }, + (None, Some(path)) => { + let (workspace, sandbox_target) = + match agent::load_room_target(&self.state, &self.room) { + Ok(found) => found, + Err(err) => return ToolResult::failure(call.id, err.message), + }; + match crate::preview::static_target(&self.state, &workspace, &sandbox_target, &path) + .await + { + Ok(target) => target, + Err(message) => return ToolResult::failure(call.id, message), + } + } + (Some(_), Some(_)) => { + return ToolResult::failure(call.id, "set `path` or `port`, not both"); + } + (None, None) => { + return ToolResult::failure(call.id, "set `path` or `port`"); + } + }; + if let Err(err) = crate::preview::publish(&self.state, &self.room, &target) { + return ToolResult::failure( + call.id, + format!("could not open the preview: {}", err.message), + ); + } + let answer = match &target { + PreviewTarget::Port { port } => format!("The room preview now shows port {port}."), + PreviewTarget::Static { path, .. } => { + format!("The room preview now serves {path}.") + } + }; + ToolResult::success(call.id, answer) + } +} diff --git a/src/room/prompt.md b/src/room/prompt.md index 1190663..03f0c92 100644 --- a/src/room/prompt.md +++ b/src/room/prompt.md @@ -27,6 +27,19 @@ reading, searching, editing, and running tests. Leave the tree in a state someone else can pick up. When you finish, say which files changed and which checks you ran. +## Preview + +When what you changed is visible, point the room at it with the `preview` +tool. Use `path` for a static page: an HTML file, or a folder with an +`index.html`. The app reads it over ssh and serves it, so there is no server +to start and nothing to keep alive. Point at a build folder, not the whole +repository, unless every file in the tree is meant to be readable through the +preview link. + +Use `port` for a dev server that is already listening on 127.0.0.1 in the +sandbox. Set one of `path` or `port`, never both. The pane opens it for +everyone in the room. + {% if tools %} ## Tools diff --git a/src/util.rs b/src/util.rs index 42e4603..54a1f66 100644 --- a/src/util.rs +++ b/src/util.rs @@ -42,6 +42,23 @@ pub fn member_color(index: usize) -> &'static str { COLORS[index % COLORS.len()] } +/// A workspace-relative path with no escape. Empty names the root. +pub fn safe_rel_path(path: &str) -> Result { + let trimmed = path.trim(); + if trimmed.starts_with('/') { + return Err("path must be relative to the workspace".into()); + } + let normalized = trimmed.trim_matches('/'); + if normalized.split('/').any(|part| part == "..") { + return Err("path escapes the workspace".into()); + } + Ok(if normalized.is_empty() { + ".".to_owned() + } else { + normalized.to_owned() + }) +} + /// `@rhema` in any case, as a whole word. pub fn mentions_agent(text: &str) -> bool { let lower = text.to_lowercase(); @@ -67,6 +84,24 @@ pub fn mentions_agent(text: &str) -> bool { mod tests { use super::*; + #[test] + fn relative_paths_stay_under_the_workspace() { + assert_eq!(safe_rel_path("").unwrap(), "."); + assert_eq!(safe_rel_path("web/dist").unwrap(), "web/dist"); + assert_eq!( + safe_rel_path("/web/dist/").unwrap_err(), + "path must be relative to the workspace" + ); + assert_eq!( + safe_rel_path("web/../secret").unwrap_err(), + "path escapes the workspace" + ); + assert_eq!( + safe_rel_path("..").unwrap_err(), + "path escapes the workspace" + ); + } + #[test] fn mentions_need_a_word_boundary() { assert!(mentions_agent("@rhema fix this")); diff --git a/web/app/assets/css/main.css b/web/app/assets/css/main.css index 1a0a5ca..5be04ae 100644 --- a/web/app/assets/css/main.css +++ b/web/app/assets/css/main.css @@ -1470,6 +1470,15 @@ body.pane-resizing * { border-bottom: 1px solid var(--border); } +.preview-target { + min-width: 0; + overflow: hidden; + color: var(--muted); + font-size: var(--fs-meta); + text-overflow: ellipsis; + white-space: nowrap; +} + .port-field { width: 88px; min-height: 28px; diff --git a/web/app/components/PreviewPane.vue b/web/app/components/PreviewPane.vue index 93f756d..cb35ba1 100644 --- a/web/app/components/PreviewPane.vue +++ b/web/app/components/PreviewPane.vue @@ -1,25 +1,38 @@