luxe update and /update, editable question answers, and a version bump owed once per release

- luxe update and /update update Luxe with the command for however it was installed (cargo or
  Homebrew), run one program at a time with the terminal attached, then check that the luxe on
  PATH is the new version. Luxe never downloads or replaces its own binary. The start screen says
  "Update available · /update".
- A question's typed answer edits at its caret: arrows, word jumps, Home, End and Delete work,
  and up and down move through a wrapped answer before leaving it.
- The version check owes a bump once per release: the version on main is the next release, and
  only a released one (a v-tag) has to move.
- Dependency updates arrive through the sync, so Dependabot and the weekly jobs no longer run here.
This commit is contained in:
Evan Whittaker
2026-10-17 14:14:27 -05:00
parent 0e84deb59c
commit bf86df5098
41 changed files with 794 additions and 355 deletions

8
.gitattributes vendored
View File

@@ -37,3 +37,11 @@ shine-text.md export-ignore
# Development scripts whose inputs are the export-ignored files above
scripts/tool-ergonomics.sh export-ignore
# Automation that changes the tree on its own. The public repository is this one's export, and each
# sync replaces its tree, so a bump or a snapshot merged there alone would be reverted by the next
# sync. Dependabot and the weekly jobs run here, and what they land reaches the public repository
# with the sync after.
.github/dependabot.yml export-ignore
.github/workflows/models-snapshot.yml export-ignore
.github/workflows/real-servers.yml export-ignore

View File

@@ -1,60 +0,0 @@
# Dependabot — keeps the SHA-pinned GitHub Actions, the Cargo tree, and the website's npm deps current.
#
# For github-actions it bumps the pinned commit SHA (and the trailing `# vX` tag comment) as new
# releases land, so pinning to a SHA stays secure without going stale. Cargo updates keep the
# dependency tree fresh; the CI `--locked` + cargo-deny gates vet every bump.
#
# UPDATES ARE GROUPED, and that is a cost decision with numbers behind it. Ungrouped, one weekly run
# opened thirteen pull requests — and each one is a full CI run across three platforms, of which the
# Windows job alone takes ~17 minutes and bills at 2x. Worse, they all rebase and re-run every time
# master moves, so a single push cost hours of runner time re-testing bumps nobody had looked at yet.
# Grouped, the same week is two pull requests. Nothing is skipped and nothing auto-merges: the same
# gate runs over the same set of bumps, once instead of thirteen times.
#
# Major versions stay separate on purpose. A `thiserror 1 -> 2` is a code change to read, not a line
# in a batch, and burying it among patch bumps is how it gets waved through.
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
commit-message:
prefix: ci
groups:
actions:
patterns: ["*"]
update-types: [minor, patch]
- package-ecosystem: cargo
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
commit-message:
prefix: deps
groups:
cargo:
patterns: ["*"]
update-types: [minor, patch]
# The website is a deployed surface with its own dependency tree (Astro, Svelte, the asciinema
# player, wrangler). Same deal as cargo: batch the minor/patch churn, leave the majors to read.
- package-ecosystem: npm
directory: /web
schedule:
interval: weekly
commit-message:
prefix: deps
groups:
web:
patterns: ["*"]
update-types: [minor, patch]
ignore:
# TypeScript 7 is the native compiler, and it does not ship the programmatic API that
# `astro check` drives — `npm run check` fails on load, before it type-checks anything. This is
# upstream's to fix (withastro/roadmap#1321) and not something a bump here can carry, so the
# major is muted rather than reopened weekly. Minor and patch on 5.x still come through.
# Drop this entry when `@astrojs/check` announces TypeScript 7 support.
- dependency-name: typescript
update-types: ["version-update:semver-major"]

View File

@@ -3,8 +3,8 @@
# Mirrors the local gate (AGENTS.md / PROJECT.md) and adds `--locked` everywhere
# so a PR can never silently drift `Cargo.lock` (the core supply-chain guard).
# Third-party actions are pinned to commit SHAs (trailing `# vX` = the tag);
# Dependabot (.github/dependabot.yml) bumps the SHAs. SHA-pinned `uses:` lines
# necessarily exceed 80 cols — that's expected.
# Dependabot bumps the SHAs in the development repository. SHA-pinned `uses:`
# lines necessarily exceed 80 cols — that's expected.
name: CI
# A commit that touches only prose cannot change what the compiler or the suite says, and this

View File

@@ -1,103 +0,0 @@
name: models.dev snapshot
# The embedded snapshot is the offline/first-run floor for model metadata. The runtime refresh
# keeps live installs current, so this only has to move at release cadence — but a fresh clone or
# an air-gapped install should still know about models that shipped since the last release.
#
# Everything is verified *here*, in the job, rather than on the pull request it opens. A PR created
# with the default `GITHUB_TOKEN` does not trigger workflows — that is GitHub's loop guard, not a
# misconfiguration — so the PR's check list is empty by construction and always will be. Whatever
# has to hold before these bytes ship is therefore asserted below, before the PR exists.
on:
schedule:
- cron: "0 6 * * 1" # Mondays, 06:00 UTC
workflow_dispatch:
permissions:
contents: write
pull-requests: write
# The same build settings as `ci.yml`, which this job used to go without. Regenerating the site
# assets lists every test binary in the workspace, and with full debug info that build filled the
# runner's disk: the listing came back empty and the job died on a JSON parse, having said nothing
# about why.
env:
CARGO_TERM_COLOR: always
CARGO_NET_RETRY: "3"
CARGO_PROFILE_DEV_DEBUG: line-tables-only
CARGO_PROFILE_TEST_DEBUG: line-tables-only
jobs:
refresh:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Regenerate the snapshot
run: scripts/update-models-snapshot.sh
# The script writes deterministic bytes, so an unchanged catalog means there is nothing to
# build, test or open. Skip the expensive half rather than spending a release build to
# discover it.
- name: Did anything change?
id: changed
run: |
if git diff --quiet -- crates/luxe-providers/data/models-dev-snapshot.json.gz; then
echo "snapshot unchanged"
echo "changed=false" >>"$GITHUB_OUTPUT"
else
echo "changed=true" >>"$GITHUB_OUTPUT"
fi
- name: Install Rust
if: steps.changed.outputs.changed == 'true'
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
if: steps.changed.outputs.changed == 'true'
- name: Install nextest
if: steps.changed.outputs.changed == 'true'
uses: taiki-e/install-action@26e9283f268b880168bdbd2c545dfcd60ec2c6ab # v2.87.13
with:
tool: nextest
# What upstream churn actually breaks: a provider id that was renamed, or a preference list
# whose first entry was retired, which would hand every new account fallback metadata. Those
# live in `luxe-providers`' catalog tests; `luxe-cli` owns resolution on top of them.
- name: Verify the catalog still holds
if: steps.changed.outputs.changed == 'true'
run: cargo nextest run -p luxe-providers -p luxe-cli
# `facts.json` counts the snapshot's providers and models, so a refresh makes the generated
# site assets stale. Regenerating here keeps the PR self-consistent — shipping the snapshot
# alone turns the stale-assets gate red on master the moment it merges.
- name: Regenerate the site assets
if: steps.changed.outputs.changed == 'true'
run: |
scripts/site-assets.sh
scripts/site-assets.sh --check
- uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
if: steps.changed.outputs.changed == 'true'
with:
branch: chore/models-dev-snapshot
title: "chore: refresh the embedded models.dev snapshot"
commit-message: "chore: refresh the embedded models.dev snapshot"
body: |
Automated refresh of `crates/luxe-providers/data/models-dev-snapshot.json.gz`
from https://models.dev/api.json, with the derived counts in
`web/src/assets/generated/facts.json`.
Verified in the job that produced it — a PR opened with `GITHUB_TOKEN` gets no
workflow runs, so an empty check list here is expected, not a failure:
- `cargo nextest run -p luxe-providers -p luxe-cli`
- `scripts/site-assets.sh --check`
Regenerate locally with `scripts/update-models-snapshot.sh` followed by
`scripts/site-assets.sh`. The script writes deterministic bytes, so an unchanged
catalog produces no PR.
add-paths: |
crates/luxe-providers/data/models-dev-snapshot.json.gz
web/src/assets/generated/facts.json

View File

