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.
This commit is contained in:
vhaudiquet committed 2026-11-28 11:24:57 +01:00
1 parent 5be17cf4ef
commit 36de0aace7
20 files changed
+1026 -125

No files matched your search

+11 -8
View File
@@ -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<room>-p<port>-<hmac>.<preview host>`.
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<room>-p<port>-<expiry>-<hmac>.<preview
host>` for a port, or `r<room>-s<hash>-<expiry>-<hmac>.<preview host>`
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
Generated
+1
View File
@@ -3689,6 +3689,7 @@ dependencies = [
"hyper",
"hyper-util",
"mime_guess",
"percent-encoding",
"rand 0.8.8",
"rhema-bash",
"rhema-core",
+1
View File
@@ -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" }
+34 -16
View File
@@ -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
`<scheme>://r<room>-p<port>-<expiry>-<hmac>.<preview host>/`. 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
`<scheme>://r<room>-p<port>-<expiry>-<hmac>.<preview host>/`.
A static target is served from
`<scheme>://r<room>-s<hash>-<expiry>-<hmac>.<preview host>/`, 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:<port>` 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:<port>` 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
+39 -25
View File
@@ -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:<port>` and `127.0.0.1:<port>` 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.<domain>/room/<id>/
preview https://r<room>-p<port>-<expiry>-<sig>.preview.<domain>/
https://r<room>-s<hash>-<expiry>-<sig>.preview.<domain>/
```
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.<domain>`.
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 `*.<preview host>` 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
`*.<preview host>` 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
+2 -15
View File
@@ -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<String> {
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(
+17 -5
View File
@@ -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<u16>,
}
/// 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<Shared>,
@@ -383,12 +386,21 @@ pub async fn preview(
axum::extract::Query(query): axum::extract::Query<PreviewQuery>,
) -> AppResult<Json<Value>> {
member_of(&state, &room, &user.user.id)?;
let port = query.port.unwrap_or(3000);
if port == 0 {
let target = match query.port {
Some(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 })))
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.
+10
View File
@@ -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,
+19
View File
@@ -67,6 +67,25 @@ pub struct User {
pub avatar_updated_at: Option<i64>,
}
/// 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)]
+593 -36
View File
@@ -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<room>-p<port>-<sig>.<preview host>` routes to 127.0.0.1:<port>
//! 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<room>-p<port>-<expiry>-<sig>.<preview host>` routes to
//! 127.0.0.1:<port> inside the room's sandbox over the same ssh connection
//! settings the agent uses. `r<room>-s<hash>-<expiry>-<sig>.<preview host>`
//! 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<String> {
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<String> {
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<room>-p<port>-<expiry>-<sig>` 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<room>-p<port>-<expiry>-<sig>` or
/// `r<room>-s<hash>-<expiry>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<HostClaim> {
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<i64>,
Option<String>,
Option<String>,
Option<String>,
);
/// The room's current preview target, if one is set.
pub fn load_target(state: &Shared, room: &str) -> AppResult<Option<PreviewTarget>> {
let row: Option<PreviewRow> = 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<PreviewTarget, String> {
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<String, String> {
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<Body>) -> Response {
let host = request
.headers()
@@ -147,18 +403,25 @@ pub async fn proxy(state: Shared, request: Request<Body>) -> 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),
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,
@@ -166,6 +429,11 @@ pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
)
.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<Body>,
) -> Result<Response, (StatusCode, String)> {
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<String, (StatusCode, String)> {
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<u8>),
Missing,
Large,
}
fn parse_static_output(stdout: Vec<u8>) -> Option<StaticRead> {
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<html></html>".to_vec()),
Some(StaticRead::Body(body)) if body == b"<html></html>"
));
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"));
+6 -2
View File
@@ -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<dyn ToolResolver> =
Arc::new(MessageTool::new(state.clone(), config.room_id.clone()));
let preview_tool: Arc<dyn ToolResolver> =
Arc::new(PreviewTool::new(state.clone(), config.room_id.clone()));
let extra_tools: Arc<dyn ToolResolver> = 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,
+1
View File
@@ -79,4 +79,5 @@ impl RoomRunner {
pub mod agent;
pub mod message_tool;
pub mod preview_tool;
pub mod runner;
+110
View File
@@ -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<ToolSpec> {
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)
}
}
+13
View File
@@ -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
+35
View File
@@ -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<String, String> {
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"));
+9
View File
@@ -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;
+106 -15
View File
@@ -1,25 +1,38 @@
<script setup lang="ts">
import { ref } from 'vue'
import { Maximize2, Minimize2, X } from 'lucide-vue-next'
import { computed, ref, watch } from 'vue'
import { Maximize2, Minimize2, RefreshCw, X } from 'lucide-vue-next'
import type { PreviewResponse, PreviewTarget } from '~/types'
const props = defineProps<{ roomId: string }>()
const props = defineProps<{ roomId: string; target: PreviewTarget | null }>()
const port = ref<number | string>(3000)
const url = ref('')
const frameKey = ref(0)
const loading = ref(false)
const error = ref('')
const fullscreen = ref(false)
const manual = ref(false)
async function load() {
const value = Number(port.value)
if (!Number.isInteger(value) || value < 1 || value > 65535) {
error.value = 'Enter a port between 1 and 65535.'
return
}
const staticTarget = computed(() =>
!manual.value && props.target?.kind === 'static' ? props.target : null,
)
const targetPath = computed(() => staticTarget.value?.path ?? '')
const actionLabel = computed(() => (loading.value ? 'Opening' : url.value ? 'Reload' : 'Go'))
const frameTitle = computed(() => {
if (props.target?.kind === 'static' && !manual.value) return `Preview of ${props.target.path}`
return `Preview on port ${port.value}`
})
const emptyText = computed(() =>
props.target
? 'The preview has not loaded.'
: 'No preview yet. Enter a port, or ask @rhema to open one.',
)
async function request(query: string) {
loading.value = true
error.value = ''
try {
const response = await fetch(`/api/rooms/${encodeURIComponent(props.roomId)}/preview?port=${value}`, {
const response = await fetch(`/api/rooms/${encodeURIComponent(props.roomId)}/preview${query}`, {
credentials: 'include',
headers: { Accept: 'application/json' },
})
@@ -41,7 +54,8 @@ async function load() {
if (!body || typeof body !== 'object' || typeof (body as { url?: unknown }).url !== 'string') {
throw new Error('The server returned no preview address.')
}
url.value = (body as { url: string }).url
url.value = (body as PreviewResponse).url
frameKey.value += 1
} catch (err) {
url.value = ''
error.value = err instanceof Error ? err.message : 'The preview could not be opened.'
@@ -50,14 +64,79 @@ async function load() {
}
}
function openTarget() {
if (!props.target) return openPort()
manual.value = false
return request('')
}
function openPort() {
const value = Number(port.value)
if (!Number.isInteger(value) || value < 1 || value > 65535) {
error.value = 'Enter a port between 1 and 65535.'
return
}
manual.value = true
return request(`?port=${value}`)
}
function open() {
return manual.value || !props.target ? openPort() : openTarget()
}
function startManual() {
manual.value = true
url.value = ''
error.value = ''
if (props.target?.kind === 'port') port.value = props.target.port
}
function useTarget() {
manual.value = false
if (props.target?.kind === 'port') port.value = props.target.port
void openTarget()
}
function toggleFullscreen() {
fullscreen.value = !fullscreen.value
}
watch(
() => props.target,
(target) => {
manual.value = false
if (!target) {
url.value = ''
error.value = ''
return
}
if (target.kind === 'port') port.value = target.port
void openTarget()
},
{ immediate: true },
)
</script>
<template>
<div class="preview-wrap" :class="{ 'preview-full': fullscreen }">
<div class="preview-bar">
<template v-if="staticTarget">
<span class="preview-target mono" :title="targetPath">{{ targetPath }}</span>
<button type="button" class="btn btn-sm btn-quiet" @click="startManual">
Port
</button>
<button
type="button"
class="icon-btn"
aria-label="Reload preview"
title="Reload preview"
:disabled="loading"
@click="openTarget"
>
<RefreshCw :size="16" aria-hidden="true" />
</button>
</template>
<template v-else>
<label class="sr-only" for="preview-port">Port</label>
<input
id="preview-port"
@@ -67,10 +146,21 @@ function toggleFullscreen() {
min="1"
max="65535"
aria-label="Preview port"
@input="manual = true"
@keyup.enter="open"
>
<button type="button" class="btn btn-sm" :disabled="loading" @click="load">
{{ loading ? 'Opening' : url ? 'Reload' : 'Go' }}
<button type="button" class="btn btn-sm" :disabled="loading" @click="open">
{{ actionLabel }}
</button>
<button
v-if="target && manual"
type="button"
class="btn btn-sm btn-quiet"
@click="useTarget"
>
Room preview
</button>
</template>
<div class="room-topbar-spacer" />
<button
type="button"
@@ -97,14 +187,15 @@ function toggleFullscreen() {
<div v-if="url" class="preview-frame-wrap">
<iframe
:key="frameKey"
class="preview-frame"
:src="url"
:title="`Preview on port ${port}`"
:title="frameTitle"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
</div>
<p v-else-if="!error" class="preview-message">
Enter the port the room serves and choose Go.
{{ emptyText }}
</p>
</div>
</template>
+3 -2
View File
@@ -1,10 +1,11 @@
<script setup lang="ts">
import { ref } from 'vue'
import { Eye, FolderTree, PanelRightClose, Terminal } from 'lucide-vue-next'
import type { PreviewTarget } from '~/types'
type Tab = 'terminal' | 'preview' | 'files'
defineProps<{ roomId: string; roomName: string }>()
defineProps<{ roomId: string; roomName: string; preview: PreviewTarget | null }>()
const emit = defineEmits<{ close: [] }>()
const tab = ref<Tab>('files')
@@ -49,7 +50,7 @@ const tabs: Array<{ id: Tab; label: string; icon: typeof Terminal }> = [
<div id="pane-panel" class="pane-body" role="tabpanel" :aria-labelledby="`pane-tab-${tab}`">
<FilesPane v-if="tab === 'files'" :room-id="roomId" :room-name="roomName" />
<TerminalPane v-else-if="tab === 'terminal'" :room-id="roomId" />
<PreviewPane v-else :room-id="roomId" />
<PreviewPane v-else :room-id="roomId" :target="preview" />
</div>
</aside>
</template>
+10 -1
View File
@@ -8,6 +8,7 @@ import type {
MessagePage,
NoticeData,
PresencePeer,
PreviewTarget,
Room,
RoomDetailResponse,
StepStartData,
@@ -36,6 +37,7 @@ const detail = ref<RoomDetailResponse | null>(null)
const detailLoading = ref(true)
const detailError = ref('')
const previewTarget = ref<PreviewTarget | null>(null)
const messages = ref<Message[]>([])
const notices = ref<Array<{ seq: number; level: string; text: string }>>([])
const activities = ref<TurnActivity[]>([])
@@ -96,7 +98,7 @@ let presenceSocket: WebSocket | null = null
let presenceTimer: number | null = null
let presenceRetry = 0
const DURABLE_KINDS = new Set(['message', 'notice', 'turn_start', 'turn_end', 'tool_result'])
const DURABLE_KINDS = new Set(['message', 'notice', 'turn_start', 'turn_end', 'tool_result', 'preview'])
const BACKOFF = [1000, 2000, 5000, 10000]
useHead({
@@ -235,6 +237,11 @@ function handleEnvelope(envelope: Envelope) {
case 'message':
addMessage(eventData<Message>(envelope))
break
case 'preview': {
const data = eventData<PreviewTarget>(envelope)
if (data && (data.kind === 'port' || data.kind === 'static')) previewTarget.value = data
break
}
case 'notice': {
const data = eventData<NoticeData>(envelope)
addNotice(envelope.seq, data.level, data.text)
@@ -638,6 +645,7 @@ async function loadDetail() {
try {
const response = await api.get<RoomDetailResponse>(`/rooms/${roomId.value}`)
detail.value = response
previewTarget.value = response.preview ?? null
if (onlineIds.value.length === 0) {
onlineIds.value = response.members.filter((member) => member.online).map((member) => member.id)
}
@@ -863,6 +871,7 @@ onBeforeUnmount(() => {
v-if="paneOpen"
:room-id="detail.room.id"
:room-name="detail.room.name"
:preview="previewTarget"
@close="paneOpen = false"
/>
</div>
+6
View File
@@ -78,9 +78,14 @@ export interface Me {
color: string
}
export type PreviewTarget =
| { kind: 'port'; port: number }
| { kind: 'static'; path: string; root: string; entry: string }
export interface RoomDetailResponse {
room: Room
members: Member[]
preview: PreviewTarget | null
me: Me
}
@@ -214,6 +219,7 @@ export interface GitSummaryResponse {
export interface PreviewResponse {
url: string
target: PreviewTarget
}
export interface PresencePeer {