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:
@@ -8,7 +8,7 @@ mod permission_mode;
|
||||
pub(crate) use commands::*;
|
||||
pub(crate) use permission_mode::PermissionModeArg;
|
||||
|
||||
/// Luxe — a fast, lean, security-conscious agentic coding harness.
|
||||
/// Luxe's command line. `--help` shows the crate description from `Cargo.toml`, not this doc.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "luxe", version, about)]
|
||||
pub(crate) struct Args {
|
||||
@@ -183,11 +183,14 @@ impl Args {
|
||||
| SubCommand::Docs(_)
|
||||
| SubCommand::Doctor
|
||||
| SubCommand::Init(_)
|
||||
| SubCommand::Join(_)
|
||||
| SubCommand::Models(_)
|
||||
| SubCommand::Sessions(_)
|
||||
| SubCommand::Update(_)
|
||||
| SubCommand::Wire(_),
|
||||
) => false,
|
||||
#[cfg(feature = "remote")]
|
||||
Some(SubCommand::Remote(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,12 +256,15 @@ impl Args {
|
||||
| SubCommand::Docs(_)
|
||||
| SubCommand::Doctor
|
||||
| SubCommand::Init(_)
|
||||
| SubCommand::Join(_)
|
||||
| SubCommand::Mcp(_)
|
||||
| SubCommand::Models(_)
|
||||
| SubCommand::Sessions(_)
|
||||
| SubCommand::Update(_)
|
||||
| SubCommand::Wire(_),
|
||||
) => false,
|
||||
#[cfg(feature = "remote")]
|
||||
Some(SubCommand::Remote(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,12 @@ pub(crate) enum SubCommand {
|
||||
Doctor,
|
||||
/// Set Luxe up: a theme, a provider, the tools and the start screen.
|
||||
Init(InitArgs),
|
||||
/// Join a session another Luxe on this machine is running, speaking the `--rpc` protocol on
|
||||
/// stdin and stdout.
|
||||
Join(JoinArgs),
|
||||
/// Serve your sessions to your own phone or tablet, through Tailscale.
|
||||
#[cfg(feature = "remote")]
|
||||
Remote(RemoteArgs),
|
||||
/// Run the agent through a phased plan on its own.
|
||||
Loop(LoopArgs),
|
||||
/// Add, list and sign in to MCP servers.
|
||||
@@ -139,6 +145,70 @@ pub(crate) struct InitArgs {
|
||||
pub(crate) defaults: bool,
|
||||
}
|
||||
|
||||
/// Join arguments.
|
||||
#[derive(Parser, Debug)]
|
||||
pub(crate) struct JoinArgs {
|
||||
/// The session: its id or the start of it, or the process id of the Luxe running it. Omit
|
||||
/// it to join the one running in this folder.
|
||||
pub(crate) target: Option<String>,
|
||||
/// List the sessions running on this machine that can be joined, and exit.
|
||||
#[arg(long, conflicts_with = "target")]
|
||||
pub(crate) list: bool,
|
||||
}
|
||||
|
||||
/// Remote arguments.
|
||||
#[cfg(feature = "remote")]
|
||||
#[derive(Parser, Debug)]
|
||||
pub(crate) struct RemoteArgs {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Option<RemoteCommand>,
|
||||
/// The port to listen on, on this machine only.
|
||||
#[arg(long, default_value_t = 4519, global = true)]
|
||||
pub(crate) port: u16,
|
||||
/// Also let this tailnet login in, besides this machine's owner (repeatable).
|
||||
#[arg(long = "allow", value_name = "LOGIN", global = true)]
|
||||
pub(crate) allow: Vec<String>,
|
||||
}
|
||||
|
||||
/// Remote subcommand — pair and manage your devices.
|
||||
#[cfg(feature = "remote")]
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum RemoteCommand {
|
||||
/// Check Tailscale, publish the bridge on your tailnet, start it at login, and pair a device.
|
||||
Setup,
|
||||
/// Show a QR code and link that pair one phone or tablet, good for ten minutes.
|
||||
Pair,
|
||||
/// List the paired devices.
|
||||
Devices {
|
||||
#[command(subcommand)]
|
||||
command: Option<DevicesCommand>,
|
||||
},
|
||||
/// Manage the user service that runs the bridge at login.
|
||||
Service {
|
||||
#[command(subcommand)]
|
||||
command: ServiceCommand,
|
||||
},
|
||||
}
|
||||
|
||||
/// Service subcommand.
|
||||
#[cfg(feature = "remote")]
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum ServiceCommand {
|
||||
/// Stop the service and stop it starting at login.
|
||||
Remove,
|
||||
}
|
||||
|
||||
/// Devices subcommand.
|
||||
#[cfg(feature = "remote")]
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum DevicesCommand {
|
||||
/// Unpair a device and close its open sessions.
|
||||
Revoke {
|
||||
/// The device's id, from `luxe remote devices`
|
||||
id: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Sessions arguments.
|
||||
#[derive(Parser, Debug)]
|
||||
pub(crate) struct SessionsArgs {
|
||||
|
||||
128
crates/luxe-cli/src/cli/join_command.rs
Normal file
128
crates/luxe-cli/src/cli/join_command.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
//! `luxe join` — a session another Luxe is running, over stdin and stdout.
|
||||
//!
|
||||
//! The running Luxe shares its session on a local endpoint (`cli::share`), and this command is the
|
||||
//! plain way in: it picks the session from the records in the runtime folder, connects, and copies
|
||||
//! bytes both ways. What crosses is the `--rpc` protocol untouched, so a client written for
|
||||
//! `luxe --rpc` drives a joined session by launching `luxe join` instead.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Context;
|
||||
use luxe_core::local_endpoint::{self, LiveSession};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
use super::args::JoinArgs;
|
||||
|
||||
/// List the joinable sessions, or join one and pass the protocol through until either side ends.
|
||||
pub(crate) async fn run_join_command(args: JoinArgs, work_root: &Path) -> anyhow::Result<()> {
|
||||
let running = local_endpoint::running_sessions(&luxe_core::user_dirs::luxe_runtime_dir());
|
||||
if args.list {
|
||||
print!("{}", listing(&running));
|
||||
return Ok(());
|
||||
}
|
||||
let cwd = work_root.to_string_lossy();
|
||||
let session = pick(&running, args.target.as_deref(), &cwd)?;
|
||||
let stream = local_endpoint::connect(&session.address)
|
||||
.await
|
||||
.with_context(|| format!("could not join session {}", session.session_id))?;
|
||||
pass_through(stream).await
|
||||
}
|
||||
|
||||
/// The session `target` names, or with no target the only one running in `cwd`.
|
||||
fn pick<'a>(
|
||||
running: &'a [LiveSession],
|
||||
target: Option<&str>,
|
||||
cwd: &str,
|
||||
) -> anyhow::Result<&'a LiveSession> {
|
||||
let matching: Vec<&LiveSession> = match target {
|
||||
Some(target) => running.iter().filter(|session| names(session, target)).collect(),
|
||||
None => running.iter().filter(|session| session.cwd == cwd).collect(),
|
||||
};
|
||||
match matching.as_slice() {
|
||||
[only] => Ok(only),
|
||||
[] => anyhow::bail!("{}", nothing_to_join(running, target, cwd)),
|
||||
several => anyhow::bail!(
|
||||
"{} sessions match; name one by id or process:\n{}",
|
||||
several.len(),
|
||||
listing_of(several.iter().copied())
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `target` is the session's process id or the start of its id.
|
||||
fn names(session: &LiveSession, target: &str) -> bool {
|
||||
let target = target.trim();
|
||||
!target.is_empty()
|
||||
&& (session.session_id.starts_with(target) || target == session.pid.to_string())
|
||||
}
|
||||
|
||||
fn nothing_to_join(running: &[LiveSession], target: Option<&str>, cwd: &str) -> String {
|
||||
let wanted = match target {
|
||||
Some(target) => format!("no running session matches `{target}`"),
|
||||
None => format!("no session is running in {cwd}"),
|
||||
};
|
||||
if running.is_empty() {
|
||||
return format!(
|
||||
"{wanted}, and none is running on this machine that can be joined. A Luxe shares \
|
||||
its session unless `joinable` is off or LUXE_JOINABLE=0."
|
||||
);
|
||||
}
|
||||
format!("{wanted}. These can be joined:\n{}", listing(running))
|
||||
}
|
||||
|
||||
fn listing(running: &[LiveSession]) -> String {
|
||||
listing_of(running.iter())
|
||||
}
|
||||
|
||||
fn listing_of<'a>(sessions: impl Iterator<Item = &'a LiveSession>) -> String {
|
||||
sessions
|
||||
.map(|session| format!("{} pid {} {}\n", session.session_id, session.pid, session.cwd))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Copy stdin to the session and the session to stdout. Ends when the session closes the
|
||||
/// connection, which it also does once it has read the end of our stdin.
|
||||
async fn pass_through(stream: local_endpoint::LocalStream) -> anyhow::Result<()> {
|
||||
let (mut from_session, mut to_session) = tokio::io::split(stream);
|
||||
let mut input = read_stdin();
|
||||
let upload = tokio::spawn(async move {
|
||||
while let Some(chunk) = input.recv().await {
|
||||
if to_session.write_all(&chunk).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = to_session.shutdown().await;
|
||||
});
|
||||
let mut stdout = tokio::io::stdout();
|
||||
let downloaded = tokio::io::copy(&mut from_session, &mut stdout).await;
|
||||
upload.abort();
|
||||
downloaded.context("the joined session's output stopped")?;
|
||||
stdout.flush().await.context("could not write to stdout")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stdin, read on a thread of its own. Tokio's stdin reads on its blocking pool, and the runtime
|
||||
/// waits for that read on the way out, so a session that closes first would leave `luxe join`
|
||||
/// hanging until the next keystroke. A plain thread is simply abandoned at exit.
|
||||
fn read_stdin() -> tokio::sync::mpsc::Receiver<Vec<u8>> {
|
||||
let (chunks, received) = tokio::sync::mpsc::channel(16);
|
||||
std::thread::spawn(move || {
|
||||
let mut stdin = std::io::stdin().lock();
|
||||
let mut buffer = vec![0; 8192];
|
||||
loop {
|
||||
let read = match std::io::Read::read(&mut stdin, &mut buffer) {
|
||||
Ok(0) => return,
|
||||
Ok(read) => read,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return tracing::warn!(%error, "stopped reading stdin"),
|
||||
};
|
||||
if chunks.blocking_send(buffer[..read].to_vec()).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
received
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
75
crates/luxe-cli/src/cli/join_command/tests.rs
Normal file
75
crates/luxe-cli/src/cli/join_command/tests.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use super::*;
|
||||
|
||||
fn running(pid: u32, session_id: &str, cwd: &str) -> LiveSession {
|
||||
LiveSession {
|
||||
pid,
|
||||
session_id: session_id.to_string(),
|
||||
cwd: cwd.to_string(),
|
||||
address: format!("/run/luxe/{pid}.sock"),
|
||||
luxe_version: "0.1.3".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sessions() -> Vec<LiveSession> {
|
||||
vec![
|
||||
running(101, "aaaa-1111", "/work/app"),
|
||||
running(202, "aaab-2222", "/work/site"),
|
||||
running(303, "cccc-3333", "/work/site"),
|
||||
]
|
||||
}
|
||||
|
||||
/// With no target, the session running in this folder is the one joined.
|
||||
///
|
||||
/// The break this catches: ignoring the folder, so `luxe join` in one project lands in another's
|
||||
/// session, or refuses because more than one Luxe is running somewhere.
|
||||
#[test]
|
||||
fn no_target_joins_the_session_running_here() {
|
||||
let all = sessions();
|
||||
assert_eq!(pick(&all, None, "/work/app").unwrap().pid, 101);
|
||||
}
|
||||
|
||||
/// Two sessions in one folder are named, not guessed between.
|
||||
///
|
||||
/// The break this catches: taking the first match, which joins whichever pid sorts lower.
|
||||
#[test]
|
||||
fn two_sessions_in_the_folder_are_listed_not_guessed() {
|
||||
let all = sessions();
|
||||
let error = pick(&all, None, "/work/site").unwrap_err().to_string();
|
||||
assert!(error.contains("2 sessions match"), "{error}");
|
||||
assert!(error.contains("aaab-2222") && error.contains("cccc-3333"), "{error}");
|
||||
}
|
||||
|
||||
/// A target names a session by the start of its id or by its Luxe's process id.
|
||||
///
|
||||
/// The break this catches: matching the id exactly, so the short form the listing invites fails,
|
||||
/// or not accepting a pid, which is what `ps` and herdr show.
|
||||
#[test]
|
||||
fn a_target_is_an_id_prefix_or_a_pid() {
|
||||
let all = sessions();
|
||||
assert_eq!(pick(&all, Some("cccc"), "/elsewhere").unwrap().pid, 303);
|
||||
assert_eq!(pick(&all, Some("202"), "/elsewhere").unwrap().session_id, "aaab-2222");
|
||||
}
|
||||
|
||||
/// A prefix two ids share is refused, and so is an empty one.
|
||||
///
|
||||
/// The break this catches: an empty target matching every id as a prefix of all of them.
|
||||
#[test]
|
||||
fn an_ambiguous_or_empty_target_is_refused() {
|
||||
let all = sessions();
|
||||
assert!(pick(&all, Some("aaa"), "/work/app").is_err());
|
||||
assert!(!names(&all[0], " "));
|
||||
}
|
||||
|
||||
/// Nothing to join says why, and how sharing is turned back on when nothing is running.
|
||||
///
|
||||
/// The break this catches: a bare "not found" when every Luxe has `joinable` off, which leaves the
|
||||
/// reader with nothing to try.
|
||||
#[test]
|
||||
fn nothing_to_join_says_what_is_running() {
|
||||
let none = pick(&[], None, "/work/app").unwrap_err().to_string();
|
||||
assert!(none.contains("joinable"), "{none}");
|
||||
let all = sessions();
|
||||
let elsewhere = pick(&all, None, "/work/other").unwrap_err().to_string();
|
||||
assert!(elsewhere.contains("no session is running in /work/other"), "{elsewhere}");
|
||||
assert!(elsewhere.contains("aaaa-1111 pid 101 /work/app"), "{elsewhere}");
|
||||
}
|
||||
152
crates/luxe-cli/src/cli/remote_command.rs
Normal file
152
crates/luxe-cli/src/cli/remote_command.rs
Normal file
@@ -0,0 +1,152 @@
|
||||
//! `luxe remote` — the bridge that serves this machine's sessions to your own devices.
|
||||
//!
|
||||
//! The serving is `luxe_remote`'s; this is the terminal around it: who is let in, where it
|
||||
//! listens, setting it up, pairing and revoking devices, and stopping on Ctrl-C.
|
||||
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::Context;
|
||||
use luxe_remote::{Access, DeviceBook, Tailnet};
|
||||
|
||||
use super::args::{DevicesCommand, RemoteArgs, RemoteCommand, ServiceCommand};
|
||||
use crate::output::outln;
|
||||
|
||||
mod invitation;
|
||||
mod render;
|
||||
mod setup;
|
||||
|
||||
/// Runs `luxe remote` and its subcommands.
|
||||
pub(crate) async fn run_remote_command(args: RemoteArgs) -> anyhow::Result<()> {
|
||||
let devices = DeviceBook::at(DeviceBook::default_path());
|
||||
match args.command {
|
||||
None => serve(args.port, args.allow, devices).await,
|
||||
Some(RemoteCommand::Setup) => setup::setup(args.port, args.allow, &devices).await,
|
||||
Some(RemoteCommand::Pair) => invitation::pair(args.port, &devices).await,
|
||||
Some(RemoteCommand::Devices { command: None }) => list_devices(&devices),
|
||||
Some(RemoteCommand::Devices { command: Some(DevicesCommand::Revoke { id }) }) => {
|
||||
revoke(&devices, &id)
|
||||
}
|
||||
Some(RemoteCommand::Service { command: ServiceCommand::Remove }) => remove_service(),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_service() -> anyhow::Result<()> {
|
||||
match luxe_remote::service::remove()? {
|
||||
true => outln!("The bridge's service is stopped and won't start at login."),
|
||||
false => outln!("No service for the bridge is installed."),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serves until Ctrl-C.
|
||||
async fn serve(port: u16, allow: Vec<String>, devices: DeviceBook) -> anyhow::Result<()> {
|
||||
let tailnet = luxe_remote::this_machine().await;
|
||||
let machine = tailnet.as_ref().ok().map(|tailnet| tailnet.machine().to_owned());
|
||||
let logins = allowed_logins(tailnet, allow)?;
|
||||
let access = Access { logins: logins.clone(), devices };
|
||||
let bridge = bridge(port, access, machine).await?;
|
||||
outln!("Luxe remote is listening on http://{}. Ctrl-C stops it.", bridge.address());
|
||||
outln!("It lets in {}, from a paired device.", logins.join(", "));
|
||||
bridge
|
||||
.serve(async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bridge `luxe remote` runs: starting sessions with this luxe, drawing them as the TUI does,
|
||||
/// and named for the computer when Tailscale said what it's called.
|
||||
async fn bridge(
|
||||
port: u16,
|
||||
access: Access,
|
||||
machine: Option<String>,
|
||||
) -> anyhow::Result<luxe_remote::Bridge> {
|
||||
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
||||
let runtime_dir = luxe_core::user_dirs::luxe_runtime_dir();
|
||||
let luxe = std::env::current_exe()
|
||||
.map_err(|error| anyhow::anyhow!("could not find this luxe to start sessions: {error}"))?;
|
||||
let bridge = luxe_remote::Bridge::bind(address, runtime_dir, access).await?;
|
||||
let bridge = bridge.starting_sessions(luxe);
|
||||
let bridge = bridge.rendering_with(std::sync::Arc::new(render::TuiRenderer));
|
||||
Ok(match machine {
|
||||
Some(machine) => bridge.named(machine),
|
||||
None => bridge,
|
||||
})
|
||||
}
|
||||
|
||||
/// The owner, as Tailscale reports them, plus any `--allow`ed logins. Without the owner, only an
|
||||
/// explicit `--allow` lets anyone in: guessing would mean an allowlist nobody chose.
|
||||
fn allowed_logins(
|
||||
owner: Result<Tailnet, luxe_remote::TailnetError>,
|
||||
mut allow: Vec<String>,
|
||||
) -> anyhow::Result<Vec<String>> {
|
||||
match owner {
|
||||
Ok(tailnet) => allow.insert(0, tailnet.login),
|
||||
Err(error) if allow.is_empty() => {
|
||||
return Err(error).context(
|
||||
"couldn't learn this machine's tailnet login; pass `--allow <login>` to name who \
|
||||
may use the bridge",
|
||||
);
|
||||
}
|
||||
Err(error) => tracing::warn!(%error, "serving only the --allow logins"),
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
allow.retain(|login| seen.insert(login.clone()));
|
||||
Ok(allow)
|
||||
}
|
||||
|
||||
fn list_devices(devices: &DeviceBook) -> anyhow::Result<()> {
|
||||
let paired = devices.devices();
|
||||
if paired.is_empty() {
|
||||
outln!("No devices are paired. Pair one with `luxe remote pair`.");
|
||||
return Ok(());
|
||||
}
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_secs());
|
||||
for device in paired {
|
||||
let age = age(now.saturating_sub(device.paired_at));
|
||||
outln!(" {} {} ({}, paired {age})", device.id, device.name, device.login);
|
||||
}
|
||||
outln!("\nUnpair one with `luxe remote devices revoke <id>`.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn revoke(devices: &DeviceBook, id: &str) -> anyhow::Result<()> {
|
||||
match devices.revoke(id)? {
|
||||
Some(device) => outln!("Unpaired {} ({id}); its open sessions close too.", device.name),
|
||||
None => anyhow::bail!("no paired device has the id {id}; see `luxe remote devices`"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How long ago, in the largest whole unit that fits.
|
||||
fn age(seconds: u64) -> String {
|
||||
const DAY: u64 = 24 * 60 * 60;
|
||||
match seconds / DAY {
|
||||
0 => "today".to_string(),
|
||||
1 => "yesterday".to_string(),
|
||||
days => format!("{days} days ago"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The owner always leads the allowlist, and nobody is let in when no one was named.
|
||||
///
|
||||
/// The break this catches: serving an empty allowlist when Tailscale can't be asked (which
|
||||
/// shuts everyone out with no reason given), or dropping the owner once `--allow` is used.
|
||||
#[test]
|
||||
fn the_allowlist_is_the_owner_and_whoever_is_named() {
|
||||
let owner = || Ok(Tailnet { login: "alex@github".into(), dns_name: "desk".into() });
|
||||
let missing = || Err(luxe_remote::TailnetError::NotInstalled);
|
||||
let both = allowed_logins(owner(), vec!["sam@github".into()]).unwrap();
|
||||
assert_eq!(both, ["alex@github", "sam@github"]);
|
||||
let repeated = allowed_logins(owner(), vec!["alex@github".into()]).unwrap();
|
||||
assert_eq!(repeated, ["alex@github"]);
|
||||
assert_eq!(allowed_logins(missing(), vec!["sam@github".into()]).unwrap(), ["sam@github"]);
|
||||
assert!(allowed_logins(missing(), vec![]).is_err());
|
||||
}
|
||||
}
|
||||
80
crates/luxe-cli/src/cli/remote_command/invitation.rs
Normal file
80
crates/luxe-cli/src/cli/remote_command/invitation.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
//! The invitation a phone scans: a QR code in the terminal, and the same link in words.
|
||||
|
||||
use std::io::Write;
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
|
||||
use std::time::Duration;
|
||||
|
||||
use luxe_remote::{DeviceBook, Tailnet};
|
||||
use qrcode::render::unicode::Dense1x2;
|
||||
use qrcode::QrCode;
|
||||
|
||||
use crate::output::outln;
|
||||
|
||||
/// `luxe remote pair`: one invitation, shown.
|
||||
pub(super) async fn pair(port: u16, devices: &DeviceBook) -> anyhow::Result<()> {
|
||||
match luxe_remote::this_machine().await {
|
||||
Ok(tailnet) => show(port, devices, &tailnet),
|
||||
Err(error) => {
|
||||
let token = devices.invite()?;
|
||||
outln!("Tailscale couldn't name this machine ({error}).");
|
||||
outln!("Open /pair on the bridge's tailnet address and add #{token} to it.");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Issues an invitation and shows it as a QR code and a link to `https://<this machine>/pair`.
|
||||
///
|
||||
/// The invitation rides in the link's fragment, which a browser never sends to a server, so it
|
||||
/// stays out of Serve's and the bridge's logs.
|
||||
pub(super) fn show(port: u16, devices: &DeviceBook, tailnet: &Tailnet) -> anyhow::Result<()> {
|
||||
let token = devices.invite()?;
|
||||
let link = format!("https://{}/pair#{token}", tailnet.dns_name);
|
||||
if let Some(code) = qr(&link) {
|
||||
outln!("{code}");
|
||||
}
|
||||
outln!("On the phone or tablet: install Tailscale, sign in as {}, then", tailnet.login);
|
||||
outln!("scan this or open the link. It pairs one device, within ten minutes.\n");
|
||||
outln!(" {link}\n");
|
||||
if !bridge_listening(port) {
|
||||
outln!("The bridge isn't running yet: start it with `luxe remote` before scanning.");
|
||||
}
|
||||
let _ = std::io::stdout().flush();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `text` as a QR code drawn in half-height blocks, light modules as blocks so it reads on the
|
||||
/// dark background most terminals have.
|
||||
fn qr(text: &str) -> Option<String> {
|
||||
let code = QrCode::new(text.as_bytes()).ok()?;
|
||||
let drawn = code
|
||||
.render::<Dense1x2>()
|
||||
.dark_color(Dense1x2::Light)
|
||||
.light_color(Dense1x2::Dark)
|
||||
.quiet_zone(true)
|
||||
.build();
|
||||
Some(drawn)
|
||||
}
|
||||
|
||||
/// Whether something answers on the bridge's port.
|
||||
pub(super) fn bridge_listening(port: u16) -> bool {
|
||||
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
||||
TcpStream::connect_timeout(&address, Duration::from_millis(500)).is_ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The code is drawn with modules as blocks and a quiet zone a camera can find.
|
||||
///
|
||||
/// The break this catches: losing the quiet zone or the inversion, either of which leaves a
|
||||
/// code most phone cameras won't pick out of a dark terminal.
|
||||
#[test]
|
||||
fn the_code_has_a_quiet_zone_of_blocks() {
|
||||
let code = qr("https://desk.tail1234.ts.net/pair#abc").unwrap();
|
||||
let first = code.lines().next().unwrap();
|
||||
assert!(first.chars().all(|c| c == '\u{2588}'), "the border is solid: {first:?}");
|
||||
assert!(code.lines().count() > 10);
|
||||
}
|
||||
}
|
||||
255
crates/luxe-cli/src/cli/remote_command/render.rs
Normal file
255
crates/luxe-cli/src/cli/remote_command/render.rs
Normal file
@@ -0,0 +1,255 @@
|
||||
//! The TUI's renderer, handed to the bridge so the phone draws text the way the terminal does.
|
||||
|
||||
use luxe_remote::{StatusFacts, StatusSegment, StatusTone};
|
||||
use luxe_tui::markdown::html;
|
||||
use luxe_tui::statusline::plain;
|
||||
|
||||
/// Markdown, highlighting, tool glyphs and the status line's wording from `luxe-tui`.
|
||||
pub(super) struct TuiRenderer;
|
||||
|
||||
impl luxe_remote::Renderer for TuiRenderer {
|
||||
fn markdown(&self, text: &str, voice: luxe_remote::Voice) -> String {
|
||||
let voice = match voice {
|
||||
luxe_remote::Voice::Answer => html::Voice::Answer,
|
||||
luxe_remote::Voice::Reasoning => html::Voice::Reasoning,
|
||||
};
|
||||
html::render(text, voice)
|
||||
}
|
||||
|
||||
fn tool_glyph(&self, tool: &str) -> String {
|
||||
// the app's font has the Nerd Font marks whatever this terminal can draw
|
||||
luxe_tui::widgets::tool_icon(tool).at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
|
||||
}
|
||||
|
||||
fn status(&self, facts: &StatusFacts) -> Vec<StatusSegment> {
|
||||
let facts = plain::Facts {
|
||||
model: facts.model.as_ref(),
|
||||
thinking: facts.thinking,
|
||||
context: facts.context.map(|usage| (usage.used_tokens, usage.context_window)),
|
||||
plan: facts.plan.as_ref(),
|
||||
session: facts.session.as_ref(),
|
||||
};
|
||||
plain::segments(&facts).into_iter().map(status_segment).collect()
|
||||
}
|
||||
|
||||
fn image_glyph(&self) -> String {
|
||||
luxe_tui::glyphs::Icon::Image.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
|
||||
}
|
||||
|
||||
fn code_line(&self, text: &str, language: Option<&str>) -> String {
|
||||
html::code_line(text, language)
|
||||
}
|
||||
|
||||
fn todo_mark(&self, status: luxe_core::TodoSummaryStatus) -> String {
|
||||
luxe_tui::marks::todo(status, luxe_tui::glyphs::GlyphTier::Nerd).to_string()
|
||||
}
|
||||
|
||||
fn change_mark(&self, status: luxe_core::workspace::FileChangeStatus) -> String {
|
||||
luxe_tui::marks::change(status).to_string()
|
||||
}
|
||||
|
||||
fn file_mark(&self, name: &str) -> luxe_remote::FileMark {
|
||||
// the extension, as the TUI's tree reads it for a file's mark
|
||||
let extension = name.rsplit_once('.').map_or("", |(_, extension)| extension);
|
||||
let icon = luxe_tui::widgets::language_icon(&extension.to_ascii_lowercase());
|
||||
let glyph = icon.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string();
|
||||
luxe_remote::FileMark { glyph, hue: mark_hue(luxe_tui::widgets::language_hue_role(icon)) }
|
||||
}
|
||||
|
||||
fn folder_mark(&self) -> String {
|
||||
luxe_tui::glyphs::Icon::Folder.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
|
||||
}
|
||||
|
||||
fn branch_mark(&self) -> String {
|
||||
luxe_tui::glyphs::Icon::Branch.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
|
||||
}
|
||||
|
||||
fn mode_mark(&self, mode: &str) -> String {
|
||||
luxe_tui::modes::icon(mode).at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
|
||||
}
|
||||
|
||||
fn github_marks(&self) -> luxe_remote::GithubMarks {
|
||||
use luxe_tui::glyphs::{GlyphTier::Nerd, Icon, Mark};
|
||||
luxe_remote::GithubMarks {
|
||||
pull_request: Icon::PullRequest.at(Nerd).to_owned(),
|
||||
issue: Icon::Issue.at(Nerd).to_owned(),
|
||||
yes: Mark::Yes.at(Nerd).to_owned(),
|
||||
no: Mark::No.at(Nerd).to_owned(),
|
||||
waiting: Mark::Waiting.at(Nerd).to_owned(),
|
||||
elision: Mark::Elision.at(Nerd).to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn ago(&self, at: u64, now: u64) -> String {
|
||||
luxe_tui::github_detail::ago(at, now)
|
||||
}
|
||||
|
||||
fn github_readable(&self, body: &str) -> String {
|
||||
luxe_tui::github_detail::readable(body)
|
||||
}
|
||||
|
||||
fn home_icon(&self, side: u32, colors: luxe_remote::TileColors) -> Option<Vec<u8>> {
|
||||
luxe_tui::widgets::tile_png(side, colors.plate, colors.ink)
|
||||
.inspect_err(|error| tracing::warn!(%error, side, "could not draw the app icon"))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_hue(hue: luxe_tui::widgets::LanguageHue) -> luxe_remote::MarkHue {
|
||||
use luxe_remote::MarkHue;
|
||||
use luxe_tui::widgets::LanguageHue;
|
||||
match hue {
|
||||
LanguageHue::Warning => MarkHue::Warning,
|
||||
LanguageHue::Info => MarkHue::Info,
|
||||
LanguageHue::Success => MarkHue::Success,
|
||||
LanguageHue::Error => MarkHue::Error,
|
||||
LanguageHue::ThinkingUltra => MarkHue::ThinkingUltra,
|
||||
LanguageHue::Text => MarkHue::Text,
|
||||
LanguageHue::Muted => MarkHue::Muted,
|
||||
}
|
||||
}
|
||||
|
||||
fn status_segment(segment: plain::Segment) -> StatusSegment {
|
||||
let kind = match segment.kind {
|
||||
plain::Kind::Context => "context",
|
||||
plain::Kind::Cost => "cost",
|
||||
plain::Kind::Thinking => "thinking",
|
||||
plain::Kind::Model => "model",
|
||||
};
|
||||
let tone = match segment.tone {
|
||||
plain::Tone::Plain => StatusTone::Plain,
|
||||
plain::Tone::Warning => StatusTone::Warning,
|
||||
plain::Tone::Error => StatusTone::Error,
|
||||
};
|
||||
StatusSegment { kind, glyph: segment.glyph.map(str::to_string), label: segment.label, tone }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use luxe_remote::{Renderer, Voice};
|
||||
|
||||
use super::TuiRenderer;
|
||||
|
||||
/// The break this catches: the voices crossed, so reasoning loses its line breaks and an
|
||||
/// answer keeps the model's.
|
||||
#[test]
|
||||
fn each_voice_reaches_the_tui_as_itself() {
|
||||
assert_eq!(TuiRenderer.markdown("a\nb", Voice::Reasoning), "<p>a<br>b</p>");
|
||||
assert_eq!(TuiRenderer.markdown("a\nb", Voice::Answer), "<p>a b</p>");
|
||||
}
|
||||
|
||||
/// The break this catches: the glyph taken at this terminal's tier, which is ASCII or none
|
||||
/// under a plain terminal, though the app's font always has the marks.
|
||||
#[test]
|
||||
fn tool_glyphs_are_the_nerd_font_marks() {
|
||||
let nerd = luxe_tui::widgets::tool_icon("bash").at(luxe_tui::glyphs::GlyphTier::Nerd);
|
||||
luxe_tui::glyphs::set_tier(luxe_tui::glyphs::GlyphTier::Ascii);
|
||||
let glyph = TuiRenderer.tool_glyph("bash");
|
||||
let image = TuiRenderer.image_glyph();
|
||||
let done = TuiRenderer.todo_mark(luxe_core::TodoSummaryStatus::Completed);
|
||||
luxe_tui::glyphs::set_tier(luxe_tui::glyphs::GlyphTier::Nerd);
|
||||
assert_eq!(glyph, nerd);
|
||||
let nerd_image = luxe_tui::glyphs::Icon::Image.at(luxe_tui::glyphs::GlyphTier::Nerd);
|
||||
assert_eq!(image, nerd_image, "an attached image's mark too");
|
||||
let nerd_done = luxe_tui::glyphs::Mark::Yes.at(luxe_tui::glyphs::GlyphTier::Nerd);
|
||||
assert_eq!(done, nerd_done, "a todo's mark too");
|
||||
}
|
||||
|
||||
/// The break this catches: a diff row's code left plain, or a changed file's letter crossed,
|
||||
/// so the phone's dock and diffs stop matching the TUI's.
|
||||
#[test]
|
||||
fn diffs_and_changes_reach_the_tui() {
|
||||
let code = TuiRenderer.code_line("fn a() {}", Some("rs"));
|
||||
assert!(code.starts_with("<span class=\"t-accent-secondary\">fn</span>"), "{code}");
|
||||
let modified = luxe_core::workspace::FileChangeStatus::Modified;
|
||||
assert_eq!(TuiRenderer.change_mark(modified), "M");
|
||||
}
|
||||
|
||||
/// The break this catches: a file's mark read from the whole name or a cased extension, a
|
||||
/// language's hue crossed with another's, or the folder's mark taken at this terminal's tier,
|
||||
/// so the phone's tree stops matching the TUI's.
|
||||
#[test]
|
||||
fn tree_marks_are_the_tui_language_marks() {
|
||||
use luxe_remote::MarkHue;
|
||||
use luxe_tui::glyphs::{GlyphTier, Icon};
|
||||
let nerd = |icon: Icon| icon.at(GlyphTier::Nerd).to_string();
|
||||
luxe_tui::glyphs::set_tier(GlyphTier::Ascii);
|
||||
let rust = TuiRenderer.file_mark("main.RS");
|
||||
let toml = TuiRenderer.file_mark("Cargo.toml");
|
||||
let folder = TuiRenderer.folder_mark();
|
||||
luxe_tui::glyphs::set_tier(GlyphTier::Nerd);
|
||||
assert_eq!(
|
||||
rust,
|
||||
luxe_remote::FileMark { glyph: nerd(Icon::LangRust), hue: MarkHue::Warning }
|
||||
);
|
||||
assert_eq!(
|
||||
toml,
|
||||
luxe_remote::FileMark { glyph: nerd(Icon::LangToml), hue: MarkHue::Error }
|
||||
);
|
||||
assert_eq!(TuiRenderer.file_mark("Makefile").hue, MarkHue::Muted);
|
||||
assert_eq!(folder, nerd(Icon::Folder));
|
||||
}
|
||||
|
||||
/// The break this catches: the project panel's branch drawn with another mark than the TUI's
|
||||
/// project section, or at this terminal's tier rather than the phone's.
|
||||
#[test]
|
||||
fn the_branch_mark_is_the_tui_branch_mark() {
|
||||
use luxe_tui::glyphs::{GlyphTier, Icon};
|
||||
luxe_tui::glyphs::set_tier(GlyphTier::Ascii);
|
||||
let branch = TuiRenderer.branch_mark();
|
||||
luxe_tui::glyphs::set_tier(GlyphTier::Nerd);
|
||||
assert_eq!(branch, Icon::Branch.at(GlyphTier::Nerd));
|
||||
}
|
||||
|
||||
/// The break this catches: a GitHub mark taken at this terminal's tier or crossed with
|
||||
/// another, ages in other words than the TUI's, or a body's HTML left as tags.
|
||||
#[test]
|
||||
fn github_reaches_the_tui_marks_and_words() {
|
||||
use luxe_tui::glyphs::{GlyphTier, Icon, Mark};
|
||||
luxe_tui::glyphs::set_tier(GlyphTier::Ascii);
|
||||
let marks = TuiRenderer.github_marks();
|
||||
luxe_tui::glyphs::set_tier(GlyphTier::Nerd);
|
||||
assert_eq!(marks.pull_request, Icon::PullRequest.at(GlyphTier::Nerd));
|
||||
assert_eq!(marks.issue, Icon::Issue.at(GlyphTier::Nerd));
|
||||
assert_eq!(marks.yes, Mark::Yes.at(GlyphTier::Nerd));
|
||||
assert_eq!(marks.no, Mark::No.at(GlyphTier::Nerd));
|
||||
assert_eq!(marks.waiting, Mark::Waiting.at(GlyphTier::Nerd));
|
||||
assert_eq!(marks.elision, Mark::Elision.at(GlyphTier::Nerd));
|
||||
assert_eq!(TuiRenderer.ago(1_000, 1_000 + 3 * 3600), "3h ago");
|
||||
let body = TuiRenderer.github_readable("<details><summary>Notes</summary>x</details>");
|
||||
assert!(!body.contains('<'), "{body}");
|
||||
}
|
||||
|
||||
/// The break this catches: the bridge's default (no icon) left in place, so the home screen
|
||||
/// gets a screenshot of the page instead of the mark, or the size asked for not passed on.
|
||||
#[test]
|
||||
fn the_icon_is_the_tui_tile_at_the_size_asked_for() {
|
||||
let colors = luxe_remote::TileColors { plate: [0; 3], ink: [0xff; 3] };
|
||||
let png = TuiRenderer.home_icon(180, colors).expect("an icon");
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG");
|
||||
// the header chunk's width and height, big-endian, after the signature and chunk head
|
||||
assert_eq!(png[16..24], [0, 0, 0, 180, 0, 0, 0, 180]);
|
||||
}
|
||||
|
||||
/// The break this catches: facts dropped or crossed on the way to the TUI, so the phone's
|
||||
/// status line misses the context reading, or colors a full window as a roomy one.
|
||||
#[test]
|
||||
fn status_facts_reach_the_tui_and_come_back_as_its_segments() {
|
||||
let facts: luxe_remote::StatusFacts = serde_json::from_value(serde_json::json!({
|
||||
"model": {"provider": "anthropic", "model": "claude-x"},
|
||||
"thinking": "medium",
|
||||
"context": {"used_tokens": 950, "context_window": 1000},
|
||||
}))
|
||||
.expect("the app's status facts parse");
|
||||
let segments = TuiRenderer.status(&facts);
|
||||
let words: Vec<_> = segments.iter().map(|s| (s.kind, s.label.as_str(), s.tone)).collect();
|
||||
assert_eq!(
|
||||
words,
|
||||
[
|
||||
("context", "95.0%/1.0k", luxe_remote::StatusTone::Error),
|
||||
("thinking", "med", luxe_remote::StatusTone::Plain),
|
||||
("model", "claude-x", luxe_remote::StatusTone::Plain),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
172
crates/luxe-cli/src/cli/remote_command/setup.rs
Normal file
172
crates/luxe-cli/src/cli/remote_command/setup.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
//! `luxe remote setup` — from nothing to a paired phone, asking before each step that changes
|
||||
//! something outside Luxe.
|
||||
//!
|
||||
//! Four steps: Tailscale is there and signed in; Serve carries `https://<this machine>/` to the
|
||||
//! bridge; a user service runs the bridge at login; and an invitation to scan. Each step that is
|
||||
//! already done says so and moves on, so running setup again is how to check it.
|
||||
|
||||
use std::io::{BufRead, IsTerminal, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use luxe_remote::service::Launch;
|
||||
use luxe_remote::{DeviceBook, Published, Tailnet, TailnetError};
|
||||
|
||||
use crate::output::{out, outln};
|
||||
|
||||
/// Runs every step in order. Only a missing or signed-out Tailscale stops it.
|
||||
pub(super) async fn setup(
|
||||
port: u16,
|
||||
allow: Vec<String>,
|
||||
devices: &DeviceBook,
|
||||
) -> anyhow::Result<()> {
|
||||
let tailnet = check_tailscale().await?;
|
||||
publish_step(port, &tailnet).await;
|
||||
service_step(port, &tailnet, allow);
|
||||
wait_for_bridge(port).await;
|
||||
outln!();
|
||||
super::invitation::show(port, devices, &tailnet)
|
||||
}
|
||||
|
||||
/// Gives a service that just started up to two seconds to bind its port.
|
||||
async fn wait_for_bridge(port: u16) {
|
||||
for _ in 0..10 {
|
||||
if super::invitation::bridge_listening(port) {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_tailscale() -> anyhow::Result<Tailnet> {
|
||||
match luxe_remote::this_machine().await {
|
||||
Ok(tailnet) => {
|
||||
outln!("Tailscale: signed in as {} on {}.", tailnet.login, tailnet.dns_name);
|
||||
Ok(tailnet)
|
||||
}
|
||||
Err(error) => {
|
||||
outln!("{}", tailscale_advice(&error));
|
||||
Err(error.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tailscale_advice(error: &TailnetError) -> &'static str {
|
||||
match error {
|
||||
TailnetError::NotInstalled => {
|
||||
"Install Tailscale from https://tailscale.com/download and sign in, then run \
|
||||
`luxe remote setup` again."
|
||||
}
|
||||
TailnetError::NotRunning(_) => {
|
||||
"Sign in to Tailscale with `tailscale up`, then run `luxe remote setup` again."
|
||||
}
|
||||
TailnetError::Failed(_) | TailnetError::Unreadable(_) => {
|
||||
"Check that Tailscale is running with `tailscale status`, then run `luxe remote setup` \
|
||||
again."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_step(port: u16, tailnet: &Tailnet) {
|
||||
let address = format!("https://{}/", tailnet.dns_name);
|
||||
match luxe_remote::published(port).await {
|
||||
Ok(Published::Here) => outln!("Serve: {address} leads to the bridge."),
|
||||
Ok(Published::Elsewhere(target)) => outln!(
|
||||
"Serve: {address} already leads to {target}, so setup leaves it alone. \
|
||||
`tailscale serve --bg {port}` would point it at the bridge instead."
|
||||
),
|
||||
Ok(Published::Nowhere) => offer_publish(port, &address).await,
|
||||
Err(error) => outln!("Serve: couldn't read its settings ({error})."),
|
||||
}
|
||||
}
|
||||
|
||||
async fn offer_publish(port: u16, address: &str) {
|
||||
let question = format!("Publish the bridge at {address}, for your tailnet only?");
|
||||
if !confirm(&question) {
|
||||
outln!("Skipped. `tailscale serve --bg {port}` publishes it when you're ready.");
|
||||
return;
|
||||
}
|
||||
match luxe_remote::publish(port).await {
|
||||
Ok(()) => outln!("Serve: {address} now leads to the bridge."),
|
||||
Err(error) => {
|
||||
outln!("Serve: {error}");
|
||||
outln!("{}", SERVE_HINT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What usually stops `tailscale serve` for an ordinary account.
|
||||
const SERVE_HINT: &str = if cfg!(target_os = "linux") {
|
||||
"If it said access denied, let your account manage Tailscale with \
|
||||
`sudo tailscale set --operator=$USER`, then run setup again."
|
||||
} else {
|
||||
"Fix what Tailscale said above, then run setup again."
|
||||
};
|
||||
|
||||
fn service_step(port: u16, tailnet: &Tailnet, allow: Vec<String>) {
|
||||
if luxe_remote::service::installed() {
|
||||
outln!("Service: installed, so the bridge runs whenever you're signed in.");
|
||||
return;
|
||||
}
|
||||
if !confirm("Run the bridge whenever you're signed in, as a user service?") {
|
||||
outln!("Skipped. Run `luxe remote` yourself whenever your devices should reach Luxe.");
|
||||
return;
|
||||
}
|
||||
let launch =
|
||||
Launch { program: luxe_program(), args: service_args(port, &tailnet.login, allow) };
|
||||
match luxe_remote::service::install(&launch) {
|
||||
Ok(recorded) => outln!("Service: installed ({recorded}) and started."),
|
||||
Err(error) => outln!("Service: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's flags as the service runs it, the owner named outright so the service doesn't
|
||||
/// depend on reaching Tailscale as it starts.
|
||||
fn service_args(port: u16, owner: &str, allow: Vec<String>) -> Vec<String> {
|
||||
let mut args = vec!["remote".into(), "--port".into(), port.to_string()];
|
||||
for login in std::iter::once(owner.to_string()).chain(allow) {
|
||||
args.extend(["--allow".into(), login]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// This binary, by the path on `PATH` when that is the same file, since an upgrade replaces the
|
||||
/// file a package manager links from `PATH` and leaves a versioned path behind.
|
||||
fn luxe_program() -> PathBuf {
|
||||
let running = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("luxe"));
|
||||
let on_path = luxe_core::program::resolve("luxe");
|
||||
let same = |path: &PathBuf| path.canonicalize().ok() == running.canonicalize().ok();
|
||||
on_path.filter(same).unwrap_or(running)
|
||||
}
|
||||
|
||||
/// Asks a yes-or-no question, yes by default. Without a terminal to ask, the answer is no.
|
||||
fn confirm(question: &str) -> bool {
|
||||
if !std::io::stdin().is_terminal() {
|
||||
outln!("{question} Not asked, with no terminal to answer in.");
|
||||
return false;
|
||||
}
|
||||
out!("{question} [Y/n] ");
|
||||
let _ = std::io::stdout().flush();
|
||||
let mut answer = String::new();
|
||||
if std::io::stdin().lock().read_line(&mut answer).is_err() {
|
||||
return false;
|
||||
}
|
||||
let answer = answer.trim().to_lowercase();
|
||||
answer.is_empty() || answer.starts_with('y')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The service names the owner and every `--allow`, on the port setup was given.
|
||||
///
|
||||
/// The break this catches: a service that relies on finding Tailscale as it starts, which
|
||||
/// launchd's bare `PATH` doesn't, so the bridge comes up letting nobody in.
|
||||
#[test]
|
||||
fn the_service_names_who_it_lets_in() {
|
||||
let args = service_args(4600, "alex@github", vec!["sam@github".into()]);
|
||||
let expected =
|
||||
["remote", "--port", "4600", "--allow", "alex@github", "--allow", "sam@github"];
|
||||
assert_eq!(args, expected);
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,18 @@
|
||||
//! terminal (the TUI owns the screen), so that holds without any special care here — and
|
||||
//! `rpc_stdout_carries_only_protocol_frames` keeps it holding.
|
||||
|
||||
mod frame;
|
||||
mod translate;
|
||||
|
||||
use frame::write_frame;
|
||||
pub(super) use frame::{Opening, SharedTranscript};
|
||||
use luxe_core::engine::Action;
|
||||
use luxe_core::event::Action as WireAction;
|
||||
use luxe_core::Event;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
|
||||
use tokio::sync::mpsc;
|
||||
use translate::{to_engine_action, CatalogResolver, GithubWrites, ModelResolver, Policy, Rejected};
|
||||
use translate::{to_engine_action, Rejected};
|
||||
pub(super) use translate::{CatalogResolver, GithubWrites, ModelResolver, Policy};
|
||||
|
||||
/// Depth of the channel carrying locally-generated frames (rejections) to the single writer.
|
||||
///
|
||||
@@ -24,6 +28,9 @@ use translate::{to_engine_action, CatalogResolver, GithubWrites, ModelResolver,
|
||||
/// already being told so.
|
||||
const LOCAL_FRAME_BUFFER: usize = 32;
|
||||
|
||||
/// The catalog a session's clients resolve and list models through, shared by every one of them.
|
||||
pub(super) type Models = std::sync::Arc<dyn ModelResolver + Send + Sync>;
|
||||
|
||||
/// Run the RPC front-end against stdio until the client closes the stream or stdin ends.
|
||||
///
|
||||
/// Args: `(settings, github_writes)` — the second is `--github-writes`, which lets the client
|
||||
@@ -44,6 +51,7 @@ pub(crate) async fn run_rpc(
|
||||
let policy = Policy {
|
||||
github_writes: GithubWrites::for_launch(github_writes, mode),
|
||||
github_sections: luxe_core::config::Config::load(&settings.state_root).github.sections(),
|
||||
joined: false,
|
||||
};
|
||||
let handle = crate::engine_setup::build_engine(
|
||||
&settings,
|
||||
@@ -63,6 +71,9 @@ pub(crate) async fn run_rpc(
|
||||
},
|
||||
crate::workspace_runtime::pull_request_watch(&settings.work_root),
|
||||
);
|
||||
// Shared like a terminal's, which is how a phone reaches a session the bridge started
|
||||
let (events, _sharing) =
|
||||
super::share::share(events, handle.actions.clone(), &settings, &handle.session_id.0);
|
||||
|
||||
let ready = Event::Ready {
|
||||
protocol_version: luxe_core::PROTOCOL_VERSION,
|
||||
@@ -82,12 +93,12 @@ pub(crate) async fn run_rpc(
|
||||
}
|
||||
|
||||
serve(
|
||||
ready,
|
||||
ready.into(),
|
||||
events,
|
||||
handle.actions,
|
||||
tokio::fs::File::from_std(input),
|
||||
tokio::io::stdout(),
|
||||
&CatalogResolver,
|
||||
std::sync::Arc::new(CatalogResolver { settings: settings.clone() }),
|
||||
policy,
|
||||
)
|
||||
.await?;
|
||||
@@ -100,21 +111,25 @@ pub(crate) async fn run_rpc(
|
||||
/// Generic over the streams so the protocol — handshake, framing, translation, refusal, shutdown —
|
||||
/// is exercised end to end in tests without a real stdin, a real terminal, or a live provider.
|
||||
/// `run_rpc` is this function with stdio and the real catalog plugged in.
|
||||
async fn serve<R, W>(
|
||||
ready: Event,
|
||||
///
|
||||
/// A client that joined a terminal's session (`policy.joined`) never closes the engine: its
|
||||
/// hangup or `close` ends its own connection, and the terminal carries on.
|
||||
pub(super) async fn serve<R, W>(
|
||||
opening: Opening,
|
||||
mut events: mpsc::Receiver<Event>,
|
||||
engine_tx: mpsc::Sender<Action>,
|
||||
input: R,
|
||||
mut output: W,
|
||||
models: &'static (dyn ModelResolver + Sync),
|
||||
models: Models,
|
||||
policy: Policy,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin,
|
||||
{
|
||||
if !emit(&mut output, &ready).await? {
|
||||
engine_tx.send(Action::Close).await.ok();
|
||||
let joined = policy.joined;
|
||||
if !emit_opening(&mut output, opening).await? {
|
||||
close_unless_joined(&engine_tx, joined).await;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -131,6 +146,8 @@ where
|
||||
// ordered against each other: `select!` takes whichever is ready. Nothing needs them to be — a
|
||||
// refusal is about the client's own input, not about engine state — and pretending otherwise
|
||||
// would mean holding one stream up for the other.
|
||||
//
|
||||
// A joined client's reader ending *is* the end of its session, since the engine outlives it.
|
||||
let mut refusals_open = true;
|
||||
loop {
|
||||
let frame = tokio::select! {
|
||||
@@ -140,6 +157,7 @@ where
|
||||
},
|
||||
refusal = local_rx.recv(), if refusals_open => match refusal {
|
||||
Some(refusal) => refusal,
|
||||
None if joined => break,
|
||||
None => {
|
||||
refusals_open = false;
|
||||
continue;
|
||||
@@ -163,19 +181,26 @@ where
|
||||
|
||||
reader.abort();
|
||||
// The engine may already be gone (the client sent `close`); saying so twice is harmless.
|
||||
engine_tx.send(Action::Close).await.ok();
|
||||
close_unless_joined(&engine_tx, joined).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the engine as a client leaves, unless the client only joined it.
|
||||
async fn close_unless_joined(engine_tx: &mpsc::Sender<Action>, joined: bool) {
|
||||
if !joined {
|
||||
engine_tx.send(Action::Close).await.ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read wire actions until EOF, forwarding what translates and refusing what does not.
|
||||
///
|
||||
/// EOF means the client is gone, so the engine is told to close rather than left running behind a
|
||||
/// stream nobody is reading.
|
||||
/// stream nobody is reading. A joined client's EOF or `close` only ends the read.
|
||||
async fn read_actions<R>(
|
||||
input: R,
|
||||
engine_tx: mpsc::Sender<Action>,
|
||||
local_tx: mpsc::Sender<Event>,
|
||||
models: &'static (dyn ModelResolver + Sync),
|
||||
models: Models,
|
||||
policy: Policy,
|
||||
) where
|
||||
R: AsyncRead + Unpin,
|
||||
@@ -193,18 +218,26 @@ async fn read_actions<R>(
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let action = match parse_action(&line, models, &policy) {
|
||||
Ok(action) => action,
|
||||
let reply = match parse_action(&line, &*models, &policy) {
|
||||
Ok(Inbound::Engine(action)) => Ok(*action),
|
||||
Ok(Inbound::Answer(answer)) => Err(answer),
|
||||
Err(rejected) => {
|
||||
let refusal =
|
||||
Event::ActionRejected { kind: rejected.kind, reason: rejected.reason };
|
||||
if local_tx.send(refusal).await.is_err() {
|
||||
Err(Event::ActionRejected { kind: rejected.kind, reason: rejected.reason })
|
||||
}
|
||||
};
|
||||
let action = match reply {
|
||||
Ok(action) => action,
|
||||
Err(reply) => {
|
||||
if local_tx.send(reply).await.is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let closing = matches!(action, Action::Close);
|
||||
if closing && policy.joined {
|
||||
break;
|
||||
}
|
||||
if engine_tx.send(action).await.is_err() {
|
||||
break;
|
||||
}
|
||||
@@ -212,7 +245,7 @@ async fn read_actions<R>(
|
||||
break;
|
||||
}
|
||||
}
|
||||
engine_tx.send(Action::Close).await.ok();
|
||||
close_unless_joined(&engine_tx, policy.joined).await;
|
||||
}
|
||||
|
||||
/// Parse and translate one inbound line.
|
||||
@@ -221,9 +254,9 @@ async fn read_actions<R>(
|
||||
/// is testable without any IO at all.
|
||||
fn parse_action(
|
||||
line: &str,
|
||||
models: &(dyn ModelResolver + Sync),
|
||||
models: &(dyn ModelResolver + Send + Sync),
|
||||
policy: &Policy,
|
||||
) -> Result<Action, Rejected> {
|
||||
) -> Result<Inbound, Rejected> {
|
||||
// Read the envelope before the payload, so a frame that names itself and then fails to
|
||||
// deserialize is still refused *by name*. Reporting `kind: null` for a `steer_turn` missing its
|
||||
// text sends the client looking through every frame it wrote instead of the one that was wrong.
|
||||
@@ -232,15 +265,49 @@ fn parse_action(
|
||||
let kind = raw.get("kind").and_then(serde_json::Value::as_str).map(str::to_string);
|
||||
let wire: WireAction = serde_json::from_value(raw)
|
||||
.map_err(|error| Rejected { kind, reason: error.to_string() })?;
|
||||
to_engine_action(wire, models, policy)
|
||||
if let WireAction::ListModels { request_id } = wire {
|
||||
return Ok(Inbound::Answer(Event::ModelsListed { request_id, models: models.choices() }));
|
||||
}
|
||||
to_engine_action(wire, models, policy).map(|action| Inbound::Engine(Box::new(action)))
|
||||
}
|
||||
|
||||
/// What one inbound line comes to.
|
||||
#[derive(Debug)]
|
||||
enum Inbound {
|
||||
/// An action for the engine
|
||||
Engine(Box<Action>),
|
||||
/// An answer for this client alone, which the engine has no part in
|
||||
Answer(Event),
|
||||
}
|
||||
|
||||
/// Write one frame, reporting `false` once the client has stopped reading.
|
||||
///
|
||||
/// A hangup is how a session ends when the other end is `head` or a closed editor pane, so it
|
||||
/// resolves to a clean exit rather than an error written to a pipe nobody is holding.
|
||||
async fn emit<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> anyhow::Result<bool> {
|
||||
match write_frame(out, event).await {
|
||||
/// Send `ready` and any transcript, saying whether the client is still there.
|
||||
///
|
||||
/// Takes the opening by value so the transcript is let go once sent: held for the connection, it
|
||||
/// would pin a superseded copy of every message, and each commit would copy the snapshot's whole
|
||||
/// list to append to it.
|
||||
async fn emit_opening<W: AsyncWrite + Unpin>(
|
||||
out: &mut W,
|
||||
opening: Opening,
|
||||
) -> anyhow::Result<bool> {
|
||||
if !emit(out, &opening.ready).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
match opening.transcript {
|
||||
Some(transcript) => emit(out, &transcript).await,
|
||||
None => Ok(true),
|
||||
}
|
||||
}
|
||||
|
||||
async fn emit<W, F>(out: &mut W, frame: &F) -> anyhow::Result<bool>
|
||||
where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: serde::Serialize + ?Sized,
|
||||
{
|
||||
match write_frame(out, frame).await {
|
||||
Ok(()) => Ok(true),
|
||||
Err(error)
|
||||
if matches!(
|
||||
@@ -255,23 +322,5 @@ async fn emit<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> anyhow::Resu
|
||||
}
|
||||
}
|
||||
|
||||
/// Write one frame and flush it, so a streaming client sees tokens as they arrive.
|
||||
///
|
||||
/// A frame that cannot serialize is logged and dropped rather than ending the session: losing one
|
||||
/// event is recoverable for a client, and a dead stream is not.
|
||||
async fn write_frame<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> std::io::Result<()> {
|
||||
let line = match serde_json::to_string(event) {
|
||||
Ok(line) => line,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "rpc: dropping an event that would not serialize");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
out.write_all(line.as_bytes()).await?;
|
||||
out.write_all(b"\n").await?;
|
||||
out.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
99
crates/luxe-cli/src/cli/rpc/frame.rs
Normal file
99
crates/luxe-cli/src/cli/rpc/frame.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Frames — one JSON object per line, written without growing one buffer to the biggest frame.
|
||||
//!
|
||||
//! A joiner's `session_loaded` carries the whole transcript, tens of megabytes on a long session,
|
||||
//! and a phone joins again on every reconnect. Encoded into one `String` it grows by doubling,
|
||||
//! about four times its size allocated for every join, so a frame is encoded into fixed-size pieces
|
||||
//! instead, and a shared session's transcript goes out from the snapshot's copy, not a clone of it.
|
||||
|
||||
use luxe_core::event::SessionMessage;
|
||||
use luxe_core::Event;
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// Bytes in each piece of an encoded frame.
|
||||
const CHUNK_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// What a client is sent ahead of the event stream: `ready`, then for a joiner the transcript.
|
||||
pub(in crate::cli) struct Opening {
|
||||
pub(in crate::cli) ready: Event,
|
||||
/// The transcript so far, for a client joining a session already under way
|
||||
pub(in crate::cli) transcript: Option<SharedTranscript>,
|
||||
}
|
||||
|
||||
impl From<Event> for Opening {
|
||||
fn from(ready: Event) -> Self {
|
||||
Self { ready, transcript: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's transcript, sent as its `session_loaded` frame and shared with the snapshot that
|
||||
/// keeps it, so a join doesn't copy every message.
|
||||
pub(in crate::cli) struct SharedTranscript {
|
||||
pub(in crate::cli) session_id: String,
|
||||
pub(in crate::cli) messages: Arc<Vec<SessionMessage>>,
|
||||
}
|
||||
|
||||
/// `Event::SessionLoaded`'s wire shape over borrowed fields; a test pins it to the event's own.
|
||||
#[derive(Serialize)]
|
||||
#[serde(tag = "kind", content = "content", rename_all = "snake_case")]
|
||||
enum LoadedFrame<'a> {
|
||||
SessionLoaded { session_id: &'a str, messages: &'a [SessionMessage] },
|
||||
}
|
||||
|
||||
impl Serialize for SharedTranscript {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let frame =
|
||||
LoadedFrame::SessionLoaded { session_id: &self.session_id, messages: &self.messages };
|
||||
frame.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write one frame and flush it, so a streaming client sees tokens as they arrive.
|
||||
///
|
||||
/// A frame that cannot serialize is logged and dropped rather than ending the session: losing one
|
||||
/// event is recoverable for a client, and a dead stream is not. Nothing is written until the whole
|
||||
/// frame has encoded, so a failure never leaves half a line.
|
||||
pub(super) async fn write_frame<W, F>(out: &mut W, frame: &F) -> std::io::Result<()>
|
||||
where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: Serialize + ?Sized,
|
||||
{
|
||||
let mut encoded = Pieces::default();
|
||||
if let Err(error) = serde_json::to_writer(&mut encoded, frame) {
|
||||
tracing::warn!(%error, "rpc: dropping an event that would not serialize");
|
||||
return Ok(());
|
||||
}
|
||||
for piece in encoded.full.iter().chain(std::iter::once(&encoded.current)) {
|
||||
out.write_all(piece).await?;
|
||||
}
|
||||
out.write_all(b"\n").await?;
|
||||
out.flush().await
|
||||
}
|
||||
|
||||
/// An encoded frame in pieces of at most `CHUNK_BYTES`. The first grows like any buffer, so a
|
||||
/// token's frame costs what it always did, and a large frame is never copied into a bigger one.
|
||||
#[derive(Default)]
|
||||
struct Pieces {
|
||||
full: Vec<Vec<u8>>,
|
||||
current: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::io::Write for Pieces {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
if self.current.len() == CHUNK_BYTES {
|
||||
let next = Vec::with_capacity(CHUNK_BYTES);
|
||||
self.full.push(std::mem::replace(&mut self.current, next));
|
||||
}
|
||||
let taken = bytes.len().min(CHUNK_BYTES - self.current.len());
|
||||
self.current.extend_from_slice(&bytes[..taken]);
|
||||
Ok(taken)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
88
crates/luxe-cli/src/cli/rpc/frame/tests.rs
Normal file
88
crates/luxe-cli/src/cli/rpc/frame/tests.rs
Normal file
@@ -0,0 +1,88 @@
|
||||
use super::*;
|
||||
use luxe_core::message::Message;
|
||||
use luxe_core::session::EntryId;
|
||||
|
||||
fn messages() -> Vec<SessionMessage> {
|
||||
["first", "second"]
|
||||
.into_iter()
|
||||
.map(|text| SessionMessage { entry_id: EntryId(text.into()), message: Message::user(text) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn written<F: Serialize + ?Sized>(frame: &F) -> String {
|
||||
let mut out = Vec::new();
|
||||
write_frame(&mut out, frame).await.expect("writing to memory");
|
||||
String::from_utf8(out).expect("frames are UTF-8")
|
||||
}
|
||||
|
||||
/// The shared transcript goes out byte for byte as the `session_loaded` event would.
|
||||
///
|
||||
/// The break this catches: the borrowed copy of the event's shape drifting from `Event`, a renamed
|
||||
/// field or a lost `rename_all`, which every joining client would read as an unknown frame.
|
||||
#[test]
|
||||
fn the_shared_transcript_encodes_as_session_loaded() {
|
||||
let shared =
|
||||
SharedTranscript { session_id: "session-1".into(), messages: Arc::new(messages()) };
|
||||
let event = Event::SessionLoaded { session_id: "session-1".into(), messages: messages() };
|
||||
assert_eq!(serde_json::to_string(&shared).unwrap(), serde_json::to_string(&event).unwrap());
|
||||
}
|
||||
|
||||
/// A frame bigger than several pieces arrives whole, as one line.
|
||||
///
|
||||
/// The break this catches: losing the last piece or the full ones, or cutting a piece a byte off,
|
||||
/// which garbles exactly the large `session_loaded` frame a long session sends.
|
||||
#[tokio::test]
|
||||
async fn a_frame_of_many_pieces_is_written_whole() {
|
||||
let text: String =
|
||||
(0..CHUNK_BYTES * 3 + 17).map(|at| char::from(b'a' + (at % 26) as u8)).collect();
|
||||
let event = Event::Notice(text);
|
||||
let expected = format!("{}\n", serde_json::to_string(&event).unwrap());
|
||||
assert_eq!(written(&event).await, expected);
|
||||
}
|
||||
|
||||
/// A large frame is held in pieces of one chunk at most, never one buffer of the whole.
|
||||
///
|
||||
/// The break this catches: dropping the cap on a piece, which grows the first one by doubling to the
|
||||
/// frame's size, the very allocation this module exists to avoid.
|
||||
#[test]
|
||||
fn a_large_frame_is_held_in_chunk_sized_pieces() {
|
||||
let mut encoded = Pieces::default();
|
||||
serde_json::to_writer(&mut encoded, &"x".repeat(CHUNK_BYTES * 3)).unwrap();
|
||||
assert_eq!(encoded.full.len(), 3);
|
||||
assert!(encoded.full.iter().all(|piece| piece.len() == CHUNK_BYTES));
|
||||
assert!(encoded.current.capacity() <= CHUNK_BYTES, "{}", encoded.current.capacity());
|
||||
}
|
||||
|
||||
/// A token's frame still fits in one piece, so the common case pays for no more than it did.
|
||||
///
|
||||
/// The break this catches: starting every frame on a full piece, a 64 KB allocation for each of
|
||||
/// the thousands of token deltas a reply streams.
|
||||
#[test]
|
||||
fn a_small_frame_stays_in_its_first_piece() {
|
||||
let mut encoded = Pieces::default();
|
||||
serde_json::to_writer(&mut encoded, &Event::Notice("hi".into())).unwrap();
|
||||
assert!(encoded.full.is_empty());
|
||||
assert!(encoded.current.capacity() < CHUNK_BYTES, "{}", encoded.current.capacity());
|
||||
}
|
||||
|
||||
/// Serializes as a list whose second element fails, after the first has been encoded.
|
||||
struct FailsPartway;
|
||||
|
||||
impl Serialize for FailsPartway {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
use serde::ser::{Error, SerializeSeq};
|
||||
let mut list = serializer.serialize_seq(Some(2))?;
|
||||
list.serialize_element("encoded")?;
|
||||
drop(list);
|
||||
Err(S::Error::custom("cannot encode the rest"))
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame that fails partway writes nothing rather than half a line.
|
||||
///
|
||||
/// The break this catches: streaming the encoding straight to the client, which leaves a broken
|
||||
/// line that turns every later frame into a parse error.
|
||||
#[tokio::test]
|
||||
async fn a_frame_that_fails_partway_writes_nothing() {
|
||||
assert_eq!(written(&FailsPartway).await, "");
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
use luxe_core::provider::ModelInfo;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
/// A resolver with no dependence on the developer's `models.json`.
|
||||
struct FixedModels;
|
||||
@@ -8,14 +9,42 @@ impl ModelResolver for FixedModels {
|
||||
fn resolve(&self, provider: &str, id: &str) -> ModelInfo {
|
||||
ModelInfo { r#ref: luxe_core::provider::ModelRef::new(provider, id), ..Default::default() }
|
||||
}
|
||||
|
||||
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
|
||||
vec![luxe_core::event::ModelChoice {
|
||||
provider: "anthropic".into(),
|
||||
model: "claude-sonnet-5".into(),
|
||||
name: "Claude Sonnet 5".into(),
|
||||
thinking_levels: vec![luxe_core::provider::ThinkingLevel::Off],
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
fn policy(github_writes: GithubWrites) -> Policy {
|
||||
Policy { github_writes, github_sections: Vec::new() }
|
||||
Policy { github_writes, github_sections: Vec::new(), joined: false }
|
||||
}
|
||||
|
||||
fn parse(line: &str) -> Result<Action, Rejected> {
|
||||
parse_action(line, &FixedModels, &policy(GithubWrites::NotEnabled))
|
||||
match parse_action(line, &FixedModels, &policy(GithubWrites::NotEnabled))? {
|
||||
Inbound::Engine(action) => Ok(*action),
|
||||
Inbound::Answer(answer) => panic!("answered without the engine: {answer:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `list_models` is answered to the client that asked, with the catalog's choices, and the
|
||||
/// engine never hears of it.
|
||||
///
|
||||
/// The break this catches: forwarding it to the engine, which has no arm for it; or answering
|
||||
/// with nothing, so the phone's picker opens empty.
|
||||
#[tokio::test]
|
||||
async fn the_protocol_answers_which_models_there_are() {
|
||||
let ask = "{\"kind\":\"list_models\",\"content\":{\"request_id\":\"models:1\"}}\n";
|
||||
let session = run_session(ask, Vec::new()).await;
|
||||
let listed = session.frames.iter().find(|frame| frame["kind"] == "models_listed");
|
||||
let listed = listed.expect("an answer");
|
||||
assert_eq!(listed["content"]["request_id"], "models:1");
|
||||
assert_eq!(listed["content"]["models"][0]["model"], "claude-sonnet-5");
|
||||
assert!(session.actions.iter().all(|action| matches!(action, Action::Close)));
|
||||
}
|
||||
|
||||
/// A well-formed frame becomes the engine action it names.
|
||||
@@ -120,12 +149,12 @@ async fn run_session(input: &str, events: Vec<Event>) -> Session {
|
||||
github_writes: false,
|
||||
};
|
||||
let served = serve(
|
||||
ready,
|
||||
ready.into(),
|
||||
event_rx,
|
||||
engine_tx,
|
||||
server_read,
|
||||
server_write,
|
||||
&FixedModels,
|
||||
std::sync::Arc::new(FixedModels),
|
||||
policy(GithubWrites::NotEnabled),
|
||||
);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), served)
|
||||
@@ -338,12 +367,12 @@ async fn a_real_write_failure_is_not_mistaken_for_a_hangup() {
|
||||
github_writes: false,
|
||||
};
|
||||
let served = serve(
|
||||
ready,
|
||||
ready.into(),
|
||||
event_rx,
|
||||
engine_tx,
|
||||
server_read,
|
||||
FailingWriter,
|
||||
&FixedModels,
|
||||
std::sync::Arc::new(FixedModels),
|
||||
policy(GithubWrites::NotEnabled),
|
||||
);
|
||||
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), served)
|
||||
@@ -383,12 +412,12 @@ async fn a_client_that_stops_reading_is_not_an_error() {
|
||||
github_writes: false,
|
||||
};
|
||||
let served = serve(
|
||||
ready,
|
||||
ready.into(),
|
||||
event_rx,
|
||||
engine_tx,
|
||||
server_read,
|
||||
server_write,
|
||||
&FixedModels,
|
||||
std::sync::Arc::new(FixedModels),
|
||||
policy(GithubWrites::NotEnabled),
|
||||
);
|
||||
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), served)
|
||||
@@ -397,6 +426,61 @@ async fn a_client_that_stops_reading_is_not_an_error() {
|
||||
assert!(outcome.is_ok(), "a client hangup is a clean end: {outcome:?}");
|
||||
}
|
||||
|
||||
/// A joiner's transcript is let go once it's sent, while the client stays connected.
|
||||
///
|
||||
/// The break this catches: `serve` keeping the opening for the whole connection, which pins a stale
|
||||
/// copy of every message per client and makes each commit copy the snapshot's whole list.
|
||||
#[tokio::test]
|
||||
async fn a_sent_transcript_is_released_while_the_client_stays() {
|
||||
let message = luxe_core::event::SessionMessage {
|
||||
entry_id: luxe_core::session::EntryId("entry-1".into()),
|
||||
message: luxe_core::message::Message::user("hello"),
|
||||
};
|
||||
let messages = std::sync::Arc::new(vec![message]);
|
||||
let transcript =
|
||||
SharedTranscript { session_id: "session-1".into(), messages: messages.clone() };
|
||||
let (served, mut lines) = serve_joiner(transcript);
|
||||
|
||||
lines.next_line().await.unwrap().expect("the ready frame");
|
||||
let loaded = lines.next_line().await.unwrap().expect("the transcript frame");
|
||||
assert!(loaded.starts_with(r#"{"kind":"session_loaded""#), "{loaded}");
|
||||
assert_eq!(holders_once_settled(&messages).await, 1, "serve still holds the transcript");
|
||||
assert!(!served.is_finished(), "the client is still connected");
|
||||
served.abort();
|
||||
}
|
||||
|
||||
/// Serve a joiner opening on `transcript`, connected until aborted, and what its client reads.
|
||||
fn serve_joiner(
|
||||
transcript: SharedTranscript,
|
||||
) -> (
|
||||
tokio::task::JoinHandle<anyhow::Result<()>>,
|
||||
tokio::io::Lines<BufReader<tokio::io::DuplexStream>>,
|
||||
) {
|
||||
let (client_write, server_read) = tokio::io::duplex(1024);
|
||||
let (server_write, client_read) = tokio::io::duplex(64 * 1024);
|
||||
let (engine_tx, engine_rx) = mpsc::channel::<Action>(64);
|
||||
let (event_tx, event_rx) = mpsc::channel::<Event>(64);
|
||||
let opening = Opening { ready: Event::Notice("ready".into()), transcript: Some(transcript) };
|
||||
let (models, policy) = (std::sync::Arc::new(FixedModels), policy(GithubWrites::NotEnabled));
|
||||
let served = tokio::spawn(async move {
|
||||
// Held open, so the session waits on its client instead of ending
|
||||
let _open = (client_write, engine_rx, event_tx);
|
||||
serve(opening, event_rx, engine_tx, server_read, server_write, models, policy).await
|
||||
});
|
||||
(served, BufReader::new(client_read).lines())
|
||||
}
|
||||
|
||||
/// How many hold `messages` once anything still sending it has had its chance to let go.
|
||||
async fn holders_once_settled<T>(messages: &std::sync::Arc<T>) -> usize {
|
||||
for _ in 0..100 {
|
||||
if std::sync::Arc::strong_count(messages) == 1 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
std::sync::Arc::strong_count(messages)
|
||||
}
|
||||
|
||||
/// Every frame written is one line of JSON — the framing rule a client parses by.
|
||||
///
|
||||
/// `run_session` panics on any line that will not parse, so a stray `println!` anywhere in this
|
||||
|
||||
@@ -39,6 +39,8 @@ pub(crate) struct Policy {
|
||||
pub(crate) github_writes: GithubWrites,
|
||||
/// The `/github` sections a bare `list_github` runs: the user's configured ones
|
||||
pub(crate) github_sections: Vec<luxe_core::config::GithubSection>,
|
||||
/// Whether the client joined a session a terminal runs, rather than starting its own
|
||||
pub(crate) joined: bool,
|
||||
}
|
||||
|
||||
/// Whether a client may publish to GitHub, and if not, why not.
|
||||
@@ -95,16 +97,71 @@ pub(crate) trait ModelResolver {
|
||||
/// same contract `--model` has always had, and it is what makes a local or proxied model
|
||||
/// usable without an entry in anyone's catalog.
|
||||
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo;
|
||||
|
||||
/// The models a client can switch to, configured ones first, for `list_models`.
|
||||
fn choices(&self) -> Vec<luxe_core::event::ModelChoice>;
|
||||
}
|
||||
|
||||
/// The real catalog: configured models first, models.dev filling the gaps, defaults under that.
|
||||
pub(crate) struct CatalogResolver;
|
||||
///
|
||||
/// Holds the launch's settings because which providers can be reached depends on them: a key
|
||||
/// passed on the command line reaches a provider nothing else configures.
|
||||
pub(crate) struct CatalogResolver {
|
||||
pub(crate) settings: crate::engine_setup::AgentSettings,
|
||||
}
|
||||
|
||||
impl ModelResolver for CatalogResolver {
|
||||
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo {
|
||||
let config = crate::engine_setup::load_luxe_config();
|
||||
crate::model_catalog::resolve_model(&config, provider, id).0
|
||||
}
|
||||
|
||||
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
|
||||
crate::model_catalog::choices(&self.settings)
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the client's policy refuses `wire`, before it means anything to the engine.
|
||||
fn policy_refusal(wire: &WireAction, policy: &Policy) -> Option<String> {
|
||||
let kind = wire.kind();
|
||||
if wire.writes_to_github() {
|
||||
if let Some(reason) = policy.github_writes.refusal(kind) {
|
||||
return Some(reason);
|
||||
}
|
||||
}
|
||||
if wire.writes_the_repository() && policy.github_writes == GithubWrites::ReadOnly {
|
||||
return Some(format!("{kind} writes to the repository, and this session is read-only"));
|
||||
}
|
||||
session_refusal(wire, policy)
|
||||
}
|
||||
|
||||
/// Why `wire` is refused for the client's place in the session: the one that started it, or one
|
||||
/// that joined.
|
||||
fn session_refusal(wire: &WireAction, policy: &Policy) -> Option<String> {
|
||||
let kind = wire.kind();
|
||||
// A joined client's introduction is kept by the share layer, so one that gets here started
|
||||
// the session
|
||||
if matches!(wire, WireAction::Introduce { .. }) {
|
||||
return Some(format!("{kind} is for a client that joined a running session"));
|
||||
}
|
||||
// The protocol answers it from the catalog before translating (`rpc::parse_action`)
|
||||
if matches!(wire, WireAction::ListModels { .. }) {
|
||||
return Some(format!("{kind} is answered by the protocol, not the engine"));
|
||||
}
|
||||
let switches = matches!(wire, WireAction::NewSession | WireAction::LoadSession(_));
|
||||
if policy.joined && switches {
|
||||
let reason = "would switch the session the terminal is showing: switch it there, or start \
|
||||
another Luxe";
|
||||
return Some(format!("{kind} {reason}"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Review progress carrying only the walked chapters, which is all the wire sends.
|
||||
fn walked(
|
||||
walked_chapter_ids: Vec<luxe_core::guided_review::ChapterId>,
|
||||
) -> luxe_core::guided_review::ReviewProgress {
|
||||
luxe_core::guided_review::ReviewProgress { walked_chapter_ids, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Translate one wire action into the engine action it stands for.
|
||||
@@ -116,15 +173,8 @@ pub(crate) fn to_engine_action(
|
||||
models: &dyn ModelResolver,
|
||||
policy: &Policy,
|
||||
) -> Result<Action, Rejected> {
|
||||
if wire.writes_to_github() {
|
||||
if let Some(reason) = policy.github_writes.refusal(wire.kind()) {
|
||||
return Err(Rejected { kind: Some(wire.kind().to_string()), reason });
|
||||
}
|
||||
}
|
||||
if wire.writes_the_repository() && policy.github_writes == GithubWrites::ReadOnly {
|
||||
let kind = wire.kind();
|
||||
let reason = format!("{kind} writes to the repository, and this session is read-only");
|
||||
return Err(Rejected { kind: Some(kind.to_string()), reason });
|
||||
if let Some(reason) = policy_refusal(&wire, policy) {
|
||||
return Err(Rejected { kind: Some(wire.kind().to_string()), reason });
|
||||
}
|
||||
Ok(match wire {
|
||||
WireAction::SubmitUserMessage { text, images } => {
|
||||
@@ -159,15 +209,10 @@ pub(crate) fn to_engine_action(
|
||||
Action::EditReview { request_id, review_id, edit }
|
||||
}
|
||||
WireAction::RecordReviewProgress { review_id, walked_chapter_ids } => {
|
||||
Action::RecordReviewProgress {
|
||||
review_id,
|
||||
progress: luxe_core::guided_review::ReviewProgress {
|
||||
walked_chapter_ids,
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
Action::RecordReviewProgress { review_id, progress: walked(walked_chapter_ids) }
|
||||
}
|
||||
WireAction::RecordReviewSeen { review_id } => Action::RecordReviewSeen { review_id },
|
||||
WireAction::ShowOpenReview { request_id } => Action::ShowOpenReview { request_id },
|
||||
WireAction::RefreshGuidedReview { request_id, review_id, revision_id } => {
|
||||
Action::RefreshGuidedReview { request_id, review_id, expected_revision: revision_id }
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ impl ModelResolver for OneModel {
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn policy(github_writes: GithubWrites) -> Policy {
|
||||
@@ -22,6 +26,7 @@ fn policy(github_writes: GithubWrites) -> Policy {
|
||||
name: "Mine".into(),
|
||||
query: "is:open is:pr author:@me repo:{repo}".into(),
|
||||
}],
|
||||
joined: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +34,20 @@ fn translate(wire: WireAction) -> Result<Action, Rejected> {
|
||||
to_engine_action(wire, &OneModel, &policy(GithubWrites::Allowed))
|
||||
}
|
||||
|
||||
/// A client that joined a terminal's session can't switch it, and one that started its own can.
|
||||
///
|
||||
/// The break this catches: dropping the joined check, which lets a phone swap out the
|
||||
/// conversation the person at the terminal is reading.
|
||||
#[test]
|
||||
fn a_joined_client_cannot_switch_the_session() {
|
||||
let joined = Policy { joined: true, ..policy(GithubWrites::Allowed) };
|
||||
for wire in [WireAction::NewSession, WireAction::LoadSession("other".into())] {
|
||||
let refused = to_engine_action(wire.clone(), &OneModel, &joined);
|
||||
assert!(refused.is_err(), "a joined client ran {}", wire.kind());
|
||||
assert!(translate(wire).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
/// A steer for the summary has to survive the crossing; without it `/compact keep the API
|
||||
/// decisions` is an ordinary compaction that silently ignored what it was told.
|
||||
#[test]
|
||||
@@ -104,6 +123,18 @@ fn each_wire_action_arrives_as_the_engine_action_it_names() {
|
||||
));
|
||||
}
|
||||
|
||||
/// The client that started a session is refused when it introduces itself, by name.
|
||||
///
|
||||
/// The break this catches: the arm falling to the catch-all, which tells a client that a published
|
||||
/// kind is unknown.
|
||||
#[test]
|
||||
fn the_starting_client_cannot_introduce_itself() {
|
||||
let introduce = WireAction::Introduce { name: "iPhone".into(), watch_only: false, yours: true };
|
||||
let refused = translate(introduce).unwrap_err();
|
||||
assert_eq!(refused.kind.as_deref(), Some("introduce"));
|
||||
assert!(refused.reason.contains("joined a running session"), "{}", refused.reason);
|
||||
}
|
||||
|
||||
/// Every GitHub action reaches the engine as the action it names, carrying its payload.
|
||||
///
|
||||
/// Same break as above, sharpest here: overview and conversation share a payload, as do
|
||||
@@ -248,6 +279,10 @@ fn each_review_action_arrives_as_the_engine_action_it_names() {
|
||||
translate(WireAction::RecordReviewSeen { review_id: id("review:1") }),
|
||||
Ok(Action::RecordReviewSeen { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
translate(WireAction::ShowOpenReview { request_id: load.clone() }),
|
||||
Ok(Action::ShowOpenReview { request_id }) if request_id == load
|
||||
));
|
||||
assert!(matches!(
|
||||
translate(WireAction::RefreshGuidedReview {
|
||||
request_id: load.clone(),
|
||||
@@ -523,7 +558,10 @@ fn an_unknown_frame_is_refused_by_name() {
|
||||
/// comes from the built-in defaults rather than from whatever the developer has configured.
|
||||
#[test]
|
||||
fn the_real_resolver_answers_about_the_model_it_was_asked() {
|
||||
let info = CatalogResolver.resolve("no-such-provider", "no-such-model-9e3f");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let overrides = crate::engine_setup::CliOverrides::default();
|
||||
let settings = crate::engine_setup::AgentSettings::resolve(dir.path().into(), overrides);
|
||||
let info = CatalogResolver { settings }.resolve("no-such-provider", "no-such-model-9e3f");
|
||||
assert_eq!(info.r#ref.provider, "no-such-provider");
|
||||
assert_eq!(info.r#ref.id, "no-such-model-9e3f");
|
||||
assert!(info.context_window > 0, "a zero window makes every context percentage a lie");
|
||||
@@ -539,7 +577,7 @@ fn the_real_resolver_answers_about_the_model_it_was_asked() {
|
||||
fn the_translator_covers_the_whole_published_vocabulary() {
|
||||
assert_eq!(
|
||||
WireAction::KINDS.len(),
|
||||
51,
|
||||
54,
|
||||
"a wire action was published without a translator arm: {:?}",
|
||||
WireAction::KINDS
|
||||
);
|
||||
|
||||
236
crates/luxe-cli/src/cli/share.rs
Normal file
236
crates/luxe-cli/src/cli/share.rs
Normal file
@@ -0,0 +1,236 @@
|
||||
//! Session sharing — the terminal's session, offered to other front-ends on this machine.
|
||||
//!
|
||||
//! "The terminal" is whichever front-end started the session: the TUI, or the client on the other
|
||||
//! end of `luxe --rpc`. The terminal stays in charge. A client that connects to the local endpoint
|
||||
//! (a Unix socket or a named pipe only this user can open) speaks the protocol `luxe --rpc` does:
|
||||
//! it gets a `ready` frame, then what it missed, then every event as it happens, and its actions
|
||||
//! reach the same engine the terminal drives. A joined client can't switch or close the session,
|
||||
//! and leaving closes nothing. The terminal is told when one joins, leaves, or answers a prompt.
|
||||
|
||||
mod clients;
|
||||
mod guest;
|
||||
mod guests;
|
||||
mod snapshot;
|
||||
|
||||
use super::rpc::{GithubWrites, Policy};
|
||||
use luxe_core::engine::Action;
|
||||
use luxe_core::local_endpoint::{EndpointListener, LiveSession, Publication};
|
||||
use luxe_core::Event;
|
||||
use snapshot::Snapshot;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
/// Events the terminal hasn't drawn yet, as deep as the stream it reads without sharing.
|
||||
const TERMINAL_BUFFER: usize = 256;
|
||||
|
||||
/// How far a joined client may fall behind before it's dropped and has to join again.
|
||||
///
|
||||
/// Deep because token deltas are one event each, and a phone on a slow link reads in bursts.
|
||||
const CLIENT_BACKLOG: usize = 4096;
|
||||
|
||||
/// The session on offer. Dropping it takes the offer down and disconnects every client.
|
||||
pub(crate) struct Sharing {
|
||||
tasks: Vec<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Drop for Sharing {
|
||||
fn drop(&mut self) {
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What every joined client shares: the session's state, its live events, and the terminal.
|
||||
#[derive(Clone)]
|
||||
struct Shared {
|
||||
snapshot: Arc<Mutex<Snapshot>>,
|
||||
live: broadcast::Sender<Event>,
|
||||
engine_tx: mpsc::Sender<Action>,
|
||||
/// Weak, so the terminal's stream ends with the engine's while clients are still connected:
|
||||
/// `--rpc` exits on that end
|
||||
terminal: mpsc::WeakSender<Event>,
|
||||
cwd: String,
|
||||
policy: Policy,
|
||||
/// What `select_model` resolves through and `list_models` lists
|
||||
models: super::rpc::Models,
|
||||
/// The process whose descendants are refused: this one, outside tests
|
||||
agent_pid: u32,
|
||||
/// Who's joined now, for the terminal's dock
|
||||
guests: guests::GuestList,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// The snapshot, even if a panic elsewhere poisoned the lock: it holds no invariant a
|
||||
/// half-finished update could break that a client couldn't recover from by joining again.
|
||||
fn snapshot(&self) -> MutexGuard<'_, Snapshot> {
|
||||
self.snapshot.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Fold `event` into the snapshot and hand it to every client, as one step so a client
|
||||
/// joining in between sees it exactly once.
|
||||
fn publish(&self, event: &Event) {
|
||||
let mut snapshot = self.snapshot();
|
||||
snapshot.observe(event);
|
||||
// No receivers is the normal state with nobody joined
|
||||
let _ = self.live.send(event.clone());
|
||||
}
|
||||
|
||||
/// Put a line in front of the person at the terminal.
|
||||
async fn tell_terminal(&self, notice: String) {
|
||||
self.to_terminal(Event::Notice(notice)).await;
|
||||
}
|
||||
|
||||
/// Tell the terminal who's joined now, for its dock.
|
||||
async fn tell_guests(&self) {
|
||||
self.to_terminal(Event::GuestsChanged(self.guests.names())).await;
|
||||
}
|
||||
|
||||
async fn to_terminal(&self, event: Event) {
|
||||
// The terminal gone means the session is ending, and nobody is left to tell
|
||||
let Some(terminal) = self.terminal.upgrade() else { return };
|
||||
let _ = terminal.send(event).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Offer the session `events` belongs to, and return the stream the terminal reads instead.
|
||||
///
|
||||
/// With `joinable` off nothing listens. When the endpoint can't be opened the terminal runs
|
||||
/// exactly as it would unshared, and the reason goes to the log: sharing is a convenience,
|
||||
/// never a reason to refuse to start.
|
||||
pub(crate) fn share(
|
||||
events: mpsc::Receiver<Event>,
|
||||
engine_tx: mpsc::Sender<Action>,
|
||||
settings: &crate::engine_setup::AgentSettings,
|
||||
session_id: &str,
|
||||
) -> (mpsc::Receiver<Event>, Option<Sharing>) {
|
||||
let config = luxe_core::config::Config::load(&settings.state_root);
|
||||
if !config.joinable() {
|
||||
tracing::info!("not sharing the session: joinable is off");
|
||||
return (events, None);
|
||||
}
|
||||
let Some((listener, record)) = open_endpoint(settings, session_id) else {
|
||||
return (events, None);
|
||||
};
|
||||
let (terminal, terminal_rx) = mpsc::channel(TERMINAL_BUFFER);
|
||||
let shared = Shared {
|
||||
snapshot: Arc::new(Mutex::new(Snapshot::new(session_id.to_string()))),
|
||||
live: broadcast::channel(CLIENT_BACKLOG).0,
|
||||
engine_tx,
|
||||
terminal: terminal.downgrade(),
|
||||
cwd: settings.work_root.to_string_lossy().into_owned(),
|
||||
policy: guest_policy(settings, &config),
|
||||
models: Arc::new(super::rpc::CatalogResolver { settings: settings.clone() }),
|
||||
agent_pid: std::process::id(),
|
||||
guests: guests::GuestList::default(),
|
||||
};
|
||||
let tasks = vec![
|
||||
tokio::spawn(clients::accept(listener, shared.clone())),
|
||||
tokio::spawn(tee(events, shared, terminal, record)),
|
||||
];
|
||||
tracing::info!(%session_id, "sharing the session on the local endpoint");
|
||||
(terminal_rx, Some(Sharing { tasks }))
|
||||
}
|
||||
|
||||
/// Listen on the local endpoint and publish the record that lists it.
|
||||
fn open_endpoint(
|
||||
settings: &crate::engine_setup::AgentSettings,
|
||||
session_id: &str,
|
||||
) -> Option<(EndpointListener, Option<Record>)> {
|
||||
let dir = luxe_core::user_dirs::luxe_runtime_dir();
|
||||
let listener = match EndpointListener::bind(&dir) {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, dir = %dir.display(), "not sharing the session");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let record = publish_record(&dir, &listener, settings, session_id);
|
||||
Some((listener, record))
|
||||
}
|
||||
|
||||
/// What a joined client may do: what the terminal may, with GitHub writes left off, since
|
||||
/// `--github-writes` is a choice made for one `--rpc` client and nobody made it for this one.
|
||||
fn guest_policy(
|
||||
settings: &crate::engine_setup::AgentSettings,
|
||||
config: &luxe_core::config::Config,
|
||||
) -> Policy {
|
||||
let mode = crate::engine_setup::effective_permission_mode(
|
||||
&settings.state_root,
|
||||
settings.permission_mode,
|
||||
settings.trust_project,
|
||||
);
|
||||
Policy {
|
||||
github_writes: GithubWrites::for_launch(false, mode),
|
||||
github_sections: config.github.sections(),
|
||||
joined: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy every engine event to the clients and on to the terminal, until either end is gone.
|
||||
///
|
||||
/// Owns the terminal's only strong sender, so the terminal's stream ends when this does.
|
||||
async fn tee(
|
||||
mut events: mpsc::Receiver<Event>,
|
||||
shared: Shared,
|
||||
terminal: mpsc::Sender<Event>,
|
||||
mut record: Option<Record>,
|
||||
) {
|
||||
while let Some(event) = events.recv().await {
|
||||
shared.publish(&event);
|
||||
if let (Event::SessionLoaded { session_id, .. }, Some(record)) = (&event, record.as_mut()) {
|
||||
record.follow(session_id);
|
||||
}
|
||||
if terminal.send(event).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The published record of this session, which `luxe join` and `luxe remote` list.
|
||||
struct Record {
|
||||
session: LiveSession,
|
||||
publication: Publication,
|
||||
}
|
||||
|
||||
impl Record {
|
||||
/// Keep the record naming the session the terminal shows.
|
||||
fn follow(&mut self, session_id: &str) {
|
||||
if self.session.session_id == session_id {
|
||||
return;
|
||||
}
|
||||
self.session.session_id = session_id.to_string();
|
||||
if let Err(error) = self.publication.update(&self.session) {
|
||||
tracing::warn!(%error, "could not update the shared session's record");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the record that lists this session, or log why it couldn't be written: the endpoint
|
||||
/// still works for a client that knows its address.
|
||||
fn publish_record(
|
||||
dir: &Path,
|
||||
listener: &EndpointListener,
|
||||
settings: &crate::engine_setup::AgentSettings,
|
||||
session_id: &str,
|
||||
) -> Option<Record> {
|
||||
let session = LiveSession {
|
||||
pid: std::process::id(),
|
||||
session_id: session_id.to_string(),
|
||||
cwd: settings.work_root.to_string_lossy().into_owned(),
|
||||
address: listener.address().to_string(),
|
||||
luxe_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
};
|
||||
match session.publish(dir) {
|
||||
Ok(publication) => Some(Record { session, publication }),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "could not publish the shared session's record");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
185
crates/luxe-cli/src/cli/share/clients.rs
Normal file
185
crates/luxe-cli/src/cli/share/clients.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
//! One joined client at a time: checked, caught up, then served like any RPC client.
|
||||
|
||||
use super::super::rpc;
|
||||
use super::guest::{self, Guest};
|
||||
use super::Shared;
|
||||
use luxe_core::engine::Action;
|
||||
use luxe_core::local_endpoint::{EndpointListener, Joined, LocalStream};
|
||||
use luxe_core::Event;
|
||||
use tokio::sync::broadcast::{self, error::RecvError};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
/// Actions a client may queue before its reads wait on the engine.
|
||||
const ACTION_BUFFER: usize = 32;
|
||||
|
||||
/// Frames queued for one client's socket; past this, the shared backlog takes the slack.
|
||||
const CLIENT_WRITE_BUFFER: usize = 256;
|
||||
|
||||
/// Bytes of a client's input held between reading it and the protocol taking it.
|
||||
const SIFTED_BUFFER: usize = 64 * 1024;
|
||||
|
||||
/// How long to wait before accepting again after an accept failed, so a lasting failure (out of
|
||||
/// file handles) logs a few lines a second instead of spinning a core.
|
||||
const ACCEPT_RETRY: std::time::Duration = std::time::Duration::from_millis(250);
|
||||
|
||||
/// Take clients until the task is aborted, which disconnects every one of them.
|
||||
pub(super) async fn accept(mut listener: EndpointListener, shared: Shared) {
|
||||
let mut clients = JoinSet::new();
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok(joined) => {
|
||||
clients.spawn(serve_client(joined, shared.clone()));
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "could not accept a client of the shared session");
|
||||
tokio::time::sleep(ACCEPT_RETRY).await;
|
||||
}
|
||||
}
|
||||
// Reap finished clients so a long session doesn't keep one entry per visit
|
||||
while clients.try_join_next().is_some() {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one client from its `ready` frame until it leaves or the session ends.
|
||||
async fn serve_client(joined: Joined, shared: Shared) {
|
||||
let (guest, named) = Guest::new(joined.peer);
|
||||
if guest.descends_from(shared.agent_pid).await {
|
||||
tracing::warn!(peer = ?joined.peer, "refused a client started by this session's agent");
|
||||
let notice = format!("Refused {guest}: the agent started it, and can't approve itself");
|
||||
shared.tell_terminal(notice).await;
|
||||
return;
|
||||
}
|
||||
let served = serve_rpc(joined.stream, &shared, guest.clone(), named);
|
||||
let (arrival, ()) = tokio::join!(announce(&shared, guest.clone()), served);
|
||||
tracing::info!(peer = ?joined.peer, %guest, "a client left the shared session");
|
||||
let Some(arrival) = arrival else { return };
|
||||
shared.guests.leave(arrival.seat);
|
||||
shared.tell_guests().await;
|
||||
if arrival.told {
|
||||
shared.tell_terminal(format!("{guest} left this session")).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// How a client was announced: its seat in the dock's list, and whether the transcript was told.
|
||||
struct Arrival {
|
||||
seat: u64,
|
||||
told: bool,
|
||||
}
|
||||
|
||||
/// Seats the client in the dock's list once it has had a moment to say who it is, unless it opened
|
||||
/// as watch-only. Only someone else's client earns a line in the transcript: the person at the
|
||||
/// terminal knows their own phone joined, and a phone reconnects often.
|
||||
async fn announce(shared: &Shared, mut guest: Guest) -> Option<Arrival> {
|
||||
guest.introduced().await;
|
||||
if guest.watch_only() {
|
||||
tracing::info!(%guest, "a watch-only client joined the shared session");
|
||||
return None;
|
||||
}
|
||||
let seat = shared.guests.arrive(guest.to_string());
|
||||
shared.tell_guests().await;
|
||||
let told = !guest.yours();
|
||||
if told {
|
||||
shared.tell_terminal(format!("{guest} joined this session")).await;
|
||||
}
|
||||
Some(Arrival { seat, told })
|
||||
}
|
||||
|
||||
/// The RPC protocol over `stream`, fed from the shared session rather than an engine of its own.
|
||||
async fn serve_rpc(
|
||||
stream: LocalStream,
|
||||
shared: &Shared,
|
||||
guest: Guest,
|
||||
named: tokio::sync::watch::Sender<Option<guest::Introduction>>,
|
||||
) {
|
||||
let (opening, frames, live) = catch_up(shared);
|
||||
let (events_tx, events_rx) = mpsc::channel(CLIENT_WRITE_BUFFER);
|
||||
let _feed = AbortOnDrop(tokio::spawn(feed(frames, live, events_tx)));
|
||||
let (actions_tx, actions_rx) = mpsc::channel(ACTION_BUFFER);
|
||||
let _relay = AbortOnDrop(tokio::spawn(relay(actions_rx, shared.clone(), guest)));
|
||||
let (read, write) = tokio::io::split(stream);
|
||||
let (sifted, input) = tokio::io::duplex(SIFTED_BUFFER);
|
||||
let _sift = AbortOnDrop(tokio::spawn(guest::sift(read, sifted, named)));
|
||||
let (policy, models) = (shared.policy.clone(), shared.models.clone());
|
||||
let served = rpc::serve(opening, events_rx, actions_tx, input, write, models, policy);
|
||||
if let Err(error) = served.await {
|
||||
tracing::warn!(%error, "a shared session's client ended with an error");
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ready` frame and transcript, what else the client missed, and the live stream picking up
|
||||
/// right after it.
|
||||
///
|
||||
/// Taken under the lock `publish` holds, so no event falls between the catch-up and the stream.
|
||||
fn catch_up(shared: &Shared) -> (rpc::Opening, Vec<Event>, broadcast::Receiver<Event>) {
|
||||
let snapshot = shared.snapshot();
|
||||
let ready = Event::Ready {
|
||||
protocol_version: luxe_core::PROTOCOL_VERSION,
|
||||
luxe_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
session_id: snapshot.session_id().to_string(),
|
||||
cwd: shared.cwd.clone(),
|
||||
github_writes: shared.policy.github_writes.allowed(),
|
||||
};
|
||||
let opening = rpc::Opening { ready, transcript: Some(snapshot.transcript()) };
|
||||
(opening, snapshot.frames(), shared.live.subscribe())
|
||||
}
|
||||
|
||||
/// Hand the client its catch-up and then the live stream, until it falls too far behind.
|
||||
async fn feed(frames: Vec<Event>, mut live: broadcast::Receiver<Event>, out: mpsc::Sender<Event>) {
|
||||
for frame in frames {
|
||||
if out.send(frame).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let event = match live.recv().await {
|
||||
Ok(event) => event,
|
||||
Err(RecvError::Lagged(missed)) => {
|
||||
let notice = format!("This client fell {missed} events behind: join again");
|
||||
let _ = out.send(Event::Notice(notice)).await;
|
||||
return;
|
||||
}
|
||||
Err(RecvError::Closed) => return,
|
||||
};
|
||||
if out.send(event).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pass the client's actions to the engine, telling the terminal about each answer it gives.
|
||||
async fn relay(mut actions: mpsc::Receiver<Action>, shared: Shared, guest: Guest) {
|
||||
while let Some(action) = actions.recv().await {
|
||||
let answer = answer_notice(&shared, &action, &guest);
|
||||
if shared.engine_tx.send(action).await.is_err() {
|
||||
return;
|
||||
}
|
||||
if let Some(notice) = answer {
|
||||
shared.tell_terminal(notice).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to tell the terminal about `action`, when it answers a prompt that's still waiting.
|
||||
///
|
||||
/// A prompt the terminal already answered is a no-op for the engine, so it says nothing here.
|
||||
fn answer_notice(shared: &Shared, action: &Action, guest: &Guest) -> Option<String> {
|
||||
use luxe_core::permission::PermissionReply;
|
||||
let (id, verb) = match action {
|
||||
Action::RespondPermission { id, reply: PermissionReply::Reject } => (id.as_str(), "Denied"),
|
||||
Action::RespondPermission { id, .. } => (id.as_str(), "Approved"),
|
||||
Action::AnswerQuestion { id, .. } => (id.as_str(), "Answered"),
|
||||
_ => return None,
|
||||
};
|
||||
let waiting = shared.snapshot().is_waiting(id);
|
||||
waiting.then(|| format!("{verb} from {guest}"))
|
||||
}
|
||||
|
||||
/// Aborts its task when dropped, so a client's helpers end with it.
|
||||
struct AbortOnDrop(tokio::task::JoinHandle<()>);
|
||||
|
||||
impl Drop for AbortOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
144
crates/luxe-cli/src/cli/share/guest.rs
Normal file
144
crates/luxe-cli/src/cli/share/guest.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
//! Guest — who a joined client is, as the terminal names it: the name it introduced itself by, or
|
||||
//! its process id.
|
||||
//!
|
||||
//! The bridge introduces each device it relays for, so the terminal says "Approved from iPhone"
|
||||
//! rather than naming the bridge's process. The name is cosmetic, since any program running as
|
||||
//! you could claim one, and the ancestry check goes by process id, not by name.
|
||||
//!
|
||||
//! A client that opens by introducing itself as watch-only, like the bridge's notification
|
||||
//! watcher, isn't announced. Being unseen is why it can't act: everything it sends after that is
|
||||
//! dropped here, before the protocol sees it.
|
||||
|
||||
use luxe_core::local_endpoint::descends_from;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// How long a new client gets to introduce itself before the terminal says it joined.
|
||||
pub(super) const INTRODUCTION_WAIT: std::time::Duration = std::time::Duration::from_secs(1);
|
||||
|
||||
/// The longest name the terminal shows.
|
||||
const NAME_LIMIT: usize = 40;
|
||||
|
||||
/// What a client said about itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct Introduction {
|
||||
pub(super) name: String,
|
||||
pub(super) watch_only: bool,
|
||||
/// Paired by the person at the terminal, so its comings and goings needn't be told
|
||||
pub(super) yours: bool,
|
||||
}
|
||||
|
||||
/// Who joined.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Guest {
|
||||
pid: Option<u32>,
|
||||
said: watch::Receiver<Option<Introduction>>,
|
||||
}
|
||||
|
||||
impl Guest {
|
||||
/// A guest known by `pid` until it introduces itself through the returned sender.
|
||||
pub(super) fn new(pid: Option<u32>) -> (Self, watch::Sender<Option<Introduction>>) {
|
||||
let (named, said) = watch::channel(None);
|
||||
(Self { pid, said }, named)
|
||||
}
|
||||
|
||||
/// Whether the client opened as watch-only, so it isn't announced.
|
||||
pub(super) fn watch_only(&self) -> bool {
|
||||
self.said.borrow().as_ref().is_some_and(|said| said.watch_only)
|
||||
}
|
||||
|
||||
/// Whether the bridge said the person at the terminal paired it. Cosmetic, as the name is: it
|
||||
/// decides only whether joining earns a line in the transcript.
|
||||
pub(super) fn yours(&self) -> bool {
|
||||
self.said.borrow().as_ref().is_some_and(|said| said.yours)
|
||||
}
|
||||
|
||||
/// Whether the client is `agent` or a process it started, directly or not.
|
||||
///
|
||||
/// A tripwire, not a wall: a command can detach from its parent first. Unknown ancestry
|
||||
/// passes, since refusing it would refuse every client on a system that hides it.
|
||||
pub(super) async fn descends_from(&self, agent: u32) -> bool {
|
||||
let Some(peer) = self.pid else { return false };
|
||||
let ancestry = tokio::task::spawn_blocking(move || descends_from(peer, agent));
|
||||
ancestry.await.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Waits up to [`INTRODUCTION_WAIT`] for a name, so "joined" names the device.
|
||||
pub(super) async fn introduced(&mut self) {
|
||||
let named = self.said.wait_for(Option::is_some);
|
||||
let _ = tokio::time::timeout(INTRODUCTION_WAIT, named).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Guest {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if let Some(said) = self.said.borrow().as_ref() {
|
||||
return f.write_str(&said.name);
|
||||
}
|
||||
match self.pid {
|
||||
Some(pid) => write!(f, "a client (pid {pid})"),
|
||||
None => f.write_str("a client"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the client's lines to `protocol`, keeping its introductions for `named`.
|
||||
///
|
||||
/// Read here rather than in the protocol because the name is the share layer's business: the
|
||||
/// engine has no use for it, and the client that started a session has nobody to introduce
|
||||
/// itself to. Once a client opens as watch-only, nothing more of it is read for the protocol.
|
||||
pub(super) async fn sift(
|
||||
client: impl AsyncRead + Unpin,
|
||||
mut protocol: impl AsyncWrite + Unpin,
|
||||
named: watch::Sender<Option<Introduction>>,
|
||||
) {
|
||||
let mut lines = BufReader::new(client).lines();
|
||||
let mut opening = true;
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if !for_protocol(&line, &mut opening, &named) {
|
||||
continue;
|
||||
}
|
||||
if protocol.write_all(format!("{line}\n").as_bytes()).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `line` goes on to the protocol: not when it's an introduction, which `named` keeps,
|
||||
/// nor when the client opened as watch-only.
|
||||
fn for_protocol(
|
||||
line: &str,
|
||||
opening: &mut bool,
|
||||
named: &watch::Sender<Option<Introduction>>,
|
||||
) -> bool {
|
||||
if named.borrow().as_ref().is_some_and(|said| said.watch_only) {
|
||||
tracing::warn!("dropped a line from a watch-only client");
|
||||
return false;
|
||||
}
|
||||
let first = std::mem::take(opening);
|
||||
let Some(mut said) = introduction(line) else { return true };
|
||||
said.watch_only &= first;
|
||||
named.send_replace(Some(said));
|
||||
false
|
||||
}
|
||||
|
||||
/// What an `introduce` frame says, its name made fit for one line of the terminal.
|
||||
///
|
||||
/// Anything else, a malformed introduction included, is `None` and goes on to the protocol, which
|
||||
/// refuses it by name.
|
||||
fn introduction(line: &str) -> Option<Introduction> {
|
||||
if !line.contains("introduce") {
|
||||
return None;
|
||||
}
|
||||
let luxe_core::event::Action::Introduce { name, watch_only, yours } =
|
||||
serde_json::from_str(line).ok()?
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let name: String = name.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
let name: String = name.trim().chars().take(NAME_LIMIT).collect();
|
||||
(!name.is_empty()).then_some(Introduction { name, watch_only, yours })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
71
crates/luxe-cli/src/cli/share/guest/tests.rs
Normal file
71
crates/luxe-cli/src/cli/share/guest/tests.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use super::*;
|
||||
|
||||
fn name_of(line: &str) -> Option<String> {
|
||||
introduction(line).map(|said| said.name)
|
||||
}
|
||||
|
||||
/// An introduction gives its name, made fit for one line; nothing else does.
|
||||
///
|
||||
/// The break this catches, one per line: taking the name from another frame (submit), passing a
|
||||
/// newline or escape code into the terminal's notice (control), letting a long name push the
|
||||
/// notice off the line (long), or naming a client nothing (blank).
|
||||
#[test]
|
||||
fn only_an_introduction_names_a_client() {
|
||||
let introduce = |name: &str| format!(r#"{{"kind":"introduce","content":{{"name":"{name}"}}}}"#);
|
||||
assert_eq!(name_of(&introduce("iPhone")).as_deref(), Some("iPhone"));
|
||||
let submit = r#"{"kind":"submit_user_message","content":{"text":"introduce yourself"}}"#;
|
||||
assert_eq!(name_of(submit), None);
|
||||
assert_eq!(name_of(&introduce(r"Alex\n\u001b[2Jphone")).as_deref(), Some("Alex [2Jphone"));
|
||||
assert_eq!(name_of(&introduce(&"x".repeat(60))).map(|name| name.len()), Some(NAME_LIMIT));
|
||||
assert_eq!(name_of(&introduce(" ")), None);
|
||||
}
|
||||
|
||||
/// What `input` passes on to the protocol, and the guest it leaves.
|
||||
async fn sifted(input: &str) -> (String, Guest) {
|
||||
let (sifted, mut protocol) = tokio::io::duplex(1024);
|
||||
let (guest, named) = Guest::new(Some(7));
|
||||
sift(input.as_bytes(), sifted, named).await;
|
||||
let mut passed = String::new();
|
||||
tokio::io::AsyncReadExt::read_to_string(&mut protocol, &mut passed).await.unwrap();
|
||||
(passed, guest)
|
||||
}
|
||||
|
||||
const WATCHER: &str =
|
||||
"{\"kind\":\"introduce\",\"content\":{\"name\":\"Notifications\",\"watch_only\":true}}\n";
|
||||
|
||||
/// The client's other lines reach the protocol in order, and its introduction doesn't.
|
||||
///
|
||||
/// The break this catches: forwarding the introduction, which the protocol refuses back to the
|
||||
/// bridge as if it had sent something wrong; or losing the line after it.
|
||||
#[tokio::test]
|
||||
async fn sifting_keeps_the_introduction_and_passes_the_rest() {
|
||||
let input = "{\"kind\":\"cancel\"}\n{\"kind\":\"introduce\",\"content\":{\"name\":\"iPad\"}}\n\
|
||||
{\"kind\":\"retry\"}\n";
|
||||
let (passed, guest) = sifted(input).await;
|
||||
assert_eq!(passed, "{\"kind\":\"cancel\"}\n{\"kind\":\"retry\"}\n");
|
||||
assert_eq!(guest.to_string(), "iPad");
|
||||
assert!(!guest.watch_only());
|
||||
}
|
||||
|
||||
/// A client that opens as watch-only is marked so, and nothing it sends after reaches the
|
||||
/// protocol.
|
||||
///
|
||||
/// The break this catches: an unannounced client steering or approving, unseen at the desk.
|
||||
#[tokio::test]
|
||||
async fn a_watch_only_client_cant_act() {
|
||||
let (passed, guest) = sifted(&format!("{WATCHER}{{\"kind\":\"cancel\"}}\n")).await;
|
||||
assert_eq!(passed, "");
|
||||
assert!(guest.watch_only());
|
||||
assert_eq!(guest.to_string(), "Notifications");
|
||||
}
|
||||
|
||||
/// Watch-only counts only as the opening line.
|
||||
///
|
||||
/// The break this catches: a client cancelling the turn, then introducing itself as watch-only so
|
||||
/// the terminal never says it was there.
|
||||
#[tokio::test]
|
||||
async fn watch_only_after_acting_is_just_a_name() {
|
||||
let (passed, guest) = sifted(&format!("{{\"kind\":\"cancel\"}}\n{WATCHER}")).await;
|
||||
assert_eq!(passed, "{\"kind\":\"cancel\"}\n");
|
||||
assert!(!guest.watch_only());
|
||||
}
|
||||
59
crates/luxe-cli/src/cli/share/guests.rs
Normal file
59
crates/luxe-cli/src/cli/share/guests.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
//! Guests — who's joined the shared session right now, by name, for the terminal's dock.
|
||||
//!
|
||||
//! Each announced client takes a seat when it joins and gives it up when it leaves, so two of the
|
||||
//! same name (a phone that reconnected before its old socket closed) are counted apart.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
/// The clients in the session now, in the order they joined.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct GuestList {
|
||||
seated: Arc<Mutex<Vec<(u64, String)>>>,
|
||||
next: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl GuestList {
|
||||
/// Seats `name`, returning the seat to give up on leaving.
|
||||
pub(super) fn arrive(&self, name: String) -> u64 {
|
||||
let seat = self.next.fetch_add(1, Ordering::Relaxed);
|
||||
self.seated().push((seat, name));
|
||||
seat
|
||||
}
|
||||
|
||||
/// Gives up `seat`.
|
||||
pub(super) fn leave(&self, seat: u64) {
|
||||
self.seated().retain(|(taken, _)| *taken != seat);
|
||||
}
|
||||
|
||||
/// Everyone seated, by name.
|
||||
pub(super) fn names(&self) -> Vec<String> {
|
||||
self.seated().iter().map(|(_, name)| name.clone()).collect()
|
||||
}
|
||||
|
||||
/// The list, even if a panic elsewhere poisoned the lock: a stale name is all it could hold.
|
||||
fn seated(&self) -> MutexGuard<'_, Vec<(u64, String)>> {
|
||||
self.seated.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A guest leaves by its seat, so one of two with the same name leaving leaves the other.
|
||||
///
|
||||
/// The break this catches: a phone that reconnected before its old socket closed vanishing
|
||||
/// from the dock when the old one goes, while it's still joined.
|
||||
#[test]
|
||||
fn a_guest_leaves_by_its_seat_not_its_name() {
|
||||
let guests = GuestList::default();
|
||||
let old = guests.arrive("iPhone".into());
|
||||
let _new = guests.arrive("iPhone".into());
|
||||
let ipad = guests.arrive("iPad".into());
|
||||
guests.leave(old);
|
||||
assert_eq!(guests.names(), ["iPhone", "iPad"]);
|
||||
guests.leave(ipad);
|
||||
assert_eq!(guests.names(), ["iPhone"]);
|
||||
}
|
||||
}
|
||||
140
crates/luxe-cli/src/cli/share/snapshot.rs
Normal file
140
crates/luxe-cli/src/cli/share/snapshot.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
//! What a client joining mid-session has missed, kept current from the event stream.
|
||||
//!
|
||||
//! A joiner opens on the same frames a resume would show: the transcript so far, whether a turn is
|
||||
//! running, then the latest state, usage and workspace, the tool cards of a turn still running, and
|
||||
//! any prompt still waiting for an answer. Text a reply has already streamed is not replayed; it
|
||||
//! arrives whole once the message commits.
|
||||
|
||||
use super::super::rpc::SharedTranscript;
|
||||
use luxe_core::event::SessionMessage;
|
||||
use luxe_core::Event;
|
||||
use std::mem::discriminant;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The session as a client joining now should first see it.
|
||||
pub(super) struct Snapshot {
|
||||
session_id: String,
|
||||
/// Shared with the joiners being sent it, so a join costs a reference, not a copy
|
||||
transcript: Arc<Vec<SessionMessage>>,
|
||||
/// Whether a turn has started and not yet ended
|
||||
turning: bool,
|
||||
/// The newest event of each kind where only the newest matters
|
||||
latest: Vec<Event>,
|
||||
/// Tool cards of the turn in flight, by call id
|
||||
activity: Vec<Event>,
|
||||
/// Permission prompts and questions nobody has answered yet
|
||||
waiting: Vec<Event>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// An empty snapshot of `session_id`, before the engine has said anything.
|
||||
pub(super) fn new(session_id: String) -> Self {
|
||||
Self {
|
||||
session_id,
|
||||
transcript: Arc::default(),
|
||||
turning: false,
|
||||
latest: Vec::new(),
|
||||
activity: Vec::new(),
|
||||
waiting: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The session the stream is about now.
|
||||
pub(super) fn session_id(&self) -> &str {
|
||||
&self.session_id
|
||||
}
|
||||
|
||||
/// Whether the prompt `id` names is still waiting for an answer.
|
||||
pub(super) fn is_waiting(&self, id: &str) -> bool {
|
||||
self.waiting.iter().any(|prompt| prompt_id(prompt) == id)
|
||||
}
|
||||
|
||||
/// Fold one event in.
|
||||
pub(super) fn observe(&mut self, event: &Event) {
|
||||
match event {
|
||||
Event::SessionLoaded { session_id, messages } => self.load(session_id, messages),
|
||||
Event::MessageCommitted { entry_id, message, .. } => {
|
||||
let message =
|
||||
SessionMessage { entry_id: entry_id.clone(), message: message.clone() };
|
||||
// Copies the list only if a joiner is still being sent it, which is brief
|
||||
Arc::make_mut(&mut self.transcript).push(message);
|
||||
}
|
||||
Event::StateChanged(_)
|
||||
| Event::SessionUsage(_)
|
||||
| Event::ContextUsage { .. }
|
||||
| Event::PlanUsage(_)
|
||||
| Event::WorkspaceUpdated(_) => replace_kind(&mut self.latest, event),
|
||||
Event::ToolActivityUpdated(activity) => self.track_activity(&activity.call_id, event),
|
||||
Event::PermissionRequested { .. } | Event::QuestionAsked { .. } => {
|
||||
self.waiting.push(event.clone());
|
||||
}
|
||||
Event::PromptClosed { id } => self.waiting.retain(|prompt| prompt_id(prompt) != id),
|
||||
Event::TurnStarted => self.turning = true,
|
||||
Event::TurnEnded { .. } => self.end_turn(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The transcript so far, which a new client is sent first, as its `session_loaded` frame.
|
||||
pub(super) fn transcript(&self) -> SharedTranscript {
|
||||
SharedTranscript {
|
||||
session_id: self.session_id.clone(),
|
||||
messages: Arc::clone(&self.transcript),
|
||||
}
|
||||
}
|
||||
|
||||
/// The frames that bring a new client up to now after the transcript, oldest first.
|
||||
pub(super) fn frames(&self) -> Vec<Event> {
|
||||
self.turning
|
||||
.then_some(Event::TurnStarted)
|
||||
.into_iter()
|
||||
.chain(self.latest.iter().cloned())
|
||||
.chain(self.activity.iter().cloned())
|
||||
.chain(self.waiting.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Start over on a loaded session, which replaces everything a front-end shows.
|
||||
fn load(&mut self, session_id: &str, messages: &[SessionMessage]) {
|
||||
self.session_id = session_id.to_string();
|
||||
self.transcript = Arc::new(messages.to_vec());
|
||||
self.end_turn();
|
||||
}
|
||||
|
||||
/// Nothing of a finished turn is still running or waiting.
|
||||
fn end_turn(&mut self) {
|
||||
self.turning = false;
|
||||
self.activity.clear();
|
||||
self.waiting.clear();
|
||||
}
|
||||
|
||||
/// Keep only the newest card for `call_id`.
|
||||
fn track_activity(&mut self, call_id: &str, event: &Event) {
|
||||
self.activity.retain(|kept| activity_call(kept) != Some(call_id));
|
||||
self.activity.push(event.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the kept event of `event`'s kind, or keep it as the first of its kind.
|
||||
fn replace_kind(kept: &mut Vec<Event>, event: &Event) {
|
||||
let kind = discriminant(event);
|
||||
kept.retain(|old| discriminant(old) != kind);
|
||||
kept.push(event.clone());
|
||||
}
|
||||
|
||||
/// The id a waiting prompt answers to, in the form `PromptClosed` carries.
|
||||
fn prompt_id(prompt: &Event) -> &str {
|
||||
match prompt {
|
||||
Event::PermissionRequested { id, .. } => id.as_str(),
|
||||
Event::QuestionAsked { id, .. } => id.as_str(),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool call a kept card belongs to.
|
||||
fn activity_call(event: &Event) -> Option<&str> {
|
||||
match event {
|
||||
Event::ToolActivityUpdated(activity) => Some(&activity.call_id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
385
crates/luxe-cli/src/cli/share/tests.rs
Normal file
385
crates/luxe-cli/src/cli/share/tests.rs
Normal file
@@ -0,0 +1,385 @@
|
||||
use super::*;
|
||||
use luxe_core::local_endpoint::{connect, LocalStream};
|
||||
use luxe_core::permission::PermissionRequestId;
|
||||
use luxe_core::Message;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
|
||||
/// A shared session with no engine or terminal behind it, and the far ends of both.
|
||||
struct Harness {
|
||||
shared: Shared,
|
||||
engine_rx: mpsc::Receiver<Action>,
|
||||
terminal_rx: mpsc::Receiver<Event>,
|
||||
/// The strong end `tee` owns in a real session, which keeps the terminal's stream open
|
||||
terminal: mpsc::Sender<Event>,
|
||||
}
|
||||
|
||||
/// No process descends from this one, so the tripwire lets the test's own connections in.
|
||||
const NOBODY: u32 = u32::MAX;
|
||||
|
||||
/// A catalog with nothing in it, so no test reads the developer's `models.json`.
|
||||
struct NoModels;
|
||||
|
||||
impl super::super::rpc::ModelResolver for NoModels {
|
||||
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo {
|
||||
let r#ref = luxe_core::provider::ModelRef::new(provider, id);
|
||||
luxe_core::ModelInfo { r#ref, ..Default::default() }
|
||||
}
|
||||
|
||||
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn harness(agent_pid: u32) -> Harness {
|
||||
let (engine_tx, engine_rx) = mpsc::channel(16);
|
||||
let (terminal, terminal_rx) = mpsc::channel(16);
|
||||
let shared = Shared {
|
||||
snapshot: Arc::new(Mutex::new(Snapshot::new("session-1".into()))),
|
||||
live: broadcast::channel(CLIENT_BACKLOG).0,
|
||||
engine_tx,
|
||||
terminal: terminal.downgrade(),
|
||||
cwd: "/work".into(),
|
||||
policy: Policy {
|
||||
github_writes: GithubWrites::NotEnabled,
|
||||
github_sections: Vec::new(),
|
||||
joined: true,
|
||||
},
|
||||
models: Arc::new(NoModels),
|
||||
agent_pid,
|
||||
guests: super::guests::GuestList::default(),
|
||||
};
|
||||
Harness { shared, engine_rx, terminal_rx, terminal }
|
||||
}
|
||||
|
||||
fn permission_asked(id: &PermissionRequestId) -> Event {
|
||||
Event::PermissionRequested {
|
||||
id: id.clone(),
|
||||
session_id: "session-1".into(),
|
||||
tool: "bash".into(),
|
||||
permission: "bash".into(),
|
||||
summary: "Run: cargo test".into(),
|
||||
always_patterns: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn committed(text: &str) -> Event {
|
||||
Event::MessageCommitted {
|
||||
session_id: "session-1".into(),
|
||||
entry_id: luxe_core::session::EntryId(text.into()),
|
||||
message: Message::user(text),
|
||||
}
|
||||
}
|
||||
|
||||
fn kinds(frames: &[Event]) -> Vec<&'static str> {
|
||||
frames
|
||||
.iter()
|
||||
.map(|frame| match frame {
|
||||
Event::SessionLoaded { .. } => "session_loaded",
|
||||
Event::StateChanged(_) => "state_changed",
|
||||
Event::ContextUsage { .. } => "context_usage",
|
||||
Event::PermissionRequested { .. } => "permission_requested",
|
||||
Event::TurnStarted => "turn_started",
|
||||
_ => "other",
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A joiner opens on the transcript, then the newest of each kept state, then the prompt.
|
||||
///
|
||||
/// The break this catches: dropping the commit fold, which opens a joined phone on an empty
|
||||
/// conversation, or keeping every usage update, which replays a turn's worth of stale readings.
|
||||
#[test]
|
||||
fn a_joiner_catches_up_on_the_transcript_state_and_waiting_prompt() {
|
||||
let mut snapshot = Snapshot::new("session-1".into());
|
||||
let id = PermissionRequestId::new();
|
||||
for event in [
|
||||
committed("first"),
|
||||
Event::ContextUsage { used_tokens: 1, context_window: 10 },
|
||||
committed("second"),
|
||||
Event::ContextUsage { used_tokens: 2, context_window: 10 },
|
||||
permission_asked(&id),
|
||||
] {
|
||||
snapshot.observe(&event);
|
||||
}
|
||||
let frames = snapshot.frames();
|
||||
assert_eq!(kinds(&frames), ["context_usage", "permission_requested"]);
|
||||
assert_eq!(snapshot.transcript().messages.len(), 2);
|
||||
assert!(matches!(frames[0], Event::ContextUsage { used_tokens: 2, .. }));
|
||||
}
|
||||
|
||||
/// A joiner mid-turn is told a turn is running, right after the transcript; one after it isn't.
|
||||
///
|
||||
/// The break this catches: leaving `turn_started` out of the catch-up, so a phone opening on a
|
||||
/// running session shows it idle, with no stop button, until the next token arrives.
|
||||
#[test]
|
||||
fn a_joiner_mid_turn_hears_the_turn_started() {
|
||||
let mut snapshot = Snapshot::new("session-1".into());
|
||||
snapshot.observe(&Event::TurnStarted);
|
||||
snapshot.observe(&committed("first"));
|
||||
assert_eq!(kinds(&snapshot.frames()), ["turn_started"]);
|
||||
snapshot.observe(&Event::TurnEnded { reason: luxe_core::event::StopReason::EndTurn });
|
||||
assert!(snapshot.frames().is_empty());
|
||||
}
|
||||
|
||||
/// A prompt someone answered isn't put in front of the next joiner.
|
||||
///
|
||||
/// The break this catches: ignoring `prompt_closed`, so a phone joining after the terminal
|
||||
/// approved shows a prompt whose answer the engine would throw away.
|
||||
#[test]
|
||||
fn an_answered_prompt_is_not_replayed() {
|
||||
let mut snapshot = Snapshot::new("session-1".into());
|
||||
let answered = PermissionRequestId::new();
|
||||
let open = PermissionRequestId::new();
|
||||
snapshot.observe(&permission_asked(&answered));
|
||||
snapshot.observe(&permission_asked(&open));
|
||||
snapshot.observe(&Event::PromptClosed { id: answered.as_str().into() });
|
||||
assert!(!snapshot.is_waiting(answered.as_str()));
|
||||
assert!(snapshot.is_waiting(open.as_str()));
|
||||
}
|
||||
|
||||
/// Loading a session replaces the transcript rather than adding to it.
|
||||
///
|
||||
/// The break this catches: appending on `session_loaded`, which shows a joiner the previous
|
||||
/// session's conversation above the one the terminal switched to.
|
||||
#[test]
|
||||
fn a_loaded_session_replaces_what_came_before() {
|
||||
let mut snapshot = Snapshot::new("session-1".into());
|
||||
snapshot.observe(&committed("old"));
|
||||
snapshot.observe(&Event::SessionLoaded { session_id: "session-2".into(), messages: vec![] });
|
||||
let transcript = snapshot.transcript();
|
||||
assert_eq!(transcript.session_id, "session-2");
|
||||
assert!(transcript.messages.is_empty());
|
||||
}
|
||||
|
||||
/// A commit while a joiner is still being sent the transcript leaves the joiner's copy alone.
|
||||
///
|
||||
/// The break this catches: the snapshot appending to a list a joiner shares, which would put a
|
||||
/// message in a `session_loaded` frame the live stream then sends again.
|
||||
#[test]
|
||||
fn a_commit_mid_join_leaves_the_joiners_transcript_alone() {
|
||||
let mut snapshot = Snapshot::new("session-1".into());
|
||||
snapshot.observe(&committed("first"));
|
||||
let sending = snapshot.transcript();
|
||||
snapshot.observe(&committed("second"));
|
||||
assert_eq!(sending.messages.len(), 1);
|
||||
assert_eq!(snapshot.transcript().messages.len(), 2);
|
||||
}
|
||||
|
||||
/// Read one frame off a client's stream.
|
||||
async fn next_frame(lines: &mut tokio::io::Lines<impl tokio::io::AsyncBufRead + Unpin>) -> String {
|
||||
let line = tokio::time::timeout(std::time::Duration::from_secs(5), lines.next_line());
|
||||
line.await.expect("a frame in time").expect("readable").expect("the stream is open")
|
||||
}
|
||||
|
||||
/// Wait for the terminal to be told something containing `needle`.
|
||||
async fn notice_containing(terminal_rx: &mut mpsc::Receiver<Event>, needle: &str) -> String {
|
||||
let wait = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while let Some(event) = terminal_rx.recv().await {
|
||||
if let Event::Notice(text) = event {
|
||||
if text.contains(needle) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("the terminal stream ended before a notice about {needle:?}");
|
||||
});
|
||||
wait.await.expect("a notice in time")
|
||||
}
|
||||
|
||||
type ClientLines = tokio::io::Lines<BufReader<tokio::io::ReadHalf<LocalStream>>>;
|
||||
|
||||
/// Serve `shared` on a fresh endpoint and connect one client to it.
|
||||
async fn join(
|
||||
shared: &Shared,
|
||||
) -> (tempfile::TempDir, JoinHandle<()>, ClientLines, tokio::io::WriteHalf<LocalStream>) {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let listener = EndpointListener::bind(dir.path()).expect("bind");
|
||||
let address = listener.address().to_string();
|
||||
let accept = tokio::spawn(clients::accept(listener, shared.clone()));
|
||||
let stream = connect(&address).await.expect("connect");
|
||||
let (read, write) = tokio::io::split(stream);
|
||||
(dir, accept, BufReader::new(read).lines(), write)
|
||||
}
|
||||
|
||||
/// A command the agent ran is turned away before it sees a frame, and the terminal hears why.
|
||||
///
|
||||
/// The break this catches: skipping the ancestry check, so the agent's own `bash` could join
|
||||
/// its session and approve the prompt it's waiting on.
|
||||
#[tokio::test]
|
||||
async fn the_agents_own_command_is_refused() {
|
||||
let Harness { shared, mut engine_rx, mut terminal_rx, terminal: _terminal } =
|
||||
harness(std::process::id());
|
||||
let (_dir, _accept, mut lines, _write) = join(&shared).await;
|
||||
notice_containing(&mut terminal_rx, "Refused").await;
|
||||
let read = tokio::time::timeout(std::time::Duration::from_secs(5), lines.next_line());
|
||||
assert!(matches!(read.await, Ok(Ok(None)) | Ok(Err(_))), "the refused client got a frame");
|
||||
assert!(engine_rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
/// A client joins over the endpoint, catches up, answers, and leaves without closing anything.
|
||||
///
|
||||
/// The break this catches: a joined client's hangup reaching the engine as `close`, which would
|
||||
/// end the terminal's session the moment a phone dropped off the network.
|
||||
#[tokio::test]
|
||||
async fn a_client_joins_answers_and_leaves_without_closing_the_session() {
|
||||
let Harness { shared, mut engine_rx, mut terminal_rx, terminal: _terminal } = harness(NOBODY);
|
||||
let id = PermissionRequestId::new();
|
||||
shared.publish(&permission_asked(&id));
|
||||
let (_dir, _accept, mut lines, mut write) = join(&shared).await;
|
||||
assert!(next_frame(&mut lines).await.contains(r#""kind":"ready""#));
|
||||
assert!(next_frame(&mut lines).await.contains(r#""kind":"session_loaded""#));
|
||||
assert!(next_frame(&mut lines).await.contains(r#""kind":"permission_requested""#));
|
||||
notice_containing(&mut terminal_rx, "joined").await;
|
||||
|
||||
let answer = format!(
|
||||
r#"{{"kind":"respond_permission","content":{{"id":"{}","reply":"once"}}}}"#,
|
||||
id.as_str()
|
||||
);
|
||||
write.write_all(format!("{answer}\n").as_bytes()).await.expect("write");
|
||||
assert!(matches!(engine_rx.recv().await, Some(Action::RespondPermission { .. })));
|
||||
notice_containing(&mut terminal_rx, "Approved from").await;
|
||||
|
||||
drop((lines, write));
|
||||
notice_containing(&mut terminal_rx, "left").await;
|
||||
assert!(engine_rx.try_recv().is_err(), "leaving must not reach the engine");
|
||||
}
|
||||
|
||||
/// A client that introduces itself is named when it joins and when it answers.
|
||||
///
|
||||
/// The break this catches: the terminal saying who joined before the introduction can arrive, or
|
||||
/// naming the bridge's process, so "Approved from" never says which device answered.
|
||||
#[tokio::test]
|
||||
async fn an_introduced_client_is_named_when_it_joins_and_answers() {
|
||||
let Harness { shared, mut engine_rx, mut terminal_rx, terminal: _terminal } = harness(NOBODY);
|
||||
let id = PermissionRequestId::new();
|
||||
shared.publish(&permission_asked(&id));
|
||||
let (_dir, _accept, _lines, mut write) = join(&shared).await;
|
||||
let introduce = r#"{"kind":"introduce","content":{"name":"iPhone"}}"#;
|
||||
write.write_all(format!("{introduce}\n").as_bytes()).await.expect("write");
|
||||
notice_containing(&mut terminal_rx, "iPhone joined").await;
|
||||
|
||||
let answer = format!(
|
||||
r#"{{"kind":"respond_permission","content":{{"id":"{}","reply":"once"}}}}"#,
|
||||
id.as_str()
|
||||
);
|
||||
write.write_all(format!("{answer}\n").as_bytes()).await.expect("write");
|
||||
assert!(matches!(engine_rx.recv().await, Some(Action::RespondPermission { .. })));
|
||||
notice_containing(&mut terminal_rx, "Approved from iPhone").await;
|
||||
}
|
||||
|
||||
/// Every notice the terminal hears, up to and including the one containing `needle`.
|
||||
async fn notices_until(terminal_rx: &mut mpsc::Receiver<Event>, needle: &str) -> Vec<String> {
|
||||
let mut heard = Vec::new();
|
||||
while !heard.last().is_some_and(|text: &String| text.contains(needle)) {
|
||||
heard.push(notice_containing(terminal_rx, "").await);
|
||||
}
|
||||
heard
|
||||
}
|
||||
|
||||
/// A client that opens as watch-only gets the session but isn't announced, joining or leaving.
|
||||
/// An ordinary client, joining and leaving after it, marks where its notices would have been.
|
||||
///
|
||||
/// The break this catches: the terminal saying "Notifications joined this session" in every
|
||||
/// session while a phone has notifications on.
|
||||
#[tokio::test]
|
||||
async fn a_watch_only_client_comes_and_goes_unannounced() {
|
||||
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal: _terminal } =
|
||||
harness(NOBODY);
|
||||
let (_dir, _accept, mut lines, mut write) = join(&shared).await;
|
||||
let watcher = r#"{"kind":"introduce","content":{"name":"Notifications","watch_only":true}}"#;
|
||||
write.write_all(format!("{watcher}\n").as_bytes()).await.expect("write");
|
||||
assert!(next_frame(&mut lines).await.contains(r#""kind":"ready""#));
|
||||
drop((lines, write));
|
||||
|
||||
let (_dir, _accept, lines, mut write) = join(&shared).await;
|
||||
let introduce = r#"{"kind":"introduce","content":{"name":"iPad"}}"#;
|
||||
write.write_all(format!("{introduce}\n").as_bytes()).await.expect("write");
|
||||
let mut heard = notices_until(&mut terminal_rx, "iPad joined").await;
|
||||
drop((lines, write));
|
||||
heard.extend(notices_until(&mut terminal_rx, "iPad left").await);
|
||||
assert!(heard.iter().all(|text| !text.contains("Notifications")), "{heard:?}");
|
||||
}
|
||||
|
||||
/// Everything the terminal hears until it's told the guests are `expected`.
|
||||
async fn heard_until_guests(
|
||||
terminal_rx: &mut mpsc::Receiver<Event>,
|
||||
expected: &[&str],
|
||||
) -> Vec<Event> {
|
||||
let wait = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
let mut heard = Vec::new();
|
||||
while let Some(event) = terminal_rx.recv().await {
|
||||
let done = matches!(&event, Event::GuestsChanged(guests) if guests == expected);
|
||||
heard.push(event);
|
||||
if done {
|
||||
return heard;
|
||||
}
|
||||
}
|
||||
panic!("the terminal stream ended before the guests were {expected:?}");
|
||||
});
|
||||
wait.await.expect("the guests in time")
|
||||
}
|
||||
|
||||
fn notices(heard: &[Event]) -> Vec<&str> {
|
||||
heard
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Event::Notice(text) => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The owner's own device joins and leaves the dock's list without a line in the transcript.
|
||||
///
|
||||
/// The break this catches: a phone's every reconnect adding "joined" and "left" lines to the
|
||||
/// owner's transcript, or the dock never told it came or went.
|
||||
#[tokio::test]
|
||||
async fn the_owners_device_is_listed_quietly() {
|
||||
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal: _terminal } =
|
||||
harness(NOBODY);
|
||||
let (_dir, _accept, lines, mut write) = join(&shared).await;
|
||||
let yours = r#"{"kind":"introduce","content":{"name":"iPhone","yours":true}}"#;
|
||||
write.write_all(format!("{yours}\n").as_bytes()).await.expect("write");
|
||||
let mut heard = heard_until_guests(&mut terminal_rx, &["iPhone"]).await;
|
||||
drop((lines, write));
|
||||
heard.extend(heard_until_guests(&mut terminal_rx, &[]).await);
|
||||
assert!(notices(&heard).is_empty(), "{heard:?}");
|
||||
}
|
||||
|
||||
/// Someone else's device is listed and still announced, joining and leaving.
|
||||
///
|
||||
/// The break this catches: a stranger's device joining the owner's session unremarked, or kept
|
||||
/// off the dock's list.
|
||||
#[tokio::test]
|
||||
async fn anyone_elses_device_is_listed_and_announced() {
|
||||
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal: _terminal } =
|
||||
harness(NOBODY);
|
||||
let (_dir, _accept, lines, mut write) = join(&shared).await;
|
||||
let theirs = r#"{"kind":"introduce","content":{"name":"Sam's iPad"}}"#;
|
||||
write.write_all(format!("{theirs}\n").as_bytes()).await.expect("write");
|
||||
let mut heard = heard_until_guests(&mut terminal_rx, &["Sam's iPad"]).await;
|
||||
drop((lines, write));
|
||||
heard.extend(notices_until(&mut terminal_rx, "left").await.into_iter().map(Event::Notice));
|
||||
let said = notices(&heard);
|
||||
assert!(said.iter().any(|text| text.contains("Sam's iPad joined")), "{said:?}");
|
||||
assert!(said.iter().any(|text| text.contains("Sam's iPad left")), "{said:?}");
|
||||
}
|
||||
|
||||
/// The terminal's stream ends when the engine's does, even with a client still connected.
|
||||
///
|
||||
/// The break this catches: a connected client holding the terminal's stream open, so `luxe --rpc`
|
||||
/// never sees the session end and never exits.
|
||||
#[tokio::test]
|
||||
async fn the_terminal_stream_ends_with_the_engines() {
|
||||
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal } = harness(NOBODY);
|
||||
let (events_tx, events) = mpsc::channel(4);
|
||||
let (_dir, _accept, mut lines, _write) = join(&shared).await;
|
||||
assert!(next_frame(&mut lines).await.contains(r#""kind":"ready""#));
|
||||
notice_containing(&mut terminal_rx, "joined").await;
|
||||
|
||||
let tee = tokio::spawn(tee(events, shared, terminal, None));
|
||||
drop(events_tx);
|
||||
tee.await.expect("tee ends with the engine's stream");
|
||||
let end = tokio::time::timeout(std::time::Duration::from_secs(5), terminal_rx.recv());
|
||||
assert_eq!(end.await.expect("the stream ends in time"), None);
|
||||
}
|
||||
@@ -66,6 +66,7 @@ pub(super) async fn run_tui(
|
||||
events: engine_rx,
|
||||
closer,
|
||||
session_id,
|
||||
claim: _claim,
|
||||
} = start_engine(&settings).await?;
|
||||
let event_rx = crate::workspace_runtime::bridge(
|
||||
engine_rx,
|
||||
@@ -75,6 +76,8 @@ pub(super) async fn run_tui(
|
||||
},
|
||||
crate::workspace_runtime::pull_request_watch(&settings.work_root),
|
||||
);
|
||||
let (event_rx, _sharing) =
|
||||
super::share::share(event_rx, engine_tx.clone(), &settings, &session_id.0);
|
||||
let exit = main_loop::run(
|
||||
event_rx,
|
||||
engine_tx.clone(),
|
||||
@@ -180,7 +183,13 @@ impl Next<'_> {
|
||||
// Another of your sessions, in its own worktree when it has one
|
||||
shutdown_workspace_services().await;
|
||||
let mut next = self.fresh(ResumeMode::Session(launch.session.clone()));
|
||||
match enter_session_worktree(&launch.session, &mut next).await {
|
||||
let state_root = &self.settings.state_root;
|
||||
let entered =
|
||||
match crate::engine_setup::open_elsewhere_now(state_root, &launch.session) {
|
||||
Some(why) => Err(anyhow::anyhow!(why)),
|
||||
None => enter_session_worktree(&launch.session, &mut next).await,
|
||||
};
|
||||
match entered {
|
||||
Ok(()) => *self.settings = next,
|
||||
Err(error) => self.carry_on(
|
||||
session_id,
|
||||
|
||||
Reference in New Issue
Block a user