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:
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user