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:
@@ -68,16 +68,17 @@ impl ToolActivityProjector {
|
||||
self.composing(call_id, name, subject.as_deref(), body.as_ref())
|
||||
}
|
||||
Event::ToolStarted { call_id, name } => {
|
||||
self.started(call_id, name).into_iter().collect()
|
||||
self.started(call_id, name).into_iter().chain(self.fit_writing()).collect()
|
||||
}
|
||||
Event::ToolProgress { call_id, chunk } => {
|
||||
self.progressed(call_id, chunk).into_iter().collect()
|
||||
}
|
||||
Event::ToolCompleted { call_id, is_error, output } => {
|
||||
self.settle(call_id, *is_error, Some(bounded_display(output))).into_iter().collect()
|
||||
let settled = self.settle(call_id, *is_error, Some(bounded_display(output)));
|
||||
settled.into_iter().chain(self.fit_writing()).collect()
|
||||
}
|
||||
Event::ToolEnded { call_id, is_error } => {
|
||||
self.ended(call_id, *is_error).into_iter().collect()
|
||||
self.ended(call_id, *is_error).into_iter().chain(self.fit_writing()).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
@@ -95,6 +96,35 @@ impl ToolActivityProjector {
|
||||
Some(open.clone())
|
||||
}
|
||||
|
||||
/// How the card of a call still being written should read: waiting while another call runs,
|
||||
/// since that one is the busy card and this one can't run before it, and working otherwise.
|
||||
fn writing_state(&self, call_id: &str) -> ToolActivityState {
|
||||
let running = self
|
||||
.calls
|
||||
.iter()
|
||||
.any(|(id, open)| id != call_id && open.state == ToolActivityState::Running);
|
||||
if running {
|
||||
ToolActivityState::Queued
|
||||
} else {
|
||||
ToolActivityState::Composing
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the card of the call being written between waiting and working as a call ahead of
|
||||
/// it starts or stops.
|
||||
fn fit_writing(&mut self) -> Option<ToolActivity> {
|
||||
let call_id = self.writing.clone()?;
|
||||
let state = self.writing_state(&call_id);
|
||||
let open = self.calls.get_mut(&call_id)?;
|
||||
let unsent = matches!(open.state, ToolActivityState::Composing | ToolActivityState::Queued);
|
||||
if !unsent || open.state == state {
|
||||
return None;
|
||||
}
|
||||
open.revision += 1;
|
||||
open.state = state;
|
||||
Some(open.clone())
|
||||
}
|
||||
|
||||
/// Opens (or fills in) the card for the call the model is writing right now.
|
||||
///
|
||||
/// `Composing` is a *working* state — the model is producing this call as the reader watches,
|
||||
@@ -105,7 +135,9 @@ impl ToolActivityProjector {
|
||||
/// written; whichever came before it has been written in full and is merely waiting its turn.
|
||||
/// Saying that is what keeps exactly one card looking busy — two spinning `bash` cards read as
|
||||
/// two shells at once, and a paused mark on all of them put a stopped sign over a card that
|
||||
/// was visibly filling in.
|
||||
/// was visibly filling in. An earlier call can run while this one is written, though, and then
|
||||
/// that one is the busy card: this one opens `Queued`, since it can't run before it either,
|
||||
/// and [`Self::fit_writing`] puts it back to work if the model is still writing it.
|
||||
///
|
||||
/// What it does not yet have is a batch position — the message has not committed, so how many
|
||||
/// calls it asked for is not known — or a body, whose payload is the argument still arriving.
|
||||
@@ -126,10 +158,17 @@ impl ToolActivityProjector {
|
||||
}
|
||||
|
||||
let label = subject.map(bounded_display).unwrap_or_default();
|
||||
let state = self.writing_state(call_id);
|
||||
match self.calls.get_mut(call_id) {
|
||||
// The call growing under the card that is already drawing it: the subject arriving, or
|
||||
// another few lines of the payload. Said twice, neither is worth a revision.
|
||||
Some(open) if open.state == ToolActivityState::Composing => {
|
||||
// another few lines of the payload. Said twice, neither is worth a revision. Queued
|
||||
// here is a card held behind a running call, since only the call being written composes.
|
||||
Some(open)
|
||||
if matches!(
|
||||
open.state,
|
||||
ToolActivityState::Composing | ToolActivityState::Queued
|
||||
) =>
|
||||
{
|
||||
let renamed = !label.is_empty() && open.label != label;
|
||||
let grew = body.is_some_and(|body| open.card_body.as_ref() != Some(body));
|
||||
if renamed || grew {
|
||||
@@ -150,6 +189,7 @@ impl ToolActivityProjector {
|
||||
let mut activity =
|
||||
ToolActivity::composing(session_id, call_id, name, label, now_ms());
|
||||
activity.card_body = body.cloned();
|
||||
activity.state = state;
|
||||
self.calls.insert(call_id.to_owned(), activity.clone());
|
||||
updates.push(activity);
|
||||
}
|
||||
|
||||
@@ -336,6 +336,68 @@ fn exactly_one_card_is_working_at_a_time() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A call written while an earlier one runs waits under that one, and works again once it's over.
|
||||
///
|
||||
/// Calls run as soon as they're written, so the model can be writing one while another runs. The
|
||||
/// break this catches: opening the written call as `Composing` regardless, which puts a spinner on
|
||||
/// it beside the running card, with a paused one between them that reads as stuck.
|
||||
#[test]
|
||||
fn a_call_written_while_another_runs_waits_behind_it() {
|
||||
let mut projector = ToolActivityProjector::default();
|
||||
projector.project(&Event::SessionLoaded { session_id: "session-a".into(), messages: vec![] });
|
||||
let compose = |id: &str| Event::ToolCallComposing {
|
||||
call_id: id.into(),
|
||||
name: "edit".into(),
|
||||
subject: Some(format!("{id}.rs")),
|
||||
body: None,
|
||||
};
|
||||
let start = |id: &str| Event::ToolStarted { call_id: id.into(), name: "edit".into() };
|
||||
let finish = |id: &str| Event::ToolCompleted {
|
||||
call_id: id.into(),
|
||||
is_error: false,
|
||||
output: "Applied".into(),
|
||||
};
|
||||
let steps: Vec<(&str, Event)> = vec![
|
||||
("the model writes the first edit", compose("a")),
|
||||
("which runs as soon as it's written", start("a")),
|
||||
("while the model writes the second", compose("b")),
|
||||
("and the third", compose("c")),
|
||||
("the first finishes", finish("a")),
|
||||
("the second runs", start("b")),
|
||||
("and finishes, with the third still being written", finish("b")),
|
||||
];
|
||||
|
||||
let mut shape = Vec::new();
|
||||
for (note, event) in steps {
|
||||
projector.project(&event);
|
||||
let mut states: Vec<(String, ToolActivityState)> =
|
||||
projector.calls.iter().map(|(id, row)| (id.clone(), row.state)).collect();
|
||||
states.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
let working = states.iter().filter(|(_, state)| state.is_working()).count();
|
||||
assert!(working <= 1, "{note}: {working} cards claim to be working: {states:?}");
|
||||
shape.push((note, states.into_iter().map(|(_, state)| state).collect::<Vec<_>>()));
|
||||
}
|
||||
|
||||
use ToolActivityState::{Composing, Queued, Running, Succeeded};
|
||||
assert_eq!(
|
||||
shape,
|
||||
[
|
||||
("the model writes the first edit", vec![Composing]),
|
||||
("which runs as soon as it's written", vec![Running]),
|
||||
("while the model writes the second", vec![Running, Queued]),
|
||||
("and the third", vec![Running, Queued, Queued]),
|
||||
// For the instant between one call ending and the next starting, writing the third
|
||||
// is the only thing happening; the next event takes it back
|
||||
("the first finishes", vec![Succeeded, Queued, Composing]),
|
||||
("the second runs", vec![Succeeded, Running, Queued]),
|
||||
(
|
||||
"and finishes, with the third still being written",
|
||||
vec![Succeeded, Succeeded, Composing]
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// A refused or cancelled call is answered without ever being dispatched. Its card is the one
|
||||
/// the model's writing opened, and it has to settle from there or it spins forever.
|
||||
#[test]
|
||||
|
||||
@@ -8,8 +8,12 @@ mod commands;
|
||||
mod docs_command;
|
||||
mod doctor_command;
|
||||
pub(crate) mod headless;
|
||||
mod join_command;
|
||||
mod models_command;
|
||||
#[cfg(feature = "remote")]
|
||||
mod remote_command;
|
||||
mod rpc;
|
||||
mod share;
|
||||
mod tui;
|
||||
pub(crate) mod update_command;
|
||||
mod wire_command;
|
||||
@@ -22,6 +26,7 @@ use auth_command::run_auth_command;
|
||||
use commands::{run_loop_command, run_mcp_command, run_sessions_command};
|
||||
use doctor_command::run_doctor_command;
|
||||
use headless::run_headless;
|
||||
use join_command::run_join_command;
|
||||
use models_command::run_models_command;
|
||||
use tui::run_tui;
|
||||
use wire_command::run_wire_command;
|
||||
@@ -107,9 +112,7 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
|
||||
match cmd {
|
||||
SubCommand::Auth(auth_args) => return run_auth_command(auth_args.command).await,
|
||||
SubCommand::Init(init_args) => return crate::init::run_init(init_args, settings).await,
|
||||
SubCommand::Loop(loop_args) => {
|
||||
return run_loop_command(loop_args.command, settings).await;
|
||||
}
|
||||
SubCommand::Loop(looping) => return run_loop_command(looping.command, settings).await,
|
||||
SubCommand::Mcp(mcp_args) => return run_mcp_command(mcp_args.command, &settings).await,
|
||||
SubCommand::Models(models_args) => {
|
||||
return run_models_command(models_args.command, settings).await
|
||||
@@ -118,6 +121,9 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
|
||||
return run_sessions_command(sessions_args.command, settings).await
|
||||
}
|
||||
SubCommand::Doctor => return run_doctor_command(settings).await,
|
||||
SubCommand::Join(join) => return run_join_command(join, &settings.work_root).await,
|
||||
#[cfg(feature = "remote")]
|
||||
SubCommand::Remote(remote) => return remote_command::run_remote_command(remote).await,
|
||||
SubCommand::Wire(wire_args) => return run_wire_command(wire_args),
|
||||
SubCommand::Docs(_) | SubCommand::Update(_) => {
|
||||
unreachable!("`luxe docs` and `luxe update` return before a project is entered")
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -23,7 +23,9 @@ mod spend;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_env;
|
||||
use session::attach_session;
|
||||
pub(crate) use session::{resumed_session, IssueBinding, ResumeMode, WorktreeBinding};
|
||||
pub(crate) use session::{
|
||||
open_elsewhere_now, resumed_session, IssueBinding, ResumeMode, WorktreeBinding,
|
||||
};
|
||||
pub(crate) use settings::{AgentSettings, CliOverrides};
|
||||
pub(crate) use spend::LoopSpendSink;
|
||||
mod tooling_summary;
|
||||
@@ -57,6 +59,9 @@ pub(crate) struct EngineHandle {
|
||||
pub(crate) session_id: luxe_core::SessionId,
|
||||
/// How a front-end that is exiting lets the engine finish first.
|
||||
pub(crate) closer: EngineCloser,
|
||||
/// The claim on the session taken before the engine existed, so nobody else can take it
|
||||
/// before the engine claims it too; dropping it leaves the engine's own
|
||||
pub(crate) claim: Option<luxe_core::session::SessionClaim>,
|
||||
}
|
||||
|
||||
/// What an idle engine needs to wind down with no `SessionEnd` hooks to wait on.
|
||||
@@ -126,7 +131,7 @@ pub(crate) async fn build_engine(
|
||||
let todo_root = prepare_state_dirs(settings).await?;
|
||||
|
||||
let mut store = open_session_store(&settings.state_root);
|
||||
let session_id = attach_session(settings, &mut store)?;
|
||||
let (session_id, claim) = attach_session(settings, &mut store)?;
|
||||
|
||||
let model = settings.launch_model();
|
||||
|
||||
@@ -218,7 +223,7 @@ pub(crate) async fn build_engine(
|
||||
.map_err(|error| anyhow::anyhow!("engine channel closed: {error}"))?;
|
||||
}
|
||||
|
||||
Ok(EngineHandle { actions, events, session_id: attached, closer })
|
||||
Ok(EngineHandle { actions, events, session_id: attached, closer, claim })
|
||||
}
|
||||
|
||||
/// Makes the directories a session writes into, and answers where its checklists go.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use luxe_core::session::{SessionId, SessionStore};
|
||||
use luxe_core::session::{SessionClaim, SessionError, SessionId, SessionStore};
|
||||
|
||||
use super::AgentSettings;
|
||||
|
||||
@@ -135,7 +135,7 @@ pub(crate) struct WorktreeBinding {
|
||||
pub(super) fn attach_session(
|
||||
settings: &AgentSettings,
|
||||
store: &mut luxe_core::session::JsonlSessionStore,
|
||||
) -> anyhow::Result<SessionId> {
|
||||
) -> anyhow::Result<(SessionId, Option<SessionClaim>)> {
|
||||
let session_id = match (&settings.resume, resumed_session(store, &settings.resume)) {
|
||||
(ResumeMode::New, _) => store.create(&settings.state_root.to_string_lossy())?,
|
||||
(_, Some(id)) => {
|
||||
@@ -154,6 +154,8 @@ pub(super) fn attach_session(
|
||||
anyhow::bail!("session '{id}' not found for this project")
|
||||
}
|
||||
};
|
||||
// Before the records below, which are writes too
|
||||
let claim = claim_session(store, &session_id)?;
|
||||
// A session in a worktree says so in its own log, which is how resuming finds the worktree
|
||||
if let Some(binding) = &settings.worktree {
|
||||
record_worktree(store, &session_id, binding, &settings.state_root);
|
||||
@@ -164,7 +166,50 @@ pub(super) fn attach_session(
|
||||
if let Some((number, url)) = &settings.pull_request {
|
||||
record_pull_request(store, &session_id, *number, url);
|
||||
}
|
||||
Ok(session_id)
|
||||
Ok((session_id, claim))
|
||||
}
|
||||
|
||||
/// Claim `session_id` for this process, or say which Luxe has it open and how to get there.
|
||||
fn claim_session(
|
||||
store: &luxe_core::session::JsonlSessionStore,
|
||||
session_id: &SessionId,
|
||||
) -> anyhow::Result<Option<SessionClaim>> {
|
||||
match store.claim(session_id) {
|
||||
Ok(claim) => Ok(claim),
|
||||
Err(SessionError::OpenElsewhere(id)) => anyhow::bail!(open_elsewhere(&id)),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `session` can't be opened here right now, when another Luxe has it open.
|
||||
///
|
||||
/// Asked before leaving the session that's running, so the reader stays where they are rather
|
||||
/// than landing outside the TUI. This process's own claims don't count against it.
|
||||
pub(crate) fn open_elsewhere_now(state_root: &std::path::Path, session: &str) -> Option<String> {
|
||||
let store = super::open_session_store(state_root);
|
||||
let id = SessionId(session.to_string());
|
||||
match store.claim(&id) {
|
||||
Err(SessionError::OpenElsewhere(id)) => Some(open_elsewhere(&id)),
|
||||
// Any other failure meets the session's start, which reports it in full
|
||||
Ok(_) | Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the session is open, when the Luxe that has it says so, and what to do about it.
|
||||
fn open_elsewhere(id: &SessionId) -> String {
|
||||
let runtime = luxe_core::user_dirs::luxe_runtime_dir();
|
||||
let holder = luxe_core::local_endpoint::live_sessions(&runtime)
|
||||
.into_iter()
|
||||
.find(|live| live.session_id == id.0);
|
||||
let place = match holder {
|
||||
Some(live) => format!(" (process {}, in {})", live.pid, live.cwd),
|
||||
None => String::new(),
|
||||
};
|
||||
// `luxe join` is not offered: it speaks the protocol, so a person running it sees JSON
|
||||
format!(
|
||||
"session {id} is already open in another Luxe{place}. Carry on there, or close it \
|
||||
there first"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -229,4 +274,35 @@ mod tests {
|
||||
assert_eq!(resumed_session(&store, &ResumeMode::Session("nope".into())), None);
|
||||
assert_eq!(resumed_session(&store, &ResumeMode::PullRequest(9)), None);
|
||||
}
|
||||
|
||||
/// A session another process holds is refused up front, with the way to reach it, and the
|
||||
/// check made before leaving a running session says the same.
|
||||
///
|
||||
/// The break this catches: attaching without a claim, so a second `luxe --resume` opens a
|
||||
/// second writer on the log, or a resume from inside the TUI that lands the reader outside it.
|
||||
#[test]
|
||||
fn a_session_open_in_another_process_is_refused_and_says_so() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut store = open_session_store(dir.path());
|
||||
let id = store.create("/work").unwrap();
|
||||
let lock = store.session_path(&id).unwrap().with_extension("lock");
|
||||
let other_process = std::fs::File::create(&lock).unwrap();
|
||||
other_process.try_lock().unwrap();
|
||||
let settings = {
|
||||
let _env = super::super::test_env::ENV_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let _home = super::super::test_env::isolated_env();
|
||||
let mut settings = AgentSettings::resolve(dir.path().to_path_buf(), Default::default());
|
||||
settings.resume = ResumeMode::Session(id.0.clone());
|
||||
settings
|
||||
};
|
||||
|
||||
let refused = attach_session(&settings, &mut store).expect_err("held elsewhere");
|
||||
let expected = format!("session {id} is already open in another Luxe");
|
||||
assert!(refused.to_string().contains(&expected), "{refused}");
|
||||
assert!(open_elsewhere_now(dir.path(), &id.0).is_some());
|
||||
drop(other_process);
|
||||
assert!(open_elsewhere_now(dir.path(), &id.0).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,6 +469,16 @@ script can tell a failure from an answer without reading the output.
|
||||
| `luxe models show <provider/id>` | What Luxe knows about a model, and where each value came from. A bare ID uses the active provider. |
|
||||
| `luxe models refresh` | Refresh the model catalog. `--force` even if it is fresh. |
|
||||
| `luxe sessions list` | Sessions in this project, newest first |
|
||||
| `luxe join [id]` | Join a session another Luxe is running, speaking the [RPC protocol](rpc.md#join-a-running-session) on stdin and stdout. The id can be its start, or the Luxe's process id; without one, it joins the session running in this folder. |
|
||||
| `luxe join --list` | Sessions running on this machine that can be joined |
|
||||
| `luxe remote` | Serve this machine's sessions to your own phone or tablet. Listens on this machine only, for Tailscale Serve to carry to your devices, and lets in this machine's tailnet owner from a paired device. |
|
||||
| `luxe remote --port <n>` | The port it listens on (default 4519) |
|
||||
| `luxe remote --allow <login>` | Also let this tailnet login in, as Tailscale names it (`alex@github`). Repeatable. |
|
||||
| `luxe remote setup` | Check Tailscale, offer to publish the bridge on your tailnet with Tailscale Serve, offer to run it at login as a user service, then show a QR code to pair a device. Each step that changes something outside Luxe asks first. |
|
||||
| `luxe remote pair` | Show a QR code and link that pair one phone or tablet. They work once, within ten minutes. |
|
||||
| `luxe remote devices` | The paired devices |
|
||||
| `luxe remote devices revoke <id>` | Unpair a device. Its open sessions close within a few seconds. |
|
||||
| `luxe remote service remove` | Stop the bridge's user service and stop it starting at login |
|
||||
| `luxe mcp list` | Configured MCP servers |
|
||||
| `luxe mcp add --id <id> --name <name>` | Add a server to the project's `.luxe/mcp.json`, with `--command "<program> <args>"` or `--url <url>`. It counts as a [project's server](mcp.md#servers-a-project-brings). |
|
||||
| `luxe mcp remove --id <id>` | Remove a server from the project's `.luxe/mcp.json` |
|
||||
@@ -846,6 +856,19 @@ This is local to your machine and on by default. Outside herdr nothing is sent.
|
||||
{ "herdr": false }
|
||||
```
|
||||
|
||||
### Joining a session
|
||||
|
||||
A running Luxe lets another program on this machine join its session: `luxe join`, a script, or
|
||||
whatever you build on [the RPC protocol](rpc.md#join-a-running-session). Only your user account can
|
||||
connect, and nothing listens on the network. To turn it off:
|
||||
|
||||
```json title="~/.config/luxe/config.json"
|
||||
{ "joinable": false }
|
||||
```
|
||||
|
||||
`LUXE_JOINABLE=0` turns it off for one run. A project's config can turn it off too, but can't turn
|
||||
it back on once yours has.
|
||||
|
||||
### Updates
|
||||
|
||||
Once a day, Luxe checks whether a newer release exists, and when one does the start screen says
|
||||
@@ -911,6 +934,7 @@ Every key in `config.json`, with its default.
|
||||
| `notification_method` | `auto` | `auto`, `osc9` or `osc777` |
|
||||
| `bell` | `false` | Terminal bell when a turn ends or something waits on you |
|
||||
| `herdr` | `true` | Report the agent's state to herdr; see [herdr](#herdr) |
|
||||
| `joinable` | `true` | Let another program on this machine join a running session; see [Joining a session](#joining-a-session) |
|
||||
| `statusline.visibility` | `auto` | `auto`, `shown` or `hidden`; see [Appearance](appearance.md#statusline) |
|
||||
| `statusline.style` | `slab` | `slab` or `flat` |
|
||||
| `statusline.left` | `["project", "branch", "pr", "todo", "changes"]` | Modules on the left |
|
||||
@@ -1340,6 +1364,7 @@ UTF-8 is ignored, as if the variable were unset.
|
||||
| `LUXE_SIZE_CHECK` | `1` | `0` stops telling the agent when an edit takes a file past 500 lines or a function past 20 |
|
||||
| `LUXE_DEBUG_NUDGE` | `1` | `0` stops suggesting the debugger after repeated test failures |
|
||||
| `LUXE_PLAN_NUDGE` | `1` | `0` stops reminding the agent to update its checklist |
|
||||
| `LUXE_NESTED_INSTRUCTIONS` | `1` | `0` stops reading the [`AGENTS.md` of folders](project-context.md#folders-the-agent-works-in) the agent works in |
|
||||
| `LUXE_LAZY_TOOLS` | `1` | `0` sends every tool's description with every request |
|
||||
| `LUXE_CORE_TOOLS` | | The tools sent with every request, comma-separated; the rest load when needed |
|
||||
| `LUXE_DAP_STOP_TIMEOUT_SECS` | `30` | How long the debugger waits for a program to stop |
|
||||
@@ -1356,6 +1381,8 @@ UTF-8 is ignored, as if the variable were unset.
|
||||
| `LUXE_FILE_MANAGER`, then `FILE_MANAGER` | The file manager `O` in the dock's file tree opens a folder in. Without either, the first of yazi, lf, ranger and nnn that is installed, then your desktop's own. |
|
||||
| `LUXE_HERDR` | `0` stops reporting state to [Herdr](recipes.md#run-luxe-in-herdr) |
|
||||
| `LUXE_UPDATE_CHECK` | `0` turns off the update check |
|
||||
| `LUXE_JOINABLE` | `0` stops other programs [joining](configuration.md#joining-a-session) this run's session |
|
||||
| `LUXE_RUNTIME_DIR` | Where a running Luxe keeps the socket and record that let a program join it, instead of `luxe` in `$XDG_RUNTIME_DIR` on Linux or `$TMPDIR` on macOS, or `run` in the state folder |
|
||||
|
||||
## Diagnostics
|
||||
|
||||
@@ -2090,6 +2117,7 @@ guide is reference, for when you need it.
|
||||
| Resume a session, or see what fills the context | [Sessions and context](sessions.md) |
|
||||
| See what the agent can use | [Tools](tools.md) |
|
||||
| Let the agent work through a plan on its own | [Autonomous runs](loop.md) |
|
||||
| Reach your sessions from your phone or tablet | [Luxe on your phone](remote.md) |
|
||||
| Change the theme, keys or statusline | [Configuration](configuration.md) |
|
||||
| Give the agent your project's conventions | [Project context](project-context.md) |
|
||||
| Add tools, skills or your own commands | [Extending Luxe](extending.md), [Recipes](recipes.md) |
|
||||
@@ -2421,7 +2449,8 @@ While the agent works, you can keep typing:
|
||||
| `alt+↑` | Bring waiting messages back into the composer to edit |
|
||||
| `ctrl+esc` | Stop the turn. Waiting messages come back into the composer. |
|
||||
|
||||
A waiting message sits above the composer, marked `steering` or `queued`, until it is delivered.
|
||||
A waiting message sits above the composer, marked `steering` or `queued`, until it is delivered. A
|
||||
message with an image is always queued, because steering carries text only.
|
||||
|
||||
`ctrl+v` or `shift+insert` pastes. Pasted text of three lines or more, or over 150 bytes, becomes a
|
||||
`[Pasted 40 lines]` chip, and a pasted image becomes `[Pasted Image]`. Both are sent in full. A chip, like a mention, is deleted with one `backspace`.
|
||||
@@ -2452,7 +2481,7 @@ conversation, or in its place below 80 columns.
|
||||
| **FILES** | The project as a tree, with what changed marked in it. Click a file to [preview](#preview) it. |
|
||||
| **ELSEWHERE** | Files the session changed outside the project, when there are any |
|
||||
| **MODEL** | The provider, model, thinking level and [mode](agent.md#plan-then-build). Click the model to change it, or the mode to switch it. |
|
||||
| **SESSION** | Context used, tokens and cost, with what a review and compaction cost on rows of their own. A review's row shows its full cost once its guide or drafted summary is done. |
|
||||
| **SESSION** | Context used, tokens and cost, with what a review and compaction cost on rows of their own. A review's row shows its full cost once its guide or drafted summary is done. While a phone or another client has [joined](remote.md), a **joined** row names it. |
|
||||
|
||||
`alt+d` shows or hides the dock, and `/dock left` or `/dock right` moves it. To set it for good:
|
||||
|
||||
@@ -3053,6 +3082,15 @@ session repeats that same text, which is what lets the provider reuse its cache.
|
||||
the agent in the next session: `/new`, or resuming one. If you switch Git branches mid-session, the
|
||||
agent is told with your next message.
|
||||
|
||||
### Folders the agent works in
|
||||
|
||||
An `AGENTS.md` in a folder below the repository's top, but not on the way to where you started,
|
||||
joins when the agent first opens, writes or searches a path in that folder. It's added to that
|
||||
tool result, once, and Luxe shows **Following** and the file's path. The system prompt doesn't
|
||||
change, so the cache holds. Ignored folders, such as `node_modules`, are skipped. If a rewind or a
|
||||
compaction drops the file, it joins again the next time the agent goes there.
|
||||
`LUXE_NESTED_INSTRUCTIONS=0` turns this off.
|
||||
|
||||
**Project context** lists every file a turn reads, and says whose rules each one carries:
|
||||
**global**, **project** or **folder** context. Type `context` on the start screen and open it.
|
||||
`enter` opens a file in your editor, or creates one from a template. The template's guidance is in
|
||||
@@ -3470,7 +3508,7 @@ luxe --resume <id> # a specific one
|
||||
@@@ page: recipes
|
||||
---
|
||||
title: "Recipes"
|
||||
summary: "Extensions put together: Asana, subagents, a classifier guard, Herdr, and a local model."
|
||||
summary: "Extensions put together: Asana, subagents, a classifier guard, Herdr, your phone, and a local model."
|
||||
order: 8
|
||||
group: "Extend"
|
||||
---
|
||||
@@ -3716,6 +3754,60 @@ The one token worth a second thought is `panel_bg`: Herdr draws the active tab a
|
||||
on an `accent` fill, so it has to stay dark enough to read there. Lifting it to `#201e1a` gives the
|
||||
tab bar a surface of its own if you prefer the chrome delineated.
|
||||
|
||||
## Luxe from your phone
|
||||
|
||||
Your sessions keep running on your computer, and your phone or tablet reaches them over
|
||||
[Tailscale](https://tailscale.com), a private network between your own devices. Nothing is opened to
|
||||
the internet. This is the terminal over SSH; [Luxe on your phone](remote.md) is Luxe's own way in.
|
||||
|
||||
1. Install Tailscale on the computer and on the phone, and sign in to the same account on both.
|
||||
2. On the computer, turn on SSH. On Linux and macOS, Tailscale can do it for you:
|
||||
|
||||
```bash
|
||||
sudo tailscale up --ssh
|
||||
```
|
||||
|
||||
On Windows, turn on the OpenSSH Server in Settings, under Optional features.
|
||||
3. Run Luxe in [Herdr](#run-luxe-in-herdr), so your sessions outlive the terminal you started
|
||||
them in.
|
||||
4. On the phone, connect with an SSH app such as Blink Shell or Termius, using the computer's
|
||||
Tailscale name, and run `herdr`. It attaches to the panes you left, with Luxe where it was.
|
||||
|
||||
```bash
|
||||
mosh you@desk -- herdr
|
||||
```
|
||||
|
||||
[Mosh](https://mosh.org) keeps the connection through a locked screen or a switch from Wi-Fi to
|
||||
cellular. It needs `mosh` installed on the computer too, which Linux and macOS have and Windows
|
||||
does not; plain `ssh` works everywhere.
|
||||
|
||||
On an iPad with a keyboard, this is Luxe as you know it. On a phone, Luxe fits a narrow screen,
|
||||
and Herdr marks which session is waiting on you.
|
||||
|
||||
### A notification when Luxe needs you
|
||||
|
||||
[Luxe on your phone](remote.md#notifications) has notifications built in. Without it, a
|
||||
[hook](hooks.md) can post to [ntfy](https://ntfy.sh), whose app shows it on your phone:
|
||||
|
||||
```json title="~/.config/luxe/hooks.json"
|
||||
{
|
||||
"PermissionRequested": [
|
||||
{ "command": ["curl", "-s", "-d", "Luxe is waiting for an approval", "https://ntfy.sh/your-topic"] }
|
||||
],
|
||||
"BeforeToolUse": [
|
||||
{ "matcher": "question", "command": ["curl", "-s", "-d", "Luxe has a question", "https://ntfy.sh/your-topic"] }
|
||||
],
|
||||
"AgentEnd": [
|
||||
{ "command": ["curl", "-s", "-d", "Luxe finished", "https://ntfy.sh/your-topic"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- **Anyone who knows an ntfy.sh topic can read it**, so pick a long random name, or run ntfy
|
||||
yourself on your Tailscale network. The messages above say only that something is waiting, never
|
||||
the command.
|
||||
- **`AgentEnd` fires after every turn**, at your desk too. Leave it out if that is too many.
|
||||
|
||||
## A local model in LM Studio
|
||||
|
||||
1. Load a model in LM Studio and start its server.
|
||||
@@ -3740,6 +3832,207 @@ to it rather than replacing the file:
|
||||
```
|
||||
|
||||
[Custom providers](custom-providers.md) covers samplers and request formats.
|
||||
@@@ page: remote
|
||||
---
|
||||
title: "Luxe on your phone"
|
||||
summary: "Reach the sessions running on your computer from your own phone or tablet, over Tailscale."
|
||||
order: 13
|
||||
group: "Using Luxe"
|
||||
---
|
||||
|
||||
`luxe remote` lets your phone or tablet see the sessions running on your computer, join one, and
|
||||
start new ones. It listens on your computer only. [Tailscale](https://tailscale.com), a private
|
||||
network between your own devices, carries it to them over HTTPS, so nothing is opened to the
|
||||
internet and there is no Luxe server in between.
|
||||
|
||||
On the phone it's an app in the browser, drawn like the interface in your theme. For the whole
|
||||
terminal, editor included, [Luxe from your phone](recipes.md#luxe-from-your-phone) works over SSH.
|
||||
|
||||
## Set it up
|
||||
|
||||
1. Install Tailscale on the computer and on the phone, and sign in to the same account on both.
|
||||
2. On the computer, run:
|
||||
|
||||
```bash
|
||||
luxe remote setup
|
||||
```
|
||||
|
||||
3. Scan the QR code it shows with the phone's camera, and give the device a name.
|
||||
4. On an iPhone or iPad, add it to the Home Screen: in Safari, Share, then Add to Home Screen. It
|
||||
opens full screen with the Luxe mark as its icon, and keeps the sign-in Safari had when you
|
||||
added it. An app added before pairing asks for the invitation link instead: copy it from
|
||||
`luxe remote pair` and paste it in.
|
||||
|
||||
Setup takes four steps, and asks before each one that changes something outside Luxe:
|
||||
|
||||
| Step | Does |
|
||||
| --- | --- |
|
||||
| Tailscale | Checks it is installed and signed in, and stops here if not |
|
||||
| Serve | Publishes the bridge at `https://<computer>.<tailnet>.ts.net/` with Tailscale Serve, for your tailnet only. One that already leads somewhere else is left alone. |
|
||||
| Service | Runs the bridge whenever you're signed in to the computer |
|
||||
| Pairing | Shows a QR code for one device |
|
||||
|
||||
A step that's already done says so and moves on, so running setup again is how to check it. On
|
||||
Linux, Serve may say access was denied; let your account manage Tailscale once, then run setup
|
||||
again:
|
||||
|
||||
```bash
|
||||
sudo tailscale set --operator=$USER
|
||||
```
|
||||
|
||||
The service is your own, and needs no administrator:
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Linux | A systemd user unit, `~/.config/systemd/user/luxe-remote.service` |
|
||||
| macOS | A launch agent, `~/Library/LaunchAgents/dev.luxe.remote.plist` |
|
||||
| Windows | `Luxe remote` under `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` |
|
||||
|
||||
Without it, run `luxe remote` in a terminal, and your devices reach Luxe while it runs.
|
||||
|
||||
## Devices
|
||||
|
||||
```bash
|
||||
luxe remote pair # a QR code and link for one more device
|
||||
luxe remote devices # the paired ones
|
||||
luxe remote devices revoke a41c9e02 # unpair one
|
||||
```
|
||||
|
||||
An invitation pairs one device, within ten minutes. Revoking a device disconnects it within a few
|
||||
seconds; the sessions it had open carry on.
|
||||
|
||||
Only your own Tailscale login gets in. To let someone else on your tailnet in too, name them when
|
||||
you set up, and send them an invitation from `luxe remote pair`:
|
||||
|
||||
```bash
|
||||
luxe remote service remove
|
||||
luxe remote setup --allow sam@github
|
||||
```
|
||||
|
||||
## Two or more computers
|
||||
|
||||
Each computer runs its own bridge at its own address, so one phone can reach several: set each up
|
||||
as above, with Tailscale signed in to the same account, and pair the phone with each. Every one is
|
||||
its own app on the Home Screen, named for the computer as Tailscale names it (`desk` for
|
||||
`desk.tail1234.ts.net`), with the name beside the Luxe mark in its session list and after the
|
||||
project in its notifications, "luxe · desk". Luxe finds Tailscale by the `tailscale` command, so
|
||||
on a Mac check that `tailscale version` works in Terminal before running setup.
|
||||
|
||||
## What your device sees
|
||||
|
||||
Every Luxe running on the computer as you: the interface, `luxe --rpc`, and any started from your
|
||||
device. A device that joins a session is a guest, as in [joining a
|
||||
session](rpc.md#join-a-running-session): it sees the conversation so far and every live event, and
|
||||
can answer prompts and send messages. It can't switch or end the session, or publish to GitHub.
|
||||
|
||||
In a session, the app can:
|
||||
|
||||
- Name the session's folder and branch in the header, starred when the tree has changes.
|
||||
- Show the conversation as the interface draws it: markdown, highlighted code, tool cards. A long
|
||||
one opens on its latest 300 items, and **Show earlier** at the top brings 300 more at a time.
|
||||
- Send a message, with photos from the camera or library, and steer or stop a running turn. While
|
||||
one runs, a line over the message box says what sending will do: steer it at the next step, or
|
||||
wait for the turn to end when a photo is attached.
|
||||
- Run `/compact`, `/cost`, `/dock`, `/mode`, `/model` and `/thinking`, offered as you type a `/`. The
|
||||
interface's other commands work its own screen, so a message that starts with one goes to the
|
||||
agent as written.
|
||||
- Mention a project file: type `@` and pick from the project's folders, a level at a time. A picked
|
||||
file goes in as its path, which is what the interface sends the model for one.
|
||||
- Answer permission prompts and questions. As in the interface, every answer but Reject waits a
|
||||
moment after a prompt appears, so a stray tap can't grant anything.
|
||||
- Switch the mode with a tap on the status line, which also shows the context, thinking level and
|
||||
model. Tap those for the session's details: switch the mode, the thinking level or the model
|
||||
(from the same list as `/model`, with the levels each model honors), and see the cost.
|
||||
- Show [the dock](interface.md#the-dock), with the plan and the changed files. On an iPad or an
|
||||
open iPhone Duo it's a rail beside the conversation: the header's dock button or `/dock` shows
|
||||
and hides it, `/dock left` or `/dock right` moves it, and it starts from your `dock.mode` and
|
||||
`dock.position` [settings](configuration.md), as the interface does. On a phone the header has
|
||||
one menu button, and the dock is the first tab of the panel it opens; `/dock` opens it there
|
||||
too. A long plan scrolls in a box of its own that keeps the work in hand in view, until you
|
||||
scroll it yourself. Tap a file for its diff.
|
||||
- Browse the project's files from the header's menu button, in the interface's FILES tree, and
|
||||
read a file highlighted as the interface shows it. **Mention** adds its path to your message.
|
||||
On an iPad or an open iPhone Duo the tree is a rail and a file opens beside it; on a screen wide
|
||||
enough the conversation stays in view too.
|
||||
- Ask about particular lines of a file, a diff or a review chapter, as you would in the interface's
|
||||
File view: tap a line's number to pick it and another to stretch the pick, or select text the
|
||||
phone's usual way, down to part of a line, and tap **Ask** for the lines it covers. Your message
|
||||
gets the path and lines the interface would send. Tap anywhere else to let a pick go, and copy a
|
||||
selection with the phone's own menu. In a diff, a removed line can't be picked, since the file
|
||||
no longer has it.
|
||||
- Read the project's pull requests and issues in the same panel's GitHub tab, by the sections
|
||||
[`/github`](github.md) shows. Tap one for its overview (what stands between it and merged, or
|
||||
who's on an issue) and its conversation. **Mention** adds it to your message. It only reads: a
|
||||
joined session runs with GitHub writes off, so merging, replying and resolving stay in the
|
||||
interface.
|
||||
- Walk the open [Guided Review](guided-review.md) in the Review tab: the guide's summary and
|
||||
chapters, each one opened beside it with the guide's notes over its diffs. **Reviewed** marks a
|
||||
chapter read, the same progress `/review` keeps, and **Next** opens the one after. The phone
|
||||
joins the review the interface has open rather than starting its own, since a session holds one;
|
||||
with none open, **Review changes** reviews the working changes.
|
||||
- Comment on a review chapter: pick a line, or a run of lines, and tap **Comment**, or tap
|
||||
**Comment on the chapter** with nothing picked. Make it a question if you want an answer rather
|
||||
than a fix, then **Save** it to send later or **Send** it now. Each comment shows under what it's
|
||||
about with the agent's replies, and can be replied to, resolved, or, unsent, sent or deleted.
|
||||
The guide counts what's unsent and sends it all. Comments made in the interface show up too.
|
||||
Editing a comment, re-anchoring one the code moved away from, and commenting on a removed line
|
||||
are the interface's.
|
||||
|
||||
The interface says which device joined, "iPhone joined this session", and which one answered a
|
||||
prompt, "Approved from iPhone". A session with [`joinable`](configuration.md#joining-a-session) set
|
||||
to `false` is out of reach, from your device too.
|
||||
|
||||
## Starting a session
|
||||
|
||||
Tap **New** on the session list to start Luxe in a folder: one where Luxe is running now, one with
|
||||
a [herdr](recipes.md#run-luxe-in-herdr) pane, one where the bridge has seen Luxe run, or any path
|
||||
you type. What you type narrows the folders it offers, by name and then by path. They're only the
|
||||
ones above: it never looks through your home folder.
|
||||
|
||||
**herdr is optional, and recommended.** You don't need it to reach your sessions; it decides what
|
||||
happens to the ones you start away from your desk:
|
||||
|
||||
- **With herdr running**, the bridge opens a herdr pane in that folder, in the workspace already
|
||||
there or a new one named after it. The session survives a restart of the bridge, and waits for
|
||||
you at your desk like any other pane.
|
||||
- **Without it**, the bridge runs `luxe --rpc` itself, and the session lasts as long as the bridge
|
||||
does. At your desk, `luxe --resume` on it is refused while the bridge has it, and says so.
|
||||
|
||||
The bridge uses herdr only when herdr's server is already running, and never starts it.
|
||||
|
||||
## Notifications
|
||||
|
||||
A device can hear when a session needs it: a prompt waiting on an answer, or a long turn finished.
|
||||
Turn them on under **Notifications** in the app's session list. On an iPhone or iPad the app has to
|
||||
be on your Home Screen first (in Safari, Share, then Add to Home Screen), and paired from there, since
|
||||
the Home Screen app keeps its own sign-in.
|
||||
|
||||
A notification says what's waiting and where, "Approve bash" over `my-app`, never the command, and
|
||||
tapping it opens the session. Answering takes the app. So that one doesn't buzz you while you're
|
||||
at your desk:
|
||||
|
||||
- A prompt is held for ten seconds, and one answered meanwhile is never sent.
|
||||
- A finished turn is news only after a turn of thirty seconds or more.
|
||||
- A device with that session open on screen isn't told about it.
|
||||
|
||||
While any device has notifications on, the bridge joins each running session to watch. It joins
|
||||
watch-only, so the interface doesn't announce it and it can't act in the session.
|
||||
[Security](security.md#luxe-remote) covers what a notification carries and where it goes.
|
||||
|
||||
## Turn it off
|
||||
|
||||
```bash
|
||||
luxe remote service remove
|
||||
tailscale serve --https=443 off
|
||||
```
|
||||
|
||||
The first stops the bridge and stops it starting at sign-in; the second takes the address off
|
||||
your tailnet. Your paired devices stay paired until you revoke them, in case you set it up again.
|
||||
|
||||
## How it's kept to you
|
||||
|
||||
Every request needs your Tailscale login, which only Tailscale Serve can vouch for, and every
|
||||
session needs a paired device as well. [Security](security.md#luxe-remote) has the details.
|
||||
@@@ page: rpc
|
||||
---
|
||||
title: "The RPC protocol"
|
||||
@@ -3758,8 +4051,8 @@ luxe --rpc --github-writes # also lets your client publish to GitHub
|
||||
```
|
||||
|
||||
A client is trusted like the interface it replaces: it answers permission prompts, and it cannot
|
||||
loosen any permission rule. There is no network listener; your client is the process that started
|
||||
Luxe.
|
||||
loosen any permission rule. Nothing listens on the network. Your client either started Luxe, or
|
||||
[joined a session](#join-a-running-session) open in the interface on the same machine.
|
||||
|
||||
## A session
|
||||
|
||||
@@ -3767,6 +4060,7 @@ Luxe.
|
||||
→ {"kind":"ready","content":{"protocol_version":2,"luxe_version":"0.1.0","session_id":"…","cwd":"/work/app","github_writes":false}}
|
||||
→ {"kind":"state_changed","content":{"model":{…},"streaming":false,"mode":"build","thinking":"off"}}
|
||||
← {"kind":"submit_user_message","content":{"text":"what does this repo do?"}}
|
||||
→ {"kind":"turn_started"}
|
||||
→ {"kind":"tool_started","content":{"call_id":"call_1","name":"read"}}
|
||||
→ {"kind":"token_delta","content":{"block":0,"delta":"It is "}}
|
||||
→ {"kind":"turn_usage","content":{"prompt_tokens":5018,"completion_tokens":26,"cost_usd":0.0258,…}}
|
||||
@@ -3816,6 +4110,43 @@ for line in luxe.stdout:
|
||||
Three rules make a working client: read `ready` first, answer both kinds of prompt, and ignore
|
||||
what you do not recognize.
|
||||
|
||||
## Join a running session
|
||||
|
||||
A session open in the interface can be joined while you keep using it, and so can one a `luxe --rpc`
|
||||
client started. `luxe join` connects to it and speaks this protocol on stdin and stdout, so the
|
||||
client above works with `["luxe", "join"]` in place of `["luxe", "--rpc"]`.
|
||||
|
||||
```bash
|
||||
luxe join --list # sessions running on this machine
|
||||
luxe join # the one running in this folder
|
||||
luxe join 5898d57b # one by the start of its id, or by its Luxe's process id
|
||||
```
|
||||
|
||||
After `ready` comes the session so far: `session_loaded` with the transcript, the latest
|
||||
`state_changed`, `session_usage` and `workspace_updated`, a `tool_activity_updated` for each call
|
||||
of a turn in flight, and any `permission_requested` or `question_asked` still waiting. Then the
|
||||
live events, the same ones the interface gets.
|
||||
|
||||
A joined client is a guest in someone else's session:
|
||||
|
||||
- **Either side can answer a prompt.** The first answer counts, and `prompt_closed` tells everyone
|
||||
to put the prompt away. The interface says which client answered.
|
||||
- **It can't switch or end the session.** `new_session` and `load_session` are refused with
|
||||
`action_rejected`. `close`, or the end of your stdin, disconnects you and leaves Luxe running.
|
||||
- **GitHub writes are off**, and `ready` says `"github_writes": false`.
|
||||
- **Keep reading.** A client that falls far behind gets a `notice` and is disconnected. Join
|
||||
again for a fresh copy of the session.
|
||||
|
||||
The interface lists who's joined in its dock, and says in the conversation when a client joins or
|
||||
leaves, by the name it gives in `introduce` if it sends one within a second of connecting, or by
|
||||
its process id. A device the bridge introduces as `yours`, paired by you, is listed but not
|
||||
announced: you know your own phone joined, and a phone reconnects often.
|
||||
|
||||
A running Luxe lists its session in a file in its [runtime folder](environment.md#integrations),
|
||||
`<pid>.json`, with the `address` to connect to: a Unix socket, or a named pipe on Windows. Connect
|
||||
there yourself to skip `luxe join`.
|
||||
To stop sessions being joined, set [`joinable`](configuration.md#joining-a-session) to `false`.
|
||||
|
||||
## Actions
|
||||
|
||||
| `kind` | `content` | Does |
|
||||
@@ -3831,6 +4162,7 @@ what you do not recognize.
|
||||
| `answer_question` | `{"id": "ask:…", "reply": {"answered": ["postgres"]}}` | Answer a question, or `{"reply": "cancelled"}` |
|
||||
| `set_permission_auto_approve` | `true` | Approve every prompt for the rest of the session. Deny rules still apply. |
|
||||
| `select_model` | `{"provider": "anthropic", "model": "claude-sonnet-5"}` | Switch models |
|
||||
| `list_models` | `{"request_id": "…"}` | The models you can switch to, configured ones first, each with the thinking levels it honors; answered by `models_listed`, to you alone |
|
||||
| `set_thinking_level` | `"high"` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh` or `ultra` |
|
||||
| `set_mode` | `"plan"` | `build` or `plan`; see [Plan, then build](agent.md#plan-then-build). A name that is not a mode is answered by a `notice`. |
|
||||
| `request_review` | `{"focus": "error handling"}`, or nothing | A [second opinion](agent.md#a-second-opinion) on the uncommitted changes; answered by `review_started`, then `review_finished` |
|
||||
@@ -3844,6 +4176,7 @@ what you do not recognize.
|
||||
| `load_file_diff` | `{"request_id": "…", "path": "src/main.rs"}` | One file's change, outside any review; answered by `file_diff_loaded` |
|
||||
| `list_directory` | `{"request_id": "…", "path": "src"}` | One project folder's entries, without what `.gitignore` ignores unless `"include_ignored": true`, which marks each such entry `"ignored": true`; answered by `directory_listed` |
|
||||
| `read_project_file` | `{"request_id": "…", "path": "src/main.rs"}` | One project file's text, up to 2 MB; answered by `project_file_read` |
|
||||
| `introduce` | `{"name": "iPhone"}` | A joined client's name, which the interface uses when it says who joined or answered. Add `"watch_only": true` as your first line to read without being announced; Luxe then drops everything else you send. `"yours": true` says the person at the terminal paired it, so it's listed without a line in the conversation. Refused from the client that started the session. |
|
||||
| `close` | | Shut down, stopping a turn in flight the way `cancel` does. The stream ends after it. |
|
||||
|
||||
### Guided Review
|
||||
@@ -3853,6 +4186,9 @@ carries the whole review (its `id`, `revision_id`, files, hunks and chapters), a
|
||||
`review_session_restored`, which carries its comments. Everything below names the review by its
|
||||
`id`. An action for a review that is no longer the open one is refused.
|
||||
|
||||
A session has one open review, and every load makes a new one, so a second client that loads its
|
||||
own replaces the review the first is reading. To join it instead, send `show_open_review`.
|
||||
|
||||
```text
|
||||
← {"kind":"load_guided_review","content":{"request_id":"r1","target":{"kind":"working_tree"}}}
|
||||
→ {"kind":"guided_review_loaded","content":{"request_id":"r1","review":{"id":"review:…","revision_id":"…",…}}}
|
||||
@@ -3891,6 +4227,7 @@ the comment stays `open`.
|
||||
| `edit_review` | `{"request_id", "review_id", "edit", …}` | Change the comments, as above |
|
||||
| `record_review_progress` | `{"review_id", "walked_chapter_ids": [...]}` | Which chapters were read. Saved when it changed, never answered. |
|
||||
| `record_review_seen` | `{"review_id"}` | Remember what the walked chapters covered, so the next review of the same target leads with what is new |
|
||||
| `show_open_review` | `{"request_id"}` | Ask for the review open now, whoever opened it, answered by `open_review_shown` |
|
||||
| `refresh_guided_review` | `{"request_id", "review_id", "revision_id"}` | Read the change again, keeping the comments, if the review is still at `revision_id`. Answered like a load. |
|
||||
| `commit_review_chapters` | `{"request_id", "review_id", "revision_id", "chapter_ids", "squash"}` | A commit per chapter, or one with `squash`. All chapters when `chapter_ids` is left out. Never pushes. Answered by `review_committed`. |
|
||||
| `prepare_pull_request` | `{"request_id", "review_id"}` | Draft the pull request this branch's review would open; answered by `pull_request_prepared` |
|
||||
@@ -3963,6 +4300,7 @@ There are around sixty. These are the ones a front end is built on:
|
||||
| `message_committed` | A complete message was added to the transcript |
|
||||
| `permission_requested` | **Answer it** with `respond_permission`, or the turn waits. If `always_patterns` is empty, offer only `once` and `reject`. |
|
||||
| `question_asked` | **Answer it** with `answer_question` |
|
||||
| `turn_started` | A turn began, from any client. It comes before the turn's message is saved, and `turn_ended` always follows. A client joining mid-turn gets it as part of catching up. |
|
||||
| `turn_ended` | The turn finished; `reason` says why |
|
||||
| `provider_retrying` | The provider failed before answering, and Luxe is trying again |
|
||||
| `state_changed` | Model, thinking level, mode, and whether a turn is running |
|
||||
@@ -3972,8 +4310,10 @@ There are around sixty. These are the ones a front end is built on:
|
||||
| `context_usage`, `context_composition` | How full the context window is, and with what |
|
||||
| `compaction_started`, `compaction_done`, `compaction_stopped` | A summary of the conversation is being written, on request or mid-turn. It can take a minute. It always ends in `compaction_done` (with `tokens_after`) or `compaction_stopped` (failed or cancelled). |
|
||||
| `workspace_updated` | The project, Git changes, todos and tools: what the dock shows |
|
||||
| `prompt_closed` | A prompt stopped waiting, answered here or by another client, or cancelled. Take it down by `id`. |
|
||||
| `session_loaded`, `sessions_refreshed` | A transcript was restored; the session list changed |
|
||||
| `notice`, `error` | Something to show. `error` ends the turn. |
|
||||
| `guests_changed` | The names of the clients joined now, sent to the interface as one joins or leaves, for its dock. |
|
||||
| `action_rejected` | Your frame was refused and nothing happened |
|
||||
|
||||
Guided Review, as the interface sees it:
|
||||
@@ -3983,6 +4323,7 @@ Guided Review, as the interface sees it:
|
||||
| `guided_review_loading`, `guided_review_loaded`, `guided_review_failed` | A review you asked for, by `request_id`. `loaded` carries the whole review: files, hunks and chapters. |
|
||||
| `guided_review_guide_updated` | Better chapters and a summary replaced the first ones, for the same pinned revision |
|
||||
| `review_session_restored` | The comments and progress that go with the review just loaded. It always follows `guided_review_loaded`, after a restart too. |
|
||||
| `open_review_shown` | The answer to `show_open_review`, under its `request_id`: the open `review` and its `session`, or neither when no review is open. `reading` says what each chapter asks of the reader: `needs_review` items, and the `reason` when one thing accounts for all of them. |
|
||||
| `review_session_saved`, `review_session_save_failed` | A change to them was stored, or refused. Luxe reports its own changes this way too: a turn starting, the agent's report, a review posted. |
|
||||
| `review_feedback_turn_dispatched`, `review_feedback_turn_completed`, `review_feedback_turn_failed` | Feedback you sent reaching the agent, and how its turn went |
|
||||
| `review_questions_answered`, `remediation_reported` | The agent's answer to a question, and its report on a fix |
|
||||
@@ -3990,6 +4331,7 @@ Guided Review, as the interface sees it:
|
||||
| `last_turn_available` | The agent's last turn can be reviewed on its own |
|
||||
| `file_diff_loaded`, `file_diff_failed` | One file's change, for `load_file_diff` |
|
||||
| `directory_listed`, `directory_list_failed` | One folder's entries, for `list_directory` |
|
||||
| `models_listed` | The models for `list_models`: each has `provider` and `model` for `select_model`, a `name` to show, and its `thinking_levels` |
|
||||
| `project_file_read`, `project_file_read_failed` | One file's text, for `read_project_file` |
|
||||
|
||||
GitHub:
|
||||
@@ -4021,7 +4363,9 @@ list is closed.
|
||||
|
||||
## Security
|
||||
|
||||
- Luxe listens on nothing; your client is the process that started it.
|
||||
- Nothing listens on the network. A [joined](#join-a-running-session) session takes connections
|
||||
on a local socket or pipe that only your user account can open, and turns away any program the
|
||||
agent itself started, so the agent can't answer its own prompts.
|
||||
- Permission rules are enforced inside Luxe. A client cannot weaken a `deny`: reading `.env` is
|
||||
refused here as everywhere.
|
||||
- Prompts go to your client to answer. To approve everything, send `set_permission_auto_approve` or
|
||||
@@ -4190,6 +4534,69 @@ or `"agent": { "on_ask": "deny" }` in `config.json`. A project can set `deny` bu
|
||||
closing an issue. Auto-approve and unattended runs refuse them. To let an unattended run do one,
|
||||
allow it in your own rules, such as `"bash": { "gh pr merge *": "allow" }`.
|
||||
|
||||
## Joining a session
|
||||
|
||||
A session open in the interface can be [joined](rpc.md#join-a-running-session) by another program,
|
||||
which then sees the conversation and can answer its prompts. That makes who may join a security
|
||||
question:
|
||||
|
||||
- **Only your user account.** The socket sits in a folder only you can open, only you can use it,
|
||||
and Luxe checks the account of whatever connects. On Windows the named pipe admits your account
|
||||
alone, and refuses remote clients.
|
||||
Nothing listens on the network.
|
||||
- **Not the agent.** A program the agent started, at any depth, is turned away, so it can't
|
||||
approve its own prompts. Luxe checks the joining process's ancestry. It can't see past a program
|
||||
that detaches from its parent, such as one started with `setsid` and left running after its
|
||||
parent exits, so treat this as a tripwire, not a wall. A command that would do that should be
|
||||
something your rules ask about.
|
||||
- **A guest can't do everything.** A joined client can't switch or end the session, and can't
|
||||
publish to GitHub.
|
||||
|
||||
Anything running as you can already read your sessions on disk and your credentials, so joining
|
||||
adds a way to steer, not a way to read. To turn it off, set
|
||||
[`joinable`](configuration.md#joining-a-session) to `false`.
|
||||
|
||||
## Luxe remote
|
||||
|
||||
[`luxe remote`](remote.md) is the one part of Luxe that answers network requests, and it is off
|
||||
until you run it. It puts your sessions in reach of your phone, so it takes two things to get in:
|
||||
|
||||
- **Your Tailscale login.** The bridge listens on this machine only (`127.0.0.1`) and refuses to
|
||||
listen anywhere else. Tailscale Serve carries it to your tailnet over HTTPS and adds the login of
|
||||
whoever is asking, replacing any the request brought. A request without one didn't come through
|
||||
Serve and is refused, and so is a login other than yours or one you `--allow`. Luxe never uses
|
||||
Tailscale Funnel, which would publish it to the internet.
|
||||
- **A paired device.** Any program on this machine can reach a local port and claim a login, so
|
||||
every session also needs the credential a device gets when it pairs. An invitation works once,
|
||||
within ten minutes. Luxe keeps only a hash of each invitation and credential, in
|
||||
`~/.config/luxe/remote.json`. The device keeps its credential in a cookie scripts can't read,
|
||||
sent only over HTTPS and never with a request from another site; a request a page on another
|
||||
site makes is refused too.
|
||||
|
||||
Revoking a device disconnects it within a few seconds. A device joins a session as a guest, with
|
||||
the same limits as any [joined client](#joining-a-session), and the interface names it when it joins
|
||||
and when it answers a prompt. The name is the device's own label: whether a client may answer
|
||||
prompts at all is still decided by the process checks above.
|
||||
|
||||
Notifications are off until you turn them on in the app, one device at a time, and they never
|
||||
answer anything: a notification says what is waiting and where, such as "Approve bash" over the
|
||||
folder's name, never the command, and answering takes the app. While any device has them on, the
|
||||
bridge joins each running session to watch for prompts. It joins watch-only: the terminal doesn't
|
||||
announce it, and Luxe drops anything it sends, so a client nobody sees can't act. Each
|
||||
notification is sealed so only that device can read it (RFC 8291) and posted to the push service
|
||||
the device's browser picked; the push service sees when, not what. The bridge posts only to
|
||||
Apple's, Google's, Mozilla's and Microsoft's push services, so a paired device can't aim it at
|
||||
anything else on your network. It signs with a key of its own, kept in `remote.json`, and revoking
|
||||
a device ends its notifications.
|
||||
|
||||
The bridge starts Luxe only in a folder a device asks for, as you, in a herdr pane when herdr is
|
||||
already running and as its own `luxe --rpc` otherwise. A packager can build Luxe without the
|
||||
`remote` feature, which leaves out the bridge entirely.
|
||||
|
||||
A session is open in one Luxe at a time. A second `luxe --resume` of a session the interface
|
||||
already has, or a resume from the session list, is refused and says which process has it. The lock
|
||||
is the operating system's, so a crash never leaves a session stuck.
|
||||
|
||||
## Secrets
|
||||
|
||||
- Credentials are stored in `~/.config/luxe/auth.json`, readable only by you. Luxe warns if
|
||||
@@ -4303,6 +4710,9 @@ There is no telemetry. Luxe connects only to:
|
||||
5. GitHub, through your own `gh`, when you, the agent or an [RPC client](rpc.md#github-writes) work
|
||||
with pull requests and issues. A client can write there only if you start it with
|
||||
`--github-writes`.
|
||||
6. Your device's push service (Apple's, for an iPhone), when you turn on notifications in the
|
||||
[`luxe remote`](remote.md#notifications) app, sealed so only that device can read them
|
||||
(turning them off in the app stops it)
|
||||
|
||||
None of them carries anything about you or your machine. The update check sends no version,
|
||||
platform or identifier; it downloads a public file and compares versions locally.
|
||||
@@ -4310,15 +4720,23 @@ platform or identifier; it downloads a public file and compares versions locally
|
||||
One local report stays on your machine: inside a [herdr](configuration.md#herdr) pane, Luxe runs
|
||||
herdr's own command to tell it whether the agent is working, idle or waiting on you, and the id of
|
||||
the session for herdr to resume. Nothing is sent outside herdr, and `"herdr": false` stops it.
|
||||
And a running session takes connections on a local socket only you can open, so another program can
|
||||
[join it](#joining-a-session); `"joinable": false` stops that.
|
||||
|
||||
Apart from notifications, `luxe remote` sends nothing of its own. It answers your paired devices
|
||||
through Tailscale Serve and runs your own `tailscale` and `herdr` commands; see
|
||||
[Luxe remote](#luxe-remote).
|
||||
|
||||
What you post to GitHub is yours alone: reviews, replies and pull requests are posted from a
|
||||
preview, with nothing added, and no agent tool can post them.
|
||||
|
||||
## Supply chain
|
||||
|
||||
Luxe is written in Rust with `unsafe` code denied throughout, apart from two reviewed blocks in what
|
||||
ships: one starts each command in a session of its own, so nothing the agent runs can reach your
|
||||
terminal, and one on Windows keeps the programs Luxe starts off the stdin `--rpc` reads. CI checks
|
||||
Luxe is written in Rust with `unsafe` code denied throughout, apart from a few small, reviewed
|
||||
modules that call the operating system directly. One starts each command in a session of its own,
|
||||
so nothing the agent runs can reach your terminal. On Windows, one keeps the programs Luxe starts
|
||||
off the stdin `--rpc` reads, one ends a command's whole process tree on a timeout, and one locks
|
||||
the [session pipe](#joining-a-session) to your account. CI checks
|
||||
every dependency's security advisories and license with `cargo-deny`, builds with `--locked`, and
|
||||
pins its GitHub Actions to exact commits.
|
||||
@@@ page: sessions
|
||||
|
||||
@@ -153,6 +153,28 @@ pub(crate) fn build_menu(settings: &AgentSettings) -> ModelMenu {
|
||||
ModelMenu { catalog: entries, active }
|
||||
}
|
||||
|
||||
/// The models a client of the protocol can switch to: the `/model` menu in its order, leaving out
|
||||
/// rows only guessed for an endpoint that hasn't said what it serves.
|
||||
pub(crate) fn choices(settings: &AgentSettings) -> Vec<luxe_core::event::ModelChoice> {
|
||||
offered(&build_menu(settings).catalog)
|
||||
}
|
||||
|
||||
fn offered(menu: &[ModelEntry]) -> Vec<luxe_core::event::ModelChoice> {
|
||||
menu.iter().filter(|entry| !entry.unverified).map(|entry| choice(&entry.info)).collect()
|
||||
}
|
||||
|
||||
/// `info` as a client offers it, with the thinking levels it honors as they are, not clamped.
|
||||
fn choice(info: &ModelInfo) -> luxe_core::event::ModelChoice {
|
||||
let levels = luxe_core::provider::ThinkingLevel::ALL.iter().copied();
|
||||
let honored = levels.filter(|level| info.effective_thinking_level(*level) == *level);
|
||||
luxe_core::event::ModelChoice {
|
||||
provider: info.r#ref.provider.clone(),
|
||||
model: info.r#ref.id.clone(),
|
||||
name: info.display().to_string(),
|
||||
thinking_levels: honored.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a provider needs no credential at all — a server on this machine.
|
||||
///
|
||||
/// Naming one on the command line is the whole statement of intent: there is no key to check, so
|
||||
|
||||
@@ -223,3 +223,44 @@ fn an_unconfigured_machine_has_no_models_to_choose_between() {
|
||||
);
|
||||
drop(dir);
|
||||
}
|
||||
|
||||
/// A choice names the model as `select_model` takes it, and offers the levels it honors as they
|
||||
/// are: only `off` for a model that doesn't reason, and nothing it would quietly clamp.
|
||||
///
|
||||
/// The break this catches: offering every level for every model, so a phone sets `ultra` and the
|
||||
/// engine silently runs `high`; or sending the display name where `select_model` wants the id.
|
||||
#[test]
|
||||
fn a_choice_offers_only_the_levels_its_model_honors() {
|
||||
use luxe_core::provider::ThinkingLevel::{High, Low, Medium, Minimal, Off};
|
||||
let mut info = ModelInfo {
|
||||
r#ref: luxe_core::provider::ModelRef::new("anthropic", "claude-sonnet-5"),
|
||||
display_name: Some("Claude Sonnet 5".into()),
|
||||
reasoning: false,
|
||||
..Default::default()
|
||||
};
|
||||
let plain = choice(&info);
|
||||
assert_eq!((plain.provider.as_str(), plain.model.as_str()), ("anthropic", "claude-sonnet-5"));
|
||||
assert_eq!(plain.name, "Claude Sonnet 5");
|
||||
assert_eq!(plain.thinking_levels, [Off]);
|
||||
info.reasoning = true;
|
||||
assert_eq!(choice(&info).thinking_levels, [Off, Minimal, Low, Medium, High]);
|
||||
}
|
||||
|
||||
/// A row only guessed for an endpoint that hasn't said what it serves isn't offered.
|
||||
///
|
||||
/// The break this catches: a phone offering an Azure resource deployments it doesn't have, which
|
||||
/// fail on the first turn.
|
||||
#[test]
|
||||
fn a_guessed_row_isnt_offered() {
|
||||
let entry = |id: &str, unverified: bool| ModelEntry {
|
||||
info: ModelInfo {
|
||||
r#ref: luxe_core::provider::ModelRef::new("azure", id),
|
||||
..Default::default()
|
||||
},
|
||||
label: id.into(),
|
||||
configured: false,
|
||||
unverified,
|
||||
};
|
||||
let offered = offered(&[entry("served", false), entry("guessed", true)]);
|
||||
assert_eq!(offered.iter().map(|choice| choice.model.as_str()).collect::<Vec<_>>(), ["served"]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user