@@ -1,80 +0,0 @@
name: real language servers
# The `#[ignore]`d LSP tests, run against servers that are actually installed.
#
# They are ignored for a good reason — each one spawns a real server, which the canonical gate has
# no business doing on every push — and that reason is also how they rot: nothing ran them, so a
# TypeScript adapter that reported every `.ts` file as clean sat green for months. An ignored test
# nobody runs is worth roughly nothing.
#
# So: weekly, and on demand, off the PR path entirely. What it catches is drift *underneath* Luxe —
# a server that changed its handshake, a language whose toolchain moved to a protocol Luxe does not
# speak — which is a class of failure no amount of stub testing sees, and which arrives on a
# calendar rather than in a diff.
on:
schedule:
- cron: "0 7 * * 1" # Mondays, 07:00 UTC
workflow_dispatch:
permissions:
contents: read
concurrency:
group: real-servers-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
CARGO_NET_RETRY: "3"
CARGO_PROFILE_TEST_DEBUG: line-tables-only
jobs:
servers:
name: lsp against installed servers
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust (stable + rust-analyzer)
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
with:
components: rust-analyzer
- name: Cache cargo + target
uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
- name: Install nextest
uses: taiki-e/install-action@26e9283f268b880168bdbd2c545dfcd60ec2c6ab # v2.87.13
with:
tool: nextest
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 24
# Every test here skips itself when its server is absent, so this list is what gets covered
# rather than what is required. `typescript` is installed beside its language server because
# `typescript-language-server` is a driver and does nothing without one.
- name: Install language servers
run: |
npm i -g typescript typescript-language-server pyright \
bash-language-server yaml-language-server vscode-langservers-extracted \
svelte-language-server
go install golang.org/x/tools/gopls@latest
echo "$(go env GOPATH)/bin" >>"${GITHUB_PATH}"
- name: Which servers answered
run: |
for server in rust-analyzer typescript-language-server tsc pyright-langserver \
gopls clangd bash-language-server yaml-language-server \
vscode-json-language-server svelteserver; do
printf '%-32s %s\n' "${server}" "$(command -v "${server}" || echo 'not installed')"
done
# Serially: several of these index a project, and a runner with two cores running six
# language servers at once measures the runner rather than the adapter.
- name: Real-server suite
run: >
cargo nextest run -p luxe-lsp --locked --run-ignored all
--test-threads 1 --no-fail-fast -E 'test(/real_/)'

View File

@@ -5,8 +5,9 @@ and versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1.0, a minor bump (0.x.0) may break config, flags or the `--rpc` protocol, and a patch bump never
does.
A pull request that changes what ships (`crates/`, `Cargo.toml`, `Cargo.lock`) bumps the workspace
version by one step and adds its section here; `scripts/version-check.py` holds it to that.
The version on `main` is always the next release. The first change to what ships (`crates/`,
`Cargo.toml`, `Cargo.lock`) after a release bumps it one step and opens its section here, and later
changes add to that section until it ships; `scripts/version-check.py` holds them to it.
## [0.1.0]

View File

@@ -283,12 +283,15 @@ cd web && npm run deploy # needs `wrangler login` once
## Versioning
One version for the whole workspace (`[workspace.package]` in `Cargo.toml`), following semver. A
pull request to the public repository that changes what ships (`crates/`, `Cargo.toml`,
`Cargo.lock`) bumps it by exactly one step, updates the internal path-dependency pins to match, and
adds a `## [x.y.z]` section to `CHANGELOG.md`. The `Version` workflow runs
`scripts/version-check.py` against the target branch to hold it to that; changes to the site, the
guide or CI owe no bump.
One version for the whole workspace (`[workspace.package]` in `Cargo.toml`), following semver, and
the version on `main` is always the next release. The first pull request to the public repository
that changes what ships (`crates/`, `Cargo.toml`, `Cargo.lock`) after a release, which is when a
`v<version>` tag marks the current one, bumps it by exactly one step, updates the internal
path-dependency pins to match, and adds a `## [x.y.z]` section to `CHANGELOG.md`. Later pull
requests before the next release owe no bump and add their entries to that section; one that
breaks something may still move a pending patch to a minor, one step past the last release. The
`Version` workflow runs `scripts/version-check.py` against the target branch to hold it to that;
changes to the site, the guide or CI owe nothing.
```bash
python3 scripts/version-check.py origin/main # what the pull request check runs

View File

@@ -11,6 +11,7 @@ pub(crate) mod headless;
mod models_command;
mod rpc;
mod tui;
pub(crate) mod update_command;
mod wire_command;
mod worktree;
@@ -40,6 +41,10 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
if let Some(SubCommand::Docs(docs)) = &args.command {
return docs_command::run(docs);
}
// An update is about this binary, not a project, so it runs from anywhere
if let Some(SubCommand::Update(update)) = &args.command {
return update_command::run(update.check).await;
}
args.validate()?;
// Where the project begins, which is not always where the shell was standing. Everything after
// this — sessions, logs, instructions, the file index, every tool's relative path — is measured
@@ -114,8 +119,8 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
}
SubCommand::Doctor => return run_doctor_command(settings).await,
SubCommand::Wire(wire_args) => return run_wire_command(wire_args),
SubCommand::Docs(_) => {
unreachable!("`luxe docs` returned before a project was entered")
SubCommand::Docs(_) | SubCommand::Update(_) => {
unreachable!("`luxe docs` and `luxe update` return before a project is entered")
}
}
}

View File

@@ -185,6 +185,7 @@ impl Args {
| SubCommand::Init(_)
| SubCommand::Models(_)
| SubCommand::Sessions(_)
| SubCommand::Update(_)
| SubCommand::Wire(_),
) => false,
}
@@ -255,6 +256,7 @@ impl Args {
| SubCommand::Mcp(_)
| SubCommand::Models(_)
| SubCommand::Sessions(_)
| SubCommand::Update(_)
| SubCommand::Wire(_),
) => false,
}

View File

@@ -21,10 +21,20 @@ pub(crate) enum SubCommand {
Models(ModelsArgs),
/// List this project's sessions.
Sessions(SessionsArgs),
/// Update Luxe with the command for however it was installed.
Update(UpdateArgs),
/// Summarize a `LUXE_WIRE_LOG` capture.
Wire(WireArgs),
}
/// Update arguments.
#[derive(Parser, Debug)]
pub(crate) struct UpdateArgs {
/// Only say whether a newer release exists, and how to get it.
#[arg(long)]
pub(crate) check: bool,
}
/// Docs arguments.
#[derive(Parser, Debug)]
pub(crate) struct DocsArgs {

View File

@@ -5,11 +5,15 @@ use super::worktree::{
check_out_pull_request, enter_session_worktree, remove_worktree, take_up_issue_in_worktree,
};
/// The one line under the dashboard, or nothing.
/// The one line under the dashboard, or nothing: that an update exists, and how to take it. The
/// versions and the command wait for `/update`, where the reader decides.
fn footer_note(repo_root: &std::path::Path) -> Option<String> {
crate::update_check::cached_notice(repo_root).map(|notice| notice.line())
crate::update_check::cached_notice(repo_root).map(|_| UPDATE_HINT.to_string())
}
/// What the dashboard says when a newer Luxe exists.
const UPDATE_HINT: &str = "Update available · /update";
/// Whether the startup dashboard should be shown.
///
/// Suppressed when resuming, when the session already has its work — `--issue` or `--pr` said
@@ -151,6 +155,12 @@ impl Next<'_> {
remove_worktree(&self.settings.state_root, &path).await;
return Ok(Flow::Leave);
}
TuiExit::Update => {
// The terminal is the reader's again, so the package manager's output reaches them
shutdown_workspace_services().await;
super::update_command::run(false).await?;
return Ok(Flow::Leave);
}
TuiExit::TakeUpIssue(number) => {
// A new session on the issue, in its worktree; the one left stays as it was
shutdown_workspace_services().await;
@@ -342,3 +352,28 @@ pub(super) async fn shutdown_workspace_services() {
tracing::warn!("workspace service shutdown timed out; relying on kill-on-drop reaping");
}
}
#[cfg(test)]
mod tests {
use luxe_core::update::UpdateState;
/// The start screen says only that an update exists and how to take it, and nothing when it
/// does not; the versions and the command wait for `/update`.
///
/// Mutates the environment, which nextest makes safe by giving each test its own process.
#[test]
fn the_footer_says_an_update_is_available_and_how() {
let dir = tempfile::tempdir().expect("tempdir");
let cache = dir.path().join("update.json");
std::env::set_var("LUXE_UPDATE_PATH", &cache);
std::env::set_var("LUXE_UPDATE_CHECK", "1");
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap();
for (latest, footer) in [("99.0.0", Some("Update available · /update")), ("0.0.1", None)] {
let state = UpdateState { latest: Some(latest.into()), checked_at: now.as_secs() };
state.store(&cache).expect("store");
assert_eq!(super::footer_note(dir.path()).as_deref(), footer, "{latest}");
}
std::env::remove_var("LUXE_UPDATE_PATH");
std::env::remove_var("LUXE_UPDATE_CHECK");
}
}

View File

@@ -0,0 +1,142 @@
//! `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
//! writes a binary itself. `/update` on the dashboard comes here too, once the TUI has handed the
//! terminal back.
use anyhow::{anyhow, bail, Context};
use luxe_core::update::{self, InstallSource};
use std::path::{Path, PathBuf};
/// 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;
let latest = crate::update_check::check_now()
.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.");
return Ok(());
}
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)
}
_ => {
println!("{}", instructions(source, check_only, cfg!(windows)));
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 {
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<()> {
for step in steps {
let Some((program, args)) = step.split_first() else { continue };
let line = step.join(" ");
println!("Running: {line}");
let status = tokio::process::Command::new(program)
.args(args)
.status()
.await
.with_context(|| format!("could not start `{program}`"))?;
if !status.success() {
bail!("`{line}` failed ({status}), so Luxe is unchanged");
}
}
Ok(())
}
/// How the update landed, read from the `luxe` a shell would run now.
#[derive(Debug, PartialEq, Eq)]
enum Outcome {
/// It reports the new version
Updated,
/// `PATH` finds another copy first: the update went to one file and the shell runs another
Shadowed { found: PathBuf, updated: PathBuf },
/// The same copy still reports an older version: the package did not have the release yet
NotYet { reported: String },
/// No `luxe` on `PATH`, or none that says its version
Unknown,
}
/// Judges the result from what was found on `PATH`, the copy that ran the update, what the found
/// one reports, and the version the update was for.
fn outcome(found: Option<&Path>, updated: &Path, reported: Option<&str>, latest: &str) -> Outcome {
let Some(found) = found else { return Outcome::Unknown };
if reported.is_some_and(|reported| !update::is_newer(latest, reported)) {
return Outcome::Updated;
}
let same = |a: &Path, b: &Path| {
a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(a, b)| a == b)
};
if !same(found, updated) {
return Outcome::Shadowed { found: found.to_path_buf(), updated: updated.to_path_buf() };
}
match reported {
Some(reported) => Outcome::NotYet { reported: reported.to_string() },
None => Outcome::Unknown,
}
}
/// The `luxe` a shell would run now, and the outcome it shows.
async fn installed_now(latest: &str) -> 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)
}
/// The version `path --version` prints, as `luxe 0.2.0`.
async fn version_of(path: &Path) -> Option<String> {
let output = tokio::process::Command::new(path).arg("--version").output().await.ok()?;
parse_version(&String::from_utf8_lossy(&output.stdout))
}
/// The version in `--version` output: its last word, when that is semver.
fn parse_version(output: &str) -> Option<String> {
let word = update::normalize_version(output.split_whitespace().last()?);
semver::Version::parse(word).is_ok().then(|| word.to_string())
}
/// Says how it went; an update that did not take effect is an error, so a script can tell.
fn report(outcome: Outcome) -> anyhow::Result<()> {
match outcome {
Outcome::Updated => println!("Updated. Start the new version with `luxe`."),
Outcome::Unknown => println!("The update finished. `luxe --version` will confirm it."),
Outcome::Shadowed { found, updated } => bail!(
"the update went to {}, but `luxe` on your PATH is {}; remove that copy, or put the \
updated one's directory first on PATH",
updated.display(),
found.display()
),
Outcome::NotYet { reported } => bail!(
"the update finished, but `luxe --version` still says {reported}; the new release may \
not have reached your package manager yet, so try again in a while"
),
}
Ok(())
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,69 @@
use super::*;
/// Two files in a temporary directory: the copy the update ran from, and another.
fn copies() -> (tempfile::TempDir, PathBuf, PathBuf) {
let dir = tempfile::tempdir().expect("tempdir");
let updated = dir.path().join("updated-luxe");
let other = dir.path().join("other-luxe");
for path in [&updated, &other] {
std::fs::write(path, b"").expect("a stand-in binary");
}
(dir, updated, other)
}
#[test]
fn the_version_is_the_last_word_when_it_is_semver() {
assert_eq!(parse_version("luxe 0.2.0\n").as_deref(), Some("0.2.0"));
assert_eq!(parse_version("luxe v0.2.0").as_deref(), Some("0.2.0"));
assert_eq!(parse_version("luxe nightly"), None);
assert_eq!(parse_version(""), None);
}
/// The new version reported, or one past it, is a finished update.
#[test]
fn a_copy_reporting_the_new_version_is_updated() {
let (_dir, updated, _) = copies();
assert_eq!(outcome(Some(&updated), &updated, Some("0.2.0"), "0.2.0"), Outcome::Updated);
assert_eq!(outcome(Some(&updated), &updated, Some("0.2.1"), "0.2.0"), Outcome::Updated);
}
/// The loop Codex CLI's users hit: the update lands in one file and the shell runs another.
#[test]
fn another_copy_first_on_path_is_named() {
let (_dir, updated, other) = copies();
let shadowed = outcome(Some(&other), &updated, Some("0.1.0"), "0.2.0");
assert_eq!(shadowed, Outcome::Shadowed { found: other, updated });
}
/// A symlink to the copy that updated is that copy, as the development install's is, so an old
/// version there means the package was behind, not that a second copy is in the way.
#[cfg(unix)]
#[test]
fn a_link_to_the_updated_copy_is_the_same_copy() {
let (dir, updated, _) = copies();
let link = dir.path().join("luxe");
std::os::unix::fs::symlink(&updated, &link).expect("symlink");
let behind = outcome(Some(&link), &updated, Some("0.1.0"), "0.2.0");
assert_eq!(behind, Outcome::NotYet { reported: "0.1.0".into() });
}
#[test]
fn no_luxe_on_path_or_no_version_cannot_be_judged() {
let (_dir, updated, _) = copies();
assert_eq!(outcome(None, &updated, None, "0.2.0"), Outcome::Unknown);
assert_eq!(outcome(Some(&updated), &updated, None, "0.2.0"), Outcome::Unknown);
}
/// 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);
assert!(check.contains("luxe update") && check.contains("cargo install"), "{check}");
let download = instructions(InstallSource::Archive, false, 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}"
);
}

