Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md

- luxe remote puts the sessions on your computer in reach of your own phone or tablet over
  Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a
  paired device and your own Tailscale login.
- luxe join lets another program on the same machine join a running session over the RPC protocol.
- An AGENTS.md in a subfolder reaches the model the first time it works there.
- Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing.
- A session is open in one Luxe at a time, web_search shares results across its phrasings, and a
  grep glob starting with ! excludes.

The CHANGELOG has the full list.
This commit is contained in:
Evan Whittaker
2026-10-20 02:40:13 -05:00
parent 99e30d6d0f
commit d2129a886f
423 changed files with 31666 additions and 1669 deletions

View File

@@ -0,0 +1,146 @@
//! Access — who may reach the bridge, checked on every request.
//!
//! Two layers, both required for anything that touches a session:
//!
//! - **A tailnet login on the allowlist.** Tailscale Serve sets `Tailscale-User-Login` on what it
//! forwards and drops any copy a client sent, so the header names the person behind the request.
//! A request without it did not come through Serve, and is refused.
//! - **A paired device.** The header names a person, not a device, and any process on this machine
//! can reach the loopback port and write the header itself. The device's own credential, from
//! pairing, is what a process on this machine doesn't have.
//!
//! A browser also says which page sent a request (`Origin`), and one from another site is refused,
//! so a page elsewhere can't use the device's cookie to open a session socket.
use axum::extract::{Request, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use std::sync::Arc;
use crate::devices::Device;
use crate::routes::Bridged;
/// The header Tailscale Serve sets to the signed-in tailnet user.
pub(crate) const LOGIN_HEADER: &str = "tailscale-user-login";
/// The cookie a paired device carries its credential in.
pub(crate) const CREDENTIAL_COOKIE: &str = "luxe_device";
/// The tailnet login behind a request, once checked.
#[derive(Debug, Clone)]
pub(crate) struct Login(pub(crate) String);
/// Why a request was turned away.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Refusal {
NotThroughTailscale,
LoginNotAllowed(String),
CrossSite,
NotPaired,
}
impl IntoResponse for Refusal {
fn into_response(self) -> Response {
let (status, reason) = match self {
Self::NotThroughTailscale => (
StatusCode::UNAUTHORIZED,
"this bridge answers only through Tailscale Serve".to_string(),
),
Self::LoginNotAllowed(login) => {
(StatusCode::FORBIDDEN, format!("{login} is not allowed on this bridge"))
}
Self::CrossSite => (StatusCode::FORBIDDEN, "cross-site requests are refused".into()),
Self::NotPaired => (StatusCode::UNAUTHORIZED, "this device isn't paired".into()),
};
(status, reason).into_response()
}
}
/// The allowed tailnet login a request came from, or why it has none.
pub(crate) fn tailnet_login(headers: &HeaderMap, allowed: &[String]) -> Result<Login, Refusal> {
let login = headers
.get(LOGIN_HEADER)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|login| !login.is_empty())
.ok_or(Refusal::NotThroughTailscale)?;
// an email address, which Tailscale has reported in different cases for the same account
let login_folded = login.to_lowercase();
if !allowed.iter().any(|allowed| allowed.to_lowercase() == login_folded) {
return Err(Refusal::LoginNotAllowed(login.to_string()));
}
Ok(Login(login.to_string()))
}
/// Refuses a request a page on another site sent. One with no `Origin` is not from a browser
/// page, so it carries no cookie it didn't own.
pub(crate) fn same_site(headers: &HeaderMap) -> Result<(), Refusal> {
let Some(origin) = headers.get(header::ORIGIN).and_then(|value| value.to_str().ok()) else {
return Ok(());
};
let authority = origin.split_once("://").map_or(origin, |(_, rest)| rest);
// Serve may hand the original host on in either
let mut hosts = [header::HOST.as_str(), "x-forwarded-host"]
.into_iter()
.filter_map(|name| headers.get(name)?.to_str().ok());
if hosts.any(|host| host.eq_ignore_ascii_case(authority)) {
return Ok(());
}
Err(Refusal::CrossSite)
}
/// The device credential a request carries, if any.
pub(crate) fn credential(headers: &HeaderMap) -> Option<&str> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|cookies| cookies.split(';'))
.filter_map(|cookie| cookie.trim().split_once('='))
.find_map(|(name, value)| (name == CREDENTIAL_COOKIE).then_some(value))
}
/// The cookie that pairs a device: unreadable to scripts, HTTPS only, never sent by another site,
/// and kept for as long as a browser keeps any cookie.
pub(crate) fn credential_cookie(credential: &str) -> String {
format!(
"{CREDENTIAL_COOKIE}={credential}; HttpOnly; Secure; SameSite=Strict; Path=/; \
Max-Age=34560000"
)
}
/// Every route: a tailnet login on the allowlist, from this site.
pub(crate) async fn require_login(
State(bridged): State<Arc<Bridged>>,
mut request: Request,
next: Next,
) -> Response {
let checked = tailnet_login(request.headers(), &bridged.logins)
.and_then(|login| same_site(request.headers()).map(|()| login));
match checked {
Ok(login) => {
request.extensions_mut().insert(login);
next.run(request).await
}
Err(refusal) => refusal.into_response(),
}
}
/// Session routes: a paired device as well.
pub(crate) async fn require_device(
State(bridged): State<Arc<Bridged>>,
mut request: Request,
next: Next,
) -> Response {
let Some(device) = paired_device(&bridged, request.headers()).await else {
return Refusal::NotPaired.into_response();
};
request.extensions_mut().insert(device);
next.run(request).await
}
async fn paired_device(bridged: &Bridged, headers: &HeaderMap) -> Option<Device> {
let credential = credential(headers)?.to_string();
let devices = bridged.devices.clone();
tokio::task::spawn_blocking(move || devices.holder(&credential)).await.ok().flatten()
}

View File

@@ -0,0 +1,213 @@
//! App — the phone app's files, served from the binary.
//!
//! Plain HTML, CSS and ES modules from `app/`, with nothing built: what is in the repository is what
//! a phone runs. A release build embeds the folder and a debug build reads it from disk, so editing
//! the app takes a reload.
//!
//! The app shows what a model wrote, so the page carries a Content-Security-Policy that runs only
//! the app's own scripts. The import map is the one inline script, and the policy names it by hash,
//! computed from the page as served so the two can't drift apart.
use axum::extract::{Path, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use base64::Engine as _;
use luxe_core::config::{DockConfig, DockMode, DockPosition, StatuslineStyle};
use luxe_core::theme::ColorValue;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::Arc;
use crate::routes::Bridged;
#[derive(rust_embed::Embed)]
#[folder = "app/"]
pub(crate) struct AppFiles;
/// The status bar style the page is written with; the page's own, for a dark theme.
const DARK_STATUS_BAR: &str = "content=\"black-translucent\"";
/// The page's `<html>` tag as written; the served page adds where the dock starts and how
/// headings are cut.
const HTML_TAG: &str = "<html lang=\"en\">";
/// The page's title as written, and the home screen name iOS suggests; a named bridge puts the
/// computer in both.
const PAGE_TITLE: &str = "<title>Luxe</title>";
const HOME_SCREEN_TITLE: &str = "name=\"apple-mobile-web-app-title\" content=\"Luxe\"";
/// What the page takes from your own config: a project's can't reach here.
#[derive(Default)]
struct PageLook {
theme: HashMap<String, ColorValue>,
dock: DockConfig,
statusline: StatuslineStyle,
}
fn page_look() -> PageLook {
let config = luxe_core::config::Config::load_global();
let theme = config.resolved_theme(&luxe_core::theme::ThemeRegistry::installed());
PageLook { theme, dock: config.dock, statusline: config.statusline.style() }
}
/// `/`: the app's page, with the status bar style your theme wants, named for the computer.
pub(crate) async fn index(State(bridged): State<Arc<Bridged>>) -> Response {
let Some(page) = AppFiles::get("index.html") else {
return (StatusCode::INTERNAL_SERVER_ERROR, "the app is missing from this build")
.into_response();
};
let look = tokio::task::spawn_blocking(page_look).await.unwrap_or_default();
let page = themed_page(&String::from_utf8_lossy(&page.data), &look);
let page = named_page(&page, bridged.machine.as_deref());
let policy = content_security_policy(&page);
let mut response = ([(header::CONTENT_TYPE, "text/html; charset=utf-8")], page).into_response();
insert(response.headers_mut(), header::CONTENT_SECURITY_POLICY, &policy);
insert(response.headers_mut(), header::CACHE_CONTROL, "no-cache");
response
}
/// The page as `look` wants it: the status bar style iOS reads when the app is added, the dock's
/// mode and side, which the app starts from as the TUI starts from them, and whether headings are
/// cut into slabs, which `statusline.style` decides for the TUI's.
fn themed_page(page: &str, look: &PageLook) -> String {
let style = crate::home_screen::status_bar_style(&look.theme);
page.replacen(DARK_STATUS_BAR, &format!("content=\"{style}\""), 1).replacen(
HTML_TAG,
&html_tag(look),
1,
)
}
/// The page named for the computer `machine`: its title, the name iOS suggests when it's added to
/// the home screen, and a `luxe-machine` meta the app reads to say which computer it reaches.
/// Unnamed, it stays plain Luxe.
fn named_page(page: &str, machine: Option<&str>) -> String {
let Some(machine) = machine else {
return page.to_owned();
};
let name = crate::render::escape(machine);
let title = crate::render::escape(&crate::home_screen::app_name(Some(machine)));
page.replacen(
PAGE_TITLE,
&format!("<title>{title}</title>\n<meta name=\"luxe-machine\" content=\"{name}\">"),
1,
)
.replacen(
HOME_SCREEN_TITLE,
&format!("name=\"apple-mobile-web-app-title\" content=\"{name}\""),
1,
)
}
fn html_tag(look: &PageLook) -> String {
let (mode, side) = dock_attributes(&look.dock);
let headings = match look.statusline {
StatuslineStyle::Flat => "flat",
StatuslineStyle::Slab | StatuslineStyle::Unknown => "slab",
};
format!(
"<html lang=\"en\" data-dock-mode=\"{mode}\" data-dock-side=\"{side}\" \
data-headings=\"{headings}\">"
)
}
fn dock_attributes(dock: &DockConfig) -> (&'static str, &'static str) {
let mode = match dock.mode() {
DockMode::Shown => "shown",
DockMode::Hidden => "hidden",
DockMode::Auto | DockMode::Unknown => "auto",
};
let side = match dock.position() {
DockPosition::Right => "right",
DockPosition::Left | DockPosition::Unknown => "left",
};
(mode, side)
}
/// `/app/{*path}`: one of the app's files, answered with 304 when the phone already has it.
pub(crate) async fn file(Path(path): Path<String>, request: HeaderMap) -> Response {
let Some(file) = AppFiles::get(&path) else {
return (StatusCode::NOT_FOUND, format!("no app file {path}")).into_response();
};
let tag = format!("\"{}\"", base16ct::lower::encode_string(&file.metadata.sha256_hash()));
let cached =
request.get(header::IF_NONE_MATCH).is_some_and(|sent| sent.as_bytes() == tag.as_bytes());
let mut response =
if cached { StatusCode::NOT_MODIFIED.into_response() } else { file.data.into_response() };
let headers = response.headers_mut();
insert(headers, header::CONTENT_TYPE, content_type(&path));
insert(headers, header::ETAG, &tag);
// revalidate on every load, which a 304 makes cheap, so a phone never runs a stale app
insert(headers, header::CACHE_CONTROL, "no-cache");
insert(headers, header::X_CONTENT_TYPE_OPTIONS, "nosniff");
response
}
/// `/service-worker.js`: the app's service worker, served from the top so it covers the whole app
/// (a worker reaches only as far as the folder it's served from).
pub(crate) async fn service_worker(request: HeaderMap) -> Response {
file(Path("worker/service-worker.js".into()), request).await
}
/// `/theme.css`: the active theme's colors, read on each load so the phone follows a new theme.
pub(crate) async fn theme() -> Response {
let css = tokio::task::spawn_blocking(active_theme_css).await.unwrap_or_else(|error| {
tracing::warn!(%error, "could not read the theme");
String::new()
});
let mut response = ([(header::CONTENT_TYPE, "text/css; charset=utf-8")], css).into_response();
insert(response.headers_mut(), header::CACHE_CONTROL, "no-cache");
response
}
fn active_theme_css() -> String {
luxe_core::theme::css::stylesheet(&active_theme())
}
/// The theme the terminal would be drawn in from your own config: a project's can't reach here.
pub(crate) fn active_theme() -> HashMap<String, ColorValue> {
let registry = luxe_core::theme::ThemeRegistry::installed();
luxe_core::config::Config::load_global().resolved_theme(&registry)
}
fn insert(headers: &mut HeaderMap, name: header::HeaderName, value: &str) {
if let Ok(value) = HeaderValue::from_str(value) {
headers.insert(name, value);
}
}
/// The type a file is served as, by its extension. Only what `app/` holds.
fn content_type(path: &str) -> &'static str {
match path.rsplit_once('.').map(|(_, extension)| extension) {
Some("js" | "mjs") => "text/javascript; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("html") => "text/html; charset=utf-8",
Some("json") => "application/json",
Some("webmanifest") => "application/manifest+json",
Some("svg") => "image/svg+xml",
Some("png") => "image/png",
Some("woff2") => "font/woff2",
_ => "text/plain; charset=utf-8",
}
}
/// The page's policy: the app's own files, its import map by hash, and nothing from elsewhere.
pub(crate) fn content_security_policy(page: &str) -> String {
let import_map = inline_script(page, "<script type=\"importmap\">").unwrap_or_default();
let digest = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(import_map));
format!(
"default-src 'none'; script-src 'self' 'sha256-{digest}'; style-src 'self'; \
img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; manifest-src 'self'; \
base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
)
}
/// The text of the inline script that opens with `opening`, exactly as the browser hashes it.
fn inline_script<'a>(page: &'a str, opening: &str) -> Option<&'a str> {
let start = page.find(opening)? + opening.len();
let length = page[start..].find("</script>")?;
Some(&page[start..start + length])
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,153 @@
use super::*;
#[derive(serde::Deserialize)]
struct Vendored {
file: String,
version: String,
sha256: String,
}
fn manifest() -> Vec<Vendored> {
let manifest = AppFiles::get("vendor/manifest.json").expect("the vendor manifest");
serde_json::from_slice(&manifest.data).expect("a readable manifest")
}
/// Every vendored file is the one its package published, and every one is listed.
///
/// The break this catches: a hand edit to a vendored file, which then ships under the upstream
/// version's name, or a file added beside them that nothing vouches for.
#[test]
fn vendored_files_match_their_manifest() {
let listed = manifest();
for entry in &listed {
let file = AppFiles::get(&format!("vendor/{}", entry.file)).expect("a listed file");
let digest = base16ct::lower::encode_string(&Sha256::digest(&file.data));
assert_eq!(digest, entry.sha256, "{} isn't {}'s published file", entry.file, entry.version);
}
let modules =
AppFiles::iter().filter(|path| path.starts_with("vendor/") && path.ends_with(".mjs"));
for module in modules {
let file = module.trim_start_matches("vendor/");
assert!(listed.iter().any(|entry| entry.file == file), "{file} isn't in the manifest");
}
}
/// Each font the stylesheet asks for is in the build, with its license beside it.
///
/// The break this catches: renaming a subset in `scripts/remote-fonts.sh` without the stylesheet,
/// so the phone quietly falls back to its own monospace face; or a font shipped without the OFL
/// text its license requires to travel with it.
#[test]
fn every_font_the_stylesheet_names_is_embedded() {
let style = AppFiles::get("style.css").expect("the stylesheet");
let style = String::from_utf8_lossy(&style.data);
let named: Vec<&str> =
style.split("url(\"").skip(1).filter_map(|rest| rest.split('"').next()).collect();
assert!(named.len() >= 3, "the stylesheet names no fonts: {named:?}");
for path in named {
assert!(AppFiles::get(path).is_some(), "{path} is named but not embedded");
}
for license in ["fonts/OFL-JetBrainsMono.txt", "fonts/OFL-AdwaitaMono.txt"] {
assert!(AppFiles::get(license).is_some(), "{license} is missing");
}
}
/// The policy names the import map by the hash of exactly the bytes between its tags.
///
/// The break this catches: hashing the tags, trimmed text or the whole page, which the browser
/// doesn't match, so the import map is blocked and the app never starts. The hash is pinned from
/// `sha256 | base64` of the literal.
#[test]
fn the_policy_allows_the_import_map_by_its_hash() {
let page = r#"<head><script type="importmap">{"imports":{"preact":"/app/vendor/preact.mjs"}}</script>
<script type="module" src="/app/main.js"></script></head>"#;
let policy = content_security_policy(page);
assert!(
policy.contains("script-src 'self' 'sha256-opQT9hhH9RSRDfDGg0J92nWa2thMilr5GvqVi+cOsyE='"),
"{policy}"
);
}
/// The policy keeps the page to its own origin.
///
/// The break this catches: a policy that lets a script, style or connection come from anywhere,
/// so markup a model slips into the transcript can load code that drives the session.
#[test]
fn the_policy_allows_nothing_from_elsewhere() {
let policy = content_security_policy("");
for directive in
["default-src 'none'", "style-src 'self'", "connect-src 'self'", "base-uri 'none'"]
{
assert!(policy.contains(directive), "{directive} is missing from {policy}");
}
assert!(!policy.contains("unsafe-inline") && !policy.contains('*'), "{policy}");
}
/// The page a light theme gets asks iOS for dark status bar text, and a dark one keeps its own.
///
/// The break this catches: the page's meta reworded so the swap no longer finds it, leaving
/// white status bar text over a light theme's header.
#[test]
fn the_status_bar_follows_the_theme() {
let page = AppFiles::get("index.html").expect("the page");
let page = String::from_utf8_lossy(&page.data);
let meta =
|style: &str| format!("name=\"apple-mobile-web-app-status-bar-style\" content=\"{style}\"");
let look = |color| PageLook {
theme: HashMap::from([("background".to_string(), color)]),
..PageLook::default()
};
let light = themed_page(&page, &look(ColorValue::Rgb(250, 250, 245)));
assert!(light.contains(&meta("default")), "{light}");
let dark = themed_page(&page, &look(ColorValue::Rgb(18, 16, 14)));
assert!(dark.contains(&meta("black-translucent")), "{dark}");
}
/// The page carries the dock's mode and side from the config, and the TUI's defaults without one.
///
/// The break this catches: the page's `<html>` tag reworded so the swap no longer finds it, or a
/// config's side or mode dropped, so the phone's dock ignores where you keep the TUI's.
#[test]
fn the_page_says_where_the_dock_starts() {
let page = AppFiles::get("index.html").expect("the page");
let page = String::from_utf8_lossy(&page.data);
let plain = themed_page(&page, &PageLook::default());
assert!(plain.contains(r#"data-dock-mode="auto" data-dock-side="left""#), "{plain}");
let dock = DockConfig { mode: Some(DockMode::Hidden), position: Some(DockPosition::Right) };
let configured = themed_page(&page, &PageLook { dock, ..PageLook::default() });
assert!(configured.contains(r#"data-dock-mode="hidden" data-dock-side="right""#));
let dock = DockConfig { mode: Some(DockMode::Shown), position: None };
let shown = themed_page(&page, &PageLook { dock, ..PageLook::default() });
assert!(shown.contains(r#"data-dock-mode="shown""#));
}
/// The page cuts headings into slabs, as the TUI does, unless `statusline.style` is flat.
///
/// The break this catches: a flat config ignored, so the phone draws slabs the TUI doesn't, or the
/// default made flat.
#[test]
fn the_page_says_how_headings_are_cut() {
let page = AppFiles::get("index.html").expect("the page");
let page = String::from_utf8_lossy(&page.data);
let plain = themed_page(&page, &PageLook::default());
assert!(plain.contains(r#"data-headings="slab""#), "{plain}");
let flat = PageLook { statusline: StatuslineStyle::Flat, ..PageLook::default() };
assert!(themed_page(&page, &flat).contains(r#"data-headings="flat""#));
}
/// A named bridge's page carries the computer in its title, the name iOS suggests for the home
/// screen, and the meta the app reads; an unnamed one is the page as written.
///
/// The break this catches: the page's title or home screen meta reworded so the swap finds
/// nothing, leaving two computers' apps both "Luxe", or a name put in unescaped.
#[test]
fn the_page_is_named_for_its_computer() {
let page = AppFiles::get("index.html").expect("the page");
let page = String::from_utf8_lossy(&page.data);
let named = named_page(&page, Some("desk"));
assert!(named.contains("<title>Luxe \u{00b7} desk</title>"), "{named}");
assert!(named.contains(r#"name="apple-mobile-web-app-title" content="desk""#));
assert!(named.contains(r#"<meta name="luxe-machine" content="desk">"#));
assert!(named_page(&page, Some("a\"b")).contains(r#"content="a&quot;b""#));
assert_eq!(named_page(&page, None), page);
}

View File

@@ -0,0 +1,211 @@
//! Devices — the phones and tablets paired with this machine, and the invitations that pair them.
//!
//! An invitation is one use and ten minutes. Redeeming it gives the device a credential of its own,
//! which the host keeps only as a digest, so the file holds nothing a reader could sign in with.
//! The file is shared between the running bridge and `luxe remote devices`/`pair`, so every
//! change goes through core's locked read-modify-write and the bridge reads it fresh each time:
//! a device revoked from another terminal is refused on its next request.
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use luxe_core::json_file::{FileError, FileMode, JsonFile};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::secrets::{digest, random_id, random_secret};
use crate::RemoteError;
/// How long an invitation can be redeemed for.
pub const INVITATION_LIFETIME_SECS: u64 = 10 * 60;
/// A paired phone or tablet.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Device {
/// Short id to revoke it by
pub id: String,
/// What it called itself when it paired
pub name: String,
/// The tailnet login that paired it
pub login: String,
/// When it paired, in seconds since the Unix epoch
pub paired_at: u64,
credential_sha256: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
push: Option<crate::push::Subscription>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Invitation {
token_sha256: String,
expires_at: u64,
}
/// What `remote.json` holds.
#[derive(Debug, Default, Serialize, Deserialize)]
struct Registry {
#[serde(default)]
devices: Vec<Device>,
#[serde(default)]
invitations: Vec<Invitation>,
/// The bridge's push signing key, made when a device first asks for it
#[serde(default, skip_serializing_if = "Option::is_none")]
push_key: Option<KeptKey>,
}
/// A private key as the file keeps it, base64url PKCS#8, which never prints.
#[derive(Clone, Serialize, Deserialize)]
#[serde(transparent)]
struct KeptKey(String);
impl std::fmt::Debug for KeptKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("KeptKey(..)")
}
}
/// Why an invitation was turned down.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PairingError {
/// Never issued, already used, or expired: the three look the same on purpose
#[error(
"this invitation has expired or was already used; run `luxe remote pair` for a new one"
)]
InvitationUnusable,
}
impl Registry {
fn invite(&mut self, token: &str, now: u64) {
self.forget_expired(now);
let expires_at = now + INVITATION_LIFETIME_SECS;
self.invitations.push(Invitation { token_sha256: digest(token), expires_at });
}
/// Trades `token` for the `paired` device, spending the invitation.
fn redeem(&mut self, token: &str, paired: Device, now: u64) -> Result<Device, PairingError> {
self.forget_expired(now);
let wanted = digest(token);
let at = self.invitations.iter().position(|invitation| invitation.token_sha256 == wanted);
let Some(at) = at else {
return Err(PairingError::InvitationUnusable);
};
self.invitations.remove(at);
self.devices.push(paired.clone());
Ok(paired)
}
fn holder(&self, credential: &str) -> Option<&Device> {
let wanted = digest(credential);
self.devices.iter().find(|device| device.credential_sha256 == wanted)
}
fn revoke(&mut self, id: &str) -> Option<Device> {
let at = self.devices.iter().position(|device| device.id == id)?;
Some(self.devices.remove(at))
}
fn forget_expired(&mut self, now: u64) {
self.invitations.retain(|invitation| invitation.expires_at > now);
}
}
/// The paired devices and open invitations, in a file only this user can read.
#[derive(Debug, Clone)]
pub struct DeviceBook {
file: JsonFile,
}
impl DeviceBook {
/// The book in `path`, created on first write.
pub fn at(path: PathBuf) -> Self {
Self { file: JsonFile::new(path, FileMode::OwnerOnly) }
}
/// Where it lives unless told otherwise: `remote.json` beside Luxe's other settings.
pub fn default_path() -> PathBuf {
luxe_core::user_dirs::luxe_config_dir().join("remote.json")
}
/// A new invitation, good for one device for ten minutes. The token is returned once and kept
/// only as a digest.
pub fn invite(&self) -> Result<String, RemoteError> {
let token = random_secret();
self.change(|registry| registry.invite(&token, now()))?;
Ok(token)
}
/// Every paired device, oldest first.
pub fn devices(&self) -> Vec<Device> {
self.load().devices
}
/// Unpairs the device with this id, returning it, or `None` when there is no such device.
pub fn revoke(&self, id: &str) -> Result<Option<Device>, RemoteError> {
self.change(|registry| registry.revoke(id))
}
/// Redeems `token` for a new device, returning it and the credential it signs in with.
pub(crate) fn pair(
&self,
token: &str,
name: &str,
login: &str,
) -> Result<(Device, String), RemoteError> {
let credential = random_secret();
let paired = Device {
id: random_id(),
name: name.to_string(),
login: login.to_string(),
paired_at: now(),
credential_sha256: digest(&credential),
push: None,
};
let device = self.change(|registry| registry.redeem(token, paired, now()))??;
Ok((device, credential))
}
/// The device `credential` belongs to.
pub(crate) fn holder(&self, credential: &str) -> Option<Device> {
self.load().holder(credential).cloned()
}
fn load(&self) -> Registry {
let Some(map) = self.file.read() else {
return Registry::default();
};
serde_json::from_value(Value::Object(map))
.inspect_err(|error| tracing::warn!(%error, "the paired-device file doesn't read"))
.unwrap_or_default()
}
fn change<T>(&self, edit: impl FnOnce(&mut Registry) -> T) -> Result<T, RemoteError> {
let path = self.file.path().to_path_buf();
let outcome = self.file.modify(|map| {
let mut registry: Registry = serde_json::from_value(Value::Object(std::mem::take(map)))
.map_err(|error| FileError::Unparseable {
path,
reason: format!("not a paired-device list ({error})"),
})?;
let outcome = edit(&mut registry);
*map = into_map(&registry);
Ok(outcome)
})?;
Ok(outcome)
}
}
fn into_map(registry: &Registry) -> Map<String, Value> {
match serde_json::to_value(registry) {
Ok(Value::Object(map)) => map,
_ => unreachable!("a struct of vectors serializes to an object"),
}
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|elapsed| elapsed.as_secs()).unwrap_or(0)
}
mod push;
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,89 @@
//! The push half of the device book: the bridge's signing key, and each device's subscription.
//!
//! Kept in the same file as the devices, so revoking a device takes its subscription with it, and
//! under the same lock, so two bridges starting at once agree on one key.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use super::{Device, DeviceBook, KeptKey, Registry};
use crate::push::{Subscription, Vapid, VapidError};
use crate::RemoteError;
/// Why the push key couldn't be had.
#[derive(Debug, thiserror::Error)]
pub(crate) enum PushKeyError {
/// The device file couldn't be read or written
#[error(transparent)]
File(#[from] RemoteError),
/// The key couldn't be made, or the kept one doesn't read
#[error(transparent)]
Key(#[from] VapidError),
}
impl Registry {
/// The kept key, or a new one kept from now on.
fn push_key_document(&mut self) -> Result<Vec<u8>, VapidError> {
if let Some(KeptKey(kept)) = &self.push_key {
return URL_SAFE_NO_PAD.decode(kept).map_err(|_| VapidError::Unreadable);
}
let (_, document) = Vapid::generate()?;
self.push_key = Some(KeptKey(URL_SAFE_NO_PAD.encode(&document)));
Ok(document)
}
/// Sets the subscription of device `id`, saying whether there is such a device.
fn subscribe(&mut self, id: &str, subscription: Option<Subscription>) -> bool {
let Some(device) = self.devices.iter_mut().find(|device| device.id == id) else {
return false;
};
device.push = subscription;
true
}
/// Drops device `id`'s subscription if it's still at `endpoint`, the one a push service
/// reported gone; a device that subscribed again since keeps its new one.
fn forget_endpoint(&mut self, id: &str, endpoint: &str) {
let device = self.devices.iter_mut().find(|device| device.id == id);
if let Some(device) = device.filter(|device| device.push_endpoint() == Some(endpoint)) {
device.push = None;
}
}
}
impl Device {
/// Where this device takes notifications, when it asked for them.
pub(crate) fn subscription(&self) -> Option<&Subscription> {
self.push.as_ref()
}
fn push_endpoint(&self) -> Option<&str> {
self.push.as_ref().map(|subscription| subscription.endpoint.as_str())
}
}
impl DeviceBook {
/// The bridge's push signing key, made and kept the first time it's asked for.
pub(crate) fn push_key(&self) -> Result<Vapid, PushKeyError> {
let document = self.change(Registry::push_key_document)??;
Ok(Vapid::from_pkcs8(&document)?)
}
/// Sends device `id`'s notifications to `subscription` from now on, or stops them with
/// `None`. False when there's no such device.
pub(crate) fn subscribe(
&self,
id: &str,
subscription: Option<Subscription>,
) -> Result<bool, RemoteError> {
self.change(|registry| registry.subscribe(id, subscription))
}
/// Forgets device `id`'s subscription at `endpoint`, which its push service says is gone.
pub(crate) fn forget_endpoint(&self, id: &str, endpoint: &str) -> Result<(), RemoteError> {
self.change(|registry| registry.forget_endpoint(id, endpoint))
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,82 @@
use super::*;
use crate::push::Subscription;
fn subscription(endpoint: &str) -> Subscription {
let keys = crate::push::SubscriptionKeys {
p256dh: "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"
.into(),
auth: "BTBZMqHH6r4Tts7J_aSIgg".into(),
};
Subscription { endpoint: endpoint.into(), keys }
}
/// A book with one paired device, and that device.
fn paired() -> (tempfile::TempDir, DeviceBook, Device) {
let dir = tempfile::tempdir().unwrap();
let book = DeviceBook::at(dir.path().join("remote.json"));
let token = book.invite().unwrap();
let (device, _) = book.pair(&token, "iPhone", "alex@github").unwrap();
(dir, book, device)
}
fn kept(book: &DeviceBook, id: &str) -> Option<Subscription> {
let devices = book.devices();
devices.iter().find(|device| device.id == id)?.subscription().cloned()
}
/// The break this catches: a new key on every ask, so each subscription is to a key the bridge
/// no longer signs with and Apple refuses every push (`VapidPkHashMismatch`).
#[test]
fn the_push_key_is_made_once_and_kept() {
let (_dir, book, _) = paired();
let first = book.push_key().unwrap().public_key();
assert_eq!(book.push_key().unwrap().public_key(), first);
let reopened = DeviceBook::at(book.file.path().to_path_buf());
assert_eq!(reopened.push_key().unwrap().public_key(), first);
}
/// The break this catches: a subscription kept apart from its device, so a revoked phone goes on
/// being told what your sessions are waiting for.
#[test]
fn a_subscription_goes_with_its_device() {
let (_dir, book, device) = paired();
let apple = subscription("https://web.push.apple.com/a");
assert!(book.subscribe(&device.id, Some(apple.clone())).unwrap());
assert_eq!(kept(&book, &device.id), Some(apple));
assert!(book.subscribe(&device.id, None).unwrap());
assert_eq!(kept(&book, &device.id), None, "turned off");
assert!(!book.subscribe("nobody", Some(subscription("https://web.push.apple.com/b"))).unwrap());
}
/// The break this catches: a late "gone" for an old endpoint wiping the subscription the device
/// made since, so it stops getting notifications it just turned on.
#[test]
fn a_gone_endpoint_forgets_only_that_subscription() {
let (_dir, book, device) = paired();
let fresh = subscription("https://web.push.apple.com/new");
book.subscribe(&device.id, Some(fresh.clone())).unwrap();
book.forget_endpoint(&device.id, "https://web.push.apple.com/old").unwrap();
assert_eq!(kept(&book, &device.id), Some(fresh));
book.forget_endpoint(&device.id, "https://web.push.apple.com/new").unwrap();
assert_eq!(kept(&book, &device.id), None);
}
/// The file names what it keeps as below, and the key never prints.
///
/// The break this catches: a renamed field, which a round trip can't see but which loses every
/// device's subscription and the key (so every subscription with it) on upgrade; or the key in a
/// log line through `Debug`.
#[test]
fn the_file_keeps_the_key_and_each_subscription_by_name() {
let (dir, book, device) = paired();
book.subscribe(&device.id, Some(subscription("https://web.push.apple.com/a"))).unwrap();
book.push_key().unwrap();
let written = std::fs::read_to_string(dir.path().join("remote.json")).unwrap();
let written: serde_json::Value = serde_json::from_str(&written).unwrap();
let push = &written["devices"][0]["push"];
assert_eq!(push["endpoint"], "https://web.push.apple.com/a");
assert_eq!(push["keys"]["auth"], "BTBZMqHH6r4Tts7J_aSIgg");
let key = written["push_key"].as_str().expect("the key is kept as text");
let registry = book.load();
assert!(!format!("{registry:?}").contains(key), "the key printed");
}

View File

@@ -0,0 +1,76 @@
use super::*;
const START: u64 = 1_800_000_000;
fn device(credential: &str) -> Device {
Device {
id: "a1b2c3d4".into(),
name: "iPhone".into(),
login: "alex@github".into(),
paired_at: START,
credential_sha256: digest(credential),
push: None,
}
}
/// An invitation pairs one device, once.
///
/// The break this catches: leaving the invitation in place after it is used, so a link that
/// leaked from a screenshot or a shared photo pairs a second device.
#[test]
fn an_invitation_pairs_one_device_once() {
let mut registry = Registry::default();
registry.invite("token", START);
assert!(registry.redeem("token", device("first"), START + 1).is_ok());
let again = registry.redeem("token", device("second"), START + 2);
assert_eq!(again, Err(PairingError::InvitationUnusable));
assert_eq!(registry.devices.len(), 1);
}
/// An invitation is good for ten minutes and no longer.
///
/// The break this catches: never expiring invitations, so one printed and forgotten stays a way
/// in for good.
#[test]
fn an_invitation_expires() {
let mut registry = Registry::default();
registry.invite("token", START);
let late = START + INVITATION_LIFETIME_SECS;
assert_eq!(registry.redeem("token", device("c"), late), Err(PairingError::InvitationUnusable));
registry.invite("fresh", START);
let in_time = START + INVITATION_LIFETIME_SECS - 1;
assert!(registry.redeem("fresh", device("c"), in_time).is_ok());
}
/// A device signs in with its own credential, and not after it is revoked.
///
/// The break this catches: revocation that leaves the device's credential working.
#[test]
fn a_revoked_device_no_longer_signs_in() {
let mut registry = Registry::default();
registry.invite("token", START);
registry.redeem("token", device("credential"), START).unwrap();
assert_eq!(registry.holder("credential").map(|device| device.name.as_str()), Some("iPhone"));
assert!(registry.holder("another").is_none());
assert!(registry.revoke("a1b2c3d4").is_some());
assert!(registry.holder("credential").is_none());
assert!(registry.revoke("a1b2c3d4").is_none(), "nothing left to revoke");
}
/// The file keeps digests: neither the invitation nor the credential can be read back out of it.
///
/// The break this catches: storing either as it was issued, so anyone who reads the file (a
/// backup, a synced dotfiles repository) can pair or sign in as the device.
#[test]
fn the_file_holds_no_secret_that_signs_in() {
let dir = tempfile::tempdir().unwrap();
let book = DeviceBook::at(dir.path().join("remote.json"));
let token = book.invite().unwrap();
let unused = book.invite().unwrap();
let (device, credential) = book.pair(&token, "iPad", "alex@github").unwrap();
let written = std::fs::read_to_string(dir.path().join("remote.json")).unwrap();
for secret in [&token, &unused, &credential] {
assert!(!written.contains(secret.as_str()), "{secret} is in the file");
}
assert_eq!(book.holder(&credential), Some(device));
}

View File

@@ -0,0 +1,147 @@
//! Folders — where a device can start a session.
//!
//! The folders Luxe is running in now, the ones herdr's panes are in, and the ones the bridge has
//! seen Luxe running in before, remembered in a small file. Never a scan of the home folder: the
//! list is where you've already worked.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use luxe_core::json_file::{FileError, FileMode, JsonFile};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
/// How many remembered folders are kept, the longest unseen dropped first.
const REMEMBERED: usize = 50;
/// How stale a sighting gets before it's written again. The list is read every few seconds, and
/// rewriting the file each time would only refresh the order.
const RESIGHTING_SECS: u64 = 60 * 60;
/// One place a session can start, as a device sees it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct Folder {
pub(crate) path: String,
pub(crate) name: String,
/// Sessions running there now
pub(crate) sessions: usize,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct Remembered {
#[serde(default)]
folders: Vec<Sighting>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Sighting {
path: String,
last_seen: u64,
}
/// The folders the bridge has seen Luxe running in.
#[derive(Debug, Clone)]
pub(crate) struct FolderBook {
file: JsonFile,
}
impl FolderBook {
/// The book in `path`, created on first sighting.
pub(crate) fn at(path: PathBuf) -> Self {
Self { file: JsonFile::new(path, FileMode::OwnerOnly) }
}
/// Where it lives unless told otherwise: Luxe's state folder, since it's a record of use.
pub(crate) fn default_path() -> PathBuf {
luxe_core::user_dirs::luxe_state_dir().join("remote-folders.json")
}
/// Notes that Luxe is running in each of `running` now.
pub(crate) fn saw(&self, running: &[String]) -> Result<(), FileError> {
let now = now();
let since = now.saturating_sub(RESIGHTING_SECS);
if all_seen_since(&self.read().folders, running, since) {
return Ok(());
}
self.file.modify(|map| {
let mut remembered = parse(std::mem::take(map));
remember(&mut remembered.folders, running, now);
*map = into_map(&remembered);
Ok(())
})
}
/// Paths remembered, most recently seen first.
fn remembered(&self) -> Vec<String> {
let mut folders = self.read().folders;
folders.sort_by_key(|sighting| std::cmp::Reverse(sighting.last_seen));
folders.into_iter().map(|sighting| sighting.path).collect()
}
fn read(&self) -> Remembered {
self.file.read().map(parse).unwrap_or_default()
}
}
fn all_seen_since(folders: &[Sighting], running: &[String], since: u64) -> bool {
running.iter().all(|path| {
folders.iter().any(|sighting| sighting.path == *path && sighting.last_seen >= since)
})
}
/// Every folder a session could start in: running ones first, then herdr's, then remembered ones,
/// each once and only while it's still a folder.
pub(crate) fn listing(running: &[String], herdr: &[String], book: &FolderBook) -> Vec<Folder> {
let mut sessions: HashMap<&str, usize> = HashMap::new();
for path in running {
*sessions.entry(path).or_default() += 1;
}
let remembered = book.remembered();
let mut listed: Vec<Folder> = Vec::new();
for path in running.iter().chain(herdr).chain(&remembered) {
if path.is_empty() || listed.iter().any(|folder| folder.path == *path) {
continue;
}
if !Path::new(path).is_dir() {
continue;
}
let name = luxe_core::paths::dir_name(Path::new(path));
let count = sessions.get(path.as_str()).copied().unwrap_or(0);
listed.push(Folder { path: path.clone(), name, sessions: count });
}
listed
}
/// Brings each of `running` to `now`, keeping the [`REMEMBERED`] most recent.
fn remember(folders: &mut Vec<Sighting>, running: &[String], now: u64) {
for path in running {
match folders.iter_mut().find(|sighting| sighting.path == *path) {
Some(sighting) => sighting.last_seen = now,
None => folders.push(Sighting { path: path.clone(), last_seen: now }),
}
}
folders.sort_by_key(|sighting| std::cmp::Reverse(sighting.last_seen));
folders.truncate(REMEMBERED);
}
/// The remembered folders, or none when the file doesn't read: it's a convenience, rebuilt by use.
fn parse(map: Map<String, Value>) -> Remembered {
serde_json::from_value(Value::Object(map))
.inspect_err(|error| tracing::warn!(%error, "the remembered-folder file doesn't read"))
.unwrap_or_default()
}
fn into_map(remembered: &Remembered) -> Map<String, Value> {
match serde_json::to_value(remembered) {
Ok(Value::Object(map)) => map,
_ => unreachable!("a struct of vectors serializes to an object"),
}
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|elapsed| elapsed.as_secs()).unwrap_or(0)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,68 @@
use super::*;
fn sighting(path: &str, last_seen: u64) -> Sighting {
Sighting { path: path.into(), last_seen }
}
/// A sighting refreshes a folder already known and adds a new one, and the oldest go past the cap.
///
/// The break this catches, one per assertion: a second entry for a folder seen again; a new folder
/// not kept; or the cap dropping the newest instead of the longest unseen.
#[test]
fn sightings_refresh_add_and_forget_the_oldest() {
let mut folders: Vec<Sighting> =
(0..REMEMBERED as u64).map(|age| sighting(&format!("/old/{age}"), 100 - age)).collect();
remember(&mut folders, &["/old/3".into(), "/new".into()], 1_000);
assert_eq!(folders.iter().filter(|sighting| sighting.path == "/old/3").count(), 1);
assert!(folders.iter().any(|sighting| sighting.path == "/new"));
assert_eq!(folders.len(), REMEMBERED);
let oldest = format!("/old/{}", REMEMBERED - 1);
assert!(!folders.iter().any(|sighting| sighting.path == oldest), "the longest unseen goes");
}
/// Running folders lead with their counts, then herdr's, then remembered ones, each once and only
/// while it is a folder.
///
/// The break this catches, one per folder: losing the count (app), listing a folder twice (app
/// again, from herdr), losing herdr's (tools), or listing one that has since gone (gone).
#[test]
fn the_listing_leads_with_running_folders_and_lists_each_once() {
let root = tempfile::tempdir().unwrap();
let folder = |name: &str| {
let path = root.path().join(name);
std::fs::create_dir_all(&path).unwrap();
path.to_string_lossy().into_owned()
};
let (app, tools, notes) = (folder("app"), folder("tools"), folder("notes"));
let gone = root.path().join("gone").to_string_lossy().into_owned();
let book = FolderBook::at(root.path().join("folders.json"));
book.saw(&[notes.clone(), gone]).unwrap();
let listed = listing(&[app.clone(), app.clone()], &[app.clone(), tools.clone()], &book);
let paths: Vec<&str> = listed.iter().map(|folder| folder.path.as_str()).collect();
assert_eq!(paths, [app.as_str(), tools.as_str(), notes.as_str()]);
assert_eq!(listed[0].sessions, 2);
assert_eq!(listed[0].name, "app");
assert_eq!(listed[1].sessions, 0);
}
/// A folder seen within the hour isn't written again; one seen longer ago is.
///
/// The break this catches: rewriting the file on every list, which a phone polling the session
/// list turns into a write every few seconds.
#[test]
fn a_recent_sighting_is_not_written_again() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("folders.json");
let book = FolderBook::at(path.clone());
let marked = |last_seen: u64| {
let text = format!(r#"{{"folders":[{{"path":"/app","last_seen":{last_seen}}}],"mark":1}}"#);
std::fs::write(&path, text).unwrap();
};
marked(now());
book.saw(&["/app".into()]).unwrap();
assert!(std::fs::read_to_string(&path).unwrap().contains("mark"), "rewritten while fresh");
marked(0);
book.saw(&["/app".into()]).unwrap();
assert!(!std::fs::read_to_string(&path).unwrap().contains("mark"), "not rewritten when stale");
}

View File

@@ -0,0 +1,128 @@
//! Home screen — what a phone needs to keep the app as an icon: a manifest, and the icon.
//!
//! Added to an iPhone's home screen, the app opens on its own, without Safari's bars, as the
//! manifest's `display: standalone` asks. Both are drawn in your theme, as `/theme.css` is, and
//! like it they need only the tailnet login: a browser fetches a manifest without cookies, so a
//! paired-device check would turn it away, and neither says anything a page of the app doesn't.
use std::collections::HashMap;
use std::sync::Arc;
use axum::extract::{Path, State};
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use luxe_core::theme::{ColorValue, ThemeRegistry};
use crate::render::TileColors;
use crate::routes::Bridged;
/// The sides an icon is drawn at: iOS's home screen, and the two sizes a manifest lists.
const ICON_SIDES: [u32; 3] = [180, 192, 512];
/// `/manifest.webmanifest`: the app as a home screen keeps it, named for the computer it reaches.
pub(crate) async fn manifest(State(bridged): State<Arc<Bridged>>) -> Response {
let colors = theme_colors().await;
let body = manifest_json(&hex(colors.plate), bridged.machine.as_deref()).to_string();
let mut response =
([(header::CONTENT_TYPE, "application/manifest+json")], body).into_response();
no_cache(&mut response);
response
}
/// `/icons/{side}.png`: the tile, at one of [`ICON_SIDES`].
pub(crate) async fn icon(
State(bridged): State<Arc<Bridged>>,
Path(file): Path<String>,
) -> Response {
let Some(side) = icon_side(&file) else {
return (StatusCode::NOT_FOUND, format!("no icon {file}")).into_response();
};
let colors = theme_colors().await;
let renderer = bridged.renderer.clone();
let drawn = tokio::task::spawn_blocking(move || renderer.home_icon(side, colors)).await;
let Ok(Some(png)) = drawn else {
return (StatusCode::NOT_FOUND, "this bridge draws no icon").into_response();
};
let mut response = ([(header::CONTENT_TYPE, "image/png")], png).into_response();
no_cache(&mut response);
response
}
/// The side `file` names, when it's one this bridge draws: `180.png` and the like.
fn icon_side(file: &str) -> Option<u32> {
let side = file.strip_suffix(".png")?.parse().ok()?;
ICON_SIDES.contains(&side).then_some(side)
}
/// The manifest for a theme whose background is `background`, for the computer `machine`. The
/// icon already says Luxe, so a named one's home screen label is the computer: an app for each of
/// two computers tells itself apart.
fn manifest_json(background: &str, machine: Option<&str>) -> serde_json::Value {
let icon = |side: u32| {
let (src, sizes) = (format!("/icons/{side}.png"), format!("{side}x{side}"));
serde_json::json!({ "src": src, "sizes": sizes, "type": "image/png" })
};
serde_json::json!({
"id": "/",
"name": app_name(machine),
"short_name": machine.unwrap_or("Luxe"),
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": background,
"theme_color": background,
"icons": [icon(192), icon(512)],
})
}
/// The app's name: `Luxe · desk` for the computer `desk`, or plain Luxe unnamed.
pub(crate) fn app_name(machine: Option<&str>) -> String {
machine.map_or_else(|| "Luxe".to_owned(), |machine| format!("Luxe \u{00b7} {machine}"))
}
/// The active theme's tile colors, read off the async threads like the stylesheet.
async fn theme_colors() -> TileColors {
let theme = tokio::task::spawn_blocking(crate::app::active_theme).await;
tile_colors(&theme.unwrap_or_default())
}
/// The plate and letter `theme` gives the tile. A color that isn't RGB (an ANSI palette, the
/// terminal's default) can't be drawn, so it falls back to the built-in theme's.
fn tile_colors(theme: &HashMap<String, ColorValue>) -> TileColors {
let builtin =
ThemeRegistry::new().resolve(luxe_core::config::DEFAULT_THEME).unwrap_or_default();
let pick = |token: &str, last: [u8; 3]| {
rgb(theme, token).or_else(|| rgb(&builtin, token)).unwrap_or(last)
};
TileColors { plate: pick("background", [0; 3]), ink: pick("accent", [0xff; 3]) }
}
fn rgb(theme: &HashMap<String, ColorValue>, token: &str) -> Option<[u8; 3]> {
match theme.get(token)? {
ColorValue::Rgb(red, green, blue) => Some([*red, *green, *blue]),
_ => None,
}
}
fn hex([red, green, blue]: [u8; 3]) -> String {
format!("#{red:02x}{green:02x}{blue:02x}")
}
/// How iOS draws the status bar over the app from the home screen: see-through, with white
/// text over the app's own header, unless the theme is light enough to want dark text.
pub(crate) fn status_bar_style(theme: &HashMap<String, ColorValue>) -> &'static str {
if luxe_core::theme::css::is_light(theme.get("background")) {
"default"
} else {
"black-translucent"
}
}
fn no_cache(response: &mut Response) {
response
.headers_mut()
.insert(header::CACHE_CONTROL, header::HeaderValue::from_static("no-cache"));
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,69 @@
use super::*;
fn theme(pairs: &[(&str, ColorValue)]) -> HashMap<String, ColorValue> {
pairs.iter().map(|(token, color)| (token.to_string(), color.clone())).collect()
}
/// The break this catches: a renamed field or a lost icon in the manifest, which iOS reads once,
/// when the app is added, and never asks about again.
#[test]
fn the_manifest_is_pinned() {
let expected = serde_json::json!({
"id": "/",
"name": "Luxe",
"short_name": "Luxe",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#12100e",
"theme_color": "#12100e",
"icons": [
{ "src": "/icons/192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/512.png", "sizes": "512x512", "type": "image/png" },
],
});
assert_eq!(manifest_json("#12100e", None), expected);
}
/// A named bridge's app is named for its computer, and the home screen label is the computer
/// alone, since the icon already says Luxe.
///
/// The break this catches: two computers' apps both suggested as "Luxe", so the phone shows two
/// identical icons, or the full name crowding the home screen's short label.
#[test]
fn a_named_bridge_names_its_app_for_the_computer() {
let named = manifest_json("#12100e", Some("desk"));
assert_eq!(
(named["name"].as_str(), named["short_name"].as_str()),
(Some("Luxe \u{00b7} desk"), Some("desk"))
);
}
/// The break this catches: the theme ignored, so the icon is the default brass whatever you
/// picked; or plate and letter crossed.
#[test]
fn the_tile_takes_the_themes_background_and_accent() {
let rgb =
theme(&[("background", ColorValue::Rgb(1, 2, 3)), ("accent", ColorValue::Rgb(4, 5, 6))]);
assert_eq!(tile_colors(&rgb), TileColors { plate: [1, 2, 3], ink: [4, 5, 6] });
}
/// The break this catches: an ANSI theme drawn in the last-resort black and white, or only one
/// of the two colors falling back, rather than the built-in theme's.
#[test]
fn a_color_that_isnt_rgb_falls_back_to_the_built_in_theme() {
let builtin = tile_colors(&HashMap::new());
let ansi = theme(&[("background", ColorValue::Ansi(0)), ("accent", ColorValue::Rgb(4, 5, 6))]);
assert_eq!(tile_colors(&ansi), TileColors { plate: builtin.plate, ink: [4, 5, 6] });
assert_ne!(builtin.plate, [0; 3], "the built-in theme's own plate, not the last resort");
}
/// The break this catches: the status bar's style the same for every theme, so a light one gets
/// white text on its own light header.
#[test]
fn a_light_theme_keeps_the_status_bar_dark_text() {
let light = theme(&[("background", ColorValue::Rgb(250, 250, 245))]);
let dark = theme(&[("background", ColorValue::Rgb(18, 16, 14))]);
assert_eq!(status_bar_style(&light), "default");
assert_eq!(status_bar_style(&dark), "black-translucent");
}

View File

@@ -0,0 +1,228 @@
//! Launch — starting a session for a device: in a herdr pane when herdr is running, otherwise as a
//! `luxe --rpc` child of the bridge.
//!
//! Either way the new Luxe shares its session like any other, so a device joins it through the
//! same route as one started at the desk. The bridge learns which session is the new one by
//! watching for its record in the runtime folder.
mod herdr;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use luxe_core::local_endpoint::{running_sessions, LiveSession};
use serde::Serialize;
use tokio::sync::watch;
use crate::folders::{self, Folder, FolderBook};
pub(crate) use herdr::Herdr;
/// How long a new Luxe gets to share its session. It takes about a second.
const APPEAR_TIMEOUT: Duration = Duration::from_secs(20);
/// How often the runtime folder is reread while waiting.
const APPEAR_POLL: Duration = Duration::from_millis(250);
/// Where a started session runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Place {
/// A herdr pane, which outlives the bridge and shows at the desk
Herdr,
/// A child of the bridge, which lasts while the bridge does
Bridge,
}
/// Why a session couldn't be started.
#[derive(Debug, thiserror::Error)]
pub(crate) enum LaunchError {
/// The device asked for something that isn't a folder here
#[error("{0}")]
NotAFolder(String),
/// herdr is running but turned the request down
#[error("herdr couldn't open a pane: {0}")]
Herdr(String),
/// The child couldn't be started
#[error("couldn't start luxe: {0}")]
Spawn(#[source] std::io::Error),
/// Luxe started but no session showed up in time
#[error("luxe started in {0} but didn't share a session within 20 seconds")]
NeverAppeared(String),
}
/// Starts sessions, and holds the ones it runs itself.
pub(crate) struct Launcher {
/// The `luxe` a child runs: the bridge's own
program: PathBuf,
herdr: Herdr,
folders: FolderBook,
/// Dropped with the launcher, which has each child's watcher close its stdin: a child ends its
/// session on that, as for any client hanging up, so the bridge stopping ends them cleanly
held: watch::Sender<()>,
}
impl Launcher {
/// A launcher that runs `program` when `herdr` can't open a pane, remembering folders in
/// `folders`.
pub(crate) fn new(program: PathBuf, herdr: Herdr, folders: FolderBook) -> Self {
Self { program, herdr, folders, held: watch::channel(()).0 }
}
/// Where a session could start, and whether it would open in herdr.
pub(crate) async fn folders(&self, runtime_dir: &Path) -> (Vec<Folder>, bool) {
let running = running_now(runtime_dir).await;
let running: Vec<String> = running.into_iter().map(|session| session.cwd).collect();
let in_herdr = self.herdr.running().await;
let mut herdr = Vec::new();
if in_herdr {
let panes = self.herdr.panes().await;
let panes = panes.inspect_err(|error| tracing::warn!(%error, "no folders from herdr"));
herdr = panes.unwrap_or_default().into_iter().map(|pane| pane.cwd).collect();
}
self.saw(running.clone()).await;
let book = self.folders.clone();
let listed = tokio::task::spawn_blocking(move || folders::listing(&running, &herdr, &book));
(listed.await.unwrap_or_default(), in_herdr)
}
/// Notes the folders Luxe is running in, for the list a device starts sessions from.
pub(crate) async fn saw(&self, running: Vec<String>) {
let book = self.folders.clone();
let noted = tokio::task::spawn_blocking(move || book.saw(&running)).await;
if let Ok(Err(error)) = noted {
tracing::warn!(%error, "could not note the folders Luxe is running in");
}
}
/// Starts Luxe in `folder` and waits for the session it shares.
pub(crate) async fn start(
&self,
folder: &Path,
runtime_dir: &Path,
) -> Result<(LiveSession, Place), LaunchError> {
let before = running_pids(runtime_dir).await;
let place = if self.herdr.running().await {
self.herdr.open(folder).await?;
Place::Herdr
} else {
self.spawn(folder)?;
Place::Bridge
};
let session = appeared(runtime_dir, before, folder).await?;
Ok((session, place))
}
fn spawn(&self, folder: &Path) -> Result<(), LaunchError> {
let mut command = tokio::process::Command::new(&self.program);
command
.arg("--rpc")
.current_dir(folder)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
// a bridge running in a herdr pane would have each child report into that pane
.env_remove("HERDR_ENV")
.env_remove("HERDR_PANE_ID");
luxe_core::program::detach_from_terminal(&mut command);
let child = command.spawn().map_err(LaunchError::Spawn)?;
tokio::spawn(watch_child(child, self.held.subscribe()));
Ok(())
}
}
/// Waits on a child until it ends, closing its stdin once the launcher is gone.
///
/// Waited on rather than left alone because an exited child nobody waits on keeps its process id
/// alive, and its record would list a session that can't be joined.
async fn watch_child(mut child: tokio::process::Child, mut held: watch::Receiver<()>) {
let pid = child.id();
let stdin = child.stdin.take();
let ended = tokio::select! {
status = child.wait() => Some(status),
// only ever an error: nothing is sent, and it fails once the launcher drops
_ = held.changed() => None,
};
let status = match ended {
Some(status) => status,
None => {
drop(stdin);
child.wait().await
}
};
match status {
Ok(status) => tracing::info!(?pid, %status, "a session the bridge started has ended"),
Err(error) => tracing::warn!(?pid, %error, "lost track of a session the bridge started"),
}
}
/// The folder a device asked for, as a full path to a folder that exists. A leading `~` is the
/// home folder, since that's how people type paths.
pub(crate) fn resolve_folder(asked: &str, home: Option<&Path>) -> Result<PathBuf, LaunchError> {
let asked = asked.trim();
let path = match (asked.strip_prefix('~'), home) {
(Some(rest), Some(home)) if rest.is_empty() || rest.starts_with(['/', '\\']) => {
home.join(rest.trim_start_matches(['/', '\\']))
}
_ => PathBuf::from(asked),
};
if !path.is_absolute() {
return Err(LaunchError::NotAFolder(format!("`{asked}` isn't a full path")));
}
if !path.is_dir() {
let shown = luxe_core::paths::display(&path);
return Err(LaunchError::NotAFolder(format!("{shown} isn't a folder on this machine")));
}
Ok(path)
}
async fn running_now(runtime_dir: &Path) -> Vec<LiveSession> {
let dir = runtime_dir.to_path_buf();
// reads a folder and, on Windows, asks `tasklist` about each pid
tokio::task::spawn_blocking(move || running_sessions(&dir)).await.unwrap_or_default()
}
async fn running_pids(runtime_dir: &Path) -> HashSet<u32> {
running_now(runtime_dir).await.iter().map(|session| session.pid).collect()
}
/// Waits for the session started in `folder` to be listed.
async fn appeared(
runtime_dir: &Path,
before: HashSet<u32>,
folder: &Path,
) -> Result<LiveSession, LaunchError> {
let before = std::sync::Arc::new(before);
let deadline = tokio::time::Instant::now() + APPEAR_TIMEOUT;
while tokio::time::Instant::now() < deadline {
let (dir, before, wanted) = (runtime_dir.to_path_buf(), before.clone(), folder.to_owned());
let found = tokio::task::spawn_blocking(move || {
newcomer(&running_sessions(&dir), &before, &wanted)
});
if let Ok(Some(session)) = found.await {
return Ok(session);
}
tokio::time::sleep(APPEAR_POLL).await;
}
Err(LaunchError::NeverAppeared(luxe_core::paths::display(folder)))
}
/// The session in `running` that wasn't there `before` and works on `folder`.
///
/// "Works on" rather than "is in": a Luxe started in a subfolder of a repository shares the
/// repository's root as its folder.
fn newcomer(running: &[LiveSession], before: &HashSet<u32>, folder: &Path) -> Option<LiveSession> {
let folder = folder.canonicalize().ok()?;
running
.iter()
.filter(|session| !before.contains(&session.pid))
.find(|session| {
let cwd = Path::new(&session.cwd).canonicalize();
cwd.is_ok_and(|cwd| luxe_core::paths::contains(&cwd, &folder))
})
.cloned()
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,149 @@
//! Herdr — opening a pane that runs `luxe`, through herdr's CLI.
//!
//! Only when herdr's server is already running. The CLI never starts one, and a server the bridge
//! started would hold panes nobody is attached to. `HERDR_SESSION` picks the session, as it does
//! for any herdr command.
use std::path::Path;
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use super::LaunchError;
/// How long one herdr command gets; each answers from the running server at once.
const ASK_TIMEOUT: Duration = Duration::from_secs(10);
/// Whether sessions may be started in herdr.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Herdr {
/// When herdr's server is running
WhenRunning,
/// Never, so tests don't open panes in the developer's herdr
Off,
}
#[derive(Deserialize)]
struct ServerStatus {
running: bool,
#[serde(default)]
compatible: Option<bool>,
}
#[derive(Deserialize)]
struct Reply<T> {
result: T,
}
#[derive(Deserialize)]
struct Created {
root_pane: Pane,
}
#[derive(Deserialize)]
struct PaneList {
panes: Vec<Pane>,
}
/// One herdr pane: the terminal a process runs in.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct Pane {
pane_id: String,
workspace_id: String,
/// The folder its shell is in, empty when herdr doesn't know
#[serde(default)]
pub(crate) cwd: String,
}
#[derive(Deserialize)]
struct Refusal {
error: RefusalReason,
}
#[derive(Deserialize)]
struct RefusalReason {
message: String,
}
impl Herdr {
/// Whether herdr's server is up and speaks this CLI's protocol.
pub(crate) async fn running(self) -> bool {
if self == Herdr::Off {
return false;
}
ask(&["status", "server", "--json"]).await.is_ok_and(|json| is_running(&json))
}
/// Opens a pane in `folder` and runs `luxe` in it: a new tab in the workspace already working
/// there, or a new workspace named after the folder.
pub(crate) async fn open(self, folder: &Path) -> Result<(), LaunchError> {
let shown = folder.to_string_lossy();
let created = match workspace_for(&self.panes().await?, folder) {
Some(workspace) => {
ask(&["tab", "create", "--workspace", workspace, "--cwd", &shown, "--no-focus"])
.await?
}
None => {
let label = luxe_core::paths::dir_name(folder);
ask(&["workspace", "create", "--cwd", &shown, "--label", &label, "--no-focus"])
.await?
}
};
let pane = parse::<Created>(&created)?.root_pane.pane_id;
// the `luxe` on PATH, as the person would type it in that pane
ask(&["pane", "run", &pane, "luxe"]).await?;
Ok(())
}
/// Every pane in the session, for the folders they're in.
pub(crate) async fn panes(self) -> Result<Vec<Pane>, LaunchError> {
if self == Herdr::Off {
return Ok(Vec::new());
}
Ok(parse::<PaneList>(&ask(&["pane", "list"]).await?)?.panes)
}
}
fn is_running(json: &str) -> bool {
serde_json::from_str::<ServerStatus>(json)
.is_ok_and(|status| status.running && status.compatible != Some(false))
}
/// The workspace with a pane in `folder`, where a new tab joins the work already there.
fn workspace_for<'a>(panes: &'a [Pane], folder: &Path) -> Option<&'a str> {
panes.iter().find(|pane| Path::new(&pane.cwd) == folder).map(|pane| pane.workspace_id.as_str())
}
fn parse<T: DeserializeOwned>(json: &str) -> Result<T, LaunchError> {
let reply: Reply<T> = serde_json::from_str(json).map_err(|error| {
LaunchError::Herdr(format!("it said something this can't read: {error}"))
})?;
Ok(reply.result)
}
/// What `herdr <args>` prints, or why it failed in herdr's own words.
async fn ask(args: &[&str]) -> Result<String, LaunchError> {
let program = luxe_core::program::resolve("herdr")
.ok_or_else(|| LaunchError::Herdr("the `herdr` command isn't on PATH".into()))?;
let asked = tokio::process::Command::new(program).args(args).kill_on_drop(true).output();
let output = tokio::time::timeout(ASK_TIMEOUT, asked)
.await
.map_err(|_| LaunchError::Herdr("it didn't answer within 10 seconds".into()))?
.map_err(|error| LaunchError::Herdr(error.to_string()))?;
if !output.status.success() {
return Err(LaunchError::Herdr(refusal(&String::from_utf8_lossy(&output.stderr))));
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
/// herdr's reason from the JSON it prints on a failure, or the text itself when it isn't JSON.
fn refusal(stderr: &str) -> String {
match serde_json::from_str::<Refusal>(stderr) {
Ok(refusal) => refusal.error.message,
Err(_) => stderr.trim().to_string(),
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,48 @@
use super::*;
/// `herdr status server --json` from herdr 0.9.3, running and stopped, trimmed to what matters.
const RUNNING: &str = r#"{"status":"running","running":true,"version":"0.9.3","protocol":22,"compatible":true,"endpoint_compatible":true,"session":"luxetest"}"#;
const STOPPED: &str = r#"{"status":"not_running","running":false,"version":null,"protocol":null,"capabilities":null,"compatible":null,"endpoint_compatible":null,"session":null}"#;
/// Herdr counts as running only when its server is up and speaks this CLI's protocol.
///
/// The break this catches: reading only `running`, so a server left from an older herdr gets
/// commands it can't answer and every start fails, when a child would have worked.
#[test]
fn herdr_runs_when_its_server_is_up_and_compatible() {
assert!(is_running(RUNNING));
assert!(!is_running(STOPPED));
assert!(!is_running(&RUNNING.replace(r#""compatible":true"#, r#""compatible":false"#)));
assert!(!is_running("not json"));
}
/// The pane to run `luxe` in is read from what `workspace create` printed.
///
/// The break this catches: a field renamed in the reply this reads, copied from herdr 0.9.3.
#[test]
fn the_new_pane_is_read_from_herdrs_reply() {
let created = r#"{"id":"cli:workspace:create","result":{"root_pane":{"agent_status":"unknown","cwd":"/tmp/herdr-proj","focused":false,"pane_id":"w2:p1","tab_id":"w2:t1","workspace_id":"w2"},"tab":{"tab_id":"w2:t1","workspace_id":"w2"},"type":"workspace_created","workspace":{"label":"herdr-proj","workspace_id":"w2"}}}"#;
assert_eq!(parse::<Created>(created).unwrap().root_pane.pane_id, "w2:p1");
}
/// A new session joins the workspace already working in its folder, and only that one.
///
/// The break this catches: matching a folder's parent or neighbor, which puts the tab in some other
/// project's workspace.
#[test]
fn a_session_joins_the_workspace_in_its_folder() {
let listed = r#"{"id":"cli:pane:list","result":{"panes":[{"cwd":"/home/alex/app-two","pane_id":"w1:p1","workspace_id":"w1"},{"cwd":"/home/alex/app","pane_id":"w2:p1","workspace_id":"w2"}],"type":"pane_list"}}"#;
let panes = parse::<PaneList>(listed).unwrap().panes;
assert_eq!(workspace_for(&panes, Path::new("/home/alex/app")), Some("w2"));
assert_eq!(workspace_for(&panes, Path::new("/home/alex")), None);
}
/// A failure says why in herdr's words, and anything that isn't its JSON passes through.
///
/// The break this catches: showing the device herdr's raw JSON, or nothing when it isn't JSON.
#[test]
fn a_refusal_says_why_in_herdrs_words() {
let stderr = r#"{"error":{"code":"pane_not_found","message":"pane w9:p9 not found"},"id":"cli:request"}"#;
assert_eq!(refusal(stderr), "pane w9:p9 not found");
assert_eq!(refusal(" no server\n"), "no server");
}

View File

@@ -0,0 +1,90 @@
use super::*;
fn session(pid: u32, cwd: &Path) -> LiveSession {
LiveSession {
pid,
session_id: format!("session-{pid}"),
cwd: cwd.to_string_lossy().into_owned(),
address: String::new(),
luxe_version: "0.1.3".into(),
}
}
/// `~` and `~/sub` are the home folder and a folder in it.
///
/// The break this catches: taking `~` literally, so the folder a person types on a phone keyboard
/// is refused as not a full path.
#[test]
fn a_tilde_is_the_home_folder() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir(home.path().join("app")).unwrap();
assert_eq!(resolve_folder("~", Some(home.path())).unwrap(), home.path());
assert_eq!(resolve_folder(" ~/app ", Some(home.path())).unwrap(), home.path().join("app"));
}
/// A relative path is refused rather than resolved against wherever the bridge happens to run.
///
/// The break this catches: dropping the full-path check, so `app` starts Luxe in the service's
/// working folder, which nobody chose.
#[test]
fn a_relative_path_is_refused() {
let home = tempfile::tempdir().unwrap();
let refused = resolve_folder("app", Some(home.path())).unwrap_err();
assert!(refused.to_string().contains("isn't a full path"), "{refused}");
}
/// A file, or nothing at all, isn't a folder to start in.
///
/// The break this catches: checking only that the path exists, so a file reaches the child as its
/// working folder and the start fails with an OS error nobody can act on.
#[test]
fn only_a_folder_that_exists_is_accepted() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("notes.txt");
std::fs::write(&file, "").unwrap();
for path in [file, dir.path().join("missing")] {
let refused = resolve_folder(&path.to_string_lossy(), None).unwrap_err();
assert!(refused.to_string().contains("isn't a folder"), "{refused}");
}
}
/// The new session is the one that appeared since, in the folder asked for or a parent of it.
///
/// The break this catches, one per session in the list: answering with a session that was already
/// running there (1), or one that started elsewhere at the same moment (2). The last one is found
/// because a Luxe started in a repository's subfolder shares the repository's root.
#[test]
fn the_new_session_is_the_one_that_appeared_where_it_was_asked_for() {
let root = tempfile::tempdir().unwrap();
let asked = root.path().join("crates/app");
std::fs::create_dir_all(&asked).unwrap();
let elsewhere = tempfile::tempdir().unwrap();
let running = [session(1, &asked), session(2, elsewhere.path()), session(3, root.path())];
let before = HashSet::from([1]);
let found = newcomer(&running, &before, &asked).expect("the session in the repository");
assert_eq!(found.pid, 3);
assert_eq!(newcomer(&running[..2], &before, &asked), None);
}
/// A child started for a device shares its session, and ends when the bridge lets go of it.
///
/// The break this catches: losing the child's stdin, which ends the session the moment it starts,
/// or keeping it past the bridge, which leaves sessions running that nothing can reach.
#[cfg(unix)]
#[tokio::test]
async fn a_child_runs_while_the_bridge_holds_it() {
let runtime = tempfile::tempdir().unwrap();
let folder = tempfile::tempdir().unwrap();
let book = FolderBook::at(runtime.path().join("folders.json"));
let launcher = Launcher::new(crate::tests::fake_luxe(runtime.path()), Herdr::Off, book);
let (started, place) = launcher.start(folder.path(), runtime.path()).await.unwrap();
assert_eq!(place, Place::Bridge);
assert!(luxe_core::program::process_is_alive(started.pid));
drop(launcher);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while luxe_core::program::process_is_alive(started.pid) {
assert!(std::time::Instant::now() < deadline, "the child outlived the bridge");
tokio::time::sleep(Duration::from_millis(50)).await;
}
}

View File

@@ -0,0 +1,221 @@
//! Luxe remote — the bridge between your own devices and the sessions running on this machine.
//!
//! Each running Luxe shares its session on a local endpoint only this user can open
//! (`luxe_core::local_endpoint`). The bridge is the one thing that puts those sessions on a
//! network, and only on the loopback interface: Tailscale Serve carries it to your tailnet and does
//! the HTTPS. A phone lists the sessions over HTTP and joins one over a WebSocket, which the bridge
//! pipes to that session's endpoint a protocol line per text frame. What crosses is the published
//! `--rpc` protocol, untouched, so the bridge holds no session state of its own.
//!
//! Who gets in is the `access` module's call: a tailnet login on the allowlist, and a device paired
//! through [`DeviceBook`].
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
mod access;
mod app;
mod devices;
mod folders;
mod home_screen;
mod launch;
mod pairing;
mod push;
mod relay;
mod render;
mod routes;
mod secrets;
pub mod service;
mod sessions;
mod tailnet;
pub use devices::{Device, DeviceBook, PairingError, INVITATION_LIFETIME_SECS};
pub use render::{
ContextUsage, FileMark, GithubMarks, MarkHue, Renderer, StatusFacts, StatusSegment, StatusTone,
TileColors, Voice,
};
pub use tailnet::{publish, published, this_machine, Published, Tailnet, TailnetError};
/// How often the bridge rereads the paired devices to close a revoked one's sockets.
const REVOCATION_CHECK: Duration = Duration::from_secs(2);
/// Who may use the bridge.
#[derive(Debug, Clone)]
pub struct Access {
/// Tailnet logins allowed in, as Tailscale Serve reports them (`alex@github`)
pub logins: Vec<String>,
/// The paired devices
pub devices: DeviceBook,
}
/// Why the bridge could not start or keep serving.
#[derive(Debug, thiserror::Error)]
pub enum RemoteError {
/// The address is reachable from beyond this machine
#[error(
"refusing to listen on {0}: the bridge listens on this machine only, and Tailscale Serve \
takes it to your devices"
)]
NotLoopback(SocketAddr),
/// The port could not be bound or served
#[error("could not {action} on {address}: {source}")]
Io {
/// What was being done
action: &'static str,
/// Where
address: SocketAddr,
/// The operating system's reason
#[source]
source: std::io::Error,
},
/// The paired-device file could not be read or written
#[error("paired devices: {0}")]
Devices(#[from] luxe_core::json_file::FileError),
/// An invitation was turned down
#[error(transparent)]
Pairing(#[from] PairingError),
}
/// A bridge bound to its port, ready to serve.
pub struct Bridge {
listener: tokio::net::TcpListener,
address: SocketAddr,
runtime_dir: PathBuf,
access: Access,
launcher: Option<launch::Launcher>,
renderer: std::sync::Arc<dyn Renderer>,
presence: push::Presence,
courier: Option<std::sync::Arc<dyn push::Courier>>,
machine: Option<String>,
}
impl Bridge {
/// Binds `address`, which must be on the loopback interface, to serve the sessions recorded in
/// `runtime_dir` to those `access` lets in.
///
/// Loopback is enforced here rather than left to a default: anything wider would put every
/// session in reach of the local network, with only the device check in front of it.
pub async fn bind(
address: SocketAddr,
runtime_dir: PathBuf,
access: Access,
) -> Result<Self, RemoteError> {
let (listener, address) = listen_on(address).await?;
Ok(Self::listening(listener, address, runtime_dir, access))
}
/// A bridge on `listener` with nothing added yet: plain text, no launcher, no name.
fn listening(
listener: tokio::net::TcpListener,
address: SocketAddr,
runtime_dir: PathBuf,
access: Access,
) -> Self {
Self {
listener,
address,
runtime_dir,
access,
launcher: None,
renderer: std::sync::Arc::new(render::PlainText),
presence: push::Presence::default(),
courier: None,
machine: None,
}
}
/// Names the computer it serves, as its tailnet does, on the phone's app and its
/// notifications: one phone can have an app for each of several computers.
pub fn named(mut self, machine: impl Into<String>) -> Self {
self.machine = Some(machine.into());
self
}
/// Renders messages for the app with `renderer`. Without one the app shows plain text.
pub fn rendering_with(mut self, renderer: std::sync::Arc<dyn Renderer>) -> Self {
self.renderer = renderer;
self
}
/// Lets devices start sessions: in a herdr pane when herdr is running, otherwise by running
/// `program`, the bridge's own `luxe`, as `luxe --rpc`.
pub fn starting_sessions(self, program: PathBuf) -> Self {
let folders = folders::FolderBook::at(folders::FolderBook::default_path());
self.with_launcher(launch::Launcher::new(program, launch::Herdr::WhenRunning, folders))
}
pub(crate) fn with_launcher(mut self, launcher: launch::Launcher) -> Self {
self.launcher = Some(launcher);
self
}
/// Posts notifications through `courier` instead of Web Push.
#[cfg(test)]
pub(crate) fn notifying_through(mut self, courier: std::sync::Arc<dyn push::Courier>) -> Self {
self.courier = Some(courier);
self
}
/// Which devices have which sessions open.
#[cfg(test)]
pub(crate) fn presence(&self) -> push::Presence {
self.presence.clone()
}
/// Where it is listening, with the port the system picked when asked for port 0.
pub fn address(&self) -> SocketAddr {
self.address
}
/// Serves until `shutdown` resolves.
pub async fn serve(
self,
shutdown: impl std::future::Future<Output = ()> + Send + 'static,
) -> Result<(), RemoteError> {
let address = self.address;
let devices = self.access.devices.clone();
let (runtime_dir, presence) = (self.runtime_dir.clone(), self.presence.clone());
let (courier, machine) = (self.courier.clone(), self.machine.clone());
let _notifying = push::start(runtime_dir, devices, presence, courier, machine);
let (listener, app) = self.into_router();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown)
.await
.map_err(|source| RemoteError::Io { action: "serve", address, source })
}
fn into_router(self) -> (tokio::net::TcpListener, axum::Router) {
let app = routes::router(routes::Bridged {
runtime_dir: self.runtime_dir,
logins: self.access.logins,
devices: self.access.devices,
launcher: self.launcher,
renderer: self.renderer,
presence: self.presence,
machine: self.machine,
});
(self.listener, app)
}
}
/// A listener on `address`, which must be on the loopback interface, and where it landed.
async fn listen_on(
address: SocketAddr,
) -> Result<(tokio::net::TcpListener, SocketAddr), RemoteError> {
if !address.ip().is_loopback() {
return Err(RemoteError::NotLoopback(address));
}
let listener = tokio::net::TcpListener::bind(address)
.await
.map_err(|source| RemoteError::Io { action: "listen", address, source })?;
let landed = listener.local_addr().map_err(|source| RemoteError::Io {
action: "read the address",
address,
source,
})?;
Ok((listener, landed))
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,45 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pair with Luxe</title>
<style>
body { background: #161616; color: #d8d8d8; font: 15px/1.5 ui-monospace, monospace; margin: 2rem; }
h1 { font-size: 1rem; color: #e0b46c; }
input, button { font: inherit; padding: .5rem; margin: .25rem 0; width: 100%; box-sizing: border-box; }
.error { color: #e06c6c; }
</style>
</head>
<body>
<h1>Pair this device with Luxe</h1>
<form id="pair">
<label>Device name <input id="name" autocomplete="off"></label>
<button>Pair</button>
</form>
<p id="status"></p>
<script type="module">
const guess = /iPad/.test(navigator.userAgent) ? "iPad" : /iPhone/.test(navigator.userAgent) ? "iPhone" : "";
document.getElementById("name").value = guess;
// the invitation rides in the fragment, which a browser never sends to a server or a log
const invitation = location.hash.slice(1);
history.replaceState(null, "", location.pathname);
const status = document.getElementById("status");
document.getElementById("pair").addEventListener("submit", async (event) => {
event.preventDefault();
const name = document.getElementById("name").value;
const response = await fetch("/api/pair", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ invitation, name }),
});
if (response.ok) {
location.replace("/");
return;
}
status.className = "error";
status.textContent = await response.text();
});
</script>
</body>
</html>

View File

@@ -0,0 +1,88 @@
//! Pairing — a device trades an invitation for a credential of its own.
use std::sync::Arc;
use axum::extract::State;
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
use serde::Deserialize;
use crate::access::{credential_cookie, Login};
use crate::routes::Bridged;
use crate::RemoteError;
/// Longest name a device keeps; it is a label in a list, not a description.
const NAME_LIMIT: usize = 40;
/// What the pairing page sends.
#[derive(Debug, Deserialize)]
pub(crate) struct PairRequest {
invitation: String,
#[serde(default)]
name: String,
}
/// Redeems the invitation and sets the device's credential as a cookie the page never sees.
pub(crate) async fn pair(
State(bridged): State<Arc<Bridged>>,
Extension(Login(login)): Extension<Login>,
Json(request): Json<PairRequest>,
) -> Response {
let devices = bridged.devices.clone();
let name = device_name(&request.name);
let paired =
tokio::task::spawn_blocking(move || devices.pair(request.invitation.trim(), &name, &login))
.await;
match paired {
Ok(outcome) => answer(outcome),
Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(),
}
}
fn answer(paired: Result<(crate::devices::Device, String), RemoteError>) -> Response {
match paired {
Ok((device, credential)) => {
tracing::info!(device = %device.name, id = %device.id, "a device paired");
let cookie = [(header::SET_COOKIE, credential_cookie(&credential))];
let body = serde_json::json!({ "id": device.id, "name": device.name });
(cookie, Json(body)).into_response()
}
Err(RemoteError::Pairing(refused)) => {
(StatusCode::BAD_REQUEST, refused.to_string()).into_response()
}
Err(error) => {
tracing::error!(%error, "could not record a paired device");
(StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response()
}
}
}
/// The name a device asked for, made fit for a list: one line, bounded, never empty.
fn device_name(asked: &str) -> String {
let name: String =
asked.chars().map(|c| if c.is_control() { ' ' } else { c }).take(NAME_LIMIT).collect();
let name = name.trim();
if name.is_empty() {
"Device".to_string()
} else {
name.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A device's name is a single bounded line, so `luxe remote devices` stays a list.
///
/// The break this catches: storing the name as sent, so a newline forges a second row in the
/// listing, or an empty one leaves a row with nothing to recognize it by.
#[test]
fn a_device_name_is_one_short_line() {
assert_eq!(device_name("Evan's iPhone"), "Evan's iPhone");
assert_eq!(device_name("phone\nabc1234 Fake"), "phone abc1234 Fake");
assert_eq!(device_name(" "), "Device");
assert_eq!(device_name(&"x".repeat(100)).len(), NAME_LIMIT);
}
}

View File

@@ -0,0 +1,153 @@
//! Push — notifications on your devices when a session wants you, sent by the bridge itself.
//!
//! Web Push, as iOS has offered it to home-screen web apps since 16.4: a device that opted in
//! gives the bridge a subscription, and the bridge posts each notification, sealed so only that
//! device can read it, straight to the push service the subscription names (Apple's, for an
//! iPhone). There is no Luxe server in between, and the push service sees when, not what.
//!
//! [`watch`] hears what the sessions are waiting for, and [`notify`] takes each notice to every
//! subscribed device that doesn't have that session open in front of it.
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::mpsc;
pub(crate) mod api;
mod encryption;
mod notice;
mod presence;
mod subscription;
mod vapid;
mod watch;
mod web_push;
pub(crate) use presence::Presence;
pub(crate) use subscription::Subscription;
#[cfg(test)]
pub(crate) use subscription::{tests::FROM_SAFARI, SubscriptionKeys};
#[cfg(test)]
pub(crate) use tests::Recording;
pub(crate) use vapid::{Vapid, VapidError};
pub(crate) use web_push::Courier;
use crate::devices::{Device, DeviceBook};
use notice::Notice;
use web_push::{Delivery, WebPush};
/// Notices heard but not yet posted. A few sessions, each with a prompt or two at a time.
const NOTICE_BUFFER: usize = 64;
/// Notifications from the sessions under `runtime_dir` to the devices in `devices`, until the
/// returned guard drops. They go through `courier`, or Web Push signed with the bridge's key, each
/// titled with `machine` when the bridge has a name.
pub(crate) fn start(
runtime_dir: PathBuf,
devices: DeviceBook,
presence: Presence,
courier: Option<Arc<dyn Courier>>,
machine: Option<String>,
) -> watch::Watcher {
watch::Watcher(tokio::spawn(notify(runtime_dir, devices, presence, courier, machine)))
}
async fn notify(
runtime_dir: PathBuf,
devices: DeviceBook,
presence: Presence,
mut courier: Option<Arc<dyn Courier>>,
machine: Option<String>,
) {
let (heard, mut notices) = mpsc::channel(NOTICE_BUFFER);
let watching = watch::watch_sessions(runtime_dir, devices.clone(), heard);
let _watching = watch::Watcher(tokio::spawn(watching));
while let Some(notice) = notices.recv().await {
let Some(courier) = courier_for(&mut courier, &devices).await else { continue };
let notice = on_machine(notice, machine.as_deref());
dispatch(&devices, &presence, &*courier, &notice).await;
}
}
/// `notice` titled with the computer it came from as well as the project, so a phone paired with
/// two computers can tell which one wants it: `luxe · desk`.
fn on_machine(mut notice: Notice, machine: Option<&str>) -> Notice {
if let Some(machine) = machine {
notice.title = format!("{} \u{00b7} {machine}", notice.title);
}
notice
}
/// The courier, made on first use: the key is made when a device first subscribes, so it's there
/// by the time anything is heard.
async fn courier_for(
kept: &mut Option<Arc<dyn Courier>>,
devices: &DeviceBook,
) -> Option<Arc<dyn Courier>> {
if let Some(courier) = kept {
return Some(courier.clone());
}
match web_push(devices.clone()).await {
Ok(courier) => Some(kept.insert(Arc::new(courier)).clone()),
Err(error) => {
tracing::error!(%error, "couldn't set up notifications");
None
}
}
}
/// Web Push with the bridge's key, for logging when it can't be had.
async fn web_push(devices: DeviceBook) -> Result<WebPush, String> {
match tokio::task::spawn_blocking(move || devices.push_key()).await {
Ok(Ok(vapid)) => WebPush::new(vapid).map_err(|error| error.to_string()),
Ok(Err(error)) => Err(error.to_string()),
Err(error) => Err(error.to_string()),
}
}
/// Posts `notice` to every subscribed device that doesn't have its session open.
async fn dispatch(
devices: &DeviceBook,
presence: &Presence,
courier: &dyn Courier,
notice: &Notice,
) {
let reader = devices.clone();
let paired = tokio::task::spawn_blocking(move || reader.devices()).await.unwrap_or_default();
for device in &paired {
let Some(subscription) = device.subscription() else { continue };
if presence.is_here(&device.id, &notice.session) {
tracing::debug!(device = %device.name, "not notifying a device looking at the session");
continue;
}
let delivered = courier.deliver(subscription, notice).await;
settle(devices, device, &subscription.endpoint, delivered).await;
}
}
/// Logs how a post went, and forgets a subscription its push service says is gone.
async fn settle(
devices: &DeviceBook,
device: &Device,
endpoint: &str,
delivered: Result<Delivery, web_push::PushError>,
) {
match delivered {
Ok(Delivery::Taken) => tracing::debug!(device = %device.name, "sent a notification"),
Ok(Delivery::Gone) => {
tracing::info!(device = %device.name, "a device's notifications ended at its push service");
forget(devices.clone(), device.id.clone(), endpoint.to_string()).await;
}
Err(error) => tracing::warn!(%error, device = %device.name, "couldn't send a notification"),
}
}
/// Drops the device's subscription, unless it has since subscribed somewhere new.
async fn forget(devices: DeviceBook, id: String, endpoint: String) {
let forgot = tokio::task::spawn_blocking(move || devices.forget_endpoint(&id, &endpoint));
if let Ok(Err(error)) = forgot.await {
tracing::warn!(%error, "couldn't forget an ended subscription");
}
}
#[cfg(test)]
pub(crate) mod tests;

View File

@@ -0,0 +1,87 @@
//! The routes a device turns its notifications on and off with, behind the paired-device check.
//!
//! `GET /api/push` gives the key to subscribe with and whether this device is subscribed,
//! `PUT /api/push` takes the subscription the browser made, and `DELETE /api/push` stops them.
use std::sync::Arc;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
use super::Subscription;
use crate::access::Refusal;
use crate::devices::Device;
use crate::routes::Bridged;
/// What the app needs to subscribe, or to show that it has.
#[derive(serde::Serialize)]
struct PushStatus {
/// The bridge's public key, base64url, for `PushManager.subscribe`
key: String,
/// Whether the bridge has a subscription for this device
subscribed: bool,
}
/// The bridge's push key, and whether this device is subscribed.
pub(crate) async fn status(
State(bridged): State<Arc<Bridged>>,
Extension(device): Extension<Device>,
) -> Response {
let devices = bridged.devices.clone();
let key = tokio::task::spawn_blocking(move || devices.push_key()).await;
match key {
Ok(Ok(vapid)) => {
let subscribed = device.subscription().is_some();
Json(PushStatus { key: vapid.public_key(), subscribed }).into_response()
}
Ok(Err(error)) => failed(&error),
Err(error) => failed(&error),
}
}
/// Sends this device's notifications to the subscription its browser made.
pub(crate) async fn subscribe(
State(bridged): State<Arc<Bridged>>,
Extension(device): Extension<Device>,
Json(subscription): Json<Subscription>,
) -> Response {
match subscription.checked() {
Ok(subscription) => keep(&bridged, &device, Some(subscription)).await,
Err(refused) => {
tracing::warn!(device = %device.name, %refused, "refused a push subscription");
(StatusCode::BAD_REQUEST, refused.to_string()).into_response()
}
}
}
/// Stops this device's notifications.
pub(crate) async fn unsubscribe(
State(bridged): State<Arc<Bridged>>,
Extension(device): Extension<Device>,
) -> Response {
keep(&bridged, &device, None).await
}
async fn keep(bridged: &Bridged, device: &Device, subscription: Option<Subscription>) -> Response {
let (devices, id) = (bridged.devices.clone(), device.id.clone());
let on = subscription.is_some();
let kept = tokio::task::spawn_blocking(move || devices.subscribe(&id, subscription)).await;
match kept {
Ok(Ok(true)) => {
tracing::info!(device = %device.name, on, "a device changed its notifications");
StatusCode::NO_CONTENT.into_response()
}
// revoked since the request was let in
Ok(Ok(false)) => Refusal::NotPaired.into_response(),
Ok(Err(error)) => failed(&error),
Err(error) => failed(&error),
}
}
fn failed(error: &dyn std::error::Error) -> Response {
tracing::error!(%error, "couldn't read or keep a push subscription");
let reason = format!("couldn't keep notifications: {error}");
(StatusCode::INTERNAL_SERVER_ERROR, reason).into_response()
}

View File

@@ -0,0 +1,120 @@
//! Encryption — a push message sealed for one device, as RFC 8291 has it.
//!
//! The push service carries the message and can't read it: each one is sealed with a key agreed
//! between a throwaway key of the bridge's and the key the device's browser made when it
//! subscribed, mixed with the subscription's own secret.
use ring::rand::SecureRandom;
use ring::{aead, agreement, hkdf, rand};
/// The record size a message declares. One record holds the whole message, which a push service
/// caps at 4 KiB anyway.
const RECORD_SIZE: u32 = 4096;
/// Bytes a record adds to its message: the delimiter that ends the last record, and the AES-GCM
/// tag.
const RECORD_OVERHEAD: usize = 1 + 16;
/// Why a message couldn't be sealed.
#[derive(Debug, thiserror::Error)]
pub(crate) enum EncryptionError {
/// The subscription's key isn't a P-256 point
#[error("the subscription's key isn't a P-256 public key")]
BadSubscriptionKey,
/// The message won't fit one record
#[error("a push message of {0} bytes is too long for one record")]
TooLong(usize),
/// The system's randomness failed
#[error("the system's random number source failed")]
Random,
}
/// The two secrets a message is sealed with.
#[derive(Debug, PartialEq, Eq)]
struct ContentKeys {
key: [u8; 16],
nonce: [u8; 12],
}
/// `message` sealed for the subscription with public key `device_key` and secret `auth`, as the
/// body of an `aes128gcm` push request.
pub(crate) fn encrypt(
message: &[u8],
device_key: &[u8],
auth: &[u8],
) -> Result<Vec<u8>, EncryptionError> {
if message.len() + RECORD_OVERHEAD > RECORD_SIZE as usize {
return Err(EncryptionError::TooLong(message.len()));
}
let random = rand::SystemRandom::new();
let (ours, our_key) = throwaway_key(&random)?;
let mut salt = [0u8; 16];
random.fill(&mut salt).map_err(|_| EncryptionError::Random)?;
let theirs = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, device_key);
let keys = agreement::agree_ephemeral(ours, &theirs, |shared| {
content_keys(shared, auth, device_key, our_key.as_ref(), &salt)
})
.map_err(|_| EncryptionError::BadSubscriptionKey)?;
Ok(seal(&keys, &salt, our_key.as_ref(), message))
}
/// A key pair for one message, so a message read once its key leaks says nothing of the others.
fn throwaway_key(
random: &rand::SystemRandom,
) -> Result<(agreement::EphemeralPrivateKey, agreement::PublicKey), EncryptionError> {
let ours = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, random)
.map_err(|_| EncryptionError::Random)?;
let public = ours.compute_public_key().map_err(|_| EncryptionError::Random)?;
Ok((ours, public))
}
/// The content keys from the agreed secret, RFC 8291 section 3.4: the subscription's secret and
/// both public keys are mixed in first, then the message's salt.
fn content_keys(
shared: &[u8],
auth: &[u8],
device_key: &[u8],
our_key: &[u8],
salt: &[u8],
) -> ContentKeys {
let key_info = [b"WebPush: info\0".as_slice(), device_key, our_key].concat();
let combined = hkdf::Salt::new(hkdf::HKDF_SHA256, auth).extract(shared);
let keying: [u8; 32] = expand(&combined, &key_info);
let content = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(&keying);
ContentKeys {
key: expand(&content, b"Content-Encoding: aes128gcm\0"),
nonce: expand(&content, b"Content-Encoding: nonce\0"),
}
}
/// The header (salt, record size, the bridge's key) and then the one sealed record.
fn seal(keys: &ContentKeys, salt: &[u8; 16], our_key: &[u8], message: &[u8]) -> Vec<u8> {
let mut record = [message, &[2]].concat();
let unbound =
aead::UnboundKey::new(&aead::AES_128_GCM, &keys.key).expect("16 bytes is an AES-128 key");
let nonce = aead::Nonce::assume_unique_for_key(keys.nonce);
aead::LessSafeKey::new(unbound)
.seal_in_place_append_tag(nonce, aead::Aad::empty(), &mut record)
.expect("one record is far below AES-GCM's length limit");
let key_length = u8::try_from(our_key.len()).expect("a P-256 point is 65 bytes");
let header = [salt.as_slice(), &RECORD_SIZE.to_be_bytes(), &[key_length], our_key].concat();
[header, record].concat()
}
/// `N` bytes of HKDF output.
fn expand<const N: usize>(key: &hkdf::Prk, info: &[u8]) -> [u8; N] {
struct Length(usize);
impl hkdf::KeyType for Length {
fn len(&self) -> usize {
self.0
}
}
let mut out = [0u8; N];
key.expand(&[info], Length(N))
.and_then(|okm| okm.fill(&mut out))
.expect("HKDF-SHA-256 gives up to 8160 bytes");
out
}
#[cfg(test)]
pub(crate) mod tests;

View File

@@ -0,0 +1,105 @@
use super::*;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
/// RFC 8291 Appendix A, whose values every test here is held to.
mod rfc {
pub(super) const MESSAGE: &str = "When I grow up, I want to be a watermelon";
pub(super) const OUR_KEY: &str =
"BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8";
pub(super) const DEVICE_KEY: &str =
"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
pub(super) const SALT: &str = "DGv6ra1nlYgDCS1FRnbzlw";
pub(super) const AUTH: &str = "BTBZMqHH6r4Tts7J_aSIgg";
pub(super) const SHARED: &str = "kyrL1jIIOHEzg3sM2ZWRHDRB62YACZhhSlknJ672kSs";
pub(super) const CONTENT_KEY: &str = "oIhVW04MRdy2XN9CiKLxTg";
pub(super) const NONCE: &str = "4h_95klXJ5E_qnoN";
pub(super) const HEADER: &str = "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8";
pub(super) const SEALED: &str =
"8pfeW0KbunFT06SuDKoJH9Ql87S1QUrdirN6GcG7sFz1y1sqLgVi1VhjVkHsUoEsbI_0LpXMuGvnzQ";
}
fn bytes(base64url: &str) -> Vec<u8> {
URL_SAFE_NO_PAD.decode(base64url).expect("the RFC's values are base64url")
}
fn rfc_keys() -> ContentKeys {
let (shared, auth) = (bytes(rfc::SHARED), bytes(rfc::AUTH));
let (device, ours, salt) = (bytes(rfc::DEVICE_KEY), bytes(rfc::OUR_KEY), bytes(rfc::SALT));
content_keys(&shared, &auth, &device, &ours, &salt)
}
/// The key and nonce come out as the RFC's do from its agreed secret.
///
/// The break this catches: any slip in the key schedule (the info strings, which key goes first,
/// salt and secret swapped), each of which a device rejects as a message it can't open.
#[test]
fn the_content_keys_are_the_rfcs() {
let keys = rfc_keys();
assert_eq!(keys.key.as_slice(), bytes(rfc::CONTENT_KEY));
assert_eq!(keys.nonce.as_slice(), bytes(rfc::NONCE));
}
/// The sealed body is the RFC's header and ciphertext, byte for byte.
///
/// The break this catches: a wrong header field (record size, key length, the device's key where
/// ours belongs) or a missing end-of-record delimiter.
#[test]
fn a_message_is_sealed_as_the_rfcs() {
let salt: [u8; 16] = bytes(rfc::SALT).try_into().expect("16 bytes");
let body = seal(&rfc_keys(), &salt, &bytes(rfc::OUR_KEY), rfc::MESSAGE.as_bytes());
assert_eq!(body, [bytes(rfc::HEADER), bytes(rfc::SEALED)].concat());
}
/// A device opens what `encrypt` sealed for it, agreeing its key with the one in the header.
///
/// The break this catches: `encrypt` mixing the keys in the wrong order or putting the wrong key
/// in the header, which the pinned halves above can't see.
#[test]
fn a_device_opens_what_was_sealed_for_it() {
let random = rand::SystemRandom::new();
let device = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &random).unwrap();
let device_key = device.compute_public_key().unwrap();
let auth = [7u8; 16];
let body = encrypt(b"Approve bash", device_key.as_ref(), &auth).unwrap();
assert_eq!(open(device, device_key.as_ref(), &auth, &body), b"Approve bash\x02");
}
/// What the device with private key `device` reads from `body`, as its browser would: the key in
/// the header agreed with its own, and the one record opened, delimiter and all.
pub(crate) fn open(
device: agreement::EphemeralPrivateKey,
device_key: &[u8],
auth: &[u8],
body: &[u8],
) -> Vec<u8> {
let (salt, our_key, sealed) = (&body[..16], &body[21..86], &body[86..]);
let ours = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, our_key);
let keys = agreement::agree_ephemeral(device, &ours, |shared| {
content_keys(shared, auth, device_key, our_key, salt)
})
.expect("the header's key is on the curve");
let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &keys.key).unwrap());
let mut record = sealed.to_vec();
let nonce = aead::Nonce::assume_unique_for_key(keys.nonce);
key.open_in_place(nonce, aead::Aad::empty(), &mut record).expect("it opens").to_vec()
}
/// The break this catches: sealing a message longer than its record says, which the push service
/// refuses, rather than saying why here.
#[test]
fn a_message_too_long_for_one_record_is_refused() {
let device = [4u8; 65];
let longest = vec![b'x'; RECORD_SIZE as usize - RECORD_OVERHEAD];
assert!(!matches!(encrypt(&longest, &device, &[0; 16]), Err(EncryptionError::TooLong(_))));
let longer = vec![b'x'; longest.len() + 1];
assert!(matches!(encrypt(&longer, &device, &[0; 16]), Err(EncryptionError::TooLong(_))));
}
/// The break this catches: a key that isn't on the curve sealed for anyway, sending a message no
/// device can open.
#[test]
fn a_key_off_the_curve_is_refused() {
let sealed = encrypt(b"hi", &[4u8; 65], &[0; 16]);
assert!(matches!(sealed, Err(EncryptionError::BadSubscriptionKey)));
}

View File

@@ -0,0 +1,118 @@
//! Notice — what a notification says, read from one session's events.
//!
//! A notification says what is waiting and where, never the detail: "Approve bash" with the
//! folder's name, not the command, and opening it leads to the prompt. Answering takes the app.
//!
//! Two rules keep it from buzzing at someone sitting at their desk. A prompt is held for a few
//! seconds first, and one answered meanwhile is never sent. A turn's end is only news when the
//! turn ran long enough for someone to have walked away.
use luxe_core::{Event, StopReason};
use std::time::Duration;
use tokio::time::Instant;
/// How long a prompt waits before it's sent, for an answer at the desk to beat it.
pub(crate) const PROMPT_GRACE: Duration = Duration::from_secs(10);
/// The shortest turn whose end is sent: a quick reply is read where it was asked for.
pub(crate) const LONG_TURN: Duration = Duration::from_secs(30);
/// One notification, as the service worker shows it.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub(crate) struct Notice {
/// The project folder's name
pub(crate) title: String,
/// What's waiting, in a few words
pub(crate) body: String,
/// The session it opens
pub(crate) session: String,
/// Whether to deliver now rather than when the device saves power
#[serde(skip)]
pub(crate) urgent: bool,
}
/// What an event means for notifications.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Heard {
/// Send this now
Now(Notice),
/// Send this unless prompt `id` closes within [`PROMPT_GRACE`]
Prompt(String, Notice),
/// Prompt `id` was answered, wherever
Closed(String),
}
/// One session's stream, read for what's worth a notification.
pub(crate) struct Reading {
session: String,
folder: String,
turn_began: Option<Instant>,
}
impl Reading {
/// A reading of the session `session` running in `cwd`.
pub(crate) fn new(session: &str, cwd: &str) -> Self {
let folder = std::path::Path::new(cwd).file_name().map(|name| name.to_string_lossy());
let folder = folder.map_or_else(|| cwd.to_string(), |name| name.into_owned());
Self { session: session.to_string(), folder, turn_began: None }
}
/// What `event`, seen at `now`, means.
pub(crate) fn read(&mut self, event: &Event, now: Instant) -> Option<Heard> {
if is_turn_sign(event) {
self.turn_began.get_or_insert(now);
}
match event {
Event::Ready { session_id, .. } | Event::SessionLoaded { session_id, .. } => {
self.session.clone_from(session_id);
None
}
Event::PermissionRequested { .. } | Event::QuestionAsked { .. } => self.prompt(event),
Event::PromptClosed { id } => Some(Heard::Closed(id.clone())),
Event::TurnEnded { reason } => self.turn_ended(reason, now).map(Heard::Now),
_ => None,
}
}
fn prompt(&self, event: &Event) -> Option<Heard> {
let (id, body) = match event {
Event::PermissionRequested { id, tool, .. } => (id.as_str(), format!("Approve {tool}")),
Event::QuestionAsked { id, .. } => (id.as_str(), "Luxe has a question".to_string()),
_ => return None,
};
Some(Heard::Prompt(id.to_string(), self.notice(body, true)))
}
fn turn_ended(&mut self, reason: &StopReason, now: Instant) -> Option<Notice> {
let began = self.turn_began.take()?;
if now.duration_since(began) < LONG_TURN {
return None;
}
let body = match reason {
StopReason::EndTurn | StopReason::ToolCall => "Finished, and waiting for you",
StopReason::Other(_) => "Stopped",
};
Some(self.notice(body.into(), false))
}
fn notice(&self, body: String, urgent: bool) -> Notice {
Notice { title: self.folder.clone(), body, session: self.session.clone(), urgent }
}
}
/// Whether `event` shows a turn running. The engine says so with `TurnStarted`, which comes
/// first; the message that opened the turn, or anything it streams, stands in for it from a
/// session whose Luxe predates that event.
fn is_turn_sign(event: &Event) -> bool {
match event {
Event::TurnStarted
| Event::TokenDelta { .. }
| Event::ThinkingDelta { .. }
| Event::ToolCallComposing { .. } => true,
Event::MessageCommitted { message, .. } => message.role == luxe_core::message::Role::User,
_ => false,
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,126 @@
use super::*;
use luxe_core::Message;
/// Frames as a session sends them, copied from core's pinned wire shapes.
const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#;
const QUESTION: &str = r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"session-1","prompt":"Which database?","options":[{"label":"postgres","description":"Relational, boring, correct","recommended":true}],"multi":false}}"#;
const CLOSED: &str = r#"{"kind":"prompt_closed","content":{"id":"perm:1"}}"#;
const DELTA: &str = r#"{"kind":"token_delta","content":{"block":0,"delta":"hello"}}"#;
const FINISHED: &str = r#"{"kind":"turn_ended","content":{"reason":"end_turn"}}"#;
fn event(line: &str) -> Event {
serde_json::from_str(line).expect("a protocol frame")
}
fn committed(message: Message) -> Event {
let frame = serde_json::json!({
"kind": "message_committed",
"content": { "session_id": "session-1", "entry_id": "e1", "message": message },
});
serde_json::from_value(frame).expect("a committed message")
}
fn reading() -> Reading {
Reading::new("session-1", "/home/alex/work/luxe-dev")
}
/// A notice for `body` from the reading above.
fn notice(body: &str, urgent: bool) -> Notice {
let (title, session) = ("luxe-dev".into(), "session-1".into());
Notice { title, body: body.into(), session, urgent }
}
/// The break this catches: the command, the question's text or its options in the notification,
/// where a lock screen shows them to whoever is looking.
#[test]
fn a_prompt_says_what_waits_and_never_the_detail() {
let now = Instant::now();
let asked = reading().read(&event(PERMISSION), now);
assert_eq!(asked, Some(Heard::Prompt("perm:1".into(), notice("Approve bash", true))));
let asked = reading().read(&event(QUESTION), now);
let expected = Heard::Prompt("ask:1".into(), notice("Luxe has a question", true));
assert_eq!(asked, Some(expected));
assert_eq!(reading().read(&event(CLOSED), now), Some(Heard::Closed("perm:1".into())));
}
/// The break this catches: a quick reply at the desk buzzing the phone, or a long turn ending
/// without a word to someone who walked away.
#[test]
fn only_a_long_turns_end_is_news() {
let start = Instant::now();
let mut quick = reading();
quick.read(&committed(Message::user("hi")), start);
assert_eq!(quick.read(&event(FINISHED), start + LONG_TURN - Duration::from_secs(1)), None);
let mut long = reading();
long.read(&committed(Message::user("refactor it")), start);
let ended = long.read(&event(FINISHED), start + LONG_TURN);
assert_eq!(ended, Some(Heard::Now(notice("Finished, and waiting for you", false))));
}
/// The break this catches: timing a turn from its first sign each time it shows (every delta),
/// so no turn is ever long; or from a reply the model committed, which isn't a turn starting.
#[test]
fn a_turn_is_timed_from_its_first_sign() {
let start = Instant::now();
let mut reading = reading();
reading.read(&event(DELTA), start);
reading.read(&event(DELTA), start + LONG_TURN);
assert!(reading.read(&event(FINISHED), start + LONG_TURN).is_some(), "timed from the first");
let mut replies = super::tests::reading();
replies.read(&committed(Message::assistant("done")), start);
assert_eq!(replies.read(&event(FINISHED), start + LONG_TURN), None, "a reply isn't a start");
}
/// A turn is timed from `turn_started`, ahead of anything it streams.
///
/// The break this catches: ignoring `turn_started`, so a turn that spends its first seconds
/// waiting on the model is timed short, and its end isn't news.
#[test]
fn a_turn_is_timed_from_when_it_started() {
let start = Instant::now();
let mut reading = reading();
reading.read(&event(r#"{"kind":"turn_started"}"#), start);
reading.read(&event(DELTA), start + Duration::from_secs(20));
assert!(reading.read(&event(FINISHED), start + LONG_TURN).is_some());
}
/// The break this catches: a turn's start carried past its end, so the next quick turn looks long.
#[test]
fn each_turn_is_timed_on_its_own() {
let start = Instant::now();
let mut reading = reading();
reading.read(&event(DELTA), start);
reading.read(&event(FINISHED), start + Duration::from_secs(1));
reading.read(&event(DELTA), start + LONG_TURN);
assert_eq!(reading.read(&event(FINISHED), start + LONG_TURN + Duration::from_secs(1)), None);
}
/// The break this catches: reading a stop's free-text reason (ruled out), or calling a cancelled
/// or failed turn finished.
#[test]
fn a_turn_that_stopped_says_so() {
let start = Instant::now();
let mut reading = reading();
reading.read(&event(DELTA), start);
let stopped = Event::TurnEnded { reason: StopReason::Other("cancelled".into()) };
assert_eq!(
reading.read(&stopped, start + LONG_TURN),
Some(Heard::Now(notice("Stopped", false)))
);
}
/// The break this catches: a notice naming the session the watcher joined after the terminal
/// moved to another one, so opening it lands on a session that isn't running.
#[test]
fn a_notice_names_the_session_now_running() {
let mut reading = reading();
let loaded = serde_json::json!({
"kind": "session_loaded", "content": { "session_id": "session-2", "messages": [] },
});
reading.read(&serde_json::from_value(loaded).unwrap(), Instant::now());
let Some(Heard::Prompt(_, asked)) = reading.read(&event(PERMISSION), Instant::now()) else {
panic!("a prompt is heard");
};
assert_eq!(asked.session, "session-2");
}

View File

@@ -0,0 +1,72 @@
//! Presence — which devices have which session open right now.
//!
//! The app closes its socket when it's hidden, so an open socket means the session is on that
//! device's screen, and a notification about it would only repeat what's in front of you.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
/// A device id and a session id.
type Visit = (String, String);
/// The sockets open now, counted per device and session.
#[derive(Debug, Clone, Default)]
pub(crate) struct Presence {
open: Arc<Mutex<HashMap<Visit, usize>>>,
}
impl Presence {
/// Counts `device` as looking at `session` until the returned guard drops.
pub(crate) fn arrive(&self, device: &str, session: &str) -> Here {
let visit = (device.to_string(), session.to_string());
*self.lock().entry(visit.clone()).or_default() += 1;
Here { presence: self.clone(), visit }
}
/// Whether `device` has `session` open.
pub(crate) fn is_here(&self, device: &str, session: &str) -> bool {
self.lock().contains_key(&(device.to_string(), session.to_string()))
}
// a panic elsewhere can't leave a count half-changed, so a poisoned lock is still right
fn lock(&self) -> MutexGuard<'_, HashMap<Visit, usize>> {
self.open.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// One open socket, counted while it lives.
pub(crate) struct Here {
presence: Presence,
visit: Visit,
}
impl Drop for Here {
fn drop(&mut self) {
let mut open = self.presence.lock();
let Some(count) = open.get_mut(&self.visit) else { return };
*count -= 1;
if *count == 0 {
open.remove(&self.visit);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The break this catches: the first socket to close clearing the device, though the session
/// is still open in another tab or a second socket, or one device's socket covering another.
#[test]
fn a_device_is_here_while_any_of_its_sockets_is_open() {
let presence = Presence::default();
let first = presence.arrive("phone", "s1");
let second = presence.arrive("phone", "s1");
assert!(!presence.is_here("tablet", "s1"), "another device");
assert!(!presence.is_here("phone", "s2"), "another session");
drop(first);
assert!(presence.is_here("phone", "s1"), "one socket is still open");
drop(second);
assert!(!presence.is_here("phone", "s1"));
}
}

View File

@@ -0,0 +1,92 @@
//! Subscription — where a device asked to be sent notifications, and the keys to seal them with.
//!
//! The device names the address the bridge will post to, so the address is held to the push
//! services browsers use: HTTPS, on a known host. Anything else would let a paired device point
//! the bridge at a machine on your network.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use serde::{Deserialize, Serialize};
/// The push services a subscription may name, each with its subdomains: Apple's (Safari, every
/// browser on iOS), Google's (Chrome), Mozilla's (Firefox) and Microsoft's (Edge).
const PUSH_SERVICES: &[&str] =
&["push.apple.com", "fcm.googleapis.com", "push.services.mozilla.com", "notify.windows.com"];
/// A device's push subscription, as `PushSubscription.toJSON()` gives it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Subscription {
/// Where the push service takes this device's notifications
pub(crate) endpoint: String,
/// The keys the browser made for it
pub(crate) keys: SubscriptionKeys,
}
/// The browser's half of the encryption, base64url.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SubscriptionKeys {
/// Its P-256 public key
pub(crate) p256dh: String,
/// The secret shared with the bridge alone
pub(crate) auth: String,
}
/// Why a subscription was turned down.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub(crate) enum SubscriptionError {
/// The endpoint isn't an HTTPS URL on the default port
#[error("a push endpoint must be an https:// address")]
NotHttps,
/// The endpoint's host isn't a push service a browser uses
#[error("{0} isn't a push service this bridge sends to")]
UnknownService(String),
/// The keys aren't a P-256 point and a 16-byte secret
#[error("the subscription's keys aren't the ones Web Push uses")]
BadKeys,
}
impl Subscription {
/// This subscription, if it names a push service and carries usable keys.
pub(crate) fn checked(self) -> Result<Self, SubscriptionError> {
let host = push_host(&self.endpoint)?;
if !PUSH_SERVICES.iter().any(|service| is_within(&host, service)) {
return Err(SubscriptionError::UnknownService(host));
}
let (public, auth) = self.key_bytes().ok_or(SubscriptionError::BadKeys)?;
if public.len() != 65 || public[0] != 4 || auth.len() != 16 {
return Err(SubscriptionError::BadKeys);
}
Ok(self)
}
/// The browser's public key and the shared secret, decoded.
pub(crate) fn key_bytes(&self) -> Option<(Vec<u8>, Vec<u8>)> {
let public = URL_SAFE_NO_PAD.decode(&self.keys.p256dh).ok()?;
let auth = URL_SAFE_NO_PAD.decode(&self.keys.auth).ok()?;
Some((public, auth))
}
/// The push service's origin, which a VAPID token must name.
pub(crate) fn audience(&self) -> Option<String> {
let url = reqwest::Url::parse(&self.endpoint).ok()?;
Some(url.origin().ascii_serialization())
}
}
/// The host of `endpoint`, when it's HTTPS on the default port.
fn push_host(endpoint: &str) -> Result<String, SubscriptionError> {
let url = reqwest::Url::parse(endpoint).map_err(|_| SubscriptionError::NotHttps)?;
if url.scheme() != "https" || url.port().is_some() {
return Err(SubscriptionError::NotHttps);
}
let host = url.host_str().ok_or(SubscriptionError::NotHttps)?;
Ok(host.to_ascii_lowercase())
}
/// Whether `host` is `service` or one of its subdomains.
fn is_within(host: &str, service: &str) -> bool {
host == service || host.strip_suffix(service).is_some_and(|rest| rest.ends_with('.'))
}
#[cfg(test)]
pub(crate) mod tests;

View File

@@ -0,0 +1,70 @@
use super::*;
/// A subscription in the shape the Push API gives `PushSubscription.toJSON()`, with an endpoint
/// on Apple's push service and RFC 8291's example keys. Not captured from a device: swap in a real
/// one when there is one.
pub(crate) const FROM_SAFARI: &str = r#"{"endpoint":"https://web.push.apple.com/QGuQyavXutnMH8nrLlUjPZe_eVbc4ndHqoGAHGBrP2bIG7WY_DuCO7B0fhd7QAEXMaChjqCnDiuWvDEvkFvYg1vbqgxQp9zc5uj2BLsdLUn6R7Kp5YnWzMw6V_Ekd8CKk8Q3t6c2RU1yhp9eu5fcWkoUd3pUwP7sOTzmjVPCQCmY","keys":{"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4","auth":"BTBZMqHH6r4Tts7J_aSIgg"},"expirationTime":null}"#;
fn safari() -> Subscription {
serde_json::from_str(FROM_SAFARI).expect("Safari's shape reads")
}
fn at(endpoint: &str) -> Subscription {
Subscription { endpoint: endpoint.into(), ..safari() }
}
/// The break this catches: reading only some other browser's shape, so Safari's subscription
/// (the one an iPhone sends) is refused or loses its keys.
#[test]
fn a_subscription_from_safari_is_taken() {
let subscription = safari().checked().expect("it's Apple's push service");
assert_eq!(subscription.audience().as_deref(), Some("https://web.push.apple.com"));
}
/// The break this catches: a host check that's a plain suffix or substring match, so a name
/// that only ends like a push service's (or contains one) is posted to.
#[test]
fn only_a_push_services_own_hosts_are_taken() {
for endpoint in [
"https://fcm.googleapis.com/fcm/send/abc",
"https://updates.push.services.mozilla.com/wpush/v2/abc",
"https://wns2-par02p.notify.windows.com/w/?token=abc",
] {
assert!(at(endpoint).checked().is_ok(), "{endpoint}");
}
for endpoint in [
"https://evilpush.apple.com.example.net/x",
"https://notpush.apple.com/x",
"https://example.net/web.push.apple.com",
"https://192.168.1.1/push",
] {
let refused = at(endpoint).checked();
assert!(matches!(refused, Err(SubscriptionError::UnknownService(_))), "{endpoint}");
}
}
/// The break this catches: posting over plain HTTP, or to a push service's host on another port,
/// where something other than the push service may be listening.
#[test]
fn an_endpoint_must_be_https_on_its_usual_port() {
for endpoint in ["http://web.push.apple.com/x", "https://web.push.apple.com:8443/x", "nonsense"]
{
assert_eq!(at(endpoint).checked(), Err(SubscriptionError::NotHttps), "{endpoint}");
}
}
/// The break this catches: taking keys that can't seal a message, so every notification to the
/// device fails later, with nothing said when it subscribed.
#[test]
fn keys_that_cant_seal_a_message_are_refused() {
let bad = |p256dh: &str, auth: &str| {
let keys = SubscriptionKeys { p256dh: p256dh.into(), auth: auth.into() };
Subscription { keys, ..safari() }.checked()
};
let good = safari().keys;
assert_eq!(bad("not base64!", &good.auth), Err(SubscriptionError::BadKeys));
assert_eq!(bad(&good.p256dh[..60], &good.auth), Err(SubscriptionError::BadKeys));
assert_eq!(bad(&good.p256dh, "c2hvcnQ"), Err(SubscriptionError::BadKeys));
let compressed = URL_SAFE_NO_PAD.encode([[2u8].as_slice(), &[9; 64]].concat());
assert_eq!(bad(&compressed, &good.auth), Err(SubscriptionError::BadKeys));
}

View File

@@ -0,0 +1,121 @@
use super::*;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
/// Posts nowhere: keeps the endpoints it was handed and the titles it was asked to show, and
/// answers each with `reply`.
pub(crate) struct Recording {
sent: Mutex<Vec<String>>,
titles: Mutex<Vec<String>>,
reply: Delivery,
}
impl Recording {
fn answering(reply: Delivery) -> Self {
Self { sent: Mutex::default(), titles: Mutex::default(), reply }
}
/// The titles of the notices posted, in order.
pub(crate) fn titles(&self) -> Vec<String> {
self.titles.lock().unwrap().clone()
}
/// One whose every post goes through.
pub(crate) fn taking() -> Self {
Self::answering(Delivery::Taken)
}
/// The endpoints posted to, in order.
pub(crate) fn sent(&self) -> Vec<String> {
self.sent.lock().unwrap().clone()
}
}
impl Courier for Recording {
fn deliver<'a>(
&'a self,
subscription: &'a Subscription,
notice: &'a Notice,
) -> Pin<Box<dyn Future<Output = Result<Delivery, web_push::PushError>> + Send + 'a>> {
self.sent.lock().unwrap().push(subscription.endpoint.clone());
self.titles.lock().unwrap().push(notice.title.clone());
let reply = self.reply;
Box::pin(async move { Ok(reply) })
}
}
fn notice() -> Notice {
let (title, body, session) = ("luxe-dev".into(), "Approve bash".into(), "session-1".into());
Notice { title, body, session, urgent: true }
}
/// Pairs a device named `name`, subscribed at `endpoint` when there is one, and returns its id.
fn device(book: &DeviceBook, name: &str, endpoint: Option<&str>) -> String {
let token = book.invite().unwrap();
let (device, _) = book.pair(&token, name, "alex@github").unwrap();
let keys = SubscriptionKeys {
p256dh: "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"
.into(),
auth: "BTBZMqHH6r4Tts7J_aSIgg".into(),
};
let subscription = endpoint.map(|endpoint| Subscription { endpoint: endpoint.into(), keys });
book.subscribe(&device.id, subscription).unwrap();
device.id
}
fn book() -> (tempfile::TempDir, DeviceBook) {
let dir = tempfile::tempdir().unwrap();
let book = DeviceBook::at(dir.path().join("remote.json"));
(dir, book)
}
/// The break this catches: a notice sent to a device with that very session on screen, to one
/// that never opted in, or held back from a device that's only looking at another session.
#[tokio::test]
async fn a_notice_reaches_each_subscribed_device_not_looking_at_it() {
let (_dir, book) = book();
let presence = Presence::default();
let elsewhere = device(&book, "iPhone", Some("https://web.push.apple.com/phone"));
let looking = device(&book, "iPad", Some("https://web.push.apple.com/ipad"));
device(&book, "Laptop", None);
let _phone = presence.arrive(&elsewhere, "session-2");
let _ipad = presence.arrive(&looking, "session-1");
let courier = Recording::answering(Delivery::Taken);
dispatch(&book, &presence, &courier, &notice()).await;
assert_eq!(courier.sent(), ["https://web.push.apple.com/phone"]);
}
fn kept(book: &DeviceBook, id: &str) -> Option<String> {
let devices = book.devices();
let device = devices.iter().find(|device| device.id == id)?;
Some(device.subscription()?.endpoint.clone())
}
/// The break this catches: a subscription Apple has dropped posted to forever (each one a wasted
/// request, and a 410 in the log), or one forgotten after a post that went through.
#[tokio::test]
async fn a_subscription_is_forgotten_only_when_its_service_says_it_is_gone() {
let (_dir, book) = book();
let id = device(&book, "iPhone", Some("https://web.push.apple.com/phone"));
let presence = Presence::default();
dispatch(&book, &presence, &Recording::answering(Delivery::Taken), &notice()).await;
assert_eq!(kept(&book, &id).as_deref(), Some("https://web.push.apple.com/phone"));
dispatch(&book, &presence, &Recording::answering(Delivery::Gone), &notice()).await;
assert_eq!(kept(&book, &id), None);
}
/// A named bridge's notice says which computer it's from, after the project; an unnamed one is
/// left as the session wrote it.
///
/// The break this catches: a phone paired with two computers told "luxe-dev" wants it, with no
/// way to know which computer to open, or the body or session changed along with the title.
#[test]
fn a_notice_names_the_computer_it_came_from() {
let named = on_machine(notice(), Some("desk"));
assert_eq!(named.title, "luxe-dev \u{00b7} desk");
assert_eq!((named.body.as_str(), named.session.as_str()), ("Approve bash", "session-1"));
assert_eq!(on_machine(notice(), None).title, "luxe-dev");
}

View File

@@ -0,0 +1,74 @@
//! VAPID — how the bridge proves to a push service that it's the server a device subscribed to.
//!
//! A device subscribes with the bridge's public key, and each push carries a short token signed
//! with the private one (RFC 8292). The token names the push service it's for and when it
//! expires, and as its contact the project's homepage: nothing about this machine or its owner.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use ring::rand::SystemRandom;
use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_FIXED_SIGNING};
/// The contact a token names. A push service wants a URL or `mailto:` there.
const CONTACT: &str = env!("CARGO_PKG_HOMEPAGE");
/// Why the bridge's push key couldn't be made, read or used.
#[derive(Debug, thiserror::Error)]
pub(crate) enum VapidError {
/// The stored key isn't a P-256 key in PKCS#8
#[error("the stored push key isn't a P-256 private key")]
Unreadable,
/// The system's randomness failed
#[error("the system's random number source failed")]
Random,
}
/// The bridge's push signing key.
pub(crate) struct Vapid {
pair: EcdsaKeyPair,
random: SystemRandom,
}
impl Vapid {
/// A new key, and the PKCS#8 document to keep it in.
pub(crate) fn generate() -> Result<(Self, Vec<u8>), VapidError> {
let random = SystemRandom::new();
let document = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &random)
.map_err(|_| VapidError::Random)?;
let kept = document.as_ref().to_vec();
Ok((Self::from_pkcs8(&kept)?, kept))
}
/// The key kept in `document`.
pub(crate) fn from_pkcs8(document: &[u8]) -> Result<Self, VapidError> {
let random = SystemRandom::new();
let pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, document, &random)
.map_err(|_| VapidError::Unreadable)?;
Ok(Self { pair, random })
}
/// The public key, base64url, as a device passes it to `PushManager.subscribe`.
pub(crate) fn public_key(&self) -> String {
URL_SAFE_NO_PAD.encode(self.pair.public_key().as_ref())
}
/// The `Authorization` header for the push service at origin `audience`, good until
/// `expires_at` (seconds since the Unix epoch).
pub(crate) fn authorization(
&self,
audience: &str,
expires_at: u64,
) -> Result<String, VapidError> {
let header = URL_SAFE_NO_PAD.encode(br#"{"typ":"JWT","alg":"ES256"}"#);
let claims = serde_json::json!({ "aud": audience, "exp": expires_at, "sub": CONTACT });
let claims = URL_SAFE_NO_PAD.encode(claims.to_string());
let signed = format!("{header}.{claims}");
let signature =
self.pair.sign(&self.random, signed.as_bytes()).map_err(|_| VapidError::Random)?;
let signature = URL_SAFE_NO_PAD.encode(signature.as_ref());
Ok(format!("vapid t={signed}.{signature}, k={}", self.public_key()))
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,68 @@
use super::*;
use ring::signature::{UnparsedPublicKey, ECDSA_P256_SHA256_FIXED};
const APPLE: &str = "https://web.push.apple.com";
/// The token and key out of an `Authorization` header.
fn parts(header: &str) -> (String, Vec<u8>) {
let rest = header.strip_prefix("vapid t=").expect("a vapid header");
let (token, key) = rest.split_once(", k=").expect("a token and a key");
(token.to_string(), URL_SAFE_NO_PAD.decode(key).expect("the key is base64url"))
}
fn decoded(segment: &str) -> serde_json::Value {
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).unwrap()).unwrap()
}
/// The token says what Apple checks: ES256, the push service it's for, the expiry, and a URL to
/// reach the sender.
///
/// The break this catches: a claim renamed or dropped, or a contact that isn't a URL, which Apple
/// answers with 403 `BadJwtToken` for every push.
#[test]
fn the_token_carries_what_apple_checks() {
let (vapid, _) = Vapid::generate().unwrap();
let (token, _) = parts(&vapid.authorization(APPLE, 1_800_000_000).unwrap());
let segments: Vec<&str> = token.split('.').collect();
assert_eq!(segments.len(), 3, "{token}");
assert_eq!(decoded(segments[0]), serde_json::json!({ "typ": "JWT", "alg": "ES256" }));
let claims =
serde_json::json!({ "aud": APPLE, "exp": 1_800_000_000u64, "sub": "https://luxe.dev" });
assert_eq!(decoded(segments[1]), claims);
}
/// The signature checks out against the key the header gives, with ring's verifier rather than
/// anything of the bridge's.
///
/// The break this catches: signing other bytes than the token's first two parts, a DER signature
/// where JWS wants the fixed 64 bytes, or the header naming another key.
#[test]
fn the_token_is_signed_by_the_key_it_names() {
let (vapid, _) = Vapid::generate().unwrap();
let (token, key) = parts(&vapid.authorization(APPLE, 1_800_000_000).unwrap());
let (signed, signature) = token.rsplit_once('.').unwrap();
let signature = URL_SAFE_NO_PAD.decode(signature).unwrap();
let verifier = UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, &key);
assert!(verifier.verify(signed.as_bytes(), &signature).is_ok());
assert_eq!(URL_SAFE_NO_PAD.encode(&key), vapid.public_key());
}
/// The key a device subscribed with is the one the bridge signs with after a restart.
///
/// The break this catches: the kept document not being the key in use, so every subscription is
/// refused (`VapidPkHashMismatch`) once the bridge restarts.
#[test]
fn a_kept_key_is_the_same_key() {
let (vapid, document) = Vapid::generate().unwrap();
let kept = Vapid::from_pkcs8(&document).unwrap();
assert_eq!(kept.public_key(), vapid.public_key());
let key = URL_SAFE_NO_PAD.decode(kept.public_key()).unwrap();
assert_eq!((key.len(), key[0]), (65, 4), "an uncompressed P-256 point");
}
/// The break this catches: a damaged key file taken for a key, or a panic, rather than an error
/// the bridge can report.
#[test]
fn a_damaged_key_is_an_error() {
assert!(matches!(Vapid::from_pkcs8(b"not a key"), Err(VapidError::Unreadable)));
}

View File

@@ -0,0 +1,162 @@
//! Watch — the bridge's own reader on every running session, while any device wants notifications.
//!
//! A phone's socket lasts only while the app is on screen, so nothing would hear a prompt
//! arrive while it's in a pocket. Instead the bridge joins each running session itself, as a
//! watch-only client, which the terminal doesn't announce and which can't act. It reads the
//! stream and sends nothing back. With no device subscribed it joins nothing, and leaves what it
//! had joined.
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
use luxe_core::local_endpoint::{self, LiveSession};
use luxe_core::Event;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc;
use tokio::time::Instant;
use super::notice::{Heard, Notice, Reading, PROMPT_GRACE};
use crate::devices::DeviceBook;
/// How often the running sessions and the subscriptions are looked at again.
pub(crate) const WATCH_CHECK: Duration = Duration::from_secs(5);
/// Who the watcher joins as: unannounced, so its name shows only in the session's log.
pub(crate) const WATCHER: crate::relay::Introduction<'static> =
crate::relay::Introduction { name: "Notifications", watch_only: true, yours: false };
/// Keeps a reader on each running session while any device is subscribed, sending what they hear
/// to `notices`, until the task is dropped.
pub(crate) async fn watch_sessions(
runtime_dir: PathBuf,
devices: DeviceBook,
notices: mpsc::Sender<Notice>,
) {
let mut watching: HashMap<String, Watcher> = HashMap::new();
loop {
let running = if anyone_subscribed(&devices).await {
running(runtime_dir.clone()).await
} else {
Vec::new()
};
keep_watching(&mut watching, running, &notices);
tokio::time::sleep(WATCH_CHECK).await;
}
}
/// Stops the readers of sessions no longer running (and of any that quit), and starts one on each
/// session that has none, keyed by endpoint: a session's id changes when the terminal switches.
fn keep_watching(
watching: &mut HashMap<String, Watcher>,
running: Vec<LiveSession>,
notices: &mpsc::Sender<Notice>,
) {
let live = |address: &String| running.iter().any(|session| &session.address == address);
watching.retain(|address, watcher| live(address) && !watcher.0.is_finished());
for session in running {
let notices = notices.clone();
watching
.entry(session.address.clone())
.or_insert_with(|| Watcher(tokio::spawn(watch_session(session, notices))));
}
}
/// A task stopped when dropped: a session's reader, or the notifications as a whole.
pub(crate) struct Watcher(pub(super) tokio::task::JoinHandle<()>);
impl Drop for Watcher {
fn drop(&mut self) {
self.0.abort();
}
}
async fn anyone_subscribed(devices: &DeviceBook) -> bool {
let devices = devices.clone();
let paired = tokio::task::spawn_blocking(move || devices.devices()).await;
paired.is_ok_and(|paired| paired.iter().any(|device| device.subscription().is_some()))
}
async fn running(runtime_dir: PathBuf) -> Vec<LiveSession> {
// reads a folder and, on Windows, asks `tasklist` about each pid
let found = tokio::task::spawn_blocking(move || local_endpoint::running_sessions(&runtime_dir));
found.await.unwrap_or_default()
}
/// Reads `session` until it ends, sending its notices on, each prompt only once it's waited
/// [`PROMPT_GRACE`] unanswered.
pub(crate) async fn watch_session(session: LiveSession, notices: mpsc::Sender<Notice>) {
let Some(mut lines) = join(&session).await else { return };
let mut reading = Reading::new(&session.session_id, &session.cwd);
let mut held = Held::default();
loop {
// both are cancel-safe: a line stays buffered, and a held prompt is taken only once due
let heard = tokio::select! {
line = lines.next_line() => match line {
Ok(Some(line)) => {
decode(&line).and_then(|event| reading.read(&event, Instant::now()))
}
Ok(None) | Err(_) => return,
},
notice = held.due() => Some(Heard::Now(notice)),
};
if !held.take(heard, &notices).await {
return;
}
}
}
/// The session's stream, joined as the watcher.
async fn join(
session: &LiveSession,
) -> Option<tokio::io::Lines<BufReader<local_endpoint::LocalStream>>> {
match crate::routes::open(&session.address, &WATCHER).await {
Ok(stream) => Some(BufReader::new(stream).lines()),
Err(error) => {
tracing::warn!(%error, session = %session.session_id, "couldn't watch a session");
None
}
}
}
fn decode(line: &str) -> Option<Event> {
serde_json::from_str(line)
.inspect_err(|error| tracing::debug!(%error, "a session line that isn't an event"))
.ok()
}
/// Prompts waiting out their grace.
#[derive(Default)]
struct Held {
prompts: Vec<(Instant, String, Notice)>,
}
impl Held {
/// Acts on what was heard: sends it, holds it or lets one go. False once nobody's listening.
async fn take(&mut self, heard: Option<Heard>, notices: &mpsc::Sender<Notice>) -> bool {
match heard {
Some(Heard::Now(notice)) => return notices.send(notice).await.is_ok(),
Some(Heard::Prompt(id, notice)) => {
self.prompts.push((Instant::now() + PROMPT_GRACE, id, notice));
}
Some(Heard::Closed(id)) => self.prompts.retain(|(_, held, _)| *held != id),
None => {}
}
true
}
/// The next prompt to come due, once it has; never, with none held.
async fn due(&mut self) -> Notice {
let Some(next) = self.prompts.iter().map(|(due, ..)| *due).min() else {
return std::future::pending().await;
};
tokio::time::sleep_until(next).await;
let at = self.prompts.iter().position(|(due, ..)| *due == next);
// only `take` drops a prompt, and it can't run while this waits
let at = at.expect("a due prompt is still held");
self.prompts.remove(at).2
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,145 @@
use super::*;
use luxe_core::event::Action;
use luxe_core::local_endpoint::{EndpointListener, Joined, Publication};
use tokio::io::AsyncWriteExt;
const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#;
const QUESTION: &str = r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"session-1","prompt":"Which database?","options":[],"multi":false}}"#;
const CLOSED: &str = r#"{"kind":"prompt_closed","content":{"id":"perm:1"}}"#;
/// A session's endpoint, and the folder it's published in.
struct Session {
listener: EndpointListener,
live: LiveSession,
runtime: tempfile::TempDir,
}
fn session() -> Session {
let runtime = tempfile::tempdir().unwrap();
let listener = EndpointListener::bind(runtime.path()).unwrap();
let live = LiveSession {
pid: std::process::id(),
session_id: "session-1".into(),
cwd: "/work/luxe-dev".into(),
address: listener.address().to_string(),
luxe_version: "0.1.3".into(),
};
Session { listener, live, runtime }
}
/// Starts a watcher on `session`, and takes its notices and the session's end of the stream.
async fn watched(session: &mut Session) -> (mpsc::Receiver<Notice>, Joined, Watcher) {
let (notices, heard) = mpsc::channel(8);
let watcher = Watcher(tokio::spawn(watch_session(session.live.clone(), notices)));
let joined = session.listener.accept().await.unwrap();
(heard, joined, watcher)
}
async fn say(joined: &mut Joined, lines: &[&str]) {
let text: String = lines.iter().map(|line| format!("{line}\n")).collect();
joined.stream.write_all(text.as_bytes()).await.unwrap();
}
/// The watcher opens as watch-only, so the terminal doesn't announce it, and then says nothing.
///
/// The break this catches: a watcher that joins as an ordinary client (the terminal says
/// "Notifications joined this session" in every session) or that sends the session anything else,
/// an answer included.
#[tokio::test(start_paused = true)]
async fn the_watcher_introduces_itself_and_says_nothing_else() {
let mut session = session();
let (_heard, joined, _watcher) = watched(&mut session).await;
let mut lines = BufReader::new(joined.stream).lines();
let first = lines.next_line().await.unwrap().unwrap();
let introduced: Action = serde_json::from_str(&first).unwrap();
let watcher =
Action::Introduce { name: "Notifications".into(), watch_only: true, yours: false };
assert_eq!(introduced, watcher);
let more = tokio::time::timeout(Duration::from_secs(60), lines.next_line()).await;
assert!(more.is_err(), "the watcher sent {more:?}");
}
/// The break this catches: a prompt sent the moment it's asked, buzzing a phone while you answer
/// at the desk, or never sent at all.
#[tokio::test(start_paused = true)]
async fn a_prompt_is_sent_once_it_has_waited() {
let mut session = session();
let (mut heard, mut joined, _watcher) = watched(&mut session).await;
let asked = Instant::now();
say(&mut joined, &[PERMISSION]).await;
let notice = heard.recv().await.expect("a notice");
assert_eq!((notice.title.as_str(), notice.body.as_str()), ("luxe-dev", "Approve bash"));
assert!(asked.elapsed() >= PROMPT_GRACE, "sent after {:?}", asked.elapsed());
}
/// The break this catches: a prompt answered at the desk still reaching the phone, or one answer
/// letting every held prompt go.
#[tokio::test(start_paused = true)]
async fn a_prompt_answered_in_time_is_never_sent() {
let mut session = session();
let (mut heard, mut joined, _watcher) = watched(&mut session).await;
say(&mut joined, &[PERMISSION, QUESTION, CLOSED]).await;
let notice = heard.recv().await.expect("a notice");
assert_eq!(notice.body, "Luxe has a question");
tokio::time::sleep(PROMPT_GRACE * 2).await;
assert!(heard.try_recv().is_err(), "the answered prompt was sent");
}
/// The break this catches: a watcher that outlives its session, holding a task (and in time a
/// file handle) for every session that ever ran.
#[tokio::test(start_paused = true)]
async fn the_watcher_ends_with_its_session() {
let mut session = session();
let (_heard, joined, watcher) = watched(&mut session).await;
// once it has introduced itself it's reading, rather than failing to join
let mut lines = BufReader::new(joined.stream).lines();
lines.next_line().await.unwrap().expect("an introduction");
drop(lines);
tokio::time::timeout(Duration::from_secs(5), async {
while !watcher.0.is_finished() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the watcher stopped");
}
/// A book with one paired device, and that device's id.
fn paired() -> (tempfile::TempDir, DeviceBook, String) {
let dir = tempfile::tempdir().unwrap();
let book = DeviceBook::at(dir.path().join("remote.json"));
let token = book.invite().unwrap();
let (device, _) = book.pair(&token, "iPhone", "alex@github").unwrap();
(dir, book, device.id)
}
fn subscribe(book: &DeviceBook, id: &str, on: bool) {
let subscription = on.then(|| serde_json::from_str(crate::push::FROM_SAFARI).unwrap());
book.subscribe(id, subscription).unwrap();
}
/// Whether the watcher joins `session` within a few checks.
async fn joins(session: &mut Session) -> Option<Joined> {
tokio::time::timeout(WATCH_CHECK * 3, session.listener.accept()).await.ok()?.ok()
}
/// The break this catches: a bridge that sits in every session whether or not anyone wants
/// notifications (a "Notifications joined" line in every terminal), or that never joins.
#[tokio::test(start_paused = true)]
async fn sessions_are_watched_only_while_a_device_is_subscribed() {
let mut session = session();
let _record: Publication = session.live.publish(session.runtime.path()).unwrap();
let (_dir, book, id) = paired();
let (notices, _heard) = mpsc::channel(8);
let runtime = session.runtime.path().to_path_buf();
let _watching = Watcher(tokio::spawn(watch_sessions(runtime, book.clone(), notices)));
assert!(joins(&mut session).await.is_none(), "joined with nobody subscribed");
subscribe(&book, &id, true);
let joined = joins(&mut session).await.expect("joined once a device subscribed");
subscribe(&book, &id, false);
let mut lines = BufReader::new(joined.stream).lines();
let _introduction = lines.next_line().await.unwrap();
let ended = tokio::time::timeout(WATCH_CHECK * 3, lines.next_line()).await;
assert!(matches!(ended, Ok(Ok(None))), "still watching after the last device left: {ended:?}");
}

View File

@@ -0,0 +1,177 @@
//! Web push — one notification posted to the push service a device subscribed through (RFC 8030).
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use super::encryption::{encrypt, EncryptionError};
use super::notice::Notice;
use super::{Subscription, Vapid, VapidError};
/// How long a push service keeps a notification for a device that's offline, in seconds. Past an
/// hour, what it says has likely changed.
const TIME_TO_LIVE: u32 = 3600;
/// How long a signed token is good for. Apple takes up to a day.
const TOKEN_LIFETIME_SECS: u64 = 12 * 3600;
/// A token is signed again once it has less than this left. Apple asks for no new token more
/// often than hourly, which this keeps to.
const TOKEN_RENEWAL_SECS: u64 = 3600;
/// The longest a post to a push service may take, so a stalled one can't hold the rest back.
const POST_TIMEOUT: Duration = Duration::from_secs(15);
/// What a push service did with a notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Delivery {
/// Taken for delivery
Taken,
/// The subscription has expired or been withdrawn, and won't take any more
Gone,
}
/// Why a notification wasn't posted.
#[derive(Debug, thiserror::Error)]
pub(crate) enum PushError {
/// It couldn't be sealed for the device
#[error(transparent)]
Encryption(#[from] EncryptionError),
/// The token couldn't be signed
#[error(transparent)]
Key(#[from] VapidError),
/// The push service couldn't be reached
#[error("couldn't reach the push service: {0}")]
Network(#[from] reqwest::Error),
/// The push service turned it down
#[error("the push service refused it with {status}: {reason}")]
Refused {
/// Its status code
status: u16,
/// What it said, cut short
reason: String,
},
/// The subscription's endpoint or keys don't read
#[error("the subscription doesn't read")]
BadSubscription,
}
/// What posts a notification. The bridge's is [`WebPush`]; tests post nowhere.
pub(crate) trait Courier: Send + Sync {
/// Posts `notice` to `subscription`.
fn deliver<'a>(
&'a self,
subscription: &'a Subscription,
notice: &'a Notice,
) -> Pin<Box<dyn Future<Output = Result<Delivery, PushError>> + Send + 'a>>;
}
/// A signed token, and when it expires.
struct Token {
header: String,
expires_at: u64,
}
/// The bridge's courier: Web Push over HTTPS, signed with the bridge's key.
pub(crate) struct WebPush {
client: reqwest::Client,
vapid: Vapid,
tokens: Mutex<HashMap<String, Token>>,
}
impl WebPush {
/// A courier signing with `vapid`.
pub(crate) fn new(vapid: Vapid) -> Result<Self, PushError> {
let client = reqwest::Client::builder().timeout(POST_TIMEOUT).build()?;
Ok(Self { client, vapid, tokens: Mutex::new(HashMap::new()) })
}
/// The post for `notice` to `subscription`, as of `now` (seconds since the Unix epoch).
pub(crate) fn request(
&self,
subscription: &Subscription,
notice: &Notice,
now: u64,
) -> Result<reqwest::Request, PushError> {
let audience = subscription.audience().ok_or(PushError::BadSubscription)?;
let body = sealed(subscription, notice)?;
let urgency = if notice.urgent { "high" } else { "normal" };
let mut post = self.client.post(&subscription.endpoint).body(body);
post = post.header("TTL", TIME_TO_LIVE).header("Urgency", urgency);
post = post.header("Content-Encoding", "aes128gcm");
post = post.header("Content-Type", "application/octet-stream");
post = post.header("Authorization", self.authorization(&audience, now)?);
post = post.header("Topic", topic(&notice.session));
Ok(post.build()?)
}
/// The `Authorization` header for `audience`, reusing a token that has an hour left.
fn authorization(&self, audience: &str, now: u64) -> Result<String, PushError> {
let mut tokens = self.tokens.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(token) = tokens.get(audience) {
if token.expires_at > now + TOKEN_RENEWAL_SECS {
return Ok(token.header.clone());
}
}
let expires_at = now + TOKEN_LIFETIME_SECS;
let header = self.vapid.authorization(audience, expires_at)?;
tokens.insert(audience.to_string(), Token { header: header.clone(), expires_at });
Ok(header)
}
async fn post(
&self,
subscription: &Subscription,
notice: &Notice,
) -> Result<Delivery, PushError> {
let request = self.request(subscription, notice, unix_now())?;
let response = self.client.execute(request).await?;
let status = response.status();
if status.is_success() {
return Ok(Delivery::Taken);
}
if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::GONE {
return Ok(Delivery::Gone);
}
let reason = response.text().await.unwrap_or_default().chars().take(200).collect();
Err(PushError::Refused { status: status.as_u16(), reason })
}
}
impl Courier for WebPush {
fn deliver<'a>(
&'a self,
subscription: &'a Subscription,
notice: &'a Notice,
) -> Pin<Box<dyn Future<Output = Result<Delivery, PushError>> + Send + 'a>> {
Box::pin(self.post(subscription, notice))
}
}
/// `notice` as the service worker reads it, sealed for the subscription's device.
fn sealed(subscription: &Subscription, notice: &Notice) -> Result<Vec<u8>, PushError> {
let (device_key, auth) = subscription.key_bytes().ok_or(PushError::BadSubscription)?;
let message = serde_json::to_vec(notice).expect("a notice is plain strings");
Ok(encrypt(&message, &device_key, &auth)?)
}
/// The `Topic` for a session's notifications, so a push service holding several for an offline
/// device passes on only the newest. Apple takes at most 32 base64url characters and reads them as
/// base64, refusing some lengths, so it's always 32: a hash of the id, which also keeps the id
/// itself from the push service.
fn topic(session: &str) -> String {
use base64::Engine as _;
use sha2::Digest as _;
let digest = sha2::Sha256::digest(session.as_bytes());
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..24])
}
fn unix_now() -> u64 {
let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
since.map(|elapsed| elapsed.as_secs()).unwrap_or(0)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,126 @@
use super::*;
use crate::push::encryption::tests::open;
use crate::push::SubscriptionKeys;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use ring::agreement::{EphemeralPrivateKey, ECDH_P256};
const NOW: u64 = 1_800_000_000;
const SESSION: &str = "5898d57b-0000-4000-8000-000000000001";
/// A device's private key and the subscription its browser would make with it.
fn device() -> (EphemeralPrivateKey, Subscription) {
let private = EphemeralPrivateKey::generate(&ECDH_P256, &ring::rand::SystemRandom::new());
let private = private.unwrap();
let public = private.compute_public_key().unwrap();
let keys = SubscriptionKeys {
p256dh: URL_SAFE_NO_PAD.encode(public.as_ref()),
auth: URL_SAFE_NO_PAD.encode([7u8; 16]),
};
(private, Subscription { endpoint: "https://web.push.apple.com/abc".into(), keys })
}
fn courier() -> WebPush {
WebPush::new(Vapid::generate().unwrap().0).unwrap()
}
fn notice(urgent: bool) -> Notice {
let (title, body) = ("luxe-dev".into(), "Approve bash".into());
Notice { title, body, session: SESSION.into(), urgent }
}
fn header<'a>(request: &'a reqwest::Request, name: &str) -> &'a str {
request.headers()[name].to_str().unwrap()
}
/// The post goes to the subscription with the headers a push service requires, and the device
/// opens the body to the notice the service worker shows.
///
/// The break this catches: a missing `TTL` (Apple's `BadTtl`) or encoding, the wrong urgency, or a
/// body sealed for someone else or carrying fields the worker doesn't read.
#[test]
fn a_post_carries_what_the_push_service_and_the_device_need() {
let (private, subscription) = device();
let request = courier().request(&subscription, &notice(true), NOW).unwrap();
assert_eq!(request.url().as_str(), subscription.endpoint);
assert_eq!(header(&request, "TTL"), "3600");
assert_eq!(header(&request, "Urgency"), "high");
assert_eq!(header(&request, "Content-Encoding"), "aes128gcm");
assert_eq!(header(&request, "Topic"), "DJZtLYoay56CTZC7EDzavnWaSjSnBF8s");
assert!(header(&request, "Authorization").starts_with("vapid t="));
let body = request.body().and_then(reqwest::Body::as_bytes).unwrap();
let (device_key, auth) = subscription.key_bytes().unwrap();
let opened = open(private, &device_key, &auth, body);
let shown: serde_json::Value = serde_json::from_slice(&opened[..opened.len() - 1]).unwrap();
let expected =
serde_json::json!({ "title": "luxe-dev", "body": "Approve bash", "session": SESSION });
assert_eq!(shown, expected);
let later = courier().request(&subscription, &notice(false), NOW).unwrap();
assert_eq!(header(&later, "Urgency"), "normal");
}
/// The claims inside a request's token.
fn claims(request: &reqwest::Request) -> serde_json::Value {
let token = header(request, "Authorization").strip_prefix("vapid t=").unwrap();
let claims = token.split('.').nth(1).unwrap();
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims).unwrap()).unwrap()
}
/// The break this catches: a token signed for every post, which Apple asks servers not to do more
/// than hourly, or one kept past its expiry, which it refuses; or a token for the wrong service.
#[test]
fn a_token_is_reused_until_it_has_an_hour_left() {
let (_, subscription) = device();
let courier = courier();
let first = courier.request(&subscription, &notice(true), NOW).unwrap();
let token = |request: &reqwest::Request| header(request, "Authorization").to_string();
let expected = serde_json::json!({ "aud": "https://web.push.apple.com", "exp": NOW + TOKEN_LIFETIME_SECS, "sub": "https://luxe.dev" });
assert_eq!(claims(&first), expected);
let renew_at = NOW + TOKEN_LIFETIME_SECS - TOKEN_RENEWAL_SECS;
let reused = courier.request(&subscription, &notice(true), renew_at - 1).unwrap();
assert_eq!(token(&reused), token(&first));
let renewed = courier.request(&subscription, &notice(true), renew_at).unwrap();
assert_eq!(claims(&renewed)["exp"], renew_at + TOKEN_LIFETIME_SECS);
}
/// The topic is 32 base64url characters whatever the id, and differs between sessions.
///
/// The break this catches: a session id passed through whole, whose 36 characters Apple refuses
/// (`BadWebPushTopic`), a shorter one at a length Apple can't read as base64, or one topic for
/// every session, so a newer notice from one session replaces another's.
#[test]
fn a_topic_is_always_32_url_safe_characters() {
assert_eq!(topic(SESSION), "DJZtLYoay56CTZC7EDzavnWaSjSnBF8s");
assert_eq!(topic("short-1"), "GA5_ZXQcTDu9kMi-CVbgVxwQ_TCZQ-fp");
assert_eq!(topic("").len(), 32);
}
/// A push service on this machine that answers every post with the status in its path.
async fn push_service() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let answer = |axum::extract::Path(status): axum::extract::Path<u16>| async move {
(axum::http::StatusCode::from_u16(status).unwrap(), "BadDeviceToken")
};
let app = axum::Router::new().route("/{status}", axum::routing::post(answer));
tokio::spawn(async move { axum::serve(listener, app).await });
format!("http://{address}")
}
async fn delivered(courier: &WebPush, service: &str, status: u16) -> String {
let (_, mut subscription) = device();
subscription.endpoint = format!("{service}/{status}");
format!("{:?}", courier.deliver(&subscription, &notice(false)).await)
}
/// The break this catches: a dropped subscription (404 or 410) taken as a failure, so it's posted
/// to forever, or any other refusal taken as gone, so one bad request forgets a working device.
#[tokio::test]
async fn what_the_push_service_answers_is_told_apart() {
let (courier, service) = (courier(), push_service().await);
assert_eq!(delivered(&courier, &service, 201).await, "Ok(Taken)");
assert_eq!(delivered(&courier, &service, 404).await, "Ok(Gone)");
assert_eq!(delivered(&courier, &service, 410).await, "Ok(Gone)");
let refused = delivered(&courier, &service, 400).await;
assert!(refused.contains("status: 400") && refused.contains("BadDeviceToken"), "{refused}");
}

View File

@@ -0,0 +1,203 @@
//! Relay — one device's WebSocket piped to one session's local endpoint.
//!
//! The protocol is a JSON object per line, and a WebSocket already frames messages, so a line
//! becomes a text frame and a text frame becomes a line. Nothing the device sends is parsed: the
//! session answers a bad frame itself, with `action_rejected`, as it would for any client. The one
//! line held back is a session refusing the bridge's own `introduce`, which the device never sent.
use axum::extract::ws::{close_code, CloseFrame, Message, WebSocket};
use luxe_core::local_endpoint::LocalStream;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, WriteHalf};
/// The close code a device gets when it is unpaired while connected, from the range RFC 6455 leaves
/// to applications, so the app can say so instead of trying again.
pub(crate) const UNPAIRED: u16 = 4001;
/// How long to wait for the device to answer the bridge's close before dropping the connection.
const CLOSE_WAIT: Duration = Duration::from_secs(2);
/// Why a relay stopped, which decides how the device's socket is closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ending {
/// The device closed its socket, or lost it
DeviceLeft,
/// The session's endpoint closed
SessionEnded,
/// The device was unpaired while connected
Unpaired,
}
/// Tells the session who is joining, so it can say "Approved from iPhone" rather than naming the
/// bridge's process.
pub(crate) async fn introduce(
session: &mut LocalStream,
introduction: &Introduction<'_>,
) -> std::io::Result<()> {
let frame = luxe_core::event::Action::Introduce {
name: introduction.name.to_string(),
watch_only: introduction.watch_only,
yours: introduction.yours,
};
let frame = serde_json::to_string(&frame).map_err(std::io::Error::other)?;
session.write_all(one_line(&frame).as_bytes()).await
}
/// Who the bridge joins a session as.
pub(crate) struct Introduction<'a> {
/// The device it relays for, or the watcher's name
pub(crate) name: &'a str,
/// Joins unannounced and can't act, as the notification watcher does
pub(crate) watch_only: bool,
/// The device was paired by the computer's owner, the person at its terminal
pub(crate) yours: bool,
}
/// Pipes `socket` and `session` both ways until either side ends, or `until` resolves (the device
/// was revoked), then ends both.
pub(crate) async fn relay(
mut socket: WebSocket,
session: LocalStream,
until: impl std::future::Future<Output = ()>,
) {
let (from_session, mut to_session) = tokio::io::split(session);
let ending = pump(&mut socket, from_session, &mut to_session, until).await;
let _ = to_session.shutdown().await;
close(socket, ending).await;
}
/// Carries lines and frames across until one side stops, and says which.
async fn pump(
socket: &mut WebSocket,
from_session: tokio::io::ReadHalf<LocalStream>,
to_session: &mut WriteHalf<LocalStream>,
until: impl std::future::Future<Output = ()>,
) -> Ending {
let mut lines = BufReader::new(from_session).lines();
tokio::pin!(until);
// Both reads are cancel-safe, so a line or frame the other branch beat is never lost
loop {
let stopped = tokio::select! {
line = lines.next_line() => line_to_device(socket, line).await,
message = socket.recv() => frame_to_session(to_session, message).await,
() = &mut until => Some(Ending::Unpaired),
};
if let Some(ending) = stopped {
return ending;
}
}
}
async fn line_to_device(
socket: &mut WebSocket,
line: std::io::Result<Option<String>>,
) -> Option<Ending> {
match line {
Ok(Some(line)) if refuses_introduction(&line) => None,
Ok(Some(line)) => {
socket.send(Message::Text(line.into())).await.err().map(|_| Ending::DeviceLeft)
}
Ok(None) => Some(Ending::SessionEnded),
Err(error) => {
tracing::warn!(%error, "stopped reading the session");
Some(Ending::SessionEnded)
}
}
}
/// Whether `line` is the session refusing the bridge's `introduce`. Only a session started before
/// its Luxe knew the action does, and it carries on without the device's name; the refusal is of a
/// frame the device never sent, so showing it there reads as a fault. Decoded only when it could
/// be one, so every other line still passes untouched.
fn refuses_introduction(line: &str) -> bool {
if !line.contains("action_rejected") {
return false;
}
matches!(
serde_json::from_str::<luxe_core::event::Event>(line),
Ok(luxe_core::event::Event::ActionRejected { kind: Some(kind), .. }) if kind == "introduce"
)
}
async fn frame_to_session(
to_session: &mut WriteHalf<LocalStream>,
message: Option<Result<Message, axum::Error>>,
) -> Option<Ending> {
let text = match message {
Some(Ok(Message::Text(text))) => text,
// Pings are answered by axum; binary has no meaning in a line protocol
Some(Ok(Message::Binary(_) | Message::Ping(_) | Message::Pong(_))) => return None,
Some(Ok(Message::Close(_)) | Err(_)) | None => return Some(Ending::DeviceLeft),
};
let written = to_session.write_all(one_line(&text).as_bytes()).await;
written.err().map(|_| Ending::SessionEnded)
}
/// Closes the device's socket the way `ending` calls for, so the app can tell leaving, a session
/// that ended and being unpaired apart from a dropped connection, which is the one worth retrying.
async fn close(mut socket: WebSocket, ending: Ending) {
let frame = |code, reason: &str| Some(CloseFrame { code, reason: reason.into() });
let frame = match ending {
// tungstenite refuses to send once the device has closed; it queued its own answer, and
// the read below sends it
Ending::DeviceLeft => None,
Ending::SessionEnded => frame(close_code::NORMAL, "the session ended"),
Ending::Unpaired => frame(UNPAIRED, "this device was unpaired"),
};
if frame.is_some() && socket.send(Message::Close(frame)).await.is_err() {
return;
}
let answered = async { while let Some(Ok(_)) = socket.recv().await {} };
let _ = tokio::time::timeout(CLOSE_WAIT, answered).await;
}
/// `frame` as exactly one protocol line.
///
/// JSON can hold a raw line break only as whitespace between tokens (inside a string it is
/// escaped), so turning breaks into spaces keeps a pretty-printed frame one action instead of
/// several broken ones.
fn one_line(frame: &str) -> String {
let mut line: String =
frame.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect();
line.push('\n');
line
}
#[cfg(test)]
mod tests {
use super::*;
/// A pretty-printed frame reaches the session as the one line it is.
///
/// The break this catches: writing the frame as it came, so a client that sends indented JSON
/// gets several `action_rejected` answers and nothing done.
/// An older session's refusal of the bridge's `introduce` is held back, and every other
/// refusal goes through.
///
/// The break this catches: a device joining a session that predates `introduce` shown
/// "Refused: no such action `introduce`" for a frame it never sent, or the device's own
/// refused frames (and the message words alone) swallowed too.
#[test]
fn only_the_refusal_of_the_introduction_is_held_back() {
let refused = |kind: &str| {
format!("{{\"kind\":\"action_rejected\",\"content\":{{\"kind\":\"{kind}\",\"reason\":\"no such action `{kind}`\"}}}}")
};
assert!(refuses_introduction(&refused("introduce")));
assert!(!refuses_introduction(&refused("submit_user_message")));
let unparsed =
r#"{"kind":"action_rejected","content":{"reason":"no such action `introduce`"}}"#;
assert!(
!refuses_introduction(unparsed),
"the words alone don't make it the introduction's"
);
assert!(!refuses_introduction(r#"{"kind":"turn_started"}"#));
}
#[test]
fn a_frame_is_one_line_however_it_was_printed() {
let pretty = "{\n \"kind\": \"cancel\"\r\n}";
assert_eq!(one_line(pretty), "{ \"kind\": \"cancel\" }\n");
let text = r#"{"kind":"submit_user_message","content":{"text":"a\nb"}}"#;
assert_eq!(one_line(text), format!("{text}\n"), "an escaped break is not a break");
}
}

View File

@@ -0,0 +1,420 @@
//! Render — a message as the app shows it, made on the host so the app parses nothing.
//!
//! Markdown, highlighted code, tool glyphs and the status line's wording are the TUI's, and the
//! bridge doesn't depend on the TUI, so `luxe-cli` hands one in as a [`Renderer`]. What a user
//! message shows (the reader's own words, and a brief Luxe wrote to the agent as one line saying
//! so) is core's call (`luxe_core::briefs`), so that is made here. The bridge keeps no session
//! state, so the app asks: once for a finished message, and a few times a second for one still
//! growing or a status that changed.
mod diff;
mod file;
mod github;
mod review;
mod tree;
mod workspace;
pub use github::GithubMarks;
pub use tree::{FileMark, MarkHue};
use luxe_core::briefs;
use luxe_core::file_diff::{FileDiff, FileDiffFailure};
use luxe_core::github::overview::{ConversationEntry, Overview};
use luxe_core::github::ListedSection;
use luxe_core::guided_review::{
ChapterId, ChapterReading, GuidedReview, ReviewChapter, ReviewFile, ReviewFinding,
};
use luxe_core::project_files::{ProjectFile, ProjectFileFailure};
use luxe_core::provider::{PlanUsage, ThinkingLevel};
use luxe_core::usage::SessionUsage;
use luxe_core::workspace::{FileChangeStatus, TodoSummary, WorkspaceChangesSummary};
use luxe_core::ModelRef;
use luxe_core::TodoSummaryStatus;
/// Turns model text into the app's HTML, and draws the app's icon from the same art the TUI's
/// wordmark is.
pub trait Renderer: Send + Sync {
/// `text` as HTML, for `voice`. Everything in `text` is data: it must come back escaped.
fn markdown(&self, text: &str, voice: Voice) -> String;
/// The glyph a tool's card wears, as plain text.
fn tool_glyph(&self, tool: &str) -> String;
/// The status line's facts, worded as the TUI's bar words them.
fn status(&self, facts: &StatusFacts) -> Vec<StatusSegment>;
/// The glyph beside a user message's "image(s) attached" line, as plain text.
fn image_glyph(&self) -> String {
String::new()
}
/// One line of source as HTML, highlighted for `language`. It must come back escaped.
fn code_line(&self, text: &str, _language: Option<&str>) -> String {
escape(text)
}
/// The mark the dock puts beside a todo, as plain text.
fn todo_mark(&self, _status: TodoSummaryStatus) -> String {
String::new()
}
/// The mark the dock puts beside a changed file, as plain text.
fn change_mark(&self, _status: FileChangeStatus) -> String {
String::new()
}
/// The mark the file tree puts before a file named `name`, by its language.
fn file_mark(&self, _name: &str) -> FileMark {
FileMark::default()
}
/// The mark the file tree puts before a folder, as plain text.
fn folder_mark(&self) -> String {
String::new()
}
/// The mark before the checked-out branch, as the TUI's project section has it.
fn branch_mark(&self) -> String {
String::new()
}
/// The mark beside `mode`'s name, as the TUI's composer title has it, as plain text.
fn mode_mark(&self, _mode: &str) -> String {
String::new()
}
/// The marks `/github` draws, as plain text.
fn github_marks(&self) -> GithubMarks {
GithubMarks::default()
}
/// How long before `now` `at` was, both in seconds since the Unix epoch, as plain text: `3h
/// ago`. Empty from a renderer without the TUI's words for it.
fn ago(&self, _at: u64, _now: u64) -> String {
String::new()
}
/// A GitHub body with the HTML people and bots put in it reduced to the markdown it amounts
/// to, as GitHub shows it. The result goes through [`Renderer::markdown`].
fn github_readable(&self, body: &str) -> String {
body.to_owned()
}
/// The home-screen icon, `side` pixels square, in `colors`, as PNG bytes; none from a
/// renderer with no art to draw it from.
fn home_icon(&self, _side: u32, _colors: TileColors) -> Option<Vec<u8>> {
None
}
}
/// The icon's two colors: the theme's background for the plate, its accent for the letter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TileColors {
/// The square behind the letter
pub plate: [u8; 3],
/// The letter
pub ink: [u8; 3],
}
/// What a session last reported about itself, as the app forwards it from the frames.
#[derive(Debug, Default, serde::Deserialize)]
pub struct StatusFacts {
/// From `state_changed`
pub model: Option<ModelRef>,
/// From `state_changed`
pub thinking: Option<ThinkingLevel>,
/// From `context_usage`
pub context: Option<ContextUsage>,
/// From `plan_usage`
pub plan: Option<PlanUsage>,
/// From `session_usage`
pub session: Option<SessionUsage>,
}
/// A `context_usage` frame's content.
#[derive(Debug, Clone, Copy, serde::Deserialize)]
pub struct ContextUsage {
/// Tokens in the window
pub used_tokens: u32,
/// The window's size
pub context_window: u32,
}
/// One fact on the status line, as words; the bridge escapes them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusSegment {
/// Which fact, as the class the app styles it by: `context`, `cost`, `thinking` or `model`
pub kind: &'static str,
/// The mark in front of it, if any
pub glyph: Option<String>,
/// The words
pub label: String,
/// How loudly to color it
pub tone: StatusTone,
}
/// How loudly a status segment is colored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusTone {
/// Body text
Plain,
/// The theme's warning color
Warning,
/// The theme's error color
Error,
}
/// Which reader model text is rendered for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Voice {
/// An answer
Answer,
/// Model reasoning, which keeps its line breaks and leaves its code plain
Reasoning,
}
/// The renderer a bridge has until it is handed the TUI's: every word shown, escaped, with no
/// formatting and no glyphs.
pub(crate) struct PlainText;
impl Renderer for PlainText {
fn markdown(&self, text: &str, _voice: Voice) -> String {
format!("<p class=\"plain\">{}</p>", escape(text))
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, facts: &StatusFacts) -> Vec<StatusSegment> {
let model = facts.model.as_ref().map(|model| model.display().to_string());
let segment =
|label| StatusSegment { kind: "model", glyph: None, label, tone: StatusTone::Plain };
model.into_iter().map(segment).collect()
}
}
/// What the app asks to have rendered, in one round trip.
#[derive(Debug, serde::Deserialize)]
pub(crate) struct RenderRequest {
pub(crate) pieces: Vec<Piece>,
}
/// One thing to render.
#[derive(Debug, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum Piece {
/// An answer's text
Answer { text: String },
/// Reasoning's text
Reasoning { text: String },
/// A user message's content blocks, as the wire carries them
User { content: Vec<WireBlock> },
/// A tool, by name
Tool { name: String },
/// The status line
Status(Box<StatusFacts>),
/// The todos from `workspace_updated`, as the dock's PLAN shows them
Plan { todos: Box<TodoSummary> },
/// The changed files from `workspace_updated`, each a way into its diff
Changes { changes: Box<WorkspaceChangesSummary> },
/// A `file_diff_loaded` frame's diff
Diff { diff: Box<FileDiff> },
/// A `file_diff_failed` frame's reason
DiffFailed { error: FileDiffFailure },
/// A `project_file_read` frame's file
File { file: Box<ProjectFile> },
/// A `project_file_read_failed` frame's reason
FileFailed { error: ProjectFileFailure },
/// The Files tab's rows, marked from the changes the dock has
Tree { rows: Vec<tree::TreeRow>, changes: Option<Box<WorkspaceChangesSummary>> },
/// The project panel's bar: the session's folder name behind the tree's folder mark, then the
/// branch from a `workspace_updated` frame, marked when the tree is dirty
ProjectName {
name: String,
#[serde(default)]
branch: Option<String>,
#[serde(default)]
dirty: bool,
},
/// The status line's mode button: the mode's name behind its mark
ModeName { mode: String },
/// A `github_listed` section, as `/github`'s list draws it. Args: `now`, the app's clock in
/// seconds since the Unix epoch, as in the pieces below
GithubList { repository: Option<String>, section: Box<ListedSection>, now: u64 },
/// A `github_overview_read` overview's header, above the detail's tabs
GithubHeader { overview: Box<Overview>, now: u64 },
/// Its Overview tab
GithubOverview { overview: Box<Overview>, now: u64 },
/// A `github_conversation_read` frame's entries, `opened_by_you` from the overview
GithubConversation {
entries: Vec<ConversationEntry>,
now: u64,
#[serde(default)]
opened_by_you: bool,
},
/// An `open_review_shown` review as the guide, with `reading` from the same frame. The app
/// sends the review without its hunks' lines, which the guide doesn't show
ReviewGuide {
review: Box<GuidedReview>,
#[serde(default)]
reading: Vec<ChapterReading>,
#[serde(default)]
walked: Vec<ChapterId>,
},
/// One chapter opened. Args: `files`, only the files it names, holding only its hunks
ReviewChapter {
chapter: Box<ReviewChapter>,
files: Vec<ReviewFile>,
place: review::Place,
reading: Option<ChapterReading>,
/// The open session's comments; the chapter shows the ones on it
#[serde(default)]
findings: Vec<ReviewFinding>,
},
}
/// A content block as the wire carries it, where only text is read. The app sends any other block
/// as just its type, so a photo's bytes don't make the round trip.
#[derive(Debug, serde::Deserialize)]
#[serde(tag = "type", content = "content", rename_all = "snake_case")]
pub(crate) enum WireBlock {
/// Text
Text(String),
/// An image, counted
Image,
/// Anything else
#[serde(other)]
Other,
}
/// The pieces' HTML, in the order they were asked for.
#[derive(Debug, serde::Serialize)]
pub(crate) struct Rendered {
pub(crate) html: Vec<String>,
}
/// `piece` as the app's HTML.
pub(crate) fn render(renderer: &dyn Renderer, piece: &Piece) -> String {
match piece {
// what the agent wrote for Luxe to read (a remediation report, a draft) isn't the reader's
Piece::Answer { text } => renderer.markdown(&briefs::for_the_reader(text), Voice::Answer),
Piece::Reasoning { text } => renderer.markdown(text, Voice::Reasoning),
Piece::User { content } => user_message(content) + &images_attached(renderer, content),
Piece::Tool { name } => escape(&renderer.tool_glyph(name)),
Piece::Status(facts) => renderer.status(facts).iter().map(status_segment).collect(),
Piece::Plan { todos } => workspace::plan(renderer, todos),
Piece::Changes { changes } => workspace::changes(renderer, changes),
Piece::Diff { diff } => diff::file(renderer, diff),
Piece::DiffFailed { error } => diff::failed(error),
Piece::File { file } => file::file(renderer, file),
Piece::FileFailed { error } => file::failed(error),
Piece::Tree { rows, changes } => tree::tree(renderer, rows, changes.as_deref()),
Piece::ProjectName { name, branch, dirty } => {
tree::project_name(renderer, name, branch.as_deref(), *dirty)
}
Piece::ModeName { mode } => mode_name(renderer, mode),
Piece::GithubList { .. }
| Piece::GithubHeader { .. }
| Piece::GithubOverview { .. }
| Piece::GithubConversation { .. } => github_piece(renderer, piece),
Piece::ReviewGuide { review, reading, walked } => {
review::guide(renderer, review, reading, walked)
}
Piece::ReviewChapter { chapter, files, place, reading, findings } => {
review::chapter(renderer, chapter, files, place, reading.as_ref(), findings)
}
}
}
fn github_piece(renderer: &dyn Renderer, piece: &Piece) -> String {
let cx = |now: &u64| github::Context::new(renderer, *now);
match piece {
Piece::GithubList { repository, section, now } => {
github::list(&cx(now), repository.as_deref(), section)
}
Piece::GithubHeader { overview, now } => github::header(&cx(now), overview),
Piece::GithubOverview { overview, now } => github::overview(&cx(now), overview),
Piece::GithubConversation { entries, now, opened_by_you } => {
github::conversation(&cx(now), entries, *opened_by_you)
}
_ => String::new(),
}
}
/// `mode` behind its mark, or alone from a renderer without one.
fn mode_name(renderer: &dyn Renderer, mode: &str) -> String {
let mark = renderer.mode_mark(mode);
if mark.is_empty() {
return escape(mode);
}
format!(
"<span class=\"mode-mark\" aria-hidden=\"true\">{}</span> {}",
escape(&mark),
escape(mode)
)
}
fn status_segment(segment: &StatusSegment) -> String {
let tone = match segment.tone {
StatusTone::Plain => "",
StatusTone::Warning => " tone-warning",
StatusTone::Error => " tone-error",
};
let glyph = segment.glyph.as_deref().map(|glyph| {
format!("<span class=\"seg-glyph\" aria-hidden=\"true\">{}</span> ", escape(glyph))
});
format!(
"<span class=\"seg seg-{}{tone}\">{}{}</span>",
segment.kind,
glyph.unwrap_or_default(),
escape(&segment.label)
)
}
/// A user message as the transcript shows it: the reader's words as they wrote them, without the
/// notes that ride along for the model, and each brief as one line.
fn user_message(content: &[WireBlock]) -> String {
let texts = content.iter().map(|block| match block {
WireBlock::Text(text) => Some(text.as_str()),
WireBlock::Image | WireBlock::Other => None,
});
briefs::readers_texts(texts).iter().map(|(_, text)| user_block(text)).collect()
}
/// The line the TUI puts under a message that carried images.
fn images_attached(renderer: &dyn Renderer, content: &[WireBlock]) -> String {
let count = content.iter().filter(|block| matches!(block, WireBlock::Image)).count();
if count == 0 {
return String::new();
}
let glyph = renderer.image_glyph();
let glyph = if glyph.is_empty() { glyph } else { format!("{} ", escape(&glyph)) };
format!("<p class=\"attached\">{glyph}{count} image(s) attached</p>")
}
/// One block of a user message. A question from a review is the reader's own words, so it shows
/// what they asked under where they asked it.
fn user_block(text: &str) -> String {
let asked = briefs::review_questions(text);
if !asked.is_empty() {
return asked.iter().map(asked_in_review).collect();
}
match briefs::label(text) {
Some(label) => format!("<p class=\"brief\">{}</p>", escape(label)),
None => format!("<p class=\"words\">{}</p>", escape(text)),
}
}
fn asked_in_review(asked: &briefs::ReviewQuestion) -> String {
format!(
"<p class=\"words\"><span class=\"chip\">Asked in review \u{b7} {}</span>\n{}</p>",
escape(&asked.location),
escape(&asked.question)
)
}
/// `text` with everything that means something in HTML escaped.
pub(crate) fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for character in text.chars() {
match character {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(character),
}
}
out
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,93 @@
//! One file's diff, as the app shows it when a changed file is tapped.
//!
//! Unified, since a phone has no room for two columns, with each line's numbers, its sign and its
//! code highlighted the way the TUI's diff views highlight it. The row colors are the theme's diff
//! tints, applied by the app's stylesheet.
use super::{escape, Renderer};
use luxe_core::file_diff::{FileDiff, FileDiffFailure};
use luxe_core::guided_review::{ReviewFile, ReviewHunk, ReviewLine, ReviewLineKind};
/// The whole diff, or a line saying why there are no lines to show.
pub(super) fn file(renderer: &dyn Renderer, diff: &FileDiff) -> String {
let Some(file) = diff.file.as_deref() else {
return note("No change: the file matches the last commit.");
};
whole(renderer, file)
}
/// Every hunk of `file`, or a line saying why there are no lines to show.
pub(super) fn whole(renderer: &dyn Renderer, file: &ReviewFile) -> String {
if !file.is_text() {
return note("This change isn't text, so there are no lines to show.");
}
let hunks: String = file.hunks.iter().map(|hunk| hunk_html(renderer, file, hunk)).collect();
format!("{}{hunks}</div>", opening(file))
}
/// A diff block's opening tag, naming the file its lines can be picked in: the new side's path,
/// since a pick points at the file as it is now. A deleted file has nothing to point at.
pub(super) fn opening(file: &ReviewFile) -> String {
match file.new_path.as_deref() {
Some(path) => {
format!("<div class=\"diff\" data-path=\"{}\">", escape(&path.display().to_string()))
}
None => "<div class=\"diff\">".to_owned(),
}
}
/// Why the diff couldn't be captured, in core's words.
pub(super) fn failed(error: &FileDiffFailure) -> String {
note(&escape(&error.to_string()))
}
/// One hunk under its `@@` line.
pub(super) fn hunk_html(renderer: &dyn Renderer, file: &ReviewFile, hunk: &ReviewHunk) -> String {
let (old, new) = (hunk.old_range, hunk.new_range);
let heading = hunk.heading.as_deref().map(|heading| format!(" {}", escape(heading)));
let mut out = format!(
"<div class=\"hunk\"><p class=\"hunk-head\">@@ -{},{} +{},{} @@{}</p>",
old.start,
old.count,
new.start,
new.count,
heading.unwrap_or_default()
);
for line in &hunk.lines {
out.push_str(&line_html(renderer, file.language.as_deref(), line));
}
out + "</div>"
}
fn line_html(renderer: &dyn Renderer, language: Option<&str>, line: &ReviewLine) -> String {
let (kind, sign) = match line.kind {
ReviewLineKind::Context => ("context", " "),
ReviewLineKind::Deletion => ("deletion", "-"),
ReviewLineKind::Addition => ("addition", "+"),
// a note about the file, not a line of it, so it isn't code either
ReviewLineKind::NoNewlineMarker => {
return format!("<p class=\"dl dl-note\">{}</p>", escape(&line.text));
}
};
// only a line the file still has can be picked; a deleted one has no number to point at
let picks = line.new_line.map(|line| format!(" data-line=\"{line}\"")).unwrap_or_default();
format!(
"<p class=\"dl dl-{kind}\"{picks}><span class=\"ln\">{}</span><span class=\"ln\">{}</span>\
<span class=\"sign\">{sign}</span><code>{}</code></p>",
number(line.old_line),
number(line.new_line),
renderer.code_line(&line.text, language)
)
}
fn number(line: Option<u32>) -> String {
line.map(|line| line.to_string()).unwrap_or_default()
}
/// A line about the file rather than of it; `words` must already be escaped.
pub(super) fn note(words: &str) -> String {
format!("<p class=\"diff-note\">{words}</p>")
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,107 @@
use super::{failed, file};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
use luxe_core::file_diff::FileDiff;
use luxe_core::file_diff::FileDiffFailure;
/// Code that shows the language it was highlighted for, escaped.
struct Bracketed;
impl Renderer for Bracketed {
fn markdown(&self, text: &str, _voice: Voice) -> String {
escape(text)
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn code_line(&self, text: &str, language: Option<&str>) -> String {
format!("[{}:{}]", language.unwrap_or("-"), escape(text))
}
}
/// A `file_diff_loaded` frame's `diff`, copied from a live session.
const ADDED: &str = r#"{"path": "notes.txt", "file": {"id": "file:bebf0714d086bce43fab95f77103f6ec03bf140a484e7bc0eabaad1e0fc6c2fa", "old_path": null, "new_path": "notes.txt", "status": "added", "language": "txt", "additions": 1, "deletions": 0, "hunks": [{"id": "hunk:a6cc64dc21d9131afb5ce63a2d7f2eec2a826f3660d3f0d4b1d43295fa97babd", "old_range": {"start": 0, "count": 0}, "new_range": {"start": 1, "count": 1}, "heading": null, "symbol": null, "lines": [{"old_line": null, "new_line": 1, "kind": "addition", "text": "hello"}], "noise": "semantic"}], "binary": false, "generated": false, "non_text": null}, "untracked": false}"#;
/// One line of each kind, for a hunk built on [`ADDED`].
const EVERY_KIND: &str = r#"[{"old_line": 4, "new_line": 4, "kind": "context", "text": "fn a() {"}, {"old_line": 5, "new_line": null, "kind": "deletion", "text": " x < y"}, {"old_line": null, "new_line": 5, "kind": "addition", "text": " x > y"}, {"old_line": null, "new_line": null, "kind": "no_newline_marker", "text": "\\ No newline at end of file"}]"#;
fn diff(json: &str) -> FileDiff {
serde_json::from_str(json).expect("a file diff as core sends it")
}
/// The break this catches: the hunk's range, a line's numbers, sign or kind wrong, its code not
/// highlighted for the file's language, or the block and the line not saying what a pick of it
/// points at.
#[test]
fn an_added_file_shows_its_line() {
let expected = "<div class=\"diff\" data-path=\"notes.txt\"><div class=\"hunk\">\
<p class=\"hunk-head\">@@ -0,0 +1,1 @@</p><p class=\"dl dl-addition\" data-line=\"1\">\
<span class=\"ln\"></span><span class=\"ln\">1</span><span class=\"sign\">+</span>\
<code>[txt:hello]</code></p></div></div>";
assert_eq!(file(&Bracketed, &diff(ADDED)), expected);
}
/// The break this catches: a deletion signed or numbered as an addition or as context, a hunk's
/// heading dropped or unescaped, or the no-newline note drawn as a line of code.
#[test]
fn each_kind_of_line_keeps_its_sign_and_numbers() {
let modified = ADDED.replace(r#""heading": null"#, r#""heading": "impl <A>""#).replace(
r#"[{"old_line": null, "new_line": 1, "kind": "addition", "text": "hello"}]"#,
EVERY_KIND,
);
let html = file(&Bracketed, &diff(&modified));
// a deleted line names no line to pick: the file doesn't have it any more
let row = |kind: &str, old: &str, new: &str, sign: &str, code: &str| {
let picks = if new.is_empty() { String::new() } else { format!(" data-line=\"{new}\"") };
format!(
"<p class=\"dl dl-{kind}\"{picks}><span class=\"ln\">{old}</span><span \
class=\"ln\">{new}</span><span class=\"sign\">{sign}</span><code>[txt:{code}]</code></p>"
)
};
let expected = format!(
"<p class=\"hunk-head\">@@ -0,0 +1,1 @@ impl &lt;A&gt;</p>{}{}{}\
<p class=\"dl dl-note\">\\ No newline at end of file</p></div>",
row("context", "4", "4", " ", "fn a() {"),
row("deletion", "5", "", "-", " x &lt; y"),
row("addition", "", "5", "+", " x &gt; y"),
);
assert!(html.contains(&expected), "{html}");
}
/// A deleted file's block names no file to pick in, and a path is text in its attribute.
///
/// The break this catches: Ask offered on a file that's gone (the old path points at nothing), or a
/// path with a quote closing the attribute early.
#[test]
fn only_a_file_that_is_still_there_can_be_picked_in() {
let deleted = ADDED.replace(
r#""old_path": null, "new_path": "notes.txt""#,
r#""old_path": "notes.txt", "new_path": null"#,
);
assert!(file(&Bracketed, &diff(&deleted)).starts_with("<div class=\"diff\"><div"));
let quoted = ADDED.replace(r#""new_path": "notes.txt""#, r#""new_path": "a\"b&c.txt""#);
let html = file(&Bracketed, &diff(&quoted));
assert!(html.starts_with("<div class=\"diff\" data-path=\"a&quot;b&amp;c.txt\">"), "{html}");
}
/// The break this catches: a failure shown as nothing, or Git's words written into the page
/// unescaped.
#[test]
fn a_failure_says_why_in_cores_words() {
let git: FileDiffFailure =
serde_json::from_str(r#"{"git": "bad <ref>"}"#).expect("core's shape");
let expected = "<p class=\"diff-note\">git could not describe this file: bad &lt;ref&gt;</p>";
assert_eq!(failed(&git), expected);
}
/// The break this catches: a file that matches its base, or a binary one, drawn as an empty diff
/// with nothing saying why.
#[test]
fn a_diff_with_no_lines_says_why() {
let unchanged = r#"{"path": "notes.txt", "file": null, "untracked": false}"#;
assert!(file(&Bracketed, &diff(unchanged)).contains("matches the last commit"));
let binary = ADDED.replace(r#""binary": false"#, r#""binary": true"#);
assert!(file(&Bracketed, &diff(&binary)).contains("isn't text"));
}

View File

@@ -0,0 +1,61 @@
//! One project file, as the app's Files tab shows it.
//!
//! Each line numbered and highlighted the way a diff's lines are, so a file reads like the context
//! lines of its diff, and like those it keeps its indentation and scrolls sideways.
use super::diff::note;
use super::{escape, Renderer};
use luxe_core::project_files::{ProjectFile, ProjectFileFailure};
use std::path::Path;
/// The file's lines, or a line saying why there are none, with a note when the text stops short.
pub(super) fn file(renderer: &dyn Renderer, file: &ProjectFile) -> String {
if file.binary {
return note("Binary file");
}
if file.text.is_empty() {
return note("Empty file");
}
// core labels a diff's language by its extension, so a file's is the same
let language = Path::new(&file.path).extension().and_then(|extension| extension.to_str());
let lines: String = file
.text
.lines()
.enumerate()
.map(|(index, line)| line_html(renderer, language, index + 1, line))
.collect();
let path = escape(&file.path);
format!("<div class=\"file\" data-path=\"{path}\">{lines}</div>{}", cut_short(file))
}
/// Why the file couldn't be read, in core's words.
pub(super) fn failed(error: &ProjectFileFailure) -> String {
note(&escape(&error.to_string()))
}
fn line_html(renderer: &dyn Renderer, language: Option<&str>, number: usize, text: &str) -> String {
format!(
"<p class=\"fl\" data-line=\"{number}\"><span class=\"ln\">{number}</span><code>{}</code></p>",
renderer.code_line(text, language)
)
}
fn cut_short(file: &ProjectFile) -> String {
if !file.truncated {
return String::new();
}
note(&format!("First {} of {}", size(file.text.len() as u64), size(file.bytes)))
}
/// Bytes the way a person reads them: `900 B`, `12 KB`, `3.4 MB`.
fn size(bytes: u64) -> String {
const KB: u64 = 1024;
match bytes {
0..KB => format!("{bytes} B"),
KB..1_048_576 => format!("{} KB", bytes / KB),
_ => format!("{:.1} MB", bytes as f64 / 1_048_576.0),
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,93 @@
use super::{failed, file, size};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
use luxe_core::project_files::{ProjectFile, ProjectFileFailure};
/// Code that shows the language it was highlighted for, escaped.
struct Bracketed;
impl Renderer for Bracketed {
fn markdown(&self, text: &str, _voice: Voice) -> String {
escape(text)
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn code_line(&self, text: &str, language: Option<&str>) -> String {
format!("[{}:{}]", language.unwrap_or("-"), escape(text))
}
}
/// A `project_file_read` frame's `file`, copied from `luxe --rpc`.
const READ: &str = r#"{"path":"a.rs","text":"fn main() {\n\tprintln!(\"<hi>\");\n}\n","bytes":33,"truncated":false,"binary":false}"#;
fn read(edit: impl FnOnce(&mut ProjectFile)) -> ProjectFile {
let mut file = serde_json::from_str(READ).expect("a project file as core sends it");
edit(&mut file);
file
}
/// The break this catches: lines numbered from zero or out of order, a line dropped, the trailing
/// newline drawn as an empty last line, the code not highlighted for the file's extension, or a
/// line not saying which file and line a pick of it points at.
#[test]
fn a_file_shows_each_line_numbered_and_highlighted() {
let expected = "<div class=\"file\" data-path=\"a.rs\">\
<p class=\"fl\" data-line=\"1\"><span class=\"ln\">1</span><code>[rs:fn main() {]</code></p>\
<p class=\"fl\" data-line=\"2\"><span class=\"ln\">2</span>\
<code>[rs:\tprintln!(&quot;&lt;hi&gt;&quot;);]</code></p>\
<p class=\"fl\" data-line=\"3\"><span class=\"ln\">3</span><code>[rs:}]</code></p></div>";
assert_eq!(file(&Bracketed, &read(|_| ())), expected);
}
/// The break this catches: a file with no extension highlighted as some language anyway.
#[test]
fn a_file_without_an_extension_is_highlighted_as_nothing() {
let html = file(&Bracketed, &read(|file| file.path = "Makefile".into()));
assert!(html.contains("<code>[-:fn main() {]</code>"), "{html}");
}
/// The break this catches: a cut-short file shown as if it were whole, or the note's sizes swapped.
#[test]
fn a_cut_short_file_says_how_much_is_shown() {
let html = file(
&Bracketed,
&read(|file| {
file.truncated = true;
file.bytes = 3 * 1_048_576;
}),
);
assert!(html.ends_with("<p class=\"diff-note\">First 33 B of 3.0 MB</p>"), "{html}");
}
/// The break this catches: a binary file's empty text drawn as an empty file, or the reverse.
#[test]
fn a_binary_file_and_an_empty_one_each_say_so() {
let binary = read(|file| {
file.binary = true;
file.text.clear();
});
let empty = read(|file| file.text.clear());
assert_eq!(file(&Bracketed, &binary), "<p class=\"diff-note\">Binary file</p>");
assert_eq!(file(&Bracketed, &empty), "<p class=\"diff-note\">Empty file</p>");
}
/// The break this catches: a failure's reason left out, or a path in it not escaped.
#[test]
fn a_failure_says_why_in_cores_words() {
let not_found: ProjectFileFailure = serde_json::from_str(r#""not_found""#).expect("a failure");
let unreadable = ProjectFileFailure::Unreadable("<denied>".into());
assert_eq!(failed(&not_found), "<p class=\"diff-note\">nothing is there any more</p>");
assert!(failed(&unreadable).contains("&lt;denied&gt;"));
}
/// The break this catches: a boundary in the wrong unit, so 1024 bytes reads `1024 B`.
#[test]
fn sizes_read_in_the_unit_a_person_expects() {
assert_eq!(size(1023), "1023 B");
assert_eq!(size(1024), "1 KB");
assert_eq!(size(1_048_575), "1023 KB");
assert_eq!(size(1_048_576), "1.0 MB");
}

View File

@@ -0,0 +1,133 @@
//! GitHub — `/github`'s list, overview and conversation, drawn as the TUI draws them.
//!
//! The engine fetched everything and the app hands it back as pieces, so the bridge stays
//! stateless. Every fact is a word beside its mark, as in the TUI, so a missing glyph loses polish
//! and nothing else. Titles and bodies are strangers' words: sanitized by core, reduced from
//! GitHub's HTML by the renderer, and rendered escaped. Nothing here offers a write: a joined
//! session runs with GitHub writes off.
mod conversation;
mod list;
mod overview;
pub(super) use conversation::conversation;
pub(super) use list::list;
pub(super) use overview::{header, overview};
use luxe_core::github::PullRequestState;
use super::{escape, Renderer, Voice};
/// Characters of a body rendered before it's cut, as the TUI's detail cuts it.
const BODY_MAX_CHARS: usize = 20_000;
/// Characters of a title shown, as the TUI's header shows it.
const TITLE_MAX_CHARS: usize = 300;
/// The separator between facts on a line.
const DOT: &str = "<span class=\"dim\"> \u{b7} </span>";
/// The marks `/github` draws, as plain text.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GithubMarks {
/// Before a pull request's row
pub pull_request: String,
/// Before an issue's row
pub issue: String,
/// Passed or approved
pub yes: String,
/// Failed or refused
pub no: String,
/// Running or waiting on someone
pub waiting: String,
/// Before a count of lines left out
pub elision: String,
}
/// What every GitHub view draws with: the renderer, its marks, and the app's clock, which the app
/// sends so a piece renders the same whenever it's asked.
pub(super) struct Context<'a> {
renderer: &'a dyn Renderer,
marks: GithubMarks,
now: u64,
}
impl<'a> Context<'a> {
pub(super) fn new(renderer: &'a dyn Renderer, now: u64) -> Self {
Self { renderer, marks: renderer.github_marks(), now }
}
/// How long ago `at` was, in the TUI's words, escaped; empty from a renderer without them.
fn ago(&self, at: u64) -> String {
escape(&self.renderer.ago(at, self.now))
}
/// A stranger's markdown as HTML: sanitized, its HTML reduced, rendered escaped.
fn body(&self, text: &str) -> String {
let clean = luxe_core::github::untrusted(text, BODY_MAX_CHARS);
let readable = self.renderer.github_readable(&clean);
if readable.trim().is_empty() {
return String::new();
}
self.renderer.markdown(&readable, Voice::Answer)
}
}
/// A title, sanitized and escaped.
fn title(text: &str) -> String {
escape(&luxe_core::github::untrusted(text, TITLE_MAX_CHARS))
}
/// The state's word and the class that colors it, shared by a row's mark and the state chip.
fn state_word(state: PullRequestState, draft: bool, issue: bool) -> (&'static str, &'static str) {
match (state, draft) {
(PullRequestState::Open, true) => ("draft", "hue-muted"),
(PullRequestState::Open, false) => ("open", "hue-success"),
(PullRequestState::Merged, _) => ("merged", "hue-secondary"),
(PullRequestState::Closed, _) if issue => ("closed", "hue-secondary"),
(PullRequestState::Closed, _) => ("closed", "hue-error"),
}
}
/// `mara`, or `dependabot bot` with the word quiet: a bot is named as one. `ghost` for a
/// deleted account.
fn login(login: &str, bot: bool) -> String {
let login = login.trim_end_matches("[bot]");
match (login.is_empty(), bot) {
(true, _) => "<span class=\"hue-muted\">ghost</span>".to_owned(),
(false, true) => format!(
"<span class=\"hue-muted\">{}</span><span class=\"dim\"> bot</span>",
escape(login)
),
(false, false) => format!("<span class=\"hue-secondary\">{}</span>", escape(login)),
}
}
/// `+50 −12` in the diff colors.
fn counts(additions: u64, deletions: u64) -> String {
format!(
"<span class=\"add\">+{additions}</span> <span class=\"del\">\u{2212}{deletions}</span>"
)
}
/// `words` after `glyph` in `class`, the glyph left out when the renderer has none.
fn marked(glyph: &str, words: &str, class: &str) -> String {
let lead = if glyph.is_empty() { String::new() } else { format!("{} ", escape(glyph)) };
format!("<span class=\"{class}\">{lead}{}</span>", escape(words))
}
/// `count` with its thousands set apart: `3,250`.
fn grouped(count: u64) -> String {
let digits = count.to_string();
let mut out = String::new();
for (index, digit) in digits.chars().enumerate() {
if index > 0 && (digits.len() - index).is_multiple_of(3) {
out.push(',');
}
out.push(digit);
}
out
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,203 @@
//! The Conversation: everything said, oldest first, each entry a card of its own.
//!
//! The cards are the TUI's: the tone says what kind of thing was said (an open thread in the info
//! color, changes requested in the error color, a bot quieter than a person), a long comment folds
//! to its first lines, and a thread shows its last word until it's opened.
use luxe_core::github::overview::{by_bot_login, ConversationEntry, Verdict};
use luxe_core::github::{rfc3339_seconds, ConversationComment, ReviewThread, ThreadComment};
use super::{Context, BODY_MAX_CHARS, DOT};
use crate::render::escape;
/// Lines of a comment's source past which it folds. Agents write long, and a timeline of whole
/// comments is a wall; a fold that hides one line costs the line it saves.
const FOLD_LINES: usize = 7;
/// Characters of a thread's last word shown while it's folded, as the TUI shows it.
const LAST_WORD_CHARS: usize = 400;
/// The conversation's cards. `opened_by_you` names the description as yours when you wrote it.
pub(in crate::render) fn conversation(
cx: &Context,
entries: &[ConversationEntry],
opened_by_you: bool,
) -> String {
let cards: String = entries.iter().map(|entry| card(cx, entry, opened_by_you)).collect();
format!("<div class=\"gh-conversation\">{cards}</div>")
}
fn card(cx: &Context, entry: &ConversationEntry, opened_by_you: bool) -> String {
match entry {
ConversationEntry::Opening { author, body, at } => {
let title = speaker(&author.login, author.bot, opened_by_you)
+ &said("opened", "hue-muted")
+ &said(&cx.ago(*at), "hue-muted");
said_card(cx, if author.bot { "quiet" } else { "person" }, &title, body)
}
ConversationEntry::Comment(comment) => {
let title = speaker(&comment.author, comment.bot, comment.mine)
+ &said("commented", "hue-muted")
+ &when(cx, &comment.created_at);
said_card(cx, if comment.bot { "quiet" } else { "person" }, &title, &comment.body)
}
ConversationEntry::Review { comment, verdict, line_comments } => {
review_card(cx, comment, *verdict, *line_comments)
}
ConversationEntry::Thread(thread) => thread_card(cx, thread),
}
}
/// `@mara` naming a speaker: yours in the accent, a bot's quiet and named as one, anyone else's
/// in the color a reviewer wears.
fn speaker(login: &str, bot: bool, mine: bool) -> String {
let login = login.trim_end_matches("[bot]");
if login.is_empty() {
return "<span class=\"hue-muted\">@ghost</span>".to_owned();
}
let name = escape(&format!("@{login}"));
match (mine, bot) {
(true, _) => format!("<span class=\"gh-mine\">{name}</span>"),
(false, true) => {
format!("<span class=\"hue-muted\">{name}</span><span class=\"dim\"> bot</span>")
}
(false, false) => format!("<span class=\"hue-secondary\">{name}</span>"),
}
}
/// ` · words` in `class`.
fn said(words: &str, class: &str) -> String {
format!("{DOT}<span class=\"{class}\">{}</span>", escape(words))
}
/// ` · 3h ago` from GitHub's timestamp, or nothing when it can't be read.
fn when(cx: &Context, created_at: &str) -> String {
rfc3339_seconds(created_at).map(|at| said(&cx.ago(at), "hue-muted")).unwrap_or_default()
}
/// A review's summary card, toned by its verdict unless a bot gave it.
fn review_card(
cx: &Context,
comment: &ConversationComment,
verdict: Verdict,
lines: usize,
) -> String {
let (words, class, tone) = match verdict {
Verdict::Approved => ("approved", "hue-success", "approved"),
Verdict::ChangesRequested => ("requested changes", "hue-error", "changes"),
Verdict::Commented => ("reviewed", "hue-muted", "person"),
Verdict::Dismissed => ("review dismissed", "hue-muted", "person"),
Verdict::Requested => ("asked to review", "hue-warning", "person"),
};
let title = speaker(&comment.author, comment.bot, comment.mine)
+ &said(words, class)
+ &line_comments(lines)
+ &when(cx, &comment.created_at);
said_card(cx, if comment.bot { "quiet" } else { tone }, &title, &comment.body)
}
fn line_comments(count: usize) -> String {
match count {
0 => String::new(),
1 => said("1 line comment", "hue-muted"),
n => said(&format!("{n} line comments"), "hue-muted"),
}
}
/// A card for something said: its title, then its body, folded when it runs long.
fn said_card(cx: &Context, tone: &str, title: &str, body: &str) -> String {
let rendered = cx.body(body);
let fold = folds(body);
let (class, unfold) = match fold {
true => (" folded", unfold_button(cx)),
false => ("", String::new()),
};
format!(
"<section class=\"gh-card tone-{tone}{class}\"><p class=\"gh-card-title\">{title}</p>\
<div class=\"gh-body md\">{rendered}</div>{unfold}</section>"
)
}
/// Whether a body says more lines than a card shows before it folds.
fn folds(body: &str) -> bool {
let clean = luxe_core::github::untrusted(body, BODY_MAX_CHARS);
clean.lines().filter(|line| !line.trim().is_empty()).count() > FOLD_LINES
}
fn unfold_button(cx: &Context) -> String {
let lead = match cx.marks.elision.is_empty() {
true => String::new(),
false => format!("{} ", escape(&cx.marks.elision)),
};
format!("<button type=\"button\" class=\"gh-unfold\">{lead}Show all</button>")
}
/// A review thread: who started it, where, whether it's settled, then its last word folded or
/// every comment open, as a native disclosure so it opens without the app.
fn thread_card(cx: &Context, thread: &ReviewThread) -> String {
let first = thread.comments.first();
let starter = first.map(|comment| comment.author.as_str()).unwrap_or_default();
let (state, class, tone) = match (thread.resolved, thread.outdated) {
(true, _) => ("resolved", "dim", "person"),
(false, true) => ("outdated", "dim", "person"),
(false, false) => ("unresolved", "hue-info", "unresolved"),
};
let title = speaker(starter, first.is_some_and(by_bot_login), false)
+ &format!("{DOT}{}", escape(&place(thread)))
+ &said(state, class)
+ &replies(thread.total_comments);
let comments: String =
thread.comments.iter().map(|comment| thread_comment(cx, comment)).collect();
format!(
"<details class=\"gh-card gh-thread tone-{tone}\"><summary><span class=\"gh-card-title\">\
{title}</span>{}</summary>{comments}</details>",
last_word(thread)
)
}
/// `src/api/webhook.rs:42`, the path cut to its last two parts when it's long.
fn place(thread: &ReviewThread) -> String {
let parts: Vec<&str> = thread.path.split('/').collect();
let path = match parts.len() {
0..=3 => thread.path.clone(),
n => format!("\u{2026}/{}", parts[n - 2..].join("/")),
};
match thread.line {
Some(line) => format!("{path}:{line}"),
None => path,
}
}
fn replies(total: usize) -> String {
match total.saturating_sub(1) {
0 => String::new(),
1 => said("1 reply", "hue-muted"),
n => said(&format!("{n} replies"), "hue-muted"),
}
}
/// What a folded thread shows: the last comment, on one line.
fn last_word(thread: &ReviewThread) -> String {
let Some(comment) = thread.comments.last() else {
return String::new();
};
let words = luxe_core::github::untrusted(&comment.body, LAST_WORD_CHARS);
let words = words.split_whitespace().collect::<Vec<_>>().join(" ");
let who = format!("@{}: ", comment.author.trim_end_matches("[bot]"));
format!(
"<span class=\"gh-last\"><span class=\"hue-muted\">{}</span>{}</span>",
escape(&who),
escape(&words)
)
}
/// One comment in an opened thread: who and when, then what they said.
fn thread_comment(cx: &Context, comment: &ThreadComment) -> String {
let head =
speaker(&comment.author, by_bot_login(comment), false) + &when(cx, &comment.created_at);
format!(
"<div class=\"gh-reply\"><p class=\"gh-card-title\">{head}</p><div class=\"gh-body \
md\">{}</div></div>",
cx.body(&comment.body)
)
}

View File

@@ -0,0 +1,146 @@
//! The list side of `/github`: how many a tab's search found, then each pull request or issue on
//! the TUI's two lines.
//!
//! Line one is what it is: a state mark, the number, the title, how long ago it changed. Line two
//! is where it stands, quiet: who opened it, how big it is, and on the right its status in words.
//! A row is a button whose data says which item to open; the app owns the tap.
use luxe_core::github::overview::RowFacts;
use luxe_core::github::{
rfc3339_seconds, ListItem, ListedSection, PullRequestState, ReviewDecision,
};
use super::{counts, grouped, login, marked, state_word, title, Context, DOT};
use crate::render::escape;
/// A tab's rows, or why it has none. `repository` is the checkout's, which a row from elsewhere
/// names its own beside.
pub(in crate::render) fn list(
cx: &Context,
repository: Option<&str>,
section: &ListedSection,
) -> String {
if let Some(error) = &section.error {
return format!("<p class=\"gh-note hue-error\">{}</p>", escape(error));
}
if section.items.is_empty() {
return "<p class=\"gh-note dim\">Nothing matches this search</p>".to_owned();
}
let rows: String = section.items.iter().map(|item| row(cx, item, repository)).collect();
format!("<div class=\"gh-list\"><p class=\"gh-count dim\">{}</p>{rows}</div>", shown(section))
}
/// How many are here of how many there are. The rest are GitHub's to show: paging needs the
/// section's query, which the listing doesn't carry.
fn shown(section: &ListedSection) -> String {
let loaded = section.items.len() as u64;
match section.total {
Some(total) if total > loaded => format!("{} of {}", grouped(loaded), grouped(total)),
_ => format!("{} shown", grouped(loaded)),
}
}
fn row(cx: &Context, item: &ListItem, repository: Option<&str>) -> String {
let age = rfc3339_seconds(&item.updated_at).map(|at| cx.ago(at)).unwrap_or_default();
format!(
"<button type=\"button\" class=\"gh-row\" data-number=\"{}\" data-pull=\"{}\" \
data-repository=\"{}\" data-url=\"{}\"><span class=\"gh-line\">{}\
<span class=\"dim\">#{} </span><span class=\"gh-title\">{}</span>\
<span class=\"gh-right dim\">{}</span></span>{}</button>",
item.number,
item.pull_request,
escape(&item.repository),
escape(&item.url),
row_mark(cx, item),
item.number,
title(&item.title),
age.trim_end_matches(" ago"),
second_line(cx, item, repository.is_some_and(|here| here != item.repository))
)
}
/// A pull request's or an issue's mark, in its state's color.
fn row_mark(cx: &Context, item: &ListItem) -> String {
let issue = !item.pull_request;
let glyph = if issue { &cx.marks.issue } else { &cx.marks.pull_request };
if glyph.is_empty() {
return String::new();
}
let (_, class) = state_word(item.state, item.draft, issue);
format!("<span class=\"gh-mark {class}\">{}</span>", escape(glyph))
}
/// Who opened it, from where when it's another repository, and how big it is, then its status.
fn second_line(cx: &Context, item: &ListItem, elsewhere: bool) -> String {
let facts = item.facts.as_ref();
let mut left = login(&item.author, facts.is_some_and(|facts| facts.author_bot));
if elsewhere {
left += &format!("{DOT}<span class=\"hue-muted\">{}</span>", escape(&item.repository));
}
if let Some(facts) = facts {
left += &size(facts, item.pull_request);
}
format!(
"<span class=\"gh-line gh-sub\"><span class=\"gh-who\">{left}</span>\
<span class=\"gh-right\">{}</span></span>",
status(cx, item, facts).join(DOT)
)
}
/// A pull request's diff counts, or an issue's labels, after a separator; nothing for an issue
/// without labels.
fn size(facts: &RowFacts, pull_request: bool) -> String {
if pull_request {
return format!("{DOT}{}", counts(facts.additions, facts.deletions));
}
if facts.labels.is_empty() {
return String::new();
}
let names: Vec<&str> = facts.labels.iter().map(|label| label.name.as_str()).collect();
format!("{DOT}<span class=\"hue-muted\">{}</span>", escape(&names.join(", ")))
}
/// Where it stands, in words: `✗ 1 failing · changes requested`.
fn status(cx: &Context, item: &ListItem, facts: Option<&RowFacts>) -> Vec<String> {
let mut parts = Vec::new();
let (word, class) = state_word(item.state, item.draft, !item.pull_request);
if item.draft || item.state != PullRequestState::Open {
parts.push(marked("", word, class));
}
let Some(facts) = facts else {
return parts;
};
match item.pull_request {
true => parts.extend(pull_request_status(cx, facts)),
false => parts.extend(issue_status(cx, facts)),
}
parts
}
fn issue_status(cx: &Context, facts: &RowFacts) -> Option<String> {
if let Some(number) = facts.linked_pull_request {
return Some(marked(&cx.marks.waiting, &format!("PR #{number}"), "hue-warning"));
}
let noun = if facts.comments == 1 { "comment" } else { "comments" };
(facts.comments > 0).then(|| marked("", &format!("{} {noun}", facts.comments), "hue-muted"))
}
fn pull_request_status(cx: &Context, facts: &RowFacts) -> Vec<String> {
let checks = &facts.checks;
let mut parts = Vec::new();
if checks.failed > 0 {
parts.push(marked(&cx.marks.no, &format!("{} failing", checks.failed), "hue-error"));
} else if checks.pending > 0 {
parts.push(marked(&cx.marks.waiting, "running", "hue-warning"));
} else if checks.passed > 0 {
parts.push(marked(&cx.marks.yes, "checks", "hue-success"));
}
let review = match facts.review_decision {
Some(ReviewDecision::ChangesRequested) => Some(("changes requested", "hue-error")),
Some(ReviewDecision::Approved) => Some(("approved", "hue-success")),
Some(ReviewDecision::ReviewRequired) => Some(("needs review", "hue-muted")),
None => None,
};
parts.extend(review.map(|(word, class)| marked("", word, class)));
parts
}

View File

@@ -0,0 +1,279 @@
//! The detail's header and its Overview: what stands between a pull request and merged, or who
//! is on an issue, then the start of the description.
//!
//! The merge checks are core's (`merge_checks`), so the phone and the TUI agree on what blocks a
//! merge. Their actions are GitHub writes or agent work, which a joined session doesn't take, so a
//! row shows its evidence and no key; only "open #N", which reads, is offered.
use luxe_core::github::overview::{
blocking, merge_checks, CheckAction, CheckMark, IssueOverview, Label, LinkedPullRequest,
MergeCheck, Overview, PullRequestOverview, Reviewer, ReviewerKind, Verdict,
};
use luxe_core::github::{Author, PullRequestState};
use super::{counts, login, state_word, title, Context, BODY_MAX_CHARS, DOT};
use crate::render::escape;
/// Lines of the description the Overview quotes before pointing at Conversation.
const EXCERPT_LINES: usize = 5;
/// Labels the header shows, as the TUI's does.
const HEADER_LABELS: usize = 4;
/// `#182 Title`, then who, where and how big, then the state and labels as chips.
pub(in crate::render) fn header(cx: &Context, overview: &Overview) -> String {
let (head, meta) = match overview {
Overview::PullRequest(pr) => (heading_facts(pr), pull_request_meta(pr)),
Overview::Issue(issue) => (issue_facts(issue), String::new()),
};
format!(
"<header class=\"gh-head\"><h2 class=\"gh-heading\"><span class=\"dim\">#{} </span>{}</h2>\
<p class=\"gh-meta\">{}{meta}{DOT}<span class=\"dim\">{}</span></p>\
<p class=\"gh-chips\">{}</p></header>",
overview.number(),
title(head.title),
login(&head.author.login, head.author.bot),
cx.ago(head.updated_at),
chips(&head)
)
}
/// What the header says about either kind.
struct HeadFacts<'a> {
title: &'a str,
author: &'a Author,
state: PullRequestState,
draft: bool,
issue: bool,
labels: &'a [Label],
updated_at: u64,
}
fn heading_facts(pr: &PullRequestOverview) -> HeadFacts<'_> {
let (title, author, labels) = (&pr.title, &pr.author, &pr.labels);
HeadFacts {
title,
author,
state: pr.state,
draft: pr.draft,
issue: false,
labels,
updated_at: pr.updated_at,
}
}
fn issue_facts(issue: &IssueOverview) -> HeadFacts<'_> {
let (title, author, labels) = (&issue.title, &issue.author, &issue.labels);
HeadFacts {
title,
author,
state: issue.state,
draft: false,
issue: true,
labels,
updated_at: issue.updated_at,
}
}
/// ` · master ← feature · +8 −8 in 4 files`.
fn pull_request_meta(pr: &PullRequestOverview) -> String {
let files = if pr.changed_files == 1 { "file" } else { "files" };
format!(
"{DOT}{} <span class=\"hue-muted\">\u{2190}</span> {}{DOT}{} \
<span class=\"hue-muted\">in {} {files}</span>",
escape(&pr.base_ref),
escape(&pr.head_ref),
counts(pr.additions, pr.deletions),
pr.changed_files
)
}
/// The state as a filled chip cut from its own color, then up to four labels on the chip surface.
fn chips(head: &HeadFacts) -> String {
let (word, class) = state_word(head.state, head.draft, head.issue);
let mut out = format!("<span class=\"gh-state {class}\">{word}</span>");
for label in head.labels.iter().take(HEADER_LABELS) {
let name = escape(&luxe_core::github::untrusted(&label.name, 40));
out += &format!(" <span class=\"gh-label-chip\"><span class=\"hue-muted\">\u{25cf}</span> {name}</span>");
}
out
}
/// The Overview's sections, under the header.
pub(in crate::render) fn overview(cx: &Context, overview: &Overview) -> String {
match overview {
Overview::PullRequest(pr) => {
status_section(cx, pr) + &reviewers_section(cx, pr) + &excerpt(cx, &pr.body)
}
Overview::Issue(issue) => issue_section(cx, issue) + &excerpt(cx, &issue.body),
}
}
/// A section's heading, with a quiet note against the far edge.
fn section_heading(text: &str, note: Option<String>) -> String {
let note = note.map(|note| format!("<span class=\"gh-right dim\">{}</span>", escape(&note)));
format!("<h3 class=\"gh-section\">{text}{}</h3>", note.unwrap_or_default())
}
/// One row: its mark, a label in the label column, then the evidence.
fn check_row(cx: &Context, mark: CheckMark, label: &str, detail: &str) -> String {
let (glyph, class) = match mark {
CheckMark::Pass => (cx.marks.yes.as_str(), "hue-success"),
CheckMark::Fail => (cx.marks.no.as_str(), "hue-error"),
CheckMark::Wait => (cx.marks.waiting.as_str(), "hue-warning"),
CheckMark::Note => ("\u{2013}", "hue-muted"),
};
format!(
"<p class=\"gh-check\"><span class=\"gh-mark {class}\">{}</span>\
<span class=\"gh-label\">{}</span><span class=\"gh-evidence\">{detail}</span></p>",
escape(glyph),
escape(label)
)
}
/// The checks between the pull request and merged, blockers first.
fn status_section(cx: &Context, pr: &PullRequestOverview) -> String {
let checks = merge_checks(pr);
if checks.is_empty() {
return String::new();
}
let note = match blocking(&checks) {
0 => None,
count => Some(format!("{count} incomplete")),
};
let rows: String = checks.iter().map(|check| merge_row(cx, check)).collect();
section_heading("Status", note) + &rows
}
/// A merge check's row: a failure's evidence in body text, the rest quiet, and a way to the pull
/// request below it in a stack, the one action that only reads.
fn merge_row(cx: &Context, check: &MergeCheck) -> String {
let tone = if check.mark == CheckMark::Fail { "" } else { "hue-muted" };
let mut detail = format!("<span class=\"{tone}\">{}</span>", escape(&check.detail));
if let Some(CheckAction::OpenBelow(number)) = check.action {
detail += &format!(
" <button type=\"button\" class=\"gh-open\" data-number=\"{number}\" \
data-pull=\"true\">open #{number}</button>"
);
}
check_row(cx, check.mark, check.label, &detail)
}
/// Each reviewer, with what they said and when.
fn reviewers_section(cx: &Context, pr: &PullRequestOverview) -> String {
if pr.reviewers.is_empty() {
return String::new();
}
let approved = pr.reviewers.iter().filter(|r| r.verdict == Verdict::Approved).count();
let note = format!("{approved} of {} approved", pr.reviewers.len());
let rows: String = pr.reviewers.iter().map(|reviewer| reviewer_row(cx, reviewer)).collect();
section_heading("Reviewers", Some(note)) + &rows
}
fn reviewer_row(cx: &Context, reviewer: &Reviewer) -> String {
let (mark, said, class) = match reviewer.verdict {
Verdict::Approved => (CheckMark::Pass, "approved", "hue-success"),
Verdict::ChangesRequested => (CheckMark::Fail, "changes requested", "hue-error"),
Verdict::Commented => (CheckMark::Note, "commented", "hue-muted"),
Verdict::Dismissed => (CheckMark::Note, "dismissed", "hue-muted"),
Verdict::Requested => (CheckMark::Wait, "requested", "hue-warning"),
};
let kind = match reviewer.kind {
ReviewerKind::Team => " \u{b7} team",
ReviewerKind::Bot => " \u{b7} bot",
ReviewerKind::User => "",
};
let when = reviewer.at.map(|at| format!(" \u{b7} {}", cx.ago(at))).unwrap_or_default();
let detail = format!(
"<span class=\"{class}\">{said}</span><span class=\"dim\">{kind}</span>\
<span class=\"hue-muted\">{when}</span>"
);
check_row(cx, mark, &reviewer.login, &detail)
}
/// Who's on an issue, which pull requests close it, and its milestone.
fn issue_section(cx: &Context, issue: &IssueOverview) -> String {
let assignees = match issue.assignees.as_slice() {
[] => "<span class=\"hue-muted\">unassigned</span>".to_owned(),
logins => format!("<span class=\"hue-secondary\">{}</span>", escape(&logins.join(", "))),
};
let mut rows = check_row(cx, CheckMark::Note, "Assignees", &assignees);
rows += &closing_rows(cx, issue);
if let Some(milestone) = &issue.milestone {
rows += &check_row(cx, CheckMark::Note, "Milestone", &escape(milestone));
}
section_heading("Status", None) + &rows
}
/// The pull requests that close the issue when they merge, each a way to open it.
fn closing_rows(cx: &Context, issue: &IssueOverview) -> String {
let closing: Vec<_> = issue.linked.iter().filter(|linked| linked.closes).collect();
if closing.is_empty() {
let none = "<span class=\"hue-muted\">none yet</span>";
return check_row(cx, CheckMark::Note, "Pull requests", none);
}
let label = |index| if index == 0 { "Pull requests" } else { "" };
closing
.iter()
.enumerate()
.map(|(index, linked)| closing_row(cx, label(index), linked))
.collect()
}
/// Which pull request, how far along, and whose: the question the row answers is whether
/// somebody is already on it.
fn closing_row(cx: &Context, label: &str, linked: &LinkedPullRequest) -> String {
let (word, class) = state_word(linked.state, linked.draft, false);
let mark = match linked.state {
PullRequestState::Open => CheckMark::Wait,
PullRequestState::Merged => CheckMark::Pass,
PullRequestState::Closed => CheckMark::Note,
};
let detail = format!(
"<button type=\"button\" class=\"gh-open\" data-number=\"{0}\" data-pull=\"true\">#{0}\
</button>{DOT}<span class=\"{class}\">{word}</span>{DOT}{1}",
linked.number,
login(&linked.author, false)
);
check_row(cx, mark, label, &detail)
}
/// A heading and the first lines of the description, pointing at Conversation for the rest.
fn excerpt(cx: &Context, body: &str) -> String {
let heading = section_heading("Description", None);
let readable = cx.renderer.github_readable(&luxe_core::github::untrusted(body, BODY_MAX_CHARS));
let (kept, hidden) = first_lines(&readable, EXCERPT_LINES);
if kept.trim().is_empty() {
return heading + "<p class=\"gh-note dim\">No description</p>";
}
let rendered = cx.renderer.markdown(&kept, crate::render::Voice::Answer);
let more = match hidden {
0 => String::new(),
hidden => format!(
"<button type=\"button\" class=\"gh-more\" data-tab=\"conversation\">{} {hidden} more \
lines in Conversation</button>",
escape(&cx.marks.elision)
),
};
format!("{heading}<div class=\"gh-body md\">{rendered}</div>{more}")
}
/// The first `keep` lines of `text` that say something, with the blank lines between them, and
/// how many lines that say something are left: a paragraph break isn't worth one of the five.
fn first_lines(text: &str, keep: usize) -> (String, usize) {
let mut said = 0;
let mut kept = String::new();
let mut lines = text.lines();
for line in lines.by_ref() {
if !line.trim().is_empty() {
if said == keep {
let hidden = 1 + lines.filter(|line| !line.trim().is_empty()).count();
return (kept, hidden);
}
said += 1;
}
kept += line;
kept.push('\n');
}
(kept, 0)
}

View File

@@ -0,0 +1,47 @@
use super::{Context, GithubMarks};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
mod conversation;
mod list;
mod overview;
/// The marks as words and ages in seconds, so a test reads which mark and which clock landed
/// where. Bodies come back marked twice, `<md>R:…</md>`, to show they were made readable first.
struct Worded;
impl Renderer for Worded {
fn markdown(&self, text: &str, _voice: Voice) -> String {
format!("<md>{}</md>", escape(text))
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn github_marks(&self) -> GithubMarks {
let word = |word: &str| word.to_owned();
GithubMarks {
pull_request: word("PR"),
issue: word("IS"),
yes: word("Y"),
no: word("N"),
waiting: word("W"),
elision: word("…"),
}
}
fn ago(&self, at: u64, now: u64) -> String {
format!("{}s ago", now.saturating_sub(at))
}
fn github_readable(&self, body: &str) -> String {
match body.trim().is_empty() {
true => body.to_owned(),
false => format!("R:{body}"),
}
}
}
/// An hour after `at`, by the app's clock.
fn an_hour_after(at: u64) -> Context<'static> {
Context::new(&Worded, at + 3600)
}

View File

@@ -0,0 +1,141 @@
use super::an_hour_after;
use crate::render::github::conversation;
use luxe_core::github::overview::ConversationEntry;
use serde_json::{json, Value};
/// A `github_conversation_read` frame's opening entry, copied from a live session, its long
/// dependabot body cut to its first line.
const OPENING: &str = r#"{"kind": "opening", "author": {"login": "dependabot", "bot": true}, "body": "Bumps the actions group with 2 updates in the / directory.", "at": 1792259399}"#;
const CHANGED: u64 = 1_792_259_399;
/// When `CHANGED` was, as GitHub writes a comment's time.
const CHANGED_TEXT: &str = "2026-10-17T17:49:59Z";
fn drawn(entries: Vec<Value>, opened_by_you: bool) -> String {
let entries: Vec<ConversationEntry> =
serde_json::from_value(json!(entries)).expect("entries as core sends them");
conversation(&an_hour_after(CHANGED), &entries, opened_by_you)
}
fn comment(author: &str, bot: bool, mine: bool, body: &str) -> Value {
json!({"id": "IC_1", "author": author, "bot": bot, "mine": mine, "body": body,
"created_at": CHANGED_TEXT, "url": "https://github.com/o/r/pull/1#issuecomment-1"})
}
/// A comment as the timeline's own entry.
fn said(author: &str, bot: bool, mine: bool, body: &str) -> Value {
let mut entry = comment(author, bot, mine, body);
entry["kind"] = json!("comment");
entry
}
fn review(verdict: &str, line_comments: usize, bot: bool) -> Value {
let comment = comment("mara", bot, false, "Looks fine.");
json!({"kind": "review", "comment": comment, "verdict": verdict, "line_comments": line_comments})
}
fn thread(path: &str, resolved: bool, outdated: bool, said: &[(&str, &str)]) -> Value {
let comments: Vec<Value> = said
.iter()
.map(|(author, body)| {
json!({"author": author,
"body": body, "created_at": CHANGED_TEXT, "url": "https://github.com/o/r/pull/1#r1"})
})
.collect();
json!({"kind": "thread", "id": "PRRT_1", "path": path, "line": 42, "start_line": null,
"side": "right", "outdated": outdated, "resolved": resolved, "file_level": false,
"comments": comments, "total_comments": said.len(), "anchor_text": null,
"can_reply": false, "can_resolve": false})
}
/// The break this catches: the real opening entry drawn as a person's, without its age, or with
/// its body rendered before its HTML was made readable.
#[test]
fn the_opening_reads_as_the_tuis() {
let opening: Value = serde_json::from_str(OPENING).expect("an opening as core sends it");
let html = drawn(vec![opening], false);
assert!(html.contains("<section class=\"gh-card tone-quiet\">"), "{html}");
let bot = "<span class=\"hue-muted\">@dependabot</span><span class=\"dim\"> bot</span>";
assert!(html.contains(bot), "{html}");
assert!(html.contains(">opened</span>"), "{html}");
assert!(html.contains(">3600s ago</span>"), "{html}");
assert!(html.contains("<md>R:Bumps the actions group"), "{html}");
}
/// The break this catches: your own description or comment not named as yours, a person's
/// comment drawn quiet, or a comment's time dropped.
#[test]
fn a_comment_names_its_speaker() {
let opening = json!({"kind": "opening", "author": {"login": "me", "bot": false}, "body": "x", "at": CHANGED});
let html = drawn(vec![opening], true);
assert!(html.contains("<span class=\"gh-mine\">@me</span>"), "{html}");
let html = drawn(vec![said("jo", false, false, "Hi.")], false);
assert!(html.contains("<section class=\"gh-card tone-person\">"), "{html}");
assert!(html.contains("<span class=\"hue-secondary\">@jo</span>"), "{html}");
assert!(html.contains(">commented</span>"), "{html}");
assert!(html.contains(">3600s ago</span>"), "{html}");
let html = drawn(vec![said("me", false, true, "Hi.")], false);
assert!(html.contains("<span class=\"gh-mine\">@me</span>"), "{html}");
let html = drawn(vec![said("", false, false, "Hi.")], false);
assert!(html.contains("<span class=\"hue-muted\">@ghost</span>"), "{html}");
}
/// The break this catches: a verdict in the wrong words or tone, a bot's review toned like a
/// person's, or the line comments miscounted.
#[test]
fn a_review_is_toned_by_its_verdict() {
let html = drawn(vec![review("approved", 0, false)], false);
assert!(html.contains("tone-approved"), "{html}");
assert!(html.contains("<span class=\"hue-success\">approved</span>"), "{html}");
assert!(!html.contains("line comment"), "{html}");
let html = drawn(vec![review("changes_requested", 1, false)], false);
assert!(html.contains("tone-changes"), "{html}");
assert!(html.contains("<span class=\"hue-error\">requested changes</span>"), "{html}");
assert!(html.contains(">1 line comment</span>"), "{html}");
let html = drawn(vec![review("changes_requested", 3, true)], false);
assert!(html.contains("tone-quiet"), "{html}");
assert!(html.contains(">3 line comments</span>"), "{html}");
}
/// The break this catches: a long comment drawn whole, or a short one folded behind a button.
#[test]
fn a_long_comment_folds() {
let long = (1..=8).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
let html = drawn(vec![said("jo", false, false, &long)], false);
assert!(html.contains("tone-person folded"), "{html}");
assert!(html.contains("<button type=\"button\" class=\"gh-unfold\">… Show all</button>"));
let short = (1..=7).map(|n| format!("line {n}\n")).collect::<String>();
let html = drawn(vec![said("jo", false, false, &short)], false);
assert!(!html.contains("folded") && !html.contains("gh-unfold"), "{html}");
}
/// The break this catches: an open thread not in the info tone, its place or reply count wrong,
/// its last word missing while folded, or a reply left out once it's opened.
#[test]
fn an_open_thread_shows_its_last_word() {
let said = [("mara", "Why\nthis?"), ("jo", "Because.")];
let html = drawn(vec![thread("src/api/v1/hook.rs", false, false, &said)], false);
assert!(html.contains("<details class=\"gh-card gh-thread tone-unresolved\">"), "{html}");
assert!(html.contains("<span class=\"hue-secondary\">@mara</span>"), "{html}");
assert!(html.contains("<span class=\"dim\"> \u{b7} </span>\u{2026}/v1/hook.rs:42"), "{html}");
assert!(html.contains("<span class=\"hue-info\">unresolved</span>"), "{html}");
assert!(html.contains(">1 reply</span>"), "{html}");
let last = "<span class=\"gh-last\"><span class=\"hue-muted\">@jo: </span>Because.</span>";
assert!(html.contains(last), "{html}");
assert!(html.contains("<md>R:Why\nthis?</md>"), "{html}");
}
/// The break this catches: a settled thread still toned as open, or a short path cut.
#[test]
fn a_settled_thread_is_quiet() {
let said = [("mara", "Fixed.")];
let html = drawn(vec![thread("crates/x/hook.rs", true, false, &said)], false);
assert!(html.contains("tone-person"), "{html}");
assert!(html.contains("</span>crates/x/hook.rs:42"), "{html}");
assert!(html.contains("<span class=\"dim\">resolved</span>"), "{html}");
assert!(!html.contains(" reply<"), "{html}");
let html = drawn(vec![thread("src/hook.rs", false, true, &said)], false);
assert!(html.contains("<span class=\"dim\">outdated</span>"), "{html}");
assert!(html.contains("tone-person"), "{html}");
}

View File

@@ -0,0 +1,146 @@
use super::an_hour_after;
use crate::render::github::list;
use luxe_core::github::{rfc3339_seconds, ListedSection};
use serde_json::{json, Value};
/// A `github_listed` item, copied from a live session's "Pull requests" section.
const ITEM: &str = r#"{"pull_request": true, "number": 211, "title": "chore: refresh the embedded models.dev snapshot", "url": "https://github.com/nora-quinn/luxe-dev/pull/211", "repository": "nora-quinn/luxe-dev", "author": "github-actions", "draft": false, "updated_at": "2026-10-19T12:25:08Z", "state": "open", "facts": {"author_bot": true, "additions": 2, "deletions": 2, "checks": {"passed": 0, "failed": 0, "pending": 0, "skipped": 0}, "review_decision": null, "comments": 0, "labels": [], "linked_pull_request": null}}"#;
const HERE: Option<&str> = Some("nora-quinn/luxe-dev");
fn item() -> Value {
serde_json::from_str(ITEM).expect("a listed item as core sends it")
}
fn section(items: Vec<Value>, total: Option<u64>) -> ListedSection {
let section = json!({"name": "Pull requests", "items": items, "error": null, "total": total});
serde_json::from_value(section).expect("a listed section as core sends it")
}
/// When `ITEM` last changed.
fn changed() -> u64 {
rfc3339_seconds("2026-10-19T12:25:08Z").expect("the item's time reads")
}
/// One section holding `item`, drawn an hour after it changed.
fn drawn(item: Value) -> String {
list(&an_hour_after(changed()), HERE, &section(vec![item], Some(1)))
}
/// The break this catches: a row the app can't open (number, kind or link missing), the mark in
/// the wrong state color, a bot named as a person, the age keeping its "ago", or the diff counts
/// dropped from line two.
#[test]
fn a_pull_request_row_reads_as_the_tuis() {
let html = drawn(item());
assert!(html.contains("data-number=\"211\" data-pull=\"true\""), "{html}");
assert!(html.contains("data-url=\"https://github.com/nora-quinn/luxe-dev/pull/211\""));
assert!(html.contains("<span class=\"gh-mark hue-success\">PR</span>"), "{html}");
assert!(html.contains("<span class=\"dim\">#211 </span>"), "{html}");
assert!(html.contains("refresh the embedded models.dev snapshot"), "{html}");
let bot = "<span class=\"hue-muted\">github-actions</span><span class=\"dim\"> bot</span>";
assert!(html.contains(bot), "{html}");
assert!(html.contains("<span class=\"gh-right dim\">3600s</span>"), "{html}");
assert!(html.contains("<span class=\"add\">+2</span>"), "{html}");
assert!(!html.contains(">open<"), "an open pull request doesn't say so: {html}");
}
/// The break this catches: the checks or the review left out of line two, or their marks crossed.
#[test]
fn a_pull_request_row_says_where_it_stands() {
let mut failing = item();
failing["facts"]["checks"] = json!({"passed": 3, "failed": 1, "pending": 2, "skipped": 0});
failing["facts"]["review_decision"] = json!("changes_requested");
let html = drawn(failing);
assert!(html.contains("<span class=\"hue-error\">N 1 failing</span>"), "{html}");
assert!(html.contains("<span class=\"hue-error\">changes requested</span>"), "{html}");
let mut running = item();
running["facts"]["checks"] = json!({"passed": 3, "failed": 0, "pending": 2, "skipped": 0});
running["facts"]["review_decision"] = json!("approved");
let html = drawn(running);
assert!(html.contains("<span class=\"hue-warning\">W running</span>"), "{html}");
assert!(html.contains("<span class=\"hue-success\">approved</span>"), "{html}");
let mut passed = item();
passed["facts"]["checks"] = json!({"passed": 3, "failed": 0, "pending": 0, "skipped": 0});
assert!(drawn(passed).contains("<span class=\"hue-success\">Y checks</span>"));
}
/// The break this catches: a draft or a merged pull request that doesn't say so, or its mark in
/// the open color.
#[test]
fn a_row_names_any_state_but_open() {
let mut draft = item();
draft["draft"] = json!(true);
let html = drawn(draft);
assert!(html.contains("<span class=\"gh-mark hue-muted\">PR</span>"), "{html}");
assert!(html.contains("<span class=\"hue-muted\">draft</span>"), "{html}");
let mut merged = item();
merged["state"] = json!("merged");
assert!(drawn(merged).contains("<span class=\"hue-secondary\">merged</span>"));
}
/// The break this catches: an issue drawn with a pull request's mark or diff counts, its labels
/// left out, or the pull request on it not named.
#[test]
fn an_issue_row_shows_its_labels_and_its_pull_request() {
let mut issue = item();
issue["pull_request"] = json!(false);
issue["facts"]["labels"] = json!([{"name": "bug", "color": "d73a4a"}]);
issue["facts"]["linked_pull_request"] = json!(9);
let html = drawn(issue.clone());
assert!(html.contains("data-pull=\"false\""), "{html}");
assert!(html.contains(">IS</span>"), "{html}");
assert!(html.contains("<span class=\"hue-muted\">bug</span>"), "{html}");
assert!(html.contains("<span class=\"hue-warning\">W PR #9</span>"), "{html}");
assert!(!html.contains("class=\"add\""), "an issue has no diff: {html}");
issue["facts"]["linked_pull_request"] = json!(null);
issue["facts"]["comments"] = json!(1);
assert!(drawn(issue).contains("<span class=\"hue-muted\">1 comment</span>"));
}
/// The break this catches: a row from another repository that doesn't say which, or one from
/// this checkout that names it anyway.
#[test]
fn a_row_names_its_repository_only_when_it_is_elsewhere() {
let one = section(vec![item()], Some(1));
let here = list(&an_hour_after(changed()), HERE, &one);
assert!(!here.contains("<span class=\"hue-muted\">nora-quinn/luxe-dev</span>"), "{here}");
let elsewhere = list(&an_hour_after(changed()), Some("someone/else"), &one);
let named = "<span class=\"hue-muted\">nora-quinn/luxe-dev</span>";
assert!(elsewhere.contains(named), "{elsewhere}");
}
/// The break this catches: a count that hides how many more GitHub has, says "of" when there
/// are no more, or runs a big number together.
#[test]
fn the_count_says_how_many_of_how_many() {
let cx = an_hour_after(0);
let count = |total| list(&cx, HERE, &section(vec![item()], total));
assert!(count(Some(3250)).contains(">1 of 3,250</p>"), "{}", count(Some(3250)));
assert!(count(Some(120_000)).contains(">1 of 120,000</p>"), "{}", count(Some(120_000)));
assert!(count(Some(1)).contains(">1 shown</p>"), "{}", count(Some(1)));
assert!(count(None).contains(">1 shown</p>"), "{}", count(None));
}
/// The break this catches: an empty tab drawn as a blank, or a failed search's reason lost or
/// let through unescaped.
#[test]
fn an_empty_or_failed_tab_says_so() {
let cx = an_hour_after(0);
let empty = list(&cx, HERE, &section(Vec::new(), Some(0)));
assert_eq!(empty, "<p class=\"gh-note dim\">Nothing matches this search</p>");
let mut failed = section(Vec::new(), None);
failed.error = Some("gh <auth> failed".into());
let html = list(&cx, HERE, &failed);
assert_eq!(html, "<p class=\"gh-note hue-error\">gh &lt;auth&gt; failed</p>");
}
/// The break this catches: a stranger's title reaching the page as markup.
#[test]
fn a_title_is_escaped() {
let mut hostile = item();
hostile["title"] = json!("<img src=x onerror=alert(1)>");
let html = drawn(hostile);
assert!(html.contains("&lt;img"), "{html}");
assert!(!html.contains("<img"), "{html}");
}

View File

@@ -0,0 +1,171 @@
use super::an_hour_after;
use crate::render::github::{header, overview};
use luxe_core::github::overview::Overview;
use serde_json::{json, Value};
/// A `github_overview_read` frame's overview, copied from a live session, its long dependabot
/// body cut to its first line.
const PULL_REQUEST: &str = r#"{"kind": "pull_request", "overview": {"number": 235, "node_id": "PR_kwDOTyoMn88AAAABHrSs7g", "title": "ci: bump the actions group across 1 directory with 2 updates", "body": "Bumps the actions group with 2 updates.", "url": "https://github.com/nora-quinn/luxe-dev/pull/235", "repository": "nora-quinn/luxe-dev", "author": {"login": "dependabot", "bot": true}, "state": "open", "draft": false, "base_ref": "master", "head_ref": "dependabot/github_actions/actions-9d10962cbb", "head_oid": "60e64cfa2f3a722e189a82e06dc3be3808b548a5", "cross_repository": false, "additions": 8, "deletions": 8, "changed_files": 4, "commits": 1, "updated_at": 1792259399, "labels": [{"name": "dependencies", "color": "0366d6"}, {"name": "github_actions", "color": "000000"}], "merge_status": "unknown", "review_decision": null, "reviewers": [], "checks": {"passed": 8, "failed": 0, "pending": 0, "skipped": 0}, "failing": [], "unresolved_threads": 0, "stack": null, "viewer": {"author": false, "can_push": true, "can_merge": true}, "merge_methods": ["merge", "squash", "rebase"], "merge_settings": {"last_method": "merge", "deletes_branch": false, "can_auto_merge": false, "can_cancel_auto_merge": false, "auto_merge": null}, "conversation_count": 1}}"#;
/// An issue's overview in core's shape; the repository the session ran in has no issues to copy.
const ISSUE: &str = r#"{"kind": "issue", "overview": {"number": 41, "title": "Crash on start", "body": "It crashes.", "url": "https://github.com/o/r/issues/41", "repository": "o/r", "author": {"login": "mara", "bot": false}, "state": "open", "updated_at": 1792259399, "labels": [], "assignees": [], "milestone": null, "linked": [], "conversation_count": 0}}"#;
const CHANGED: u64 = 1_792_259_399;
fn value(json: &str) -> Value {
serde_json::from_str(json).expect("an overview as core sends it")
}
fn parsed(value: Value) -> Overview {
serde_json::from_value(value).expect("an overview as core sends it")
}
fn headed(value: Value) -> String {
header(&an_hour_after(CHANGED), &parsed(value))
}
fn sections(value: Value) -> String {
overview(&an_hour_after(CHANGED), &parsed(value))
}
/// The break this catches: the number, title, author, branches, size or age left out of the
/// header, a bot named as a person, or the state chip in the wrong color.
#[test]
fn a_pull_requests_header_reads_as_the_tuis() {
let html = headed(value(PULL_REQUEST));
assert!(html.contains("<span class=\"dim\">#235 </span>ci: bump the actions group"), "{html}");
let bot = "<span class=\"hue-muted\">dependabot</span><span class=\"dim\"> bot</span>";
assert!(html.contains(bot), "{html}");
let branches = "master <span class=\"hue-muted\">\u{2190}</span> dependabot/github_actions";
assert!(html.contains(branches), "{html}");
assert!(html.contains("<span class=\"add\">+8</span>"), "{html}");
assert!(html.contains("in 4 files</span>"), "{html}");
assert!(html.contains("<span class=\"dim\">3600s ago</span>"), "{html}");
assert!(html.contains("<span class=\"gh-state hue-success\">open</span>"), "{html}");
assert!(html.contains("\u{25cf}</span> dependencies</span>"), "{html}");
}
/// The break this catches: "1 files", or a header that shows every label however many there are.
#[test]
fn the_header_counts_one_file_and_caps_its_labels() {
let mut pull_request = value(PULL_REQUEST);
pull_request["overview"]["changed_files"] = json!(1);
let labels: Vec<Value> =
(1..=5).map(|n| json!({"name": format!("l{n}"), "color": "000000"})).collect();
pull_request["overview"]["labels"] = json!(labels);
let html = headed(pull_request);
assert!(html.contains("in 1 file</span>"), "{html}");
assert!(html.contains("> l4</span>"), "{html}");
assert!(!html.contains("> l5</span>"), "{html}");
}
/// The break this catches: an issue's header drawn with a pull request's branches, or its closed
/// state in the pull request's red.
#[test]
fn an_issues_header_has_no_branches() {
let mut issue = value(ISSUE);
issue["overview"]["state"] = json!("closed");
let html = headed(issue);
assert!(html.contains("<span class=\"dim\">#41 </span>Crash on start"), "{html}");
assert!(!html.contains('\u{2190}'), "{html}");
assert!(html.contains("<span class=\"gh-state hue-secondary\">closed</span>"), "{html}");
}
/// The break this catches: a blocker drawn with a passing mark or quiet, the count of what's
/// incomplete dropped, or the stack's "open #N" (the one action that only reads) missing.
#[test]
fn the_status_marks_what_blocks_a_merge() {
let mut draft = value(PULL_REQUEST);
draft["overview"]["draft"] = json!(true);
draft["overview"]["stack"] = json!({"trunk": "master", "trunk_is_default": true, "above": [],
"below": [{"number": 230, "title": "base", "head_ref": "base", "draft": false, "checked": true}]});
let html = sections(draft);
assert!(
html.contains("<h3 class=\"gh-section\">Status<span class=\"gh-right dim\">"),
"{html}"
);
assert!(html.contains("incomplete</span></h3>"), "{html}");
let blocker = "<span class=\"gh-mark hue-error\">N</span><span class=\"gh-label\">Draft</span>\
<span class=\"gh-evidence\"><span class=\"\">still a draft</span>";
assert!(html.contains(blocker), "{html}");
let open = "<button type=\"button\" class=\"gh-open\" data-number=\"230\" data-pull=\"true\">\
open #230</button>";
assert!(html.contains(open), "{html}");
}
/// The break this catches: a passing check drawn as a blocker, or "0 incomplete" on a pull
/// request with nothing left to do.
#[test]
fn a_passing_check_is_quiet() {
let mut ready = value(PULL_REQUEST);
ready["overview"]["merge_status"] = json!("clean");
let html = sections(ready);
assert!(html
.contains("<span class=\"gh-mark hue-success\">Y</span><span class=\"gh-label\">Checks"));
assert!(html.contains("<span class=\"hue-muted\">"), "{html}");
assert!(!html.contains("incomplete"), "{html}");
}
/// The break this catches: the approval count wrong, a verdict in the wrong color, a team not
/// named as one, or a Reviewers heading over nobody.
#[test]
fn reviewers_say_what_they_said() {
let mut reviewed = value(PULL_REQUEST);
reviewed["overview"]["reviewers"] = json!([
{"login": "mara", "kind": "user", "verdict": "approved", "at": CHANGED},
{"login": "core", "kind": "team", "verdict": "changes_requested", "at": null}
]);
let html = sections(reviewed);
assert!(html.contains(">1 of 2 approved</span></h3>"), "{html}");
assert!(html.contains("<span class=\"gh-label\">mara</span>"), "{html}");
assert!(html.contains("<span class=\"hue-success\">approved</span>"), "{html}");
assert!(html.contains("\u{b7} 3600s ago"), "{html}");
assert!(html.contains(
"<span class=\"hue-error\">changes requested</span><span class=\"dim\"> \u{b7} team</span>"
));
assert!(!sections(value(PULL_REQUEST)).contains("Reviewers"));
}
/// The break this catches: the excerpt quoting more or fewer than five lines that say something,
/// a blank line spending one of the five, the count of the rest wrong, or a body rendered without
/// its HTML made readable first.
#[test]
fn the_description_quotes_five_lines() {
let body = |text: &str| {
let mut pull_request = value(PULL_REQUEST);
pull_request["overview"]["body"] = json!(text);
sections(pull_request)
};
let long = body("one\n\ntwo\nthree\nfour\nfive\nsix\nseven");
assert!(long.contains("<md>R:one\n\ntwo\nthree\nfour\nfive\n</md>"), "{long}");
let more = "data-tab=\"conversation\">… 2 more lines in Conversation</button>";
assert!(long.contains(more), "{long}");
let short = body("one\ntwo\nthree\nfour\nfive");
assert!(short.contains("five\n</md>") && !short.contains("gh-more"), "{short}");
assert!(body(" ").contains("<p class=\"gh-note dim\">No description</p>"));
}
/// The break this catches: an issue's assignees, closing pull requests or milestone left out,
/// a pull request that only mentions the issue listed as closing it, or nothing said when nobody
/// is on it.
#[test]
fn an_issue_says_who_is_on_it() {
let html = sections(value(ISSUE));
assert!(html.contains("<span class=\"hue-muted\">unassigned</span>"), "{html}");
assert!(html.contains("<span class=\"hue-muted\">none yet</span>"), "{html}");
assert!(!html.contains("Milestone"), "{html}");
let mut staffed = value(ISSUE);
staffed["overview"]["assignees"] = json!(["mara", "jo"]);
staffed["overview"]["milestone"] = json!("v1");
staffed["overview"]["linked"] = json!([
{"number": 7, "title": "Fix", "state": "open", "draft": false, "author": "jo", "closes": true},
{"number": 8, "title": "See", "state": "open", "draft": false, "author": "jo", "closes": false}
]);
let html = sections(staffed);
assert!(html.contains("<span class=\"hue-secondary\">mara, jo</span>"), "{html}");
assert!(html.contains("data-number=\"7\" data-pull=\"true\">#7</button>"), "{html}");
assert!(!html.contains("data-number=\"8\""), "{html}");
assert!(
html.contains("<span class=\"gh-label\">Milestone</span><span class=\"gh-evidence\">v1")
);
}

View File

@@ -0,0 +1,314 @@
//! Review — the open Guided Review as the app shows it: the guide, then one chapter at a time.
//!
//! The guide is the TUI's guide pane as a page: the brief, then each chapter's number, kind and
//! title, with either its rationale and files or the one line saying nothing in it needs the
//! reader. That call is the host's (`open_review_shown`'s reading), since it's decided from lines
//! the app doesn't send back. A chapter is its items in order, grouped under the file they're in,
//! each with the guide's sentence for it above its diff, as the TUI's narration band puts it.
use super::{diff, escape, Renderer, Voice};
use luxe_core::guided_review::{
ChapterId, ChapterKind, ChapterReading, GuidedReview, ReviewChapter, ReviewFile,
ReviewFileStatus, ReviewFinding, ReviewItemRef,
};
use std::collections::HashMap;
mod findings;
/// File rows a chapter lists in the guide before the rest are counted, as the TUI windows them.
const FILE_ROWS: usize = 8;
/// The whole guide: the brief, then every chapter.
pub(super) fn guide(
renderer: &dyn Renderer,
review: &GuidedReview,
reading: &[ChapterReading],
walked: &[ChapterId],
) -> String {
let owners = Owners::of(&review.files);
let total = review.chapters.len();
let chapters: String = review
.chapters
.iter()
.enumerate()
.map(|(index, chapter)| {
let place = Place { number: index + 1, total, walked: walked.contains(&chapter.id) };
let reading = reading.iter().find(|it| it.chapter_id == chapter.id);
guide_chapter(renderer, chapter, &place, reading, &owners.files_of(chapter))
})
.collect();
format!("<div class=\"rv-guide\">{}{chapters}</div>", brief(renderer, review))
}
/// One chapter opened: its heading, then its items with their notes and diffs.
pub(super) fn chapter(
renderer: &dyn Renderer,
chapter: &ReviewChapter,
files: &[ReviewFile],
place: &Place,
reading: Option<&ChapterReading>,
findings: &[ReviewFinding],
) -> String {
let mut out = format!("<header class=\"rv-head\">{}", heading(chapter, place, reading));
out.push_str(&prose(renderer, chapter, reading));
out.push_str("</header>");
out.push_str(&findings::on_chapter(renderer, findings, &chapter.id));
out.push_str(&items_html(renderer, chapter, files, findings));
format!("<div class=\"rv-chapter-view\">{out}</div>")
}
/// A chapter's items in its order, with a file's path said once above the run of items in it and
/// the comments on a hunk under it.
fn items_html(
renderer: &dyn Renderer,
chapter: &ReviewChapter,
files: &[ReviewFile],
findings: &[ReviewFinding],
) -> String {
let mut out = String::new();
let mut current: Option<&str> = None;
for item in &chapter.items {
let Some((file, hunk)) = locate(files, item) else { continue };
if current != Some(file.id.as_str()) {
current = Some(file.id.as_str());
out.push_str(&format!("<p class=\"rv-file\">{}</p>", escape(&path_of(file))));
}
out.push_str(&item_html(renderer, chapter, file, hunk));
let comments = hunk.map(|hunk| findings::on_hunk(renderer, findings, &hunk.id));
out.push_str(&comments.unwrap_or_default());
}
out
}
/// Where a chapter sits: `number` of `total`, and whether the reader has walked it.
#[derive(Debug, Clone, Copy, serde::Deserialize)]
pub(crate) struct Place {
pub(crate) number: usize,
pub(crate) total: usize,
#[serde(default)]
pub(crate) walked: bool,
}
/// The guide's opening: the summary's intent and claims, or the agent's own words when no summary
/// was written.
fn brief(renderer: &dyn Renderer, review: &GuidedReview) -> String {
let words = match review.brief.as_ref() {
Some(brief) => {
let claims: String =
brief.account.iter().map(|claim| bullet(renderer, claim)).collect();
let claims = if claims.is_empty() { claims } else { format!("<ul>{claims}</ul>") };
renderer.markdown(&brief.intent, Voice::Answer) + &claims
}
None => agents_words(renderer, review),
};
if words.is_empty() {
return String::new();
}
format!("<section class=\"rv-brief md\">{words}</section>")
}
fn bullet(renderer: &dyn Renderer, claim: &str) -> String {
format!("<li>{}</li>", renderer.markdown(claim, Voice::Answer))
}
/// What the turn was asked and what it said it did, with the TUI's line saying so.
fn agents_words(renderer: &dyn Renderer, review: &GuidedReview) -> String {
let Some(provenance) = review.provenance.as_ref() else {
return String::new();
};
let mut out: String =
provenance.requests.iter().map(|it| renderer.markdown(it, Voice::Answer)).collect();
if let Some(account) = provenance.account.as_deref() {
out.push_str(&renderer.markdown(account, Voice::Answer));
out.push_str(
"<p class=\"rv-dim\">the agent\u{2019}s own words \u{2014} no summary was written for \
this review</p>",
);
}
out
}
fn guide_chapter(
renderer: &dyn Renderer,
chapter: &ReviewChapter,
place: &Place,
reading: Option<&ChapterReading>,
files: &[&ReviewFile],
) -> String {
let quiet = if needs_nothing(reading) { " quiet" } else { "" };
let rows = if needs_nothing(reading) { String::new() } else { file_rows(files) };
format!(
"<section class=\"rv-chapter{quiet}\" data-chapter=\"{}\">{}{}{rows}</section>",
escape(chapter.id.as_str()),
heading(chapter, place, reading),
prose(renderer, chapter, reading),
)
}
/// `01 / 05 CORE reviewed`, then the title, which opens the chapter.
fn heading(chapter: &ReviewChapter, place: &Place, reading: Option<&ChapterReading>) -> String {
let walked = if place.walked { "<span class=\"rv-walked\">reviewed</span>" } else { "" };
let quiet = if needs_nothing(reading) { " quiet" } else { "" };
format!(
"<p class=\"rv-meta\"><span>{:02} / {:02}</span><span>{}</span>{walked}</p>\
<button type=\"button\" class=\"rv-title{quiet}\" data-chapter=\"{}\">{}</button>",
place.number,
place.total,
kind_label(chapter.kind),
escape(chapter.id.as_str()),
escape(&chapter.title),
)
}
/// The rationale and impact, or the one line that says why there's nothing to read.
fn prose(
renderer: &dyn Renderer,
chapter: &ReviewChapter,
reading: Option<&ChapterReading>,
) -> String {
if needs_nothing(reading) {
let reason = reading.and_then(|it| it.reason.as_deref());
let words = reason.map_or_else(
|| "nothing here needs you".to_owned(),
|reason| format!("{reason} \u{2014} nothing here needs you"),
);
return format!("<p class=\"rv-reason\">{}</p>", escape(&words));
}
let rationale = renderer.markdown(&chapter.rationale, Voice::Answer);
let impact = chapter.impact.as_deref().map(|impact| {
format!("<div class=\"rv-impact\">{}</div>", renderer.markdown(impact, Voice::Answer))
});
format!("<div class=\"rv-prose md\">{rationale}{}</div>", impact.unwrap_or_default())
}
/// A chapter the host found nothing in for the reader. No reading means the host didn't say, and
/// that's not the same as nothing.
fn needs_nothing(reading: Option<&ChapterReading>) -> bool {
reading.is_some_and(|reading| reading.needs_review == 0)
}
fn kind_label(kind: ChapterKind) -> &'static str {
match kind {
ChapterKind::Core => "CORE",
ChapterKind::Consequence => "CONSEQUENCE",
ChapterKind::Test => "TESTS",
ChapterKind::Supporting => "SUPPORTING",
ChapterKind::Generated => "GENERATED",
}
}
fn file_rows(files: &[&ReviewFile]) -> String {
let rows: String = files.iter().take(FILE_ROWS).map(|file| file_row(file)).collect();
let more = files.len().saturating_sub(FILE_ROWS);
let more = if more > 0 {
format!("<li class=\"rv-more\">\u{2026} {more} more</li>")
} else {
String::new()
};
format!("<ul class=\"rv-files\">{rows}{more}</ul>")
}
/// `M path +12 −3`, or what the change was for a file with no lines to count.
fn file_row(file: &ReviewFile) -> String {
let (letter, tone) = status(file.status);
let change = match (file.non_text.as_ref(), file.additions, file.deletions) {
(Some(change), _, _) => format!("<span class=\"rv-dim\">{}</span>", escape(&change.summary)),
(None, Some(added), Some(deleted)) => format!(
"<span class=\"rv-added\">+{added}</span><span class=\"rv-deleted\">\u{2212}{deleted}</span>"
),
_ => String::new(),
};
format!(
"<li><span class=\"rv-status {tone}\">{letter}</span><span class=\"rv-path\">{}</span>\
{change}</li>",
escape(&path_of(file))
)
}
fn status(status: ReviewFileStatus) -> (&'static str, &'static str) {
match status {
ReviewFileStatus::Added => ("A", "tone-added"),
ReviewFileStatus::Untracked => ("?", "tone-added"),
ReviewFileStatus::Modified => ("M", "tone-modified"),
ReviewFileStatus::Deleted => ("D", "tone-deleted"),
ReviewFileStatus::Renamed => ("R", "tone-moved"),
ReviewFileStatus::Copied => ("C", "tone-moved"),
}
}
/// One item: the hunk's symbol and the guide's sentence for it, then its lines.
fn item_html(
renderer: &dyn Renderer,
chapter: &ReviewChapter,
file: &ReviewFile,
hunk: Option<&luxe_core::guided_review::ReviewHunk>,
) -> String {
let Some(hunk) = hunk else {
let note = chapter.note_for(&ReviewItemRef::File(file.id.clone()));
return note_html(note) + &diff::whole(renderer, file);
};
let symbol = hunk.symbol.as_ref().and_then(|symbol| symbol.name.as_deref());
let symbol = symbol.map(|it| format!("<p class=\"rv-symbol\">{}</p>", escape(it)));
let note = note_html(chapter.note_for_hunk(&hunk.id));
let lines = diff::hunk_html(renderer, file, hunk);
format!("{}{note}{}{lines}</div>", symbol.unwrap_or_default(), diff::opening(file))
}
fn note_html(note: Option<&str>) -> String {
note.map(|note| format!("<p class=\"rv-note\">{}</p>", escape(note))).unwrap_or_default()
}
/// The file an item is in and, for a hunk, the hunk; `None` when the app didn't send it.
fn locate<'a>(
files: &'a [ReviewFile],
item: &ReviewItemRef,
) -> Option<(&'a ReviewFile, Option<&'a luxe_core::guided_review::ReviewHunk>)> {
match item {
ReviewItemRef::File(id) => files.iter().find(|file| &file.id == id).map(|it| (it, None)),
ReviewItemRef::Hunk(id) => files.iter().find_map(|file| {
file.hunks.iter().find(|hunk| &hunk.id == id).map(|hunk| (file, Some(hunk)))
}),
}
}
fn path_of(file: &ReviewFile) -> String {
let path = file.new_path.as_deref().or(file.old_path.as_deref());
path.map_or_else(|| "(unknown path)".to_owned(), |path| path.display().to_string())
}
/// Which file holds each id a chapter can name, built once per guide rather than scanned per item.
struct Owners<'a> {
by_id: HashMap<&'a str, &'a ReviewFile>,
}
impl<'a> Owners<'a> {
fn of(files: &'a [ReviewFile]) -> Self {
let mut by_id = HashMap::new();
for file in files {
by_id.insert(file.id.as_str(), file);
for hunk in &file.hunks {
by_id.insert(hunk.id.as_str(), file);
}
}
Self { by_id }
}
/// A chapter's files in the order it names them, each once.
fn files_of(&self, chapter: &ReviewChapter) -> Vec<&'a ReviewFile> {
let mut files: Vec<&ReviewFile> = Vec::new();
for item in &chapter.items {
let id = match item {
ReviewItemRef::File(id) => id.as_str(),
ReviewItemRef::Hunk(id) => id.as_str(),
};
let Some(file) = self.by_id.get(id) else { continue };
if !files.iter().any(|seen| seen.id == file.id) {
files.push(file);
}
}
files
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,151 @@
//! Findings — the reader's comments, as cards under the hunk or chapter they're about.
//!
//! Each card is the TUI's: its label, what kind of comment it is and where it stands in the TUI's
//! words, the comment, then the thread that followed. The phone has no thread window, so the whole
//! thread is on the card. The buttons carry `data-act` for the app to send the edit; which ones a
//! card has follows what the review desk accepts in that state.
use super::super::{escape, Renderer, Voice};
use luxe_core::guided_review::{
ChapterId, DiffSide, FindingAnchor, FindingMessageAuthor, FindingSeverity, FindingState,
HunkId, ReviewFinding,
};
/// Cards for the comments on lines of `hunk`, or on the hunk itself.
pub(super) fn on_hunk(
renderer: &dyn Renderer,
findings: &[ReviewFinding],
hunk: &HunkId,
) -> String {
let on = |finding: &&ReviewFinding| match &finding.anchor {
FindingAnchor::Line { hunk_id, .. } | FindingAnchor::Hunk { hunk_id, .. } => {
hunk_id == hunk
}
_ => false,
};
findings.iter().filter(on).map(|finding| card(renderer, finding)).collect()
}
/// Cards for the comments on the chapter as a whole.
pub(super) fn on_chapter(
renderer: &dyn Renderer,
findings: &[ReviewFinding],
chapter: &ChapterId,
) -> String {
let on = |finding: &&ReviewFinding| matches!(&finding.anchor, FindingAnchor::Chapter { chapter_id } if chapter_id == chapter);
findings.iter().filter(on).map(|finding| card(renderer, finding)).collect()
}
fn card(renderer: &dyn Renderer, finding: &ReviewFinding) -> String {
let (state, tone) = state_words(finding);
format!(
"<article class=\"rv-finding rv-tone-{tone}\" data-finding=\"{}\"><p class=\"rv-finding-head\">\
<span class=\"rv-label\">{}</span><span>{}</span><span class=\"rv-state\">{state}</span>{}\
</p><div class=\"rv-finding-body md\">{}</div>{}{}</article>",
escape(finding.id.as_str()),
escape(&finding.label),
kind(finding),
place(&finding.anchor),
renderer.markdown(&finding.body, Voice::Answer),
thread(renderer, finding),
actions(finding),
)
}
/// What kind of comment it is, as the TUI's comment window heads it.
fn kind(finding: &ReviewFinding) -> &'static str {
match finding.severity {
FindingSeverity::Question => "question",
_ if finding.github_thread.is_some() => "reviewer comment",
_ => "comment",
}
}
/// The line a line comment is on; the old side says so, since its number isn't the file's now.
fn place(anchor: &FindingAnchor) -> String {
match anchor {
FindingAnchor::Line { side: DiffSide::Old, line, .. } => {
format!("<span>removed line {line}</span>")
}
FindingAnchor::Line { line, .. } => format!("<span>line {line}</span>"),
_ => String::new(),
}
}
/// Where it stands, in the TUI's words without its key hints, and the tone it's drawn in.
fn state_words(finding: &ReviewFinding) -> (&'static str, &'static str) {
let last = finding.thread.last().map(|message| message.author);
let question = finding.severity == FindingSeverity::Question;
match finding.state {
FindingState::Draft | FindingState::Open if finding.posted.is_some() => {
("on GitHub", "dim")
}
FindingState::Draft => ("unsent", "warning"),
FindingState::Open if question && last == Some(FindingMessageAuthor::Agent) => {
("answered", "success")
}
FindingState::Open if last == Some(FindingMessageAuthor::System) => {
("no word from the agent", "warning")
}
FindingState::Open if last == Some(FindingMessageAuthor::Agent) => {
("the agent replied", "info")
}
FindingState::Open => ("sent \u{00b7} waiting on the agent", "dim"),
FindingState::NeedsVerification => ("to verify", "info"),
FindingState::Resolved => ("verified", "success"),
FindingState::Stale => ("the code moved", "dim"),
}
}
/// Every word after the comment, each said by who said it. The reader's opening message is the
/// comment itself, so it isn't said twice.
fn thread(renderer: &dyn Renderer, finding: &ReviewFinding) -> String {
let said: String = finding
.thread
.iter()
.skip_while(|message| {
message.author == FindingMessageAuthor::Reviewer && message.body == finding.body
})
.map(|message| {
let who = match message.author {
FindingMessageAuthor::Reviewer => "you",
FindingMessageAuthor::Agent => "agent",
FindingMessageAuthor::System => "luxe",
};
let words = renderer.markdown(&message.body, Voice::Answer);
format!("<div class=\"rv-said\"><p class=\"rv-who\">{who}</p><div class=\"md\">{words}</div></div>")
})
.collect();
said
}
/// The edits the review desk takes in this state: a draft is sent or deleted, an open comment
/// answered or resolved, a resolved one reopened. A moved one is the TUI's to re-anchor.
fn acts(finding: &ReviewFinding) -> &'static [(&'static str, &'static str)] {
match finding.state {
_ if finding.posted.is_some() => &[],
FindingState::Draft => &[("send", "Send"), ("delete", "Delete")],
FindingState::Open | FindingState::NeedsVerification => {
&[("reply", "Reply"), ("resolve", "Resolve")]
}
FindingState::Resolved => &[("reopen", "Reopen")],
FindingState::Stale => &[],
}
}
fn actions(finding: &ReviewFinding) -> String {
let acts = acts(finding);
if acts.is_empty() {
return String::new();
}
let buttons: String = acts
.iter()
.map(|(act, words)| {
format!("<button type=\"button\" class=\"mention\" data-act=\"{act}\">{words}</button>")
})
.collect();
format!("<p class=\"rv-finding-acts\">{buttons}</p>")
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1 @@
{"review":{"id":"review:d99c1f45-e9f9-44e2-8e34-d5d28da37eb7","revision_id":"revision:2725a9262f2a20b9384fd34815f4c078d000aa46532d273ec949648d8fc35ca0","target":{"kind":"working_tree"},"source":{"base":{"kind":"head","oid":"a259681d8fab17fc77922c7fd5646eb60ab91a29"},"content_digest":"revision:2725a9262f2a20b9384fd34815f4c078d000aa46532d273ec949648d8fc35ca0","includes_staged":false,"includes_unstaged":true,"included_untracked_files":0,"captured_at_ms":1792442788572},"context":{"title":"Guided Review","goal":null,"phase_index":null,"phase_title":null,"planning_excerpt":null,"acceptance_excerpt":null,"source_intent":null,"source_commits":0},"files":[{"id":"file:f8c40bfe747fc99f88dd0ab57dc05fce0c80c39442da35d02395336d1c40a2f4","old_path":"config.rs","new_path":"config.rs","status":"modified","language":"rs","additions":3,"deletions":2,"hunks":[{"id":"hunk:4a6ae38e19f2513e9025942160970e253b6f89ca60b6c84880626b3c66c3f0cf","old_range":{"start":1,"count":2},"new_range":{"start":1,"count":3},"heading":null,"symbol":null,"lines":[{"old_line":1,"new_line":null,"kind":"deletion","text":"pub const PORT: u16 = 4000;"},{"old_line":2,"new_line":null,"kind":"deletion","text":"pub const HOST: &str = \"localhost\";"},{"old_line":null,"new_line":1,"kind":"addition","text":"pub const PORT: u16 = 4519;"},{"old_line":null,"new_line":2,"kind":"addition","text":"pub const HOST: &str = \"luxe.local\";"},{"old_line":null,"new_line":3,"kind":"addition","text":"pub const RETRIES: u32 = 2;"}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null}],"chapters":[{"id":"chapter:de5954563943cbdb6abfe21d1eda0812f1dbe9c7bebfa9f73bd8f479846e4ef7","title":"Core implementation","rationale":"Groups source-backed implementation changes.","impact":null,"kind":"core","items":[{"kind":"hunk","id":"hunk:4a6ae38e19f2513e9025942160970e253b6f89ca60b6c84880626b3c66c3f0cf"}],"notes":[]}],"checks":{"checks":[]},"stats":{"files":1,"hunks":1,"additions":3,"deletions":2,"binary_files":0,"non_text_files":0,"excluded_files":0},"generated_at_ms":1792442788572,"insight":null,"provenance":null,"seen":null,"brief":null},"findings":[{"id":"finding:06d4fc78-b794-463e-9e4d-55dfe9113425","label":"R1","anchor":{"kind":"line","file_id":"file:f8c40bfe747fc99f88dd0ab57dc05fce0c80c39442da35d02395336d1c40a2f4","hunk_id":"hunk:4a6ae38e19f2513e9025942160970e253b6f89ca60b6c84880626b3c66c3f0cf","side":"new","line":1,"context_hash":"sha256:6727922be2c161f00b05c06516fe62ac4247f363580a567aa1aa2edac94cf645"},"severity":"question","title":"Why 4519?","body":"Why 4519?","proposed_fix":null,"state":"draft","thread":[]},{"id":"finding:e862bf84-8257-44ad-b587-d22a95320bbc","label":"R2","anchor":{"kind":"chapter","chapter_id":"chapter:de5954563943cbdb6abfe21d1eda0812f1dbe9c7bebfa9f73bd8f479846e4ef7"},"severity":"issue","title":"Keep the old host as a fallback.","body":"Keep the old host as a fallback.","proposed_fix":null,"state":"draft","thread":[]}]}

View File

@@ -0,0 +1,190 @@
use super::super::{chapter, Place};
use super::{acts, state_words};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
use luxe_core::guided_review::{
FindingMessage, FindingMessageAuthor, FindingSeverity, FindingState, GuidedReview,
ReviewFinding,
};
/// Prose marked so a test can tell it went through the markdown hook.
struct Marked;
impl Renderer for Marked {
fn markdown(&self, text: &str, _voice: Voice) -> String {
format!("<p>md:{}</p>", escape(text))
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn code_line(&self, text: &str, _language: Option<&str>) -> String {
escape(text)
}
}
/// A real review of a scratch project and the two comments made on it over RPC: a question on its
/// first added line (R1) and an issue on its chapter (R2), both unsent.
fn captured() -> (GuidedReview, Vec<ReviewFinding>) {
#[derive(serde::Deserialize)]
struct Scratch {
review: GuidedReview,
findings: Vec<ReviewFinding>,
}
let scratch: Scratch =
serde_json::from_str(include_str!("scratch.json")).expect("the captured comments parse");
(scratch.review, scratch.findings)
}
fn open(review: &GuidedReview, findings: &[ReviewFinding]) -> String {
let place = Place { number: 1, total: 1, walked: false };
chapter(&Marked, &review.chapters[0], &review.files, &place, None, findings)
}
/// A line comment sits under its hunk, and a chapter comment above the chapter's first hunk.
///
/// The break this catches: comments dropped from the chapter, or drawn away from what they're
/// about, so the reader can't tell which line was asked about.
#[test]
fn comments_sit_under_what_they_are_about() {
let (review, findings) = captured();
let html = open(&review, &findings);
let hunk = html.find("<div class=\"hunk\">").expect("the hunk");
let r1 = html.find("data-finding=\"finding:06d4fc78").expect("the line comment");
let r2 = html.find(">R2<").expect("the chapter comment");
assert!(r2 < hunk && hunk < r1, "{html}");
}
/// A card says what it is, where it is and where it stands, then the comment through the
/// markdown hook, with the edits an unsent one takes.
///
/// The break this catches: a card missing its label, kind, line or state, the comment shown raw,
/// or an unsent comment that can't be sent or deleted from the phone.
#[test]
fn an_unsent_card_says_what_and_where_and_offers_send() {
let (review, findings) = captured();
let html = open(&review, &findings[..1]);
let head = "<span class=\"rv-label\">R1</span><span>question</span><span class=\"rv-state\">\
unsent</span><span>line 1</span>";
assert!(html.contains(head), "{html}");
assert!(html.contains("<div class=\"rv-finding-body md\"><p>md:Why 4519?</p></div>"));
assert!(html.contains("data-act=\"send\">Send</button>"));
assert!(html.contains("data-act=\"delete\">Delete</button>"));
assert!(html.contains("rv-finding rv-tone-warning"));
}
/// Comments on another hunk or chapter stay off this one.
///
/// The break this catches: every comment in the review piled onto whichever chapter is open.
#[test]
fn comments_elsewhere_stay_off_the_chapter() {
let (review, mut findings) = captured();
for finding in &mut findings {
let mut anchor = serde_json::to_value(&finding.anchor).expect("an anchor");
let field = if anchor.get("hunk_id").is_some() { "hunk_id" } else { "chapter_id" };
anchor[field] = serde_json::json!(format!("{field}:elsewhere"));
finding.anchor = serde_json::from_value(anchor).expect("an anchor elsewhere");
}
assert!(!open(&review, &findings).contains("rv-finding"));
}
/// A finding in `state`, its thread ending with a word from `last`.
fn finding(
state: FindingState,
severity: FindingSeverity,
last: Option<FindingMessageAuthor>,
) -> ReviewFinding {
let (_, mut findings) = captured();
let mut finding = findings.remove(0);
finding.state = state;
finding.severity = severity;
finding.thread = last.map(|author| said(author, "reply")).into_iter().collect();
finding
}
fn said(author: FindingMessageAuthor, body: &str) -> FindingMessage {
FindingMessage { author, body: body.into(), created_at_ms: 1 }
}
/// Where a sent comment stands, in the TUI's words.
///
/// The break this catches: the phone saying "waiting" when the agent has answered, or calling an
/// answer to a comment an answer to a question, which is what tells the reader to follow up.
#[test]
fn a_sent_comment_says_whether_the_agent_has_answered() {
use FindingMessageAuthor::{Agent, System};
use FindingSeverity::{Issue, Question};
let words = |state, severity, last| state_words(&finding(state, severity, last)).0;
assert_eq!(words(FindingState::Open, Question, Some(Agent)), "answered");
assert_eq!(words(FindingState::Open, Issue, Some(Agent)), "the agent replied");
assert_eq!(words(FindingState::Open, Issue, Some(System)), "no word from the agent");
assert_eq!(words(FindingState::Open, Issue, None), "sent \u{00b7} waiting on the agent");
assert_eq!(words(FindingState::NeedsVerification, Issue, None), "to verify");
assert_eq!(words(FindingState::Resolved, Issue, None), "verified");
assert_eq!(words(FindingState::Stale, Issue, None), "the code moved");
}
/// Each state offers only the edits the review desk takes in it.
///
/// The break this catches: Delete offered on a sent comment (refused), Reply on an unsent one, or
/// a button on a moved comment, whose re-anchoring is the TUI's.
#[test]
fn each_state_offers_the_edits_it_takes() {
let names = |state| -> Vec<&str> {
acts(&finding(state, FindingSeverity::Issue, None)).iter().map(|(act, _)| *act).collect()
};
assert_eq!(names(FindingState::Draft), ["send", "delete"]);
assert_eq!(names(FindingState::Open), ["reply", "resolve"]);
assert_eq!(names(FindingState::NeedsVerification), ["reply", "resolve"]);
assert_eq!(names(FindingState::Resolved), ["reopen"]);
assert!(names(FindingState::Stale).is_empty());
}
/// A comment posted to GitHub is GitHub's now: it says so and offers nothing.
///
/// The break this catches: Send offered on a comment already posted, which would post it twice.
#[test]
fn a_posted_comment_is_on_github() {
let mut posted = finding(FindingState::Draft, FindingSeverity::Issue, None);
posted.posted = serde_json::from_value(serde_json::json!({"review_id": 7, "url": "https://x"}))
.expect("a posted comment");
assert_eq!(state_words(&posted).0, "on GitHub");
assert!(acts(&posted).is_empty());
}
/// The thread follows the comment, each word by who said it, the reader's opening not repeated.
///
/// The break this catches: the agent's answer missing from the card (the phone has no thread
/// window), told as the reader's, or the comment said twice.
#[test]
fn the_thread_follows_the_comment_by_who_said_it() {
let (review, mut findings) = captured();
let body = findings[0].body.clone();
findings[0].state = FindingState::Open;
findings[0].thread = vec![
said(FindingMessageAuthor::Reviewer, &body),
said(FindingMessageAuthor::Agent, "It is the bridge port"),
said(FindingMessageAuthor::Reviewer, "Say so in a comment"),
];
let html = open(&review, &findings[..1]);
assert_eq!(html.matches("md:Why 4519?").count(), 1, "{html}");
let word = |who: &str, words: &str| {
html.find(&format!("<p class=\"rv-who\">{who}</p><div class=\"md\"><p>md:{words}"))
};
let (agent, you) = (word("agent", "It is the bridge port"), word("you", "Say so in a comment"));
assert!(agent.zip(you).is_some_and(|(agent, you)| agent < you), "{html}");
}
/// A comment on a removed line says so: its number is the old file's.
///
/// The break this catches: a removed line's comment saying "line 12" of a file whose line 12 is
/// something else now.
#[test]
fn a_comment_on_a_removed_line_says_removed() {
let (review, mut findings) = captured();
let mut anchor = serde_json::to_value(&findings[0].anchor).expect("an anchor");
anchor["side"] = serde_json::json!("old");
findings[0].anchor = serde_json::from_value(anchor).expect("an old-side anchor");
assert!(open(&review, &findings[..1]).contains("<span>removed line 1</span>"));
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,351 @@
use super::{chapter, guide, Place};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
use luxe_core::guided_review::{
ChapterReading, GuidedReview, ItemNote, ReviewBrief, ReviewFile, TurnProvenance,
};
/// Prose marked so a test can tell it went through the markdown hook, and code by language.
struct Marked;
impl Renderer for Marked {
fn markdown(&self, text: &str, _voice: Voice) -> String {
format!("<p>md:{}</p>", escape(text))
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn code_line(&self, text: &str, language: Option<&str>) -> String {
format!("[{}:{}]", language.unwrap_or("-"), escape(text))
}
}
/// A real `open_review_shown` (PR #230's review on this repository), cut to three items a
/// chapter with hunks of four lines, and with the planning notes and PR body blanked.
fn captured() -> (GuidedReview, Vec<ChapterReading>) {
#[derive(serde::Deserialize)]
struct Shown {
review: GuidedReview,
reading: Vec<ChapterReading>,
}
let shown: Shown =
serde_json::from_str(include_str!("pr-230.json")).expect("the captured review parses");
(shown.review, shown.reading)
}
fn guide_of(review: &GuidedReview, reading: &[ChapterReading]) -> String {
guide(&Marked, review, reading, &[])
}
/// The section `guide` drew for chapter `index`.
fn section(html: &str, review: &GuidedReview, index: usize) -> String {
let id = review.chapters[index].id.as_str();
let start = html.find(&format!("data-chapter=\"{id}\"")).expect("the chapter is drawn");
let end = html[start..].find("</section>").expect("its section closes") + start;
html[start..end].to_owned()
}
/// Every chapter, in order, numbered against the whole and labeled by kind.
///
/// The break this catches: numbering from zero or against the wrong total, or a kind mislabeled,
/// which is how a reader tells the core of a change from its tests.
#[test]
fn chapters_are_numbered_and_labeled_in_order() {
let (review, reading) = captured();
let html = guide_of(&review, &reading);
let places = ["01 / 03</span><span>CORE", "02 / 03</span><span>TESTS", "03 / 03</span>"];
let at: Vec<usize> = places.iter().map(|it| html.find(it).expect(it)).collect();
assert!(at.windows(2).all(|pair| pair[0] < pair[1]), "in the review's order");
assert!(html.contains("<span>SUPPORTING</span>"));
}
/// A walked chapter says so; the others don't.
///
/// The break this catches: every chapter or none reading as reviewed, so the list can't say where
/// the reader got to.
#[test]
fn only_walked_chapters_say_reviewed() {
let (review, reading) = captured();
let html = guide(&Marked, &review, &reading, &[review.chapters[1].id.clone()]);
assert!(!section(&html, &review, 0).contains("reviewed"));
assert!(section(&html, &review, 1).contains("<span class=\"rv-walked\">reviewed</span>"));
}
/// A chapter to read shows its rationale through the markdown hook and its files, each once, in
/// the order it names them.
///
/// The break this catches: a file listed per hunk (a chapter touching `cli.rs` twice lists it
/// twice), or the rationale skipping the TUI's markdown.
#[test]
fn a_chapter_to_read_shows_its_rationale_and_files_once() {
let (review, reading) = captured();
let core = section(&guide_of(&review, &reading), &review, 0);
assert!(core.contains(&format!("md:{}", escape(&review.chapters[0].rationale))));
assert_eq!(core.matches("crates/luxe-cli/src/cli.rs").count(), 1, "{core}");
let (first, second) = (core.find("cli.rs").expect("cli.rs"), core.find("args.rs"));
assert!(second.is_some_and(|second| first < second), "the chapter's order");
assert!(core.contains("<span class=\"rv-status tone-modified\">M</span>"));
}
/// An impact sits under the rationale, marked as one.
///
/// The break this catches: the impact dropped, which is the line saying what the change does to
/// everything else.
#[test]
fn an_impact_follows_the_rationale() {
let (mut review, reading) = captured();
review.chapters[0].impact = Some("Clients see a new frame".into());
let core = section(&guide_of(&review, &reading), &review, 0);
assert!(core.contains("<div class=\"rv-impact\"><p>md:Clients see a new frame</p></div>"));
}
/// The reading for one chapter, overriding what the capture said.
fn reading_with(
review: &GuidedReview,
needs_review: usize,
reason: Option<&str>,
) -> ChapterReading {
let chapter_id = review.chapters[2].id.clone();
ChapterReading { chapter_id, needs_review, reason: reason.map(str::to_owned) }
}
/// A chapter nothing in needs the reader is one quiet line saying why, without its files.
///
/// The break this catches: a lockfile chapter spending the page like the core change, or saying
/// nothing about why it's safe to skip.
#[test]
fn a_chapter_needing_nothing_says_why_in_one_line() {
let (review, _) = captured();
let reading = [reading_with(&review, 0, Some("formatting only"))];
let quiet = section(&guide_of(&review, &reading), &review, 2);
assert!(quiet.contains("formatting only \u{2014} nothing here needs you"), "{quiet}");
assert!(quiet.contains("rv-title quiet"));
assert!(!quiet.contains("rv-files") && !quiet.contains("md:"));
}
/// With no one reason, it still says there's nothing to read.
///
/// The break this catches: an empty line where the reason would go.
#[test]
fn a_chapter_needing_nothing_for_mixed_reasons_says_only_that() {
let (review, _) = captured();
let reading = [reading_with(&review, 0, None)];
let quiet = section(&guide_of(&review, &reading), &review, 2);
assert!(quiet.contains("<p class=\"rv-reason\">nothing here needs you</p>"), "{quiet}");
}
/// A chapter the host said nothing about is one to read.
///
/// The break this catches: a missing reading folding the chapter away, so a stale or partial
/// frame hides work.
#[test]
fn a_chapter_without_a_reading_is_one_to_read() {
let (review, _) = captured();
let open = section(&guide_of(&review, &[]), &review, 2);
assert!(open.contains("rv-files") && !open.contains("rv-reason"));
}
/// The summary leads: its intent, then its claims as a list.
///
/// The break this catches: the brief left out, or its claims run together as one paragraph.
#[test]
fn the_summary_leads_the_guide() {
let (mut review, reading) = captured();
let account = vec!["Adds a frame".into(), "Pins it".into()];
review.brief = Some(ReviewBrief { intent: "Let a phone join".into(), account });
let html = guide_of(&review, &reading);
let brief = "<section class=\"rv-brief md\"><p>md:Let a phone join</p><ul><li><p>md:Adds a \
frame</p></li><li><p>md:Pins it</p></li></ul></section>";
assert!(html.starts_with(&format!("<div class=\"rv-guide\">{brief}")), "{html}");
}
/// Without a summary, the agent's own words lead, said to be just that.
///
/// The break this catches: the turn's account passed off as a reviewed summary.
#[test]
fn without_a_summary_the_agents_words_lead_and_say_so() {
let (mut review, reading) = captured();
let provenance = TurnProvenance {
requests: vec!["make it join".into()],
account: Some("I added show_open_review".into()),
..TurnProvenance::default()
};
review.provenance = Some(provenance);
let html = guide_of(&review, &reading);
let words = html.find("md:make it join").zip(html.find("md:I added show_open_review"));
assert!(words.is_some_and(|(asked, said)| asked < said), "{html}");
assert!(html.contains("no summary was written for this review"));
}
/// With neither, the guide opens on the chapters.
///
/// The break this catches: an empty brief box above the first chapter.
#[test]
fn with_nothing_to_say_there_is_no_brief() {
let (review, reading) = captured();
assert!(!guide_of(&review, &reading).contains("rv-brief"));
}
/// Past eight files, the rest are counted.
///
/// The break this catches: a forty-file chapter listing every path, or the count off by one.
#[test]
fn files_past_eight_are_counted() {
let (mut review, _) = captured();
let template = review.files[0].clone();
review.chapters[2].items = (0..11).map(|n| copy_of(&mut review, &template, n)).collect();
let html = guide_of(&review, &[]);
assert_eq!(section(&html, &review, 2).matches("<li><span class=\"rv-status").count(), 8);
assert!(html.contains("<li class=\"rv-more\">\u{2026} 3 more</li>"));
}
/// A file numbered `n`, added to the review, named by the item returned.
fn copy_of(
review: &mut GuidedReview,
template: &ReviewFile,
n: usize,
) -> luxe_core::guided_review::ReviewItemRef {
let mut file = template.clone();
file.id = serde_json::from_value(serde_json::json!(format!("file:{n}"))).expect("an id");
file.new_path = Some(format!("docs/{n}.md").into());
review.files.push(file.clone());
luxe_core::guided_review::ReviewItemRef::File(file.id)
}
/// Titles and paths are text, never markup.
///
/// The break this catches: a branch's chapter title running script in the page.
#[test]
fn titles_are_escaped() {
let (mut review, reading) = captured();
review.chapters[0].title = "<img src=x onerror=alert(1)>".into();
let html = guide_of(&review, &reading);
assert!(html.contains("&lt;img src=x onerror=alert(1)&gt;") && !html.contains("<img"));
}
fn item_id(item: &luxe_core::guided_review::ReviewItemRef) -> &str {
match item {
luxe_core::guided_review::ReviewItemRef::File(id) => id.as_str(),
luxe_core::guided_review::ReviewItemRef::Hunk(id) => id.as_str(),
}
}
/// The opened chapter's files with only its hunks, as the app sends them.
fn opened(review: &GuidedReview, index: usize) -> Vec<ReviewFile> {
let items = &review.chapters[index].items;
let named = |id: &str| items.iter().any(|item| item_id(item) == id);
let mut files: Vec<ReviewFile> = review.files.clone();
files.retain_mut(|file| {
file.hunks.retain(|hunk| named(hunk.id.as_str()));
named(file.id.as_str()) || !file.hunks.is_empty()
});
files
}
fn open(review: &GuidedReview, index: usize) -> String {
let place = Place { number: index + 1, total: review.chapters.len(), walked: false };
chapter(&Marked, &review.chapters[index], &opened(review, index), &place, None, &[])
}
/// An opened chapter names each file once above its run of hunks, in the chapter's order.
///
/// The break this catches: the path repeated above every hunk, or a hunk drawn under the wrong
/// file.
#[test]
fn an_opened_chapter_names_each_file_once_above_its_hunks() {
let (review, _) = captured();
let html = open(&review, 0);
assert_eq!(html.matches("<p class=\"rv-file\">crates/luxe-cli/src/cli.rs</p>").count(), 1);
let path = html.find("rv-file\">crates/luxe-cli/src/cli.rs").expect("the path");
let hunks: Vec<usize> = html.match_indices("<div class=\"hunk\">").map(|(at, _)| at).collect();
assert_eq!(hunks.len(), 3, "the chapter's three hunks");
assert!(path < hunks[1], "cli.rs heads its hunks: {html}");
}
/// The guide's sentence for a hunk sits above that hunk's lines.
///
/// The break this catches: notes dropped, or put under the wrong hunk, which narrates code the
/// reader isn't looking at.
#[test]
fn a_note_sits_above_its_hunk() {
let (mut review, _) = captured();
let second = item_id(&review.chapters[0].items[1]).to_owned();
review.chapters[0].notes = vec![ItemNote { item: second, note: "Reads the flag".into() }];
let html = open(&review, 0);
let note = html.find("<p class=\"rv-note\">Reads the flag</p>").expect("the note");
let hunks: Vec<usize> = html.match_indices("<div class=\"hunk\">").map(|(at, _)| at).collect();
assert!(hunks[0] < note && note < hunks[1], "{html}");
}
/// The symbol a hunk sits in heads it, as the TUI's narration names it.
///
/// The break this catches: the function name dropped, leaving only line numbers to say where the
/// change is.
#[test]
fn a_hunks_symbol_heads_it() {
let (mut review, _) = captured();
let symbol = luxe_core::guided_review::SymbolContext {
kind: "function".into(),
name: Some("run_rpc".into()),
};
let first = item_id(&review.chapters[0].items[0]).to_owned();
let hunk = review.files.iter_mut().flat_map(|file| file.hunks.iter_mut());
hunk.filter(|hunk| hunk.id.as_str() == first)
.for_each(|hunk| hunk.symbol = Some(symbol.clone()));
let html = open(&review, 0);
let named = html.find("<p class=\"rv-symbol\">run_rpc</p>").expect("the symbol");
assert!(named < html.find("<div class=\"hunk\">").expect("a hunk"), "{html}");
}
/// The capture with chapter 2 naming one binary file as a whole, noted by the guide.
fn with_a_binary_file() -> GuidedReview {
let (mut review, _) = captured();
let template = review.files[0].clone();
let item = copy_of(&mut review, &template, 1);
let file = review.files.last_mut().expect("the copy");
file.hunks.clear();
file.non_text = Some(luxe_core::guided_review::NonTextChange {
kind: luxe_core::guided_review::NonTextChangeKind::Binary,
summary: "binary, 4 KiB".into(),
});
let note = ItemNote { item: item_id(&item).to_owned(), note: "The new icon".into() };
review.chapters[2].items = vec![item];
review.chapters[2].notes = vec![note];
review
}
/// A file named as a whole shows its note and says why there are no lines.
///
/// The break this catches: a binary or mode-only change drawn as nothing at all, so the reader
/// can't tell it was part of the chapter.
#[test]
fn a_whole_file_item_shows_its_note_and_why_there_are_no_lines() {
let review = with_a_binary_file();
let html = open(&review, 2);
let note = html.find("<p class=\"rv-note\">The new icon</p>").expect("the note");
let why = html.find("isn&#39;t text").or_else(|| html.find("isn't text"));
assert!(why.is_some_and(|why| note < why), "{html}");
}
/// A file with no lines to count says what changed in the guide's row instead.
///
/// The break this catches: a binary file's row with no figures and no words.
#[test]
fn a_file_without_lines_says_what_changed() {
let review = with_a_binary_file();
let row = section(&guide_of(&review, &[]), &review, 2);
assert!(row.contains("<span class=\"rv-dim\">binary, 4 KiB</span>"), "{row}");
}
/// An item whose file the app didn't send is left out rather than failing the chapter.
///
/// The break this catches: one missing file blanking the whole chapter.
#[test]
fn an_item_without_its_file_is_left_out() {
let (review, _) = captured();
let place = Place { number: 1, total: 3, walked: false };
let html = chapter(&Marked, &review.chapters[0], &[], &place, None, &[]);
assert!(html.contains(&escape(&review.chapters[0].title)) && !html.contains("hunk"));
}

View File

@@ -0,0 +1,256 @@
use super::*;
fn user(content: serde_json::Value) -> String {
let piece: Piece =
serde_json::from_value(serde_json::json!({ "kind": "user", "content": content }))
.expect("a user piece as the app sends it");
render(&PlainText, &piece)
}
/// A user message shows what the reader wrote, escaped, and not what rode along for the model.
///
/// The break this catches: hook context shown as the reader's words, or their words written into
/// the page unescaped.
#[test]
fn a_user_message_shows_only_the_readers_words() {
let html = user(serde_json::json!([
{ "type": "text", "content": "why <b>this</b>?" },
{ "type": "text", "content": "[hook] Plan check: 10 tool calls" },
]));
assert_eq!(html, "<p class=\"words\">why &lt;b&gt;this&lt;/b&gt;?</p>");
}
/// An image sent first keeps its place, so hook context after it is still hidden.
///
/// The break this catches: skipping the blocks that aren't text instead of keeping them as
/// placeholders, which moves the hook's note to block 0, where it reads as the reader's own.
#[test]
fn an_image_keeps_its_place_in_a_user_message() {
let html = user(serde_json::json!([
{ "type": "image" },
{ "type": "text", "content": "[hook] Plan check: 10 tool calls" },
]));
assert_eq!(html, "<p class=\"attached\">1 image(s) attached</p>");
}
/// The break this catches: images left without a trace, so a photo sent from the phone vanishes
/// from the conversation, or counted wrong, or their glyph written into the page unescaped.
#[test]
fn images_show_as_the_tuis_attached_line() {
let piece: Piece = serde_json::from_value(serde_json::json!({
"kind": "user",
"content": [{ "type": "text", "content": "what's this?" }, { "type": "image" }, { "type": "image" }],
}))
.expect("a user piece as the app sends it");
assert_eq!(
render(&Loud, &piece),
"<p class=\"words\">what&#39;s this?</p><p class=\"attached\">&amp; 2 image(s) attached</p>"
);
}
/// The break this catches: a file or tree piece renamed, sent to another piece's renderer, or the
/// tree refusing the `null` changes the app sends before anything changed, so the Files tab's
/// request is refused or drawn as something else.
#[test]
fn the_file_pieces_arrive_by_their_kinds() {
let pieces = serde_json::json!([
{ "kind": "file", "file": { "path": "a.rs", "text": "x\n", "bytes": 2 } },
{ "kind": "file_failed", "error": "wrong_kind" },
{ "kind": "tree", "rows": [{ "kind": "note", "depth": 0, "text": "Loading" }],
"changes": null },
]);
let pieces: Vec<Piece> = serde_json::from_value(pieces).expect("the pieces the app sends");
let html: Vec<String> = pieces.iter().map(|piece| render(&PlainText, piece)).collect();
assert!(html[0].starts_with("<div class=\"file\" "), "{html:?}");
assert!(html[1].contains("not what it was asked for"), "{html:?}");
assert!(html[2].starts_with("<div class=\"tree\">"), "{html:?}");
}
/// The break this catches: a GitHub piece renamed or sent to another's renderer, or the
/// conversation refusing a request without `opened_by_you`, so the GitHub tab's request is refused.
#[test]
fn the_github_pieces_arrive_by_their_kinds() {
let issue = serde_json::json!({ "kind": "issue", "overview": { "number": 41, "title": "Crash",
"body": "", "url": "https://github.com/o/r/issues/41", "repository": "o/r",
"author": { "login": "mara", "bot": false }, "state": "open", "updated_at": 0,
"labels": [], "assignees": [], "milestone": null, "linked": [], "conversation_count": 0 } });
let pieces = serde_json::json!([
{ "kind": "github_list", "repository": null, "now": 0,
"section": { "name": "Mine", "items": [], "error": null, "total": 0 } },
{ "kind": "github_header", "overview": issue, "now": 0 },
{ "kind": "github_overview", "overview": issue, "now": 0 },
{ "kind": "github_conversation", "entries": [], "now": 0 },
]);
let pieces: Vec<Piece> = serde_json::from_value(pieces).expect("the pieces the app sends");
let html: Vec<String> = pieces.iter().map(|piece| render(&PlainText, piece)).collect();
assert!(html[0].contains("Nothing matches this search"), "{html:?}");
assert!(html[1].starts_with("<header class=\"gh-head\">"), "{html:?}");
assert!(html[2].starts_with("<h3 class=\"gh-section\">Status"), "{html:?}");
assert_eq!(html[3], "<div class=\"gh-conversation\"></div>");
}
/// The break this catches: a review piece renamed, or one refusing a request that leaves out what
/// the app may not have (the walked chapters, a chapter's reading or whether it was walked).
#[test]
fn the_review_pieces_arrive_by_their_kinds() {
let shown: serde_json::Value =
serde_json::from_str(include_str!("review/pr-230.json")).expect("the captured review");
let chapter = &shown["review"]["chapters"][0];
let pieces = serde_json::json!([
{ "kind": "review_guide", "review": shown["review"], "reading": shown["reading"] },
{ "kind": "review_chapter", "chapter": chapter, "files": [],
"place": { "number": 1, "total": 3 }, "reading": null },
]);
let pieces: Vec<Piece> = serde_json::from_value(pieces).expect("the pieces the app sends");
let html: Vec<String> = pieces.iter().map(|piece| render(&PlainText, piece)).collect();
assert!(html[0].starts_with("<div class=\"rv-guide\">"), "{html:?}");
assert!(html[1].starts_with("<div class=\"rv-chapter-view\">"), "{html:?}");
}
/// The break this catches: a dock or diff piece renamed, so the app's request for it is refused
/// as a whole and nothing on the screen renders.
#[test]
fn the_dock_and_diff_pieces_arrive_by_their_kinds() {
let pieces = serde_json::json!([
{ "kind": "plan", "todos": { "current": null, "items": [], "pending": 0, "in_progress": 0,
"completed": 0, "blocked": 0, "total": 0, "truncated": false } },
{ "kind": "changes", "changes": { "files": [], "total_files": 0, "additions": 0,
"deletions": 0, "truncated": false } },
{ "kind": "diff", "diff": { "path": "a", "file": null, "untracked": false } },
{ "kind": "diff_failed", "error": "too_large" },
]);
let pieces: Vec<Piece> = serde_json::from_value(pieces).expect("the pieces the app sends");
let html: Vec<String> = pieces.iter().map(|piece| render(&PlainText, piece)).collect();
assert!(html[0].contains(">PLAN</span>"), "{html:?}");
assert!(html[1].contains(">FILES</span>"), "{html:?}");
assert!(html[2].contains("matches the last commit"), "{html:?}");
assert!(html[3].contains("too large"), "{html:?}");
}
/// The break this catches: a message with no images given an "attached" line anyway.
#[test]
fn words_alone_say_nothing_is_attached() {
let html =
user(serde_json::json!([{ "type": "text", "content": "hi" }, { "type": "tool_result" }]));
assert_eq!(html, "<p class=\"words\">hi</p>");
}
/// The break this catches: a brief Luxe wrote shown whole, as a page of instructions in the
/// reader's colors.
#[test]
fn a_brief_shows_as_one_line() {
let html = user(serde_json::json!([
{ "type": "text", "content": "Draft a reply to @jon on PR 12.\n\nKeep it short." },
]));
assert_eq!(html, "<p class=\"brief\">Drafted a reply</p>");
}
/// A question from a review is the reader's, so it shows, under where it was asked.
///
/// The break this catches: the brief labeled as one line instead, losing the question the answer
/// below it is answering.
#[test]
fn a_review_question_shows_what_was_asked() {
let brief = "Guided review feedback\nSubmission: submission:1\nReview: review:2\n\
Source revision: revision:3\nMode: Question\n\n\
- Question · Why two passes?\n\
\x20 Finding ID: finding:2\n\
\x20 Evidence: src/a.rs:3 (new)\n\
\x20 Why two passes?\n\
Do not rewrite unrelated code.";
let html = user(serde_json::json!([{ "type": "text", "content": brief }]));
assert_eq!(
html,
"<p class=\"words\"><span class=\"chip\">Asked in review \u{b7} src/a.rs:3 (new)</span>\n\
Why two passes?</p>"
);
}
/// A renderer that words every status the same, with a mark and words that need escaping.
struct Loud;
impl Renderer for Loud {
fn markdown(&self, _text: &str, _voice: Voice) -> String {
String::new()
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
let segment = |kind, glyph: Option<&str>, tone| StatusSegment {
kind,
glyph: glyph.map(str::to_string),
label: "<9%>".into(),
tone,
};
vec![
segment("context", Some("&"), StatusTone::Error),
segment("cost", None, StatusTone::Plain),
segment("model", None, StatusTone::Warning),
]
}
fn image_glyph(&self) -> String {
"&".into()
}
fn mode_mark(&self, mode: &str) -> String {
if mode == "plan" { "P&" } else { "B" }.into()
}
}
/// The break this catches: the mode button showing build's mark in plan mode (or none at all),
/// its mark or name written unescaped, or a renderer without marks leaving an empty mark behind.
#[test]
fn a_mode_wears_its_own_mark() {
let mode = |mode: &str| Piece::ModeName { mode: mode.into() };
assert_eq!(
render(&Loud, &mode("plan")),
"<span class=\"mode-mark\" aria-hidden=\"true\">P&amp;</span> plan"
);
assert!(render(&Loud, &mode("<b>")).ends_with(">B</span> &lt;b&gt;"));
assert_eq!(render(&PlainText, &mode("build")), "build");
}
/// The break this catches: a status segment's words or mark written into the page unescaped, a
/// tone lost so a full window reads as a roomy one, or the app's facts not parsing as sent.
#[test]
fn a_status_renders_each_segment_escaped_with_its_tone() {
let piece: Piece = serde_json::from_value(serde_json::json!({
"kind": "status",
"model": {"provider": "anthropic", "model": "claude-x"},
"thinking": "high",
"context": {"used_tokens": 1, "context_window": 2},
}))
.expect("a status piece as the app sends it");
assert_eq!(
render(&Loud, &piece),
"<span class=\"seg seg-context tone-error\">\
<span class=\"seg-glyph\" aria-hidden=\"true\">&amp;</span> &lt;9%&gt;</span>\
<span class=\"seg seg-cost\">&lt;9%&gt;</span>\
<span class=\"seg seg-model tone-warning\">&lt;9%&gt;</span>"
);
}
/// The break this catches: the plain renderer, which a bridge has before the TUI's, showing no
/// model, so a phone can't tell what's answering.
#[test]
fn the_plain_renderer_names_the_model() {
let facts = StatusFacts {
model: Some(luxe_core::ModelRef::new("anthropic", "claude-x")),
..StatusFacts::default()
};
let labels: Vec<_> = PlainText.status(&facts).into_iter().map(|s| s.label).collect();
assert_eq!(labels, ["claude-x"]);
}
/// The break this catches: an answer rendered as sent, so a draft meant for its card shows in
/// the conversation too.
#[test]
fn an_answer_leaves_out_what_was_written_for_luxe() {
let piece = Piece::Answer { text: "```luxe-draft\nThanks, merged.\n```".into() };
let html = render(&PlainText, &piece);
assert!(!html.contains("merged"), "{html}");
}

View File

@@ -0,0 +1,193 @@
//! The Files tab's tree, drawn as the TUI's dock draws FILES.
//!
//! One row a line: a `│` guide for each level down, a chevron on a folder, the folder or language
//! mark in its hue, then the name, with a changed file's counts and letter at the right edge and a
//! dot on a closed folder that holds a change. The app decides which folders are open and sends
//! the rows it can see, so this draws and keeps nothing.
use super::workspace::{change_status, counts};
use super::{escape, Renderer};
use luxe_core::workspace::{FileChangeSummary, WorkspaceChangesSummary};
/// The mark a file wears in the tree, and the theme role it's colored by.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FileMark {
/// The glyph, as plain text; empty for none
pub glyph: String,
/// What colors it
pub hue: MarkHue,
}
/// The theme roles a language's mark is colored by, each a variable in the app's stylesheet.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MarkHue {
/// The theme's warning hue
Warning,
/// The theme's info hue
Info,
/// The theme's success hue
Success,
/// The theme's error hue
Error,
/// The deepest thinking level's hue
ThinkingUltra,
/// Body text
Text,
/// Muted text, for a mark with no known hue
#[default]
Muted,
}
impl MarkHue {
fn class(self) -> &'static str {
match self {
Self::Warning => "hue-warning",
Self::Info => "hue-info",
Self::Success => "hue-success",
Self::Error => "hue-error",
Self::ThinkingUltra => "hue-thinking-ultra",
Self::Text => "hue-text",
Self::Muted => "hue-muted",
}
}
}
/// One row the app can see, as it sends it.
#[derive(Debug, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum TreeRow {
/// A folder, open or closed
Folder(Entry),
/// A file
File(Entry),
/// Words where entries would be: loading, empty, or why not
Note { depth: usize, text: String },
}
/// A folder or file in the tree.
#[derive(Debug, serde::Deserialize)]
pub(crate) struct Entry {
/// From the project's root, `/` between folders
path: String,
name: String,
/// Folders above it, below the root
depth: usize,
/// Whether a folder shows what's in it
#[serde(default)]
open: bool,
}
/// Every row, marked from `changes` where a file in it changed.
pub(super) fn tree(
renderer: &dyn Renderer,
rows: &[TreeRow],
changes: Option<&WorkspaceChangesSummary>,
) -> String {
let changed = changes.map_or(&[][..], |changes| changes.files.as_slice());
let rows: String = rows.iter().map(|row| tree_row(renderer, row, changed)).collect();
format!("<div class=\"tree\">{rows}</div>")
}
/// The project's name behind the folder mark, then its branch, as the TUI's project section has
/// them: the branch quieter, with ` *` when the tree has changes.
pub(super) fn project_name(
renderer: &dyn Renderer,
name: &str,
branch: Option<&str>,
dirty: bool,
) -> String {
let folder = escape(&renderer.folder_mark());
let mut out = format!("<span class=\"project-mark\">{folder}</span>{}", escape(name));
if let Some(branch) = branch {
let dirty = if dirty { " *" } else { "" };
out.push_str(&format!(
"<span class=\"project-branch\"><span class=\"project-mark\">{}</span>{}{dirty}</span>",
escape(&renderer.branch_mark()),
escape(branch)
));
}
out
}
fn tree_row(renderer: &dyn Renderer, row: &TreeRow, changed: &[FileChangeSummary]) -> String {
match row {
TreeRow::Folder(folder) => {
folder_row(renderer, folder, holds_change(changed, &folder.path))
}
TreeRow::File(file) => {
file_row(renderer, file, changed.iter().find(|change| display(change) == file.path))
}
TreeRow::Note { depth, text } => {
format!("<p class=\"tree-row tree-note\">{}{}</p>", guides(*depth), escape(text))
}
}
}
fn folder_row(renderer: &dyn Renderer, folder: &Entry, holds_change: bool) -> String {
let chevron = if folder.open { "\u{25be}" } else { "\u{25b8}" };
// only a closed folder hides the change, so only a closed one says it's there
let dot = match holds_change && !folder.open {
true => "<span class=\"tree-right held\">\u{2022}</span>",
false => "",
};
format!(
"<button type=\"button\" class=\"tree-row\" data-folder=\"{}\" aria-expanded=\"{}\">\
{}<span class=\"chevron\">{chevron}</span>{}<span class=\"tree-name folder\">{}</span>\
{dot}</button>",
escape(&folder.path),
folder.open,
guides(folder.depth),
mark(&renderer.folder_mark(), "hue-secondary"),
escape(&folder.name)
)
}
fn file_row(renderer: &dyn Renderer, file: &Entry, change: Option<&FileChangeSummary>) -> String {
let file_mark = renderer.file_mark(&file.name);
let (name_class, right) = match change {
Some(change) => {
(format!(" change-{}", change_status(change.status)), change_cells(renderer, change))
}
None => (String::new(), String::new()),
};
format!(
"<button type=\"button\" class=\"tree-row\" data-file=\"{}\">{}<span class=\"chevron\">\
</span>{}<span class=\"tree-name{name_class}\">{}</span>{right}</button>",
escape(&file.path),
guides(file.depth),
mark(&file_mark.glyph, file_mark.hue.class()),
escape(&file.name)
)
}
/// ` +6 −0 M`, as the dock's change rows end.
fn change_cells(renderer: &dyn Renderer, change: &FileChangeSummary) -> String {
format!(
"<span class=\"tree-right\">{} <span class=\"change-{}\">{}</span></span>",
counts(change.additions, change.deletions),
change_status(change.status),
escape(&renderer.change_mark(change.status))
)
}
fn guides(depth: usize) -> String {
"<span class=\"guide\" aria-hidden=\"true\"></span>".repeat(depth)
}
/// The mark's cells, kept even when there's no glyph so names line up with their neighbors'.
fn mark(glyph: &str, hue: &str) -> String {
format!("<span class=\"mark {hue}\" aria-hidden=\"true\">{}</span>", escape(glyph))
}
fn holds_change(changed: &[FileChangeSummary], folder: &str) -> bool {
changed
.iter()
.any(|file| display(file).strip_prefix(folder).is_some_and(|rest| rest.starts_with('/')))
}
fn display(file: &FileChangeSummary) -> String {
luxe_core::paths::display(&file.path)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,140 @@
use super::{project_name, tree, FileMark, MarkHue, TreeRow};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
use luxe_core::workspace::{FileChangeStatus, WorkspaceChangesSummary};
/// Marks that say what they are: `F` for a file, warm for Rust, `D` for a folder, a status's name.
struct Marked;
impl Renderer for Marked {
fn markdown(&self, text: &str, _voice: Voice) -> String {
escape(text)
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn change_mark(&self, status: FileChangeStatus) -> String {
format!("{status:?}")
}
fn file_mark(&self, name: &str) -> FileMark {
let hue = if name.ends_with(".rs") { MarkHue::Warning } else { MarkHue::Muted };
FileMark { glyph: "F".into(), hue }
}
fn folder_mark(&self) -> String {
"D".into()
}
fn branch_mark(&self) -> String {
"B".into()
}
}
/// A `workspace_updated` frame's `changes`, copied from a live session, with its file moved into
/// `src/` so a folder holds it.
const CHANGES: &str = r#"{"files": [{"path": "src/notes.txt", "status": "added", "additions": 1, "deletions": 0, "binary": false}], "total_files": 1, "additions": 1, "deletions": 0, "truncated": false}"#;
/// The panel's bar names the project behind the tree's folder mark, and the name stays text.
///
/// The break this catches: a drawn icon standing in for the TUI's glyph, so the bar and the tree
/// disagree at every tier, or a folder named like markup running as markup.
#[test]
fn the_project_name_wears_the_folder_mark() {
assert_eq!(
project_name(&Marked, "luxe", None, true),
"<span class=\"project-mark\">D</span>luxe",
"no branch, nothing after the name, dirty or not"
);
assert!(project_name(&Marked, "<b>x", None, false).ends_with("&lt;b&gt;x"));
}
/// The branch follows the name behind its own mark, starred only when the tree has changes.
///
/// The break this catches: the dirty star shown on a clean tree or lost on a dirty one, the branch
/// drawn without the TUI's mark, or a branch name running as markup.
#[test]
fn the_branch_follows_the_name_starred_when_dirty() {
let branch = |dirty| project_name(&Marked, "luxe", Some("remote-access"), dirty);
let lead = "<span class=\"project-mark\">D</span>luxe<span class=\"project-branch\">\
<span class=\"project-mark\">B</span>remote-access";
assert_eq!(branch(true), format!("{lead} *</span>"));
assert_eq!(branch(false), format!("{lead}</span>"));
assert!(project_name(&Marked, "x", Some("<i>"), false).contains("&lt;i&gt;"));
}
fn rows(json: serde_json::Value) -> Vec<TreeRow> {
serde_json::from_value(json).expect("rows as the app sends them")
}
fn changes() -> WorkspaceChangesSummary {
serde_json::from_str(CHANGES).expect("a changes summary as core sends it")
}
/// The break this catches: a guide too many or too few, an open folder drawn closed, a mark in the
/// wrong hue, or the attribute the app's tap reads missing or crossed between folder and file.
#[test]
fn rows_read_as_the_tuis_tree() {
let rows = rows(serde_json::json!([
{ "kind": "folder", "path": "src", "name": "src", "depth": 0, "open": true },
{ "kind": "file", "path": "src/main.rs", "name": "main.rs", "depth": 1 },
]));
let expected = "<div class=\"tree\">\
<button type=\"button\" class=\"tree-row\" data-folder=\"src\" aria-expanded=\"true\">\
<span class=\"chevron\">▾</span><span class=\"mark hue-secondary\" aria-hidden=\"true\">D\
</span><span class=\"tree-name folder\">src</span></button>\
<button type=\"button\" class=\"tree-row\" data-file=\"src/main.rs\">\
<span class=\"guide\" aria-hidden=\"true\"></span><span class=\"chevron\"></span>\
<span class=\"mark hue-warning\" aria-hidden=\"true\">F</span>\
<span class=\"tree-name\">main.rs</span></button></div>";
assert_eq!(tree(&Marked, &rows, None), expected);
}
/// The break this catches: a changed file's counts or letter dropped, or its name not colored by
/// its status, as the TUI's tree colors it.
#[test]
fn a_changed_file_ends_with_its_counts_and_letter() {
let rows = rows(serde_json::json!([
{ "kind": "file", "path": "src/notes.txt", "name": "notes.txt", "depth": 1 },
{ "kind": "file", "path": "notes.txt", "name": "notes.txt", "depth": 0 },
]));
let html = tree(&Marked, &rows, Some(&changes()));
let changed =
"<span class=\"tree-name change-added\">notes.txt</span><span class=\"tree-right\"> \
<span class=\"add\">+1</span> <span class=\"del\">−0</span> \
<span class=\"change-added\">Added</span></span></button>";
assert_eq!(html.matches(changed).count(), 1, "only the file at that path is marked: {html}");
}
/// The break this catches: the dot on an open folder, whose change is in plain sight, missing from
/// a closed one, or shown for a folder whose name only starts the changed file's (`sr` for `src`).
#[test]
fn a_closed_folder_holding_a_change_wears_a_dot() {
let folder = |path: &str, open: bool| serde_json::json!({ "kind": "folder", "path": path, "name": path, "depth": 0, "open": open });
let html = |row| tree(&Marked, &rows(serde_json::json!([row])), Some(&changes()));
let dot = "<span class=\"tree-right held\">•</span>";
assert!(html(folder("src", false)).contains(dot));
assert!(!html(folder("src", true)).contains(dot));
assert!(!html(folder("sr", false)).contains(dot));
}
/// The break this catches: a note drawn at the wrong depth, or written into the page unescaped.
#[test]
fn a_note_stands_where_entries_would() {
let rows = rows(serde_json::json!([{ "kind": "note", "depth": 2, "text": "<empty>" }]));
let expected = "<div class=\"tree\"><p class=\"tree-row tree-note\">\
<span class=\"guide\" aria-hidden=\"true\"></span><span class=\"guide\" aria-hidden=\"true\">\
</span>&lt;empty&gt;</p></div>";
assert_eq!(tree(&Marked, &rows, None), expected);
}
/// The break this catches: a path or name written into the attribute the app reads, or the page,
/// unescaped, so a file named with a quote breaks out of it.
#[test]
fn paths_and_names_are_escaped() {
let rows = rows(serde_json::json!([
{ "kind": "file", "path": "a\"<b>", "name": "a\"<b>", "depth": 0 },
]));
let html = tree(&Marked, &rows, None);
assert!(html.contains("data-file=\"a&quot;&lt;b&gt;\""), "{html}");
assert!(html.contains(">a&quot;&lt;b&gt;</span>"), "{html}");
}

View File

@@ -0,0 +1,108 @@
//! The dock's sections, as the app shows them beside the transcript: the plan and the changes.
//!
//! The TUI's words and marks, laid out for a touch screen: every row of the plan wraps rather than
//! scrolling in a window of its own, and each changed file is a button that opens its diff.
use super::{escape, Renderer};
use luxe_core::workspace::{
FileChangeStatus, FileChangeSummary, TodoSummary, TodoSummaryItem, WorkspaceChangesSummary,
};
use luxe_core::TodoSummaryStatus;
/// `PLAN 2/5`, the counts, and the checklist in the order it was written.
pub(super) fn plan(renderer: &dyn Renderer, todos: &TodoSummary) -> String {
let mut out = heading("PLAN", &format!("{}/{}", todos.completed, todos.total));
out.push_str(&format!(
"<p class=\"dock-sub\">{} pending \u{b7} {} active \u{b7} {} done</p><ol class=\"todos\">",
todos.pending, todos.in_progress, todos.completed
));
for item in &todos.items {
out.push_str(&todo_row(renderer, item));
}
out.push_str("</ol>");
out + &more(todos.total, todos.items.len())
}
fn todo_row(renderer: &dyn Renderer, item: &TodoSummaryItem) -> String {
let (status, words) = todo_status(item.status);
format!(
"<li class=\"todo todo-{status}\"><span class=\"todo-mark\" role=\"img\" \
aria-label=\"{words}\">{}</span> <span class=\"todo-subject\">{}</span></li>",
escape(&renderer.todo_mark(item.status)),
escape(&item.subject)
)
}
/// The status as the class the stylesheet colors by, and as words for a screen reader.
fn todo_status(status: TodoSummaryStatus) -> (&'static str, &'static str) {
match status {
TodoSummaryStatus::Pending => ("pending", "to do"),
TodoSummaryStatus::InProgress => ("in-progress", "in progress"),
TodoSummaryStatus::Completed => ("completed", "done"),
TodoSummaryStatus::Blocked => ("blocked", "blocked"),
}
}
/// `FILES 3 changed +7 −0`, and a row for each file.
pub(super) fn changes(renderer: &dyn Renderer, changes: &WorkspaceChangesSummary) -> String {
let counts = counts(changes.additions, changes.deletions);
let mut out = heading("FILES", &format!("{} changed{counts}", changes.total_files));
if changes.files.is_empty() {
return out + "<p class=\"dock-sub\">nothing has changed</p>";
}
out.push_str("<ul class=\"changes\">");
for file in &changes.files {
out.push_str(&change_row(renderer, file));
}
out.push_str("</ul>");
out + &more(changes.total_files, changes.files.len())
}
fn change_row(renderer: &dyn Renderer, file: &FileChangeSummary) -> String {
let path = escape(&luxe_core::paths::display(&file.path));
format!(
"<li><button type=\"button\" class=\"change change-{}\" data-path=\"{path}\">\
<span class=\"change-path\">{path}</span><span class=\"change-counts\">{}</span> \
<span class=\"change-mark\">{}</span></button></li>",
change_status(file.status),
counts(file.additions, file.deletions),
escape(&renderer.change_mark(file.status)),
)
}
pub(super) fn change_status(status: FileChangeStatus) -> &'static str {
match status {
FileChangeStatus::Added => "added",
FileChangeStatus::Modified => "modified",
FileChangeStatus::Deleted => "deleted",
FileChangeStatus::Renamed => "renamed",
FileChangeStatus::Untracked => "untracked",
}
}
/// ` +6 −0`, or nothing when Git couldn't count, since `+0 −0` would claim nothing changed.
pub(super) fn counts(additions: Option<u64>, deletions: Option<u64>) -> String {
let (Some(additions), Some(deletions)) = (additions, deletions) else {
return String::new();
};
format!(
" <span class=\"add\">+{additions}</span> <span class=\"del\">\u{2212}{deletions}</span>"
)
}
/// The TUI's heading: the word cut into a badge at the depth both of these sections sit at, with
/// what it sums up riding bare beside it.
fn heading(title: &str, rest: &str) -> String {
format!("<p class=\"dock-head\"><span class=\"badge raised\">{title}</span> {rest}</p>")
}
/// `and 3 more`, for rows the snapshot left out.
fn more(total: usize, shown: usize) -> String {
match total.saturating_sub(shown) {
0 => String::new(),
left => format!("<p class=\"dock-sub\">and {left} more</p>"),
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,122 @@
use super::{changes, plan};
use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice};
use luxe_core::workspace::{FileChangeStatus, TodoSummary, WorkspaceChangesSummary};
use luxe_core::TodoSummaryStatus;
/// Marks that name their status, with markup in them so escaping shows.
struct Named;
impl Renderer for Named {
fn markdown(&self, text: &str, _voice: Voice) -> String {
escape(text)
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn todo_mark(&self, status: TodoSummaryStatus) -> String {
format!("<{status:?}>")
}
fn change_mark(&self, status: FileChangeStatus) -> String {
format!("{status:?}")
}
}
/// A `workspace_updated` frame's `todos`, copied from a live session.
const TODOS: &str = r#"{"current": {"id": "2", "subject": "Write the summary", "status": "in_progress", "blocked_by": []}, "items": [{"id": "1", "subject": "Read the notes", "status": "completed", "blocked_by": []}, {"id": "2", "subject": "Write the summary", "status": "in_progress", "blocked_by": []}, {"id": "3", "subject": "Check the summary", "status": "pending", "blocked_by": []}], "pending": 1, "in_progress": 1, "completed": 1, "blocked": 0, "total": 3, "truncated": false}"#;
/// A `workspace_updated` frame's `changes`, copied from a live session.
const CHANGES: &str = r#"{"files": [{"path": "notes.txt", "status": "added", "additions": 1, "deletions": 0, "binary": false}, {"path": "README.md", "status": "untracked", "additions": 3, "deletions": 0, "binary": false}], "total_files": 2, "additions": 4, "deletions": 0, "truncated": false}"#;
fn todos(json: &str) -> TodoSummary {
serde_json::from_str(json).expect("a todos summary as core sends it")
}
fn changed(json: &str) -> WorkspaceChangesSummary {
serde_json::from_str(json).expect("a changes summary as core sends it")
}
/// The break this catches: the dock's heading, counts or marks crossed or dropped, rows reordered
/// (the TUI keeps the order they were written in), a status class misspelled so the stylesheet
/// can't color it, or a mark written into the page unescaped.
#[test]
fn the_plan_reads_as_the_docks_checklist() {
let row = |status: &str, words: &str, mark: &str, subject: &str| {
format!(
"<li class=\"todo todo-{status}\"><span class=\"todo-mark\" role=\"img\" \
aria-label=\"{words}\">&lt;{mark}&gt;</span> <span class=\"todo-subject\">{subject}\
</span></li>"
)
};
let expected = format!(
"<p class=\"dock-head\"><span class=\"badge raised\">PLAN</span> 1/3</p>\
<p class=\"dock-sub\">1 pending · 1 active · 1 done</p><ol class=\"todos\">{}{}{}</ol>",
row("completed", "done", "Completed", "Read the notes"),
row("in-progress", "in progress", "InProgress", "Write the summary"),
row("pending", "to do", "Pending", "Check the summary"),
);
assert_eq!(plan(&Named, &todos(TODOS)), expected);
}
/// The break this catches: a trimmed plan shown as if it were all of it, or its counts crossed
/// (the live plan above has as many pending as active, so it can't tell them apart).
#[test]
fn a_trimmed_plan_says_how_much_more_there_is() {
let trimmed = TODOS
.replace("\"pending\": 1,", "\"pending\": 3,")
.replace("\"total\": 3, \"truncated\": false", "\"total\": 5, \"truncated\": true");
let html = plan(&Named, &todos(&trimmed));
assert!(html.contains(">3 pending · 1 active · 1 done<"), "{html}");
assert!(html.ends_with("</ol><p class=\"dock-sub\">and 2 more</p>"), "{html}");
}
/// The break this catches: a file's path, counts or mark crossed or dropped, the button without the
/// path the app opens the diff by, or the heading's totals wrong.
#[test]
fn each_change_is_a_way_into_its_diff() {
let expected = "<p class=\"dock-head\"><span class=\"badge raised\">FILES</span> 2 changed \
<span class=\"add\">+4</span> <span class=\"del\">−0</span></p><ul class=\"changes\">\
<li><button type=\"button\" class=\"change change-added\" data-path=\"notes.txt\">\
<span class=\"change-path\">notes.txt</span><span class=\"change-counts\"> \
<span class=\"add\">+1</span> <span class=\"del\">−0</span></span> \
<span class=\"change-mark\">Added</span></button></li>\
<li><button type=\"button\" class=\"change change-untracked\" data-path=\"README.md\">\
<span class=\"change-path\">README.md</span><span class=\"change-counts\"> \
<span class=\"add\">+3</span> <span class=\"del\">−0</span></span> \
<span class=\"change-mark\">Untracked</span></button></li></ul>";
assert_eq!(changes(&Named, &changed(CHANGES)), expected);
}
/// The break this catches: counts Git couldn't make printed as `+0 −0`, which says the file
/// didn't change, when a binary file plainly did.
#[test]
fn counts_git_couldnt_make_are_left_out() {
let binary = r#"{"files": [{"path": "logo.png", "status": "modified", "additions": null, "deletions": null, "binary": true}], "total_files": 1, "additions": null, "deletions": null, "truncated": false}"#;
let html = changes(&Named, &changed(binary));
assert!(html.starts_with(
"<p class=\"dock-head\"><span class=\"badge raised\">FILES</span> 1 changed</p>"
));
assert!(html.contains("<span class=\"change-counts\"></span>"), "{html}");
}
/// The break this catches: a path written into the page, or into the attribute the app reads,
/// unescaped, so a file named with a quote breaks out of it.
#[test]
fn a_path_is_escaped_everywhere_it_goes() {
let odd = CHANGES.replace("notes.txt", "a\\\"<b>.txt");
let html = changes(&Named, &changed(&odd));
assert!(html.contains("data-path=\"a&quot;&lt;b&gt;.txt\""), "{html}");
assert!(html.contains("<span class=\"change-path\">a&quot;&lt;b&gt;.txt</span>"), "{html}");
}
/// The break this catches: an empty change list drawn as an empty box, or the trimmed tail said
/// when nothing was trimmed.
#[test]
fn nothing_changed_says_so() {
let none =
r#"{"files": [], "total_files": 0, "additions": 0, "deletions": 0, "truncated": false}"#;
assert!(changes(&Named, &changed(none))
.ends_with("</p><p class=\"dock-sub\">nothing has changed</p>"));
}

View File

@@ -0,0 +1,269 @@
//! Routes — what the bridge answers, and the one place a request is turned into a session.
use std::path::PathBuf;
use std::sync::Arc;
use axum::extract::{DefaultBodyLimit, Path, State, WebSocketUpgrade};
use axum::http::StatusCode;
use axum::middleware::from_fn_with_state;
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Extension, Json, Router};
use crate::access::{require_device, require_login};
use crate::devices::{Device, DeviceBook};
use crate::folders::Folder;
use crate::launch::{self, LaunchError, Launcher, Place};
use crate::push::api as push;
use crate::sessions::{self, SessionSummary};
use crate::REVOCATION_CHECK;
/// What every route reads.
pub(crate) struct Bridged {
/// Where running Luxes record their sessions
pub(crate) runtime_dir: PathBuf,
/// Tailnet logins allowed in
pub(crate) logins: Vec<String>,
/// The paired devices, read fresh on each request
pub(crate) devices: DeviceBook,
/// What starts sessions, when this bridge may
pub(crate) launcher: Option<Launcher>,
/// What turns messages into the app's HTML
pub(crate) renderer: Arc<dyn crate::Renderer>,
/// Which devices have which sessions open, so neither is notified about what it's showing
pub(crate) presence: crate::push::Presence,
/// The computer's tailnet name, when Tailscale gave one, which names the phone's app for it
pub(crate) machine: Option<String>,
}
/// Where an invitation link lands.
const PAIR_PAGE: &str = include_str!("pair.html");
/// The most a render request may carry. A diff or a file comes back to be rendered, and core caps
/// each at 2 MiB of text, which as a diff's JSON (an object per line, with its numbers) is several
/// times that.
const RENDER_BODY_LIMIT: usize = 16 * 1024 * 1024;
pub(crate) fn router(bridged: Bridged) -> Router {
let bridged = Arc::new(bridged);
Router::new()
.route("/", get(crate::app::index))
.route("/app/{*path}", get(crate::app::file))
.route("/service-worker.js", get(crate::app::service_worker))
.route("/theme.css", get(crate::app::theme))
.route("/manifest.webmanifest", get(crate::home_screen::manifest))
.route("/icons/{file}", get(crate::home_screen::icon))
.route("/pair", get(|| async { Html(PAIR_PAGE) }))
.route("/api/pair", post(crate::pairing::pair))
.merge(paired_only(&bridged))
.layer(from_fn_with_state(bridged.clone(), require_login))
.with_state(bridged)
}
/// What only a paired device reaches: its sessions and everything about them.
fn paired_only(bridged: &Arc<Bridged>) -> Router<Arc<Bridged>> {
Router::new()
.route("/api/sessions", get(list_sessions).post(start_session))
.route("/api/folders", get(list_folders))
.route("/api/render", post(render).layer(DefaultBodyLimit::max(RENDER_BODY_LIMIT)))
.route("/api/sessions/{session_id}/socket", get(join_session))
.route("/api/push", get(push::status).put(push::subscribe).delete(push::unsubscribe))
.route_layer(from_fn_with_state(bridged.clone(), require_device))
}
async fn list_sessions(State(bridged): State<Arc<Bridged>>) -> Json<Vec<SessionSummary>> {
let runtime_dir = bridged.runtime_dir.clone();
// reads a folder and, on Windows, asks `tasklist` about each pid
let running = tokio::task::spawn_blocking(move || sessions::running(&runtime_dir)).await;
let running = running.unwrap_or_default();
if let Some(launcher) = &bridged.launcher {
launcher.saw(running.iter().map(|session| session.cwd.clone()).collect()).await;
}
Json(running)
}
/// Renders what the app asks for, off the async threads: highlighting a long block is real work.
async fn render(
State(bridged): State<Arc<Bridged>>,
Json(request): Json<crate::render::RenderRequest>,
) -> Response {
let renderer = bridged.renderer.clone();
let pieces = request.pieces;
let html = tokio::task::spawn_blocking(move || {
pieces.iter().map(|piece| crate::render::render(&*renderer, piece)).collect()
});
match html.await {
Ok(html) => Json(crate::render::Rendered { html }).into_response(),
Err(error) => {
tracing::error!(%error, "rendering failed");
(StatusCode::INTERNAL_SERVER_ERROR, "rendering failed").into_response()
}
}
}
#[derive(serde::Serialize)]
struct Folders {
folders: Vec<Folder>,
/// Whether a session started now opens in herdr
herdr: bool,
}
async fn list_folders(State(bridged): State<Arc<Bridged>>) -> Response {
let Some(launcher) = &bridged.launcher else {
return (StatusCode::NOT_IMPLEMENTED, "this bridge doesn't start sessions").into_response();
};
let (folders, herdr) = launcher.folders(&bridged.runtime_dir).await;
Json(Folders { folders, herdr }).into_response()
}
#[derive(serde::Deserialize)]
struct StartRequest {
folder: String,
}
#[derive(serde::Serialize)]
struct Started {
session: SessionSummary,
place: Place,
}
/// Starts a session in the folder the device names, answering once it can be joined.
async fn start_session(
State(bridged): State<Arc<Bridged>>,
Extension(device): Extension<Device>,
Json(request): Json<StartRequest>,
) -> Response {
let Some(launcher) = &bridged.launcher else {
return (StatusCode::NOT_IMPLEMENTED, "this bridge doesn't start sessions").into_response();
};
match start_in(launcher, &request.folder, &bridged.runtime_dir).await {
Ok((session, place)) => {
tracing::info!(session = %session.session_id, ?place, device = %device.name, "a device started a session");
let started = Started { session: SessionSummary::from(&session), place };
(StatusCode::CREATED, Json(started)).into_response()
}
Err(error) => {
tracing::warn!(%error, device = %device.name, "could not start a session");
(start_failure_status(&error), error.to_string()).into_response()
}
}
}
async fn start_in(
launcher: &Launcher,
asked: &str,
runtime_dir: &std::path::Path,
) -> Result<(luxe_core::local_endpoint::LiveSession, Place), LaunchError> {
let folder = launch::resolve_folder(asked, luxe_core::user_dirs::home_dir().as_deref())?;
launcher.start(&folder, runtime_dir).await
}
fn start_failure_status(error: &LaunchError) -> StatusCode {
match error {
LaunchError::NotAFolder(_) => StatusCode::BAD_REQUEST,
LaunchError::Herdr(_) | LaunchError::Spawn(_) => StatusCode::BAD_GATEWAY,
LaunchError::NeverAppeared(_) => StatusCode::GATEWAY_TIMEOUT,
}
}
/// Joins the session for the device, connecting before the upgrade so a session that has gone is
/// an HTTP error the app can show, not a socket that opens and closes.
async fn join_session(
State(bridged): State<Arc<Bridged>>,
Extension(device): Extension<Device>,
Path(session_id): Path<String>,
upgrade: WebSocketUpgrade,
) -> Response {
let introduction = introduction(&bridged, &device);
match connect(bridged.runtime_dir.clone(), &session_id, &introduction).await {
Ok(stream) => {
tracing::info!(session = %session_id, device = %device.name, "a device joined");
let here = bridged.presence.arrive(&device.id, &session_id);
let revoked = revoked(bridged.devices.clone(), device.id);
upgrade.on_upgrade(move |socket| async move {
crate::relay::relay(socket, stream, revoked).await;
drop(here);
})
}
Err(refusal) => refusal.into_response(),
}
}
/// Resolves once device `id` is no longer paired, checking every [`REVOCATION_CHECK`].
///
/// Polled because the file is changed by another process (`luxe remote devices revoke`), and a
/// revoked device's open sockets have to close, not just its next request fail.
async fn revoked(devices: DeviceBook, id: String) {
loop {
tokio::time::sleep(REVOCATION_CHECK).await;
let reader = devices.clone();
let paired = tokio::task::spawn_blocking(move || reader.devices()).await;
let Ok(paired) = paired else { continue };
if !paired.iter().any(|device| device.id == id) {
tracing::info!(device = %id, "closing a revoked device's socket");
return;
}
}
}
/// Who the bridge joins as for `device`: its name, and whether the computer's owner paired it,
/// judged by the first allowed login, where `luxe remote` puts the one Tailscale names as the
/// machine's.
fn introduction<'a>(bridged: &Bridged, device: &'a Device) -> crate::relay::Introduction<'a> {
let yours = owned_by(&bridged.logins, &device.login);
crate::relay::Introduction { name: &device.name, watch_only: false, yours }
}
/// Whether `login` is the owner's, the first of the allowed `logins`.
fn owned_by(logins: &[String], login: &str) -> bool {
logins.first().is_some_and(|owner| owner == login)
}
/// Connects to `session_id` and introduces the device to it as `device`.
///
/// A refusal is the status and reason to answer with.
async fn connect(
runtime_dir: PathBuf,
session_id: &str,
device: &crate::relay::Introduction<'_>,
) -> Result<luxe_core::local_endpoint::LocalStream, (StatusCode, String)> {
let wanted = session_id.to_string();
let found = tokio::task::spawn_blocking(move || sessions::find(&runtime_dir, &wanted)).await;
let Some(session) = found.ok().flatten() else {
return Err((StatusCode::NOT_FOUND, format!("no running session {session_id}")));
};
open(&session.address, device).await.map_err(|error| {
tracing::warn!(%error, session = %session_id, "could not join the session");
let reason = format!("could not join session {session_id}: {error}");
(StatusCode::BAD_GATEWAY, reason)
})
}
/// Connects to the endpoint at `address` and introduces the bridge there as `introduction`.
pub(crate) async fn open(
address: &str,
introduction: &crate::relay::Introduction<'_>,
) -> Result<luxe_core::local_endpoint::LocalStream, String> {
let connected = luxe_core::local_endpoint::connect(address).await;
let mut stream = connected.map_err(|error| error.to_string())?;
let introduced = crate::relay::introduce(&mut stream, introduction).await;
introduced.map_err(|error| error.to_string())?;
Ok(stream)
}
#[cfg(test)]
mod tests {
use super::owned_by;
/// A device is the owner's when the login that paired it is the first allowed, and only then.
///
/// The break this catches: a guest let in with `--allow` treated as the owner, so their phone
/// joins the owner's session without a line, or the owner's own phone announced every time.
#[test]
fn only_the_first_allowed_login_is_the_owners() {
let logins = ["alex@github".to_string(), "sam@github".to_string()];
assert!(owned_by(&logins, "alex@github"));
assert!(!owned_by(&logins, "sam@github"));
assert!(!owned_by(&[], "alex@github"));
}
}

View File

@@ -0,0 +1,25 @@
//! Secrets — the random strings pairing hands out, and the digests the host keeps instead.
use base64::Engine as _;
use sha2::{Digest, Sha256};
/// A fresh secret: 32 random bytes, URL-safe, so it fits in a link and a cookie as it is.
pub(crate) fn random_secret() -> String {
let mut bytes = [0u8; 32];
// a guessable credential would be a hole, not an inconvenience
getrandom::fill(&mut bytes).expect("OS randomness unavailable");
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}
/// A short random id to name a device by in a list.
pub(crate) fn random_id() -> String {
let mut bytes = [0u8; 4];
getrandom::fill(&mut bytes).expect("OS randomness unavailable");
base16ct::lower::encode_string(&bytes)
}
/// What the host stores in place of `secret`. A plain hash is enough: the secret is 256 random
/// bits, so there is nothing to guess that a slow hash would protect.
pub(crate) fn digest(secret: &str) -> String {
base16ct::lower::encode_string(&Sha256::digest(secret.as_bytes()))
}

View File

@@ -0,0 +1,123 @@
//! Service — running the bridge at login, as the platform's own per-user service.
//!
//! systemd on Linux, launchd on macOS, and the `HKCU` Run key on Windows: each one is per user and
//! needs no admin rights. What runs is written down at install ([`Launch`]), with the owner's login
//! as an `--allow`, so a service started before the network (or without `tailscale` on its `PATH`,
//! as launchd's is) still knows who to let in.
use std::path::PathBuf;
#[cfg(any(test, target_os = "macos"))]
mod launchd;
#[cfg(any(test, windows))]
mod run_key;
#[cfg(any(test, all(unix, not(target_os = "macos"))))]
mod systemd;
/// What the service runs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Launch {
/// The `luxe` binary
pub program: PathBuf,
/// Its arguments: `remote` and the bridge's flags
pub args: Vec<String>,
}
/// Why the service couldn't be installed or removed.
#[derive(Debug, thiserror::Error)]
pub enum ServiceError {
/// A file couldn't be written or removed
#[error("could not {action} {path}: {source}")]
Io {
/// What was being done
action: &'static str,
/// To which file
path: PathBuf,
/// The operating system's reason
#[source]
source: std::io::Error,
},
/// The platform's service manager refused
#[error("`{command}` failed: {detail}")]
Command {
/// The command line that failed
command: String,
/// What it said
detail: String,
},
/// Nowhere to put a service: no home folder, or a platform without a per-user service manager
#[error("this system has no per-user service manager Luxe knows how to use")]
Unsupported,
}
/// Installs and starts the service, replacing one already there. Returns where it was recorded.
pub fn install(launch: &Launch) -> Result<String, ServiceError> {
#[cfg(target_os = "macos")]
return launchd::install(launch);
#[cfg(all(unix, not(target_os = "macos")))]
return systemd::install(launch);
#[cfg(windows)]
return run_key::install(launch);
#[cfg(not(any(unix, windows)))]
{
let _ = launch;
Err(ServiceError::Unsupported)
}
}
/// Stops and removes the service. `false` when there was none.
pub fn remove() -> Result<bool, ServiceError> {
#[cfg(target_os = "macos")]
return launchd::remove();
#[cfg(all(unix, not(target_os = "macos")))]
return systemd::remove();
#[cfg(windows)]
return run_key::remove();
#[cfg(not(any(unix, windows)))]
Err(ServiceError::Unsupported)
}
/// Whether the service is installed.
pub fn installed() -> bool {
#[cfg(target_os = "macos")]
return launchd::installed();
#[cfg(all(unix, not(target_os = "macos")))]
return systemd::installed();
#[cfg(windows)]
return run_key::installed();
#[cfg(not(any(unix, windows)))]
false
}
/// Runs a service manager's command, turning a failure into what it said.
#[cfg(any(unix, windows))]
fn run(program: &str, args: &[&str]) -> Result<(), ServiceError> {
let command = || format!("{program} {}", args.join(" "));
let output = std::process::Command::new(program).args(args).output();
let output = output
.map_err(|error| ServiceError::Command { command: command(), detail: error.to_string() })?;
if output.status.success() {
return Ok(());
}
let detail = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(ServiceError::Command { command: command(), detail })
}
#[cfg(unix)]
fn write_file(path: &std::path::Path, contents: &str) -> Result<(), ServiceError> {
let io = |action| move |source| ServiceError::Io { action, path: path.to_path_buf(), source };
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(io("create the folder for"))?;
}
luxe_core::fs_atomic::replace(path, contents.as_bytes()).map_err(io("write"))
}
/// Removes `path`, `false` when it wasn't there.
#[cfg(unix)]
fn remove_file(path: &std::path::Path) -> Result<bool, ServiceError> {
match std::fs::remove_file(path) {
Ok(()) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(source) => Err(ServiceError::Io { action: "remove", path: path.to_path_buf(), source }),
}
}

View File

@@ -0,0 +1,105 @@
//! launchd — the bridge as a launch agent, `~/Library/LaunchAgents/dev.luxe.remote.plist`.
use super::Launch;
const LABEL: &str = "dev.luxe.remote";
/// Started at login, and again if it stops.
const TEMPLATE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{label}</string>
<key>ProgramArguments</key>
<array>
{arguments} </array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
"#;
/// The property list for `launch`.
fn plist(launch: &Launch) -> String {
let program = launch.program.to_string_lossy();
let arguments: String = std::iter::once(program.as_ref())
.chain(launch.args.iter().map(String::as_str))
.map(|word| format!(" <string>{}</string>\n", escape(word)))
.collect();
TEMPLATE.replace("{label}", LABEL).replace("{arguments}", &arguments)
}
fn escape(text: &str) -> String {
text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
#[cfg(target_os = "macos")]
mod manage {
use std::path::PathBuf;
use super::super::{remove_file, run, write_file, Launch, ServiceError};
use super::{plist, LABEL};
fn plist_path() -> Result<PathBuf, ServiceError> {
let home = luxe_core::user_dirs::home_dir().ok_or(ServiceError::Unsupported)?;
Ok(home.join("Library").join("LaunchAgents").join(format!("{LABEL}.plist")))
}
/// `gui/<uid>`, the signed-in user's launchd domain. Asked of `id` because reading the uid
/// directly needs `unsafe`.
fn domain() -> Result<String, ServiceError> {
let output = std::process::Command::new("id").arg("-u").output();
let output = output.map_err(|error| ServiceError::Command {
command: "id -u".into(),
detail: error.to_string(),
})?;
Ok(format!("gui/{}", String::from_utf8_lossy(&output.stdout).trim()))
}
pub(crate) fn install(launch: &Launch) -> Result<String, ServiceError> {
let path = plist_path()?;
let domain = domain()?;
// a loaded agent keeps its old command until it is booted out
let _ = run("launchctl", &["bootout", &format!("{domain}/{LABEL}")]);
write_file(&path, &plist(launch))?;
run("launchctl", &["bootstrap", &domain, &path.to_string_lossy()])?;
Ok(path.display().to_string())
}
pub(crate) fn remove() -> Result<bool, ServiceError> {
let path = plist_path()?;
if !path.exists() {
return Ok(false);
}
let _ = run("launchctl", &["bootout", &format!("{}/{LABEL}", domain()?)]);
remove_file(&path)
}
pub(crate) fn installed() -> bool {
plist_path().is_ok_and(|path| path.exists())
}
}
#[cfg(target_os = "macos")]
pub(crate) use manage::{install, installed, remove};
#[cfg(test)]
mod tests {
use super::*;
/// Each word is its own argument, escaped for XML.
///
/// The break this catches: an unescaped `&` or `<` in a path or login, which makes the plist
/// unreadable and launchd refuses it with no reason a user would find.
#[test]
fn each_word_is_an_escaped_argument() {
let launch = Launch { program: "/Users/a&b/luxe".into(), args: vec!["remote".into()] };
let plist = plist(&launch);
assert!(plist
.contains(" <string>/Users/a&amp;b/luxe</string>\n <string>remote</string>\n"));
assert!(plist.contains("<key>RunAtLoad</key>\n <true/>"), "{plist}");
}
}

View File

@@ -0,0 +1,82 @@
//! Run key — the bridge started at sign-in from `HKCU\...\CurrentVersion\Run`, which needs no admin.
//!
//! `luxe.exe` is a console program, so started bare it would open a console window at every
//! sign-in. PowerShell's hidden window style starts it with none showing, beyond a brief flash.
use super::Launch;
#[cfg(windows)]
const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";
#[cfg(windows)]
const VALUE: &str = "Luxe remote";
/// The command line the Run key holds for `launch`.
fn command_line(launch: &Launch) -> String {
let program = launch.program.to_string_lossy();
let words: Vec<String> = std::iter::once(program.as_ref())
.chain(launch.args.iter().map(String::as_str))
.map(|word| format!("'{}'", word.replace('\'', "''")))
.collect();
format!("powershell.exe -NoProfile -WindowStyle Hidden -Command \"& {}\"", words.join(" "))
}
#[cfg(windows)]
mod manage {
use super::super::{run, Launch, ServiceError};
use super::{command_line, RUN_KEY, VALUE};
pub(crate) fn install(launch: &Launch) -> Result<String, ServiceError> {
let command = command_line(launch);
run("reg", &["add", RUN_KEY, "/v", VALUE, "/t", "REG_SZ", "/d", &command, "/f"])?;
start_now(launch)?;
Ok(format!(r"{RUN_KEY}\{VALUE}"))
}
/// The Run key only acts at the next sign-in; this one starts now, with no window.
fn start_now(launch: &Launch) -> Result<(), ServiceError> {
let mut command = tokio::process::Command::new(&launch.program);
command.args(&launch.args).stdin(std::process::Stdio::null());
command.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
luxe_core::program::detach_from_terminal(&mut command);
command.spawn().map(drop).map_err(|error| ServiceError::Command {
command: launch.program.display().to_string(),
detail: error.to_string(),
})
}
pub(crate) fn remove() -> Result<bool, ServiceError> {
if !installed() {
return Ok(false);
}
run("reg", &["delete", RUN_KEY, "/v", VALUE, "/f"])?;
Ok(true)
}
pub(crate) fn installed() -> bool {
run("reg", &["query", RUN_KEY, "/v", VALUE]).is_ok()
}
}
#[cfg(windows)]
pub(crate) use manage::{install, installed, remove};
#[cfg(test)]
mod tests {
use super::*;
/// Each word reaches PowerShell as one literal string.
///
/// The break this catches: words left bare or double-quoted, so a path with a space splits, or
/// PowerShell expands a `$` in it, or an apostrophe ends the string early.
#[test]
fn each_word_is_one_literal_string() {
let launch = Launch {
program: r"C:\Users\Alex O'Neil\luxe.exe".into(),
args: vec!["remote".into(), "--allow".into(), "$alex@github".into()],
};
assert_eq!(
command_line(&launch),
r#"powershell.exe -NoProfile -WindowStyle Hidden -Command "& 'C:\Users\Alex O''Neil\luxe.exe' 'remote' '--allow' '$alex@github'""#
);
}
}

View File

@@ -0,0 +1,109 @@
//! systemd — the bridge as a user unit, `~/.config/systemd/user/luxe-remote.service`.
//!
//! A user unit runs while you're signed in; with lingering on (`loginctl enable-linger`) it also
//! runs from boot. Setup doesn't turn lingering on: that is a machine-wide choice.
use super::Launch;
const TEMPLATE: &str = "[Unit]
Description=Luxe remote: your sessions on your own devices
After=network-online.target
[Service]
ExecStart={command}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
";
/// The unit file for `launch`.
fn unit(launch: &Launch) -> String {
let program = launch.program.to_string_lossy();
let command: Vec<String> = std::iter::once(program.as_ref())
.chain(launch.args.iter().map(String::as_str))
.map(quote)
.collect();
TEMPLATE.replace("{command}", &command.join(" "))
}
/// One word of `ExecStart`, quoted the way systemd reads it: `%` and `$` would otherwise expand.
fn quote(word: &str) -> String {
let escaped =
word.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%").replace('$', "$$");
format!("\"{escaped}\"")
}
#[cfg(all(unix, not(target_os = "macos")))]
mod manage {
use std::path::PathBuf;
use super::super::{remove_file, run, write_file, Launch, ServiceError};
use super::unit;
const UNIT: &str = "luxe-remote.service";
fn unit_path() -> Result<PathBuf, ServiceError> {
let config = luxe_core::user_dirs::config_home().ok_or(ServiceError::Unsupported)?;
Ok(config.join("systemd").join("user").join(UNIT))
}
fn systemctl(args: &[&str]) -> Result<(), ServiceError> {
let mut all = vec!["--user"];
all.extend_from_slice(args);
run("systemctl", &all)
}
pub(crate) fn install(launch: &Launch) -> Result<String, ServiceError> {
let path = unit_path()?;
write_file(&path, &unit(launch))?;
systemctl(&["daemon-reload"])?;
systemctl(&["enable", UNIT])?;
// restart, not start, so a reinstall runs the new command
systemctl(&["restart", UNIT])?;
Ok(path.display().to_string())
}
pub(crate) fn remove() -> Result<bool, ServiceError> {
let path = unit_path()?;
if !path.exists() {
return Ok(false);
}
systemctl(&["disable", "--now", UNIT])?;
let removed = remove_file(&path)?;
systemctl(&["daemon-reload"])?;
Ok(removed)
}
pub(crate) fn installed() -> bool {
unit_path().is_ok_and(|path| path.exists())
}
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) use manage::{install, installed, remove};
#[cfg(test)]
mod tests {
use super::*;
/// The unit runs exactly the command it was given, whatever its path holds.
///
/// The break this catches: writing words bare, so a path with a space splits in two, or a `%`
/// or `$` in it is expanded by systemd into something else.
#[test]
fn the_unit_runs_the_command_as_given() {
let launch = Launch {
program: "/home/a b/.local/bin/luxe".into(),
args: vec!["remote".into(), "--allow".into(), "50%$off@github".into()],
};
let unit = unit(&launch);
let exec = unit.lines().find(|line| line.starts_with("ExecStart=")).unwrap();
assert_eq!(
exec,
r#"ExecStart="/home/a b/.local/bin/luxe" "remote" "--allow" "50%%$$off@github""#
);
assert!(unit.contains("WantedBy=default.target"), "it starts at login");
}
}

View File

@@ -0,0 +1,42 @@
//! Sessions — what a device is told about the sessions it can join.
use std::path::Path;
use luxe_core::local_endpoint::{self, LiveSession};
use serde::Serialize;
/// One joinable session, as a device sees it.
///
/// The endpoint's address stays on this machine: a device joins through the bridge by id, and a
/// socket path or pipe name is of no use anywhere else.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct SessionSummary {
pub(crate) session_id: String,
pub(crate) pid: u32,
pub(crate) cwd: String,
pub(crate) luxe_version: String,
}
impl From<&LiveSession> for SessionSummary {
fn from(session: &LiveSession) -> Self {
Self {
session_id: session.session_id.clone(),
pid: session.pid,
cwd: session.cwd.clone(),
luxe_version: session.luxe_version.clone(),
}
}
}
/// Every session running on this machine that can be joined.
pub(crate) fn running(runtime_dir: &Path) -> Vec<SessionSummary> {
local_endpoint::running_sessions(runtime_dir).iter().map(SessionSummary::from).collect()
}
/// The running session with exactly this id. Exact, unlike `luxe join`: a device picks from the
/// list, so a prefix would only ever be a guess.
pub(crate) fn find(runtime_dir: &Path, session_id: &str) -> Option<LiveSession> {
local_endpoint::running_sessions(runtime_dir)
.into_iter()
.find(|session| session.session_id == session_id)
}

View File

@@ -0,0 +1,116 @@
//! Tailnet — what Tailscale says about this machine: who owns it, and its name on the tailnet.
//!
//! Read from `tailscale status --json`, the CLI's stable machine-readable output, rather than the
//! local API's socket, whose path and permissions differ on every platform.
use std::collections::HashMap;
use std::time::Duration;
use serde::Deserialize;
/// How long `tailscale status` gets; it answers from the running daemon in milliseconds.
const STATUS_TIMEOUT: Duration = Duration::from_secs(10);
/// This machine on its tailnet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tailnet {
/// The login of the machine's owner, as Serve names it in `Tailscale-User-Login`
pub login: String,
/// The machine's name on the tailnet, such as `desk.tail1234.ts.net`
pub dns_name: String,
}
impl Tailnet {
/// The machine's own name, the first label of [`Tailnet::dns_name`]: `desk` for
/// `desk.tail1234.ts.net`, as the tailnet's admin console and its addresses name it.
pub fn machine(&self) -> &str {
self.dns_name.split('.').next().unwrap_or(&self.dns_name)
}
}
/// Why Tailscale couldn't say.
#[derive(Debug, thiserror::Error)]
pub enum TailnetError {
/// No `tailscale` on `PATH`
#[error("the `tailscale` command isn't installed or isn't on PATH")]
NotInstalled,
/// It ran but failed
#[error("`tailscale` failed: {0}")]
Failed(String),
/// It answered, but not with what this reads
#[error("`tailscale` said something this can't read: {0}")]
Unreadable(String),
/// Tailscale is installed but not connected
#[error("Tailscale isn't connected (it reports {0}); run `tailscale up`")]
NotRunning(String),
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Status {
backend_state: String,
#[serde(rename = "Self")]
this_machine: Option<Node>,
#[serde(default)]
user: HashMap<String, User>,
}
#[derive(Deserialize)]
struct Node {
#[serde(rename = "UserID")]
user_id: u64,
#[serde(rename = "DNSName")]
dns_name: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct User {
login_name: String,
}
/// Asks Tailscale who owns this machine and what it is called.
pub async fn this_machine() -> Result<Tailnet, TailnetError> {
parse_status(&ask_tailscale(&["status", "--json"]).await?)
}
/// What `tailscale <args>` prints, for a query that answers at once.
async fn ask_tailscale(args: &[&str]) -> Result<String, TailnetError> {
let program = luxe_core::program::resolve("tailscale").ok_or(TailnetError::NotInstalled)?;
let asked = tokio::process::Command::new(program).args(args).kill_on_drop(true).output();
let output = tokio::time::timeout(STATUS_TIMEOUT, asked)
.await
.map_err(|_| TailnetError::Failed("it didn't answer within 10 seconds".into()))?
.map_err(|error| TailnetError::Failed(error.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(TailnetError::Failed(format!("{} ({stderr})", output.status)));
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
fn parse_status(json: &str) -> Result<Tailnet, TailnetError> {
let status: Status =
serde_json::from_str(json).map_err(|error| TailnetError::Unreadable(error.to_string()))?;
if status.backend_state != "Running" {
return Err(TailnetError::NotRunning(status.backend_state));
}
let node = status
.this_machine
.ok_or_else(|| TailnetError::Unreadable("it names no machine as this one".into()))?;
let owner = status.user.get(&node.user_id.to_string()).ok_or_else(|| {
TailnetError::Unreadable(format!(
"this machine's owner, user {}, isn't listed",
node.user_id
))
})?;
let dns_name = node.dns_name.trim_end_matches('.').to_string();
Ok(Tailnet { login: owner.login_name.clone(), dns_name })
}
mod serve;
pub use serve::{publish, published, Published};
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,98 @@
//! Serve — whether Tailscale Serve already carries the bridge to the tailnet, and asking it to.
//!
//! Read from `tailscale serve status --json`, which prints Tailscale's `ServeConfig`: a `Web` map
//! from `host:port` to the handlers on each path, and a `Foreground` map holding the same shape for
//! each `tailscale serve` running in a terminal rather than in the background.
use serde_json::Value;
use super::{ask_tailscale, TailnetError};
/// What `https://<this machine>/` leads to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Published {
/// The bridge on this port
Here,
/// Something else, which setup leaves alone
Elsewhere(String),
/// Nothing yet
Nowhere,
}
/// What Serve does with `https://<this machine>/`, judged against the bridge's `port`.
pub async fn published(port: u16) -> Result<Published, TailnetError> {
let status = ask_tailscale(&["serve", "status", "--json"]).await?;
let config: Value = serde_json::from_str(&status)
.map_err(|error| TailnetError::Unreadable(error.to_string()))?;
Ok(judge(&config, port))
}
/// Asks Serve to carry `https://<this machine>/` to the bridge, in the background so it outlasts
/// the terminal. The output is the user's: Tailscale may print a link to turn HTTPS on for the
/// tailnet and wait while they do, so there is no timeout.
pub async fn publish(port: u16) -> Result<(), TailnetError> {
let program = luxe_core::program::resolve("tailscale").ok_or(TailnetError::NotInstalled)?;
let status = tokio::process::Command::new(program)
.args(["serve", "--bg", &target(port)])
.kill_on_drop(true)
.status()
.await
.map_err(|error| TailnetError::Failed(error.to_string()))?;
if !status.success() {
return Err(TailnetError::Failed(format!("serve ended with {status}")));
}
Ok(())
}
/// The address Serve proxies to. IPv4 because the bridge binds `127.0.0.1`, where `localhost`
/// could resolve to `::1` first.
fn target(port: u16) -> String {
format!("http://127.0.0.1:{port}")
}
fn judge(config: &Value, port: u16) -> Published {
let roots = root_handlers(config);
if roots.iter().any(|handler| proxies_to(handler, port)) {
return Published::Here;
}
match roots.first() {
Some(handler) => Published::Elsewhere(describe(handler)),
None => Published::Nowhere,
}
}
/// The handlers for `/` on port 443, in the background config and every foreground one.
fn root_handlers(config: &Value) -> Vec<&Value> {
let foreground = config.get("Foreground").and_then(Value::as_object);
let configs =
std::iter::once(config).chain(foreground.into_iter().flat_map(|map| map.values()));
configs
.filter_map(|config| config.get("Web")?.as_object())
.flat_map(|web| web.iter())
.filter(|(host_port, _)| host_port.ends_with(":443"))
.filter_map(|(_, site)| site.get("Handlers")?.get("/"))
.collect()
}
fn proxies_to(handler: &Value, port: u16) -> bool {
let Some(proxy) = handler.get("Proxy").and_then(Value::as_str) else {
return false;
};
let authority = proxy.strip_prefix("http://").unwrap_or(proxy).trim_end_matches('/');
let Some((host, listening)) = authority.rsplit_once(':') else {
return false;
};
let loopback = matches!(host, "127.0.0.1" | "localhost" | "[::1]");
loopback && listening.parse::<u16>().is_ok_and(|listening| listening == port)
}
fn describe(handler: &Value) -> String {
["Proxy", "Path", "Text"]
.iter()
.find_map(|kind| handler.get(*kind).and_then(Value::as_str))
.unwrap_or("another handler")
.to_string()
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,56 @@
use super::*;
fn config(json: &str) -> Value {
serde_json::from_str(json).unwrap()
}
/// What `tailscale serve --bg http://127.0.0.1:4519` left in `serve status --json` (1.102.3),
/// with the machine's name changed.
const OURS: &str = r#"{"TCP":{"443":{"HTTPS":true}},"Web":{"desk.tail1234.ts.net:443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:4519"}}}}}"#;
/// A root that already proxies to the bridge's port counts as published, however the address is
/// written.
///
/// The break this catches: matching the proxy as an exact string, so `tailscale serve 4519`
/// (which writes `localhost`) is offered again and setup tries to change a working config.
#[test]
fn a_root_proxying_to_the_bridge_is_published() {
assert_eq!(judge(&config(OURS), 4519), Published::Here);
let spelled = OURS.replace("http://127.0.0.1:4519", "http://localhost:4519/");
assert_eq!(judge(&config(&spelled), 4519), Published::Here);
}
/// A root that leads anywhere else is someone's, and setup leaves it alone.
///
/// The break this catches: taking any root handler as the bridge, so setup reports a working
/// setup that serves another app (or the bridge on another port) to the phone.
#[test]
fn a_root_leading_elsewhere_is_not_the_bridge() {
let other_port = judge(&config(OURS), 4600);
assert_eq!(other_port, Published::Elsewhere("http://127.0.0.1:4519".into()));
let lan = OURS.replace("127.0.0.1", "192.168.1.9");
assert!(matches!(judge(&config(&lan), 4519), Published::Elsewhere(_)));
}
/// Only the HTTPS root counts: a handler on another path or port isn't what the phone opens.
///
/// The break this catches: reading any handler, so `/files` or port 8443 reads as published and
/// the phone gets a 404 at the address setup printed.
#[test]
fn only_the_https_root_counts() {
assert_eq!(judge(&config("{}"), 4519), Published::Nowhere);
let other_path = OURS.replace(r#""/":"#, r#""/luxe":"#);
assert_eq!(judge(&config(&other_path), 4519), Published::Nowhere);
let other_port = OURS.replace(":443\"", ":8443\"");
assert_eq!(judge(&config(&other_port), 4519), Published::Nowhere);
}
/// A `tailscale serve` running in a terminal counts too: its config sits under `Foreground`.
///
/// The break this catches: reading only the background config, so setup offers to publish over a
/// foreground serve that already does it.
#[test]
fn a_foreground_serve_counts() {
let foreground = format!(r#"{{"Foreground":{{"a1b2":{OURS}}}}}"#);
assert_eq!(judge(&config(&foreground), 4519), Published::Here);
}

View File

@@ -0,0 +1,36 @@
use super::*;
/// Trimmed from a real `tailscale status --json` (1.102.3), with the names changed.
const RUNNING: &str = r#"{"Version":"1.102.3","BackendState":"Running","Self":{"ID":"nZN73L4Wtr11CNTRL","HostName":"desk","DNSName":"desk.tail1234.ts.net.","OS":"linux","UserID":1618724369016884,"Online":true},"MagicDNSSuffix":"tail1234.ts.net","CurrentTailnet":{"Name":"alex.github","MagicDNSSuffix":"tail1234.ts.net","MagicDNSEnabled":true},"User":{"1618724369016884":{"ID":1618724369016884,"LoginName":"alex@github","DisplayName":"Alex"},"7":{"ID":7,"LoginName":"sam@github","DisplayName":"Sam"}}}"#;
/// The owner is the user behind this machine, picked out of every user the tailnet lists.
///
/// The break this catches: a renamed field read as missing, or taking the first user listed, so
/// the allowlist holds someone else's login and the owner is refused (or a sharer let in).
#[test]
fn the_owner_is_the_user_behind_this_machine() {
let tailnet = parse_status(RUNNING).unwrap();
assert_eq!(tailnet.login, "alex@github");
assert_eq!(tailnet.dns_name, "desk.tail1234.ts.net", "the trailing dot is a DNS detail");
}
/// The machine's name is the first label of its tailnet name, as its address leads with it.
///
/// The break this catches: the phone's apps for two computers named by the tailnet (both
/// `tail1234`) or by the whole address, too long for a home screen label.
#[test]
fn the_machine_is_named_by_its_first_label() {
assert_eq!(parse_status(RUNNING).unwrap().machine(), "desk");
let bare = Tailnet { login: String::new(), dns_name: "desk".into() };
assert_eq!(bare.machine(), "desk");
}
/// A Tailscale that isn't connected says so, rather than handing back a stale login.
///
/// The break this catches: ignoring the state, so a logged-out daemon's leftover user is trusted.
#[test]
fn a_disconnected_tailscale_is_not_an_owner() {
let stopped = RUNNING.replace(r#""BackendState":"Running""#, r#""BackendState":"NeedsLogin""#);
let refused = parse_status(&stopped).unwrap_err();
assert!(matches!(refused, TailnetError::NotRunning(state) if state == "NeedsLogin"));
}

View File

@@ -0,0 +1,327 @@
use std::net::SocketAddr;
use futures::{SinkExt, StreamExt};
use luxe_core::local_endpoint::{EndpointListener, LiveSession, Publication};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::Message;
use super::*;
mod access;
mod app;
mod closing;
mod home_screen;
mod push;
mod render;
/// The device's end of a joined session socket.
type DeviceSocket =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
const SESSION: &str = "5898d57b-0000-4000-8000-000000000001";
const OWNER: &str = "alex@github";
/// A session as a running Luxe shares it: an endpoint, and its record beside it.
struct FakeSession {
listener: EndpointListener,
_record: Publication,
}
fn fake_session(runtime: &std::path::Path) -> FakeSession {
let listener = EndpointListener::bind(runtime).expect("bind the endpoint");
let record = LiveSession {
pid: std::process::id(),
session_id: SESSION.into(),
cwd: "/work/app".into(),
address: listener.address().to_string(),
luxe_version: "0.1.3".into(),
};
let _record = record.publish(runtime).expect("publish the record");
FakeSession { listener, _record }
}
/// A stand-in for `luxe --rpc`: it publishes a record for itself, then runs until stdin closes.
#[cfg(unix)]
pub(crate) fn fake_luxe(runtime: &std::path::Path) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let script = runtime.join("fake-luxe");
let record = r#"{"pid":%s,"session_id":"started","cwd":"%s","address":"","luxe_version":"0"}"#;
let body = format!(
"#!/bin/sh\nprintf '{record}' $$ \"$PWD\" > \"{dir}/$$.json\"\ncat > /dev/null\n",
dir = runtime.display()
);
std::fs::write(&script, body).unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
script
}
/// No stand-in on Windows, where only the tests that never start one run.
#[cfg(not(unix))]
pub(crate) fn fake_luxe(runtime: &std::path::Path) -> std::path::PathBuf {
runtime.join("no-luxe-here")
}
/// A bridge on a free port, and the folders it reads.
struct Harness {
address: SocketAddr,
runtime: tempfile::TempDir,
devices: DeviceBook,
presence: crate::push::Presence,
_config: tempfile::TempDir,
}
async fn harness() -> Harness {
harness_with(|bridge| bridge).await
}
/// [`harness`], drawing through `renderer`.
async fn harness_rendering(renderer: std::sync::Arc<dyn Renderer>) -> Harness {
harness_with(move |bridge| bridge.rendering_with(renderer)).await
}
/// [`harness`], with the bridge set up by `configure` before it serves.
async fn harness_with(configure: impl FnOnce(Bridge) -> Bridge) -> Harness {
let runtime = tempfile::tempdir().unwrap();
let config = tempfile::tempdir().unwrap();
let devices = DeviceBook::at(config.path().join("remote.json"));
let access = Access { logins: vec![OWNER.into()], devices: devices.clone() };
let bridge = Bridge::bind(([127, 0, 0, 1], 0).into(), runtime.path().into(), access);
let book = folders::FolderBook::at(config.path().join("remote-folders.json"));
let launcher = launch::Launcher::new(fake_luxe(runtime.path()), launch::Herdr::Off, book);
let bridge = configure(bridge.await.unwrap().with_launcher(launcher));
let (address, presence) = (bridge.address(), bridge.presence());
tokio::spawn(bridge.serve(std::future::pending()));
Harness { address, runtime, devices, presence, _config: config }
}
impl Harness {
fn url(&self, path: &str) -> String {
format!("http://{}{path}", self.address)
}
/// A request as Tailscale Serve forwards one from the owner.
fn get(&self, path: &str) -> reqwest::RequestBuilder {
reqwest::Client::new().get(self.url(path)).header("Tailscale-User-Login", OWNER)
}
/// A paired device asking for a session in `folder`.
async fn start_in(&self, folder: &str) -> reqwest::Response {
let cookie = self.pair().await;
let request = reqwest::Client::new().post(self.url("/api/sessions"));
let request = request.header("Tailscale-User-Login", OWNER).header("cookie", cookie);
request.json(&serde_json::json!({ "folder": folder })).send().await.unwrap()
}
/// Pairs a device through the pairing endpoint, returning its cookie.
async fn pair(&self) -> String {
let invitation = self.devices.invite().unwrap();
let response = reqwest::Client::new()
.post(self.url("/api/pair"))
.header("Tailscale-User-Login", OWNER)
.json(&serde_json::json!({ "invitation": invitation, "name": "iPhone" }))
.send()
.await
.unwrap();
assert_eq!(response.status(), 200, "pairing failed: {:?}", response.text().await);
let cookie = response.headers()["set-cookie"].to_str().unwrap();
cookie.split(';').next().unwrap().to_string()
}
/// A socket request for `session`, as the paired device sends it.
fn socket_request(
&self,
session: &str,
cookie: &str,
) -> tokio_tungstenite::tungstenite::handshake::client::Request {
let url = format!("ws://{}/api/sessions/{session}/socket", self.address);
let mut request = url.into_client_request().unwrap();
request.headers_mut().insert("tailscale-user-login", OWNER.parse().unwrap());
request.headers_mut().insert("cookie", cookie.parse().unwrap());
request
}
/// Pairs a device and joins `session` with it: the device's socket, and the session's end.
async fn join(
&self,
session: &mut FakeSession,
) -> (DeviceSocket, luxe_core::local_endpoint::Joined) {
let cookie = self.pair().await;
let request = self.socket_request(SESSION, &cookie);
let (device, _) = tokio_tungstenite::connect_async(request).await.expect("joined");
let joined = session.listener.accept().await.expect("the bridge connected");
(device, joined)
}
}
/// The bridge will not listen beyond this machine, whatever it is asked.
///
/// The break this catches: binding what it is given, so `--port` with a wider address, or a
/// changed default, puts every session on the local network with only the device check in front.
#[tokio::test]
async fn the_bridge_listens_on_loopback_only() {
let dir = tempfile::tempdir().unwrap();
let access = || Access { logins: vec![], devices: DeviceBook::at(dir.path().join("r.json")) };
let wide = Bridge::bind(([0, 0, 0, 0], 0).into(), dir.path().into(), access()).await;
assert!(matches!(wide, Err(RemoteError::NotLoopback(_))));
let narrow = Bridge::bind(([127, 0, 0, 1], 0).into(), dir.path().into(), access()).await;
assert!(narrow.is_ok());
}
/// The list names running sessions and keeps their local address on this machine.
///
/// The break this catches: listing a record whose Luxe has died, which the app shows as a session
/// that fails to open; or sending the endpoint's path, which means nothing off this machine.
#[tokio::test]
async fn the_list_shows_running_sessions_without_their_address() {
let bridge = harness().await;
let _live = fake_session(bridge.runtime.path());
let dead = LiveSession {
pid: dead_pid(),
session_id: "dead".into(),
cwd: "/work/old".into(),
address: "nowhere".into(),
luxe_version: "0.1.2".into(),
};
let _dead = dead.publish(bridge.runtime.path()).unwrap();
let cookie = bridge.pair().await;
let listed = bridge.get("/api/sessions").header("cookie", cookie).send().await.unwrap();
let listed: serde_json::Value = listed.json().await.unwrap();
let pid = std::process::id();
let expected = serde_json::json!([
{ "session_id": SESSION, "pid": pid, "cwd": "/work/app", "luxe_version": "0.1.3" }
]);
assert_eq!(listed, expected);
}
/// The pid of a process that has exited: this test binary, asked only to list its tests.
fn dead_pid() -> u32 {
let mut gone = std::process::Command::new(std::env::current_exe().unwrap())
.arg("--list")
.stdout(std::process::Stdio::null())
.spawn()
.unwrap();
gone.wait().unwrap();
gone.id()
}
/// A device's socket and the session's endpoint carry each other's lines, after the bridge has
/// introduced the device by the name it paired with.
///
/// The break this catches: either direction dropped or reframed, so the app sees nothing or the
/// session reads a frame as several broken actions; or no introduction, so the terminal names
/// the bridge's process instead of the phone; or the owner's own phone not said to be theirs, so
/// its every reconnect is announced.
#[tokio::test]
async fn a_device_socket_relays_the_protocol_both_ways() {
let bridge = harness().await;
let mut session = fake_session(bridge.runtime.path());
let cookie = bridge.pair().await;
let request = bridge.socket_request(SESSION, &cookie);
let (mut device, _) = tokio_tungstenite::connect_async(request).await.expect("joined");
let joined = session.listener.accept().await.expect("the bridge connected");
let (from_device, mut to_device) = tokio::io::split(joined.stream);
to_device.write_all(b"{\"kind\":\"ready\"}\n").await.unwrap();
let frame = device.next().await.expect("a frame").expect("readable");
assert_eq!(frame, Message::Text("{\"kind\":\"ready\"}".into()));
device.send(Message::Text("{\n\"kind\": \"cancel\"\n}".into())).await.unwrap();
let mut lines = BufReader::new(from_device).lines();
let introduction = r#"{"kind":"introduce","content":{"name":"iPhone","yours":true}}"#;
assert_eq!(lines.next_line().await.unwrap().as_deref(), Some(introduction));
assert_eq!(lines.next_line().await.unwrap().as_deref(), Some("{ \"kind\": \"cancel\" }"));
device.close(None).await.unwrap();
assert_eq!(lines.next_line().await.unwrap(), None, "the device left, so the bridge did");
}
/// A session older than `introduce` refuses it, and the device never sees that refusal, only what
/// follows.
///
/// The break this catches: joining a session started before an update shows "Refused: no such
/// action `introduce`" in the phone's transcript, for a frame the bridge sent, not the phone.
#[tokio::test]
async fn an_older_sessions_refusal_of_the_introduction_stays_off_the_device() {
let bridge = harness().await;
let mut session = fake_session(bridge.runtime.path());
let cookie = bridge.pair().await;
let request = bridge.socket_request(SESSION, &cookie);
let (mut device, _) = tokio_tungstenite::connect_async(request).await.expect("joined");
let joined = session.listener.accept().await.expect("the bridge connected");
let (_, mut to_device) = tokio::io::split(joined.stream);
let refusal = r#"{"kind":"action_rejected","content":{"kind":"introduce","reason":"no such action `introduce`"}}"#;
to_device.write_all(format!("{refusal}\n{{\"kind\":\"ready\"}}\n").as_bytes()).await.unwrap();
let frame = device.next().await.expect("a frame").expect("readable");
assert_eq!(frame, Message::Text("{\"kind\":\"ready\"}".into()), "the refusal was held back");
}
/// A paired device starts a session in a folder, and is told which one it can join.
///
/// The break this catches: answering before the session is listed, or with another session, so
/// the app's join that follows finds nothing to join.
#[cfg(unix)]
#[tokio::test]
async fn a_device_starts_a_session_in_a_folder() {
let bridge = harness().await;
let folder = tempfile::tempdir().unwrap();
let started = bridge.start_in(&folder.path().to_string_lossy()).await;
assert_eq!(started.status(), 201);
let started: serde_json::Value = started.json().await.unwrap();
assert_eq!(started["session"]["session_id"], "started");
assert_eq!(started["place"], "bridge");
}
/// A folder that isn't there is the device's mistake, said in words it can show.
///
/// The break this catches: launching anyway and waiting out the timeout, or answering with a
/// server error the app would offer to retry.
#[tokio::test]
async fn starting_in_a_folder_that_isnt_there_is_refused() {
let bridge = harness().await;
let missing = bridge.runtime.path().join("missing");
let refused = bridge.start_in(&missing.to_string_lossy()).await;
assert_eq!(refused.status(), 400);
assert!(refused.text().await.unwrap().contains("isn't a folder"));
}
/// The folders a device can start in include the ones Luxe is running in, counted.
///
/// The break this catches: listing only remembered folders, so a project open at the desk right
/// now is missing from the phone's list until it's been seen once before.
#[tokio::test]
async fn the_folder_list_names_where_luxe_is_running() {
let bridge = harness().await;
let project = tempfile::tempdir().unwrap();
let running = LiveSession {
pid: std::process::id(),
session_id: SESSION.into(),
cwd: project.path().to_string_lossy().into_owned(),
address: String::new(),
luxe_version: "0.1.3".into(),
};
let _record = running.publish(bridge.runtime.path()).unwrap();
let cookie = bridge.pair().await;
let listed = bridge.get("/api/folders").header("cookie", cookie).send().await.unwrap();
let listed: serde_json::Value = listed.json().await.unwrap();
assert_eq!(listed["herdr"], false);
assert_eq!(listed["folders"][0]["path"], running.cwd.as_str());
assert_eq!(listed["folders"][0]["sessions"], 1);
}
/// A session that isn't running is a plain HTTP error, before any socket opens.
///
/// The break this catches: upgrading first and closing at once, which the app can't tell apart
/// from a dropped connection worth retrying.
#[tokio::test]
async fn joining_a_session_that_is_not_running_is_not_found() {
let bridge = harness().await;
let cookie = bridge.pair().await;
let request = bridge.socket_request(SESSION, &cookie);
let refused = tokio_tungstenite::connect_async(request).await.expect_err("nothing to join");
let tokio_tungstenite::tungstenite::Error::Http(response) = refused else {
panic!("expected an HTTP refusal, got {refused:?}");
};
assert_eq!(response.status(), 404);
}

View File

@@ -0,0 +1,138 @@
use super::*;
/// Nothing answers a request that didn't come through Tailscale Serve, not even the start page.
///
/// The break this catches: checking the login only on session routes, so the bridge answers
/// anything on this machine that finds the port, and tells it what it is.
#[tokio::test]
async fn a_request_without_a_tailnet_login_is_refused() {
let bridge = harness().await;
for path in ["/", "/pair", "/api/sessions"] {
let response = reqwest::get(bridge.url(path)).await.unwrap();
assert_eq!(response.status(), 401, "{path} answered");
}
}
/// A tailnet login that isn't on the allowlist is refused, though Serve vouched for it.
///
/// The break this catches: taking any login as enough, so someone you share a node or a tailnet
/// with reaches your sessions.
#[tokio::test]
async fn a_login_not_on_the_allowlist_is_refused() {
let bridge = harness().await;
let response = reqwest::Client::new()
.get(bridge.url("/"))
.header("Tailscale-User-Login", "sam@github")
.send()
.await
.unwrap();
assert_eq!(response.status(), 403);
}
/// A login matches in any case: Tailscale has reported the same account with its name capitalized
/// and in lowercase.
///
/// The break this catches: an exact comparison, which locks the owner out of their own bridge
/// when the header and `tailscale status` disagree on case.
#[tokio::test]
async fn a_login_matches_in_any_case() {
let bridge = harness().await;
let response = reqwest::Client::new()
.get(bridge.url("/"))
.header("Tailscale-User-Login", "Alex@GitHub")
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
}
/// The owner's login opens the start page, and sessions only from a paired device.
///
/// The break this catches: letting the login alone reach sessions, when any process on this
/// machine can send the header straight to the loopback port.
#[tokio::test]
async fn sessions_need_a_paired_device() {
let bridge = harness().await;
assert_eq!(bridge.get("/").send().await.unwrap().status(), 200);
let unpaired = bridge.get("/api/sessions").send().await.unwrap();
assert_eq!(unpaired.status(), 401);
let forged = bridge.get("/api/sessions").header("cookie", "luxe_device=guess").send().await;
assert_eq!(forged.unwrap().status(), 401);
let cookie = bridge.pair().await;
let paired = bridge.get("/api/sessions").header("cookie", cookie).send().await.unwrap();
assert_eq!(paired.status(), 200);
}
/// Pairing hands over a cookie no script can read, sent only over HTTPS and only by this site,
/// and the invitation it used is spent.
///
/// The break this catches: a cookie a page script can read or another site can send, or an
/// invitation that pairs again.
#[tokio::test]
async fn pairing_sets_a_guarded_cookie_and_spends_the_invitation() {
let bridge = harness().await;
let invitation = bridge.devices.invite().unwrap();
let pair = || {
reqwest::Client::new()
.post(bridge.url("/api/pair"))
.header("Tailscale-User-Login", OWNER)
.json(&serde_json::json!({ "invitation": invitation, "name": "iPad" }))
.send()
};
let first = pair().await.unwrap();
let cookie = first.headers()["set-cookie"].to_str().unwrap();
for attribute in ["HttpOnly", "Secure", "SameSite=Strict"] {
assert!(cookie.contains(attribute), "{attribute} missing from {cookie}");
}
assert_eq!(pair().await.unwrap().status(), 400, "the invitation paired twice");
let paired = bridge.devices.devices();
assert_eq!((paired.len(), paired[0].login.as_str()), (1, OWNER));
}
/// A page on another site can't open a session socket with the device's cookie.
///
/// The break this catches: skipping the origin check on the upgrade, since a WebSocket isn't
/// held to the same-origin rule and the cookie rides along with it.
#[tokio::test]
async fn a_socket_from_another_site_is_refused() {
let bridge = harness().await;
let _session = fake_session(bridge.runtime.path());
let cookie = bridge.pair().await;
let mut request = bridge.socket_request(SESSION, &cookie);
request.headers_mut().insert("origin", "https://evil.example".parse().unwrap());
let refused = tokio_tungstenite::connect_async(request).await.expect_err("cross-site");
let tokio_tungstenite::tungstenite::Error::Http(response) = refused else {
panic!("expected an HTTP refusal, got {refused:?}");
};
assert_eq!(response.status(), 403);
let mut request = bridge.socket_request(SESSION, &cookie);
let own_site = format!("https://{}", bridge.address);
request.headers_mut().insert("origin", own_site.parse().unwrap());
assert!(tokio_tungstenite::connect_async(request).await.is_ok(), "its own page is refused");
}
/// Only Serve's own host passes for a page's origin; a missing one is not a page at all.
///
/// The break this catches: comparing against the wrong header, which refuses the app's own page
/// once Serve forwards the original host as `X-Forwarded-Host`.
#[test]
fn a_page_must_come_from_the_host_it_asked() {
let headers = |pairs: &[(&'static str, &str)]| {
let mut headers = axum::http::HeaderMap::new();
for (name, value) in pairs {
headers.insert(*name, value.parse().unwrap());
}
headers
};
let ours = "https://home.tail0.ts.net";
assert!(crate::access::same_site(&headers(&[])).is_ok());
assert!(crate::access::same_site(&headers(&[("origin", ours), ("host", "home.tail0.ts.net")]))
.is_ok());
let forwarded =
[("origin", ours), ("host", "127.0.0.1:4519"), ("x-forwarded-host", "home.tail0.ts.net")];
assert!(crate::access::same_site(&headers(&forwarded)).is_ok());
let elsewhere = [("origin", "https://evil.example"), ("host", "home.tail0.ts.net")];
assert!(crate::access::same_site(&headers(&elsewhere)).is_err());
assert!(crate::access::same_site(&headers(&[("origin", ours)])).is_err());
}

View File

@@ -0,0 +1,90 @@
//! The app's files as a phone fetches them through the bridge.
use super::*;
/// The page comes with its policy, and a module with its type.
///
/// The break this catches: serving the page without the policy, or a module as plain text, which
/// a browser refuses to run, so the app is a blank page.
#[tokio::test]
async fn the_app_is_served_with_its_policy_and_types() {
let bridge = harness().await;
let page = bridge.get("/").send().await.unwrap();
assert_eq!(page.status(), 200);
let policy = page.headers()["content-security-policy"].to_str().unwrap().to_string();
assert!(policy.contains("'sha256-"), "the import map isn't allowed: {policy}");
assert!(page.text().await.unwrap().contains("type=\"importmap\""));
let module = bridge.get("/app/vendor/preact.mjs").send().await.unwrap();
assert_eq!(module.status(), 200);
assert_eq!(module.headers()["content-type"], "text/javascript; charset=utf-8");
}
/// The break this catches: the worker served only under `/app/`, where it would cover nothing but
/// that folder and never see a notification tapped on the app's page, or served as plain text,
/// which a browser refuses to register.
#[tokio::test]
async fn the_service_worker_is_served_from_the_top() {
let bridge = harness().await;
let worker = bridge.get("/service-worker.js").send().await.unwrap();
assert_eq!(worker.status(), 200);
assert_eq!(worker.headers()["content-type"], "text/javascript; charset=utf-8");
assert!(worker.text().await.unwrap().contains("notificationclick"));
}
/// A file the phone already has is answered with 304, and a changed one in full.
///
/// The break this catches: ignoring `If-None-Match`, so every launch downloads the whole app over
/// the phone's connection; or answering 304 to any tag, so a phone keeps an old app.
#[tokio::test]
async fn a_file_the_phone_has_is_not_sent_again() {
let bridge = harness().await;
let first = bridge.get("/app/main.js").send().await.unwrap();
let tag = first.headers()["etag"].to_str().unwrap().to_string();
let again = bridge.get("/app/main.js").header("if-none-match", &tag).send().await.unwrap();
assert_eq!(again.status(), 304);
let stale = bridge.get("/app/main.js").header("if-none-match", "\"old\"").send().await.unwrap();
assert_eq!(stale.status(), 200);
}
/// A path that climbs out of the app's folder finds nothing.
///
/// The break this catches: a debug build reading `app/` from disk resolving `..`, so a phone can
/// read the bridge's source or anything beside it.
#[tokio::test]
async fn app_paths_stay_in_the_app() {
let bridge = harness().await;
for path in
["/app/..%2Fsrc%2Flib.rs", "/app/%2e%2e/Cargo.toml", "/app/vendor/..%2F..%2FCargo.toml"]
{
let response = bridge.get(path).send().await.unwrap();
assert_eq!(response.status(), 404, "{path} answered {}", response.status());
}
}
/// The app's files need the owner's tailnet login like everything else.
///
/// The break this catches: routing the files outside the login check, which shows the app to
/// anyone who can reach the port.
#[tokio::test]
async fn the_app_needs_the_owners_login() {
let bridge = harness().await;
let response = reqwest::get(bridge.url("/app/main.js")).await.unwrap();
assert_eq!(response.status(), 401);
}
/// The theme is a stylesheet of the active theme's properties, never cached as it stands.
///
/// The break this catches: a missing route or the wrong type, which the browser drops, so the app
/// draws in its fallbacks whatever theme you picked; or a cached copy, so a new theme never shows.
#[tokio::test]
async fn the_theme_is_served_as_a_stylesheet() {
let bridge = harness().await;
let response = bridge.get("/theme.css").send().await.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["content-type"], "text/css; charset=utf-8");
assert_eq!(response.headers()["cache-control"], "no-cache");
let css = response.text().await.unwrap();
assert!(css.starts_with(":root {") && css.contains("color-scheme:"), "{css}");
}

View File

@@ -0,0 +1,69 @@
//! How the bridge closes a device's socket, which is how the app tells leaving, an ended session
//! and being unpaired apart from a dropped connection.
use super::*;
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use tokio_tungstenite::tungstenite::protocol::CloseFrame;
/// The close frame the device reads next, skipping any protocol frames before it.
async fn close_frame(device: &mut DeviceSocket) -> Option<CloseFrame> {
let wait = async {
loop {
match device.next().await {
Some(Ok(Message::Close(frame))) => return frame,
Some(Ok(_)) => continue,
other => panic!("the socket ended without a close frame: {other:?}"),
}
}
};
tokio::time::timeout(REVOCATION_CHECK * 3, wait).await.expect("the socket stayed open")
}
/// A device that closes its socket gets the close answered, not a dropped connection.
///
/// The break this catches: dropping the socket as soon as the device's close arrives, so every
/// time the app leaves it sees code 1006 and can't tell that from losing the network.
#[tokio::test]
async fn a_device_that_closes_is_answered() {
let bridge = harness().await;
let mut session = fake_session(bridge.runtime.path());
let (mut device, _joined) = bridge.join(&mut session).await;
device.close(None).await.unwrap();
let answer = tokio::time::timeout(REVOCATION_CHECK, device.next()).await.expect("no answer");
assert!(matches!(answer, Some(Ok(Message::Close(_)))), "answered with {answer:?}");
}
/// A session that ends closes the device's socket normally, saying why.
///
/// The break this catches: dropping the socket when the session goes, so the app retries a
/// session that is gone instead of saying it ended.
#[tokio::test]
async fn a_session_that_ends_closes_the_socket_normally() {
let bridge = harness().await;
let mut session = fake_session(bridge.runtime.path());
let (mut device, joined) = bridge.join(&mut session).await;
drop(joined);
let frame = close_frame(&mut device).await.expect("a close code");
assert_eq!(frame.code, CloseCode::Normal);
assert_eq!(frame.reason, "the session ended");
}
/// Unpairing a connected device closes its open socket, with the code that says so.
///
/// The break this catches: checking the device only at the upgrade, so a lost phone keeps
/// steering a session it already joined; or closing it like any other ending, so the app keeps
/// retrying with a credential that will never work again instead of asking to be paired.
#[tokio::test]
async fn an_unpaired_device_is_told_so() {
let bridge = harness().await;
let mut session = fake_session(bridge.runtime.path());
let (mut device, _joined) = bridge.join(&mut session).await;
let id = bridge.devices.devices()[0].id.clone();
bridge.devices.revoke(&id).unwrap();
let frame = close_frame(&mut device).await.expect("a close code");
assert_eq!(u16::from(frame.code), relay::UNPAIRED);
assert_eq!(frame.reason, "this device was unpaired");
}

View File

@@ -0,0 +1,98 @@
//! What a phone fetches to keep the app on its home screen.
use std::sync::{Arc, Mutex};
use super::*;
/// A renderer that draws a stand-in icon and remembers the sides it was asked for.
#[derive(Default)]
struct Sketch {
asked: Mutex<Vec<u32>>,
}
impl Renderer for Sketch {
fn markdown(&self, text: &str, _voice: Voice) -> String {
text.into()
}
fn tool_glyph(&self, _tool: &str) -> String {
String::new()
}
fn status(&self, _facts: &StatusFacts) -> Vec<StatusSegment> {
Vec::new()
}
fn home_icon(&self, side: u32, _colors: TileColors) -> Option<Vec<u8>> {
self.asked.lock().unwrap().push(side);
Some(b"\x89PNG stand-in".to_vec())
}
}
/// A bridge named for its computer serves the page and the manifest named for it, so a phone
/// paired with two computers keeps two apps it can tell apart.
///
/// The break this catches: the name set on the bridge but never reaching the routes that read it,
/// so both computers' apps are added as "Luxe".
#[tokio::test]
async fn a_named_bridge_serves_an_app_named_for_its_computer() {
let bridge = harness_with(|bridge| bridge.named("desk")).await;
let page = bridge.get("/").send().await.unwrap().text().await.unwrap();
assert!(page.contains(r#"<meta name="luxe-machine" content="desk">"#), "{page}");
let manifest = bridge.get("/manifest.webmanifest").send().await.unwrap();
let manifest: serde_json::Value = manifest.json().await.unwrap();
assert_eq!(manifest["short_name"], "desk");
}
/// The page links the manifest and the icon, and the manifest asks to open on its own.
///
/// The break this catches: the links or the manifest's `display` dropped, so the home screen
/// keeps a bookmark that opens in Safari with its bars, under a screenshot for an icon.
#[tokio::test]
async fn the_page_and_manifest_make_a_home_screen_app() {
let bridge = harness().await;
let page = bridge.get("/").send().await.unwrap().text().await.unwrap();
assert!(page.contains("<link rel=\"manifest\" href=\"/manifest.webmanifest\">"), "{page}");
assert!(page.contains("<link rel=\"apple-touch-icon\" href=\"/icons/180.png\">"), "{page}");
let manifest = bridge.get("/manifest.webmanifest").send().await.unwrap();
assert_eq!(manifest.headers()["content-type"], "application/manifest+json");
let manifest: serde_json::Value = manifest.json().await.unwrap();
assert_eq!(manifest["display"], "standalone");
}
/// The manifest and icon come to the tailnet login alone, without the paired-device cookie.
///
/// The break this catches: the two routed behind the device check, where a manifest fetched
/// without credentials (as browsers fetch one) is turned away and the app installs bare.
#[tokio::test]
async fn the_manifest_and_icon_need_no_paired_device() {
let sketch = Arc::new(Sketch::default());
let bridge = harness_rendering(sketch.clone()).await;
assert_eq!(bridge.get("/manifest.webmanifest").send().await.unwrap().status(), 200);
let icon = bridge.get("/icons/180.png").send().await.unwrap();
assert_eq!(icon.status(), 200);
assert_eq!(icon.headers()["content-type"], "image/png");
assert_eq!(*sketch.asked.lock().unwrap(), [180]);
}
/// Only the sizes the page and manifest name are drawn.
///
/// The break this catches: any size drawn on request, so one URL asks the bridge for a bitmap of
/// gigabytes.
#[tokio::test]
async fn an_icon_is_drawn_only_at_the_sizes_offered() {
let sketch = Arc::new(Sketch::default());
let bridge = harness_rendering(sketch.clone()).await;
for file in ["100000.png", "181.png", "180.svg", "180"] {
let response = bridge.get(&format!("/icons/{file}")).send().await.unwrap();
assert_eq!(response.status(), 404, "{file}");
}
assert!(sketch.asked.lock().unwrap().is_empty());
}
/// A renderer with no art answers no icon, rather than an empty image.
///
/// The break this catches: a 200 with no bytes, which iOS keeps as a blank icon.
#[tokio::test]
async fn a_renderer_without_art_has_no_icon() {
let bridge = harness().await;
assert_eq!(bridge.get("/icons/180.png").send().await.unwrap().status(), 404);
}

View File

@@ -0,0 +1,117 @@
//! A device turning its notifications on and off, and what reaches it once they're on.
use super::*;
use crate::push::Recording;
fn from_safari() -> serde_json::Value {
serde_json::from_str(crate::push::FROM_SAFARI).unwrap()
}
/// A request to `/api/push` from the device with `cookie`.
fn push(bridge: &Harness, method: reqwest::Method, cookie: &str) -> reqwest::RequestBuilder {
let request = reqwest::Client::new().request(method, bridge.url("/api/push"));
request.header("Tailscale-User-Login", OWNER).header("cookie", cookie)
}
async fn status(bridge: &Harness, cookie: &str) -> serde_json::Value {
let response = push(bridge, reqwest::Method::GET, cookie).send().await.unwrap();
assert_eq!(response.status(), 200);
response.json().await.unwrap()
}
/// The break this catches: the push routes outside the paired-device check, so anything on this
/// machine that sets the login header can point the bridge's notifications somewhere.
#[tokio::test]
async fn only_a_paired_device_reaches_its_notifications() {
let bridge = harness().await;
for method in [reqwest::Method::GET, reqwest::Method::PUT, reqwest::Method::DELETE] {
let response = push(&bridge, method.clone(), "luxe_device=nope").send().await.unwrap();
assert_eq!(response.status(), 401, "{method}");
}
}
/// A device gets the key, subscribes, is told it has, and turns it off again.
///
/// The break this catches: any of the three routes not reaching the device book, or the status
/// reporting another device's subscription or none at all.
#[tokio::test]
async fn a_device_turns_its_notifications_on_and_off() {
let bridge = harness().await;
let cookie = bridge.pair().await;
let before = status(&bridge, &cookie).await;
assert_eq!(before["subscribed"], false);
let key = before["key"].as_str().unwrap();
assert_eq!(key.len(), 87, "65 bytes, base64url without padding: {key}");
let on = push(&bridge, reqwest::Method::PUT, &cookie).json(&from_safari()).send().await;
assert_eq!(on.unwrap().status(), 204);
let on = serde_json::json!({ "key": key, "subscribed": true });
assert_eq!(status(&bridge, &cookie).await, on);
assert_eq!(status(&bridge, &bridge.pair().await).await["subscribed"], false, "another's");
let off = push(&bridge, reqwest::Method::DELETE, &cookie).send().await.unwrap();
assert_eq!(off.status(), 204);
assert_eq!(status(&bridge, &cookie).await["subscribed"], false);
}
/// The break this catches: a subscription kept without the check, so a paired device can have
/// the bridge post to a machine on the local network.
#[tokio::test]
async fn a_subscription_to_somewhere_else_is_refused() {
let bridge = harness().await;
let cookie = bridge.pair().await;
let mut elsewhere = from_safari();
elsewhere["endpoint"] = "https://192.168.1.1/push".into();
let response = push(&bridge, reqwest::Method::PUT, &cookie).json(&elsewhere).send().await;
let response = response.unwrap();
assert_eq!(response.status(), 400);
assert!(response.text().await.unwrap().contains("192.168.1.1"));
assert_eq!(status(&bridge, &cookie).await["subscribed"], false);
}
/// Waits up to a minute (of a paused clock, where one is) for `done`.
async fn eventually(mut done: impl FnMut() -> bool) -> bool {
let waited = tokio::time::timeout(std::time::Duration::from_secs(60), async {
while !done() {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
});
waited.await.is_ok()
}
/// The break this catches: presence not taken on join, so a phone showing a session is buzzed
/// about it, or never let go, so it's never notified about that session again.
#[tokio::test]
async fn a_device_counts_as_looking_while_its_socket_is_open() {
let bridge = harness().await;
let mut session = fake_session(bridge.runtime.path());
let (socket, _joined) = bridge.join(&mut session).await;
let id = bridge.devices.devices()[0].id.clone();
assert!(bridge.presence.is_here(&id, SESSION));
drop(socket);
assert!(eventually(|| !bridge.presence.is_here(&id, SESSION)).await, "still looking");
}
const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#;
/// The bridge joins the session once a device subscribes, and posts to that device when a
/// prompt is left waiting, titled with the computer the bridge is named for.
///
/// The break this catches: the notifications never started with the bridge, or started without
/// the device book, the courier or the computer's name it was given.
#[tokio::test(start_paused = true)]
async fn a_prompt_left_waiting_reaches_a_subscribed_device() {
let courier = std::sync::Arc::new(Recording::taking());
let posting = courier.clone();
let bridge = harness_with(move |bridge| bridge.notifying_through(posting).named("desk")).await;
let mut session = fake_session(bridge.runtime.path());
let cookie = bridge.pair().await;
let on = push(&bridge, reqwest::Method::PUT, &cookie).json(&from_safari()).send().await;
assert_eq!(on.unwrap().status(), 204);
let mut watcher = session.listener.accept().await.expect("the bridge joined to watch");
watcher.stream.write_all(format!("{PERMISSION}\n").as_bytes()).await.unwrap();
assert!(eventually(|| !courier.sent().is_empty()).await, "nothing was posted");
assert_eq!(courier.sent(), [from_safari()["endpoint"].as_str().unwrap()]);
assert!(courier.titles()[0].ends_with(" \u{00b7} desk"), "{:?}", courier.titles());
}

View File

@@ -0,0 +1,68 @@
//! `/api/render` as the app calls it.
use super::*;
fn render_request(bridge: &Harness, cookie: Option<&str>) -> reqwest::RequestBuilder {
let request = reqwest::Client::new().post(bridge.url("/api/render"));
let request = request.header("Tailscale-User-Login", OWNER);
match cookie {
Some(cookie) => request.header("cookie", cookie),
None => request,
}
}
/// The break this catches: the route left outside the device check, so the owner's tailnet login
/// alone gets the host to do work for an unpaired browser.
#[tokio::test]
async fn rendering_needs_a_paired_device() {
let bridge = harness().await;
let pieces = serde_json::json!({ "pieces": [{ "kind": "answer", "text": "hi" }] });
let response = render_request(&bridge, None).json(&pieces).send().await.unwrap();
assert_eq!(response.status(), 401);
}
/// Each piece comes back in the order it was asked for, by the bridge's renderer.
///
/// The break this catches: answers out of order, so the app puts one message's HTML under
/// another; or a renderer that doesn't escape, which the plain one a bridge starts with must.
#[tokio::test]
async fn pieces_come_back_in_order() {
let bridge = harness().await;
let cookie = bridge.pair().await;
let pieces = serde_json::json!({ "pieces": [
{ "kind": "answer", "text": "**one** <i>" },
{ "kind": "tool", "name": "bash" },
{ "kind": "user", "content": [{ "type": "text", "content": "three" }] },
]});
let response = render_request(&bridge, Some(&cookie)).json(&pieces).send().await.unwrap();
assert_eq!(response.status(), 200);
let rendered: serde_json::Value = response.json().await.unwrap();
assert_eq!(
rendered,
serde_json::json!({ "html": [
"<p class=\"plain\">**one** &lt;i&gt;</p>",
"",
"<p class=\"words\">three</p>",
]})
);
}
/// The break this catches: the route left at axum's 2 MiB default, so a large diff, which comes
/// back to be rendered as JSON several times its text's size, is refused and never shows.
#[tokio::test]
async fn a_large_diff_can_be_rendered() {
let bridge = harness().await;
let cookie = bridge.pair().await;
let line = serde_json::json!({ "old_line": null, "new_line": 1, "kind": "addition", "text": "x".repeat(80) });
let hunk = serde_json::json!({ "id": "hunk:a", "old_range": { "start": 0, "count": 0 },
"new_range": { "start": 1, "count": 30000 }, "heading": null, "symbol": null,
"lines": vec![line; 30_000], "noise": "semantic" });
let file = serde_json::json!({ "id": "file:a", "old_path": null, "new_path": "big.txt",
"status": "added", "language": null, "additions": 30000, "deletions": 0, "hunks": [hunk],
"binary": false, "generated": false, "non_text": null });
let piece = serde_json::json!({ "kind": "diff", "diff": { "path": "big.txt", "file": file, "untracked": false } });
let body = serde_json::json!({ "pieces": [piece] });
assert!(body.to_string().len() > 3 * 1024 * 1024, "the request outgrows the default");
let response = render_request(&bridge, Some(&cookie)).json(&body).send().await.unwrap();
assert_eq!(response.status(), 200);
}