luxe 0.1.4: remembered models, wheel-driven lists, and a steadier phone app
- luxe starts on the model you last chose in this project, then the last one anywhere. Signing in opens the model picker instead of choosing for you. - Every list in a modal takes the mouse wheel and a draggable scrollbar. - The phone app shows reasoning in full, stays put while you read back through a long session, and shows a question's answer on its card. - On Windows, luxe update replaces the running luxe, and a signed-in install no longer sees setup again. - The file tree no longer shows "engine busy" in a large project, loop output is easier to follow, and the name is written lowercase. The CHANGELOG has the full list.
This commit is contained in:
@@ -62,7 +62,7 @@ fn a_failed_call_summarizes_its_own_error() {
|
||||
"edited before reading the file",
|
||||
),
|
||||
(
|
||||
"Error: 'src/lib.rs' exists and has no read on record for this Luxe run \
|
||||
"Error: 'src/lib.rs' exists and has no read on record for this luxe run \
|
||||
(read-before-write guard), so overwriting it would be blind.",
|
||||
"overwrote a file it hadn't read",
|
||||
),
|
||||
|
||||
@@ -40,6 +40,44 @@ pub(crate) fn auth_service() -> luxe_tui::auth_wizard::AuthServiceHandle {
|
||||
std::sync::Arc::new(luxe_providers::auth::ProviderAuth::new())
|
||||
}
|
||||
|
||||
/// Carries the flags that shape this run, rather than where it starts, onto `settings`.
|
||||
fn apply_run_flags(args: &Args, settings: &mut crate::engine_setup::AgentSettings) {
|
||||
settings.resume = resume_from_args(args);
|
||||
settings.permission_mode = permission_mode_from_args(args);
|
||||
settings.trust_project = args.trust_project;
|
||||
settings.disable_tools = args.no_tool.clone();
|
||||
settings.enable_tools = args.with_tool.clone();
|
||||
apply_thinking_flag(args.thinking.as_deref(), settings);
|
||||
settings.auto_approve = args.auto_approve;
|
||||
if let Some(on_ask) = args.on_ask {
|
||||
settings.on_ask = on_ask.into();
|
||||
}
|
||||
if args.auto_approve && !args.prompts_a_human() && args.starts_an_engine() {
|
||||
settings.startup_notices.push(
|
||||
"--auto-approve: an unattended run already allows an `ask`. `--on-ask deny` is how to \
|
||||
make one refuse instead."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if args.plan {
|
||||
settings.initial_mode = Some(luxe_core::mode::PLAN.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the thinking level `--thinking` names; a level luxe doesn't know is reported and ignored.
|
||||
fn apply_thinking_flag(raw: Option<&str>, settings: &mut crate::engine_setup::AgentSettings) {
|
||||
let Some(raw) = raw else {
|
||||
return;
|
||||
};
|
||||
match args::parse_thinking_level(raw) {
|
||||
Some(level) => {
|
||||
settings.initial_thinking = Some(level);
|
||||
settings.thinking_forced = true;
|
||||
}
|
||||
None => eprintln!("luxe: ignoring unknown --thinking level '{raw}'"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-level dispatch: parse args and route to the requested mode.
|
||||
pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
|
||||
// The guide is in the binary and needs nothing else: no project, no settings, no network
|
||||
@@ -58,34 +96,7 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
|
||||
let root = enter_project(&mut args, &invoked_from)?;
|
||||
// Resolve provider/model/auth once (CLI flags > env > config) and share it downstream.
|
||||
let mut settings = crate::engine_setup::AgentSettings::resolve(root, args.overrides());
|
||||
settings.resume = resume_from_args(&args);
|
||||
settings.permission_mode = permission_mode_from_args(&args);
|
||||
settings.trust_project = args.trust_project;
|
||||
settings.disable_tools = args.no_tool.clone();
|
||||
settings.enable_tools = args.with_tool.clone();
|
||||
if let Some(raw) = args.thinking.as_deref() {
|
||||
match args::parse_thinking_level(raw) {
|
||||
Some(level) => {
|
||||
settings.initial_thinking = Some(level);
|
||||
settings.thinking_forced = true;
|
||||
}
|
||||
None => eprintln!("luxe: ignoring unknown --thinking level '{raw}'"),
|
||||
}
|
||||
}
|
||||
settings.auto_approve = args.auto_approve;
|
||||
if let Some(on_ask) = args.on_ask {
|
||||
settings.on_ask = on_ask.into();
|
||||
}
|
||||
if args.auto_approve && !args.prompts_a_human() && args.starts_an_engine() {
|
||||
settings.startup_notices.push(
|
||||
"--auto-approve: an unattended run already allows an `ask`. `--on-ask deny` is how to \
|
||||
make one refuse instead."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if args.plan {
|
||||
settings.initial_mode = Some(luxe_core::mode::PLAN.to_string());
|
||||
}
|
||||
apply_run_flags(&args, &mut settings);
|
||||
|
||||
if args.starts_an_engine() {
|
||||
enter_worktree(&args, &mut settings).await?;
|
||||
@@ -104,9 +115,13 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
|
||||
// loop run needs the right context window just as much. Best-effort and non-blocking.
|
||||
crate::model_catalog::spawn_refresh();
|
||||
|
||||
// Ask, at most daily, whether a newer Luxe exists. The answer lands in a cache and is read by
|
||||
// Ask, at most daily, whether a newer luxe exists. The answer lands in a cache and is read by
|
||||
// the *next* launch's dashboard, so nothing here is on the path to a first token.
|
||||
crate::update_check::spawn_check(&settings.state_root);
|
||||
// The copy a Windows update moved aside; nothing to find anywhere else
|
||||
if cfg!(windows) {
|
||||
update_command::remove_leftover();
|
||||
}
|
||||
|
||||
if let Some(cmd) = args.command {
|
||||
match cmd {
|
||||
|
||||
@@ -8,7 +8,7 @@ mod permission_mode;
|
||||
pub(crate) use commands::*;
|
||||
pub(crate) use permission_mode::PermissionModeArg;
|
||||
|
||||
/// Luxe's command line. `--help` shows the crate description from `Cargo.toml`, not this doc.
|
||||
/// 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 {
|
||||
@@ -17,7 +17,7 @@ pub(crate) struct Args {
|
||||
pub(crate) headless: bool,
|
||||
|
||||
/// Speak the JSONL front-end protocol on stdio: wire actions in, events out. For editor
|
||||
/// plugins, alternative UIs, and anything driving Luxe as a session rather than a one-shot.
|
||||
/// plugins, alternative UIs, and anything driving luxe as a session rather than a one-shot.
|
||||
/// See `docs/guide/rpc.md`.
|
||||
#[arg(long, conflicts_with = "headless")]
|
||||
pub(crate) rpc: bool,
|
||||
@@ -279,7 +279,7 @@ impl Args {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a `--thinking` level name into a `ThinkingLevel`, accepting the same spellings Luxe
|
||||
/// Parse a `--thinking` level name into a `ThinkingLevel`, accepting the same spellings luxe
|
||||
/// displays (`off`..`ultra`, plus `max` as an alias for `ultra`). Returns `None` for unknown input.
|
||||
pub(crate) fn parse_thinking_level(raw: &str) -> Option<luxe_core::provider::ThinkingLevel> {
|
||||
let name = raw.trim().to_ascii_lowercase();
|
||||
|
||||
@@ -7,13 +7,13 @@ use clap::{Parser, Subcommand};
|
||||
pub(crate) enum SubCommand {
|
||||
/// Sign in to a provider, check credentials, or sign out.
|
||||
Auth(AuthArgs),
|
||||
/// Read Luxe's user guide, for this version.
|
||||
/// Read luxe's user guide, for this version.
|
||||
Docs(DocsArgs),
|
||||
/// Check which language servers, debug adapters and tools work on this machine.
|
||||
Doctor,
|
||||
/// Set Luxe up: a theme, a provider, the tools and the start screen.
|
||||
/// 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
|
||||
/// 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.
|
||||
@@ -27,7 +27,7 @@ pub(crate) enum SubCommand {
|
||||
Models(ModelsArgs),
|
||||
/// List this project's sessions.
|
||||
Sessions(SessionsArgs),
|
||||
/// Update Luxe with the command for however it was installed.
|
||||
/// Update luxe with the command for however it was installed.
|
||||
Update(UpdateArgs),
|
||||
/// Summarize a `LUXE_WIRE_LOG` capture.
|
||||
Wire(WireArgs),
|
||||
@@ -109,10 +109,10 @@ pub(crate) struct ModelsArgs {
|
||||
pub(crate) command: ModelsCommand,
|
||||
}
|
||||
|
||||
/// Models subcommand — what Luxe knows about a model, and where it learned it.
|
||||
/// Models subcommand — what luxe knows about a model, and where it learned it.
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum ModelsCommand {
|
||||
/// List known models for the providers Luxe can route to.
|
||||
/// List known models for the providers luxe can route to.
|
||||
List {
|
||||
/// Only this provider.
|
||||
#[arg(long)]
|
||||
@@ -148,7 +148,7 @@ pub(crate) struct InitArgs {
|
||||
/// 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
|
||||
/// 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.
|
||||
|
||||
@@ -105,17 +105,11 @@ fn report_success(service: &ProviderAuth, outcome: &LoginOutcome) {
|
||||
field("models", note);
|
||||
}
|
||||
field("saved to", &luxe_core::paths::home_relative(&service.store_path()));
|
||||
if let Some(model) = &outcome.suggested_model {
|
||||
field("model", &format!("{model} {}", style::dim("(now the default)")));
|
||||
}
|
||||
// Advice sits apart from the summary: it's about what to do later, not what just happened.
|
||||
for advice in &outcome.advice {
|
||||
outln!("\n {}", style::dim(advice));
|
||||
}
|
||||
match outcome.suggested_model {
|
||||
Some(_) => outln!("\nRun `luxe` to start, or `/model` to pick another."),
|
||||
None => outln!("\nRun `luxe` to start, then `/model` to pick a model."),
|
||||
}
|
||||
outln!("\nRun `luxe` to start, then `/model` to pick a model.");
|
||||
}
|
||||
|
||||
/// `luxe auth list` — every provider and how it's configured.
|
||||
|
||||
@@ -172,7 +172,7 @@ async fn start_loop(
|
||||
event_rx,
|
||||
running_rx,
|
||||
kickoff,
|
||||
crate::loop_view::LoopView::new(quiet),
|
||||
crate::loop_view::LoopView::new(quiet, phase),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! The guide ships in the binary, so it works offline and always describes the version installed:
|
||||
//! `scripts/guide-bundle.sh` writes every page of `docs/guide/` into `src/guide.md`, and this reads
|
||||
//! that bundle. The agent is told the command exists, so asking Luxe how to configure Luxe gets an
|
||||
//! that bundle. The agent is told the command exists, so asking luxe how to configure luxe gets an
|
||||
//! answer from the manual rather than a guess.
|
||||
|
||||
use crate::cli::args::DocsArgs;
|
||||
@@ -11,7 +11,7 @@ use crate::cli::args::DocsArgs;
|
||||
const BUNDLE: &str = include_str!("../guide.md");
|
||||
|
||||
/// The sidebar's groups, in reading order. `web/src/content.config.ts` holds the same list.
|
||||
const GROUPS: [&str; 5] = ["Get started", "Using Luxe", "Customize", "Extend", "Reference"];
|
||||
const GROUPS: [&str; 5] = ["Get started", "Using luxe", "Customize", "Extend", "Reference"];
|
||||
|
||||
/// The most lines `--search` prints, so a common word cannot flood a tool result.
|
||||
const SEARCH_LIMIT: usize = 40;
|
||||
@@ -74,7 +74,7 @@ pub(crate) fn run(args: &DocsArgs) -> anyhow::Result<()> {
|
||||
/// Every page, under its group, with its summary and how to read it.
|
||||
fn index(pages: &[Page]) -> String {
|
||||
let mut out = String::from(
|
||||
"Luxe's user guide, for this version. `luxe docs <page>` prints a page; \
|
||||
"luxe's user guide, for this version. `luxe docs <page>` prints a page; \
|
||||
`luxe docs --search <words>` finds lines across all of them.\n",
|
||||
);
|
||||
for group in GROUPS {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `luxe doctor` — is the tooling on this machine actually going to work?
|
||||
//!
|
||||
//! Luxe launches language servers and debug adapters; it does not install them, and it does not
|
||||
//! luxe launches language servers and debug adapters; it does not install them, and it does not
|
||||
//! bundle them: installation would mean owning each language's package manager and update policy.
|
||||
//! A broken or absent one can otherwise stay invisible until a tool call comes back empty.
|
||||
//!
|
||||
@@ -63,7 +63,7 @@ async fn language_servers() {
|
||||
let configured: std::collections::HashSet<String> = user.keys().cloned().collect();
|
||||
for language in registry.merge_patches(user) {
|
||||
say(&format!(
|
||||
" FAIL {language:<12} lsp-servers.json gives no `command`, and Luxe ships none"
|
||||
" FAIL {language:<12} lsp-servers.json gives no `command`, and luxe ships none"
|
||||
));
|
||||
}
|
||||
let mut languages: Vec<(&String, &ServerEntry)> = registry.iter().collect();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `luxe join` — a session another Luxe is running, over stdin and stdout.
|
||||
//! `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
|
||||
//! 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.
|
||||
@@ -63,7 +63,7 @@ fn nothing_to_join(running: &[LiveSession], target: Option<&str>, cwd: &str) ->
|
||||
};
|
||||
if running.is_empty() {
|
||||
return format!(
|
||||
"{wanted}, and none is running on this machine that can be joined. A Luxe shares \
|
||||
"{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."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ fn sessions() -> Vec<LiveSession> {
|
||||
/// 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.
|
||||
/// session, or refuses because more than one luxe is running somewhere.
|
||||
#[test]
|
||||
fn no_target_joins_the_session_running_here() {
|
||||
let all = sessions();
|
||||
@@ -39,7 +39,7 @@ fn two_sessions_in_the_folder_are_listed_not_guessed() {
|
||||
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.
|
||||
/// 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.
|
||||
@@ -62,7 +62,7 @@ fn an_ambiguous_or_empty_target_is_refused() {
|
||||
|
||||
/// 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
|
||||
/// 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() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `luxe models` — inspect and refresh the model catalog.
|
||||
//!
|
||||
//! Exists mostly for one question: *why does Luxe think my model has a 128k window?* `show`
|
||||
//! Exists mostly for one question: *why does luxe think my model has a 128k window?* `show`
|
||||
//! answers it directly by printing which layer won each field, so a stale cache, a missing
|
||||
//! provider mapping, and a forgotten config override are all distinguishable at a glance.
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ async fn serve(port: u16, allow: Vec<String>, devices: DeviceBook) -> anyhow::Re
|
||||
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!("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 {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `luxe remote setup` — from nothing to a paired phone, asking before each step that changes
|
||||
//! something outside Luxe.
|
||||
//! 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
|
||||
@@ -108,7 +108,7 @@ fn service_step(port: u16, tailnet: &Tailnet, allow: Vec<String>) {
|
||||
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.");
|
||||
outln!("Skipped. Run `luxe remote` yourself whenever your devices should reach luxe.");
|
||||
return;
|
||||
}
|
||||
let launch =
|
||||
|
||||
@@ -75,7 +75,7 @@ impl GithubWrites {
|
||||
match self {
|
||||
Self::Allowed => None,
|
||||
Self::NotEnabled => Some(format!(
|
||||
"{kind} publishes to GitHub, which this session does not allow: start Luxe with \
|
||||
"{kind} publishes to GitHub, which this session does not allow: start luxe with \
|
||||
--github-writes to let a client do that"
|
||||
)),
|
||||
Self::ReadOnly => Some(format!(
|
||||
@@ -151,7 +151,7 @@ fn session_refusal(wire: &WireAction, policy: &Policy) -> Option<String> {
|
||||
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";
|
||||
another luxe";
|
||||
return Some(format!("{kind} {reason}"));
|
||||
}
|
||||
None
|
||||
|
||||
@@ -447,7 +447,7 @@ fn github_writes_need_the_flag_and_read_only_refuses_them_anyway() {
|
||||
]
|
||||
};
|
||||
for (gate, needle) in [
|
||||
(GithubWrites::NotEnabled, "start Luxe with --github-writes"),
|
||||
(GithubWrites::NotEnabled, "start luxe with --github-writes"),
|
||||
(GithubWrites::ReadOnly, "read-only"),
|
||||
] {
|
||||
for wire in writes() {
|
||||
|
||||
@@ -11,7 +11,7 @@ fn footer_note(repo_root: &std::path::Path) -> Option<String> {
|
||||
crate::update_check::cached_notice(repo_root).map(|_| UPDATE_HINT.to_string())
|
||||
}
|
||||
|
||||
/// What the dashboard says when a newer Luxe exists.
|
||||
/// What the dashboard says when a newer luxe exists.
|
||||
const UPDATE_HINT: &str = "Update available · /update";
|
||||
|
||||
/// Whether the startup dashboard should be shown.
|
||||
@@ -295,7 +295,7 @@ async fn starting_status(
|
||||
/// mid-session shows up without relaunching. The probe is the same menu built after asking every
|
||||
/// connected local server what it is serving — a list that changes the moment somebody loads a
|
||||
/// model, and that only the endpoint knows. An Azure resource is the same question asked of a
|
||||
/// cloud: what is deployed there changes in a portal Luxe never sees. A server that is off leaves
|
||||
/// cloud: what is deployed there changes in a portal luxe never sees. A server that is off leaves
|
||||
/// the record standing.
|
||||
fn model_menu_sources(
|
||||
settings: &crate::engine_setup::AgentSettings,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! `luxe update` — run the update this install's owner provides, then check that it took.
|
||||
//!
|
||||
//! The policy is [`luxe_core::update`]'s: which owner installed this copy, which commands update
|
||||
//! it, and a refusal where Luxe cannot know them. This runs those commands one program at a time
|
||||
//! with the terminal attached, so the reader sees the package manager's own output, and Luxe never
|
||||
//! it, and a refusal where luxe cannot know them. This runs those commands one program at a time
|
||||
//! with the terminal attached, so the reader sees the package manager's own output, and luxe never
|
||||
//! writes a binary itself. `/update` on the dashboard comes here too, once the TUI has handed the
|
||||
//! terminal back.
|
||||
|
||||
@@ -10,6 +10,8 @@ use anyhow::{anyhow, bail, Context};
|
||||
use luxe_core::update::{self, InstallSource};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) use aside::remove_leftover;
|
||||
|
||||
/// Checks for a newer release now and, unless `check_only`, runs the update and checks the result.
|
||||
pub(crate) async fn run(check_only: bool) -> anyhow::Result<()> {
|
||||
let current = luxe_core::version::VERSION;
|
||||
@@ -17,50 +19,62 @@ pub(crate) async fn run(check_only: bool) -> anyhow::Result<()> {
|
||||
.await
|
||||
.map_err(|error| anyhow!("could not check for a newer release: {error}"))?;
|
||||
if !update::is_newer(&latest, current) {
|
||||
println!("Luxe {current} is the newest release.");
|
||||
println!("luxe {current} is the newest release.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("Luxe {latest} is available (you have {current}).");
|
||||
println!("luxe {latest} is available (you have {current}).");
|
||||
let source = InstallSource::detect();
|
||||
match (source.update_steps(), check_only) {
|
||||
(Some(steps), false) if !cfg!(windows) => {
|
||||
run_steps(steps).await?;
|
||||
report(installed_now(&latest).await)
|
||||
}
|
||||
(Some(steps), false) => update_with(steps, &latest).await,
|
||||
_ => {
|
||||
println!("{}", instructions(source, check_only, cfg!(windows)));
|
||||
println!("{}", instructions(source, check_only));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to tell a reader Luxe will not run an update for: they asked only to check, Windows cannot
|
||||
/// replace the running program, or no owner's command is known.
|
||||
fn instructions(source: InstallSource, check_only: bool, windows: bool) -> String {
|
||||
/// Runs the owner's steps over this copy, then checks the `luxe` a shell finds now.
|
||||
///
|
||||
/// Windows won't let a running program's file be overwritten, and `luxe update` is itself a
|
||||
/// running luxe. It does allow a rename, so the running copy steps aside first and the owner
|
||||
/// writes a new file where it was.
|
||||
async fn update_with(steps: &[&[&str]], latest: &str) -> anyhow::Result<()> {
|
||||
let exe = std::env::current_exe().context("could not find the running luxe")?;
|
||||
let aside = match cfg!(windows) {
|
||||
true => Some(aside::MovedAside::move_running(&exe)?),
|
||||
false => None,
|
||||
};
|
||||
let ran = run_steps(steps, exe.parent()).await;
|
||||
if let Some(aside) = &aside {
|
||||
aside.restore_if_missing()?;
|
||||
}
|
||||
ran?;
|
||||
report(installed_now(latest, &exe).await)
|
||||
}
|
||||
|
||||
/// What to tell a reader luxe will not run an update for: they asked only to check, or no owner's
|
||||
/// command is known.
|
||||
fn instructions(source: InstallSource, check_only: bool) -> String {
|
||||
match source.update_command() {
|
||||
Some(command) if !check_only && windows => format!(
|
||||
"Windows can't replace Luxe while it runs, so run this once it has exited: {command}"
|
||||
),
|
||||
Some(_) if check_only => format!("Run `luxe update`, or {}.", source.advice()),
|
||||
_ => format!("To update: {}.", source.advice()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs each step in turn, the terminal attached, stopping at the first that fails.
|
||||
async fn run_steps(steps: &[&[&str]]) -> anyhow::Result<()> {
|
||||
/// Runs each step in turn, the terminal attached, stopping at the first that fails. `beside` is
|
||||
/// the running binary's directory.
|
||||
async fn run_steps(steps: &[&[&str]], beside: Option<&Path>) -> anyhow::Result<()> {
|
||||
for step in steps {
|
||||
let Some((program, args)) = step.split_first() else { continue };
|
||||
let line = step.join(" ");
|
||||
println!("Running: {line}");
|
||||
let beside =
|
||||
std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf));
|
||||
let status = tokio::process::Command::new(program_path(program, beside.as_deref()))
|
||||
let status = tokio::process::Command::new(program_path(program, beside))
|
||||
.args(args)
|
||||
.status()
|
||||
.await
|
||||
.with_context(|| format!("could not start `{program}`"))?;
|
||||
if !status.success() {
|
||||
bail!("`{line}` failed ({status}), so Luxe is unchanged");
|
||||
bail!("`{line}` failed ({status}), so luxe is unchanged");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -108,15 +122,15 @@ fn outcome(found: Option<&Path>, updated: &Path, reported: Option<&str>, latest:
|
||||
}
|
||||
}
|
||||
|
||||
/// The `luxe` a shell would run now, and the outcome it shows.
|
||||
async fn installed_now(latest: &str) -> Outcome {
|
||||
/// The `luxe` a shell would run now, and the outcome it shows. `updated` is where the running copy
|
||||
/// was, read before a Windows update moved it aside.
|
||||
async fn installed_now(latest: &str, updated: &Path) -> Outcome {
|
||||
let found = luxe_core::program::resolve("luxe");
|
||||
let reported = match &found {
|
||||
Some(path) => version_of(path).await,
|
||||
None => None,
|
||||
};
|
||||
let updated = std::env::current_exe().unwrap_or_default();
|
||||
outcome(found.as_deref(), &updated, reported.as_deref(), latest)
|
||||
outcome(found.as_deref(), updated, reported.as_deref(), latest)
|
||||
}
|
||||
|
||||
/// The version `path --version` prints, as `luxe 0.2.0`.
|
||||
@@ -150,5 +164,7 @@ fn report(outcome: Outcome) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod aside;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
118
crates/luxe-cli/src/cli/update_command/aside.rs
Normal file
118
crates/luxe-cli/src/cli/update_command/aside.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
//! Moving the running copy aside — how `luxe update` gets out of its own way on Windows.
|
||||
//!
|
||||
//! Windows locks a running program's file against being overwritten or deleted, but not against
|
||||
//! being renamed. The running `luxe.exe` becomes `luxe.exe.old`, the owner's updater writes a new
|
||||
//! `luxe.exe`, and the next launch deletes the leftover once nothing is running from it. Nothing
|
||||
//! here writes a binary: it only renames the one that is already there.
|
||||
|
||||
use anyhow::Context;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The running copy, renamed out of the way of the update.
|
||||
pub(super) struct MovedAside {
|
||||
from: PathBuf,
|
||||
to: PathBuf,
|
||||
}
|
||||
|
||||
impl MovedAside {
|
||||
/// Renames `exe` to its leftover name, clearing a leftover a previous update left behind.
|
||||
pub(super) fn move_running(exe: &Path) -> anyhow::Result<Self> {
|
||||
let to = leftover_path(exe);
|
||||
remove_if_present(&to).with_context(|| {
|
||||
format!("could not remove {}, left by an earlier update", to.display())
|
||||
})?;
|
||||
std::fs::rename(exe, &to).with_context(|| {
|
||||
format!("could not move the running {} aside to update it", exe.display())
|
||||
})?;
|
||||
Ok(Self { from: exe.to_path_buf(), to })
|
||||
}
|
||||
|
||||
/// Puts the running copy back when the update left nothing where it was, so a failed update
|
||||
/// never leaves the reader without a `luxe`.
|
||||
pub(super) fn restore_if_missing(&self) -> anyhow::Result<()> {
|
||||
if self.from.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::rename(&self.to, &self.from).with_context(|| {
|
||||
format!(
|
||||
"the update left no luxe behind and {} could not be moved back to {}",
|
||||
self.to.display(),
|
||||
self.from.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes the copy an earlier update moved aside, if there is one. Called at launch, when the
|
||||
/// old copy has exited. Still running elsewhere is normal (another session), so a failure is
|
||||
/// only logged and the next launch tries again.
|
||||
pub(crate) fn remove_leftover() {
|
||||
let Ok(exe) = std::env::current_exe() else { return };
|
||||
let leftover = leftover_path(&exe);
|
||||
if let Err(error) = remove_if_present(&leftover) {
|
||||
tracing::debug!(%error, path = %leftover.display(), "leftover from an update is still in use");
|
||||
}
|
||||
}
|
||||
|
||||
/// `luxe.exe` beside itself as `luxe.exe.old`.
|
||||
fn leftover_path(exe: &Path) -> PathBuf {
|
||||
let mut name = exe.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(".old");
|
||||
exe.with_file_name(name)
|
||||
}
|
||||
|
||||
/// Removes `path`; already gone is success.
|
||||
fn remove_if_present(path: &Path) -> std::io::Result<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn installed() -> (tempfile::TempDir, PathBuf) {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let exe = dir.path().join("luxe.exe");
|
||||
std::fs::write(&exe, b"old").expect("a stand-in binary");
|
||||
(dir, exe)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_leftover_sits_beside_the_binary() {
|
||||
assert_eq!(leftover_path(Path::new("/bin/luxe.exe")), PathBuf::from("/bin/luxe.exe.old"));
|
||||
}
|
||||
|
||||
/// The update writes a new file where the old one was, and the old one is left to delete.
|
||||
#[test]
|
||||
fn an_update_that_wrote_a_new_copy_keeps_it() {
|
||||
let (_dir, exe) = installed();
|
||||
let aside = MovedAside::move_running(&exe).expect("moved");
|
||||
assert!(!exe.exists(), "the name is free for the updater");
|
||||
std::fs::write(&exe, b"new").expect("the updater's copy");
|
||||
aside.restore_if_missing().expect("nothing to restore");
|
||||
assert_eq!(std::fs::read(&exe).expect("read"), b"new");
|
||||
assert_eq!(std::fs::read(leftover_path(&exe)).expect("read"), b"old");
|
||||
}
|
||||
|
||||
/// A failed update puts the running copy back rather than leaving no `luxe` at all.
|
||||
#[test]
|
||||
fn an_update_that_wrote_nothing_puts_the_old_copy_back() {
|
||||
let (_dir, exe) = installed();
|
||||
let aside = MovedAside::move_running(&exe).expect("moved");
|
||||
aside.restore_if_missing().expect("restored");
|
||||
assert_eq!(std::fs::read(&exe).expect("read"), b"old");
|
||||
assert!(!leftover_path(&exe).exists());
|
||||
}
|
||||
|
||||
/// A leftover from the last update is cleared, not a reason to refuse this one.
|
||||
#[test]
|
||||
fn a_leftover_from_last_time_is_replaced() {
|
||||
let (_dir, exe) = installed();
|
||||
std::fs::write(leftover_path(&exe), b"older").expect("a leftover");
|
||||
MovedAside::move_running(&exe).expect("moved");
|
||||
assert_eq!(std::fs::read(leftover_path(&exe)).expect("read"), b"old");
|
||||
}
|
||||
}
|
||||
@@ -69,13 +69,8 @@ fn no_luxe_on_path_or_no_version_cannot_be_judged() {
|
||||
/// Only the reader's own command is ever named, and a check offers `luxe update` beside it.
|
||||
#[test]
|
||||
fn the_instructions_name_the_owners_command_or_none() {
|
||||
let check = instructions(InstallSource::Cargo, true, false);
|
||||
let check = instructions(InstallSource::Cargo, true);
|
||||
assert!(check.contains("luxe update") && check.contains("cargo install"), "{check}");
|
||||
let download = instructions(InstallSource::Archive, false, false);
|
||||
let download = instructions(InstallSource::Archive, false);
|
||||
assert!(download.contains("download it from"), "{download}");
|
||||
let windows = instructions(InstallSource::Cargo, false, true);
|
||||
assert!(
|
||||
windows.contains("once it has exited") && windows.contains("cargo install"),
|
||||
"{windows}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ const SECRET_PREFIXES: &[&str] = &["sk-", "sk_live_", "ghp_", "gho_", "xoxb-", "
|
||||
|
||||
/// Minimum run of key-shaped characters after a prefix before it counts as a credential.
|
||||
///
|
||||
/// Without this, reading Luxe's own `redact.rs` — whose source *contains* every prefix — reports a
|
||||
/// Without this, reading luxe's own `redact.rs` — whose source *contains* every prefix — reports a
|
||||
/// leak on every audit. The prefix alone is prose; the prefix plus a key is a secret.
|
||||
const SECRET_BODY: usize = 16;
|
||||
|
||||
|
||||
@@ -184,7 +184,7 @@ fn a_bold_label_outside_the_tools_section_is_not_a_duplicate() {
|
||||
|
||||
#[test]
|
||||
fn a_credential_prefix_in_prose_is_not_a_leak_but_a_real_key_is() {
|
||||
// Reading Luxe's own redact.rs puts every prefix in a tool result; that is not a leak.
|
||||
// Reading luxe's own redact.rs puts every prefix in a tool result; that is not a leak.
|
||||
assert!(looks_like_credential("patterns like sk- and ghp_ and AKIA").is_none());
|
||||
assert!(looks_like_credential("Authorization: Bearer short").is_none());
|
||||
let leak = looks_like_credential("key=sk-abcdefghijklmnopqrstuvwxyz0123")
|
||||
|
||||
@@ -248,7 +248,7 @@ pub(super) fn worktree_notice(
|
||||
)
|
||||
}
|
||||
|
||||
/// Leaves the session's worktree and removes it, saying how it went on the terminal Luxe has
|
||||
/// Leaves the session's worktree and removes it, saying how it went on the terminal luxe has
|
||||
/// just handed back.
|
||||
pub(super) async fn remove_worktree(project: &std::path::Path, path: &std::path::Path) {
|
||||
if let Err(error) = std::env::set_current_dir(project) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Config editor handoff — opens one of Luxe's files outside the alternate screen.
|
||||
//! Config editor handoff — opens one of luxe's files outside the alternate screen.
|
||||
//!
|
||||
//! The TUI returns control before this runs, so terminal editors inherit a normal terminal.
|
||||
//! When the editor exits, the CLI rebuilds the TUI and reloads the updated configuration.
|
||||
@@ -47,7 +47,7 @@ pub(crate) async fn open_config_file(path: PathBuf) -> anyhow::Result<PathBuf> {
|
||||
/// credential file created world-readable is a credential file leaked.
|
||||
fn ensure_file(path: PathBuf) -> anyhow::Result<PathBuf> {
|
||||
if path == Config::global_path() {
|
||||
return Config::ensure_global_file().context("creating Luxe user config");
|
||||
return Config::ensure_global_file().context("creating luxe user config");
|
||||
}
|
||||
if path.exists() {
|
||||
return Ok(path);
|
||||
|
||||
@@ -135,7 +135,7 @@ pub(crate) async fn build_engine(
|
||||
|
||||
let model = settings.launch_model();
|
||||
|
||||
// Provider routing: the adapter the settings selected, plus a registry of every provider Luxe
|
||||
// Provider routing: the adapter the settings selected, plus a registry of every provider luxe
|
||||
// knows about, so an in-session model switch *or* a mid-session `/login` reaches the right one.
|
||||
let provider = build_active_adapter(settings);
|
||||
let providers = build_provider_registry(settings, &provider);
|
||||
@@ -183,8 +183,9 @@ pub(crate) async fn build_engine(
|
||||
external_work: Some(services::shared_external_work()),
|
||||
review_context_files: config.review.context_files.clone(),
|
||||
review_exclude: config.review.exclude.clone(),
|
||||
// A real session remembers what the user picked; embedders and tests leave no trace.
|
||||
remember_runtime_state: config.agent.remember_model(),
|
||||
// A real session remembers what the user picked, here and anywhere; embedders and tests
|
||||
// leave no trace.
|
||||
remember_choices_in: config.agent.remember_model().then(|| settings.work_root.clone()),
|
||||
cache_warming: config.agent.cache_warming(),
|
||||
// Ground Guided Review in real structure (relevant files + test gaps) from the warm graph.
|
||||
review_insight_provider: Some(Arc::new(crate::review_insight::GraphReviewInsight::new(
|
||||
@@ -322,8 +323,8 @@ fn assemble_hooks(
|
||||
(hook_registry, session_end_budget)
|
||||
}
|
||||
|
||||
/// The hook that reports the agent's state to the Herdr pane Luxe runs in, so its sidebar tracks
|
||||
/// Luxe. `None` outside Herdr, under `LUXE_HERDR=0`, or with `"herdr": false`.
|
||||
/// The hook that reports the agent's state to the Herdr pane luxe runs in, so its sidebar tracks
|
||||
/// luxe. `None` outside Herdr, under `LUXE_HERDR=0`, or with `"herdr": false`.
|
||||
fn herdr_hook(config: &luxe_core::config::Config) -> Option<luxe_core::hooks::herdr::HerdrHook> {
|
||||
config.herdr().then(luxe_core::hooks::herdr::HerdrHook::detect).flatten()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Configuration loading — auth/models, permissions, command hooks, and env resolution.
|
||||
//!
|
||||
//! Every reader treats its file as read-if-present: a missing or malformed config degrades to
|
||||
//! defaults rather than failing, so Luxe runs the same with or without user config.
|
||||
//! defaults rather than failing, so luxe runs the same with or without user config.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -65,7 +65,7 @@ pub(crate) fn load_luxe_config() -> ModelsConfig {
|
||||
|
||||
/// Warn if a secrets file is readable by group or other.
|
||||
///
|
||||
/// Luxe writes its own secret files `0600` (MCP token store, review stores), but `auth.json`/
|
||||
/// luxe writes its own secret files `0600` (MCP token store, review stores), but `auth.json`/
|
||||
/// `models.json` are user-authored, so we can only nudge: ssh and aws-cli take the same stance
|
||||
/// (warn/refuse on loose credential permissions). Unix-only; a no-op elsewhere.
|
||||
#[cfg(unix)]
|
||||
@@ -230,7 +230,7 @@ pub(crate) fn global_permissions_path() -> PathBuf {
|
||||
luxe_config_dir().join("permissions.json")
|
||||
}
|
||||
|
||||
/// Luxe's own config directory. See [`luxe_core::user_dirs::luxe_config_dir`], the one owner.
|
||||
/// luxe's own config directory. See [`luxe_core::user_dirs::luxe_config_dir`], the one owner.
|
||||
pub(crate) fn luxe_config_dir() -> PathBuf {
|
||||
luxe_core::user_dirs::luxe_config_dir()
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Provider adapter construction — the active adapter plus a registry of every provider Luxe can
|
||||
//! Provider adapter construction — the active adapter plus a registry of every provider luxe can
|
||||
//! route to, so an in-session model switch or a mid-session `/login` reaches the right backend.
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -88,7 +88,7 @@ pub(super) fn active_auth(
|
||||
/// the provider's own variable, then the key its block names.
|
||||
///
|
||||
/// One chain for the provider a session starts on and every one it can switch to, so the key that
|
||||
/// goes out never depends on how the session got there. A provider Luxe does not know has no
|
||||
/// goes out never depends on how the session got there. A provider luxe does not know has no
|
||||
/// variable of its own, only the `OPENAI_API_KEY` fallback, so its configured key comes first: an
|
||||
/// OpenAI key must not go to someone else's endpoint in place of the key written for it. Keys stay
|
||||
/// as written; the source expands them per request.
|
||||
@@ -108,7 +108,7 @@ fn provider_auth(store: AuthStore, name: &str, config: Option<&ProviderConfig>)
|
||||
|
||||
/// Assemble the provider registry the engine routes through on an in-session model switch.
|
||||
///
|
||||
/// Every provider Luxe knows about is registered: the built-in catalog plus anything declared in
|
||||
/// Every provider luxe knows about is registered: the built-in catalog plus anything declared in
|
||||
/// `~/.config/luxe/{auth,models}.json`. That is what makes `/login` take effect mid-session — the
|
||||
/// adapter is already there, and its store-backed auth source finds the new credential on the next
|
||||
/// turn. A provider with no credential registers too, and answers with an actionable auth error
|
||||
@@ -154,7 +154,7 @@ pub(crate) fn build_provider_registry(
|
||||
|
||||
/// A `--model` that names its provider, `anthropic/claude-opus-5-5`, split into the two.
|
||||
///
|
||||
/// Only when the prefix is a provider Luxe knows, built in or configured, and no other provider
|
||||
/// Only when the prefix is a provider luxe knows, built in or configured, and no other provider
|
||||
/// was named: under `--provider openrouter`, `anthropic/claude-x` is OpenRouter's own id, slash and
|
||||
/// all. Without the split the whole string went to the default provider as an id, which is the
|
||||
/// form the "no model selected" error tells you to type.
|
||||
|
||||
@@ -7,7 +7,7 @@ fn the_catalog_decides_which_adapter_a_known_provider_uses() {
|
||||
assert_eq!(resolve_api("openai", None), ApiKind::OpenaiResponses);
|
||||
assert_eq!(resolve_api("openai-codex", None), ApiKind::OpenaiCodex);
|
||||
assert_eq!(resolve_api("groq", None), ApiKind::OpenaiCompletions);
|
||||
// Luxe's historical default provider name is an alias of `openai`.
|
||||
// luxe's historical default provider name is an alias of `openai`.
|
||||
assert_eq!(resolve_api("openai_compat", None), ApiKind::OpenaiResponses);
|
||||
// An unknown provider is assumed to speak the most common dialect.
|
||||
assert_eq!(resolve_api("some-proxy", None), ApiKind::OpenaiCompletions);
|
||||
@@ -266,7 +266,7 @@ async fn the_launch_providers_command_key_runs_for_each_request() {
|
||||
}
|
||||
|
||||
/// Launch and a `/model` switch find a provider's key by one chain: a sign-in first, then the
|
||||
/// provider's own variable, then the key its block names, and for a provider Luxe does not know,
|
||||
/// provider's own variable, then the key its block names, and for a provider luxe does not know,
|
||||
/// its block before `OPENAI_API_KEY`. So a configured key always beats a key meant for another
|
||||
/// provider, and which one goes out never depends on how the session reached the provider.
|
||||
#[test]
|
||||
@@ -329,7 +329,7 @@ fn launch_and_a_model_switch_send_the_same_key() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Which key each kind of provider settles on with nothing stored: a provider Luxe does not know
|
||||
/// Which key each kind of provider settles on with nothing stored: a provider luxe does not know
|
||||
/// takes the key written for it before the `OPENAI_API_KEY` fallback, and one it knows takes its
|
||||
/// own variable first.
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Warm, process-wide service singletons — the LSP client, code graph, DAP debugger, and
|
||||
//! diagnostics cache — plus the per-project session store.
|
||||
//!
|
||||
//! Luxe runs one project per process, so each service is a `OnceLock` singleton reused across
|
||||
//! luxe runs one project per process, so each service is a `OnceLock` singleton reused across
|
||||
//! every tool call and hook instead of being spawned per request.
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -56,7 +56,7 @@ pub(crate) fn tool_statuses() -> Vec<luxe_core::ToolStatus> {
|
||||
/// Three inputs, and the judgement is here rather than in `luxe-lsp` so it can be read and tested
|
||||
/// in one place: the user's preference, whether a front-end can prompt, and `--trust-project`.
|
||||
///
|
||||
/// `interactive` carries the whole argument for the default. Luxe is a coding agent someone sits
|
||||
/// `interactive` carries the whole argument for the default. luxe is a coding agent someone sits
|
||||
/// in front of; the loop is a feature, not the usual way it runs. With a person there, using the
|
||||
/// server the project pinned is ordinary work — and `node_modules/.bin` exists only because
|
||||
/// `npm install` already ran that project's install scripts, which is arbitrary code and a wider
|
||||
@@ -96,7 +96,7 @@ pub(crate) fn project_tooling_allowed() -> bool {
|
||||
|
||||
/// The process-wide warm LSP service. A singleton (like [`shared_diagnostics_store`]) so the tools,
|
||||
/// the diagnostics-on-edit hook, and the workspace collector (which reads running-server state for
|
||||
/// `/lsp`) all share one instance. Luxe runs one project per process; the collector scopes
|
||||
/// `/lsp`) all share one instance. luxe runs one project per process; the collector scopes
|
||||
/// running servers to the active root.
|
||||
pub(crate) fn build_lsp_service() -> SharedLspService {
|
||||
static SERVICE: std::sync::OnceLock<SharedLspService> = std::sync::OnceLock::new();
|
||||
@@ -112,7 +112,7 @@ pub(crate) fn build_lsp_service() -> SharedLspService {
|
||||
|
||||
/// The process-wide warm code graph service, shared by the `impact` / `module_report` tools and the
|
||||
/// graph-invalidation hook. Singleton like the LSP/DAP services; rooted at the workspace on first
|
||||
/// use (Luxe runs one project per process).
|
||||
/// use (luxe runs one project per process).
|
||||
pub(crate) fn build_graph_service(
|
||||
repo_root: &std::path::Path,
|
||||
) -> Arc<luxe_lsp::graph::GraphService> {
|
||||
@@ -223,7 +223,7 @@ fn read_config_text(path: &std::path::Path) -> Result<Option<String>, String> {
|
||||
///
|
||||
/// A shared handle at the binary boundary: it lets the (core) hook publish per-file diagnostics
|
||||
/// that the (core-agnostic) collector reads for the Context Dock without threading a channel
|
||||
/// through every front-end. Luxe runs one project per process; the collector filters entries to the
|
||||
/// through every front-end. luxe runs one project per process; the collector filters entries to the
|
||||
/// active root, so a project switch never leaks another tree's diagnostics.
|
||||
pub(crate) fn shared_diagnostics_store() -> luxe_core::lsp::DiagnosticsStore {
|
||||
static STORE: std::sync::OnceLock<luxe_core::lsp::DiagnosticsStore> =
|
||||
|
||||
@@ -169,7 +169,7 @@ pub(super) fn attach_session(
|
||||
Ok((session_id, claim))
|
||||
}
|
||||
|
||||
/// Claim `session_id` for this process, or say which Luxe has it open and how to get there.
|
||||
/// 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,
|
||||
@@ -181,7 +181,7 @@ fn claim_session(
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `session` can't be opened here right now, when another Luxe has it open.
|
||||
/// 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.
|
||||
@@ -195,7 +195,7 @@ pub(crate) fn open_elsewhere_now(state_root: &std::path::Path, session: &str) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the session is open, when the Luxe that has it says so, and what to do about it.
|
||||
/// 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)
|
||||
@@ -207,7 +207,7 @@ fn open_elsewhere(id: &SessionId) -> String {
|
||||
};
|
||||
// `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 \
|
||||
"session {id} is already open in another luxe{place}. Carry on there, or close it \
|
||||
there first"
|
||||
)
|
||||
}
|
||||
@@ -299,7 +299,7 @@ mod tests {
|
||||
};
|
||||
|
||||
let refused = attach_session(&settings, &mut store).expect_err("held elsewhere");
|
||||
let expected = format!("session {id} is already open in another Luxe");
|
||||
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);
|
||||
|
||||
@@ -153,16 +153,17 @@ impl AgentSettings {
|
||||
/// Resolve settings, letting `cli` overrides win over env and config.
|
||||
pub(crate) fn resolve(repo_root: PathBuf, cli: CliOverrides) -> Self {
|
||||
let config = load_luxe_config();
|
||||
// What the last session picked, unless the user asked us not to remember. It sits *below*
|
||||
// the CLI and the environment (a one-off `--model` must stay a one-off) and *above* the
|
||||
// configured default, which is the point: the default is where you start, not where you are
|
||||
// pinned.
|
||||
// What the last session picked in this project, or anywhere when this project has no pick
|
||||
// of its own, unless the user asked us not to remember. It sits *below* the CLI and the
|
||||
// environment (a one-off `--model` must stay a one-off) and *above* the configured
|
||||
// default, which is the point: the default is where you start, not where you are pinned.
|
||||
let ui_config = luxe_core::config::Config::load(&repo_root);
|
||||
let remembered = ui_config
|
||||
.agent
|
||||
.remember_model()
|
||||
.then(luxe_core::runtime_state::RuntimeState::load)
|
||||
.unwrap_or_default();
|
||||
let last_chosen = remembered.model_for(&repo_root);
|
||||
|
||||
let named_provider = cli.provider.or_else(|| env_nonempty("LUXE_PROVIDER"));
|
||||
let from_flag_or_env = cli.model.clone().or_else(|| env_nonempty("LUXE_MODEL"));
|
||||
@@ -175,17 +176,14 @@ impl AgentSettings {
|
||||
};
|
||||
let provider = named_provider
|
||||
.or(provider_in_model)
|
||||
.or_else(|| remembered.model.as_ref().map(|model| model.provider.clone()))
|
||||
.or_else(|| last_chosen.map(|model| model.provider.clone()))
|
||||
.or_else(|| config.default_provider.clone())
|
||||
.unwrap_or_else(|| "openai_compat".to_string());
|
||||
|
||||
// A remembered model only applies to the provider it was chosen for: pairing last session's
|
||||
// Anthropic model id with a locally forced provider would resolve to nothing.
|
||||
let remembered_model = remembered
|
||||
.model
|
||||
.as_ref()
|
||||
.filter(|model| model.provider == provider)
|
||||
.map(|model| model.id.clone());
|
||||
let remembered_model =
|
||||
last_chosen.filter(|model| model.provider == provider).map(|model| model.id.clone());
|
||||
// A configured `default_model` belongs to the provider it was configured alongside. Pairing
|
||||
// it with a provider forced on the command line produces combinations that don't exist —
|
||||
// `claude-sonnet-5` on Codex — so it only applies when that provider can actually serve it.
|
||||
|
||||
@@ -131,7 +131,7 @@ fn tool_registry_has_builtins_and_lsp() {
|
||||
/// The loop is opt-in, so nothing it owns may reach an ordinary session.
|
||||
///
|
||||
/// `loop_control` was registered unconditionally, and since it is not a core tool it landed in
|
||||
/// the "available on demand" catalog of every prompt Luxe sent — offering a plain chat session a
|
||||
/// the "available on demand" catalog of every prompt luxe sent — offering a plain chat session a
|
||||
/// tool for advancing phases of an autonomous run that was not happening.
|
||||
#[test]
|
||||
fn loop_control_is_absent_unless_a_loop_is_driving() {
|
||||
@@ -189,6 +189,7 @@ fn a_remembered_model_beats_the_configured_default_but_not_a_flag() {
|
||||
provider: "anthropic".into(),
|
||||
id: "claude-opus-5".into(),
|
||||
}),
|
||||
project_models: Vec::new(),
|
||||
thinking: Some(luxe_core::provider::ThinkingLevel::High),
|
||||
recent_commands: Vec::new(),
|
||||
panes: Default::default(),
|
||||
@@ -213,6 +214,40 @@ fn a_remembered_model_beats_the_configured_default_but_not_a_flag() {
|
||||
assert_eq!(overridden.chosen().r#ref.id, "claude-sonnet-5");
|
||||
}
|
||||
|
||||
/// The model last chosen in this project outranks the one last chosen anywhere, and a project with
|
||||
/// no pick of its own starts on the latter.
|
||||
#[test]
|
||||
fn a_projects_own_pick_beats_the_last_one_anywhere() {
|
||||
use luxe_core::runtime_state::{ProjectModel, RememberedModel, RuntimeState};
|
||||
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
|
||||
let home = tempfile::tempdir().expect("temp home");
|
||||
let state = home.path().join("state");
|
||||
std::fs::create_dir_all(&state).expect("state dir");
|
||||
let here = tempfile::tempdir().expect("temp project");
|
||||
let model =
|
||||
|provider: &str, id: &str| RememberedModel { provider: provider.into(), id: id.into() };
|
||||
RuntimeState {
|
||||
model: Some(model("anthropic", "claude-opus-5")),
|
||||
project_models: vec![ProjectModel {
|
||||
project: luxe_core::paths::display(here.path()),
|
||||
model: model("openai", "gpt-5.6"),
|
||||
}],
|
||||
..RuntimeState::default()
|
||||
}
|
||||
.save_to(&state.join("state.json"))
|
||||
.expect("write state");
|
||||
let _state_dir = EnvGuard::set("LUXE_STATE_DIR", state.to_str().expect("utf-8 path"));
|
||||
|
||||
let in_project = AgentSettings::resolve(here.path().to_path_buf(), CliOverrides::default());
|
||||
assert_eq!(
|
||||
(in_project.provider.as_str(), in_project.chosen().r#ref.id.as_str()),
|
||||
("openai", "gpt-5.6")
|
||||
);
|
||||
let elsewhere = tempfile::tempdir().expect("another project");
|
||||
let fresh = AgentSettings::resolve(elsewhere.path().to_path_buf(), CliOverrides::default());
|
||||
assert_eq!(fresh.chosen().r#ref.id, "claude-opus-5", "no pick here, so the last anywhere");
|
||||
}
|
||||
|
||||
/// A remembered model must not be pasted onto a different provider.
|
||||
#[test]
|
||||
fn a_remembered_model_is_ignored_when_the_provider_is_forced_elsewhere() {
|
||||
@@ -226,6 +261,7 @@ fn a_remembered_model_is_ignored_when_the_provider_is_forced_elsewhere() {
|
||||
provider: "anthropic".into(),
|
||||
id: "claude-opus-5".into(),
|
||||
}),
|
||||
project_models: Vec::new(),
|
||||
thinking: None,
|
||||
recent_commands: Vec::new(),
|
||||
panes: Default::default(),
|
||||
@@ -359,7 +395,7 @@ impl Drop for EnvGuard {
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing configured means nothing chosen. Luxe used to reach for whichever id the provider
|
||||
/// Nothing configured means nothing chosen. luxe used to reach for whichever id the provider
|
||||
/// catalog named first, which is a literal in the binary: it goes stale as models turn over,
|
||||
/// and the first thing a fresh install did with it was send it.
|
||||
#[test]
|
||||
@@ -541,6 +577,7 @@ fn a_models_own_thinking_level_outranks_the_remembered_one() {
|
||||
luxe_core::runtime_state::RuntimeState {
|
||||
schema_version: luxe_core::runtime_state::RUNTIME_STATE_SCHEMA_VERSION,
|
||||
model: None,
|
||||
project_models: Vec::new(),
|
||||
thinking: Some(ThinkingLevel::XHigh),
|
||||
recent_commands: Vec::new(),
|
||||
panes: Default::default(),
|
||||
|
||||
@@ -54,7 +54,7 @@ pub(crate) struct ToolDenyReport {
|
||||
removed: Vec<DeniedTool>,
|
||||
/// Essential, so the request was refused
|
||||
refused: Vec<DeniedTool>,
|
||||
/// A tool Luxe knows, not registered on this machine
|
||||
/// A tool luxe knows, not registered on this machine
|
||||
unavailable: Vec<DeniedTool>,
|
||||
/// No tool of that name anywhere, with the nearest one when there is a near miss
|
||||
unknown: Vec<(DeniedTool, Option<&'static str>)>,
|
||||
@@ -162,7 +162,7 @@ pub(crate) fn apply_tool_deny_list(
|
||||
report
|
||||
}
|
||||
|
||||
/// Every tool Luxe can register, whatever this machine happens to have installed.
|
||||
/// Every tool luxe can register, whatever this machine happens to have installed.
|
||||
///
|
||||
/// The set that makes "no such tool" tellable from "not here": four tools register only where
|
||||
/// their program exists (`debug`, `screenshot`, `ast_grep`) or where something is configured
|
||||
@@ -344,7 +344,7 @@ pub(crate) async fn register_mcp_tools(registry: &mut ToolRegistry, repo_root: &
|
||||
/// The MCP servers this run may start, and the ids of any the project declared that it may not.
|
||||
///
|
||||
/// A stdio server in `.mcp.json` is a command the repository chose, and an `eager` one must not
|
||||
/// start the moment Luxe opens a cloned tree, headless included. It answers to the gate project
|
||||
/// start the moment luxe opens a cloned tree, headless included. It answers to the gate project
|
||||
/// language servers and formatters already use, not a second one.
|
||||
pub(crate) fn mcp_servers_for_run(
|
||||
repo_root: &std::path::Path,
|
||||
|
||||
@@ -108,7 +108,7 @@ fn the_deny_list_classifies_what_a_real_run_asks_for() {
|
||||
assert_eq!(
|
||||
report.unavailable.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(),
|
||||
["mcp"],
|
||||
"a tool Luxe knows that this run never registered is not a typo"
|
||||
"a tool luxe knows that this run never registered is not a typo"
|
||||
);
|
||||
assert_eq!(report.unknown.len(), 1);
|
||||
assert_eq!(report.unknown[0].0.name, "websearch");
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,9 @@
|
||||
//! Guide check — the user guide's config examples, flags and slash commands, held against the code.
|
||||
//!
|
||||
//! `docs/guide/` is what a user copies from and what an agent follows. Luxe ignores a config key it
|
||||
//! does not know, on purpose, so an old config loads on a new Luxe; the cost is that a misspelled
|
||||
//! `docs/guide/` is what a user copies from and what an agent follows. luxe ignores a config key it
|
||||
//! does not know, on purpose, so an old config loads on a new luxe; the cost is that a misspelled
|
||||
//! or invented key in the docs loads too, and does nothing. These tests load every example the
|
||||
//! guide names a file for as that file, and fail on anything Luxe would ignore.
|
||||
//! guide names a file for as that file, and fail on anything luxe would ignore.
|
||||
//!
|
||||
//! A code block opts in by naming its file in the fence, ` ```json title="config.json" `, which is
|
||||
//! also what the site shows above the block. `scripts/docs-check.py` covers links and voice.
|
||||
@@ -76,7 +76,7 @@ fn blocks(page: &str, text: &str) -> Vec<Block> {
|
||||
blocks
|
||||
}
|
||||
|
||||
/// The keys Luxe would ignore reading `text` as `T`, as paths like `dock.mode`.
|
||||
/// The keys luxe would ignore reading `text` as `T`, as paths like `dock.mode`.
|
||||
fn ignored<T: DeserializeOwned>(text: &str) -> Result<Vec<String>, String> {
|
||||
let value: serde_json::Value = serde_json::from_str(text).map_err(|error| error.to_string())?;
|
||||
let mut paths = Vec::new();
|
||||
@@ -85,7 +85,7 @@ fn ignored<T: DeserializeOwned>(text: &str) -> Result<Vec<String>, String> {
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
/// The keys Luxe would ignore in an `auth.json`: every top-level key is a provider's credential,
|
||||
/// The keys luxe would ignore in an `auth.json`: every top-level key is a provider's credential,
|
||||
/// except the configuration keys it shares with `models.json`.
|
||||
fn auth_file(text: &str) -> Result<Vec<String>, String> {
|
||||
const CONFIGURATION: &[&str] =
|
||||
@@ -153,7 +153,7 @@ fn check_file(title: &str, text: &str) -> Result<(), String> {
|
||||
if unknown.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Luxe would ignore {}", unknown.join(", ")))
|
||||
Err(format!("luxe would ignore {}", unknown.join(", ")))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,7 +174,7 @@ fn every_named_config_example_loads() {
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"config examples Luxe would not read as written:\n{}",
|
||||
"config examples luxe would not read as written:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
@@ -235,7 +235,7 @@ fn shell_words(line: &str) -> Vec<String> {
|
||||
words
|
||||
}
|
||||
|
||||
/// What is wrong with a `luxe …` command line, if anything: a flag or subcommand Luxe lacks.
|
||||
/// What is wrong with a `luxe …` command line, if anything: a flag or subcommand luxe lacks.
|
||||
fn check_command_line(root: &clap::Command, line: &str) -> Result<(), String> {
|
||||
let mut path: Vec<&clap::Command> = vec![root];
|
||||
let words = shell_words(line);
|
||||
@@ -286,14 +286,14 @@ fn every_command_line_in_the_guide_exists() {
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "command lines Luxe would refuse:\n{}", failures.join("\n"));
|
||||
assert!(failures.is_empty(), "command lines luxe would refuse:\n{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Paths that look like a slash command in a code span.
|
||||
const NOT_COMMANDS: &[&str] =
|
||||
&["/tmp", "/etc", "/usr", "/dev", "/home", "/var", "/opt", "/bin", "/proc"];
|
||||
|
||||
/// Every slash command the guide names is one Luxe has.
|
||||
/// Every slash command the guide names is one luxe has.
|
||||
#[test]
|
||||
fn every_slash_command_in_the_guide_exists() {
|
||||
let registry = luxe_tui::commands::CommandRegistry::all();
|
||||
@@ -329,10 +329,10 @@ fn every_slash_command_in_the_guide_exists() {
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "slash commands Luxe does not have:\n{}", failures.join("\n"));
|
||||
assert!(failures.is_empty(), "slash commands luxe does not have:\n{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// The command reference lists every slash command Luxe has, and every key it binds by default, so a
|
||||
/// The command reference lists every slash command luxe has, and every key it binds by default, so a
|
||||
/// new command or binding cannot ship undocumented.
|
||||
#[test]
|
||||
fn the_command_reference_is_complete() {
|
||||
@@ -350,7 +350,7 @@ fn the_command_reference_is_complete() {
|
||||
assert!(missing.is_empty(), "commands.md does not mention:\n{}", missing.join("\n"));
|
||||
}
|
||||
|
||||
/// The configuration reference names every key `config.json` takes, from the schema Luxe writes
|
||||
/// The configuration reference names every key `config.json` takes, from the schema luxe writes
|
||||
/// beside it, so a new setting cannot ship undocumented.
|
||||
#[test]
|
||||
fn the_configuration_reference_is_complete() {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//! ranks a directory holding one above a nearer checkout, so a stray left in `/tmp` re-roots every
|
||||
//! repository beneath it.
|
||||
//!
|
||||
//! Level is controlled by `LUXE_LOG` (or `RUST_LOG`). The default is `info` for Luxe's own crates
|
||||
//! Level is controlled by `LUXE_LOG` (or `RUST_LOG`). The default is `info` for luxe's own crates
|
||||
//! and `warn` for everything else — a normal run leaves a readable account of what the agent did,
|
||||
//! without `hyper` and `rustls` narrating every socket. Init is best-effort: logging must never
|
||||
//! crash or block the app.
|
||||
@@ -54,7 +54,7 @@ impl<'a> MakeWriter<'a> for RedactingFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// Luxe's own crates, which is what the default filter turns up.
|
||||
/// luxe's own crates, which is what the default filter turns up.
|
||||
///
|
||||
/// Spelled out rather than matched by prefix because `EnvFilter` has no glob for a target prefix, and
|
||||
/// a filter that quietly matched nothing would look exactly like a quiet run.
|
||||
@@ -69,7 +69,7 @@ const LUXE_TARGETS: [&str; 8] = [
|
||||
"luxe_tools",
|
||||
];
|
||||
|
||||
/// The default filter: Luxe at `info`, everything else at `warn`.
|
||||
/// The default filter: luxe at `info`, everything else at `warn`.
|
||||
///
|
||||
/// Two things have to be true at once. A normal run should leave an account someone can read — which
|
||||
/// `warn` did not, and which is why routine loop behavior had drifted up to `warn!` just to be
|
||||
@@ -167,22 +167,22 @@ fn open_log(dir: &Path, rotate_at: u64) -> io::Result<(File, Option<io::Error>)>
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
let file = options.open(&path)?;
|
||||
// a log an older Luxe created at the umask's default is tightened too
|
||||
// a log an older luxe created at the umask's default is tightened too
|
||||
#[cfg(unix)]
|
||||
file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
|
||||
Ok((file, rotated))
|
||||
}
|
||||
|
||||
/// Drop a self-ignoring `.gitignore` into `.luxe/`, and upgrade one Luxe wrote itself.
|
||||
/// Drop a self-ignoring `.gitignore` into `.luxe/`, and upgrade one luxe wrote itself.
|
||||
///
|
||||
/// The directory ignores itself (the trick pytest/ruff/venv use), so running Luxe inside any repo
|
||||
/// The directory ignores itself (the trick pytest/ruff/venv use), so running luxe inside any repo
|
||||
/// needs no root-`.gitignore` edit or global git config. The rule is an *allowlist*: everything is
|
||||
/// machine-local by default (`*` — sessions, logs, caches, review memory, per-user UI prefs), with
|
||||
/// explicit exceptions for the handful of project-config files a team may want to version
|
||||
/// (`permissions.json`, `mcp.json`, `hooks.json`, `skills/`). Ignoring by default is the safe
|
||||
/// direction: a new artifact kind Luxe writes later stays out of git until someone opts it in.
|
||||
/// direction: a new artifact kind luxe writes later stays out of git until someone opts it in.
|
||||
///
|
||||
/// A file Luxe did not author is never touched, so a user's own curation survives.
|
||||
/// A file luxe did not author is never touched, so a user's own curation survives.
|
||||
fn ensure_self_ignored(luxe_dir: &Path) {
|
||||
let ignore = luxe_dir.join(".gitignore");
|
||||
match std::fs::read_to_string(&ignore) {
|
||||
@@ -219,7 +219,7 @@ const SELF_IGNORE_BODY: &str = "\
|
||||
# and luxe keeps it out of its own reviews and changes lists for the same reason.
|
||||
*
|
||||
|
||||
# Exceptions: project config you may want to version and share. Luxe rewrites
|
||||
# Exceptions: project config you may want to version and share. luxe rewrites
|
||||
# this file while its first line says it made it; to choose for yourself, replace
|
||||
# the file, first line included, with your own.
|
||||
!permissions.json
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
/// Luxe's own crates are visible at `info`, and dependencies are not.
|
||||
/// luxe's own crates are visible at `info`, and dependencies are not.
|
||||
///
|
||||
/// The break this catches is the one that shipped: with a bare `warn` default, nothing Luxe
|
||||
/// The break this catches is the one that shipped: with a bare `warn` default, nothing luxe
|
||||
/// logged at `info` was ever seen, so routine loop behavior drifted up to `warn!` just to be
|
||||
/// visible — an ordinary steer arrived labeled as a warning. Widening it to `info` for
|
||||
/// everything instead would swap that for a firehose, because `hyper` and `rustls` narrate every
|
||||
@@ -46,7 +46,7 @@ fn the_default_filter_shows_luxe_at_info_and_nothing_else() {
|
||||
let seen = seen.lock().expect("not poisoned").clone();
|
||||
assert!(
|
||||
seen.contains(&"luxe_core@INFO".to_string()),
|
||||
"Luxe's own routine logging must be visible: {seen:?}"
|
||||
"luxe's own routine logging must be visible: {seen:?}"
|
||||
);
|
||||
assert!(!seen.contains(&"luxe_core@DEBUG".to_string()), "debug stays opt-in: {seen:?}");
|
||||
assert!(
|
||||
@@ -153,7 +153,7 @@ fn self_ignore_hides_the_whole_directory_and_never_clobbers() {
|
||||
}
|
||||
|
||||
/// A log holds what the agent read and ran, so a new one is readable by its owner only, and one an
|
||||
/// older Luxe left at the umask's default is tightened when it is next opened.
|
||||
/// older luxe left at the umask's default is tightened when it is next opened.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_log_file_is_owner_only() {
|
||||
|
||||
@@ -179,7 +179,7 @@ mod tests {
|
||||
external_work: None,
|
||||
review_context_files: Vec::new(),
|
||||
review_exclude: Vec::new(),
|
||||
remember_runtime_state: false,
|
||||
remember_choices_in: None,
|
||||
cache_warming: luxe_core::cache_warming::CacheWarming::Off,
|
||||
review_insight_provider: None,
|
||||
github: None,
|
||||
@@ -197,7 +197,7 @@ mod tests {
|
||||
event_rx,
|
||||
running_rx,
|
||||
"Continue building.".into(),
|
||||
crate::loop_view::LoopView::new(true),
|
||||
crate::loop_view::LoopView::new(true, 0),
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
@@ -14,12 +14,20 @@
|
||||
//! Timed from the run's own start rather than the wall clock. "Twenty minutes in and still on
|
||||
//! phase 0" is the shape of the question being asked, and the absolute time is in the log for
|
||||
//! anything forensic.
|
||||
//!
|
||||
//! Each line is led by guides for the phase and iteration it belongs to ([`paint`]), and a tool
|
||||
//! call's line takes the color of its result once it has one ([`screen`]).
|
||||
|
||||
use crate::output::outln;
|
||||
mod paint;
|
||||
mod screen;
|
||||
|
||||
use paint::{CallState, Depth, Edge, Paint};
|
||||
use screen::{Printed, Screen};
|
||||
use std::collections::HashMap;
|
||||
use std::time::Instant;
|
||||
|
||||
use luxe_core::event::Event;
|
||||
use luxe_core::hooks::self_continuation::parse_iteration_notice;
|
||||
use luxe_core::message::{ContentBlock, Role};
|
||||
|
||||
/// Longest assistant line echoed into the view.
|
||||
@@ -43,16 +51,47 @@ pub(crate) struct LoopView {
|
||||
tools_this_turn: usize,
|
||||
/// When the turn now running began.
|
||||
turn_started: Option<Instant>,
|
||||
/// The phase the run is on, once known
|
||||
phase: Option<u32>,
|
||||
/// Whether an iteration's rail is open
|
||||
in_iteration: bool,
|
||||
/// The phase the run started on, until its first turn opens it: no iteration notice does
|
||||
start_phase: Option<u32>,
|
||||
/// Calls that have started and not ended, with their line and what it said
|
||||
running: HashMap<String, RunningCall>,
|
||||
paint: Paint,
|
||||
screen: Screen,
|
||||
}
|
||||
|
||||
/// A started call's line, kept to redraw it with the result.
|
||||
struct RunningCall {
|
||||
printed: Printed,
|
||||
/// When in the run it was printed, so the redraw keeps its time
|
||||
at: std::time::Duration,
|
||||
name: String,
|
||||
label: String,
|
||||
depth: Depth,
|
||||
}
|
||||
|
||||
impl LoopView {
|
||||
pub(crate) fn new(quiet: bool) -> Self {
|
||||
/// A view for a run starting on `phase`, in color on a terminal.
|
||||
pub(crate) fn new(quiet: bool, phase: u32) -> Self {
|
||||
Self::with(quiet, Some(phase), Paint::detect(), Screen::detect())
|
||||
}
|
||||
|
||||
fn with(quiet: bool, start_phase: Option<u32>, paint: Paint, screen: Screen) -> Self {
|
||||
Self {
|
||||
quiet,
|
||||
started: Instant::now(),
|
||||
labels: HashMap::new(),
|
||||
tools_this_turn: 0,
|
||||
turn_started: None,
|
||||
phase: None,
|
||||
in_iteration: false,
|
||||
start_phase,
|
||||
running: HashMap::new(),
|
||||
paint,
|
||||
screen,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,9 +103,14 @@ impl LoopView {
|
||||
match event {
|
||||
// A hook talking: the phase moved, the gate refused, the run is blocked. These are the
|
||||
// lines the whole view exists for.
|
||||
Event::Notice(message) => self.line("", message),
|
||||
Event::Notice(message) => match parse_iteration_notice(message) {
|
||||
Some((iteration, phase)) => {
|
||||
self.open_iteration(phase, &format!("iteration {iteration}"))
|
||||
}
|
||||
None => self.note(message),
|
||||
},
|
||||
Event::ProviderRetrying { attempt, attempts, reason } => {
|
||||
self.line("", &format!("retrying ({attempt}/{attempts}): {reason}"));
|
||||
self.note(&format!("retrying ({attempt}/{attempts}): {reason}"));
|
||||
}
|
||||
// Only the assistant's. The steer that opens each iteration and the gate's refusals
|
||||
// arrive as user messages the engine wrote to itself, and the notices above already
|
||||
@@ -78,7 +122,8 @@ impl LoopView {
|
||||
for block in &message.content {
|
||||
match block {
|
||||
ContentBlock::Text(text) if !text.trim().is_empty() => {
|
||||
self.line("· ", &bounded(first_line(text), MAX_SAID));
|
||||
let said = format!("· {}", bounded(first_line(text), MAX_SAID));
|
||||
self.within(&said);
|
||||
}
|
||||
ContentBlock::ToolCall { id, name, arguments } => {
|
||||
let label = luxe_core::describe_call(
|
||||
@@ -92,49 +137,114 @@ impl LoopView {
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::ToolStarted { call_id, name } => {
|
||||
if luxe_core::activity::is_bookkeeping(name) {
|
||||
return;
|
||||
}
|
||||
self.tools_this_turn += 1;
|
||||
match self.labels.get(call_id) {
|
||||
Some(label) if !label.is_empty() => self.line(" ", &format!("{name} {label}")),
|
||||
_ => self.line(" ", name),
|
||||
}
|
||||
}
|
||||
Event::ToolEnded { call_id, is_error } if *is_error => {
|
||||
let label = self.labels.get(call_id).cloned().unwrap_or_default();
|
||||
self.line(" ", format!("failed: {label}").trim_end());
|
||||
}
|
||||
Event::CompactionDone { tokens_before, tokens_after } => self.line(
|
||||
"",
|
||||
&format!("compacted {} → {}", thousands(*tokens_before), thousands(*tokens_after)),
|
||||
),
|
||||
Event::Error(message) => self.line("", &format!("error: {}", first_line(message))),
|
||||
Event::TurnEnded { reason } => {
|
||||
let took = self.turn_started.take().map(|at| at.elapsed()).unwrap_or_default();
|
||||
let tools = std::mem::take(&mut self.tools_this_turn);
|
||||
self.labels.clear();
|
||||
let ended = match reason {
|
||||
// Every ordinary ending says the same thing; the interesting ones name
|
||||
// themselves — a runaway guard, a cancel, a turn that failed.
|
||||
luxe_core::StopReason::EndTurn => "turn ended".to_string(),
|
||||
other => format!("turn ended: {other:?}"),
|
||||
};
|
||||
self.line("", &format!("{ended} · {tools} tools · {}", duration(took)));
|
||||
}
|
||||
Event::ToolStarted { call_id, name } => self.tool_started(call_id, name),
|
||||
Event::ToolEnded { call_id, is_error } => self.tool_ended(call_id, *is_error),
|
||||
Event::CompactionDone { tokens_before, tokens_after } => self.note(&format!(
|
||||
"compacted {} → {}",
|
||||
thousands(*tokens_before),
|
||||
thousands(*tokens_after)
|
||||
)),
|
||||
Event::Error(message) => self.note(&format!("error: {}", first_line(message))),
|
||||
Event::TurnEnded { reason } => self.turn_ended(reason),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Note that a turn has begun, so the line closing it can say how long it took.
|
||||
/// Note that a turn has begun, so the line closing it can say how long it took. The run's
|
||||
/// first turn opens its phase here, since no iteration notice comes before it.
|
||||
pub(crate) fn turn_started(&mut self) {
|
||||
self.turn_started = Some(Instant::now());
|
||||
if self.quiet {
|
||||
return;
|
||||
}
|
||||
if let Some(phase) = self.start_phase.take() {
|
||||
self.open_iteration(phase, "start");
|
||||
}
|
||||
}
|
||||
|
||||
/// One line: how long the run has been going, then what happened.
|
||||
fn line(&self, indent: &str, message: &str) {
|
||||
outln!("{:>9} {indent}{message}", duration(self.started.elapsed()));
|
||||
fn tool_started(&mut self, call_id: &str, name: &str) {
|
||||
if luxe_core::activity::is_bookkeeping(name) {
|
||||
return;
|
||||
}
|
||||
self.tools_this_turn += 1;
|
||||
let label = self.labels.get(call_id).cloned().unwrap_or_default();
|
||||
let depth = self.body_depth();
|
||||
let at = self.started.elapsed();
|
||||
let printed = self.print(depth, &self.paint.tool(name, &label, CallState::Running));
|
||||
let call = RunningCall { printed, at, name: name.to_string(), label, depth };
|
||||
self.running.insert(call_id.to_string(), call);
|
||||
}
|
||||
|
||||
/// Redraws the call's line in its result's color. Where it can't be redrawn, a failure gets a
|
||||
/// line of its own and a success needs none.
|
||||
fn tool_ended(&mut self, call_id: &str, is_error: bool) {
|
||||
let Some(call) = self.running.remove(call_id) else { return };
|
||||
let state = if is_error { CallState::Failed } else { CallState::Succeeded };
|
||||
let line = self.paint.tool(&call.name, &call.label, state);
|
||||
let stamped = self.stamped(call.at, call.depth, &line);
|
||||
let redrawn = self.paint.in_color() && self.screen.rewrite(call.printed, &stamped);
|
||||
if !redrawn && is_error {
|
||||
self.print(self.body_depth(), &line);
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_ended(&mut self, reason: &luxe_core::StopReason) {
|
||||
let took = self.turn_started.take().map(|at| at.elapsed()).unwrap_or_default();
|
||||
let tools = std::mem::take(&mut self.tools_this_turn);
|
||||
self.labels.clear();
|
||||
self.running.clear();
|
||||
let ended = match reason {
|
||||
// Every ordinary ending says the same thing; the interesting ones name
|
||||
// themselves — a runaway guard, a cancel, a turn that failed.
|
||||
luxe_core::StopReason::EndTurn => "turn ended".to_string(),
|
||||
other => format!("turn ended: {other:?}"),
|
||||
};
|
||||
let summary = self.paint.dim(&format!("{ended} · {tools} tools · {}", duration(took)));
|
||||
let depth = match (self.phase, self.in_iteration) {
|
||||
(Some(phase), true) => Depth::Iteration(phase, Edge::Close),
|
||||
_ => self.body_depth(),
|
||||
};
|
||||
self.in_iteration = false;
|
||||
self.print(depth, &summary);
|
||||
}
|
||||
|
||||
/// Opens an iteration, under a heading first when it starts a new phase.
|
||||
fn open_iteration(&mut self, phase: u32, label: &str) {
|
||||
if self.phase != Some(phase) {
|
||||
self.print(Depth::Phase(phase), &self.paint.phase_heading(phase));
|
||||
self.phase = Some(phase);
|
||||
}
|
||||
self.in_iteration = true;
|
||||
self.print(Depth::Iteration(phase, Edge::Open), label);
|
||||
}
|
||||
|
||||
/// A line inside whatever is open.
|
||||
fn within(&mut self, text: &str) {
|
||||
self.print(self.body_depth(), text);
|
||||
}
|
||||
|
||||
/// A hook's or the engine's notice: inside the iteration when one is open.
|
||||
fn note(&mut self, text: &str) {
|
||||
self.within(text);
|
||||
}
|
||||
|
||||
/// The depth a body line sits at now.
|
||||
fn body_depth(&self) -> Depth {
|
||||
match (self.phase, self.in_iteration) {
|
||||
(Some(phase), true) => Depth::Iteration(phase, Edge::Within),
|
||||
(Some(phase), false) => Depth::Phase(phase),
|
||||
(None, _) => Depth::Run,
|
||||
}
|
||||
}
|
||||
|
||||
/// One line: how long the run has been going, the guides, then what happened.
|
||||
fn print(&mut self, depth: Depth, text: &str) -> Printed {
|
||||
let line = self.stamped(self.started.elapsed(), depth, text);
|
||||
self.screen.print(&line)
|
||||
}
|
||||
|
||||
fn stamped(&self, elapsed: std::time::Duration, depth: Depth, text: &str) -> String {
|
||||
format!("{:>9} {}{text}", duration(elapsed), self.paint.guides(depth))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +328,7 @@ mod tests {
|
||||
/// still built labels would be a memory cost for output nobody asked for.
|
||||
#[test]
|
||||
fn a_quiet_view_does_not_even_look() {
|
||||
let mut view = LoopView::new(true);
|
||||
let mut view = recording(true);
|
||||
view.observe(&Event::MessageCommitted {
|
||||
session_id: "s".into(),
|
||||
entry_id: luxe_core::session::EntryId::new(),
|
||||
@@ -232,7 +342,7 @@ mod tests {
|
||||
/// A turn's tool count belongs to that turn, and starts again with the next one.
|
||||
#[test]
|
||||
fn each_turn_counts_its_own_tools() {
|
||||
let mut view = LoopView::new(false);
|
||||
let mut view = recording(false);
|
||||
view.turn_started();
|
||||
view.observe(&Event::ToolStarted { call_id: "a".into(), name: "read".into() });
|
||||
view.observe(&Event::ToolStarted { call_id: "b".into(), name: "edit".into() });
|
||||
@@ -243,14 +353,83 @@ mod tests {
|
||||
assert!(view.labels.is_empty(), "and does not inherit the last turn's labels");
|
||||
}
|
||||
|
||||
/// Luxe's own bookkeeping is not work anyone asked to watch.
|
||||
/// luxe's own bookkeeping is not work anyone asked to watch.
|
||||
#[test]
|
||||
fn activating_a_tool_is_not_a_step_worth_a_line() {
|
||||
let mut view = LoopView::new(false);
|
||||
let mut view = recording(false);
|
||||
view.observe(&Event::ToolStarted {
|
||||
call_id: "c".into(),
|
||||
name: luxe_core::tool::ACTIVATE_TOOLS_NAME.into(),
|
||||
});
|
||||
assert_eq!(view.tools_this_turn, 0);
|
||||
}
|
||||
|
||||
/// A plain view of a run starting on phase 0, its lines kept.
|
||||
fn recording(quiet: bool) -> LoopView {
|
||||
LoopView::with(quiet, Some(0), Paint::plain(), Screen::recording())
|
||||
}
|
||||
|
||||
/// What the view printed, past the time column.
|
||||
fn printed(view: &LoopView) -> Vec<String> {
|
||||
view.screen.lines().iter().map(|line| line[11..].to_string()).collect()
|
||||
}
|
||||
|
||||
fn notice(text: &str) -> Event {
|
||||
Event::Notice(text.into())
|
||||
}
|
||||
|
||||
fn ended(view: &mut LoopView, call_id: &str, is_error: bool) {
|
||||
view.observe(&Event::ToolEnded { call_id: call_id.into(), is_error });
|
||||
}
|
||||
|
||||
/// The first turn opens its phase and iteration itself; the turn's end closes the iteration.
|
||||
#[test]
|
||||
fn the_first_turn_is_bracketed_under_its_phase() {
|
||||
let mut view = recording(false);
|
||||
view.turn_started();
|
||||
view.observe(&Event::ToolStarted { call_id: "a".into(), name: "read".into() });
|
||||
view.observe(&Event::TurnEnded { reason: luxe_core::StopReason::EndTurn });
|
||||
let lines = printed(&view);
|
||||
assert_eq!(lines[..3], ["┃ phase 0", "┃ ┌ start", "┃ │ ○ read"], "{lines:?}");
|
||||
assert!(lines[3].starts_with("┃ └ turn ended · 1 tools"), "{lines:?}");
|
||||
}
|
||||
|
||||
/// An iteration in the same phase opens without a heading; a new phase gets one first.
|
||||
#[test]
|
||||
fn a_new_phase_gets_a_heading_and_the_same_phase_does_not() {
|
||||
let mut view = recording(false);
|
||||
view.turn_started();
|
||||
view.observe(¬ice("iteration 2 · phase 0"));
|
||||
view.observe(¬ice("iteration 3 · phase 1"));
|
||||
let lines = printed(&view);
|
||||
assert_eq!(lines[2..], ["┃ ┌ iteration 2", "┃ phase 1", "┃ ┌ iteration 3"], "{lines:?}");
|
||||
}
|
||||
|
||||
/// Other notices sit inside the open iteration, and between iterations on the phase rail.
|
||||
#[test]
|
||||
fn a_notice_sits_at_the_depth_it_arrives() {
|
||||
let mut view = recording(false);
|
||||
view.turn_started();
|
||||
view.observe(¬ice("phase 0 claimed complete — running the gate"));
|
||||
view.observe(&Event::TurnEnded { reason: luxe_core::StopReason::EndTurn });
|
||||
view.observe(¬ice("phase 0 accepted — now on phase 1"));
|
||||
let lines = printed(&view);
|
||||
assert_eq!(lines[2], "┃ │ phase 0 claimed complete — running the gate", "{lines:?}");
|
||||
assert_eq!(lines[4], "┃ phase 0 accepted — now on phase 1", "{lines:?}");
|
||||
}
|
||||
|
||||
/// Where the line can't be redrawn, a failure still gets a line saying so, and a success
|
||||
/// adds nothing to the call's own line.
|
||||
#[test]
|
||||
fn without_a_redraw_only_a_failure_adds_a_line() {
|
||||
let mut view = recording(false);
|
||||
view.turn_started();
|
||||
view.observe(&Event::ToolStarted { call_id: "a".into(), name: "read".into() });
|
||||
view.observe(&Event::ToolStarted { call_id: "b".into(), name: "bash".into() });
|
||||
ended(&mut view, "a", false);
|
||||
ended(&mut view, "b", true);
|
||||
let lines = printed(&view);
|
||||
assert_eq!(lines.len(), 5, "{lines:?}");
|
||||
assert_eq!(lines[4], "┃ │ ✗ bash · failed", "{lines:?}");
|
||||
}
|
||||
}
|
||||
|
||||
193
crates/luxe-cli/src/loop_view/paint.rs
Normal file
193
crates/luxe-cli/src/loop_view/paint.rs
Normal file
@@ -0,0 +1,193 @@
|
||||
//! Paint — how a loop line looks: the guides that lead it, and its colors when there are any.
|
||||
//!
|
||||
//! The guides work like an editor's indent guides. A phase draws a heavy rail down the left, in
|
||||
//! a color of its own; an iteration draws a light one inside it, opened with `┌` and closed with
|
||||
//! `└`. Scrolled back through a long run, or seen in a minimap, each phase is a band of one color
|
||||
//! and each iteration a bracket within it. Colors come from the terminal's own sixteen, so its
|
||||
//! theme picks the shades, and the guides are plain characters, so a log without color keeps them.
|
||||
|
||||
use crossterm::style::{Color, Stylize};
|
||||
|
||||
/// Phase rail colors, cycled by phase number so two neighboring phases never share one.
|
||||
const PHASE_COLORS: [Color; 4] = [Color::Cyan, Color::Magenta, Color::Blue, Color::Yellow];
|
||||
|
||||
/// Where a line sits in the run, which decides the guides leading it.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum Depth {
|
||||
/// Before the run has a phase
|
||||
Run,
|
||||
/// Inside a phase, between iterations
|
||||
Phase(u32),
|
||||
/// Inside an iteration of a phase.
|
||||
///
|
||||
/// Args: the phase, and which edge of the iteration the line is.
|
||||
Iteration(u32, Edge),
|
||||
}
|
||||
|
||||
/// Which part of an iteration a line is: its opening, its body, or its closing line.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum Edge {
|
||||
/// `┌`, the iteration's first line
|
||||
Open,
|
||||
/// `│`, every line between
|
||||
Within,
|
||||
/// `└`, the turn's summary
|
||||
Close,
|
||||
}
|
||||
|
||||
/// How a tool call has gone so far.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum CallState {
|
||||
/// Started, no result yet
|
||||
Running,
|
||||
/// Ended without an error
|
||||
Succeeded,
|
||||
/// Ended in an error
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Draws loop lines, in color or not.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Paint {
|
||||
color: bool,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
/// Color when stdout is a terminal that wants it: not `NO_COLOR`, not `TERM=dumb`.
|
||||
pub(super) fn detect() -> Self {
|
||||
use std::io::IsTerminal;
|
||||
let no_color = std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty());
|
||||
let dumb = std::env::var("TERM").is_ok_and(|term| term == "dumb");
|
||||
Self { color: std::io::stdout().is_terminal() && !no_color && !dumb }
|
||||
}
|
||||
|
||||
/// No color at all, as a pipe or a log gets.
|
||||
#[cfg(test)]
|
||||
pub(super) fn plain() -> Self {
|
||||
Self { color: false }
|
||||
}
|
||||
|
||||
/// Whether this paints in color.
|
||||
pub(super) fn in_color(self) -> bool {
|
||||
self.color
|
||||
}
|
||||
|
||||
/// The guides for a line at `depth`, each followed by a space.
|
||||
pub(super) fn guides(self, depth: Depth) -> String {
|
||||
match depth {
|
||||
Depth::Run => String::new(),
|
||||
Depth::Phase(phase) => format!("{} ", self.rail(phase)),
|
||||
Depth::Iteration(phase, edge) => {
|
||||
format!("{} {} ", self.rail(phase), self.dim(edge_glyph(edge)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The line that opens a phase: its number in the phase's color.
|
||||
pub(super) fn phase_heading(self, phase: u32) -> String {
|
||||
let text = format!("phase {phase}");
|
||||
match self.color {
|
||||
true => text.with(phase_color(phase)).bold().to_string(),
|
||||
false => text,
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool call: a mark and the tool's name colored by how it went, then what it was asked.
|
||||
/// A failure says so in words too, so the color never carries it alone.
|
||||
pub(super) fn tool(self, name: &str, label: &str, state: CallState) -> String {
|
||||
let (mark, color) = match state {
|
||||
CallState::Running => ("○", None),
|
||||
CallState::Succeeded => ("✓", Some(Color::Green)),
|
||||
CallState::Failed => ("✗", Some(Color::Red)),
|
||||
};
|
||||
let head = format!("{mark} {name}");
|
||||
let head = match (self.color, color) {
|
||||
(true, Some(color)) => head.with(color).bold().to_string(),
|
||||
(true, None) => head.bold().to_string(),
|
||||
(false, _) => head,
|
||||
};
|
||||
let failed = match state {
|
||||
CallState::Failed => format!(" · {}", self.colored("failed", Color::Red)),
|
||||
_ => String::new(),
|
||||
};
|
||||
format!("{head} {label}").trim_end().to_string() + &failed
|
||||
}
|
||||
|
||||
/// Secondary text: a turn's summary, the iteration rail.
|
||||
pub(super) fn dim(self, text: &str) -> String {
|
||||
match self.color {
|
||||
true => text.dim().to_string(),
|
||||
false => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn colored(self, text: &str, color: Color) -> String {
|
||||
match self.color {
|
||||
true => text.with(color).to_string(),
|
||||
false => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn rail(self, phase: u32) -> String {
|
||||
self.colored("┃", phase_color(phase))
|
||||
}
|
||||
}
|
||||
|
||||
fn phase_color(phase: u32) -> Color {
|
||||
PHASE_COLORS[phase as usize % PHASE_COLORS.len()]
|
||||
}
|
||||
|
||||
fn edge_glyph(edge: Edge) -> &'static str {
|
||||
match edge {
|
||||
Edge::Open => "┌",
|
||||
Edge::Within => "│",
|
||||
Edge::Close => "└",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_depth_draws_its_own_guides() {
|
||||
let paint = Paint::plain();
|
||||
assert_eq!(paint.guides(Depth::Run), "");
|
||||
assert_eq!(paint.guides(Depth::Phase(2)), "┃ ");
|
||||
assert_eq!(paint.guides(Depth::Iteration(2, Edge::Open)), "┃ ┌ ");
|
||||
assert_eq!(paint.guides(Depth::Iteration(2, Edge::Within)), "┃ │ ");
|
||||
assert_eq!(paint.guides(Depth::Iteration(2, Edge::Close)), "┃ └ ");
|
||||
}
|
||||
|
||||
/// Without color a failure still reads as one, and a success has no word to need.
|
||||
#[test]
|
||||
fn a_failed_call_says_so_in_words() {
|
||||
let paint = Paint::plain();
|
||||
assert_eq!(paint.tool("read", "a.rs", CallState::Running), "○ read a.rs");
|
||||
assert_eq!(paint.tool("read", "a.rs", CallState::Succeeded), "✓ read a.rs");
|
||||
assert_eq!(
|
||||
paint.tool("bash", "cargo test", CallState::Failed),
|
||||
"✗ bash cargo test · failed"
|
||||
);
|
||||
assert_eq!(paint.tool("todo", "", CallState::Succeeded), "✓ todo", "no trailing space");
|
||||
}
|
||||
|
||||
/// The tool's name takes the result's color; a plain view has no escapes at all.
|
||||
#[test]
|
||||
fn the_name_is_colored_by_the_result() {
|
||||
let paint = Paint { color: true };
|
||||
let ok = paint.tool("read", "a.rs", CallState::Succeeded);
|
||||
let failed = paint.tool("read", "a.rs", CallState::Failed);
|
||||
assert!(ok.contains(&"✓ read".with(Color::Green).bold().to_string()), "{ok:?}");
|
||||
assert!(failed.contains(&"✗ read".with(Color::Red).bold().to_string()), "{failed:?}");
|
||||
assert!(!Paint::plain().tool("read", "a.rs", CallState::Failed).contains('\x1b'));
|
||||
}
|
||||
|
||||
/// Neighboring phases never share a rail color, so a phase boundary shows in a minimap.
|
||||
#[test]
|
||||
fn neighboring_phases_differ() {
|
||||
for phase in 0..8 {
|
||||
assert_ne!(phase_color(phase), phase_color(phase + 1), "{phase}");
|
||||
}
|
||||
}
|
||||
}
|
||||
177
crates/luxe-cli/src/loop_view/screen.rs
Normal file
177
crates/luxe-cli/src/loop_view/screen.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Screen — where loop lines go, and taking one back to redraw it.
|
||||
//!
|
||||
//! A tool call is printed when it starts, because "is it still going?" is the first question about
|
||||
//! an unattended run, and its result only exists once it ends. On a terminal the start line is
|
||||
//! redrawn in place with the result. That's only safe when every line is exactly one row, so on a
|
||||
//! terminal each line is cut to the width rather than left to wrap, and a resize since the line
|
||||
//! was printed means it's left alone. A pipe or a file never gets a redraw.
|
||||
|
||||
use crate::output::{out, outln};
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
/// A line already printed, and what's needed to find it again.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Printed {
|
||||
/// How many lines came before it
|
||||
index: u64,
|
||||
/// The terminal's width when it was printed
|
||||
width: Option<u16>,
|
||||
}
|
||||
|
||||
/// The terminal or pipe the view prints to.
|
||||
pub(super) struct Screen {
|
||||
/// Whether lines may be cut to the width and redrawn
|
||||
terminal: bool,
|
||||
/// Lines printed so far
|
||||
printed: u64,
|
||||
/// Where a test's lines go instead of stdout
|
||||
recorded: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
/// A terminal when stdout is one.
|
||||
pub(super) fn detect() -> Self {
|
||||
use std::io::IsTerminal;
|
||||
Self { terminal: std::io::stdout().is_terminal(), printed: 0, recorded: None }
|
||||
}
|
||||
|
||||
/// A pipe that keeps its lines for a test to read.
|
||||
#[cfg(test)]
|
||||
pub(super) fn recording() -> Self {
|
||||
Self { terminal: false, printed: 0, recorded: Some(Vec::new()) }
|
||||
}
|
||||
|
||||
/// What a [`Screen::recording`] was given.
|
||||
#[cfg(test)]
|
||||
pub(super) fn lines(&self) -> &[String] {
|
||||
self.recorded.as_deref().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Prints `line` as one row, and says where it went.
|
||||
pub(super) fn print(&mut self, line: &str) -> Printed {
|
||||
let width = self.width();
|
||||
let printed = Printed { index: self.printed, width };
|
||||
self.printed += 1;
|
||||
if let Some(recorded) = &mut self.recorded {
|
||||
recorded.push(line.to_string());
|
||||
return printed;
|
||||
}
|
||||
match width {
|
||||
Some(cells) => outln!("{}", fit(line, usize::from(cells))),
|
||||
None => outln!("{line}"),
|
||||
}
|
||||
printed
|
||||
}
|
||||
|
||||
/// Redraws an earlier line in place. False, and nothing written, when it can't be trusted to
|
||||
/// land on the same row: not a terminal, a resize since, or scrolled past the top.
|
||||
pub(super) fn rewrite(&mut self, at: Printed, line: &str) -> bool {
|
||||
let Some(cells) = self.width().filter(|now| Some(*now) == at.width) else { return false };
|
||||
let up = self.printed - at.index;
|
||||
let rows = crossterm::terminal::size().map_or(0, |(_, rows)| u64::from(rows));
|
||||
if up == 0 || up >= rows {
|
||||
return false;
|
||||
}
|
||||
// Up to the line, clear it, draw, then back down to where the next line goes
|
||||
out!("\x1b[{up}A\r\x1b[2K{}\x1b[{up}B\r", fit(line, usize::from(cells)));
|
||||
true
|
||||
}
|
||||
|
||||
fn width(&self) -> Option<u16> {
|
||||
match self.terminal {
|
||||
true => crossterm::terminal::size().ok().map(|(cols, _)| cols),
|
||||
false => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `line` cut to fit in `width` cells, so it never wraps. Escape sequences pass through uncounted,
|
||||
/// and a cut line ends in `…` and, if it had color, a reset.
|
||||
pub(super) fn fit(line: &str, width: usize) -> String {
|
||||
if visible_width(line) <= width {
|
||||
return line.to_string();
|
||||
}
|
||||
let (cut, _) = scan(line, width.saturating_sub(1));
|
||||
let reset = if line.contains('\x1b') { "\x1b[0m" } else { "" };
|
||||
format!("{cut}…{reset}")
|
||||
}
|
||||
|
||||
/// Where the scanner is: in text, just past an escape, or inside a `CSI` sequence.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Scan {
|
||||
Text,
|
||||
Escape,
|
||||
Csi,
|
||||
}
|
||||
|
||||
/// `line` up to `budget` visible cells, with every escape sequence kept, and the cells it used.
|
||||
fn scan(line: &str, budget: usize) -> (String, usize) {
|
||||
let mut kept = String::with_capacity(line.len());
|
||||
let mut used = 0;
|
||||
let mut state = Scan::Text;
|
||||
for ch in line.chars() {
|
||||
state = match (state, ch) {
|
||||
(Scan::Text, '\x1b') => Scan::Escape,
|
||||
(Scan::Escape, '[') => Scan::Csi,
|
||||
(Scan::Escape, _) => Scan::Text,
|
||||
(Scan::Csi, '@'..='~') => Scan::Text,
|
||||
(Scan::Csi, _) => Scan::Csi,
|
||||
(Scan::Text, text) => {
|
||||
let cells = text.width().unwrap_or(0);
|
||||
if used + cells > budget {
|
||||
break;
|
||||
}
|
||||
used += cells;
|
||||
Scan::Text
|
||||
}
|
||||
};
|
||||
kept.push(ch);
|
||||
}
|
||||
(kept, used)
|
||||
}
|
||||
|
||||
fn visible_width(line: &str) -> usize {
|
||||
scan(line, usize::MAX).1
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_line_that_fits_is_left_alone() {
|
||||
assert_eq!(fit("○ read a.rs", 40), "○ read a.rs");
|
||||
assert_eq!(fit("exactly", 7), "exactly");
|
||||
}
|
||||
|
||||
/// One cell short of the width plus the ellipsis is the width, so the row never wraps.
|
||||
#[test]
|
||||
fn a_long_line_is_cut_to_the_width() {
|
||||
assert_eq!(fit("abcdefghij", 6), "abcde…");
|
||||
assert_eq!(visible_width(&fit("abcdefghij", 6)), 6);
|
||||
}
|
||||
|
||||
/// Escapes take no cells: a colored line that fits isn't cut, and a cut one is reset.
|
||||
#[test]
|
||||
fn escapes_are_not_counted() {
|
||||
let green = "\x1b[32m✓ read\x1b[39m a.rs";
|
||||
assert_eq!(visible_width(green), "✓ read a.rs".chars().count());
|
||||
assert_eq!(fit(green, 11), green);
|
||||
assert_eq!(fit(green, 5), "\x1b[32m✓ re…\x1b[0m");
|
||||
}
|
||||
|
||||
/// A wide character counts as the two cells it takes.
|
||||
#[test]
|
||||
fn wide_characters_count_double() {
|
||||
assert_eq!(visible_width("日本"), 4);
|
||||
assert_eq!(fit("日本語", 5), "日本…");
|
||||
}
|
||||
|
||||
/// A pipe never redraws: there's no row to go back to.
|
||||
#[test]
|
||||
fn a_pipe_never_redraws() {
|
||||
let mut screen = Screen::recording();
|
||||
let line = screen.print("○ read a.rs");
|
||||
assert!(!screen.rewrite(line, "✓ read a.rs"));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Model catalog wiring — cache location, refresh scheduling, and the `/model` menu.
|
||||
//!
|
||||
//! Metadata itself is resolved by [`luxe_providers::catalog`]; this module owns the parts that
|
||||
//! depend on where Luxe keeps files and when it's allowed to touch the network. Resolution is
|
||||
//! depend on where luxe keeps files and when it's allowed to touch the network. Resolution is
|
||||
//! always offline-safe — it reads the embedded snapshot plus a local cache and never blocks —
|
||||
//! while [`spawn_refresh`] keeps that cache current in the background.
|
||||
|
||||
@@ -71,7 +71,7 @@ pub(crate) fn build_menu(settings: &AgentSettings) -> ModelMenu {
|
||||
push(&mut entries, resolve_model(&config, provider, id).0, true);
|
||||
}
|
||||
|
||||
// Then everything the catalog knows for providers Luxe can actually route to: the ones with a
|
||||
// Then everything the catalog knows for providers luxe can actually route to: the ones with a
|
||||
// config block, anything the user has signed in to (a Copilot login is worthless if its models
|
||||
// never appear), and the launch's own provider when the launch itself carries the credentials
|
||||
// to reach it.
|
||||
|
||||
@@ -187,7 +187,7 @@ fn an_unconfigured_machine_has_no_models_to_choose_between() {
|
||||
let with_key = AgentSettings::resolve(std::path::PathBuf::from("."), Default::default());
|
||||
let catalog = build_menu(&with_key).catalog;
|
||||
std::env::remove_var("ANTHROPIC_API_KEY");
|
||||
assert!(!catalog.is_empty(), "an ambient key is a provider Luxe can route to");
|
||||
assert!(!catalog.is_empty(), "an ambient key is a provider luxe can route to");
|
||||
assert!(
|
||||
catalog.iter().all(|entry| entry.info.r#ref.provider == "anthropic"),
|
||||
"and only that provider's models: {:?}",
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
//! idiom.
|
||||
//!
|
||||
//! The usual cure — resetting `SIGPIPE` to its default so the process dies silently — is wrong
|
||||
//! here. Luxe writes to hook, MCP and LSP pipes and relies on `EPIPE` arriving as an error: the
|
||||
//! here. luxe writes to hook, MCP and LSP pipes and relies on `EPIPE` arriving as an error: the
|
||||
//! command-hook runner deliberately tolerates a hook that exits without reading its stdin, and a
|
||||
//! default `SIGPIPE` would kill Luxe at that line instead. So the pipe stays ignored and the
|
||||
//! default `SIGPIPE` would kill luxe at that line instead. So the pipe stays ignored and the
|
||||
//! writing goes through one place, where a reader that has gone away is a quiet, successful end of
|
||||
//! output.
|
||||
//!
|
||||
|
||||
@@ -249,10 +249,10 @@ async fn look<G: Discovery + Branches + ?Sized>(
|
||||
fn unavailable(error: &GitHubError) -> Option<String> {
|
||||
let reason = match error {
|
||||
GitHubError::NotInstalled => {
|
||||
"The GitHub CLI (`gh`) is not installed, so Luxe cannot see this branch's pull request."
|
||||
"The GitHub CLI (`gh`) is not installed, so luxe cannot see this branch's pull request."
|
||||
}
|
||||
GitHubError::NotAuthenticated { .. } => {
|
||||
"The GitHub CLI is not signed in. Run `gh auth login`, and Luxe picks it up the next \
|
||||
"The GitHub CLI is not signed in. Run `gh auth login`, and luxe picks it up the next \
|
||||
time the terminal has focus."
|
||||
}
|
||||
GitHubError::NotGitHub => "This repository has no remote on GitHub.",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The reviewer as an agent — a real turn, with the real tools, in a session of its own.
|
||||
//!
|
||||
//! A review is a model driving Luxe. It gets the same pipeline every other turn gets: the tool
|
||||
//! A review is a model driving luxe. It gets the same pipeline every other turn gets: the tool
|
||||
//! registry, the permission engine, per-tool deadlines, cancellation, the hook chain. What makes it
|
||||
//! a *review* is how its engine is built — the reviewer's model, the reviewer's tools and no others,
|
||||
//! and a mode that refuses every write — and the brief it is handed, which says who it is.
|
||||
|
||||
@@ -313,7 +313,7 @@ fn bounded_text(text: &str, limit: usize) -> String {
|
||||
value
|
||||
}
|
||||
|
||||
/// Luxe's own project directory, excluded from what it reports as *your* changes.
|
||||
/// luxe's own project directory, excluded from what it reports as *your* changes.
|
||||
const LUXE_PROJECT_DIR: &str = ".luxe";
|
||||
|
||||
async fn project_identity(root: &Path) -> ProjectIdentity {
|
||||
|
||||
@@ -17,7 +17,7 @@ pub(super) async fn collect_change_summary(root: PathBuf) -> WorkspaceChangesSum
|
||||
let counts = numstat.as_deref().map(parse_numstat).unwrap_or_default();
|
||||
let files = parse_status(&status)
|
||||
.into_iter()
|
||||
// Luxe's own project directory — sessions, logs, tasks, review artifacts — is not the
|
||||
// luxe's own project directory — sessions, logs, tasks, review artifacts — is not the
|
||||
// user's work. Listing it made the dock's count disagree with the review's forever.
|
||||
.filter(|(path, _)| !path.starts_with(LUXE_PROJECT_DIR))
|
||||
.map(|(path, status)| {
|
||||
|
||||
@@ -32,7 +32,7 @@ pub(super) async fn collect_external_summary(
|
||||
}
|
||||
let changes = collect_change_summary(root.clone()).await;
|
||||
// A repository that *contains* the project — an edit in a sibling directory of a checkout
|
||||
// Luxe was opened one level inside — reports the project's own files too. Those already
|
||||
// luxe was opened one level inside — reports the project's own files too. Those already
|
||||
// have a section, and listing them twice would double every number on the screen.
|
||||
let mut files = changes.files;
|
||||
files.retain(|file| !luxe_core::paths::contains(project_root, &root.join(&file.path)));
|
||||
|
||||
@@ -118,7 +118,7 @@ fn git_repo_with_a_commit(root: &Path) {
|
||||
}
|
||||
|
||||
/// A checkout is asked the same question the project is asked, which is the whole point of
|
||||
/// recording the root instead of the file: this change is made with the shell, so nothing Luxe
|
||||
/// recording the root instead of the file: this change is made with the shell, so nothing luxe
|
||||
/// tracks per-file could have seen it.
|
||||
#[tokio::test]
|
||||
async fn an_external_checkout_is_reported_by_git() {
|
||||
@@ -130,7 +130,7 @@ async fn an_external_checkout_is_reported_by_git() {
|
||||
|
||||
let work = ExternalWork::new();
|
||||
work.observe(&sibling.join("lib.rs"));
|
||||
// Not through any Luxe tool — exactly what the per-file ledger cannot know about.
|
||||
// Not through any luxe tool — exactly what the per-file ledger cannot know about.
|
||||
std::fs::write(sibling.join("lib.rs"), "alpha\nbeta\ngamma\n").unwrap();
|
||||
|
||||
let summary = collect_external_summary(work.record(), &project).await;
|
||||
@@ -143,7 +143,7 @@ async fn an_external_checkout_is_reported_by_git() {
|
||||
assert_eq!(summary.total_files, 1);
|
||||
}
|
||||
|
||||
/// A repository Luxe was opened *inside* reports the project's own files too. They already have
|
||||
/// A repository luxe was opened *inside* reports the project's own files too. They already have
|
||||
/// a section, and counting them twice would double every number on screen.
|
||||
#[tokio::test]
|
||||
async fn a_parent_checkout_does_not_report_the_project_twice() {
|
||||
|
||||
@@ -119,7 +119,7 @@ async fn bridge_tracks_real_engine_startup_and_new_sessions() {
|
||||
external_work: None,
|
||||
review_context_files: Vec::new(),
|
||||
review_exclude: Vec::new(),
|
||||
remember_runtime_state: false,
|
||||
remember_choices_in: None,
|
||||
cache_warming: luxe_core::cache_warming::CacheWarming::Off,
|
||||
review_insight_provider: None,
|
||||
github: None,
|
||||
|
||||
Reference in New Issue
Block a user