View File

@@ -481,6 +481,7 @@ script can tell a failure from an answer without reading the output.
| `luxe loop fresh` | Reset the run's turn count; see [Autonomous runs](loop.md#start-a-run) |
| `luxe docs [page]` | Read this guide, offline and for the installed version. `--search <words>` finds lines across every page. |
| `luxe doctor` | Check which tools, language servers and debug adapters work |
| `luxe update` | Update Luxe with the command for however it was installed; see [Updates](configuration.md#updates). `--check` only reports. |
| `luxe init` | Set up a theme, a provider, the tools and the start screen, and write them to `~/.config/luxe/config.json`. `--defaults` skips the questions, `--force` starts from an empty file; see [Editing](configuration.md#editing). |
| `luxe wire <log>` | Summarize a `LUXE_WIRE_LOG` capture; see [Troubleshooting](troubleshooting.md#see-what-is-sent-to-the-model). `--tools` breaks the tool schemas' size down per tool. |
@@ -555,6 +556,7 @@ words of it you have typed, like `pr` in `/diff pr 142`. A command that stays pl
| `/auth` | Which providers you are signed in to, and how |
| `/reload` | Re-read your config and keys without restarting |
| `/quit` | Leave Luxe. The session is already saved. |
| `/update` | Leave Luxe and update it, as `luxe update` does |
The Command Palette also lists commands with no slash form, such as **Copy message**, **Swap the
sidebar's side** and, in a review, **Send comments**.
@@ -844,17 +846,33 @@ This is local to your machine and on by default. Outside herdr nothing is sent.
{ "herdr": false }
```
### Update notice
### Updates
Once a day, Luxe checks whether a newer release exists and says so on the start screen, with the
command to update. Luxe never updates itself. The check sends nothing about you or your machine; the
comparison happens locally.
Once a day, Luxe checks whether a newer release exists, and when one does the start screen says
*Update available · /update*. The check sends nothing about you or your machine; the comparison
happens locally.
`/update`, or `luxe update` in a shell, updates Luxe with the command for however you installed
it, showing each one before it runs:
| Installed with | `luxe update` runs |
| --- | --- |
| Cargo | `cargo install --locked --force luxe-cli` |
| Homebrew | `brew update`, then `brew upgrade luxe` |
Luxe never downloads or replaces its own program; the package manager that installed it does. A
copy your system's package manager owns is left to it, and a downloaded one points you at the
releases page. On Windows, Luxe can't be replaced while it runs, so it prints the command to run
once it has exited. Afterwards it checks that the `luxe` your shell finds is the new version, and
says so if another copy earlier on your `PATH` is in the way. `luxe update --check` only reports.
To stop the daily check:
```json title="~/.config/luxe/config.json"
{ "update": { "check": false } }
```
`LUXE_UPDATE_CHECK=0` turns it off as well.
`LUXE_UPDATE_CHECK=0` turns it off as well. `luxe update` still checks when you run it.
### Launchers
@@ -2121,8 +2139,9 @@ luxe --version
This installs the `luxe` command. You need a recent stable Rust; [rustup](https://rustup.rs)
installs one.
To update, run the same command with `--force`. Luxe checks once a day for a newer release and says
so on the start screen; see [Update notice](configuration.md#update-notice) to turn that off.
To update, run `luxe update`, or `/update` inside Luxe. Luxe checks once a day for a newer release
and says so on the start screen; see [Updates](configuration.md#updates) for how it updates and how
to turn the check off.
## Build from source
@@ -4231,7 +4250,8 @@ There is no telemetry. Luxe connects only to:
2. Search providers and web pages, when the agent uses `web_search` or `web_fetch`, and GitHub
when `web_fetch` clones a repository (`"tools": { "clone_repositories": false }` stops it)
3. The models.dev catalog, to refresh model details (`LUXE_MODELS_DEV_REFRESH=0` stops it)
4. The update check, once a day (`"update": { "check": false }` stops it)
4. The update check, once a day (`"update": { "check": false }` stops it), and when you run
`luxe update` or `/update`, which then runs your package manager's own update
5. GitHub, through your own `gh`, when you, the agent or an [RPC client](rpc.md#github-writes) work
with pull requests and issues. A client can write there only if you start it with
`--github-writes`.

View File

@@ -74,10 +74,7 @@ pub(crate) fn spawn_check(repo_root: &std::path::Path) {
if !UpdateState::load(&path).is_stale(update::CHECK_TTL) {
return;
}
let url = std::env::var("LUXE_UPDATE_URL")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| update::RELEASE_MANIFEST_URL.to_string());
let url = manifest_url();
tokio::spawn(async move {
// The timestamp moves whether or not the fetch worked, so an unreachable endpoint is
@@ -93,6 +90,27 @@ pub(crate) fn spawn_check(repo_root: &std::path::Path) {
});
}
/// Asks the manifest now, whatever the cache says, and records the answer: the reader asked, as
/// `luxe update` does, so neither the daily cadence nor the opt-out applies. The request is the
/// same anonymous one the daily check makes.
pub(crate) async fn check_now() -> Result<String, String> {
let latest = fetch_latest(&manifest_url()).await?;
let path = state_path();
let state = UpdateState { latest: Some(latest.clone()), checked_at: now_secs() };
if let Err(error) = state.store(&path) {
tracing::debug!(%error, path = %path.display(), "could not cache the update check");
}
Ok(latest)
}
/// The release manifest, with `LUXE_UPDATE_URL` as a test seam.
fn manifest_url() -> String {
std::env::var("LUXE_UPDATE_URL")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| update::RELEASE_MANIFEST_URL.to_string())
}
/// Seconds since the epoch, or 0 if the clock is unreadable (which reads as "never checked").
fn now_secs() -> u64 {
std::time::SystemTime::now()
@@ -230,6 +248,25 @@ mod tests {
std::env::remove_var("LUXE_UPDATE_CHECK");
}
/// `luxe update` asks whatever the cadence and the opt-out say, since the reader asked, and
/// what it learns is cached, so the start screen agrees with it.
#[tokio::test]
async fn an_asked_for_check_ignores_the_opt_out_and_caches_the_answer() {
let dir = tempfile::tempdir().expect("tempdir");
let cache = dir.path().join("update.json");
std::env::set_var("LUXE_UPDATE_PATH", &cache);
std::env::set_var("LUXE_UPDATE_CHECK", "0");
std::env::set_var(
"LUXE_UPDATE_URL",
serve_once(r#"{"tag_name":"v99.0.0"}"#, "200 OK").await,
);
assert_eq!(check_now().await.as_deref(), Ok("99.0.0"));
assert_eq!(UpdateState::load(&cache).latest.as_deref(), Some("99.0.0"));
for name in ["LUXE_UPDATE_PATH", "LUXE_UPDATE_CHECK", "LUXE_UPDATE_URL"] {
std::env::remove_var(name);
}
}
/// Both manifest shapes resolve, so moving off the GitHub API later is a URL change rather
/// than a code change.
#[test]

View File

@@ -1,9 +1,10 @@
//! Update notice — whether a newer Luxe exists, and what *this* user should run to get it.
//!
//! Luxe does not update itself. What it does is notice that it is behind and say so once, in the
//! dashboard footer, naming the command that matches how this copy was installed. Telling somebody
//! who installed through Homebrew to run `cargo install --force` is worse than saying nothing: it
//! is wrong, and following it leaves them with two Luxes and no idea which one is on `PATH`.
//! Luxe never rewrites its own binary. It notices that it is behind and says so in the dashboard
//! footer, and on request runs the update command that matches how this copy was installed, so
//! the install's owner does the replacing. Telling somebody who installed through Homebrew to run
//! `cargo install --force` is worse than saying nothing: it is wrong, and following it leaves them
//! with two Luxes and no idea which one is on `PATH`.
//!
//! Everything here is pure or reads a local file. The one network call lives in `luxe-cli`, which
//! is where outbound requests belong; this module only decides what to make of the answer. That
@@ -82,12 +83,17 @@ impl InstallSource {
Self::Archive
}
/// What to tell the reader to run, or `None` when the honest answer is "however you installed
/// it". A wrong command is worse than an absent one, so this refuses to guess.
pub fn update_command(&self) -> Option<&'static str> {
/// The commands that update this install, in order, each as a program and its arguments, or
/// `None` when the honest answer is "however you installed it". A wrong command is worse than
/// an absent one, so this refuses to guess.
///
/// Run directly rather than through a shell, so nothing in them is ever interpreted. Homebrew
/// refreshes its index first, or `upgrade` can find nothing newer than the release the notice
/// already read; cargo installs `--locked`, the dependency versions the release was tested with.
pub fn update_steps(&self) -> Option<&'static [&'static [&'static str]]> {
match self {
Self::Cargo => Some("cargo install --force luxe-cli"),
Self::Homebrew => Some("brew upgrade luxe"),
Self::Cargo => Some(&[&["cargo", "install", "--locked", "--force", "luxe-cli"]]),
Self::Homebrew => Some(&[&["brew", "update"], &["brew", "upgrade", "luxe"]]),
// Which package manager owns it is not knowable without querying one, and guessing
// `apt` on an Arch machine is the failure this whole function exists to avoid.
Self::SystemPackage => None,
@@ -95,6 +101,12 @@ impl InstallSource {
}
}
/// [`Self::update_steps`] as one line a person could type: the steps joined with `&&`.
pub fn update_command(&self) -> Option<String> {
let steps = self.update_steps()?;
Some(steps.iter().map(|step| step.join(" ")).collect::<Vec<_>>().join(" && "))
}
/// The advice, as a sentence fragment that follows "— ".
pub fn advice(&self) -> String {
match self.update_command() {

View File

@@ -9,7 +9,26 @@ fn a_cargo_install_is_told_to_use_cargo() {
] {
assert_eq!(InstallSource::from_path(Path::new(path)), InstallSource::Cargo, "{path}");
}
assert_eq!(InstallSource::Cargo.update_command(), Some("cargo install --force luxe-cli"));
assert_eq!(
InstallSource::Cargo.update_command().as_deref(),
Some("cargo install --locked --force luxe-cli")
);
}
/// The steps are what runs, one program at a time with no shell between, so they are pinned as
/// argument lists: a flag moved into the wrong step, or a shell operator turned into an argument,
/// would read the same in the joined line and run very differently.
#[test]
fn the_update_steps_are_the_owners_own_commands() {
let cargo: &[&[&str]] = &[&["cargo", "install", "--locked", "--force", "luxe-cli"]];
let brew: &[&[&str]] = &[&["brew", "update"], &["brew", "upgrade", "luxe"]];
assert_eq!(InstallSource::Cargo.update_steps(), Some(cargo));
assert_eq!(InstallSource::Homebrew.update_steps(), Some(brew));
assert_eq!(
InstallSource::Homebrew.update_command().as_deref(),
Some("brew update && brew upgrade luxe")
);
assert_eq!(InstallSource::Archive.update_steps(), None, "a download has no owner to ask");
}
/// Homebrew is checked first because its Linux and Intel-macOS prefixes sit *inside* paths the
@@ -91,7 +110,7 @@ fn a_notice_names_both_versions_and_the_command() {
let line = notice.line();
assert!(line.contains("0.2.0"), "{line}");
assert!(line.contains("you have 0.1.0"), "{line}");
assert!(line.contains("cargo install --force luxe-cli"), "{line}");
assert!(line.contains("cargo install --locked --force luxe-cli"), "{line}");
}
#[test]

View File

@@ -21,6 +21,7 @@ pub(super) fn run_slash(app: &mut App, cmd: &crate::commands::Command) -> bool {
}
}
id::SESSIONS => app.open_sessions(),
id::UPDATE => app.outbox.update = true,
id::MODEL => {
// Opens the searchable model picker (also reachable from the palette). Selecting a
// model sends `Action::SetModel`, switching the active model in-session.

View File

@@ -122,6 +122,8 @@ fn run_command(app: &mut App, command: crate::commands::Command) {
// The mode outlives the session, so it is chosen here rather than in a session made for it
id::MODE => super::commands::dispatch(app, command),
id::SESSIONS => app.open_sessions(),
// Leaves Luxe, so a session started for it would only be left empty
id::UPDATE => app.outbox.update = true,
_ if command.slash_name() == Some("/quit") => {
app.should_quit = true;
}

View File

@@ -25,6 +25,8 @@ pub struct Outbox {
pub issue: Option<u64>,
/// A session of yours to leave this one for, and what the reader carries into it
pub resume: Option<crate::main_loop::ResumeLaunch>,
/// Whether to leave and update Luxe
pub update: bool,
/// Text to hand to the reader's editor and bring back
pub text_edit: Option<TextEdit>,
/// A file or folder to open in the reader's editor
@@ -45,7 +47,8 @@ pub struct Outbox {
impl Outbox {
/// The exit the parked asks end the TUI with, taking them all; when several are parked the
/// last of an editor file, a worktree removal, an issue, a resume and a pull request fix wins.
/// last of an editor file, a worktree removal, an issue, a resume, a pull request fix and an
/// update wins.
pub fn exit(&mut self) -> Option<TuiExit> {
[
self.editor_file.take().map(TuiExit::OpenInEditor),
@@ -53,6 +56,7 @@ impl Outbox {
self.issue.take().map(TuiExit::TakeUpIssue),
self.resume.take().map(TuiExit::ResumeSession),
self.pull_request_fix.take().map(TuiExit::FixPullRequest),
std::mem::take(&mut self.update).then_some(TuiExit::Update),
]
.into_iter()
.flatten()
@@ -93,6 +97,10 @@ mod tests {
..Outbox::default()
};
assert_eq!(everything.exit(), Some(TuiExit::FixPullRequest(fix)));
// An update asked for after a fix is the one taken, and taken once
let mut update = Outbox { issue: Some(7), update: true, ..Outbox::default() };
assert_eq!(update.exit(), Some(TuiExit::Update));
assert_eq!(update.exit(), None);
let mut removal_then_issue = Outbox {
worktree_removal: Some(PathBuf::from("/work/.luxe/worktrees/x")),
issue: Some(7),

View File

@@ -381,6 +381,34 @@ fn the_mode_command_on_the_start_screen_stays_on_it() {
assert!(matches!(actions.as_slice(), [Action::SetMode(mode)] if mode == "plan"), "{actions:?}");
}
/// `/update` on the start screen leaves Luxe for the CLI's update, which needs the terminal, and
/// starts no session on the way out.
#[test]
fn the_update_command_on_the_start_screen_leaves_to_update() {
let (tx, mut rx) = mpsc::channel(100);
let mut app = App::new(tx, KeyMap::defaults(), Default::default());
app.enter_dashboard(crate::dashboard::DashboardState::new(Vec::new()));
let update = crate::commands::CommandRegistry::all().parse_slash("/update").expect("it");
app.handle_dashboard_outcome(crate::dashboard::DashOutcome::RunCommand(update));
let mut exit = crate::main_loop::TuiExit::Quit;
crate::main_loop::collect_exit_for_tests(&mut app, &mut exit);
assert_eq!(exit, crate::main_loop::TuiExit::Update);
assert!(app.should_quit);
assert!(rx.try_recv().is_err(), "no session started for it");
}
/// From a session, `/update` typed in the composer leaves the same way.
#[test]
fn the_update_command_in_a_session_leaves_to_update() {
let (tx, _rx) = mpsc::channel(100);
let mut app = App::new(tx, KeyMap::defaults(), Default::default());
app.editor.insert_text("/update");
app.update(Msg::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)));
let mut exit = crate::main_loop::TuiExit::Quit;
crate::main_loop::collect_exit_for_tests(&mut app, &mut exit);
assert_eq!(exit, crate::main_loop::TuiExit::Update);
}
/// Setup's answers reach the reader's file one key at a time, and skipping writes a file that
/// chooses nothing, so the first run asks once.
#[tokio::test]

View File

@@ -19,6 +19,13 @@ pub(super) fn built_in() -> Vec<Command> {
.with_slash("/quit")
.summary("Leaves Luxe; the session is saved as it goes, so nothing is lost.")
.keywords(&["exit", "close"]),
Command::slash(id::UPDATE, "Update Luxe", "/update")
.summary("Quits Luxe and updates it with the command for however you installed it.")
.detail(
"The same as `luxe update`: each command is shown before it runs, in this \
terminal. A copy your system's package manager owns is left to it.",
)
.keywords(&["upgrade", "version", "release", "new"]),
Command::action(UiAction::Reload)
.with_slash("/reload")
.summary("Re-reads your config and keybindings without restarting.")

View File

@@ -34,4 +34,5 @@ pub(crate) const STATUSLINE: &str = "cmd.statusline";
pub(crate) const THEME: &str = "cmd.theme";
pub(crate) const THINKING: &str = "cmd.thinking";
pub(crate) const TOOLS: &str = "cmd.tools";
pub(crate) const UPDATE: &str = "cmd.update";
pub(crate) const WORKTREE: &str = "cmd.worktree";

View File

@@ -8,10 +8,8 @@ mod motion;
mod parts;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
pub(crate) use layout::TextLayout;
pub use layout::VisualCursor;
#[cfg(test)]
use layout::VisualSegment;
pub(crate) use layout::{TextLayout, VisualSegment};
use motion::text_command;
pub use parts::AttachedImage;
use parts::{shift_offset, PromptPart, PromptPartKind};

View File

@@ -67,6 +67,8 @@ pub enum TuiExit {
///
/// Args: `(launch)` — the session, and the draft and mode the reader carries into it.
ResumeSession(ResumeLaunch),
/// Leave Luxe and run `luxe update`, which needs the terminal for the package manager.
Update,
}
/// A pull request to fix in a new session, and the comments written reading it, which become the

View File

@@ -176,6 +176,7 @@ fn prompt_budget(available: u16, rows: &[LaidOutRow]) -> usize {
usize::from(available).saturating_sub(chrome_and_rows(rows)).clamp(1, MAX_PROMPT_ROWS)
}
mod answer;
mod rows;
mod state;

View File

@@ -0,0 +1,84 @@
//! Answer — the typed answer while it is being written: its rows, its selection, and the caret.
//!
//! The answer is the composer's [`crate::editor::Editor`], so it is drawn from the editor's own
//! wrap: the rows the reader sees are the rows up and down move through.
use super::QuestionPromptState;
use crate::editor::{Editor, TextLayout, VisualSegment};
use ratatui::style::Style;
use ratatui::text::Span;
/// The glyph drawn where typing lands.
const CARET: &str = "▏";
/// The rows of the answer being typed that fit in `max_rows`, the caret drawn where typing lands,
/// and whether rows above were scrolled off.
///
/// Each row keeps a cell for the caret, and a scrolled answer one more for the mark that says so.
/// The width it wrapped at is recorded on the state, so up and down move through these rows.
pub(super) fn editing_rows(
state: &QuestionPromptState,
room: usize,
max_rows: usize,
(text, selected): (Style, Style),
) -> (Vec<Vec<Span<'static>>>, bool) {
let editor = state.answer();
let max_rows = max_rows.max(1);
let (width, layout) = fit(editor, room, max_rows);
state.set_answer_width(width);
let caret = editor.cursor_in(&layout);
// The window follows the caret, so the row being typed in is always on screen
let first = caret.row.saturating_sub(max_rows - 1);
let rows = layout.rows()[first..]
.iter()
.take(max_rows)
.enumerate()
.map(|(offset, segments)| {
let at = (first + offset == caret.row).then_some(caret.column);
row_spans(segments, at, text, selected)
})
.collect();
(rows, first > 0)
}
/// The width the answer wraps at, and its wrap: a cell short of `room` for the caret, and one more
/// when it takes more than `max_rows` and needs the scrolled mark.
fn fit(editor: &Editor, room: usize, max_rows: usize) -> (u16, TextLayout) {
let cells = |width: usize| u16::try_from(width.max(1)).unwrap_or(u16::MAX);
let width = cells(room.saturating_sub(1));
let layout = editor.layout(width);
if layout.row_count() <= max_rows {
return (width, layout);
}
let width = cells(room.saturating_sub(2));
(width, editor.layout(width))
}
/// One row's spans, the selection lit and the caret set before the cell at column `caret`.
fn row_spans(
segments: &[VisualSegment],
caret: Option<usize>,
text: Style,
selected: Style,
) -> Vec<Span<'static>> {
let mut spans = Vec::new();
let mut column = 0usize;
for segment in segments {
let style = if segment.is_selected { text.patch(selected) } else { text };
let mut run = String::new();
for character in segment.text.chars() {
if caret == Some(column) {
spans.push(Span::styled(std::mem::take(&mut run), style));
spans.push(Span::styled(CARET, text));
}
run.push(character);
column += unicode_width::UnicodeWidthChar::width(character).unwrap_or(0);
}
spans.push(Span::styled(run, style));
}
if caret.is_some_and(|at| at >= column) {
spans.push(Span::styled(CARET, text));
}
spans.retain(|span| !span.content.is_empty());
spans
}

View File

@@ -68,22 +68,31 @@ fn row_content(
// truncating: an answer cut off at the right edge is one the reader cannot check
// before sending it.
None => {
let body = if state.editing() {
format!("{}▏", state.custom())
} else if state.custom().is_empty() {
CUSTOM_PLACEHOLDER.to_string()
} else {
state.custom().to_string()
};
let number = format!("{}. ", i + 1);
// The text column, wherever a longer number puts it
let text_at = indent + number.chars().count().saturating_sub(3);
let room = text_width.saturating_sub(text_at);
let (mut wrapped, scrolled) = custom_view(&body, room, custom_rows, state.editing());
let (mut wrapped, scrolled) = match state.editing() {
true => {
let styles = (label_style, theme.selected_bg);
super::answer::editing_rows(state, room, custom_rows, styles)
}
false => {
let body = match state.custom() {
"" => CUSTOM_PLACEHOLDER,
typed => typed,
};
let rows = wrapped_rows(body, room, custom_rows);
(
rows.into_iter().map(|row| vec![Span::styled(row, label_style)]).collect(),
false,
)
}
};
// An answer of nothing but spaces still owns a row: it is the one the cursor
// can land on, and the click regions are laid out over the rows there are.
if wrapped.is_empty() {
wrapped.push(String::new());
wrapped.push(Vec::new());
}
for (index, row) in wrapped.into_iter().enumerate() {
let mut line = if index == 0 {
@@ -99,7 +108,7 @@ fn row_content(
let lead = if index == 0 { "…" } else { " " };
line.push(Span::styled(lead, cursor_style));
}
line.push(Span::styled(row, label_style));
line.extend(row);
content.push(line);
}
}
@@ -176,24 +185,3 @@ pub(super) fn wrapped_rows(text: &str, width: usize, max_rows: usize) -> Vec<Str
}
rows
}
/// The rows of a typed answer that fit, and whether any were left above them.
///
/// While the row is being edited the caret is what has to stay on screen, so the window follows
/// the tail of the answer; at rest it reads from the top like any other text, with the usual
/// clipped-tail mark.
fn custom_view(text: &str, width: usize, max_rows: usize, editing: bool) -> (Vec<String>, bool) {
if !editing {
return (wrapped_rows(text, width, max_rows), false);
}
if max_rows == 0 {
return (Vec::new(), false);
}
let rows = wrap_rows(text, width);
if rows.len() <= max_rows {
return (rows, false);
}
// a cell short, for the mark that says there is more above
let mut rows = wrap_rows(text, width.saturating_sub(1));
(rows.split_off(rows.len() - max_rows), true)
}

View File

@@ -1,7 +1,9 @@
//! Question prompt state — which row the cursor is on, what is checked, and what a key does.
use crate::editor::Editor;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use luxe_core::question::{default_selection, QuestionOption, QuestionRequestId};
use std::cell::Cell;
/// State for an in-flight question modal (one at a time — tools dispatch sequentially).
#[derive(Clone, Debug)]
@@ -18,9 +20,11 @@ pub struct QuestionPromptState {
selected: usize,
/// Per-option checkbox state (multi-select only).
checked: Vec<bool>,
/// The user's free-text answer.
custom: String,
/// Whether the free-text row is being edited (keystrokes append to `custom`).
/// The user's free-text answer: the composer's editor, so the caret moves and edits where it is.
custom: Editor,
/// Cells the answer last wrapped at on screen, so up and down move through the rows drawn.
answer_width: Cell<u16>,
/// Whether the free-text row is being edited (keystrokes go to `custom`).
editing: bool,
/// Whether the typed answer is checked (multi-select): typing checks it, Space toggles it.
custom_checked: bool,
@@ -53,7 +57,8 @@ impl QuestionPromptState {
multi,
selected,
checked,
custom: String::new(),
custom: Editor::new(),
answer_width: Cell::new(u16::MAX),
editing: false,
custom_checked: false,
}
@@ -77,16 +82,26 @@ impl QuestionPromptState {
/// Whether row `i` is checked (multi-select), the typed answer included.
pub fn is_checked(&self, i: usize) -> bool {
if i == self.custom_row() {
return self.custom_checked && !self.custom.trim().is_empty();
return self.custom_checked && !self.custom().trim().is_empty();
}
self.checked.get(i).copied().unwrap_or(false)
}
/// The current free-text entry.
pub fn custom(&self) -> &str {
self.custom.current_input()
}
/// The free-text entry's editor, for drawing it with its caret and selection.
pub(crate) fn answer(&self) -> &Editor {
&self.custom
}
/// Records the width the answer was just drawn at; up and down wrap it the same way.
pub(super) fn set_answer_width(&self, width: u16) {
self.answer_width.set(width);
}
/// Whether the free-text row is in edit mode.
pub fn editing(&self) -> bool {
self.editing
@@ -99,7 +114,7 @@ impl QuestionPromptState {
return;
}
self.start_typing();
self.custom.push_str(&text);
self.custom.insert_text(&text);
}
/// Move the cursor to `index` (a hover or a click), clamped to range.
@@ -136,7 +151,7 @@ impl QuestionPromptState {
/// A single answer is one answer. Text left in the typed row while picking another option used
/// to ride along with it, which made a choice and an abandoned draft one reply.
fn collect(&self, option: Option<usize>) -> Vec<String> {
let custom = self.custom.trim();
let custom = self.custom().trim();
if !self.multi {
return match option {
Some(i) => vec![self.options[i].label.clone()],
@@ -206,7 +221,7 @@ impl QuestionPromptState {
if self.multi {
QuestionPromptOutcome::Answer(self.collect(None))
} else if self.selected == self.custom_row() {
if self.custom.trim().is_empty() {
if self.custom().trim().is_empty() {
self.editing = true;
QuestionPromptOutcome::Consumed
} else {
@@ -217,9 +232,9 @@ impl QuestionPromptState {
}
}
// Start typing anywhere jumps into the free-text row.
KeyCode::Char(c) if !ctrl => {
KeyCode::Char(_) if !ctrl => {
self.start_typing();
self.custom.push(c);
self.custom.handle_key(*key);
QuestionPromptOutcome::Consumed
}
_ => QuestionPromptOutcome::Consumed,
@@ -234,31 +249,56 @@ impl QuestionPromptState {
QuestionPromptOutcome::Consumed
}
KeyCode::Char('c') if ctrl => {
self.custom.clear();
QuestionPromptOutcome::Consumed
}
KeyCode::Backspace => {
self.custom.pop();
self.custom.select_all();
self.custom.delete_selection();
QuestionPromptOutcome::Consumed
}
KeyCode::Up | KeyCode::Down => self.vertical_in_answer(key),
// The answer is one reply on one line, and Tab means nothing in it
KeyCode::Tab | KeyCode::BackTab => QuestionPromptOutcome::Consumed,
// Every Enter, Shift+Enter's newline included, is the question's to answer
KeyCode::Enter => {
if self.multi {
// Commit the text and submit everything checked plus the free text.
self.editing = false;
QuestionPromptOutcome::Answer(self.collect(None))
} else if self.custom.trim().is_empty() {
} else if self.custom().trim().is_empty() {
self.editing = false;
QuestionPromptOutcome::Consumed
} else {
QuestionPromptOutcome::Answer(self.collect(None))
}
}
KeyCode::Char(c) if !ctrl => {
self.custom.push(c);
self.custom_checked = true;
// Typing, deleting and every caret motion are the composer's own
_ => {
let before = self.custom().len();
self.custom.handle_key(*key);
if self.custom().len() > before {
self.custom_checked = true;
}
QuestionPromptOutcome::Consumed
}
_ => QuestionPromptOutcome::Consumed,
}
}
/// Up and down move through the rows the answer wraps to; from its first row up, or its last
/// row down, they leave it for the options, as the launcher hands its arrows to the list.
/// Shift always stays in the answer, where it is selecting.
fn vertical_in_answer(&mut self, key: &KeyEvent) -> QuestionPromptOutcome {
self.custom.set_viewport_width(self.answer_width.get());
let up = key.code == KeyCode::Up;
let edge =
if up { self.custom.cursor_on_first_row() } else { self.custom.cursor_on_last_row() };
if edge && !key.modifiers.contains(KeyModifiers::SHIFT) {
self.editing = false;
if up {
self.move_up();
} else {
self.move_down();
}
} else {
self.custom.handle_key(*key);
}
QuestionPromptOutcome::Consumed
}
}

View File

@@ -543,3 +543,84 @@ fn the_measured_height_is_the_height_it_draws() {
}
assert_eq!(height(&s, &theme, 0, 20), 0, "no width, no panel");
}
fn type_answer(state: &mut QuestionPromptState, text: &str) {
for c in text.chars() {
state.on_key(&key(KeyCode::Char(c)));
}
}
/// The typed answer edits where its caret is: the arrows move it, and typing, Backspace and Delete
/// act there rather than at the end of the text.
#[test]
fn the_typed_answer_edits_at_its_caret() {
let mut state = state(false);
type_answer(&mut state, "helo");
state.on_key(&key(KeyCode::Left));
state.on_key(&key(KeyCode::Left));
state.on_key(&key(KeyCode::Char('l')));
assert_eq!(state.custom(), "hello");
state.on_key(&key(KeyCode::Home));
state.on_key(&key(KeyCode::Delete));
assert_eq!(state.custom(), "ello", "delete takes the character after the caret");
state.on_key(&key(KeyCode::End));
state.on_key(&key(KeyCode::Backspace));
assert_eq!(state.custom(), "ell");
assert!(state.editing(), "none of that left the answer");
}
/// A word jump moves through the answer the way it does in the composer.
#[test]
fn a_word_jump_moves_through_the_typed_answer() {
let mut state = state(false);
type_answer(&mut state, "one two");
state.on_key(&KeyEvent::new(KeyCode::Left, KeyModifiers::ALT));
type_answer(&mut state, "big ");
assert_eq!(state.custom(), "one big two");
}
/// Up and down move through the rows a long answer wraps to, and up from its first row leaves the
/// answer for the option above, the way the launcher hands its arrows to the list.
#[test]
fn up_and_down_move_through_a_wrapped_answer_then_leave_it() {
let mut state = state(false);
type_answer(&mut state, "alpha beta gamma delta epsilon zeta eta theta iota kappa");
// Drawn once, so the answer has wrapped at the panel's width
render(&state, 30, 24);
let end = state.answer().cursor();
state.on_key(&key(KeyCode::Up));
assert!(state.editing() && state.answer().cursor() < end, "up reached the row above");
state.on_key(&key(KeyCode::Down));
assert_eq!(state.answer().cursor(), end, "and down came back");
// Bounded, so a regression that never leaves fails rather than hangs
for _ in 0..10 {
if state.editing() {
state.on_key(&key(KeyCode::Up));
}
}
assert!(!state.editing(), "up from the first row leaves the answer");
assert_eq!(state.selected(), 1, "for the option above it");
}
/// An answer short enough for one row has nowhere to go: down leaves it at once.
#[test]
fn down_from_a_one_row_answer_leaves_it() {
let mut state = state(false);
type_answer(&mut state, "short");
render(&state, 60, 24);
state.on_key(&key(KeyCode::Down));
assert!(!state.editing());
assert_eq!(state.selected(), 0, "down from the last row wraps to the first option");
}
/// The caret is drawn where typing lands, not after the last character.
#[test]
fn the_caret_is_drawn_where_typing_lands() {
let mut state = state(false);
type_answer(&mut state, "abc");
state.on_key(&key(KeyCode::Left));
let (text, _) = render(&state, 60, 12);
assert!(text.contains("ab▏c"), "the caret sits before the c: {text}");
}

View File

@@ -64,9 +64,9 @@ ChatTurn@64x20: frame=91595c7c8fb3a9de hits=bc965e96875bbfe6
ChatPermission@140x44: frame=54ddeb5522ffcb19 hits=063b591e442cd221
ChatPermission@100x30: frame=b2c0e21530b64523 hits=200049ec7749eeb8
ChatPermission@64x20: frame=9f98f5664f85406f hits=abbd7bfaa97a4ed0
ChatPalette@140x44: frame=2563eb3755b4caff hits=bf9355f178f8e332
ChatPalette@100x30: frame=ef4b4b78ce5ecf34 hits=eae72d9c1c194fee
ChatPalette@64x20: frame=77258679e0458932 hits=888344c2d380ae7f
ChatPalette@140x44: frame=3022f8834ce418f2 hits=bf9355f178f8e332
ChatPalette@100x30: frame=cacc9b3e033c0401 hits=eae72d9c1c194fee
ChatPalette@64x20: frame=085c324962ef0357 hits=888344c2d380ae7f
ChatScreenshot@140x44: frame=5aec1b106f841d81 hits=1489393a2950d711
ChatScreenshot@100x30: frame=709f9e4b32a7c8f6 hits=f8537762de7b55a2
ChatScreenshot@64x20: frame=0a22c420e0e4092e hits=1e33d25e6f2a5032
@@ -178,7 +178,7 @@ ChangesFailed@64x20: frame=69cdcefbe785c866 hits=27476cdcd9937bea
ChangesExternal@140x44: frame=fc75aaae10ddb262 hits=d5c3115642e748ad
ChangesExternal@100x30: frame=522c8250b0f50ac4 hits=3dd17e6200cfb4b5
ChangesExternal@64x20: frame=a6d2706231364207 hits=6f0e8da295aaa965
ChatTools+palette: frame=96a7e733812fba95 hits=ca2a2a735278a5bd
ChatTools+palette: frame=85cc5ae977de2fa6 hits=ca2a2a735278a5bd
ChatTools+slash: frame=a3ce4c3a7d03f8d0 hits=8adf06de80ecdcb2
ChatTools+mention: frame=33c4a73f189a3dcc hits=c1b8d78b51a767b7
ChatTools+model: frame=98b419f1ad7ab1ea hits=c1b8d78b51a767b7

View File

@@ -95,6 +95,7 @@ script can tell a failure from an answer without reading the output.
| `luxe loop fresh` | Reset the run's turn count; see [Autonomous runs](loop.md#start-a-run) |
| `luxe docs [page]` | Read this guide, offline and for the installed version. `--search <words>` finds lines across every page. |
| `luxe doctor` | Check which tools, language servers and debug adapters work |
| `luxe update` | Update Luxe with the command for however it was installed; see [Updates](configuration.md#updates). `--check` only reports. |
| `luxe init` | Set up a theme, a provider, the tools and the start screen, and write them to `~/.config/luxe/config.json`. `--defaults` skips the questions, `--force` starts from an empty file; see [Editing](configuration.md#editing). |
| `luxe wire <log>` | Summarize a `LUXE_WIRE_LOG` capture; see [Troubleshooting](troubleshooting.md#see-what-is-sent-to-the-model). `--tools` breaks the tool schemas' size down per tool. |

View File

@@ -67,6 +67,7 @@ words of it you have typed, like `pr` in `/diff pr 142`. A command that stays pl
| `/auth` | Which providers you are signed in to, and how |
| `/reload` | Re-read your config and keys without restarting |
| `/quit` | Leave Luxe. The session is already saved. |
| `/update` | Leave Luxe and update it, as `luxe update` does |
The Command Palette also lists commands with no slash form, such as **Copy message**, **Swap the
sidebar's side** and, in a review, **Send comments**.

View File

@@ -139,17 +139,33 @@ This is local to your machine and on by default. Outside herdr nothing is sent.
{ "herdr": false }
```
### Update notice
### Updates
Once a day, Luxe checks whether a newer release exists and says so on the start screen, with the
command to update. Luxe never updates itself. The check sends nothing about you or your machine; the
comparison happens locally.
Once a day, Luxe checks whether a newer release exists, and when one does the start screen says
*Update available · /update*. The check sends nothing about you or your machine; the comparison
happens locally.
`/update`, or `luxe update` in a shell, updates Luxe with the command for however you installed
it, showing each one before it runs:
| Installed with | `luxe update` runs |
| --- | --- |
| Cargo | `cargo install --locked --force luxe-cli` |
| Homebrew | `brew update`, then `brew upgrade luxe` |
Luxe never downloads or replaces its own program; the package manager that installed it does. A
copy your system's package manager owns is left to it, and a downloaded one points you at the
releases page. On Windows, Luxe can't be replaced while it runs, so it prints the command to run
once it has exited. Afterwards it checks that the `luxe` your shell finds is the new version, and
says so if another copy earlier on your `PATH` is in the way. `luxe update --check` only reports.
To stop the daily check:
```json title="~/.config/luxe/config.json"
{ "update": { "check": false } }
```
`LUXE_UPDATE_CHECK=0` turns it off as well.
`LUXE_UPDATE_CHECK=0` turns it off as well. `luxe update` still checks when you run it.
### Launchers

View File

@@ -682,7 +682,7 @@
<text x="0" y="523.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan fill="#e4dfd6">Help</tspan><tspan> </tspan><tspan fill="#97938c">/help</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
<text x="0" y="545.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan fill="#e4dfd6">Inline images</tspan><tspan> </tspan><tspan fill="#97938c">/images</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
<text x="0" y="567.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
<text x="0" y="589.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan fill="#ddc084">enter</tspan><tspan fill="#e4dfd6"> run</tspan><tspan fill="#97938c"> · </tspan><tspan fill="#ddc084">↑/↓</tspan><tspan fill="#e4dfd6"> choose</tspan><tspan fill="#97938c"> · </tspan><tspan fill="#ddc084">esc</tspan><tspan fill="#e4dfd6"> close</tspan><tspan> </tspan><tspan fill="#97938c">1/40 </tspan><tspan> </tspan></text>
<text x="0" y="589.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan fill="#ddc084">enter</tspan><tspan fill="#e4dfd6"> run</tspan><tspan fill="#97938c"> · </tspan><tspan fill="#ddc084">↑/↓</tspan><tspan fill="#e4dfd6"> choose</tspan><tspan fill="#97938c"> · </tspan><tspan fill="#ddc084">esc</tspan><tspan fill="#e4dfd6"> close</tspan><tspan> </tspan><tspan fill="#97938c">1/41 </tspan><tspan> </tspan></text>
<text x="0" y="611.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
<text x="0" y="633.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan></text>
<text x="0" y="655.0" textLength="1000" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan fill="#e4dfd6"> 3.1%/1.0M</tspan><tspan> </tspan><tspan fill="#e4dfd6">󰌵 med</tspan><tspan> </tspan><tspan fill="#12100e" font-weight="700">󰚩 claude-sonnet-5</tspan><tspan> </tspan></text>

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

View File

@@ -15,8 +15,9 @@ luxe --version
This installs the `luxe` command. You need a recent stable Rust; [rustup](https://rustup.rs)
installs one.
To update, run the same command with `--force`. Luxe checks once a day for a newer release and says
so on the start screen; see [Update notice](configuration.md#update-notice) to turn that off.
To update, run `luxe update`, or `/update` inside Luxe. Luxe checks once a day for a newer release
and says so on the start screen; see [Updates](configuration.md#updates) for how it updates and how
to turn the check off.
## Build from source

View File

@@ -251,7 +251,8 @@ There is no telemetry. Luxe connects only to:
2. Search providers and web pages, when the agent uses `web_search` or `web_fetch`, and GitHub
when `web_fetch` clones a repository (`"tools": { "clone_repositories": false }` stops it)
3. The models.dev catalog, to refresh model details (`LUXE_MODELS_DEV_REFRESH=0` stops it)
4. The update check, once a day (`"update": { "check": false }` stops it)
4. The update check, once a day (`"update": { "check": false }` stops it), and when you run
`luxe update` or `/update`, which then runs your package manager's own update
5. GitHub, through your own `gh`, when you, the agent or an [RPC client](rpc.md#github-writes) work
with pull requests and issues. A client can write there only if you start it with
`--github-writes`.

0
scripts/ci-changes.py Normal file → Executable file
View File

View File

@@ -1,11 +1,11 @@
# Functions allowed over clippy's too_many_lines threshold. See scripts/fn-length-check.py.
# <lines[,lines…]> <path> <fn> # reason
399 crates/luxe-tui/src/commands/built_in.rs built_in # the command catalog: one `Command` literal per entry, no logic to pull out, so a new command raises this by its own entry
406 crates/luxe-tui/src/commands/built_in.rs built_in # the command catalog: one `Command` literal per entry, no logic to pull out, so a new command raises this by its own entry
369 crates/luxe-tui/src/app/messages.rs reduce_inner # the `Msg` reducer, one arm per message and nearly all of them one call; the fat arms already live in `app::messages::*`
353 crates/luxe-tui/src/app/commands.rs dispatch_action # maps each `UiAction` to the one call that handles it; arms are a line or two and a handler that grows moves out
257 crates/luxe-tui/src/app/events.rs reduce # the `Event` reducer, one arm per engine event; the long arms delegate to `app::events::*`
223 crates/luxe-core/src/engine/run.rs run # the engine action loop, a dispatch over `Action` where each arm is one handler call; the arms that did real work are methods
203 crates/luxe-tui/src/app/commands/slash.rs run_slash # maps each slash command to the handler that runs it; the arms that grew are in `commands::*`
204 crates/luxe-tui/src/app/commands/slash.rs run_slash # maps each slash command to the handler that runs it; the arms that grew are in `commands::*`
128 crates/luxe-core/src/engine/turn.rs run_turn # the turn state machine: its `break`s and early returns share the loop state, and every step that could stand alone (compact, stream, commit, tools, wrap-up) already does
127 crates/luxe-tui/src/main_loop/click.rs clicked_target # one arm per mouse target, each a view guard and one message or a call into a named handler
125 crates/luxe-cli/src/cli/rpc/translate.rs to_engine_action # the RPC vocabulary mapped onto `Action`, one thin arm per variant

View File

@@ -3,8 +3,11 @@
Compares the workspace version against a base ref, normally the pull request's target:
- a change to what reaches crates.io (anything under `crates/`, `Cargo.toml`, `Cargo.lock`) has to
raise the version, and by exactly one semver step, so a typo cannot skip a release;
- a change to what reaches crates.io (anything under `crates/`, `Cargo.toml`, `Cargo.lock`) on top
of a released version has to raise it, and by exactly one semver step, so a typo cannot skip a
release. A version is released once a `v<version>` tag marks it. Until then it already names the
release this change will ship in, so no bump is owed; it may still move, but only to another
single step past the last release, as when a breaking change turns a pending patch into a minor;
- the version never goes down, shipped change or not;
- every internal path dependency names the workspace version, because cargo publishes that number
and a stale `0.1.0` still resolves locally against a `0.1.1` beside it;
@@ -116,8 +119,8 @@ def problems(base_ref: str) -> list[str]:
found = []
if precedence(head) < precedence(base):
found.append(f"the version went down: {base} -> {head}")
elif ships(changed) and not is_one_step(base, head):
found.append(bump_message(base, head))
elif ships(changed) and (problem := shipped_problem(base, head, released())):
found.append(problem)
manifests = {str(p.relative_to(ROOT)): p.read_text() for p in ROOT.glob("crates/*/Cargo.toml")}
found += [f"internal dependency not pinned to {head}: {pin}" for pin in stale_pins(manifests, head)]
changelog = ROOT / "CHANGELOG.md"
@@ -126,6 +129,30 @@ def problems(base_ref: str) -> list[str]:
return found
def released() -> list[str]:
"""Every version a `v<version>` tag marks."""
tags = git("tag", "--list", "v*").split()
return [tag[1:] for tag in tags if SEMVER.match(tag[1:])]
def shipped_problem(base: str, head: str, released: list[str]) -> str | None:
"""What is wrong with `head` for a change that ships on top of `base`, or `None`.
A released base owes one step. An unreleased one already names the coming release, so it may
stay, or move to another single step past the last release before it.
"""
if base in released:
return None if is_one_step(base, head) else bump_message(base, head)
if head == base:
return None
earlier = [version for version in released if precedence(version) < precedence(base)]
last = max(earlier, key=precedence, default=None)
if is_one_step(last or base, head):
return None
since = f"the last release, {last}" if last else f"{base}, which is not released yet"
return f"{head} is not one semver step past {since}"
def bump_message(base: str, head: str) -> str:
"""Says what a shipped change needed, naming the three versions it could have taken."""
major, minor, patch, _ = parse(base)

View File

@@ -146,11 +146,17 @@ class AgainstARepository(unittest.TestCase):
self.run_git("add", "-A")
self.run_git("-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-qm", message)
def test_a_shipped_change_without_a_bump_fails(self):
def test_a_shipped_change_on_a_released_version_without_a_bump_fails(self):
self.run_git("tag", "v0.1.0", "main")
self.write("crates/a/src/lib.rs", "pub fn new() {}\n")
self.commit("change")
self.assertIn("leaves the version at 0.1.0", " ".join(vc.problems("main")))
def test_a_shipped_change_on_an_unreleased_version_needs_no_bump(self):
self.write("crates/a/src/lib.rs", "pub fn new() {}\n")
self.commit("change")
self.assertEqual(vc.problems("main"), [])
def test_a_shipped_change_with_a_bump_passes(self):
self.write("crates/a/src/lib.rs", "pub fn new() {}\n")
self.write_version("0.1.1")
@@ -163,5 +169,30 @@ class AgainstARepository(unittest.TestCase):
self.assertEqual(vc.problems("main"), [])
class ShippedProblem(unittest.TestCase):
"""The bump a shipped change owes, given which versions have been released."""
def test_a_released_base_owes_one_step(self):
self.assertIsNone(vc.shipped_problem("0.1.0", "0.1.1", ["0.1.0"]))
self.assertIn("leaves the version", vc.shipped_problem("0.1.0", "0.1.0", ["0.1.0"]))
self.assertIn("not one semver step", vc.shipped_problem("0.1.0", "0.1.2", ["0.1.0"]))
def test_an_unreleased_base_already_names_the_release(self):
self.assertIsNone(vc.shipped_problem("0.1.1", "0.1.1", ["0.1.0"]))
self.assertIsNone(vc.shipped_problem("0.1.0", "0.1.0", []), "before any release")
def test_an_unreleased_base_moves_only_one_step_past_the_last_release(self):
self.assertIsNone(vc.shipped_problem("0.1.1", "0.2.0", ["0.1.0"]), "patch became minor")
self.assertIn("last release, 0.1.0", vc.shipped_problem("0.1.1", "0.1.2", ["0.1.0"]))
def test_with_no_release_the_base_is_the_reference(self):
self.assertIsNone(vc.shipped_problem("0.1.0", "0.2.0", []))
self.assertIn("not released yet", vc.shipped_problem("0.1.0", "0.3.0", []))
def test_a_later_release_on_another_line_is_not_the_reference(self):
# A 1.0.0 tagged elsewhere does not make 0.2.0 a skip from the 0.1.x line
self.assertIsNone(vc.shipped_problem("0.1.1", "0.2.0", ["0.1.0", "1.0.0"]))
if __name__ == "__main__":
unittest.main()