15 Commits

Author SHA1 Message Date
Evan Whittaker
2e14c3dbda Merge pull request #18 from evanwhittaker/sync-0.1.5
luxe 0.1.5: a provider picker, model ids, and a guided review that says less
2026-10-22 14:07:14 -05:00
Evan Whittaker
f3ed35beb5 luxe 0.1.5: a provider picker, model ids, and a guided review that says less
The dock's provider row opens a list of providers, and the model picker opens on the provider in use, with tab to widen it; signing in opens it on the provider just signed in to. Models go by their id unless config names them, and the model row wears its maker's mark.

The guided review's guide prompt is shorter, the pull request brief shows the start of the description with the rest behind p, its commits drop the Luxe-review and Luxe-revision lines, and the weakened-gates signal is gone.

luxe update reruns the installer it was installed with, in place of luxe-cli-update. The preview's FILE tab reads files the session changed outside the project, and only those. Smaller fixes: bash headers are highlighted, the preview loses a blank row, the launcher divider sits inside its frame, and the phone app's top bar is clear of iOS's blur.

rustls-webpki 0.103.16 and webpki-roots 1.0.10 fix RUSTSEC-2026-0381 and RUSTSEC-2026-0382, and vite 8.3.4 fixes GHSA-587h-7wmj-h5pm, GHSA-698v-4r3x-3vcv and GHSA-r825-w8mm-5pxw.
2026-10-22 13:25:32 -05:00
Evan Whittaker
4705c2abaa Merge pull request #16 from evanwhittaker/sync-0.1.4
luxe 0.1.4: remembered models, wheel-driven lists, and a steadier phone app
2026-10-20 14:14:20 -05:00
Evan Whittaker
a0666d6c81 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.
2026-10-20 13:51:34 -05:00
Evan Whittaker
6184aa21fb Merge pull request #15 from evanwhittaker/sync-0.1.3
Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md
2026-10-20 03:02:25 -05:00
Evan Whittaker
d2129a886f Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md
- luxe remote puts the sessions on your computer in reach of your own phone or tablet over
  Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a
  paired device and your own Tailscale login.
- luxe join lets another program on the same machine join a running session over the RPC protocol.
- An AGENTS.md in a subfolder reaches the model the first time it works there.
- Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing.
- A session is open in one Luxe at a time, web_search shares results across its phrasings, and a
  grep glob starting with ! excludes.

The CHANGELOG has the full list.
2026-10-20 02:40:13 -05:00
Evan Whittaker
99e30d6d0f Merge pull request #14 from evanwhittaker/sync-0.1.2
Luxe 0.1.2: Windows fixes, working compaction, and compaction progress in the dock
2026-10-18 15:18:06 -05:00
Evan Whittaker
33b87c78a8 Luxe 0.1.2: Windows fixes, working compaction, and compaction progress in the dock 2026-10-18 15:04:51 -05:00
Evan Whittaker
4ed87ee4e4 Merge pull request #13 from evanwhittaker/sync-grep-and-header
grep groups by file; changes header fits; macOS test flake
2026-10-18 09:30:23 -05:00
Evan Whittaker
933c1195b4 grep names each file once with its lines under it, the changes header keeps its position whole, and the bash teardown tests stop flaking on macOS
- grep groups its lines under each file, the layout of rg --heading, rather than repeating the
  path on every line: 9–28% fewer bytes than rg -n on the searches measured. scopes: true labels
  each run of matches with the function or type around it.
- The changes pane's header shortens the path rather than cut its position, and keeps a gap
  before the FILE / DIFF switch.
- The bash teardown tests count a loop still running as a survivor, not one write already under
  way when the kill landed.
2026-10-18 09:18:05 -05:00
Evan Whittaker
7b460ab9c7 Merge pull request #12 from evanwhittaker/sync-wordmark-and-policy
Animated README wordmark, AI-assistance note and policy
2026-10-17 22:22:28 -05:00
Evan Whittaker
6501c5ed37 The README opens on the animated wordmark, says how Luxe is built, and CONTRIBUTING asks contributors to disclose AI help
- The README's wordmark is an animated GIF with a transparent background, rendered from the
  dashboard's own art and lights, in light and dark variants for GitHub's two themes.
- The README says Luxe is built with AI assistance, much of it Luxe working on itself, and
  CONTRIBUTING has an AI-assistance section: say what helped, understand the change, write to
  people in your own words.
- The redaction table's Google-key example is joined at compile time, so secret scanning stops
  reading the invented value as a leaked key.
- The MCP trust tests read Luxe's own report of what it started, so a slow runner can neither fail
  them nor pass them falsely.
2026-10-17 22:09:56 -05:00
Evan Whittaker
ab743ed98f Merge pull request #11 from evanwhittaker/sync-install-and-tools
Short install commands, edits keep file modes, tools page chart
2026-10-17 20:43:00 -05:00
Evan Whittaker
c53b394bef The workspace is 0.1.1, the release that carries the file-permissions fix
0.1.0 is released, and the first change to what ships after it bumps the version one step and opens its CHANGELOG section.
2026-10-17 20:29:45 -05:00
Evan Whittaker
f014ead3b9 Luxe installs with curl -fsSL https://luxe.dev/install.sh | sh, edits keep a file's permissions, and the tools page charts every agent by name
- luxe.dev/install.sh redirects to the latest release's installer, and luxe.dev/install.ps1 runs
  the release's PowerShell installer under Windows' default policy, so the commands are
  `curl -fsSL https://luxe.dev/install.sh | sh` and `powershell -c "irm https://luxe.dev/install.ps1 | iex"`.
  The install tabs run shell, brew, cargo, then windows.
- The edit and write tools and format-on-save keep a file's mode, so editing a script no longer
  leaves it unrunnable.
- The tools page gives Claude Code and Codex their own columns and bars, draws Luxe's own bar in
  each group, and its terminal's window controls take macOS's colors.
- scripts/aur-pkgbuild.sh writes a luxe-bin PKGBUILD from a release, for the AUR once it reopens.
2026-10-17 20:05:01 -05:00
942 changed files with 42697 additions and 6661 deletions

View File

@@ -1,6 +1,6 @@
# Nextest configuration — https://nexte.st/docs/configuration/
#
# The point of this file is a per-test timeout safety net. Luxe's test *execution* is fast
# The point of this file is a per-test timeout safety net. luxe's test *execution* is fast
# (~30s for the whole workspace once compiled), but a genuinely hung or runaway test — e.g. a
# process-spawning integration test that never reaps its child, or the historical review-gate
# fork bomb — could otherwise wedge the machine for many minutes. Nextest kills any test that

2
.gitattributes vendored
View File

@@ -14,7 +14,7 @@
# Development-process artifacts — excluded from published release archives.
#
# These are Luxe's own planning spine, journal, and dogfooding memory. Luxe never
# These are luxe's own planning spine, journal, and dogfooding memory. luxe never
# *requires* them at runtime (every reader treats them as read-if-present), so a fresh
# consumer repo starts clean. `git archive` (and scripts/publish-clean.sh) drop them via
# the `export-ignore` attribute below; the files stay in this development repo for history.

View File

@@ -136,9 +136,7 @@ jobs:
- name: Webfonts cover the assets
run: scripts/site-fonts.sh --check
# The one part of docs/brand/voice.md a machine can judge. Everything else in it — evidence
# with claims, naming the trade-off — is a human's call, and a checker that pretended otherwise
# would be one nobody trusts.
# The part of docs/brand/voice.md a machine can judge: banned words and British spellings
- name: Voice
run: python3 scripts/voice-check.py
@@ -162,6 +160,24 @@ jobs:
env:
RUSTDOCFLAGS: -D warnings
# The phone app's end-to-end test drives a real `luxe` (a session, the bridge, pairing) in
# WebKit, the only engine an iPhone has. It runs here because the Build step above already
# made `target/debug/luxe`: a job of its own would compile the workspace a second time, and
# the binary is too large to hand between jobs cheaply. The app's types and unit tests need
# no Rust, so they stay in `remote-app`.
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 24
cache: npm
cache-dependency-path: crates/luxe-remote/app-tests/package-lock.json
- name: Phone app end to end (WebKit)
working-directory: crates/luxe-remote/app-tests
run: |
npm ci
npx playwright install --with-deps webkit
npm run e2e
# Does it build and pass on the platforms nobody develops on? Linux above is the canonical gate —
# `fmt` is an answer about the source, not about the OS, so running it three times would only
# triple the noise from one rule. What cannot be known without a real runner is whether the code
@@ -342,12 +358,42 @@ jobs:
run: node ../scripts/site-cross.mjs --require webkit
working-directory: web
# The phone app `luxe remote` serves. It ships as written, with no build step, so this is where a
# type error gets caught: its JSDoc checked by tsc, and its folds unit-tested. The end-to-end
# test, one whole turn in WebKit, runs in `gate`, which already has a `luxe` built.
remote-app:
name: phone app
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
timeout-minutes: 20
defaults:
run:
working-directory: crates/luxe-remote/app-tests
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 24
cache: npm
cache-dependency-path: crates/luxe-remote/app-tests/package-lock.json
- name: Install
run: npm ci
- name: Types
run: npm run check
- name: Unit tests
run: npm test
# The one check a ruleset requires. A skipped job reports as passing but a skipped matrix job
# reports under no name a ruleset can hold, so this sums them up: it fails when any job failed or
# was cancelled, `changes` included, and passes when each one passed or had nothing to check.
passed:
name: CI passed
needs: [changes, gate, portability, msrv, supply-chain, website]
needs: [changes, gate, portability, msrv, supply-chain, website, remote-app]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5

5
.gitignore vendored
View File

@@ -21,7 +21,7 @@ __pycache__/
.DS_Store
Thumbs.db
# Luxe-specific
# luxe-specific
.luxe/
# Verification captures — throwaway evidence for one session, megabytes of it.
.pi/agent-loop/screenshots/
@@ -38,6 +38,9 @@ web/node_modules/
web/dist/
# Wrangler's dev-server scratch: caches, a shim worker, and its source maps.
web/.wrangler/
# The phone app's type checker, test libraries and browser driver
crates/luxe-remote/app-tests/node_modules/
web/.astro/
# cargo-mutants scratch output

288
AGENTS.md
View File

@@ -1,27 +1,27 @@
# AGENTS.md — Luxe
# AGENTS.md
Rules for working in this repository. Each line is something a capable engineer would get wrong
without being told; anything the code already shows is left out, because this file rides in every
request. Process, tooling and the long explanations are in [`CONTRIBUTING.md`](CONTRIBUTING.md).
Rules for working on luxe: only what you'd get wrong without being told. It's sent with every
request, so keep it short; the long version is [`CONTRIBUTING.md`](CONTRIBUTING.md).
## Commands
```bash
cargo check -p <crate> # the inner loop
cargo nextest run --workspace # ~15s once compiled
cargo check -p <crate> # quick loop
cargo nextest run --workspace # ~15s once built
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --all --check
cargo deny check
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps # a broken doc link fails CI
cargo test --workspace --examples # nextest does NOT run these
python3 scripts/size-check.py # file-size ratchet (--report lists)
python3 scripts/fn-length-check.py # function-length ratchet
python3 scripts/voice-check.py # reads source comments too
python3 scripts/docs-check.py # the guide's links, frontmatter, voice
cargo test --workspace --examples # nextest skips these
python3 scripts/size-check.py # file size limit
python3 scripts/fn-length-check.py # function length limit
python3 scripts/voice-check.py # banned words, British spelling
python3 scripts/docs-check.py # guide links, frontmatter, words
python3 scripts/version-check.py <base> # a shipped change bumps one step
scripts/guide-bundle.sh # after editing docs/guide
scripts/site-assets.sh --check # generated web assets are current
scripts/site-fonts.sh --check # webfonts cover those assets
(cd web && npm run cross) # the demos boot in every engine
scripts/site-fonts.sh --check # web fonts cover those assets
(cd web && npm run cross) # site demos run in every browser engine
scripts/win-check.sh [--clippy] # the suite for Windows, under wine
scripts/install-dev.sh # rebuild the release binary on PATH
@@ -29,160 +29,144 @@ cargo run -p luxe-cli -- # the TUI
cargo run -p luxe-cli -- --headless -p "..." # one prompt, no UI
```
Run the whole gate before calling work done, and `scripts/win-check.sh` in **both modes** before
calling anything cross-platform done: CI also lints the Windows target, and a `#[cfg(unix)]` helper
left unused there is a `-D warnings` error the default run cannot see. The voice check reads
**source comments**, so one British spelling in a doc comment fails the build (it checks itself;
do not quote the words it bans). A new glyph that reaches a captured surface needs
`scripts/site-fonts.sh` after `site-assets.sh`, or it ships as tofu.
## Before you call it done
- **Never run two builds or test runs at once.** They thrash and both take longer. Wrap unattended
runs in `timeout <secs>`; never poll with `while pgrep cargo`.
- **A slow run is compiling, not hanging.** `.config/nextest.toml` kills any test over ~120s.
- **`luxe` on `PATH` is `target/release/luxe`, and nothing above builds release.** When a reported
defect contradicts the source, check the binary's date against the fix before re-debugging.
- Run the whole list. For anything cross-platform, run `scripts/win-check.sh` with and without
`--clippy`: CI lints Windows, and an unused `#[cfg(unix)]` helper fails there.
- One build or test run at a time. Wrap unattended runs in `timeout <secs>`; never poll with
`while pgrep cargo`. A slow run is compiling, not stuck: nextest kills tests over ~120s.
- `luxe` on `PATH` is `target/release/luxe`, and only `install-dev.sh` rebuilds it. If a bug report
contradicts the source, check the binary's date first.
- The voice check reads code comments too: one British spelling in a doc comment fails CI.
- A new glyph on a captured screen needs `site-assets.sh`, then `site-fonts.sh`, or it shows as a
box.
## Architecture boundaries
## Architecture
- **Dependencies point inward to `luxe-core`.** Allowed: `providers`, `tools`, `lsp`, `dap`, `mcp`
and `tui` → `core`; `cli` → all of them. Forbidden: `core` → anything in-workspace; `tui` →
`providers`/`tools` (go through core traits).
- **`core` is pure logic and traits: no UI, no HTTP.** No `reqwest`, no `ratatui`. Spawning a
process is fine (git, hooks, formatters, the MCP stdio transport); network I/O lives in
`luxe-providers`, `luxe-tools`' web tools and `luxe-cli`, with any policy (`luxe-core::update`)
kept in core.
- **UI talks to core only over channels.** `Action` in, `Event` out. A UI never calls a provider or
a tool directly and never blocks the runtime.
- **Cross-cutting behavior is a `Hook`**, not a special case threaded through the loop.
- Dependencies point in, to `luxe-core`. `providers`, `tools`, `lsp`, `dap`, `mcp`, `remote` and
`tui` may use `core`; `cli` may use all of them. `core` uses no workspace crate, and `tui` never
uses `providers` or `tools` (go through core traits).
- `core` is logic and traits: no UI, no HTTP, no `reqwest` or `ratatui`. Spawning processes is
fine. Network code lives in `luxe-providers`, `luxe-tools`' web tools, `luxe-remote` and
`luxe-cli`; its policy (like `luxe-core::update`) stays in core.
- A UI talks to core over channels only: `Action` in, `Event` out. It never calls a provider or a
tool and never blocks the runtime.
- Behavior that cuts across the loop is a `Hook`, not a special case in the loop.
- One owner per platform question: `user_dirs` (home and luxe's folders), `program` (finding
programs and shells, detaching, killing a process tree), `paths` (path to string), `fs_atomic`
(safe file replace), `luxe-lsp::uri` (`file://` URLs).
## Rust conventions
## Rust
- **Modules:** `foo.rs` beside `foo/`, never `foo/mod.rs`, except `luxe-core/tests/common/`, since
each top-level file under `tests/` is its own binary.
- **Errors:** `thiserror` enums in libraries, `anyhow` only in `luxe-cli`. No `unwrap()`/`expect()`
on a fallible path; `expect()` is for real invariants and says why. **Branch on the variant,
never on the message**: a `to_string()` match turns rewording an error into a silent behavior
change. Messages are lowercase with no trailing period.
- **Async:** `tokio`; `spawn_blocking` for blocking work. **Turns must be abortable**: cancellation
drops the future, so anything spawned needs `kill_on_drop` or its own process-group guard.
- **Logging:** `tracing`, structured fields over interpolation, secrets through the redaction
layer. `info` is routine behavior worth reading, `debug` detail you go looking for, `warn` an
oddity the run coped with, `error` a real failure. Don't name the module; `target` does.
- **Size:** at most 500 lines of production code per file (split by responsibility) and 80 lines
per function (4 to 20 for new code). A wide `match` with thin arms is fine; a fat arm is not.
`scripts/size-check.py` and `scripts/fn-length-check.py` are ratchets: an allowlisted entry may
shrink, never grow, and a new one needs a reason a reviewer accepts.
- **Visibility:** `pub` means used from another crate; everything else is `pub(crate)` or
narrower. `unreachable_pub` checks items but not fields, so narrow fields by hand.
- **Tests:** unit tests in-module; an inline test module past 150 lines moves to a sibling
`foo/tests.rs`. Integration tests group into one binary per area (`tests/<area>/main.rs` plus
modules). `core` is fully testable headless: mock providers and temp dirs, no UI, no network. A
test in `examples/` runs only if its `[[example]]` declares `test = true`.
- **A test earns its place by being able to fail.** Watch a regression test fail on the unfixed
code. `scripts/mutants.sh -f <file>` finds the tests that cannot fail; use it on anything
security- or format-critical. A round-trip cannot catch a rename, so a persisted shape is pinned
against a literal copied from real output (a `.luxe/sessions/*.jsonl` line, a real `gh` reply).
- **Every public item has a `///` doc.**
- `foo.rs` next to `foo/`, never `foo/mod.rs` (except `luxe-core/tests/common/`).
- Errors: `thiserror` enums in libraries, `anyhow` only in `luxe-cli`. No `unwrap()` or `expect()`
on anything that can fail; `expect()` is for things that can't, and says why. Match on the error
variant, never its message. Messages are lowercase with no trailing period.
- Turns must be cancelable. Cancel drops the future, so anything spawned needs `kill_on_drop` or
its own process-group guard. Blocking work goes in `spawn_blocking`.
- Logging is `tracing`, with fields instead of formatted strings and secrets through the redaction
layer. `info` is routine, `debug` is detail, `warn` is something odd the run handled, `error` is a
real failure. Don't put the module name in the message.
- New functions are 4 to 20 lines (80 max); files are 500 lines of production code max. The size
scripts are ratchets: an allowlisted entry can shrink, never grow, and a new one needs a reason.
- `pub` means another crate uses it; everything else is `pub(crate)` or narrower. The lint skips
fields, so narrow those by hand.
- Every public item gets a `///` doc.
## Tests
- Unit tests live in the module; past 150 lines they move to a sibling `foo/tests.rs`. Integration
tests are one binary per area: `tests/<area>/main.rs` plus modules.
- `core` tests run headless: mock providers, temp dirs, no UI, no network.
- An example's tests only run if its `[[example]]` sets `test = true`.
- A test has to be able to fail. Watch a regression test fail on the old code first.
`scripts/mutants.sh -f <file>` finds tests that can't fail; use it on security and format code.
- Pin anything saved or sent against a literal copied from real output (a `.luxe/sessions/*.jsonl`
line, a real `gh` reply). A round-trip test can't catch a rename.
## Comments and docs
Lean, casual, senior-dev voice. **Less is more.** Comment the *why*: intent, trade-offs, gotchas,
constraints a reader would not guess. Never restate what the code says; a comment that paraphrases
the next line goes. If a block needs a comment to say *what* it does, extract a named function.
- Comment the why: intent, trade-offs, gotchas. Never restate the code. If a block needs a comment
to say what it does, make it a named function.
- `//!` module docs: `Name — short description.`, a blank line, then how it fits.
- `///` item docs: sentences ending in a period (what, why, edge cases). Variants with a payload get
an `Args:` line. Short field and variant docs are fragments with no period.
- `//` inline: short fragments, no period. Reserved prefixes: `LEARN:`, `NOTE:`, `TODO:`.
- Describe the code as it is: no history, ticket numbers or plan references. That's for the commit.
- No docs that echo the name (`/// Session ID` on `session_id`), no banners, no commented-out code.
- Prose people read follows [`docs/brand/voice.md`](docs/brand/voice.md). How the agent talks lives
in `luxe-core::context`'s base harness, never in a mode or tool description.
- **Module docs (`//!`)**: `Name — short description.`, a blank line, then prose framing the
module in the architecture.
- **Item docs (`///`)**: sentences ending in a period: what, then why, then edge cases.
Payload-carrying variants get an `Args:` line. Label-style field and variant docs are fragments
with no period (`/// Configured accounts`).
- **Inline (`//`)**: terse fragments, no period. Reserved prefixes: `LEARN:`, `NOTE:`, `TODO:`.
- **Shipped source describes the code as it is.** No history ("used to", the incident that taught
it), no phase numbers, ticket ids or design-note citations; the story goes in the commit message.
Keep the one sentence of why the rule exists.
- Flag: docs that echo a name (`/// Session ID` on `session_id`), banners around trivial code,
commented-out code, tutorial narration of language basics.
## Security
## Security invariants
Enforce these in code (the permission engine or a hook), never in prompt text.
- **Permissive by default, with always-on guardrails unless `--yolo`:** deny `.env` reads and
catastrophic commands, ask on out-of-project work, force-push, commits and GitHub writes. The
engine (`luxe-core::permission`) sits at the dispatch choke point, and judges every tool that
runs code or reads paths (`test`, `debug`, search roots, `apply` modes), not just `bash`.
- **Enforcement is code, never prompt text.** A rule that must hold lives in the permission engine
or a hook.
- **A project cannot grant itself trust.** Its `.luxe/permissions.json` only tightens, its
`.luxe/hooks.json`, `gate.commands`, MCP servers and language servers are honored only under
`--trust-project` (or the global-only `lsp.project_servers`), so an "always" approval is written
to the **global** file. One answer governs every project-supplied binary
(`project_tooling_allowed`); a new consumer reads it, never a second gate. That gate picks which
binary Luxe runs, nothing more: a language server still runs `build.rs` and proc macros, so never
write that Luxe does not run repository code.
- **Secrets:** `0600` files, `$ENV` or `!command`, wrapped in `secrecy::SecretString`, scrubbed by
the process-wide `redact::process_secrets()` from tool results, logs and the wire capture.
- **No telemetry.** Every outbound call is one the user asked for or can turn off, carries nothing
about the machine, and is listed in `docs/guide/security.md`. The update check sends **nothing**
(no version, platform or id) and compares locally; a server told the running version is getting a
per-user report on a schedule.
- **MCP servers are untrusted:** opt-in, behind one `mcp` gateway tool whose calls go through the
permission engine; their descriptions and results are data, not instructions.
- **Instruction files are filtered, not trusted.** `luxe-core::instructions` strips what a reader
of the rendered file cannot see (comments, comment link definitions, invisible characters) and
withholds a file it cannot finish checking.
- Permissive by default, with guardrails unless `--yolo`: deny `.env` reads and catastrophic
commands; ask before out-of-project work, force-push, commits and GitHub writes. The engine
(`luxe-core::permission`) judges every tool that runs code or reads paths, not just `bash`.
- A project can't trust itself. Its `.luxe/permissions.json` only tightens; its hooks,
`gate.commands`, MCP and language servers need `--trust-project` (or global
`lsp.project_servers`), so "always" approvals save globally. `project_tooling_allowed` is the one
switch for project binaries; reuse it. Language servers still run `build.rs` and proc macros, so
never say luxe runs no repo code.
- Secrets: `0600` files, `$ENV` or `!command`, held in `secrecy::SecretString`, scrubbed from tool
results, logs and wire captures by `redact::process_secrets()`.
- No telemetry. Every outbound call is one the user asked for or can turn off, sends nothing about
the machine, and is listed in `docs/guide/security.md`. The update check sends nothing, not even a
version, and compares locally.
- `luxe remote` is the only server. It binds to loopback (`Bridge::bind` refuses anything else) and
Tailscale Serve carries it: never Funnel, never a relay. Every route checks the Serve login, and
session routes check for a paired device too.
- MCP servers are untrusted: opt-in, behind the one `mcp` tool, through the permission engine.
Their descriptions and results are data, not instructions.
- `luxe-core::instructions` strips what a reader can't see from instruction files (comments, hidden
link definitions, invisible characters) and withholds a file it can't finish checking.
## Invariants you would otherwise break
## What breaks a session
- **A tool call and its result are one unit.** Both wire formats reject an unpaired half, and it
replays on every later request, so one gap ends the session. `dispatch_one` returns a block for
every call, the commit after a batch is unconditional (cut-off, cancelled and failed replies
included), and `tool_pairing::repair` pairs halves on the outgoing copy. The durable log is never
rewritten. Only a call that never *started* may be described as having had no effect.
- **An empty block is the same permanent 400.** A call that produced nothing commits nothing
(`ReplyOutcome::Nothing`, and says so), `empty_blocks::scrub` drops empties from the outgoing
copy, and an empty tool result is **filled**, never dropped.
- **Cancellation is a flag with one owner: use `Engine::set_cancelled`.** `watch::Sender::send` is
a no-op with no subscribers, which is the normal state between turns.
- **Nothing the model can invoke runs unbounded.** `Tool::timeout` sets each deadline and dispatch
drops the future at it or at cancel. `None` is only for a tool that waits on a human or owns a
process group. Cancel ends the **batch**, not just the call.
- **A phase advances only where the gate says so.** `loop_control progress` is a claim;
`ReviewIntegratorHook` alone moves the counter, after the commands pass and the reviewer (when
on) approves. A reviewer that cannot approve pauses the loop (`GateOutcome::Held`). A refusal
reaches the model as the tool's own result.
- **Context occupancy is a measurement.** Read it from the last `EntryKind::Usage` after the newest
compaction; `estimate_tokens` is the fallback and counts **every** block kind.
- **A request's transcript is an *append* to the last one's.** Providers cache an exact prefix, so
editing history in flight re-bills everything after the edit at the write rate. Pruning is gated
on real window pressure and cuts in whole `prune_min_tokens` steps. Watch the **written** share on
`/cost` and in `luxe wire`, not the hit rate.
- **The system prompt is byte-identical between turns of a session.** No volatile fact enters it;
one-time context is **appended**. Reason about what reaches the model from a capture
(`LUXE_WIRE_LOG` plus `luxe wire`), not from source.
- **`Action` and `Event` are a published protocol.** `luxe --rpc` streams them to clients nobody
here compiles, and an unknown tag degrades to `Other`, so a rename breaks every client and no
compiler notices. Adding is free; removing or retagging moves `PROTOCOL_VERSION`. Pinned literals
in `tests/event_serialization.rs` hold it.
- **`AGENTS.md` is the only project document in the prompt.** Anything else is pointed at.
- **A tool must beat the shell command it replaces** (bounded output, fewer round trips, correct
defaults, or a capability the shell lacks), and its description names the sibling for the
adjacent question.
- **Glyphs are polish, never meaning.** Every icon sits beside the words it labels; prefer block
- **A tool call and its result are a pair.** Providers reject half a pair on every later request,
so one gap ends the session. `dispatch_one` returns a result for every call, a batch always
commits (cut off, cancelled or failed too), and `tool_pairing::repair` fixes the outgoing copy.
Never rewrite the saved log. Only a call that never started had no effect.
- **An empty block is the same permanent 400.** An empty reply commits nothing
(`ReplyOutcome::Nothing`), `empty_blocks::scrub` drops empties from the outgoing copy, and an
empty tool result is filled, never dropped.
- **Cancel with `Engine::set_cancelled`.** `watch::Sender::send` does nothing without subscribers,
which is normal between turns.
- **Nothing the model runs is unbounded.** `Tool::timeout` sets each deadline; dispatch drops the
future at it or on cancel. `None` is only for a tool that waits on a person or owns a process
group. Cancel ends the whole batch.
- **Only the gate moves a phase.** `loop_control progress` is a claim; `ReviewIntegratorHook` moves
the counter once the commands pass and the reviewer (if on) approves, and pauses the loop
(`GateOutcome::Held`) if it can't. A refusal reaches the model as the tool's result.
- **Context use is measured.** Read it from the last `EntryKind::Usage` after the newest
compaction. `estimate_tokens` is the fallback and counts every block kind.
- **Each request appends to the last.** Providers cache an exact prefix, so editing history
re-bills everything after the edit. Pruning waits for real window pressure and cuts in whole
`prune_min_tokens` steps. Watch the written share on `/cost` and in `luxe wire`, not the hit rate.
- **The system prompt never changes mid-session.** Nothing volatile goes in it; one-time context is
appended. Judge what reaches the model from a capture (`LUXE_WIRE_LOG` plus `luxe wire`).
- **`Action` and `Event` are a public protocol.** `luxe --rpc` streams them to clients built
elsewhere, and an unknown tag becomes `Other`, so a rename breaks them silently. Adding is free;
removing or renaming bumps `PROTOCOL_VERSION`. `tests/event_serialization.rs` pins the literals.
## Product rules
- `AGENTS.md` is the only project document in the prompt. Point at anything else.
- A tool must beat the shell command it replaces (bounded output, fewer round trips, better
defaults, or something the shell can't do), and its description names the sibling tool for the
next question.
- Glyphs decorate; they never carry meaning alone. Every icon sits beside its words. Prefer block
elements, which every terminal draws.
- **Platform questions have one owner each:** `user_dirs` (home and Luxe's directories), `program`
(finding programs, shells, detaching, killing a process tree), `paths` (path to string),
`fs_atomic` (durable replace), `luxe-lsp::uri` (`file://` URLs).
- **Generated assets are generated; captures are recorded.** `web/src/assets/generated/` comes from
the Rust source and CI checks it. `web/src/assets/captures/` are real sessions recorded by
`scripts/site-record.sh`, which nothing can verify; change how Luxe looks and you owe both a
`site-assets.sh` and a re-record.
- **The wordmark constants are the art** (`luxe-tui/src/widgets/wordmark/art.rs`): one drawing, no
- `web/src/assets/generated/` comes from Rust and CI checks it; `captures/` are real sessions from
`scripts/site-record.sh`. Change how luxe looks and you owe a `site-assets.sh` run and a
re-record.
- The wordmark constants in `luxe-tui/src/widgets/wordmark/art.rs` are the logo: one drawing, no
alternatives.
- **Two voices, two homes.** Prose a person reads follows `docs/brand/voice.md`; how the agent
writes lives in `luxe-core::context`'s base harness, never in a mode or a tool description.
## Where things live
- `CONTRIBUTING.md`: process, tooling, publishing. `docs/guide/`: the user guide, also embedded in
the binary for `luxe docs`.
- `.luxe/todos/<session-id>.json`: the `todo` tool's checklist, one file per session.
- A development checkout also has `PROJECT.md` (what must stay true; read it when a design call is
ambiguous), `ROADMAP.md`, `PROGRESS.md`, `PLAN.md` and design notes, all excluded from releases.
- `CONTRIBUTING.md`: process, tooling, publishing. `docs/guide/`: the user guide, also in
`luxe docs`. `.luxe/todos/<session-id>.json`: the `todo` checklist.
- A dev checkout also has `PROJECT.md` (what must stay true; read it when a design call is
unclear), `ROADMAP.md`, `PROGRESS.md`, `PLAN.md` and design notes. None of them ship.

View File

@@ -1,7 +1,7 @@
# Changelog
Every release of Luxe, newest first. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). While Luxe is below
Every release of luxe, newest first. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). While luxe is below
1.0, a minor bump (0.x.0) may break config, flags or the `--rpc` protocol, and a patch bump never
does.
@@ -9,6 +9,293 @@ The version on `main` is always the next release. The first change to what ships
`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.5]
### Added
- Clicking the provider in the dock lists your providers. Choose one that serves the model you're
on and luxe switches to it there, keeping the model; choose any other and its models open. In
the model picker, `←` reaches the same list.
- The guided review's pull request brief opens with the start of the description, then **Read the
whole description · p**. `p` shows all of it.
- The FILE tab of the preview shows a file the session changed outside the project, highlighted
like any other. It reads only what the session itself changed out there.
### Changed
- The model picker opens on the models of the provider you're using, and `tab` shows every
provider's. Signing in opens it on the provider you just signed in to.
- Models go by their ID everywhere, like `claude-opus-5`, unless you name one in `models.json`.
- The dock's model row wears the maker's mark (Claude's for `claude-*`) and the provider row who
serves it. A provider with no mark of its own, Anthropic among them, gets a filled cloud, and a
ChatGPT subscription wears OpenAI's.
- `luxe update` runs the same installer you first installed with, so an update lands where the
install did. The separate `luxe-cli-update` program is gone.
- The mode sits above the composer.
- The guided review's guide asks the model for less, and says less.
- Commits from a guided review carry your message and nothing else. The `Luxe-review` and
`Luxe-revision` lines are gone.
- The guided review no longer flags CI and supply-chain files as "weakened gates".
- The start screen's launcher is ruled off with a muted line inside its frame.
### Fixed
- A one-line `bash` command on a tool card's header is highlighted, like the rest of the card.
- The preview runs down to the activity row when it takes the conversation's place, without a
blank row between them.
- The dock's provider and model rows light up and take clicks separately.
- In the phone app added to an iPhone's Home Screen, iOS no longer blurs the top bar.
### Security
- `rustls-webpki` 0.103.16 and `webpki-roots` 1.0.10, for RUSTSEC-2026-0381 and RUSTSEC-2026-0382:
certificate checks could trust distrusted intermediates.
## [0.1.4]
### Added
- luxe remembers the model you last chose in each project, and starts there. A project you haven't
chosen in yet starts on the model you last chose anywhere, then on `default_model`.
- The mouse wheel and the scrollbar work in every list in a modal: the model picker, the palette,
themes, sessions, providers, settings and the `/` and `@` flyouts. Both move the cursor, so Enter
never picks a row you can't see.
- The dock's telemetry row starts with the provider, beside its own mark where the font has one.
### Changed
- The name is written lowercase everywhere, as **luxe**, even to start a sentence. The dot in
**luxe.** belongs to the logo.
- `luxe --help` opens with "A coding agent for your terminal."
- Signing in no longer picks a model for you. The model picker opens at the top of its list, and
nothing changes until you choose.
- Loop output marks each phase with a colored rail and each iteration with a bracket inside it. In
a terminal a tool's line shows `○` while it runs, then a green `✓` or a red `✗`.
- The phone app shows a turn's reasoning in full, as the interface does. It was cut to three lines
with nothing to say there was more.
- A phone notification for a question reads "The agent has a question for you".
### Fixed
- On Windows, `luxe update` replaces the running luxe. Windows won't overwrite a program while
it runs, so the old copy is moved aside and deleted at the next launch.
- A luxe that's already signed in no longer opens first-run setup, even if setup was never
finished. Quitting it partway left nothing saved, so it came back at the next launch.
- Opening a large project in the file tree no longer shows "engine busy". It asked for every
changed folder at once and overflowed the queue; it now asks for a few at a time.
- The phone app stays where you are while you read back through a long session. Each new item
dropped the oldest from the top of the page, which moved everything you were reading.
- A question answered from the phone app shows its answer on its card, as the interface does. It
was hidden behind a tap, as raw text.
## [0.1.3]
### Added
- A session open in the interface can be joined by another program on the same machine while you
keep working: `luxe join` speaks the [RPC protocol](docs/guide/rpc.md#join-a-running-session)
over a local socket (a named pipe on Windows) only your account can open. A joined client gets
the session so far, then every live event, and can answer prompts. It can't switch or end the
session, publish to GitHub, or be a program the agent started. `"joinable": false` or
`LUXE_JOINABLE=0` turns it off.
- A `prompt_closed` event tells every front end when a permission prompt or question stops
waiting, so one answered elsewhere comes down everywhere.
- `luxe remote` puts the sessions running on your computer in reach of your own phone or tablet,
over [Tailscale](docs/guide/remote.md). It listens on this machine only, Tailscale Serve carries
it to your devices, and it lets in your own Tailscale login from a device you paired with a QR
code. `luxe remote setup` checks Tailscale, publishes the bridge, runs it at sign-in as a user
service (systemd, launchd, or the Windows Run key, none needing an administrator), and shows the
code. `luxe remote devices` lists and revokes devices.
- The bridge can start Luxe in a folder a device picks: in a herdr pane when herdr is running, so
the session waits at your desk, or as its own `luxe --rpc` otherwise.
- A session started with `luxe --rpc` can be joined, like one in the interface.
- An `introduce` action lets a joined client name itself, so the interface says "iPhone joined
this session" and "Approved from iPhone" rather than a process id.
- The bridge renders messages for the phone app the way the interface draws them: markdown,
highlighted code in your theme's colors with a copy control, tool icons, and your own messages
without the notes Luxe adds for the agent. The phone parses nothing itself.
- From the phone app you can write to a session, steer or stop a running turn, and answer its
permission prompts and questions. Like the interface's, a prompt holds every answer but Reject
for a moment after it appears, so a tap meant for something else can't grant anything.
- The phone app's status line shows the mode behind the interface's mark for it, which a tap
switches, and the context, thinking level and model, worded as the interface's status bar words
them. A tap on those opens the session's details, where you can switch the model or thinking
level and see the cost.
- The phone app is set in the same monospace at a size that fits more on a phone, and its session
list wears the Luxe wordmark, lit by the same slow drift as the interface's.
- The phone app's header names the session's folder and the branch it's on, behind the interface's
folder and branch marks, starred when the tree has changes. A long branch is cut first.
- The phone app can start a session in a folder you've worked in, or any other you type, and opens
it once it's ready. **New** on the session list opens a page for it, where what you type narrows
the folders it offers.
- The phone app can send photos, from the camera or the library, scaled down on the phone first so
they're quick to send.
- The phone app's composer has icon buttons for attaching a photo (a paperclip), sending (an arrow
in the accent color, dim until there's something to send) and stopping, and a line over the box
while a turn runs that says whether sending steers it or waits for it to end.
- The phone app offers the slash commands it can carry out (`/compact`, `/cost`, `/dock`, `/mode`,
`/model` and `/thinking`) as you type a `/`, and project files to mention as you type an `@`.
- The phone app shows the Context Dock, with the session's plan and changed files: a rail beside
the conversation on an iPad or an open iPhone Duo, on the side your `dock` settings choose,
which a header button and `/dock` show and hide. On a phone the header keeps to one menu button,
and the dock is the first tab of the panel it opens. A long plan scrolls in a box of its own
that keeps the work in hand in view, as the interface's rail does. Tapping a file opens its diff.
- The phone app has a project panel, behind the header's menu button. Its Files tab is the
interface's FILES tree, with its guides, icons and change marks, and shows a file highlighted
as the interface shows it, with a button that mentions it in your message. On a wide screen the
panel is a rail in the dock's place, and a file or a diff opens beside it, with the conversation
still in view where there's room, as the interface peeks beside its dock.
- The phone app's project panel has a GitHub tab: `/github`'s sections and rows, and a pull
request or issue opened beside them with its overview and conversation, drawn as the interface
draws them. It reads only, and **Mention** adds the item to your message.
- The phone app's project panel has a Review tab: the open Guided Review's guide, a chapter opened
beside it with the guide's notes over its diffs, and **Reviewed** and **Next** to walk it. It
joins the review the interface has open, through the new `show_open_review` RPC action, whose
answer also says what each chapter asks of the reader. The panel's bar names the project and its
branch with the interface's marks, as the interface's PROJECT section does.
- The phone app asks about picked lines, as the interface's File view does, in a file, a diff or a
review chapter: tap line numbers to pick them, or select text the phone's way, down to part of a
line, and **Ask** adds the path and lines to your message in the interface's words.
- The phone app comments on a review chapter: on a picked line or run of lines, or on the chapter,
as a comment or a question, saved or sent at once. Comments show under what they're about with
the agent's replies, and take a reply, resolve, send or delete; the guide sends everything unsent.
- The phone app is named for the computer it reaches, as Tailscale names it: on the Home Screen,
beside the Luxe mark in the session list, and after the project in notifications. One phone can
keep an app for each of several computers and tell them apart.
- Your own phone joining a session no longer adds "joined" and "left" lines to the conversation
each time it reconnects: the dock's SESSION block names who's joined instead. Someone else's
device is still announced.
- Escape on an iPad keyboard closes the phone app's sheet straight after a pane opens or closes,
where it used to be lost for a frame.
- The phone app's icon buttons (close, project, dock) are square, 44 points to tap, and a press or
a keyboard's focus shows Luxe's own square rather than the browser's rounded highlight.
- The phone app's headings are the interface's badges (PROJECT, PLAN, FILES, MODEL, SESSION), cut
the same way at the same depths, or bold words when `statusline.style` is flat.
- The phone app can be added to the home screen, where it opens full screen with the Luxe mark in
your theme's colors as its icon. An app on the home screen keeps its own sign-in apart from
Safari's, so one that needs pairing again takes the invitation link pasted in.
- The phone app can [notify you](docs/guide/remote.md#notifications) when a session waits on an
answer or finishes a long turn. It's off until you turn it on, one device at a time, and a
notification says only what's waiting and where. The bridge seals each one for your device and
posts it to your device's own push service, with no Luxe server in between.
- The protocol sends [`turn_started`](docs/guide/rpc.md) when a turn begins, from any client, and a
client joining mid-turn gets it while catching up. A turn sent from your phone shows as running
in the terminal right away, not from its first word.
- The protocol answers [`list_models`](docs/guide/rpc.md) with the models you can switch to, and
the thinking levels each one honors, so a client can offer the same choices as `/model`.
- A joined client can introduce itself with `watch_only`, to read a session without the interface
announcing it. Luxe drops anything else it sends. The bridge watches for notifications this way.
- An `AGENTS.md` in a folder the agent works in now reaches it, even when Luxe started somewhere
else in the repository. It's added to the first tool result that reaches the folder, once, so
the system prompt and the provider's cache are untouched. Luxe shows "Following" and the file.
See [Project context](docs/guide/project-context.md#folders-the-agent-works-in);
`LUXE_NESTED_INSTRUCTIONS=0` turns it off.
### Changed
- A session is open in one Luxe at a time. Resuming one that another Luxe has open is refused, and
the message says which process has it, rather than two of them writing the same history.
- `message_committed` now announces the messages you send too, as the protocol guide always said
it did, so a joined client sees the question as well as the answer, and the interface shows a
message a joined client sent. A `--rpc` client gets its own message back once Luxe saves it.
- The turn timer reads like a tool card's time: `42s`, then `3m 07s`, then `1h 05m`.
- `luxe --help` opens with "A beautiful coding agent for your terminal."
### Fixed
- A tool call the model writes while an earlier one is still running shows as waiting, not as a
second spinner. Only one card spins at a time again.
- A running `bash` card is titled with what the command is for, as soon as the model has written
that. It used to show the command in both the title and the body until the command finished.
- A message with an image, sent while a turn runs, is queued for its own turn. Steering it
delivered the words and dropped the image.
- A compaction is in the conversation from the moment it starts ("Compacting the conversation —
579.4k of context…"), and that line becomes the result when it ends. A minute of summary showed
nothing but the activity bar while the dock was open. The phone app shows it too.
- Typing in the phone app keeps up in a long session. It drew every item the session ever had,
and Safari slows each keystroke as a page passes a few thousand (a 9,000-item session took about
100ms a key on a desktop). It now draws the latest 300, with **Show earlier** for the rest.
- A long session no longer stalls before every model call. Luxe re-read and parsed the whole
session file each time, about 70ms on a 68 MB session. It now keeps the session it's writing in
memory and reads only what was added, about 10ms.
- A turn no longer spends seconds saving the project for **Last Turn** review. Every turn saved
two full copies of every file, synced to disk one by one (about 11 seconds a turn in a project
of 4,000 files), and never deleted any, so one project's `.luxe/reviews/turn-baselines` reached
18 GB. A copy now links the files the last one already holds, which takes under a second, and
copies the last turn doesn't need are deleted once they're an hour old.
- A long session's memory climbs much more slowly. Every model call copied the whole
conversation, every tool result included, to send the part after the last compaction. It now
copies only what it sends: over 20 turns on a 68 MB session, Luxe grew by 65 MB instead of
338 MB.
- Drawing a long session with screenshots in it is cheaper while a reply streams. Every tool
card holding an image was laid out again on every frame, even scrolled far out of view, which
in a session with a hundred screenshots was most of what the terminal UI allocated. A card is
now laid out again only when its image changes.
- A phone joining a long session costs the computer less. Each join copied the whole
conversation, then built the message carrying it in one buffer that doubled as it grew. It's
now sent from the copy Luxe already keeps, in pieces: over 120 joins of a 68 MB session, 26 GB
less allocated, and each join about 20ms faster.
- Compaction no longer fails more often the longer a session runs. The summarizer was asked for a
list of every file the session touched and shown the last summary's list to copy, though Luxe
keeps that list itself and replaced whatever the summarizer wrote. On a long session the list
grew to over 500 paths, and copying it used up the summary's output limit, so the compaction
failed with "the summary stopped short". The summarizer now writes only the prose, and its
output limit is 32K tokens, up from 16K.
- `web_search` with several phrasings gives each its share of the results. Without a key, they
went to Exa as one search ranked against the first phrasing, so the others rarely showed. Each
phrasing is now its own search, and the results take turns: the top of each, then the next.
- `web_search` says when Exa's free search is rate limited, and which phrasing it turned away. The
notice used to read as a search that found nothing.
- A `grep` glob starting with `!` excludes, as `rg -g '!target/**'` does. It used to match no file,
so the search came back empty.
## [0.1.2]
### Fixed
- Compaction works with thinking models. Summaries were cut off at 4,096 output tokens and thrown
away, so after three failures automatic compaction switched itself off and the window filled
until the model could not answer. `/compact` now gives the real reason when it fails.
- On Windows, a timed-out or cancelled command ends everything it started, not just its shell, and
the agent's commands no longer rename your terminal tab.
- On Windows, the file tools accept Git Bash paths (`/c/Users/...`), `glob` reads `src\*.py` as a
folder, and the agent's Python commands run in UTF-8 mode, so printing characters outside your
code page no longer crashes them.
- On Windows, an npm tool installed as a `.cmd` shim (such as `pyright`) is found, and Python is
looked up as `py -3`, then `python`.
- The debugger checks that `debugpy` is installed before offering Python debugging, and
`luxe doctor` says how to install it.
- A new session started from the start screen keeps its working indicator and timer from the first
moment.
### Changed
- The dock shows "compacting" while a summary is written, and its context reading drops as soon as
it finishes. `--rpc` clients get the new `compaction_started` and `compaction_stopped` events.
- An empty reply from the model at a nearly full context window suggests `/compact` instead of a
retry.
- Signing in with GitHub: the choices are clickable, and the device code has a Copy button (or
press `c`).
- The installer's closing message says how to start Luxe.
## [0.1.1]
### Fixed
- Editing a file with the edit or write tool, or format-on-save rewriting it, keeps the file's
permissions, so an edited script stays executable. A kept mode is now exact rather than trimmed
by the umask.
- The changes pane's header keeps its position (`8 of 14`) whole, shortening the path instead, and
keeps a gap between the line counts and the FILE / DIFF switch.
### Changed
- `grep` names each file once with its matching lines under it, rather than repeating the path on
every line: 9–28% fewer bytes than `rg -n` on the searches measured. `scopes: true` also labels
each run of matches with the function or type around it.
- The install guide leads with `curl -fsSL https://luxe.dev/install.sh | sh` and
`powershell -c "irm https://luxe.dev/install.ps1 | iex"`.
## [0.1.0]
The first public release.

View File

@@ -1,6 +1,6 @@
# Contributing to Luxe
# Contributing to luxe
Process and tooling for people working on Luxe itself. The rules an agent has to hold to are in
Process and tooling for people working on luxe itself. The rules an agent has to hold to are in
[`AGENTS.md`](AGENTS.md), deliberately kept short because it rides in every request; this file is
the long version, for humans, and nothing here is loaded into a prompt.
@@ -11,11 +11,25 @@ editing a page, and a test fails until you do.
## Licensing your contribution
Luxe is dual licensed under MIT (`LICENSE-MIT`) or Apache-2.0 (`LICENSE-APACHE`), at the user's
luxe is dual licensed under MIT (`LICENSE-MIT`) or Apache-2.0 (`LICENSE-APACHE`), at the user's
option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in
the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.
## AI assistance
AI help is welcome. luxe is built with plenty of it, much of it luxe working on itself. Three things
to hold to:
- **Say so.** Name the tool and how much of the change it wrote in the pull request: "written with
luxe on Claude Sonnet 5.5, then reviewed and edited by me", or "asked ChatGPT how the cache works,
wrote the fix myself". Tab completion doesn't count. A commit can carry the Linux kernel's
`Assisted-by: AGENT:MODEL` trailer.
- **Understand it.** You should be able to explain what your change does and how it fits without
asking the tool. That's the bar for any change, and the one an agent makes easiest to skip.
- **Write to people in your own words.** An issue or a pull request description is read by a person,
so keep it short, and label anything a model wrote.
## The gate
```bash
@@ -266,7 +280,7 @@ python3 scripts/voice-check.py --review
The Tools page's bars are recorded, not generated: `scripts/tool-bench.sh NAME=REPO:CASES ...` runs
each tool and the shell command it replaces in each checkout you name (the cases are in
`scripts/tool-bench/`), then in Luxe itself, and writes `web/src/data/tool-bench.json` naming every
`scripts/tool-bench/`), then in luxe itself, and writes `web/src/data/tool-bench.json` naming every
repository's commit. Each shell row is also put through the other agents' own output limits, since
that, not the raw output, is what their models are sent. Nothing checks the file; run it on
committed trees when a tool's output changes. The page draws from the first repository.
@@ -281,6 +295,48 @@ cd web && npm run build && npm run check
cd web && npm run deploy # needs `wrangler login` once
```
## The phone app
`luxe remote`'s app is plain HTML, CSS and ES modules in `crates/luxe-remote/app/`, with nothing
built. A debug build reads that folder from disk, so run `cargo run -p luxe-cli -- remote` and
reload. Preact, htm and Signals are vendored byte for byte, and a test holds them to
`app/vendor/manifest.json`:
```bash
scripts/remote-vendor.sh # fetch the pinned versions again (needs npm)
scripts/remote-fonts.sh # subset the fonts again (after site-fonts.sh)
```
Colors come from `/theme.css`, the active theme read through `luxe_core::theme::css`, the same
mapping the website's theme CSS uses. Each `var(--luxe-*)` in the app's stylesheet keeps a fallback
for a theme that leaves a color to the terminal. `app/generated/wordmark.svg` comes from the TUI's
art through `scripts/site-assets.sh`, which checks it with the website's assets.
The transcript is a pure fold of the session's frames (`app/transcript.js`), tested with Node's
own runner against a session recorded through the bridge (`app-tests/fixtures/turn.jsonl`). The
tests resolve imports through `index.html`'s import map, so they run the vendored files the phone
runs. The app's types are JSDoc, checked by `tsc` in strict mode; the tests get a looser config.
`tsc` reads expressions inside a template but not the props `htm` hands a component, so a
component's `@param` is what it promises, not something checked at the call. The end-to-end test
starts a session against a mock model, a bridge and a pairing, then drives a whole turn in WebKit,
permission and diff included. CI runs all three in its `phone app` job:
```bash
cd crates/luxe-remote/app-tests
npm ci # TypeScript, Playwright, and the vendored libraries' types
npm run check # tsc
npm test # unit tests
cargo build -p luxe-cli && npm run e2e # end to end; LUXE_BIN picks another luxe
node e2e/screenshots.mjs # the guide's phone shots, into docs/guide/phone/
```
Every iOS browser is WebKit, so check the app there. Playwright's WebKit build wants Ubuntu's ICU,
libxml2 and flite, which a rolling distro doesn't have. Without root, unpack those three `.deb`s
from the Ubuntu archive into the `minibrowser-wpe/sys/lib` of a copy of
`~/.cache/ms-playwright/webkit-*`, and point `PLAYWRIGHT_BROWSERS_PATH` at the copy. A screenshot
adds a `<style>` of Playwright's own, which the app's policy refuses and the console reports; the
page never had it.
## Versioning
One version for the whole workspace (`[workspace.package]` in `Cargo.toml`), following semver, and
@@ -298,6 +354,15 @@ python3 scripts/version-check.py origin/main # what the pull request check ru
python3 scripts/version_check_test.py # the check's own tests
```
The tags live in the public repository. A checkout that isn't a clone of it (a private development
repository, a fork) names it as the `public` remote, and the check reads its tags from there, so a
release made since your last fetch still counts:
```bash
git remote add public https://github.com/evanwhittaker/luxe.git
git remote set-url --push public DISABLED-use-a-pull-request
```
Below 1.0, a minor bump may break config, flags or the `--rpc` protocol; a patch never does.
## Releasing
@@ -310,7 +375,7 @@ git tag v0.2.0 && git push origin v0.2.0
```
`.github/workflows/release.yml`, which `dist` generates from `dist-workspace.toml`, then builds
every target, puts the archives, the install scripts and their updater on the GitHub release with
every target, puts the archives and the install scripts on the GitHub release with
an attestation for each file, publishes the Homebrew formula to `evanwhittaker/homebrew-tap`, and
publishes the crates to crates.io (`publish-crates.yml`) before announcing. Never edit
`release.yml`; change `dist-workspace.toml` and run `dist generate`.
@@ -320,9 +385,15 @@ publisher is this repository's `release.yml`. A crate whose version crates.io al
skipped, so a re-run after a partial publish carries on. `cargo publish --workspace --dry-run`
packages and builds every crate the way the registry will, dependencies first.
A new crate can't start that way: crates.io sets up Trusted Publishing only for a crate that
exists. Publish its first version by hand (`cargo publish -p <crate>`), then on crates.io open the
crate's **Settings → Trusted Publishing** and add GitHub for `evanwhittaker/luxe`, with workflow
`release.yml` and no environment, before the next tag. Without it the release stops at that crate
with "403 Forbidden: The provided access token is not valid", and every crate after it waits.
## Development-only files
A development checkout carries planning files, design notes and evaluation rigs that Luxe never
A development checkout carries planning files, design notes and evaluation rigs that luxe never
needs at runtime. They are marked `export-ignore` in `.gitattributes`, and
`scripts/publish-clean.sh <dir>` writes a release tree without them, then scans what it wrote for
anything that must not ship.

273
Cargo.lock generated
View File

@@ -152,6 +152,57 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"base64",
"bytes",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"sha1",
"sync_wrapper",
"tokio",
"tokio-tungstenite",
"tower",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
]
[[package]]
name = "base16ct"
version = "1.0.0"
@@ -616,6 +667,12 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "deltae"
version = "0.3.2"
@@ -778,7 +835,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1237,6 +1294,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -1260,6 +1323,7 @@ dependencies = [
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
@@ -1626,7 +1690,7 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "luxe-cli"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"anyhow",
"async-trait",
@@ -1638,8 +1702,10 @@ dependencies = [
"luxe-lsp",
"luxe-mcp",
"luxe-providers",
"luxe-remote",
"luxe-tools",
"luxe-tui",
"qrcode",
"reqwest",
"secrecy",
"semver",
@@ -1651,12 +1717,13 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"unicode-width",
"uuid",
]
[[package]]
name = "luxe-core"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"async-trait",
"base16ct",
@@ -1687,7 +1754,7 @@ dependencies = [
[[package]]
name = "luxe-dap"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"async-trait",
"luxe-core",
@@ -1701,7 +1768,7 @@ dependencies = [
[[package]]
name = "luxe-lsp"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"async-trait",
"base16ct",
@@ -1725,7 +1792,7 @@ dependencies = [
[[package]]
name = "luxe-mcp"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"async-trait",
"futures-util",
@@ -1745,7 +1812,7 @@ dependencies = [
[[package]]
name = "luxe-providers"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"async-trait",
"base64",
@@ -1762,15 +1829,39 @@ dependencies = [
"tracing",
]
[[package]]
name = "luxe-remote"
version = "0.1.5"
dependencies = [
"axum",
"base16ct",
"base64",
"futures",
"getrandom 0.4.3",
"luxe-core",
"reqwest",
"ring",
"rust-embed",
"serde",
"serde_json",
"sha2 0.11.0",
"tempfile",
"thiserror 1.0.69",
"tokio",
"tokio-tungstenite",
"tracing",
]
[[package]]
name = "luxe-tools"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"anyhow",
"async-trait",
"base64",
"dom_smoothie",
"encoding_rs",
"futures",
"globset",
"htmd",
"image",
@@ -1789,7 +1880,7 @@ dependencies = [
[[package]]
name = "luxe-tui"
version = "0.1.0"
version = "0.1.5"
dependencies = [
"anyhow",
"arboard",
@@ -1797,6 +1888,7 @@ dependencies = [
"base64",
"crossterm",
"futures",
"gif",
"image",
"luxe-core",
"luxe-tui",
@@ -1868,6 +1960,12 @@ dependencies = [
"regex-automata",
]
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.2"
@@ -1895,6 +1993,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1987,7 +2095,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2369,6 +2477,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
@@ -2401,6 +2518,12 @@ version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qrcode"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
[[package]]
name = "quick-error"
version = "2.0.1"
@@ -2493,6 +2616,16 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core 0.9.5",
]
[[package]]
name = "rand"
version = "0.10.2"
@@ -2504,12 +2637,31 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_core"
version = "0.10.1"
@@ -2722,6 +2874,41 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rust-embed"
version = "8.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23"
dependencies = [
"rust-embed-impl",
"rust-embed-utils",
"walkdir",
]
[[package]]
name = "rust-embed-impl"
version = "8.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053"
dependencies = [
"mime_guess",
"proc-macro2",
"quote",
"rust-embed-utils",
"syn 2.0.118",
"walkdir",
]
[[package]]
name = "rust-embed-utils"
version = "8.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a"
dependencies = [
"sha2 0.11.0",
"walkdir",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -2747,7 +2934,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2776,9 +2963,9 @@ dependencies = [
[[package]]
name = "rustls-webpki"
version = "0.103.15"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
@@ -2901,6 +3088,17 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -2922,6 +3120,17 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -3199,10 +3408,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3437,6 +3646,18 @@ dependencies = [
"tokio",
]
[[package]]
name = "tokio-tungstenite"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
@@ -3650,6 +3871,22 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand 0.9.5",
"sha1",
"thiserror 2.0.18",
]
[[package]]
name = "typenum"
version = "1.20.1"
@@ -3896,9 +4133,9 @@ dependencies = [
[[package]]
name = "webpki-roots"
version = "1.0.8"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"
checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
dependencies = [
"rustls-pki-types",
]
@@ -4003,7 +4240,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]

View File

@@ -6,12 +6,12 @@ members = ["crates/*"]
# Every crate here releases together from one workspace, so the versions move in lockstep and each
# crate inherits this one. The internal `path` dependencies carry the same number explicitly — cargo
# uses the path locally and the version on crates.io, and refuses to publish a path dep without one.
version = "0.1.0"
version = "0.1.5"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/evanwhittaker/luxe"
homepage = "https://luxe.dev"
# Bound by the dependencies: uuid needs 1.89, and ratatui, image and darling 1.88. Luxe's own floor
# Bound by the dependencies: uuid needs 1.89, and ratatui, image and darling 1.88. luxe's own floor
# is lower (`user_dirs` relies on `std::env::home_dir`, which returned `$HOME` on Windows before
# 1.85). The `msrv` CI job builds the workspace on exactly this version, so the number cannot drift.
rust-version = "1.89"
@@ -106,7 +106,7 @@ image = { version = "0.25", default-features = false, features = [
[workspace.lints.rust]
# `deny`, not `forbid`, so an audited exception can carry its own `#[allow]`, which is the line a
# reviewer has to look at. The shipped program has one: `program::detach_from_terminal`, whose
# `pre_exec(setsid)` is how a spawned command leaves Luxe's terminal (std's `Command::setsid` is not
# `pre_exec(setsid)` is how a spawned command leaves luxe's terminal (std's `Command::setsid` is not
# stable). The others are the counting allocators in luxe-tui's frame-budget test and render-perf
# example, which never ship.
unsafe_code = "deny"

View File

@@ -1,10 +1,15 @@
<h1 align="center"><img src="web/src/assets/generated/wordmark-banner.svg" alt="Luxe" width="420"></h1>
<h1 align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="web/src/assets/generated/wordmark-dark.gif">
<img src="web/src/assets/generated/wordmark-light.gif" alt="luxe" width="440">
</picture>
</h1>
Luxe is a coding agent for your terminal, written in Rust. It works in your project with the model
luxe is a coding agent for your terminal, written in Rust. It works in your project with the model
you choose, then reads back what it changed as a Guided Review, so you can comment, ask for fixes,
and open the pull request without leaving the terminal.
![Luxe adding a command with a test, reviewing the change chapter by chapter, and drafting the pull request](docs/images/luxe.gif)
![luxe adding a command with a test, reviewing the change chapter by chapter, and drafting the pull request](docs/images/luxe.gif)
*One take on Claude Sonnet 5.5, with only the waits cut: it writes `todo overdue` with a test, the
change is read back in three chapters, and the pull request is drafted from the review.*
@@ -35,13 +40,13 @@ change is read back in three chapters, and the pull request is drafted from the
the turn fails, and `--format json` streams its messages, tool calls and each call's token usage.
With nobody to answer, a call that would ask is allowed; `--on-ask deny` refuses it instead.
`luxe --rpc` speaks the whole protocol.
- **Extended with files and programs**, never code loaded into Luxe: skills, hooks, MCP servers,
your own `@` sources, and an [RPC protocol](https://luxe.dev/docs/rpc/) for driving Luxe from
- **Extended with files and programs**, never code loaded into luxe: skills, hooks, MCP servers,
your own `@` sources, and an [RPC protocol](https://luxe.dev/docs/rpc/) for driving luxe from
your own program.
Luxe connects to 24 providers and any OpenAI-compatible endpoint. Sign in with a ChatGPT or GitHub
luxe connects to 24 providers and any OpenAI-compatible endpoint. Sign in with a ChatGPT or GitHub
Copilot subscription or an OpenRouter account, or bring an API key; Anthropic and Google take API
keys only. There is no telemetry: every connection Luxe makes is one you asked for or can turn off,
keys only. There is no telemetry: every connection luxe makes is one you asked for or can turn off,
and [the guide lists them](https://luxe.dev/docs/security/#what-luxe-sends-over-the-network).
![A Guided Review: the guide on the left, the hunk being read on the right](docs/guide/images/review-guide.svg)
@@ -50,16 +55,16 @@ and [the guide lists them](https://luxe.dev/docs/security/#what-luxe-sends-over-
```bash
# macOS and Linux
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/evanwhittaker/luxe/releases/latest/download/luxe-cli-installer.sh | sh
curl -fsSL https://luxe.dev/install.sh | sh
# Homebrew
brew install evanwhittaker/tap/luxe
# Windows (PowerShell)
powershell -ExecutionPolicy Bypass -c "irm https://github.com/evanwhittaker/luxe/releases/latest/download/luxe-cli-installer.ps1 | iex"
# Cargo (Rust 1.89 or newer)
cargo install --locked luxe-cli
# Windows (PowerShell)
powershell -c "irm https://luxe.dev/install.ps1 | iex"
```
To update, run `luxe update`. To build from source:
@@ -71,16 +76,16 @@ cargo build --release
./target/release/luxe --version
```
Luxe runs on Linux, macOS and Windows, in any UTF-8 terminal; on Windows, use Windows Terminal and
luxe runs on Linux, macOS and Windows, in any UTF-8 terminal; on Windows, use Windows Terminal and
install [Git for Windows](https://gitforwindows.org/) so the agent has a POSIX shell. You also need
a model to talk to: an API key or a subscription. Your settings and credentials live in
`~/.config/luxe/` (`%APPDATA%\luxe` on Windows).
Icons come from a [Nerd Font](https://www.nerdfonts.com/) when you have one, in its **Mono** build;
without one, Luxe draws plain characters, and every icon has a word beside it. See
without one, luxe draws plain characters, and every icon has a word beside it. See
[Fonts](https://luxe.dev/docs/install/#fonts).
Luxe uses these when they are installed, and works without them:
luxe uses these when they are installed, and works without them:
| | For |
| --- | --- |
@@ -90,7 +95,7 @@ Luxe uses these when they are installed, and works without them:
| A debug adapter per language | The `debug` tool |
| [ast-grep](https://ast-grep.github.io) | Search and replace by code structure |
`luxe doctor` checks which of them Luxe can use on your machine, and how to install the rest.
`luxe doctor` checks which of them luxe can use on your machine, and how to install the rest.
## Quickstart
@@ -105,7 +110,7 @@ Luxe uses these when they are installed, and works without them:
`luxe --worktree` does the same in a worktree, so your checkout is never touched.
2. **Answer setup.** The first launch asks for a theme, a provider, which tools the agent can use,
and what Luxe opens on. Sign in with a subscription or paste an API key; a key already in your
and what luxe opens on. Sign in with a subscription or paste an API key; a key already in your
environment, such as `ANTHROPIC_API_KEY`, is found on its own. Choose a model when the picker
opens.
@@ -127,9 +132,9 @@ on the screen you are on, and `ctrl+c` quits; the session is already saved. The
## Documentation
The guide is at [luxe.dev/docs](https://luxe.dev/docs/), and built into Luxe for the version you
The guide is at [luxe.dev/docs](https://luxe.dev/docs/), and built into luxe for the version you
have: `luxe docs`, `luxe docs hooks`, `luxe docs --search "on_ask"`. Ask the agent how to do
something in Luxe and it reads the answer from the same pages.
something in luxe and it reads the answer from the same pages.
| To | Read |
| --- | --- |
@@ -143,7 +148,7 @@ something in Luxe and it reads the answer from the same pages.
| Give the agent your project's conventions | [Project context](https://luxe.dev/docs/project-context/) |
| Change the theme, keys or statusline | [Configuration](https://luxe.dev/docs/configuration/) |
| Control what the agent may do | [Security and permissions](https://luxe.dev/docs/security/) |
| Add tools, skills, hooks or your own front end | [Extending Luxe](https://luxe.dev/docs/extending/) |
| Add tools, skills, hooks or your own front end | [Extending luxe](https://luxe.dev/docs/extending/) |
| Look up a flag or an environment variable | [Command line](https://luxe.dev/docs/cli/), [Environment variables](https://luxe.dev/docs/environment/) |
| Fix something that is not working | [Troubleshooting](https://luxe.dev/docs/troubleshooting/) |
@@ -156,7 +161,11 @@ Every page is also plain markdown in [`docs/guide/`](docs/guide/), and
the site and the demos are made; [`AGENTS.md`](AGENTS.md) has the rules an agent working here holds
to. Problems and questions go to [GitHub issues](https://github.com/evanwhittaker/luxe/issues).
Luxe draws on Pi, by earendil-works, and on OpenCode, and on the unidirectional data flow of Elm
luxe is built with AI assistance, much of it luxe working on itself. Every change still passes the
full test suite and CI before it merges, and its maintainer decides what does. If AI helped with
yours, [say so](CONTRIBUTING.md#ai-assistance).
luxe draws on Pi, by earendil-works, and on OpenCode, and on the unidirectional data flow of Elm
and Ratatui.
## License

View File

@@ -1,13 +1,13 @@
# Security
Luxe runs a model's commands on your machine, so a hole in it matters. If you find one, please tell
luxe runs a model's commands on your machine, so a hole in it matters. If you find one, please tell
me privately before anyone else.
## Reporting
[Open a private advisory](https://github.com/evanwhittaker/luxe/security/advisories/new) on GitHub,
or email [contact@luxe.dev](mailto:contact@luxe.dev). Say what you did, what happened, and the
Luxe version (`luxe --version`). A transcript or a minimal repository that shows it helps most.
luxe version (`luxe --version`). A transcript or a minimal repository that shows it helps most.
I'll answer within a few days, keep you posted while it's fixed, and credit you in the advisory and
the release notes unless you'd rather not be named. Please give the fix time to ship before you

View File

@@ -3,7 +3,7 @@ name = "luxe-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "A terminal coding agent: streaming chat, tools, guided diff review, and LSP/DAP code intelligence"
description = "A coding agent for your terminal."
repository.workspace = true
homepage.workspace = true
readme = "../../README.md"
@@ -18,22 +18,29 @@ name = "luxe"
path = "src/main.rs"
[dependencies]
luxe-core = { path = "../luxe-core", version = "0.1.0" }
luxe-providers = { path = "../luxe-providers", version = "0.1.0" }
luxe-tools = { path = "../luxe-tools", version = "0.1.0" }
luxe-lsp = { path = "../luxe-lsp", version = "0.1.0" }
luxe-dap = { path = "../luxe-dap", version = "0.1.0" }
luxe-mcp = { path = "../luxe-mcp", version = "0.1.0" }
luxe-tui = { path = "../luxe-tui", version = "0.1.0" }
luxe-core = { path = "../luxe-core", version = "0.1.5" }
luxe-providers = { path = "../luxe-providers", version = "0.1.5" }
luxe-tools = { path = "../luxe-tools", version = "0.1.5" }
luxe-lsp = { path = "../luxe-lsp", version = "0.1.5" }
luxe-dap = { path = "../luxe-dap", version = "0.1.5" }
luxe-mcp = { path = "../luxe-mcp", version = "0.1.5" }
luxe-tui = { path = "../luxe-tui", version = "0.1.5" }
luxe-remote = { path = "../luxe-remote", version = "0.1.5", optional = true }
# The pairing QR in the terminal. Without its defaults it is the encoder and text renderer alone,
# with no dependencies.
qrcode = { version = "0.14", default-features = false, optional = true }
anyhow = { workspace = true }
clap = { workspace = true }
shlex = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
tokio = { workspace = true }
# `signal`: `luxe remote` runs until Ctrl-C, and stops serving cleanly when it comes
tokio = { workspace = true, features = ["signal"] }
uuid = { workspace = true }
secrecy = { workspace = true }
serde_json = { workspace = true }
# A joiner's transcript is encoded from the shared snapshot through a borrowed copy of its shape
serde = { workspace = true }
async-trait = { workspace = true }
# One request, for the update notice: a public release manifest, carrying nothing about the user.
# See `luxe_core::update` for why that constraint is load-bearing rather than a nicety.
@@ -41,18 +48,23 @@ reqwest = { workspace = true }
# `luxe auth login` reads an API key without echoing it, which needs raw mode on the real terminal.
# Pinned to luxe-tui's version so there is exactly one crossterm in the tree.
crossterm = "0.29"
# The loop view cuts each line to the terminal's width, so it can redraw a line in place
unicode-width = { workspace = true }
# Streaming the update manifest with a size cap, and comparing the version it reports.
futures = { workspace = true }
semver = { workspace = true }
# The scratch folder `luxe update` runs the installer script in, removed when it finishes
tempfile = "3"
[dev-dependencies]
tempfile = "3"
# The guide check: what Luxe would silently ignore in a config example
# The guide check: what luxe would silently ignore in a config example
serde_ignored = "0.1"
serde = { workspace = true }
[features]
default = ["clipboard-images"]
default = ["clipboard-images", "remote"]
# `luxe remote`, the only server in luxe. A packager can leave it out to ship a luxe with no
# server code at all.
remote = ["dep:luxe-remote", "dep:qrcode"]
clipboard = ["luxe-tui/clipboard"]
clipboard-images = ["luxe-tui/clipboard-images"]

View File

@@ -11,7 +11,7 @@
//! model is sent a raw 900 KB `git log`: the honest comparison is with what a harness forwards.
//!
//! `TOOL_BENCH_CASES` names a JSON file of cases (`id`, `shell`, `tool`, `args`) for measuring in a
//! repository other than this one; without it, the cases below measure Luxe itself.
//! repository other than this one; without it, the cases below measure luxe itself.
use std::process::Command;
use std::sync::Arc;
@@ -164,8 +164,9 @@ async fn main() -> anyhow::Result<()> {
/// The tools a session registers, minus the ones that wait on a person or a debugger.
fn registry(cwd: &std::path::Path) -> luxe_core::ToolRegistry {
let mut registry = luxe_core::ToolRegistry::new();
let tracker =
luxe_tools::register_builtins(&mut registry, None, luxe_tools::web::WebConfig::from_env());
let web = luxe_tools::web::WebConfig::from_env();
let outline = Arc::new(luxe_lsp::syntax::SyntaxOutline);
let tracker = luxe_tools::register_builtins(&mut registry, None, web, Some(outline));
let lsp = Arc::new(luxe_lsp::WorkspaceLspClient::with_servers(Default::default()));
let graph = Arc::new(luxe_lsp::graph::GraphService::new(cwd));
registry.register(Arc::new(

View File

@@ -68,16 +68,17 @@ impl ToolActivityProjector {
self.composing(call_id, name, subject.as_deref(), body.as_ref())
}
Event::ToolStarted { call_id, name } => {
self.started(call_id, name).into_iter().collect()
self.started(call_id, name).into_iter().chain(self.fit_writing()).collect()
}
Event::ToolProgress { call_id, chunk } => {
self.progressed(call_id, chunk).into_iter().collect()
}
Event::ToolCompleted { call_id, is_error, output } => {
self.settle(call_id, *is_error, Some(bounded_display(output))).into_iter().collect()
let settled = self.settle(call_id, *is_error, Some(bounded_display(output)));
settled.into_iter().chain(self.fit_writing()).collect()
}
Event::ToolEnded { call_id, is_error } => {
self.ended(call_id, *is_error).into_iter().collect()
self.ended(call_id, *is_error).into_iter().chain(self.fit_writing()).collect()
}
_ => Vec::new(),
}
@@ -95,6 +96,35 @@ impl ToolActivityProjector {
Some(open.clone())
}
/// How the card of a call still being written should read: waiting while another call runs,
/// since that one is the busy card and this one can't run before it, and working otherwise.
fn writing_state(&self, call_id: &str) -> ToolActivityState {
let running = self
.calls
.iter()
.any(|(id, open)| id != call_id && open.state == ToolActivityState::Running);
if running {
ToolActivityState::Queued
} else {
ToolActivityState::Composing
}
}
/// Moves the card of the call being written between waiting and working as a call ahead of
/// it starts or stops.
fn fit_writing(&mut self) -> Option<ToolActivity> {
let call_id = self.writing.clone()?;
let state = self.writing_state(&call_id);
let open = self.calls.get_mut(&call_id)?;
let unsent = matches!(open.state, ToolActivityState::Composing | ToolActivityState::Queued);
if !unsent || open.state == state {
return None;
}
open.revision += 1;
open.state = state;
Some(open.clone())
}
/// Opens (or fills in) the card for the call the model is writing right now.
///
/// `Composing` is a *working* state — the model is producing this call as the reader watches,
@@ -105,7 +135,9 @@ impl ToolActivityProjector {
/// written; whichever came before it has been written in full and is merely waiting its turn.
/// Saying that is what keeps exactly one card looking busy — two spinning `bash` cards read as
/// two shells at once, and a paused mark on all of them put a stopped sign over a card that
/// was visibly filling in.
/// was visibly filling in. An earlier call can run while this one is written, though, and then
/// that one is the busy card: this one opens `Queued`, since it can't run before it either,
/// and [`Self::fit_writing`] puts it back to work if the model is still writing it.
///
/// What it does not yet have is a batch position — the message has not committed, so how many
/// calls it asked for is not known — or a body, whose payload is the argument still arriving.
@@ -126,10 +158,17 @@ impl ToolActivityProjector {
}
let label = subject.map(bounded_display).unwrap_or_default();
let state = self.writing_state(call_id);
match self.calls.get_mut(call_id) {
// The call growing under the card that is already drawing it: the subject arriving, or
// another few lines of the payload. Said twice, neither is worth a revision.
Some(open) if open.state == ToolActivityState::Composing => {
// another few lines of the payload. Said twice, neither is worth a revision. Queued
// here is a card held behind a running call, since only the call being written composes.
Some(open)
if matches!(
open.state,
ToolActivityState::Composing | ToolActivityState::Queued
) =>
{
let renamed = !label.is_empty() && open.label != label;
let grew = body.is_some_and(|body| open.card_body.as_ref() != Some(body));
if renamed || grew {
@@ -150,6 +189,7 @@ impl ToolActivityProjector {
let mut activity =
ToolActivity::composing(session_id, call_id, name, label, now_ms());
activity.card_body = body.cloned();
activity.state = state;
self.calls.insert(call_id.to_owned(), activity.clone());
updates.push(activity);
}

View File

@@ -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",
),
@@ -336,6 +336,68 @@ fn exactly_one_card_is_working_at_a_time() {
);
}
/// A call written while an earlier one runs waits under that one, and works again once it's over.
///
/// Calls run as soon as they're written, so the model can be writing one while another runs. The
/// break this catches: opening the written call as `Composing` regardless, which puts a spinner on
/// it beside the running card, with a paused one between them that reads as stuck.
#[test]
fn a_call_written_while_another_runs_waits_behind_it() {
let mut projector = ToolActivityProjector::default();
projector.project(&Event::SessionLoaded { session_id: "session-a".into(), messages: vec![] });
let compose = |id: &str| Event::ToolCallComposing {
call_id: id.into(),
name: "edit".into(),
subject: Some(format!("{id}.rs")),
body: None,
};
let start = |id: &str| Event::ToolStarted { call_id: id.into(), name: "edit".into() };
let finish = |id: &str| Event::ToolCompleted {
call_id: id.into(),
is_error: false,
output: "Applied".into(),
};
let steps: Vec<(&str, Event)> = vec![
("the model writes the first edit", compose("a")),
("which runs as soon as it's written", start("a")),
("while the model writes the second", compose("b")),
("and the third", compose("c")),
("the first finishes", finish("a")),
("the second runs", start("b")),
("and finishes, with the third still being written", finish("b")),
];
let mut shape = Vec::new();
for (note, event) in steps {
projector.project(&event);
let mut states: Vec<(String, ToolActivityState)> =
projector.calls.iter().map(|(id, row)| (id.clone(), row.state)).collect();
states.sort_by(|left, right| left.0.cmp(&right.0));
let working = states.iter().filter(|(_, state)| state.is_working()).count();
assert!(working <= 1, "{note}: {working} cards claim to be working: {states:?}");
shape.push((note, states.into_iter().map(|(_, state)| state).collect::<Vec<_>>()));
}
use ToolActivityState::{Composing, Queued, Running, Succeeded};
assert_eq!(
shape,
[
("the model writes the first edit", vec![Composing]),
("which runs as soon as it's written", vec![Running]),
("while the model writes the second", vec![Running, Queued]),
("and the third", vec![Running, Queued, Queued]),
// For the instant between one call ending and the next starting, writing the third
// is the only thing happening; the next event takes it back
("the first finishes", vec![Succeeded, Queued, Composing]),
("the second runs", vec![Succeeded, Running, Queued]),
(
"and finishes, with the third still being written",
vec![Succeeded, Succeeded, Composing]
),
],
);
}
/// A refused or cancelled call is answered without ever being dispatched. Its card is the one
/// the model's writing opened, and it has to settle from there or it spins forever.
#[test]

View File

@@ -8,8 +8,12 @@ mod commands;
mod docs_command;
mod doctor_command;
pub(crate) mod headless;
mod join_command;
mod models_command;
#[cfg(feature = "remote")]
mod remote_command;
mod rpc;
mod share;
mod tui;
pub(crate) mod update_command;
mod wire_command;
@@ -22,6 +26,7 @@ use auth_command::run_auth_command;
use commands::{run_loop_command, run_mcp_command, run_sessions_command};
use doctor_command::run_doctor_command;
use headless::run_headless;
use join_command::run_join_command;
use models_command::run_models_command;
use tui::run_tui;
use wire_command::run_wire_command;
@@ -35,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
@@ -53,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?;
@@ -99,17 +115,19 @@ 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 {
SubCommand::Auth(auth_args) => return run_auth_command(auth_args.command).await,
SubCommand::Init(init_args) => return crate::init::run_init(init_args, settings).await,
SubCommand::Loop(loop_args) => {
return run_loop_command(loop_args.command, settings).await;
}
SubCommand::Loop(looping) => return run_loop_command(looping.command, settings).await,
SubCommand::Mcp(mcp_args) => return run_mcp_command(mcp_args.command, &settings).await,
SubCommand::Models(models_args) => {
return run_models_command(models_args.command, settings).await
@@ -118,6 +136,9 @@ pub(crate) async fn run(mut args: Args) -> anyhow::Result<()> {
return run_sessions_command(sessions_args.command, settings).await
}
SubCommand::Doctor => return run_doctor_command(settings).await,
SubCommand::Join(join) => return run_join_command(join, &settings.work_root).await,
#[cfg(feature = "remote")]
SubCommand::Remote(remote) => return remote_command::run_remote_command(remote).await,
SubCommand::Wire(wire_args) => return run_wire_command(wire_args),
SubCommand::Docs(_) | SubCommand::Update(_) => {
unreachable!("`luxe docs` and `luxe update` return before a project is entered")

View File

@@ -8,7 +8,7 @@ mod permission_mode;
pub(crate) use commands::*;
pub(crate) use permission_mode::PermissionModeArg;
/// Luxe — a fast, lean, security-conscious agentic coding harness.
/// luxe's command line. `--help` shows the crate description from `Cargo.toml`, not this doc.
#[derive(Parser, Debug)]
#[command(name = "luxe", version, about)]
pub(crate) struct Args {
@@ -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,
@@ -183,11 +183,14 @@ impl Args {
| SubCommand::Docs(_)
| SubCommand::Doctor
| SubCommand::Init(_)
| SubCommand::Join(_)
| SubCommand::Models(_)
| SubCommand::Sessions(_)
| SubCommand::Update(_)
| SubCommand::Wire(_),
) => false,
#[cfg(feature = "remote")]
Some(SubCommand::Remote(_)) => false,
}
}
@@ -253,12 +256,15 @@ impl Args {
| SubCommand::Docs(_)
| SubCommand::Doctor
| SubCommand::Init(_)
| SubCommand::Join(_)
| SubCommand::Mcp(_)
| SubCommand::Models(_)
| SubCommand::Sessions(_)
| SubCommand::Update(_)
| SubCommand::Wire(_),
) => false,
#[cfg(feature = "remote")]
Some(SubCommand::Remote(_)) => false,
}
}
@@ -273,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();

View File

@@ -7,12 +7,18 @@ 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
/// stdin and stdout.
Join(JoinArgs),
/// Serve your sessions to your own phone or tablet, through Tailscale.
#[cfg(feature = "remote")]
Remote(RemoteArgs),
/// Run the agent through a phased plan on its own.
Loop(LoopArgs),
/// Add, list and sign in to MCP servers.
@@ -21,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),
@@ -103,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)]
@@ -139,6 +145,70 @@ pub(crate) struct InitArgs {
pub(crate) defaults: bool,
}
/// Join arguments.
#[derive(Parser, Debug)]
pub(crate) struct JoinArgs {
/// The session: its id or the start of it, or the process id of the luxe running it. Omit
/// it to join the one running in this folder.
pub(crate) target: Option<String>,
/// List the sessions running on this machine that can be joined, and exit.
#[arg(long, conflicts_with = "target")]
pub(crate) list: bool,
}
/// Remote arguments.
#[cfg(feature = "remote")]
#[derive(Parser, Debug)]
pub(crate) struct RemoteArgs {
#[command(subcommand)]
pub(crate) command: Option<RemoteCommand>,
/// The port to listen on, on this machine only.
#[arg(long, default_value_t = 4519, global = true)]
pub(crate) port: u16,
/// Also let this tailnet login in, besides this machine's owner (repeatable).
#[arg(long = "allow", value_name = "LOGIN", global = true)]
pub(crate) allow: Vec<String>,
}
/// Remote subcommand — pair and manage your devices.
#[cfg(feature = "remote")]
#[derive(Subcommand, Debug)]
pub(crate) enum RemoteCommand {
/// Check Tailscale, publish the bridge on your tailnet, start it at login, and pair a device.
Setup,
/// Show a QR code and link that pair one phone or tablet, good for ten minutes.
Pair,
/// List the paired devices.
Devices {
#[command(subcommand)]
command: Option<DevicesCommand>,
},
/// Manage the user service that runs the bridge at login.
Service {
#[command(subcommand)]
command: ServiceCommand,
},
}
/// Service subcommand.
#[cfg(feature = "remote")]
#[derive(Subcommand, Debug)]
pub(crate) enum ServiceCommand {
/// Stop the service and stop it starting at login.
Remove,
}
/// Devices subcommand.
#[cfg(feature = "remote")]
#[derive(Subcommand, Debug)]
pub(crate) enum DevicesCommand {
/// Unpair a device and close its open sessions.
Revoke {
/// The device's id, from `luxe remote devices`
id: String,
},
}
/// Sessions arguments.
#[derive(Parser, Debug)]
pub(crate) struct SessionsArgs {

View File

@@ -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.

View File

@@ -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(())

View File

@@ -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 {

View File

@@ -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();
@@ -160,15 +160,11 @@ fn debug_adapters() -> String {
Vec::new()
});
for (adapter, from_config) in crate::engine_setup::merged_debug_adapters(&user) {
let program = adapter.spec.command.first().cloned().unwrap_or_default();
let state = match luxe_core::program::resolve(&program).is_some() {
true => "ok ",
false => "none ",
};
let (state, advice) = adapter_state(&adapter.spec.command);
let origin = if from_config { " (debug-adapters.json)" } else { "" };
let _ = writeln!(
out,
" {state} {:<12} {}{origin}",
" {state} {:<12} {}{origin}{advice}",
adapter.spec.id,
adapter.spec.command.join(" ")
);
@@ -177,6 +173,17 @@ fn debug_adapters() -> String {
out
}
/// Whether an adapter's `command` will start, and, when it is there but will not, what to do: the
/// same judgment that decides whether `debug` is offered.
fn adapter_state(command: &[String]) -> (&'static str, String) {
use luxe_dap::adapter::Unready;
match luxe_dap::adapter::unready(command) {
None => ("ok ", String::new()),
Some(why @ Unready::NoModule(..)) => ("none ", format!(" ({why})")),
Some(Unready::Missing(_)) => ("none ", String::new()),
}
}
/// The external programs the tools prefer, and what happens without each.
fn external_programs() -> String {
/// Program, what wants it, and what absence costs.

View File

@@ -0,0 +1,128 @@
//! `luxe join` — a session another luxe is running, over stdin and stdout.
//!
//! The running luxe shares its session on a local endpoint (`cli::share`), and this command is the
//! plain way in: it picks the session from the records in the runtime folder, connects, and copies
//! bytes both ways. What crosses is the `--rpc` protocol untouched, so a client written for
//! `luxe --rpc` drives a joined session by launching `luxe join` instead.
use std::path::Path;
use anyhow::Context;
use luxe_core::local_endpoint::{self, LiveSession};
use tokio::io::AsyncWriteExt;
use super::args::JoinArgs;
/// List the joinable sessions, or join one and pass the protocol through until either side ends.
pub(crate) async fn run_join_command(args: JoinArgs, work_root: &Path) -> anyhow::Result<()> {
let running = local_endpoint::running_sessions(&luxe_core::user_dirs::luxe_runtime_dir());
if args.list {
print!("{}", listing(&running));
return Ok(());
}
let cwd = work_root.to_string_lossy();
let session = pick(&running, args.target.as_deref(), &cwd)?;
let stream = local_endpoint::connect(&session.address)
.await
.with_context(|| format!("could not join session {}", session.session_id))?;
pass_through(stream).await
}
/// The session `target` names, or with no target the only one running in `cwd`.
fn pick<'a>(
running: &'a [LiveSession],
target: Option<&str>,
cwd: &str,
) -> anyhow::Result<&'a LiveSession> {
let matching: Vec<&LiveSession> = match target {
Some(target) => running.iter().filter(|session| names(session, target)).collect(),
None => running.iter().filter(|session| session.cwd == cwd).collect(),
};
match matching.as_slice() {
[only] => Ok(only),
[] => anyhow::bail!("{}", nothing_to_join(running, target, cwd)),
several => anyhow::bail!(
"{} sessions match; name one by id or process:\n{}",
several.len(),
listing_of(several.iter().copied())
),
}
}
/// Whether `target` is the session's process id or the start of its id.
fn names(session: &LiveSession, target: &str) -> bool {
let target = target.trim();
!target.is_empty()
&& (session.session_id.starts_with(target) || target == session.pid.to_string())
}
fn nothing_to_join(running: &[LiveSession], target: Option<&str>, cwd: &str) -> String {
let wanted = match target {
Some(target) => format!("no running session matches `{target}`"),
None => format!("no session is running in {cwd}"),
};
if running.is_empty() {
return format!(
"{wanted}, and none is running on this machine that can be joined. A luxe shares \
its session unless `joinable` is off or LUXE_JOINABLE=0."
);
}
format!("{wanted}. These can be joined:\n{}", listing(running))
}
fn listing(running: &[LiveSession]) -> String {
listing_of(running.iter())
}
fn listing_of<'a>(sessions: impl Iterator<Item = &'a LiveSession>) -> String {
sessions
.map(|session| format!("{} pid {} {}\n", session.session_id, session.pid, session.cwd))
.collect()
}
/// Copy stdin to the session and the session to stdout. Ends when the session closes the
/// connection, which it also does once it has read the end of our stdin.
async fn pass_through(stream: local_endpoint::LocalStream) -> anyhow::Result<()> {
let (mut from_session, mut to_session) = tokio::io::split(stream);
let mut input = read_stdin();
let upload = tokio::spawn(async move {
while let Some(chunk) = input.recv().await {
if to_session.write_all(&chunk).await.is_err() {
break;
}
}
let _ = to_session.shutdown().await;
});
let mut stdout = tokio::io::stdout();
let downloaded = tokio::io::copy(&mut from_session, &mut stdout).await;
upload.abort();
downloaded.context("the joined session's output stopped")?;
stdout.flush().await.context("could not write to stdout")?;
Ok(())
}
/// Stdin, read on a thread of its own. Tokio's stdin reads on its blocking pool, and the runtime
/// waits for that read on the way out, so a session that closes first would leave `luxe join`
/// hanging until the next keystroke. A plain thread is simply abandoned at exit.
fn read_stdin() -> tokio::sync::mpsc::Receiver<Vec<u8>> {
let (chunks, received) = tokio::sync::mpsc::channel(16);
std::thread::spawn(move || {
let mut stdin = std::io::stdin().lock();
let mut buffer = vec![0; 8192];
loop {
let read = match std::io::Read::read(&mut stdin, &mut buffer) {
Ok(0) => return,
Ok(read) => read,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return tracing::warn!(%error, "stopped reading stdin"),
};
if chunks.blocking_send(buffer[..read].to_vec()).is_err() {
return;
}
}
});
received
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,75 @@
use super::*;
fn running(pid: u32, session_id: &str, cwd: &str) -> LiveSession {
LiveSession {
pid,
session_id: session_id.to_string(),
cwd: cwd.to_string(),
address: format!("/run/luxe/{pid}.sock"),
luxe_version: "0.1.3".to_string(),
}
}
fn sessions() -> Vec<LiveSession> {
vec![
running(101, "aaaa-1111", "/work/app"),
running(202, "aaab-2222", "/work/site"),
running(303, "cccc-3333", "/work/site"),
]
}
/// With no target, the session running in this folder is the one joined.
///
/// The break this catches: ignoring the folder, so `luxe join` in one project lands in another's
/// session, or refuses because more than one luxe is running somewhere.
#[test]
fn no_target_joins_the_session_running_here() {
let all = sessions();
assert_eq!(pick(&all, None, "/work/app").unwrap().pid, 101);
}
/// Two sessions in one folder are named, not guessed between.
///
/// The break this catches: taking the first match, which joins whichever pid sorts lower.
#[test]
fn two_sessions_in_the_folder_are_listed_not_guessed() {
let all = sessions();
let error = pick(&all, None, "/work/site").unwrap_err().to_string();
assert!(error.contains("2 sessions match"), "{error}");
assert!(error.contains("aaab-2222") && error.contains("cccc-3333"), "{error}");
}
/// A target names a session by the start of its id or by its luxe's process id.
///
/// The break this catches: matching the id exactly, so the short form the listing invites fails,
/// or not accepting a pid, which is what `ps` and herdr show.
#[test]
fn a_target_is_an_id_prefix_or_a_pid() {
let all = sessions();
assert_eq!(pick(&all, Some("cccc"), "/elsewhere").unwrap().pid, 303);
assert_eq!(pick(&all, Some("202"), "/elsewhere").unwrap().session_id, "aaab-2222");
}
/// A prefix two ids share is refused, and so is an empty one.
///
/// The break this catches: an empty target matching every id as a prefix of all of them.
#[test]
fn an_ambiguous_or_empty_target_is_refused() {
let all = sessions();
assert!(pick(&all, Some("aaa"), "/work/app").is_err());
assert!(!names(&all[0], " "));
}
/// Nothing to join says why, and how sharing is turned back on when nothing is running.
///
/// The break this catches: a bare "not found" when every luxe has `joinable` off, which leaves the
/// reader with nothing to try.
#[test]
fn nothing_to_join_says_what_is_running() {
let none = pick(&[], None, "/work/app").unwrap_err().to_string();
assert!(none.contains("joinable"), "{none}");
let all = sessions();
let elsewhere = pick(&all, None, "/work/other").unwrap_err().to_string();
assert!(elsewhere.contains("no session is running in /work/other"), "{elsewhere}");
assert!(elsewhere.contains("aaaa-1111 pid 101 /work/app"), "{elsewhere}");
}

View File

@@ -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.

View File

@@ -0,0 +1,152 @@
//! `luxe remote` — the bridge that serves this machine's sessions to your own devices.
//!
//! The serving is `luxe_remote`'s; this is the terminal around it: who is let in, where it
//! listens, setting it up, pairing and revoking devices, and stopping on Ctrl-C.
use std::net::{Ipv4Addr, SocketAddr};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::Context;
use luxe_remote::{Access, DeviceBook, Tailnet};
use super::args::{DevicesCommand, RemoteArgs, RemoteCommand, ServiceCommand};
use crate::output::outln;
mod invitation;
mod render;
mod setup;
/// Runs `luxe remote` and its subcommands.
pub(crate) async fn run_remote_command(args: RemoteArgs) -> anyhow::Result<()> {
let devices = DeviceBook::at(DeviceBook::default_path());
match args.command {
None => serve(args.port, args.allow, devices).await,
Some(RemoteCommand::Setup) => setup::setup(args.port, args.allow, &devices).await,
Some(RemoteCommand::Pair) => invitation::pair(args.port, &devices).await,
Some(RemoteCommand::Devices { command: None }) => list_devices(&devices),
Some(RemoteCommand::Devices { command: Some(DevicesCommand::Revoke { id }) }) => {
revoke(&devices, &id)
}
Some(RemoteCommand::Service { command: ServiceCommand::Remove }) => remove_service(),
}
}
fn remove_service() -> anyhow::Result<()> {
match luxe_remote::service::remove()? {
true => outln!("The bridge's service is stopped and won't start at login."),
false => outln!("No service for the bridge is installed."),
}
Ok(())
}
/// Serves until Ctrl-C.
async fn serve(port: u16, allow: Vec<String>, devices: DeviceBook) -> anyhow::Result<()> {
let tailnet = luxe_remote::this_machine().await;
let machine = tailnet.as_ref().ok().map(|tailnet| tailnet.machine().to_owned());
let logins = allowed_logins(tailnet, allow)?;
let access = Access { logins: logins.clone(), devices };
let bridge = bridge(port, access, machine).await?;
outln!("luxe remote is listening on http://{}. Ctrl-C stops it.", bridge.address());
outln!("It lets in {}, from a paired device.", logins.join(", "));
bridge
.serve(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
/// The bridge `luxe remote` runs: starting sessions with this luxe, drawing them as the TUI does,
/// and named for the computer when Tailscale said what it's called.
async fn bridge(
port: u16,
access: Access,
machine: Option<String>,
) -> anyhow::Result<luxe_remote::Bridge> {
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
let runtime_dir = luxe_core::user_dirs::luxe_runtime_dir();
let luxe = std::env::current_exe()
.map_err(|error| anyhow::anyhow!("could not find this luxe to start sessions: {error}"))?;
let bridge = luxe_remote::Bridge::bind(address, runtime_dir, access).await?;
let bridge = bridge.starting_sessions(luxe);
let bridge = bridge.rendering_with(std::sync::Arc::new(render::TuiRenderer));
Ok(match machine {
Some(machine) => bridge.named(machine),
None => bridge,
})
}
/// The owner, as Tailscale reports them, plus any `--allow`ed logins. Without the owner, only an
/// explicit `--allow` lets anyone in: guessing would mean an allowlist nobody chose.
fn allowed_logins(
owner: Result<Tailnet, luxe_remote::TailnetError>,
mut allow: Vec<String>,
) -> anyhow::Result<Vec<String>> {
match owner {
Ok(tailnet) => allow.insert(0, tailnet.login),
Err(error) if allow.is_empty() => {
return Err(error).context(
"couldn't learn this machine's tailnet login; pass `--allow <login>` to name who \
may use the bridge",
);
}
Err(error) => tracing::warn!(%error, "serving only the --allow logins"),
}
let mut seen = std::collections::HashSet::new();
allow.retain(|login| seen.insert(login.clone()));
Ok(allow)
}
fn list_devices(devices: &DeviceBook) -> anyhow::Result<()> {
let paired = devices.devices();
if paired.is_empty() {
outln!("No devices are paired. Pair one with `luxe remote pair`.");
return Ok(());
}
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_secs());
for device in paired {
let age = age(now.saturating_sub(device.paired_at));
outln!(" {} {} ({}, paired {age})", device.id, device.name, device.login);
}
outln!("\nUnpair one with `luxe remote devices revoke <id>`.");
Ok(())
}
fn revoke(devices: &DeviceBook, id: &str) -> anyhow::Result<()> {
match devices.revoke(id)? {
Some(device) => outln!("Unpaired {} ({id}); its open sessions close too.", device.name),
None => anyhow::bail!("no paired device has the id {id}; see `luxe remote devices`"),
}
Ok(())
}
/// How long ago, in the largest whole unit that fits.
fn age(seconds: u64) -> String {
const DAY: u64 = 24 * 60 * 60;
match seconds / DAY {
0 => "today".to_string(),
1 => "yesterday".to_string(),
days => format!("{days} days ago"),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The owner always leads the allowlist, and nobody is let in when no one was named.
///
/// The break this catches: serving an empty allowlist when Tailscale can't be asked (which
/// shuts everyone out with no reason given), or dropping the owner once `--allow` is used.
#[test]
fn the_allowlist_is_the_owner_and_whoever_is_named() {
let owner = || Ok(Tailnet { login: "alex@github".into(), dns_name: "desk".into() });
let missing = || Err(luxe_remote::TailnetError::NotInstalled);
let both = allowed_logins(owner(), vec!["sam@github".into()]).unwrap();
assert_eq!(both, ["alex@github", "sam@github"]);
let repeated = allowed_logins(owner(), vec!["alex@github".into()]).unwrap();
assert_eq!(repeated, ["alex@github"]);
assert_eq!(allowed_logins(missing(), vec!["sam@github".into()]).unwrap(), ["sam@github"]);
assert!(allowed_logins(missing(), vec![]).is_err());
}
}

View File

@@ -0,0 +1,80 @@
//! The invitation a phone scans: a QR code in the terminal, and the same link in words.
use std::io::Write;
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
use std::time::Duration;
use luxe_remote::{DeviceBook, Tailnet};
use qrcode::render::unicode::Dense1x2;
use qrcode::QrCode;
use crate::output::outln;
/// `luxe remote pair`: one invitation, shown.
pub(super) async fn pair(port: u16, devices: &DeviceBook) -> anyhow::Result<()> {
match luxe_remote::this_machine().await {
Ok(tailnet) => show(port, devices, &tailnet),
Err(error) => {
let token = devices.invite()?;
outln!("Tailscale couldn't name this machine ({error}).");
outln!("Open /pair on the bridge's tailnet address and add #{token} to it.");
Ok(())
}
}
}
/// Issues an invitation and shows it as a QR code and a link to `https://<this machine>/pair`.
///
/// The invitation rides in the link's fragment, which a browser never sends to a server, so it
/// stays out of Serve's and the bridge's logs.
pub(super) fn show(port: u16, devices: &DeviceBook, tailnet: &Tailnet) -> anyhow::Result<()> {
let token = devices.invite()?;
let link = format!("https://{}/pair#{token}", tailnet.dns_name);
if let Some(code) = qr(&link) {
outln!("{code}");
}
outln!("On the phone or tablet: install Tailscale, sign in as {}, then", tailnet.login);
outln!("scan this or open the link. It pairs one device, within ten minutes.\n");
outln!(" {link}\n");
if !bridge_listening(port) {
outln!("The bridge isn't running yet: start it with `luxe remote` before scanning.");
}
let _ = std::io::stdout().flush();
Ok(())
}
/// `text` as a QR code drawn in half-height blocks, light modules as blocks so it reads on the
/// dark background most terminals have.
fn qr(text: &str) -> Option<String> {
let code = QrCode::new(text.as_bytes()).ok()?;
let drawn = code
.render::<Dense1x2>()
.dark_color(Dense1x2::Light)
.light_color(Dense1x2::Dark)
.quiet_zone(true)
.build();
Some(drawn)
}
/// Whether something answers on the bridge's port.
pub(super) fn bridge_listening(port: u16) -> bool {
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
TcpStream::connect_timeout(&address, Duration::from_millis(500)).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
/// The code is drawn with modules as blocks and a quiet zone a camera can find.
///
/// The break this catches: losing the quiet zone or the inversion, either of which leaves a
/// code most phone cameras won't pick out of a dark terminal.
#[test]
fn the_code_has_a_quiet_zone_of_blocks() {
let code = qr("https://desk.tail1234.ts.net/pair#abc").unwrap();
let first = code.lines().next().unwrap();
assert!(first.chars().all(|c| c == '\u{2588}'), "the border is solid: {first:?}");
assert!(code.lines().count() > 10);
}
}

View File

@@ -0,0 +1,255 @@
//! The TUI's renderer, handed to the bridge so the phone draws text the way the terminal does.
use luxe_remote::{StatusFacts, StatusSegment, StatusTone};
use luxe_tui::markdown::html;
use luxe_tui::statusline::plain;
/// Markdown, highlighting, tool glyphs and the status line's wording from `luxe-tui`.
pub(super) struct TuiRenderer;
impl luxe_remote::Renderer for TuiRenderer {
fn markdown(&self, text: &str, voice: luxe_remote::Voice) -> String {
let voice = match voice {
luxe_remote::Voice::Answer => html::Voice::Answer,
luxe_remote::Voice::Reasoning => html::Voice::Reasoning,
};
html::render(text, voice)
}
fn tool_glyph(&self, tool: &str) -> String {
// the app's font has the Nerd Font marks whatever this terminal can draw
luxe_tui::widgets::tool_icon(tool).at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
}
fn status(&self, facts: &StatusFacts) -> Vec<StatusSegment> {
let facts = plain::Facts {
model: facts.model.as_ref(),
thinking: facts.thinking,
context: facts.context.map(|usage| (usage.used_tokens, usage.context_window)),
plan: facts.plan.as_ref(),
session: facts.session.as_ref(),
};
plain::segments(&facts).into_iter().map(status_segment).collect()
}
fn image_glyph(&self) -> String {
luxe_tui::glyphs::Icon::Image.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
}
fn code_line(&self, text: &str, language: Option<&str>) -> String {
html::code_line(text, language)
}
fn todo_mark(&self, status: luxe_core::TodoSummaryStatus) -> String {
luxe_tui::marks::todo(status, luxe_tui::glyphs::GlyphTier::Nerd).to_string()
}
fn change_mark(&self, status: luxe_core::workspace::FileChangeStatus) -> String {
luxe_tui::marks::change(status).to_string()
}
fn file_mark(&self, name: &str) -> luxe_remote::FileMark {
// the extension, as the TUI's tree reads it for a file's mark
let extension = name.rsplit_once('.').map_or("", |(_, extension)| extension);
let icon = luxe_tui::widgets::language_icon(&extension.to_ascii_lowercase());
let glyph = icon.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string();
luxe_remote::FileMark { glyph, hue: mark_hue(luxe_tui::widgets::language_hue_role(icon)) }
}
fn folder_mark(&self) -> String {
luxe_tui::glyphs::Icon::Folder.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
}
fn branch_mark(&self) -> String {
luxe_tui::glyphs::Icon::Branch.at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
}
fn mode_mark(&self, mode: &str) -> String {
luxe_tui::modes::icon(mode).at(luxe_tui::glyphs::GlyphTier::Nerd).to_string()
}
fn github_marks(&self) -> luxe_remote::GithubMarks {
use luxe_tui::glyphs::{GlyphTier::Nerd, Icon, Mark};
luxe_remote::GithubMarks {
pull_request: Icon::PullRequest.at(Nerd).to_owned(),
issue: Icon::Issue.at(Nerd).to_owned(),
yes: Mark::Yes.at(Nerd).to_owned(),
no: Mark::No.at(Nerd).to_owned(),
waiting: Mark::Waiting.at(Nerd).to_owned(),
elision: Mark::Elision.at(Nerd).to_owned(),
}
}
fn ago(&self, at: u64, now: u64) -> String {
luxe_tui::github_detail::ago(at, now)
}
fn github_readable(&self, body: &str) -> String {
luxe_tui::github_detail::readable(body)
}
fn home_icon(&self, side: u32, colors: luxe_remote::TileColors) -> Option<Vec<u8>> {
luxe_tui::widgets::tile_png(side, colors.plate, colors.ink)
.inspect_err(|error| tracing::warn!(%error, side, "could not draw the app icon"))
.ok()
}
}
fn mark_hue(hue: luxe_tui::widgets::LanguageHue) -> luxe_remote::MarkHue {
use luxe_remote::MarkHue;
use luxe_tui::widgets::LanguageHue;
match hue {
LanguageHue::Warning => MarkHue::Warning,
LanguageHue::Info => MarkHue::Info,
LanguageHue::Success => MarkHue::Success,
LanguageHue::Error => MarkHue::Error,
LanguageHue::ThinkingUltra => MarkHue::ThinkingUltra,
LanguageHue::Text => MarkHue::Text,
LanguageHue::Muted => MarkHue::Muted,
}
}
fn status_segment(segment: plain::Segment) -> StatusSegment {
let kind = match segment.kind {
plain::Kind::Context => "context",
plain::Kind::Cost => "cost",
plain::Kind::Thinking => "thinking",
plain::Kind::Model => "model",
};
let tone = match segment.tone {
plain::Tone::Plain => StatusTone::Plain,
plain::Tone::Warning => StatusTone::Warning,
plain::Tone::Error => StatusTone::Error,
};
StatusSegment { kind, glyph: segment.glyph.map(str::to_string), label: segment.label, tone }
}
#[cfg(test)]
mod tests {
use luxe_remote::{Renderer, Voice};
use super::TuiRenderer;
/// The break this catches: the voices crossed, so reasoning loses its line breaks and an
/// answer keeps the model's.
#[test]
fn each_voice_reaches_the_tui_as_itself() {
assert_eq!(TuiRenderer.markdown("a\nb", Voice::Reasoning), "<p>a<br>b</p>");
assert_eq!(TuiRenderer.markdown("a\nb", Voice::Answer), "<p>a b</p>");
}
/// The break this catches: the glyph taken at this terminal's tier, which is ASCII or none
/// under a plain terminal, though the app's font always has the marks.
#[test]
fn tool_glyphs_are_the_nerd_font_marks() {
let nerd = luxe_tui::widgets::tool_icon("bash").at(luxe_tui::glyphs::GlyphTier::Nerd);
luxe_tui::glyphs::set_tier(luxe_tui::glyphs::GlyphTier::Ascii);
let glyph = TuiRenderer.tool_glyph("bash");
let image = TuiRenderer.image_glyph();
let done = TuiRenderer.todo_mark(luxe_core::TodoSummaryStatus::Completed);
luxe_tui::glyphs::set_tier(luxe_tui::glyphs::GlyphTier::Nerd);
assert_eq!(glyph, nerd);
let nerd_image = luxe_tui::glyphs::Icon::Image.at(luxe_tui::glyphs::GlyphTier::Nerd);
assert_eq!(image, nerd_image, "an attached image's mark too");
let nerd_done = luxe_tui::glyphs::Mark::Yes.at(luxe_tui::glyphs::GlyphTier::Nerd);
assert_eq!(done, nerd_done, "a todo's mark too");
}
/// The break this catches: a diff row's code left plain, or a changed file's letter crossed,
/// so the phone's dock and diffs stop matching the TUI's.
#[test]
fn diffs_and_changes_reach_the_tui() {
let code = TuiRenderer.code_line("fn a() {}", Some("rs"));
assert!(code.starts_with("<span class=\"t-accent-secondary\">fn</span>"), "{code}");
let modified = luxe_core::workspace::FileChangeStatus::Modified;
assert_eq!(TuiRenderer.change_mark(modified), "M");
}
/// The break this catches: a file's mark read from the whole name or a cased extension, a
/// language's hue crossed with another's, or the folder's mark taken at this terminal's tier,
/// so the phone's tree stops matching the TUI's.
#[test]
fn tree_marks_are_the_tui_language_marks() {
use luxe_remote::MarkHue;
use luxe_tui::glyphs::{GlyphTier, Icon};
let nerd = |icon: Icon| icon.at(GlyphTier::Nerd).to_string();
luxe_tui::glyphs::set_tier(GlyphTier::Ascii);
let rust = TuiRenderer.file_mark("main.RS");
let toml = TuiRenderer.file_mark("Cargo.toml");
let folder = TuiRenderer.folder_mark();
luxe_tui::glyphs::set_tier(GlyphTier::Nerd);
assert_eq!(
rust,
luxe_remote::FileMark { glyph: nerd(Icon::LangRust), hue: MarkHue::Warning }
);
assert_eq!(
toml,
luxe_remote::FileMark { glyph: nerd(Icon::LangToml), hue: MarkHue::Error }
);
assert_eq!(TuiRenderer.file_mark("Makefile").hue, MarkHue::Muted);
assert_eq!(folder, nerd(Icon::Folder));
}
/// The break this catches: the project panel's branch drawn with another mark than the TUI's
/// project section, or at this terminal's tier rather than the phone's.
#[test]
fn the_branch_mark_is_the_tui_branch_mark() {
use luxe_tui::glyphs::{GlyphTier, Icon};
luxe_tui::glyphs::set_tier(GlyphTier::Ascii);
let branch = TuiRenderer.branch_mark();
luxe_tui::glyphs::set_tier(GlyphTier::Nerd);
assert_eq!(branch, Icon::Branch.at(GlyphTier::Nerd));
}
/// The break this catches: a GitHub mark taken at this terminal's tier or crossed with
/// another, ages in other words than the TUI's, or a body's HTML left as tags.
#[test]
fn github_reaches_the_tui_marks_and_words() {
use luxe_tui::glyphs::{GlyphTier, Icon, Mark};
luxe_tui::glyphs::set_tier(GlyphTier::Ascii);
let marks = TuiRenderer.github_marks();
luxe_tui::glyphs::set_tier(GlyphTier::Nerd);
assert_eq!(marks.pull_request, Icon::PullRequest.at(GlyphTier::Nerd));
assert_eq!(marks.issue, Icon::Issue.at(GlyphTier::Nerd));
assert_eq!(marks.yes, Mark::Yes.at(GlyphTier::Nerd));
assert_eq!(marks.no, Mark::No.at(GlyphTier::Nerd));
assert_eq!(marks.waiting, Mark::Waiting.at(GlyphTier::Nerd));
assert_eq!(marks.elision, Mark::Elision.at(GlyphTier::Nerd));
assert_eq!(TuiRenderer.ago(1_000, 1_000 + 3 * 3600), "3h ago");
let body = TuiRenderer.github_readable("<details><summary>Notes</summary>x</details>");
assert!(!body.contains('<'), "{body}");
}
/// The break this catches: the bridge's default (no icon) left in place, so the home screen
/// gets a screenshot of the page instead of the mark, or the size asked for not passed on.
#[test]
fn the_icon_is_the_tui_tile_at_the_size_asked_for() {
let colors = luxe_remote::TileColors { plate: [0; 3], ink: [0xff; 3] };
let png = TuiRenderer.home_icon(180, colors).expect("an icon");
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG");
// the header chunk's width and height, big-endian, after the signature and chunk head
assert_eq!(png[16..24], [0, 0, 0, 180, 0, 0, 0, 180]);
}
/// The break this catches: facts dropped or crossed on the way to the TUI, so the phone's
/// status line misses the context reading, or colors a full window as a roomy one.
#[test]
fn status_facts_reach_the_tui_and_come_back_as_its_segments() {
let facts: luxe_remote::StatusFacts = serde_json::from_value(serde_json::json!({
"model": {"provider": "anthropic", "model": "claude-x"},
"thinking": "medium",
"context": {"used_tokens": 950, "context_window": 1000},
}))
.expect("the app's status facts parse");
let segments = TuiRenderer.status(&facts);
let words: Vec<_> = segments.iter().map(|s| (s.kind, s.label.as_str(), s.tone)).collect();
assert_eq!(
words,
[
("context", "95.0%/1.0k", luxe_remote::StatusTone::Error),
("thinking", "med", luxe_remote::StatusTone::Plain),
("model", "claude-x", luxe_remote::StatusTone::Plain),
]
);
}
}

View File

@@ -0,0 +1,172 @@
//! `luxe remote setup` — from nothing to a paired phone, asking before each step that changes
//! something outside luxe.
//!
//! Four steps: Tailscale is there and signed in; Serve carries `https://<this machine>/` to the
//! bridge; a user service runs the bridge at login; and an invitation to scan. Each step that is
//! already done says so and moves on, so running setup again is how to check it.
use std::io::{BufRead, IsTerminal, Write};
use std::path::PathBuf;
use luxe_remote::service::Launch;
use luxe_remote::{DeviceBook, Published, Tailnet, TailnetError};
use crate::output::{out, outln};
/// Runs every step in order. Only a missing or signed-out Tailscale stops it.
pub(super) async fn setup(
port: u16,
allow: Vec<String>,
devices: &DeviceBook,
) -> anyhow::Result<()> {
let tailnet = check_tailscale().await?;
publish_step(port, &tailnet).await;
service_step(port, &tailnet, allow);
wait_for_bridge(port).await;
outln!();
super::invitation::show(port, devices, &tailnet)
}
/// Gives a service that just started up to two seconds to bind its port.
async fn wait_for_bridge(port: u16) {
for _ in 0..10 {
if super::invitation::bridge_listening(port) {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
async fn check_tailscale() -> anyhow::Result<Tailnet> {
match luxe_remote::this_machine().await {
Ok(tailnet) => {
outln!("Tailscale: signed in as {} on {}.", tailnet.login, tailnet.dns_name);
Ok(tailnet)
}
Err(error) => {
outln!("{}", tailscale_advice(&error));
Err(error.into())
}
}
}
fn tailscale_advice(error: &TailnetError) -> &'static str {
match error {
TailnetError::NotInstalled => {
"Install Tailscale from https://tailscale.com/download and sign in, then run \
`luxe remote setup` again."
}
TailnetError::NotRunning(_) => {
"Sign in to Tailscale with `tailscale up`, then run `luxe remote setup` again."
}
TailnetError::Failed(_) | TailnetError::Unreadable(_) => {
"Check that Tailscale is running with `tailscale status`, then run `luxe remote setup` \
again."
}
}
}
async fn publish_step(port: u16, tailnet: &Tailnet) {
let address = format!("https://{}/", tailnet.dns_name);
match luxe_remote::published(port).await {
Ok(Published::Here) => outln!("Serve: {address} leads to the bridge."),
Ok(Published::Elsewhere(target)) => outln!(
"Serve: {address} already leads to {target}, so setup leaves it alone. \
`tailscale serve --bg {port}` would point it at the bridge instead."
),
Ok(Published::Nowhere) => offer_publish(port, &address).await,
Err(error) => outln!("Serve: couldn't read its settings ({error})."),
}
}
async fn offer_publish(port: u16, address: &str) {
let question = format!("Publish the bridge at {address}, for your tailnet only?");
if !confirm(&question) {
outln!("Skipped. `tailscale serve --bg {port}` publishes it when you're ready.");
return;
}
match luxe_remote::publish(port).await {
Ok(()) => outln!("Serve: {address} now leads to the bridge."),
Err(error) => {
outln!("Serve: {error}");
outln!("{}", SERVE_HINT);
}
}
}
/// What usually stops `tailscale serve` for an ordinary account.
const SERVE_HINT: &str = if cfg!(target_os = "linux") {
"If it said access denied, let your account manage Tailscale with \
`sudo tailscale set --operator=$USER`, then run setup again."
} else {
"Fix what Tailscale said above, then run setup again."
};
fn service_step(port: u16, tailnet: &Tailnet, allow: Vec<String>) {
if luxe_remote::service::installed() {
outln!("Service: installed, so the bridge runs whenever you're signed in.");
return;
}
if !confirm("Run the bridge whenever you're signed in, as a user service?") {
outln!("Skipped. Run `luxe remote` yourself whenever your devices should reach luxe.");
return;
}
let launch =
Launch { program: luxe_program(), args: service_args(port, &tailnet.login, allow) };
match luxe_remote::service::install(&launch) {
Ok(recorded) => outln!("Service: installed ({recorded}) and started."),
Err(error) => outln!("Service: {error}"),
}
}
/// The bridge's flags as the service runs it, the owner named outright so the service doesn't
/// depend on reaching Tailscale as it starts.
fn service_args(port: u16, owner: &str, allow: Vec<String>) -> Vec<String> {
let mut args = vec!["remote".into(), "--port".into(), port.to_string()];
for login in std::iter::once(owner.to_string()).chain(allow) {
args.extend(["--allow".into(), login]);
}
args
}
/// This binary, by the path on `PATH` when that is the same file, since an upgrade replaces the
/// file a package manager links from `PATH` and leaves a versioned path behind.
fn luxe_program() -> PathBuf {
let running = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("luxe"));
let on_path = luxe_core::program::resolve("luxe");
let same = |path: &PathBuf| path.canonicalize().ok() == running.canonicalize().ok();
on_path.filter(same).unwrap_or(running)
}
/// Asks a yes-or-no question, yes by default. Without a terminal to ask, the answer is no.
fn confirm(question: &str) -> bool {
if !std::io::stdin().is_terminal() {
outln!("{question} Not asked, with no terminal to answer in.");
return false;
}
out!("{question} [Y/n] ");
let _ = std::io::stdout().flush();
let mut answer = String::new();
if std::io::stdin().lock().read_line(&mut answer).is_err() {
return false;
}
let answer = answer.trim().to_lowercase();
answer.is_empty() || answer.starts_with('y')
}
#[cfg(test)]
mod tests {
use super::*;
/// The service names the owner and every `--allow`, on the port setup was given.
///
/// The break this catches: a service that relies on finding Tailscale as it starts, which
/// launchd's bare `PATH` doesn't, so the bridge comes up letting nobody in.
#[test]
fn the_service_names_who_it_lets_in() {
let args = service_args(4600, "alex@github", vec!["sam@github".into()]);
let expected =
["remote", "--port", "4600", "--allow", "alex@github", "--allow", "sam@github"];
assert_eq!(args, expected);
}
}

View File

@@ -9,14 +9,18 @@
//! terminal (the TUI owns the screen), so that holds without any special care here — and
//! `rpc_stdout_carries_only_protocol_frames` keeps it holding.
mod frame;
mod translate;
use frame::write_frame;
pub(super) use frame::{Opening, SharedTranscript};
use luxe_core::engine::Action;
use luxe_core::event::Action as WireAction;
use luxe_core::Event;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::sync::mpsc;
use translate::{to_engine_action, CatalogResolver, GithubWrites, ModelResolver, Policy, Rejected};
use translate::{to_engine_action, Rejected};
pub(super) use translate::{CatalogResolver, GithubWrites, ModelResolver, Policy};
/// Depth of the channel carrying locally-generated frames (rejections) to the single writer.
///
@@ -24,6 +28,9 @@ use translate::{to_engine_action, CatalogResolver, GithubWrites, ModelResolver,
/// already being told so.
const LOCAL_FRAME_BUFFER: usize = 32;
/// The catalog a session's clients resolve and list models through, shared by every one of them.
pub(super) type Models = std::sync::Arc<dyn ModelResolver + Send + Sync>;
/// Run the RPC front-end against stdio until the client closes the stream or stdin ends.
///
/// Args: `(settings, github_writes)` — the second is `--github-writes`, which lets the client
@@ -44,6 +51,7 @@ pub(crate) async fn run_rpc(
let policy = Policy {
github_writes: GithubWrites::for_launch(github_writes, mode),
github_sections: luxe_core::config::Config::load(&settings.state_root).github.sections(),
joined: false,
};
let handle = crate::engine_setup::build_engine(
&settings,
@@ -63,6 +71,9 @@ pub(crate) async fn run_rpc(
},
crate::workspace_runtime::pull_request_watch(&settings.work_root),
);
// Shared like a terminal's, which is how a phone reaches a session the bridge started
let (events, _sharing) =
super::share::share(events, handle.actions.clone(), &settings, &handle.session_id.0);
let ready = Event::Ready {
protocol_version: luxe_core::PROTOCOL_VERSION,
@@ -82,12 +93,12 @@ pub(crate) async fn run_rpc(
}
serve(
ready,
ready.into(),
events,
handle.actions,
tokio::fs::File::from_std(input),
tokio::io::stdout(),
&CatalogResolver,
std::sync::Arc::new(CatalogResolver { settings: settings.clone() }),
policy,
)
.await?;
@@ -100,21 +111,25 @@ pub(crate) async fn run_rpc(
/// Generic over the streams so the protocol — handshake, framing, translation, refusal, shutdown —
/// is exercised end to end in tests without a real stdin, a real terminal, or a live provider.
/// `run_rpc` is this function with stdio and the real catalog plugged in.
async fn serve<R, W>(
ready: Event,
///
/// A client that joined a terminal's session (`policy.joined`) never closes the engine: its
/// hangup or `close` ends its own connection, and the terminal carries on.
pub(super) async fn serve<R, W>(
opening: Opening,
mut events: mpsc::Receiver<Event>,
engine_tx: mpsc::Sender<Action>,
input: R,
mut output: W,
models: &'static (dyn ModelResolver + Sync),
models: Models,
policy: Policy,
) -> anyhow::Result<()>
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin,
{
if !emit(&mut output, &ready).await? {
engine_tx.send(Action::Close).await.ok();
let joined = policy.joined;
if !emit_opening(&mut output, opening).await? {
close_unless_joined(&engine_tx, joined).await;
return Ok(());
}
@@ -131,6 +146,8 @@ where
// ordered against each other: `select!` takes whichever is ready. Nothing needs them to be — a
// refusal is about the client's own input, not about engine state — and pretending otherwise
// would mean holding one stream up for the other.
//
// A joined client's reader ending *is* the end of its session, since the engine outlives it.
let mut refusals_open = true;
loop {
let frame = tokio::select! {
@@ -140,6 +157,7 @@ where
},
refusal = local_rx.recv(), if refusals_open => match refusal {
Some(refusal) => refusal,
None if joined => break,
None => {
refusals_open = false;
continue;
@@ -163,19 +181,26 @@ where
reader.abort();
// The engine may already be gone (the client sent `close`); saying so twice is harmless.
engine_tx.send(Action::Close).await.ok();
close_unless_joined(&engine_tx, joined).await;
Ok(())
}
/// Close the engine as a client leaves, unless the client only joined it.
async fn close_unless_joined(engine_tx: &mpsc::Sender<Action>, joined: bool) {
if !joined {
engine_tx.send(Action::Close).await.ok();
}
}
/// Read wire actions until EOF, forwarding what translates and refusing what does not.
///
/// EOF means the client is gone, so the engine is told to close rather than left running behind a
/// stream nobody is reading.
/// stream nobody is reading. A joined client's EOF or `close` only ends the read.
async fn read_actions<R>(
input: R,
engine_tx: mpsc::Sender<Action>,
local_tx: mpsc::Sender<Event>,
models: &'static (dyn ModelResolver + Sync),
models: Models,
policy: Policy,
) where
R: AsyncRead + Unpin,
@@ -193,18 +218,26 @@ async fn read_actions<R>(
if line.trim().is_empty() {
continue;
}
let action = match parse_action(&line, models, &policy) {
Ok(action) => action,
let reply = match parse_action(&line, &*models, &policy) {
Ok(Inbound::Engine(action)) => Ok(*action),
Ok(Inbound::Answer(answer)) => Err(answer),
Err(rejected) => {
let refusal =
Event::ActionRejected { kind: rejected.kind, reason: rejected.reason };
if local_tx.send(refusal).await.is_err() {
Err(Event::ActionRejected { kind: rejected.kind, reason: rejected.reason })
}
};
let action = match reply {
Ok(action) => action,
Err(reply) => {
if local_tx.send(reply).await.is_err() {
break;
}
continue;
}
};
let closing = matches!(action, Action::Close);
if closing && policy.joined {
break;
}
if engine_tx.send(action).await.is_err() {
break;
}
@@ -212,7 +245,7 @@ async fn read_actions<R>(
break;
}
}
engine_tx.send(Action::Close).await.ok();
close_unless_joined(&engine_tx, policy.joined).await;
}
/// Parse and translate one inbound line.
@@ -221,9 +254,9 @@ async fn read_actions<R>(
/// is testable without any IO at all.
fn parse_action(
line: &str,
models: &(dyn ModelResolver + Sync),
models: &(dyn ModelResolver + Send + Sync),
policy: &Policy,
) -> Result<Action, Rejected> {
) -> Result<Inbound, Rejected> {
// Read the envelope before the payload, so a frame that names itself and then fails to
// deserialize is still refused *by name*. Reporting `kind: null` for a `steer_turn` missing its
// text sends the client looking through every frame it wrote instead of the one that was wrong.
@@ -232,15 +265,49 @@ fn parse_action(
let kind = raw.get("kind").and_then(serde_json::Value::as_str).map(str::to_string);
let wire: WireAction = serde_json::from_value(raw)
.map_err(|error| Rejected { kind, reason: error.to_string() })?;
to_engine_action(wire, models, policy)
if let WireAction::ListModels { request_id } = wire {
return Ok(Inbound::Answer(Event::ModelsListed { request_id, models: models.choices() }));
}
to_engine_action(wire, models, policy).map(|action| Inbound::Engine(Box::new(action)))
}
/// What one inbound line comes to.
#[derive(Debug)]
enum Inbound {
/// An action for the engine
Engine(Box<Action>),
/// An answer for this client alone, which the engine has no part in
Answer(Event),
}
/// Write one frame, reporting `false` once the client has stopped reading.
///
/// A hangup is how a session ends when the other end is `head` or a closed editor pane, so it
/// resolves to a clean exit rather than an error written to a pipe nobody is holding.
async fn emit<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> anyhow::Result<bool> {
match write_frame(out, event).await {
/// Send `ready` and any transcript, saying whether the client is still there.
///
/// Takes the opening by value so the transcript is let go once sent: held for the connection, it
/// would pin a superseded copy of every message, and each commit would copy the snapshot's whole
/// list to append to it.
async fn emit_opening<W: AsyncWrite + Unpin>(
out: &mut W,
opening: Opening,
) -> anyhow::Result<bool> {
if !emit(out, &opening.ready).await? {
return Ok(false);
}
match opening.transcript {
Some(transcript) => emit(out, &transcript).await,
None => Ok(true),
}
}
async fn emit<W, F>(out: &mut W, frame: &F) -> anyhow::Result<bool>
where
W: AsyncWrite + Unpin,
F: serde::Serialize + ?Sized,
{
match write_frame(out, frame).await {
Ok(()) => Ok(true),
Err(error)
if matches!(
@@ -255,23 +322,5 @@ async fn emit<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> anyhow::Resu
}
}
/// Write one frame and flush it, so a streaming client sees tokens as they arrive.
///
/// A frame that cannot serialize is logged and dropped rather than ending the session: losing one
/// event is recoverable for a client, and a dead stream is not.
async fn write_frame<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> std::io::Result<()> {
let line = match serde_json::to_string(event) {
Ok(line) => line,
Err(error) => {
tracing::warn!(%error, "rpc: dropping an event that would not serialize");
return Ok(());
}
};
out.write_all(line.as_bytes()).await?;
out.write_all(b"\n").await?;
out.flush().await?;
Ok(())
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,99 @@
//! Frames — one JSON object per line, written without growing one buffer to the biggest frame.
//!
//! A joiner's `session_loaded` carries the whole transcript, tens of megabytes on a long session,
//! and a phone joins again on every reconnect. Encoded into one `String` it grows by doubling,
//! about four times its size allocated for every join, so a frame is encoded into fixed-size pieces
//! instead, and a shared session's transcript goes out from the snapshot's copy, not a clone of it.
use luxe_core::event::SessionMessage;
use luxe_core::Event;
use serde::Serialize;
use std::sync::Arc;
use tokio::io::{AsyncWrite, AsyncWriteExt};
/// Bytes in each piece of an encoded frame.
const CHUNK_BYTES: usize = 64 * 1024;
/// What a client is sent ahead of the event stream: `ready`, then for a joiner the transcript.
pub(in crate::cli) struct Opening {
pub(in crate::cli) ready: Event,
/// The transcript so far, for a client joining a session already under way
pub(in crate::cli) transcript: Option<SharedTranscript>,
}
impl From<Event> for Opening {
fn from(ready: Event) -> Self {
Self { ready, transcript: None }
}
}
/// A session's transcript, sent as its `session_loaded` frame and shared with the snapshot that
/// keeps it, so a join doesn't copy every message.
pub(in crate::cli) struct SharedTranscript {
pub(in crate::cli) session_id: String,
pub(in crate::cli) messages: Arc<Vec<SessionMessage>>,
}
/// `Event::SessionLoaded`'s wire shape over borrowed fields; a test pins it to the event's own.
#[derive(Serialize)]
#[serde(tag = "kind", content = "content", rename_all = "snake_case")]
enum LoadedFrame<'a> {
SessionLoaded { session_id: &'a str, messages: &'a [SessionMessage] },
}
impl Serialize for SharedTranscript {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let frame =
LoadedFrame::SessionLoaded { session_id: &self.session_id, messages: &self.messages };
frame.serialize(serializer)
}
}
/// Write one frame and flush it, so a streaming client sees tokens as they arrive.
///
/// A frame that cannot serialize is logged and dropped rather than ending the session: losing one
/// event is recoverable for a client, and a dead stream is not. Nothing is written until the whole
/// frame has encoded, so a failure never leaves half a line.
pub(super) async fn write_frame<W, F>(out: &mut W, frame: &F) -> std::io::Result<()>
where
W: AsyncWrite + Unpin,
F: Serialize + ?Sized,
{
let mut encoded = Pieces::default();
if let Err(error) = serde_json::to_writer(&mut encoded, frame) {
tracing::warn!(%error, "rpc: dropping an event that would not serialize");
return Ok(());
}
for piece in encoded.full.iter().chain(std::iter::once(&encoded.current)) {
out.write_all(piece).await?;
}
out.write_all(b"\n").await?;
out.flush().await
}
/// An encoded frame in pieces of at most `CHUNK_BYTES`. The first grows like any buffer, so a
/// token's frame costs what it always did, and a large frame is never copied into a bigger one.
#[derive(Default)]
struct Pieces {
full: Vec<Vec<u8>>,
current: Vec<u8>,
}
impl std::io::Write for Pieces {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if self.current.len() == CHUNK_BYTES {
let next = Vec::with_capacity(CHUNK_BYTES);
self.full.push(std::mem::replace(&mut self.current, next));
}
let taken = bytes.len().min(CHUNK_BYTES - self.current.len());
self.current.extend_from_slice(&bytes[..taken]);
Ok(taken)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,88 @@
use super::*;
use luxe_core::message::Message;
use luxe_core::session::EntryId;
fn messages() -> Vec<SessionMessage> {
["first", "second"]
.into_iter()
.map(|text| SessionMessage { entry_id: EntryId(text.into()), message: Message::user(text) })
.collect()
}
async fn written<F: Serialize + ?Sized>(frame: &F) -> String {
let mut out = Vec::new();
write_frame(&mut out, frame).await.expect("writing to memory");
String::from_utf8(out).expect("frames are UTF-8")
}
/// The shared transcript goes out byte for byte as the `session_loaded` event would.
///
/// The break this catches: the borrowed copy of the event's shape drifting from `Event`, a renamed
/// field or a lost `rename_all`, which every joining client would read as an unknown frame.
#[test]
fn the_shared_transcript_encodes_as_session_loaded() {
let shared =
SharedTranscript { session_id: "session-1".into(), messages: Arc::new(messages()) };
let event = Event::SessionLoaded { session_id: "session-1".into(), messages: messages() };
assert_eq!(serde_json::to_string(&shared).unwrap(), serde_json::to_string(&event).unwrap());
}
/// A frame bigger than several pieces arrives whole, as one line.
///
/// The break this catches: losing the last piece or the full ones, or cutting a piece a byte off,
/// which garbles exactly the large `session_loaded` frame a long session sends.
#[tokio::test]
async fn a_frame_of_many_pieces_is_written_whole() {
let text: String =
(0..CHUNK_BYTES * 3 + 17).map(|at| char::from(b'a' + (at % 26) as u8)).collect();
let event = Event::Notice(text);
let expected = format!("{}\n", serde_json::to_string(&event).unwrap());
assert_eq!(written(&event).await, expected);
}
/// A large frame is held in pieces of one chunk at most, never one buffer of the whole.
///
/// The break this catches: dropping the cap on a piece, which grows the first one by doubling to the
/// frame's size, the very allocation this module exists to avoid.
#[test]
fn a_large_frame_is_held_in_chunk_sized_pieces() {
let mut encoded = Pieces::default();
serde_json::to_writer(&mut encoded, &"x".repeat(CHUNK_BYTES * 3)).unwrap();
assert_eq!(encoded.full.len(), 3);
assert!(encoded.full.iter().all(|piece| piece.len() == CHUNK_BYTES));
assert!(encoded.current.capacity() <= CHUNK_BYTES, "{}", encoded.current.capacity());
}
/// A token's frame still fits in one piece, so the common case pays for no more than it did.
///
/// The break this catches: starting every frame on a full piece, a 64 KB allocation for each of
/// the thousands of token deltas a reply streams.
#[test]
fn a_small_frame_stays_in_its_first_piece() {
let mut encoded = Pieces::default();
serde_json::to_writer(&mut encoded, &Event::Notice("hi".into())).unwrap();
assert!(encoded.full.is_empty());
assert!(encoded.current.capacity() < CHUNK_BYTES, "{}", encoded.current.capacity());
}
/// Serializes as a list whose second element fails, after the first has been encoded.
struct FailsPartway;
impl Serialize for FailsPartway {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::{Error, SerializeSeq};
let mut list = serializer.serialize_seq(Some(2))?;
list.serialize_element("encoded")?;
drop(list);
Err(S::Error::custom("cannot encode the rest"))
}
}
/// A frame that fails partway writes nothing rather than half a line.
///
/// The break this catches: streaming the encoding straight to the client, which leaves a broken
/// line that turns every later frame into a parse error.
#[tokio::test]
async fn a_frame_that_fails_partway_writes_nothing() {
assert_eq!(written(&FailsPartway).await, "");
}

View File

@@ -1,5 +1,6 @@
use super::*;
use luxe_core::provider::ModelInfo;
use tokio::io::AsyncWriteExt;
/// A resolver with no dependence on the developer's `models.json`.
struct FixedModels;
@@ -8,14 +9,42 @@ impl ModelResolver for FixedModels {
fn resolve(&self, provider: &str, id: &str) -> ModelInfo {
ModelInfo { r#ref: luxe_core::provider::ModelRef::new(provider, id), ..Default::default() }
}
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
vec![luxe_core::event::ModelChoice {
provider: "anthropic".into(),
model: "claude-sonnet-5".into(),
name: "Claude Sonnet 5".into(),
thinking_levels: vec![luxe_core::provider::ThinkingLevel::Off],
}]
}
}
fn policy(github_writes: GithubWrites) -> Policy {
Policy { github_writes, github_sections: Vec::new() }
Policy { github_writes, github_sections: Vec::new(), joined: false }
}
fn parse(line: &str) -> Result<Action, Rejected> {
parse_action(line, &FixedModels, &policy(GithubWrites::NotEnabled))
match parse_action(line, &FixedModels, &policy(GithubWrites::NotEnabled))? {
Inbound::Engine(action) => Ok(*action),
Inbound::Answer(answer) => panic!("answered without the engine: {answer:?}"),
}
}
/// `list_models` is answered to the client that asked, with the catalog's choices, and the
/// engine never hears of it.
///
/// The break this catches: forwarding it to the engine, which has no arm for it; or answering
/// with nothing, so the phone's picker opens empty.
#[tokio::test]
async fn the_protocol_answers_which_models_there_are() {
let ask = "{\"kind\":\"list_models\",\"content\":{\"request_id\":\"models:1\"}}\n";
let session = run_session(ask, Vec::new()).await;
let listed = session.frames.iter().find(|frame| frame["kind"] == "models_listed");
let listed = listed.expect("an answer");
assert_eq!(listed["content"]["request_id"], "models:1");
assert_eq!(listed["content"]["models"][0]["model"], "claude-sonnet-5");
assert!(session.actions.iter().all(|action| matches!(action, Action::Close)));
}
/// A well-formed frame becomes the engine action it names.
@@ -120,12 +149,12 @@ async fn run_session(input: &str, events: Vec<Event>) -> Session {
github_writes: false,
};
let served = serve(
ready,
ready.into(),
event_rx,
engine_tx,
server_read,
server_write,
&FixedModels,
std::sync::Arc::new(FixedModels),
policy(GithubWrites::NotEnabled),
);
tokio::time::timeout(std::time::Duration::from_secs(5), served)
@@ -338,12 +367,12 @@ async fn a_real_write_failure_is_not_mistaken_for_a_hangup() {
github_writes: false,
};
let served = serve(
ready,
ready.into(),
event_rx,
engine_tx,
server_read,
FailingWriter,
&FixedModels,
std::sync::Arc::new(FixedModels),
policy(GithubWrites::NotEnabled),
);
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), served)
@@ -383,12 +412,12 @@ async fn a_client_that_stops_reading_is_not_an_error() {
github_writes: false,
};
let served = serve(
ready,
ready.into(),
event_rx,
engine_tx,
server_read,
server_write,
&FixedModels,
std::sync::Arc::new(FixedModels),
policy(GithubWrites::NotEnabled),
);
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), served)
@@ -397,6 +426,61 @@ async fn a_client_that_stops_reading_is_not_an_error() {
assert!(outcome.is_ok(), "a client hangup is a clean end: {outcome:?}");
}
/// A joiner's transcript is let go once it's sent, while the client stays connected.
///
/// The break this catches: `serve` keeping the opening for the whole connection, which pins a stale
/// copy of every message per client and makes each commit copy the snapshot's whole list.
#[tokio::test]
async fn a_sent_transcript_is_released_while_the_client_stays() {
let message = luxe_core::event::SessionMessage {
entry_id: luxe_core::session::EntryId("entry-1".into()),
message: luxe_core::message::Message::user("hello"),
};
let messages = std::sync::Arc::new(vec![message]);
let transcript =
SharedTranscript { session_id: "session-1".into(), messages: messages.clone() };
let (served, mut lines) = serve_joiner(transcript);
lines.next_line().await.unwrap().expect("the ready frame");
let loaded = lines.next_line().await.unwrap().expect("the transcript frame");
assert!(loaded.starts_with(r#"{"kind":"session_loaded""#), "{loaded}");
assert_eq!(holders_once_settled(&messages).await, 1, "serve still holds the transcript");
assert!(!served.is_finished(), "the client is still connected");
served.abort();
}
/// Serve a joiner opening on `transcript`, connected until aborted, and what its client reads.
fn serve_joiner(
transcript: SharedTranscript,
) -> (
tokio::task::JoinHandle<anyhow::Result<()>>,
tokio::io::Lines<BufReader<tokio::io::DuplexStream>>,
) {
let (client_write, server_read) = tokio::io::duplex(1024);
let (server_write, client_read) = tokio::io::duplex(64 * 1024);
let (engine_tx, engine_rx) = mpsc::channel::<Action>(64);
let (event_tx, event_rx) = mpsc::channel::<Event>(64);
let opening = Opening { ready: Event::Notice("ready".into()), transcript: Some(transcript) };
let (models, policy) = (std::sync::Arc::new(FixedModels), policy(GithubWrites::NotEnabled));
let served = tokio::spawn(async move {
// Held open, so the session waits on its client instead of ending
let _open = (client_write, engine_rx, event_tx);
serve(opening, event_rx, engine_tx, server_read, server_write, models, policy).await
});
(served, BufReader::new(client_read).lines())
}
/// How many hold `messages` once anything still sending it has had its chance to let go.
async fn holders_once_settled<T>(messages: &std::sync::Arc<T>) -> usize {
for _ in 0..100 {
if std::sync::Arc::strong_count(messages) == 1 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
std::sync::Arc::strong_count(messages)
}
/// Every frame written is one line of JSON — the framing rule a client parses by.
///
/// `run_session` panics on any line that will not parse, so a stray `println!` anywhere in this

View File

@@ -39,6 +39,8 @@ pub(crate) struct Policy {
pub(crate) github_writes: GithubWrites,
/// The `/github` sections a bare `list_github` runs: the user's configured ones
pub(crate) github_sections: Vec<luxe_core::config::GithubSection>,
/// Whether the client joined a session a terminal runs, rather than starting its own
pub(crate) joined: bool,
}
/// Whether a client may publish to GitHub, and if not, why not.
@@ -73,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!(
@@ -95,16 +97,71 @@ pub(crate) trait ModelResolver {
/// same contract `--model` has always had, and it is what makes a local or proxied model
/// usable without an entry in anyone's catalog.
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo;
/// The models a client can switch to, configured ones first, for `list_models`.
fn choices(&self) -> Vec<luxe_core::event::ModelChoice>;
}
/// The real catalog: configured models first, models.dev filling the gaps, defaults under that.
pub(crate) struct CatalogResolver;
///
/// Holds the launch's settings because which providers can be reached depends on them: a key
/// passed on the command line reaches a provider nothing else configures.
pub(crate) struct CatalogResolver {
pub(crate) settings: crate::engine_setup::AgentSettings,
}
impl ModelResolver for CatalogResolver {
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo {
let config = crate::engine_setup::load_luxe_config();
crate::model_catalog::resolve_model(&config, provider, id).0
}
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
crate::model_catalog::choices(&self.settings)
}
}
/// Why the client's policy refuses `wire`, before it means anything to the engine.
fn policy_refusal(wire: &WireAction, policy: &Policy) -> Option<String> {
let kind = wire.kind();
if wire.writes_to_github() {
if let Some(reason) = policy.github_writes.refusal(kind) {
return Some(reason);
}
}
if wire.writes_the_repository() && policy.github_writes == GithubWrites::ReadOnly {
return Some(format!("{kind} writes to the repository, and this session is read-only"));
}
session_refusal(wire, policy)
}
/// Why `wire` is refused for the client's place in the session: the one that started it, or one
/// that joined.
fn session_refusal(wire: &WireAction, policy: &Policy) -> Option<String> {
let kind = wire.kind();
// A joined client's introduction is kept by the share layer, so one that gets here started
// the session
if matches!(wire, WireAction::Introduce { .. }) {
return Some(format!("{kind} is for a client that joined a running session"));
}
// The protocol answers it from the catalog before translating (`rpc::parse_action`)
if matches!(wire, WireAction::ListModels { .. }) {
return Some(format!("{kind} is answered by the protocol, not the engine"));
}
let switches = matches!(wire, WireAction::NewSession | WireAction::LoadSession(_));
if policy.joined && switches {
let reason = "would switch the session the terminal is showing: switch it there, or start \
another luxe";
return Some(format!("{kind} {reason}"));
}
None
}
/// Review progress carrying only the walked chapters, which is all the wire sends.
fn walked(
walked_chapter_ids: Vec<luxe_core::guided_review::ChapterId>,
) -> luxe_core::guided_review::ReviewProgress {
luxe_core::guided_review::ReviewProgress { walked_chapter_ids, ..Default::default() }
}
/// Translate one wire action into the engine action it stands for.
@@ -116,15 +173,8 @@ pub(crate) fn to_engine_action(
models: &dyn ModelResolver,
policy: &Policy,
) -> Result<Action, Rejected> {
if wire.writes_to_github() {
if let Some(reason) = policy.github_writes.refusal(wire.kind()) {
return Err(Rejected { kind: Some(wire.kind().to_string()), reason });
}
}
if wire.writes_the_repository() && policy.github_writes == GithubWrites::ReadOnly {
let kind = wire.kind();
let reason = format!("{kind} writes to the repository, and this session is read-only");
return Err(Rejected { kind: Some(kind.to_string()), reason });
if let Some(reason) = policy_refusal(&wire, policy) {
return Err(Rejected { kind: Some(wire.kind().to_string()), reason });
}
Ok(match wire {
WireAction::SubmitUserMessage { text, images } => {
@@ -159,15 +209,10 @@ pub(crate) fn to_engine_action(
Action::EditReview { request_id, review_id, edit }
}
WireAction::RecordReviewProgress { review_id, walked_chapter_ids } => {
Action::RecordReviewProgress {
review_id,
progress: luxe_core::guided_review::ReviewProgress {
walked_chapter_ids,
..Default::default()
},
}
Action::RecordReviewProgress { review_id, progress: walked(walked_chapter_ids) }
}
WireAction::RecordReviewSeen { review_id } => Action::RecordReviewSeen { review_id },
WireAction::ShowOpenReview { request_id } => Action::ShowOpenReview { request_id },
WireAction::RefreshGuidedReview { request_id, review_id, revision_id } => {
Action::RefreshGuidedReview { request_id, review_id, expected_revision: revision_id }
}

View File

@@ -13,6 +13,10 @@ impl ModelResolver for OneModel {
..Default::default()
}
}
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
Vec::new()
}
}
fn policy(github_writes: GithubWrites) -> Policy {
@@ -22,6 +26,7 @@ fn policy(github_writes: GithubWrites) -> Policy {
name: "Mine".into(),
query: "is:open is:pr author:@me repo:{repo}".into(),
}],
joined: false,
}
}
@@ -29,6 +34,20 @@ fn translate(wire: WireAction) -> Result<Action, Rejected> {
to_engine_action(wire, &OneModel, &policy(GithubWrites::Allowed))
}
/// A client that joined a terminal's session can't switch it, and one that started its own can.
///
/// The break this catches: dropping the joined check, which lets a phone swap out the
/// conversation the person at the terminal is reading.
#[test]
fn a_joined_client_cannot_switch_the_session() {
let joined = Policy { joined: true, ..policy(GithubWrites::Allowed) };
for wire in [WireAction::NewSession, WireAction::LoadSession("other".into())] {
let refused = to_engine_action(wire.clone(), &OneModel, &joined);
assert!(refused.is_err(), "a joined client ran {}", wire.kind());
assert!(translate(wire).is_ok());
}
}
/// A steer for the summary has to survive the crossing; without it `/compact keep the API
/// decisions` is an ordinary compaction that silently ignored what it was told.
#[test]
@@ -104,6 +123,18 @@ fn each_wire_action_arrives_as_the_engine_action_it_names() {
));
}
/// The client that started a session is refused when it introduces itself, by name.
///
/// The break this catches: the arm falling to the catch-all, which tells a client that a published
/// kind is unknown.
#[test]
fn the_starting_client_cannot_introduce_itself() {
let introduce = WireAction::Introduce { name: "iPhone".into(), watch_only: false, yours: true };
let refused = translate(introduce).unwrap_err();
assert_eq!(refused.kind.as_deref(), Some("introduce"));
assert!(refused.reason.contains("joined a running session"), "{}", refused.reason);
}
/// Every GitHub action reaches the engine as the action it names, carrying its payload.
///
/// Same break as above, sharpest here: overview and conversation share a payload, as do
@@ -248,6 +279,10 @@ fn each_review_action_arrives_as_the_engine_action_it_names() {
translate(WireAction::RecordReviewSeen { review_id: id("review:1") }),
Ok(Action::RecordReviewSeen { .. })
));
assert!(matches!(
translate(WireAction::ShowOpenReview { request_id: load.clone() }),
Ok(Action::ShowOpenReview { request_id }) if request_id == load
));
assert!(matches!(
translate(WireAction::RefreshGuidedReview {
request_id: load.clone(),
@@ -412,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() {
@@ -523,7 +558,10 @@ fn an_unknown_frame_is_refused_by_name() {
/// comes from the built-in defaults rather than from whatever the developer has configured.
#[test]
fn the_real_resolver_answers_about_the_model_it_was_asked() {
let info = CatalogResolver.resolve("no-such-provider", "no-such-model-9e3f");
let dir = tempfile::tempdir().unwrap();
let overrides = crate::engine_setup::CliOverrides::default();
let settings = crate::engine_setup::AgentSettings::resolve(dir.path().into(), overrides);
let info = CatalogResolver { settings }.resolve("no-such-provider", "no-such-model-9e3f");
assert_eq!(info.r#ref.provider, "no-such-provider");
assert_eq!(info.r#ref.id, "no-such-model-9e3f");
assert!(info.context_window > 0, "a zero window makes every context percentage a lie");
@@ -539,7 +577,7 @@ fn the_real_resolver_answers_about_the_model_it_was_asked() {
fn the_translator_covers_the_whole_published_vocabulary() {
assert_eq!(
WireAction::KINDS.len(),
51,
54,
"a wire action was published without a translator arm: {:?}",
WireAction::KINDS
);

View File

@@ -0,0 +1,236 @@
//! Session sharing — the terminal's session, offered to other front-ends on this machine.
//!
//! "The terminal" is whichever front-end started the session: the TUI, or the client on the other
//! end of `luxe --rpc`. The terminal stays in charge. A client that connects to the local endpoint
//! (a Unix socket or a named pipe only this user can open) speaks the protocol `luxe --rpc` does:
//! it gets a `ready` frame, then what it missed, then every event as it happens, and its actions
//! reach the same engine the terminal drives. A joined client can't switch or close the session,
//! and leaving closes nothing. The terminal is told when one joins, leaves, or answers a prompt.
mod clients;
mod guest;
mod guests;
mod snapshot;
use super::rpc::{GithubWrites, Policy};
use luxe_core::engine::Action;
use luxe_core::local_endpoint::{EndpointListener, LiveSession, Publication};
use luxe_core::Event;
use snapshot::Snapshot;
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard};
use tokio::sync::{broadcast, mpsc};
use tokio::task::JoinHandle;
/// Events the terminal hasn't drawn yet, as deep as the stream it reads without sharing.
const TERMINAL_BUFFER: usize = 256;
/// How far a joined client may fall behind before it's dropped and has to join again.
///
/// Deep because token deltas are one event each, and a phone on a slow link reads in bursts.
const CLIENT_BACKLOG: usize = 4096;
/// The session on offer. Dropping it takes the offer down and disconnects every client.
pub(crate) struct Sharing {
tasks: Vec<JoinHandle<()>>,
}
impl Drop for Sharing {
fn drop(&mut self) {
for task in &self.tasks {
task.abort();
}
}
}
/// What every joined client shares: the session's state, its live events, and the terminal.
#[derive(Clone)]
struct Shared {
snapshot: Arc<Mutex<Snapshot>>,
live: broadcast::Sender<Event>,
engine_tx: mpsc::Sender<Action>,
/// Weak, so the terminal's stream ends with the engine's while clients are still connected:
/// `--rpc` exits on that end
terminal: mpsc::WeakSender<Event>,
cwd: String,
policy: Policy,
/// What `select_model` resolves through and `list_models` lists
models: super::rpc::Models,
/// The process whose descendants are refused: this one, outside tests
agent_pid: u32,
/// Who's joined now, for the terminal's dock
guests: guests::GuestList,
}
impl Shared {
/// The snapshot, even if a panic elsewhere poisoned the lock: it holds no invariant a
/// half-finished update could break that a client couldn't recover from by joining again.
fn snapshot(&self) -> MutexGuard<'_, Snapshot> {
self.snapshot.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Fold `event` into the snapshot and hand it to every client, as one step so a client
/// joining in between sees it exactly once.
fn publish(&self, event: &Event) {
let mut snapshot = self.snapshot();
snapshot.observe(event);
// No receivers is the normal state with nobody joined
let _ = self.live.send(event.clone());
}
/// Put a line in front of the person at the terminal.
async fn tell_terminal(&self, notice: String) {
self.to_terminal(Event::Notice(notice)).await;
}
/// Tell the terminal who's joined now, for its dock.
async fn tell_guests(&self) {
self.to_terminal(Event::GuestsChanged(self.guests.names())).await;
}
async fn to_terminal(&self, event: Event) {
// The terminal gone means the session is ending, and nobody is left to tell
let Some(terminal) = self.terminal.upgrade() else { return };
let _ = terminal.send(event).await;
}
}
/// Offer the session `events` belongs to, and return the stream the terminal reads instead.
///
/// With `joinable` off nothing listens. When the endpoint can't be opened the terminal runs
/// exactly as it would unshared, and the reason goes to the log: sharing is a convenience,
/// never a reason to refuse to start.
pub(crate) fn share(
events: mpsc::Receiver<Event>,
engine_tx: mpsc::Sender<Action>,
settings: &crate::engine_setup::AgentSettings,
session_id: &str,
) -> (mpsc::Receiver<Event>, Option<Sharing>) {
let config = luxe_core::config::Config::load(&settings.state_root);
if !config.joinable() {
tracing::info!("not sharing the session: joinable is off");
return (events, None);
}
let Some((listener, record)) = open_endpoint(settings, session_id) else {
return (events, None);
};
let (terminal, terminal_rx) = mpsc::channel(TERMINAL_BUFFER);
let shared = Shared {
snapshot: Arc::new(Mutex::new(Snapshot::new(session_id.to_string()))),
live: broadcast::channel(CLIENT_BACKLOG).0,
engine_tx,
terminal: terminal.downgrade(),
cwd: settings.work_root.to_string_lossy().into_owned(),
policy: guest_policy(settings, &config),
models: Arc::new(super::rpc::CatalogResolver { settings: settings.clone() }),
agent_pid: std::process::id(),
guests: guests::GuestList::default(),
};
let tasks = vec![
tokio::spawn(clients::accept(listener, shared.clone())),
tokio::spawn(tee(events, shared, terminal, record)),
];
tracing::info!(%session_id, "sharing the session on the local endpoint");
(terminal_rx, Some(Sharing { tasks }))
}
/// Listen on the local endpoint and publish the record that lists it.
fn open_endpoint(
settings: &crate::engine_setup::AgentSettings,
session_id: &str,
) -> Option<(EndpointListener, Option<Record>)> {
let dir = luxe_core::user_dirs::luxe_runtime_dir();
let listener = match EndpointListener::bind(&dir) {
Ok(listener) => listener,
Err(error) => {
tracing::warn!(%error, dir = %dir.display(), "not sharing the session");
return None;
}
};
let record = publish_record(&dir, &listener, settings, session_id);
Some((listener, record))
}
/// What a joined client may do: what the terminal may, with GitHub writes left off, since
/// `--github-writes` is a choice made for one `--rpc` client and nobody made it for this one.
fn guest_policy(
settings: &crate::engine_setup::AgentSettings,
config: &luxe_core::config::Config,
) -> Policy {
let mode = crate::engine_setup::effective_permission_mode(
&settings.state_root,
settings.permission_mode,
settings.trust_project,
);
Policy {
github_writes: GithubWrites::for_launch(false, mode),
github_sections: config.github.sections(),
joined: true,
}
}
/// Copy every engine event to the clients and on to the terminal, until either end is gone.
///
/// Owns the terminal's only strong sender, so the terminal's stream ends when this does.
async fn tee(
mut events: mpsc::Receiver<Event>,
shared: Shared,
terminal: mpsc::Sender<Event>,
mut record: Option<Record>,
) {
while let Some(event) = events.recv().await {
shared.publish(&event);
if let (Event::SessionLoaded { session_id, .. }, Some(record)) = (&event, record.as_mut()) {
record.follow(session_id);
}
if terminal.send(event).await.is_err() {
break;
}
}
}
/// The published record of this session, which `luxe join` and `luxe remote` list.
struct Record {
session: LiveSession,
publication: Publication,
}
impl Record {
/// Keep the record naming the session the terminal shows.
fn follow(&mut self, session_id: &str) {
if self.session.session_id == session_id {
return;
}
self.session.session_id = session_id.to_string();
if let Err(error) = self.publication.update(&self.session) {
tracing::warn!(%error, "could not update the shared session's record");
}
}
}
/// Write the record that lists this session, or log why it couldn't be written: the endpoint
/// still works for a client that knows its address.
fn publish_record(
dir: &Path,
listener: &EndpointListener,
settings: &crate::engine_setup::AgentSettings,
session_id: &str,
) -> Option<Record> {
let session = LiveSession {
pid: std::process::id(),
session_id: session_id.to_string(),
cwd: settings.work_root.to_string_lossy().into_owned(),
address: listener.address().to_string(),
luxe_version: env!("CARGO_PKG_VERSION").to_string(),
};
match session.publish(dir) {
Ok(publication) => Some(Record { session, publication }),
Err(error) => {
tracing::warn!(%error, "could not publish the shared session's record");
None
}
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,185 @@
//! One joined client at a time: checked, caught up, then served like any RPC client.
use super::super::rpc;
use super::guest::{self, Guest};
use super::Shared;
use luxe_core::engine::Action;
use luxe_core::local_endpoint::{EndpointListener, Joined, LocalStream};
use luxe_core::Event;
use tokio::sync::broadcast::{self, error::RecvError};
use tokio::sync::mpsc;
use tokio::task::JoinSet;
/// Actions a client may queue before its reads wait on the engine.
const ACTION_BUFFER: usize = 32;
/// Frames queued for one client's socket; past this, the shared backlog takes the slack.
const CLIENT_WRITE_BUFFER: usize = 256;
/// Bytes of a client's input held between reading it and the protocol taking it.
const SIFTED_BUFFER: usize = 64 * 1024;
/// How long to wait before accepting again after an accept failed, so a lasting failure (out of
/// file handles) logs a few lines a second instead of spinning a core.
const ACCEPT_RETRY: std::time::Duration = std::time::Duration::from_millis(250);
/// Take clients until the task is aborted, which disconnects every one of them.
pub(super) async fn accept(mut listener: EndpointListener, shared: Shared) {
let mut clients = JoinSet::new();
loop {
match listener.accept().await {
Ok(joined) => {
clients.spawn(serve_client(joined, shared.clone()));
}
Err(error) => {
tracing::warn!(%error, "could not accept a client of the shared session");
tokio::time::sleep(ACCEPT_RETRY).await;
}
}
// Reap finished clients so a long session doesn't keep one entry per visit
while clients.try_join_next().is_some() {}
}
}
/// Serve one client from its `ready` frame until it leaves or the session ends.
async fn serve_client(joined: Joined, shared: Shared) {
let (guest, named) = Guest::new(joined.peer);
if guest.descends_from(shared.agent_pid).await {
tracing::warn!(peer = ?joined.peer, "refused a client started by this session's agent");
let notice = format!("Refused {guest}: the agent started it, and can't approve itself");
shared.tell_terminal(notice).await;
return;
}
let served = serve_rpc(joined.stream, &shared, guest.clone(), named);
let (arrival, ()) = tokio::join!(announce(&shared, guest.clone()), served);
tracing::info!(peer = ?joined.peer, %guest, "a client left the shared session");
let Some(arrival) = arrival else { return };
shared.guests.leave(arrival.seat);
shared.tell_guests().await;
if arrival.told {
shared.tell_terminal(format!("{guest} left this session")).await;
}
}
/// How a client was announced: its seat in the dock's list, and whether the transcript was told.
struct Arrival {
seat: u64,
told: bool,
}
/// Seats the client in the dock's list once it has had a moment to say who it is, unless it opened
/// as watch-only. Only someone else's client earns a line in the transcript: the person at the
/// terminal knows their own phone joined, and a phone reconnects often.
async fn announce(shared: &Shared, mut guest: Guest) -> Option<Arrival> {
guest.introduced().await;
if guest.watch_only() {
tracing::info!(%guest, "a watch-only client joined the shared session");
return None;
}
let seat = shared.guests.arrive(guest.to_string());
shared.tell_guests().await;
let told = !guest.yours();
if told {
shared.tell_terminal(format!("{guest} joined this session")).await;
}
Some(Arrival { seat, told })
}
/// The RPC protocol over `stream`, fed from the shared session rather than an engine of its own.
async fn serve_rpc(
stream: LocalStream,
shared: &Shared,
guest: Guest,
named: tokio::sync::watch::Sender<Option<guest::Introduction>>,
) {
let (opening, frames, live) = catch_up(shared);
let (events_tx, events_rx) = mpsc::channel(CLIENT_WRITE_BUFFER);
let _feed = AbortOnDrop(tokio::spawn(feed(frames, live, events_tx)));
let (actions_tx, actions_rx) = mpsc::channel(ACTION_BUFFER);
let _relay = AbortOnDrop(tokio::spawn(relay(actions_rx, shared.clone(), guest)));
let (read, write) = tokio::io::split(stream);
let (sifted, input) = tokio::io::duplex(SIFTED_BUFFER);
let _sift = AbortOnDrop(tokio::spawn(guest::sift(read, sifted, named)));
let (policy, models) = (shared.policy.clone(), shared.models.clone());
let served = rpc::serve(opening, events_rx, actions_tx, input, write, models, policy);
if let Err(error) = served.await {
tracing::warn!(%error, "a shared session's client ended with an error");
}
}
/// The `ready` frame and transcript, what else the client missed, and the live stream picking up
/// right after it.
///
/// Taken under the lock `publish` holds, so no event falls between the catch-up and the stream.
fn catch_up(shared: &Shared) -> (rpc::Opening, Vec<Event>, broadcast::Receiver<Event>) {
let snapshot = shared.snapshot();
let ready = Event::Ready {
protocol_version: luxe_core::PROTOCOL_VERSION,
luxe_version: env!("CARGO_PKG_VERSION").to_string(),
session_id: snapshot.session_id().to_string(),
cwd: shared.cwd.clone(),
github_writes: shared.policy.github_writes.allowed(),
};
let opening = rpc::Opening { ready, transcript: Some(snapshot.transcript()) };
(opening, snapshot.frames(), shared.live.subscribe())
}
/// Hand the client its catch-up and then the live stream, until it falls too far behind.
async fn feed(frames: Vec<Event>, mut live: broadcast::Receiver<Event>, out: mpsc::Sender<Event>) {
for frame in frames {
if out.send(frame).await.is_err() {
return;
}
}
loop {
let event = match live.recv().await {
Ok(event) => event,
Err(RecvError::Lagged(missed)) => {
let notice = format!("This client fell {missed} events behind: join again");
let _ = out.send(Event::Notice(notice)).await;
return;
}
Err(RecvError::Closed) => return,
};
if out.send(event).await.is_err() {
return;
}
}
}
/// Pass the client's actions to the engine, telling the terminal about each answer it gives.
async fn relay(mut actions: mpsc::Receiver<Action>, shared: Shared, guest: Guest) {
while let Some(action) = actions.recv().await {
let answer = answer_notice(&shared, &action, &guest);
if shared.engine_tx.send(action).await.is_err() {
return;
}
if let Some(notice) = answer {
shared.tell_terminal(notice).await;
}
}
}
/// What to tell the terminal about `action`, when it answers a prompt that's still waiting.
///
/// A prompt the terminal already answered is a no-op for the engine, so it says nothing here.
fn answer_notice(shared: &Shared, action: &Action, guest: &Guest) -> Option<String> {
use luxe_core::permission::PermissionReply;
let (id, verb) = match action {
Action::RespondPermission { id, reply: PermissionReply::Reject } => (id.as_str(), "Denied"),
Action::RespondPermission { id, .. } => (id.as_str(), "Approved"),
Action::AnswerQuestion { id, .. } => (id.as_str(), "Answered"),
_ => return None,
};
let waiting = shared.snapshot().is_waiting(id);
waiting.then(|| format!("{verb} from {guest}"))
}
/// Aborts its task when dropped, so a client's helpers end with it.
struct AbortOnDrop(tokio::task::JoinHandle<()>);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}

View File

@@ -0,0 +1,144 @@
//! Guest — who a joined client is, as the terminal names it: the name it introduced itself by, or
//! its process id.
//!
//! The bridge introduces each device it relays for, so the terminal says "Approved from iPhone"
//! rather than naming the bridge's process. The name is cosmetic, since any program running as
//! you could claim one, and the ancestry check goes by process id, not by name.
//!
//! A client that opens by introducing itself as watch-only, like the bridge's notification
//! watcher, isn't announced. Being unseen is why it can't act: everything it sends after that is
//! dropped here, before the protocol sees it.
use luxe_core::local_endpoint::descends_from;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::sync::watch;
/// How long a new client gets to introduce itself before the terminal says it joined.
pub(super) const INTRODUCTION_WAIT: std::time::Duration = std::time::Duration::from_secs(1);
/// The longest name the terminal shows.
const NAME_LIMIT: usize = 40;
/// What a client said about itself.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Introduction {
pub(super) name: String,
pub(super) watch_only: bool,
/// Paired by the person at the terminal, so its comings and goings needn't be told
pub(super) yours: bool,
}
/// Who joined.
#[derive(Clone)]
pub(super) struct Guest {
pid: Option<u32>,
said: watch::Receiver<Option<Introduction>>,
}
impl Guest {
/// A guest known by `pid` until it introduces itself through the returned sender.
pub(super) fn new(pid: Option<u32>) -> (Self, watch::Sender<Option<Introduction>>) {
let (named, said) = watch::channel(None);
(Self { pid, said }, named)
}
/// Whether the client opened as watch-only, so it isn't announced.
pub(super) fn watch_only(&self) -> bool {
self.said.borrow().as_ref().is_some_and(|said| said.watch_only)
}
/// Whether the bridge said the person at the terminal paired it. Cosmetic, as the name is: it
/// decides only whether joining earns a line in the transcript.
pub(super) fn yours(&self) -> bool {
self.said.borrow().as_ref().is_some_and(|said| said.yours)
}
/// Whether the client is `agent` or a process it started, directly or not.
///
/// A tripwire, not a wall: a command can detach from its parent first. Unknown ancestry
/// passes, since refusing it would refuse every client on a system that hides it.
pub(super) async fn descends_from(&self, agent: u32) -> bool {
let Some(peer) = self.pid else { return false };
let ancestry = tokio::task::spawn_blocking(move || descends_from(peer, agent));
ancestry.await.unwrap_or(false)
}
/// Waits up to [`INTRODUCTION_WAIT`] for a name, so "joined" names the device.
pub(super) async fn introduced(&mut self) {
let named = self.said.wait_for(Option::is_some);
let _ = tokio::time::timeout(INTRODUCTION_WAIT, named).await;
}
}
impl std::fmt::Display for Guest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(said) = self.said.borrow().as_ref() {
return f.write_str(&said.name);
}
match self.pid {
Some(pid) => write!(f, "a client (pid {pid})"),
None => f.write_str("a client"),
}
}
}
/// Copies the client's lines to `protocol`, keeping its introductions for `named`.
///
/// Read here rather than in the protocol because the name is the share layer's business: the
/// engine has no use for it, and the client that started a session has nobody to introduce
/// itself to. Once a client opens as watch-only, nothing more of it is read for the protocol.
pub(super) async fn sift(
client: impl AsyncRead + Unpin,
mut protocol: impl AsyncWrite + Unpin,
named: watch::Sender<Option<Introduction>>,
) {
let mut lines = BufReader::new(client).lines();
let mut opening = true;
while let Ok(Some(line)) = lines.next_line().await {
if !for_protocol(&line, &mut opening, &named) {
continue;
}
if protocol.write_all(format!("{line}\n").as_bytes()).await.is_err() {
return;
}
}
}
/// Whether `line` goes on to the protocol: not when it's an introduction, which `named` keeps,
/// nor when the client opened as watch-only.
fn for_protocol(
line: &str,
opening: &mut bool,
named: &watch::Sender<Option<Introduction>>,
) -> bool {
if named.borrow().as_ref().is_some_and(|said| said.watch_only) {
tracing::warn!("dropped a line from a watch-only client");
return false;
}
let first = std::mem::take(opening);
let Some(mut said) = introduction(line) else { return true };
said.watch_only &= first;
named.send_replace(Some(said));
false
}
/// What an `introduce` frame says, its name made fit for one line of the terminal.
///
/// Anything else, a malformed introduction included, is `None` and goes on to the protocol, which
/// refuses it by name.
fn introduction(line: &str) -> Option<Introduction> {
if !line.contains("introduce") {
return None;
}
let luxe_core::event::Action::Introduce { name, watch_only, yours } =
serde_json::from_str(line).ok()?
else {
return None;
};
let name: String = name.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
let name: String = name.trim().chars().take(NAME_LIMIT).collect();
(!name.is_empty()).then_some(Introduction { name, watch_only, yours })
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,71 @@
use super::*;
fn name_of(line: &str) -> Option<String> {
introduction(line).map(|said| said.name)
}
/// An introduction gives its name, made fit for one line; nothing else does.
///
/// The break this catches, one per line: taking the name from another frame (submit), passing a
/// newline or escape code into the terminal's notice (control), letting a long name push the
/// notice off the line (long), or naming a client nothing (blank).
#[test]
fn only_an_introduction_names_a_client() {
let introduce = |name: &str| format!(r#"{{"kind":"introduce","content":{{"name":"{name}"}}}}"#);
assert_eq!(name_of(&introduce("iPhone")).as_deref(), Some("iPhone"));
let submit = r#"{"kind":"submit_user_message","content":{"text":"introduce yourself"}}"#;
assert_eq!(name_of(submit), None);
assert_eq!(name_of(&introduce(r"Alex\n\u001b[2Jphone")).as_deref(), Some("Alex [2Jphone"));
assert_eq!(name_of(&introduce(&"x".repeat(60))).map(|name| name.len()), Some(NAME_LIMIT));
assert_eq!(name_of(&introduce(" ")), None);
}
/// What `input` passes on to the protocol, and the guest it leaves.
async fn sifted(input: &str) -> (String, Guest) {
let (sifted, mut protocol) = tokio::io::duplex(1024);
let (guest, named) = Guest::new(Some(7));
sift(input.as_bytes(), sifted, named).await;
let mut passed = String::new();
tokio::io::AsyncReadExt::read_to_string(&mut protocol, &mut passed).await.unwrap();
(passed, guest)
}
const WATCHER: &str =
"{\"kind\":\"introduce\",\"content\":{\"name\":\"Notifications\",\"watch_only\":true}}\n";
/// The client's other lines reach the protocol in order, and its introduction doesn't.
///
/// The break this catches: forwarding the introduction, which the protocol refuses back to the
/// bridge as if it had sent something wrong; or losing the line after it.
#[tokio::test]
async fn sifting_keeps_the_introduction_and_passes_the_rest() {
let input = "{\"kind\":\"cancel\"}\n{\"kind\":\"introduce\",\"content\":{\"name\":\"iPad\"}}\n\
{\"kind\":\"retry\"}\n";
let (passed, guest) = sifted(input).await;
assert_eq!(passed, "{\"kind\":\"cancel\"}\n{\"kind\":\"retry\"}\n");
assert_eq!(guest.to_string(), "iPad");
assert!(!guest.watch_only());
}
/// A client that opens as watch-only is marked so, and nothing it sends after reaches the
/// protocol.
///
/// The break this catches: an unannounced client steering or approving, unseen at the desk.
#[tokio::test]
async fn a_watch_only_client_cant_act() {
let (passed, guest) = sifted(&format!("{WATCHER}{{\"kind\":\"cancel\"}}\n")).await;
assert_eq!(passed, "");
assert!(guest.watch_only());
assert_eq!(guest.to_string(), "Notifications");
}
/// Watch-only counts only as the opening line.
///
/// The break this catches: a client cancelling the turn, then introducing itself as watch-only so
/// the terminal never says it was there.
#[tokio::test]
async fn watch_only_after_acting_is_just_a_name() {
let (passed, guest) = sifted(&format!("{{\"kind\":\"cancel\"}}\n{WATCHER}")).await;
assert_eq!(passed, "{\"kind\":\"cancel\"}\n");
assert!(!guest.watch_only());
}

View File

@@ -0,0 +1,59 @@
//! Guests — who's joined the shared session right now, by name, for the terminal's dock.
//!
//! Each announced client takes a seat when it joins and gives it up when it leaves, so two of the
//! same name (a phone that reconnected before its old socket closed) are counted apart.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
/// The clients in the session now, in the order they joined.
#[derive(Clone, Default)]
pub(super) struct GuestList {
seated: Arc<Mutex<Vec<(u64, String)>>>,
next: Arc<AtomicU64>,
}
impl GuestList {
/// Seats `name`, returning the seat to give up on leaving.
pub(super) fn arrive(&self, name: String) -> u64 {
let seat = self.next.fetch_add(1, Ordering::Relaxed);
self.seated().push((seat, name));
seat
}
/// Gives up `seat`.
pub(super) fn leave(&self, seat: u64) {
self.seated().retain(|(taken, _)| *taken != seat);
}
/// Everyone seated, by name.
pub(super) fn names(&self) -> Vec<String> {
self.seated().iter().map(|(_, name)| name.clone()).collect()
}
/// The list, even if a panic elsewhere poisoned the lock: a stale name is all it could hold.
fn seated(&self) -> MutexGuard<'_, Vec<(u64, String)>> {
self.seated.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A guest leaves by its seat, so one of two with the same name leaving leaves the other.
///
/// The break this catches: a phone that reconnected before its old socket closed vanishing
/// from the dock when the old one goes, while it's still joined.
#[test]
fn a_guest_leaves_by_its_seat_not_its_name() {
let guests = GuestList::default();
let old = guests.arrive("iPhone".into());
let _new = guests.arrive("iPhone".into());
let ipad = guests.arrive("iPad".into());
guests.leave(old);
assert_eq!(guests.names(), ["iPhone", "iPad"]);
guests.leave(ipad);
assert_eq!(guests.names(), ["iPhone"]);
}
}

View File

@@ -0,0 +1,140 @@
//! What a client joining mid-session has missed, kept current from the event stream.
//!
//! A joiner opens on the same frames a resume would show: the transcript so far, whether a turn is
//! running, then the latest state, usage and workspace, the tool cards of a turn still running, and
//! any prompt still waiting for an answer. Text a reply has already streamed is not replayed; it
//! arrives whole once the message commits.
use super::super::rpc::SharedTranscript;
use luxe_core::event::SessionMessage;
use luxe_core::Event;
use std::mem::discriminant;
use std::sync::Arc;
/// The session as a client joining now should first see it.
pub(super) struct Snapshot {
session_id: String,
/// Shared with the joiners being sent it, so a join costs a reference, not a copy
transcript: Arc<Vec<SessionMessage>>,
/// Whether a turn has started and not yet ended
turning: bool,
/// The newest event of each kind where only the newest matters
latest: Vec<Event>,
/// Tool cards of the turn in flight, by call id
activity: Vec<Event>,
/// Permission prompts and questions nobody has answered yet
waiting: Vec<Event>,
}
impl Snapshot {
/// An empty snapshot of `session_id`, before the engine has said anything.
pub(super) fn new(session_id: String) -> Self {
Self {
session_id,
transcript: Arc::default(),
turning: false,
latest: Vec::new(),
activity: Vec::new(),
waiting: Vec::new(),
}
}
/// The session the stream is about now.
pub(super) fn session_id(&self) -> &str {
&self.session_id
}
/// Whether the prompt `id` names is still waiting for an answer.
pub(super) fn is_waiting(&self, id: &str) -> bool {
self.waiting.iter().any(|prompt| prompt_id(prompt) == id)
}
/// Fold one event in.
pub(super) fn observe(&mut self, event: &Event) {
match event {
Event::SessionLoaded { session_id, messages } => self.load(session_id, messages),
Event::MessageCommitted { entry_id, message, .. } => {
let message =
SessionMessage { entry_id: entry_id.clone(), message: message.clone() };
// Copies the list only if a joiner is still being sent it, which is brief
Arc::make_mut(&mut self.transcript).push(message);
}
Event::StateChanged(_)
| Event::SessionUsage(_)
| Event::ContextUsage { .. }
| Event::PlanUsage(_)
| Event::WorkspaceUpdated(_) => replace_kind(&mut self.latest, event),
Event::ToolActivityUpdated(activity) => self.track_activity(&activity.call_id, event),
Event::PermissionRequested { .. } | Event::QuestionAsked { .. } => {
self.waiting.push(event.clone());
}
Event::PromptClosed { id } => self.waiting.retain(|prompt| prompt_id(prompt) != id),
Event::TurnStarted => self.turning = true,
Event::TurnEnded { .. } => self.end_turn(),
_ => {}
}
}
/// The transcript so far, which a new client is sent first, as its `session_loaded` frame.
pub(super) fn transcript(&self) -> SharedTranscript {
SharedTranscript {
session_id: self.session_id.clone(),
messages: Arc::clone(&self.transcript),
}
}
/// The frames that bring a new client up to now after the transcript, oldest first.
pub(super) fn frames(&self) -> Vec<Event> {
self.turning
.then_some(Event::TurnStarted)
.into_iter()
.chain(self.latest.iter().cloned())
.chain(self.activity.iter().cloned())
.chain(self.waiting.iter().cloned())
.collect()
}
/// Start over on a loaded session, which replaces everything a front-end shows.
fn load(&mut self, session_id: &str, messages: &[SessionMessage]) {
self.session_id = session_id.to_string();
self.transcript = Arc::new(messages.to_vec());
self.end_turn();
}
/// Nothing of a finished turn is still running or waiting.
fn end_turn(&mut self) {
self.turning = false;
self.activity.clear();
self.waiting.clear();
}
/// Keep only the newest card for `call_id`.
fn track_activity(&mut self, call_id: &str, event: &Event) {
self.activity.retain(|kept| activity_call(kept) != Some(call_id));
self.activity.push(event.clone());
}
}
/// Replace the kept event of `event`'s kind, or keep it as the first of its kind.
fn replace_kind(kept: &mut Vec<Event>, event: &Event) {
let kind = discriminant(event);
kept.retain(|old| discriminant(old) != kind);
kept.push(event.clone());
}
/// The id a waiting prompt answers to, in the form `PromptClosed` carries.
fn prompt_id(prompt: &Event) -> &str {
match prompt {
Event::PermissionRequested { id, .. } => id.as_str(),
Event::QuestionAsked { id, .. } => id.as_str(),
_ => "",
}
}
/// The tool call a kept card belongs to.
fn activity_call(event: &Event) -> Option<&str> {
match event {
Event::ToolActivityUpdated(activity) => Some(&activity.call_id),
_ => None,
}
}

View File

@@ -0,0 +1,385 @@
use super::*;
use luxe_core::local_endpoint::{connect, LocalStream};
use luxe_core::permission::PermissionRequestId;
use luxe_core::Message;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
/// A shared session with no engine or terminal behind it, and the far ends of both.
struct Harness {
shared: Shared,
engine_rx: mpsc::Receiver<Action>,
terminal_rx: mpsc::Receiver<Event>,
/// The strong end `tee` owns in a real session, which keeps the terminal's stream open
terminal: mpsc::Sender<Event>,
}
/// No process descends from this one, so the tripwire lets the test's own connections in.
const NOBODY: u32 = u32::MAX;
/// A catalog with nothing in it, so no test reads the developer's `models.json`.
struct NoModels;
impl super::super::rpc::ModelResolver for NoModels {
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo {
let r#ref = luxe_core::provider::ModelRef::new(provider, id);
luxe_core::ModelInfo { r#ref, ..Default::default() }
}
fn choices(&self) -> Vec<luxe_core::event::ModelChoice> {
Vec::new()
}
}
fn harness(agent_pid: u32) -> Harness {
let (engine_tx, engine_rx) = mpsc::channel(16);
let (terminal, terminal_rx) = mpsc::channel(16);
let shared = Shared {
snapshot: Arc::new(Mutex::new(Snapshot::new("session-1".into()))),
live: broadcast::channel(CLIENT_BACKLOG).0,
engine_tx,
terminal: terminal.downgrade(),
cwd: "/work".into(),
policy: Policy {
github_writes: GithubWrites::NotEnabled,
github_sections: Vec::new(),
joined: true,
},
models: Arc::new(NoModels),
agent_pid,
guests: super::guests::GuestList::default(),
};
Harness { shared, engine_rx, terminal_rx, terminal }
}
fn permission_asked(id: &PermissionRequestId) -> Event {
Event::PermissionRequested {
id: id.clone(),
session_id: "session-1".into(),
tool: "bash".into(),
permission: "bash".into(),
summary: "Run: cargo test".into(),
always_patterns: Vec::new(),
}
}
fn committed(text: &str) -> Event {
Event::MessageCommitted {
session_id: "session-1".into(),
entry_id: luxe_core::session::EntryId(text.into()),
message: Message::user(text),
}
}
fn kinds(frames: &[Event]) -> Vec<&'static str> {
frames
.iter()
.map(|frame| match frame {
Event::SessionLoaded { .. } => "session_loaded",
Event::StateChanged(_) => "state_changed",
Event::ContextUsage { .. } => "context_usage",
Event::PermissionRequested { .. } => "permission_requested",
Event::TurnStarted => "turn_started",
_ => "other",
})
.collect()
}
/// A joiner opens on the transcript, then the newest of each kept state, then the prompt.
///
/// The break this catches: dropping the commit fold, which opens a joined phone on an empty
/// conversation, or keeping every usage update, which replays a turn's worth of stale readings.
#[test]
fn a_joiner_catches_up_on_the_transcript_state_and_waiting_prompt() {
let mut snapshot = Snapshot::new("session-1".into());
let id = PermissionRequestId::new();
for event in [
committed("first"),
Event::ContextUsage { used_tokens: 1, context_window: 10 },
committed("second"),
Event::ContextUsage { used_tokens: 2, context_window: 10 },
permission_asked(&id),
] {
snapshot.observe(&event);
}
let frames = snapshot.frames();
assert_eq!(kinds(&frames), ["context_usage", "permission_requested"]);
assert_eq!(snapshot.transcript().messages.len(), 2);
assert!(matches!(frames[0], Event::ContextUsage { used_tokens: 2, .. }));
}
/// A joiner mid-turn is told a turn is running, right after the transcript; one after it isn't.
///
/// The break this catches: leaving `turn_started` out of the catch-up, so a phone opening on a
/// running session shows it idle, with no stop button, until the next token arrives.
#[test]
fn a_joiner_mid_turn_hears_the_turn_started() {
let mut snapshot = Snapshot::new("session-1".into());
snapshot.observe(&Event::TurnStarted);
snapshot.observe(&committed("first"));
assert_eq!(kinds(&snapshot.frames()), ["turn_started"]);
snapshot.observe(&Event::TurnEnded { reason: luxe_core::event::StopReason::EndTurn });
assert!(snapshot.frames().is_empty());
}
/// A prompt someone answered isn't put in front of the next joiner.
///
/// The break this catches: ignoring `prompt_closed`, so a phone joining after the terminal
/// approved shows a prompt whose answer the engine would throw away.
#[test]
fn an_answered_prompt_is_not_replayed() {
let mut snapshot = Snapshot::new("session-1".into());
let answered = PermissionRequestId::new();
let open = PermissionRequestId::new();
snapshot.observe(&permission_asked(&answered));
snapshot.observe(&permission_asked(&open));
snapshot.observe(&Event::PromptClosed { id: answered.as_str().into() });
assert!(!snapshot.is_waiting(answered.as_str()));
assert!(snapshot.is_waiting(open.as_str()));
}
/// Loading a session replaces the transcript rather than adding to it.
///
/// The break this catches: appending on `session_loaded`, which shows a joiner the previous
/// session's conversation above the one the terminal switched to.
#[test]
fn a_loaded_session_replaces_what_came_before() {
let mut snapshot = Snapshot::new("session-1".into());
snapshot.observe(&committed("old"));
snapshot.observe(&Event::SessionLoaded { session_id: "session-2".into(), messages: vec![] });
let transcript = snapshot.transcript();
assert_eq!(transcript.session_id, "session-2");
assert!(transcript.messages.is_empty());
}
/// A commit while a joiner is still being sent the transcript leaves the joiner's copy alone.
///
/// The break this catches: the snapshot appending to a list a joiner shares, which would put a
/// message in a `session_loaded` frame the live stream then sends again.
#[test]
fn a_commit_mid_join_leaves_the_joiners_transcript_alone() {
let mut snapshot = Snapshot::new("session-1".into());
snapshot.observe(&committed("first"));
let sending = snapshot.transcript();
snapshot.observe(&committed("second"));
assert_eq!(sending.messages.len(), 1);
assert_eq!(snapshot.transcript().messages.len(), 2);
}
/// Read one frame off a client's stream.
async fn next_frame(lines: &mut tokio::io::Lines<impl tokio::io::AsyncBufRead + Unpin>) -> String {
let line = tokio::time::timeout(std::time::Duration::from_secs(5), lines.next_line());
line.await.expect("a frame in time").expect("readable").expect("the stream is open")
}
/// Wait for the terminal to be told something containing `needle`.
async fn notice_containing(terminal_rx: &mut mpsc::Receiver<Event>, needle: &str) -> String {
let wait = tokio::time::timeout(std::time::Duration::from_secs(5), async {
while let Some(event) = terminal_rx.recv().await {
if let Event::Notice(text) = event {
if text.contains(needle) {
return text;
}
}
}
panic!("the terminal stream ended before a notice about {needle:?}");
});
wait.await.expect("a notice in time")
}
type ClientLines = tokio::io::Lines<BufReader<tokio::io::ReadHalf<LocalStream>>>;
/// Serve `shared` on a fresh endpoint and connect one client to it.
async fn join(
shared: &Shared,
) -> (tempfile::TempDir, JoinHandle<()>, ClientLines, tokio::io::WriteHalf<LocalStream>) {
let dir = tempfile::tempdir().expect("tempdir");
let listener = EndpointListener::bind(dir.path()).expect("bind");
let address = listener.address().to_string();
let accept = tokio::spawn(clients::accept(listener, shared.clone()));
let stream = connect(&address).await.expect("connect");
let (read, write) = tokio::io::split(stream);
(dir, accept, BufReader::new(read).lines(), write)
}
/// A command the agent ran is turned away before it sees a frame, and the terminal hears why.
///
/// The break this catches: skipping the ancestry check, so the agent's own `bash` could join
/// its session and approve the prompt it's waiting on.
#[tokio::test]
async fn the_agents_own_command_is_refused() {
let Harness { shared, mut engine_rx, mut terminal_rx, terminal: _terminal } =
harness(std::process::id());
let (_dir, _accept, mut lines, _write) = join(&shared).await;
notice_containing(&mut terminal_rx, "Refused").await;
let read = tokio::time::timeout(std::time::Duration::from_secs(5), lines.next_line());
assert!(matches!(read.await, Ok(Ok(None)) | Ok(Err(_))), "the refused client got a frame");
assert!(engine_rx.try_recv().is_err());
}
/// A client joins over the endpoint, catches up, answers, and leaves without closing anything.
///
/// The break this catches: a joined client's hangup reaching the engine as `close`, which would
/// end the terminal's session the moment a phone dropped off the network.
#[tokio::test]
async fn a_client_joins_answers_and_leaves_without_closing_the_session() {
let Harness { shared, mut engine_rx, mut terminal_rx, terminal: _terminal } = harness(NOBODY);
let id = PermissionRequestId::new();
shared.publish(&permission_asked(&id));
let (_dir, _accept, mut lines, mut write) = join(&shared).await;
assert!(next_frame(&mut lines).await.contains(r#""kind":"ready""#));
assert!(next_frame(&mut lines).await.contains(r#""kind":"session_loaded""#));
assert!(next_frame(&mut lines).await.contains(r#""kind":"permission_requested""#));
notice_containing(&mut terminal_rx, "joined").await;
let answer = format!(
r#"{{"kind":"respond_permission","content":{{"id":"{}","reply":"once"}}}}"#,
id.as_str()
);
write.write_all(format!("{answer}\n").as_bytes()).await.expect("write");
assert!(matches!(engine_rx.recv().await, Some(Action::RespondPermission { .. })));
notice_containing(&mut terminal_rx, "Approved from").await;
drop((lines, write));
notice_containing(&mut terminal_rx, "left").await;
assert!(engine_rx.try_recv().is_err(), "leaving must not reach the engine");
}
/// A client that introduces itself is named when it joins and when it answers.
///
/// The break this catches: the terminal saying who joined before the introduction can arrive, or
/// naming the bridge's process, so "Approved from" never says which device answered.
#[tokio::test]
async fn an_introduced_client_is_named_when_it_joins_and_answers() {
let Harness { shared, mut engine_rx, mut terminal_rx, terminal: _terminal } = harness(NOBODY);
let id = PermissionRequestId::new();
shared.publish(&permission_asked(&id));
let (_dir, _accept, _lines, mut write) = join(&shared).await;
let introduce = r#"{"kind":"introduce","content":{"name":"iPhone"}}"#;
write.write_all(format!("{introduce}\n").as_bytes()).await.expect("write");
notice_containing(&mut terminal_rx, "iPhone joined").await;
let answer = format!(
r#"{{"kind":"respond_permission","content":{{"id":"{}","reply":"once"}}}}"#,
id.as_str()
);
write.write_all(format!("{answer}\n").as_bytes()).await.expect("write");
assert!(matches!(engine_rx.recv().await, Some(Action::RespondPermission { .. })));
notice_containing(&mut terminal_rx, "Approved from iPhone").await;
}
/// Every notice the terminal hears, up to and including the one containing `needle`.
async fn notices_until(terminal_rx: &mut mpsc::Receiver<Event>, needle: &str) -> Vec<String> {
let mut heard = Vec::new();
while !heard.last().is_some_and(|text: &String| text.contains(needle)) {
heard.push(notice_containing(terminal_rx, "").await);
}
heard
}
/// A client that opens as watch-only gets the session but isn't announced, joining or leaving.
/// An ordinary client, joining and leaving after it, marks where its notices would have been.
///
/// The break this catches: the terminal saying "Notifications joined this session" in every
/// session while a phone has notifications on.
#[tokio::test]
async fn a_watch_only_client_comes_and_goes_unannounced() {
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal: _terminal } =
harness(NOBODY);
let (_dir, _accept, mut lines, mut write) = join(&shared).await;
let watcher = r#"{"kind":"introduce","content":{"name":"Notifications","watch_only":true}}"#;
write.write_all(format!("{watcher}\n").as_bytes()).await.expect("write");
assert!(next_frame(&mut lines).await.contains(r#""kind":"ready""#));
drop((lines, write));
let (_dir, _accept, lines, mut write) = join(&shared).await;
let introduce = r#"{"kind":"introduce","content":{"name":"iPad"}}"#;
write.write_all(format!("{introduce}\n").as_bytes()).await.expect("write");
let mut heard = notices_until(&mut terminal_rx, "iPad joined").await;
drop((lines, write));
heard.extend(notices_until(&mut terminal_rx, "iPad left").await);
assert!(heard.iter().all(|text| !text.contains("Notifications")), "{heard:?}");
}
/// Everything the terminal hears until it's told the guests are `expected`.
async fn heard_until_guests(
terminal_rx: &mut mpsc::Receiver<Event>,
expected: &[&str],
) -> Vec<Event> {
let wait = tokio::time::timeout(std::time::Duration::from_secs(5), async {
let mut heard = Vec::new();
while let Some(event) = terminal_rx.recv().await {
let done = matches!(&event, Event::GuestsChanged(guests) if guests == expected);
heard.push(event);
if done {
return heard;
}
}
panic!("the terminal stream ended before the guests were {expected:?}");
});
wait.await.expect("the guests in time")
}
fn notices(heard: &[Event]) -> Vec<&str> {
heard
.iter()
.filter_map(|event| match event {
Event::Notice(text) => Some(text.as_str()),
_ => None,
})
.collect()
}
/// The owner's own device joins and leaves the dock's list without a line in the transcript.
///
/// The break this catches: a phone's every reconnect adding "joined" and "left" lines to the
/// owner's transcript, or the dock never told it came or went.
#[tokio::test]
async fn the_owners_device_is_listed_quietly() {
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal: _terminal } =
harness(NOBODY);
let (_dir, _accept, lines, mut write) = join(&shared).await;
let yours = r#"{"kind":"introduce","content":{"name":"iPhone","yours":true}}"#;
write.write_all(format!("{yours}\n").as_bytes()).await.expect("write");
let mut heard = heard_until_guests(&mut terminal_rx, &["iPhone"]).await;
drop((lines, write));
heard.extend(heard_until_guests(&mut terminal_rx, &[]).await);
assert!(notices(&heard).is_empty(), "{heard:?}");
}
/// Someone else's device is listed and still announced, joining and leaving.
///
/// The break this catches: a stranger's device joining the owner's session unremarked, or kept
/// off the dock's list.
#[tokio::test]
async fn anyone_elses_device_is_listed_and_announced() {
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal: _terminal } =
harness(NOBODY);
let (_dir, _accept, lines, mut write) = join(&shared).await;
let theirs = r#"{"kind":"introduce","content":{"name":"Sam's iPad"}}"#;
write.write_all(format!("{theirs}\n").as_bytes()).await.expect("write");
let mut heard = heard_until_guests(&mut terminal_rx, &["Sam's iPad"]).await;
drop((lines, write));
heard.extend(notices_until(&mut terminal_rx, "left").await.into_iter().map(Event::Notice));
let said = notices(&heard);
assert!(said.iter().any(|text| text.contains("Sam's iPad joined")), "{said:?}");
assert!(said.iter().any(|text| text.contains("Sam's iPad left")), "{said:?}");
}
/// The terminal's stream ends when the engine's does, even with a client still connected.
///
/// The break this catches: a connected client holding the terminal's stream open, so `luxe --rpc`
/// never sees the session end and never exits.
#[tokio::test]
async fn the_terminal_stream_ends_with_the_engines() {
let Harness { shared, engine_rx: _engine_rx, mut terminal_rx, terminal } = harness(NOBODY);
let (events_tx, events) = mpsc::channel(4);
let (_dir, _accept, mut lines, _write) = join(&shared).await;
assert!(next_frame(&mut lines).await.contains(r#""kind":"ready""#));
notice_containing(&mut terminal_rx, "joined").await;
let tee = tokio::spawn(tee(events, shared, terminal, None));
drop(events_tx);
tee.await.expect("tee ends with the engine's stream");
let end = tokio::time::timeout(std::time::Duration::from_secs(5), terminal_rx.recv());
assert_eq!(end.await.expect("the stream ends in time"), None);
}

View File

@@ -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.
@@ -66,6 +66,7 @@ pub(super) async fn run_tui(
events: engine_rx,
closer,
session_id,
claim: _claim,
} = start_engine(&settings).await?;
let event_rx = crate::workspace_runtime::bridge(
engine_rx,
@@ -75,6 +76,8 @@ pub(super) async fn run_tui(
},
crate::workspace_runtime::pull_request_watch(&settings.work_root),
);
let (event_rx, _sharing) =
super::share::share(event_rx, engine_tx.clone(), &settings, &session_id.0);
let exit = main_loop::run(
event_rx,
engine_tx.clone(),
@@ -180,7 +183,13 @@ impl Next<'_> {
// Another of your sessions, in its own worktree when it has one
shutdown_workspace_services().await;
let mut next = self.fresh(ResumeMode::Session(launch.session.clone()));
match enter_session_worktree(&launch.session, &mut next).await {
let state_root = &self.settings.state_root;
let entered =
match crate::engine_setup::open_elsewhere_now(state_root, &launch.session) {
Some(why) => Err(anyhow::anyhow!(why)),
None => enter_session_worktree(&launch.session, &mut next).await,
};
match entered {
Ok(()) => *self.settings = next,
Err(error) => self.carry_on(
session_id,
@@ -286,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,

View File

@@ -1,15 +1,18 @@
//! `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.
//! 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. A copy luxe's
//! installer script put there is updated by running that script again ([`installer`]). Either way
//! 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};
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,30 +20,70 @@ 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)
}
_ => {
println!("{}", instructions(source, check_only, cfg!(windows)));
match route(source, check_only) {
Some(route) => update_with(route, &latest).await,
None => {
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 {
/// How `luxe update` updates a copy.
#[derive(Debug, PartialEq, Eq)]
enum Route {
/// The owner's own commands, in order
Steps(&'static [&'static [&'static str]]),
/// The release's installer script, run again over this copy
Installer,
}
/// The route for `source`, or `None` when luxe only says what to do: the reader asked just to
/// check, or no owner's update is known.
fn route(source: InstallSource, check_only: bool) -> Option<Route> {
if check_only {
return None;
}
match source {
InstallSource::Installer => Some(Route::Installer),
_ => source.update_steps().map(Route::Steps),
}
}
/// Updates this copy by `route`, 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(route: Route, 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 = match &route {
Route::Steps(steps) => run_steps(steps).await,
Route::Installer => installer::run(latest, &exe).await,
};
if let Some(aside) = &aside {
aside.restore_if_missing()?;
}
ran?;
if route == Route::Installer {
installer::remove_legacy_updater(&exe);
}
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()),
}
@@ -52,30 +95,18 @@ async fn run_steps(steps: &[&[&str]]) -> anyhow::Result<()> {
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)
.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(())
}
/// Where to run `program` from: `beside` this binary when it is there, which is where the
/// installer put its updater, whether or not that directory is on `PATH`; by name otherwise.
fn program_path(program: &str, beside: Option<&Path>) -> PathBuf {
let name = format!("{program}{}", std::env::consts::EXE_SUFFIX);
beside
.map(|dir| dir.join(name))
.filter(|path| path.is_file())
.unwrap_or_else(|| PathBuf::from(program))
}
/// How the update landed, read from the `luxe` a shell would run now.
#[derive(Debug, PartialEq, Eq)]
enum Outcome {
@@ -108,15 +139,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 +181,8 @@ fn report(outcome: Outcome) -> anyhow::Result<()> {
Ok(())
}
mod aside;
mod installer;
#[cfg(test)]
mod tests;

View 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 update 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");
}
}

View File

@@ -0,0 +1,235 @@
//! Installer update — how `luxe update` updates a copy luxe's own installer script put there.
//!
//! It downloads the release's installer script, the one the install instructions pipe into a
//! shell, and runs it over this copy's directory. The script writes the binary, as it did on the
//! first install; luxe only picks the script and the directory ([`luxe_core::update::installer`]).
//!
//! Two things it does that the script alone would not. The script works in a scratch folder luxe
//! makes and removes, because dist's PowerShell installer never deletes its own and would leave a
//! folder holding the downloaded zip in `%TEMP%` on every update. And everything the script prints
//! is copied to a log as well as shown, so a failure can be read after the console scrolls away.
use anyhow::{bail, Context};
use luxe_core::update::{installer, InstallReceipt, InstallTarget, LEGACY_UPDATER};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
use tokio::sync::mpsc;
/// How long the script's download may take. It is a few dozen kilobytes; a minute covers a slow
/// link without leaving someone staring at a hung `luxe update`.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60);
/// The most script luxe will accept. The real one is about 25 KB; this is remote content that is
/// about to run, so anything far larger is not it.
const MAX_SCRIPT_BYTES: usize = 1024 * 1024;
/// How often and how far apart removing the scratch folder is tried. Windows can hold a file that
/// was just written (an antivirus scan of the downloaded zip), so one failure is not final.
const SCRATCH_REMOVE_TRIES: u32 = 3;
const SCRATCH_REMOVE_PAUSE: Duration = Duration::from_millis(500);
/// Runs the installer script for `latest` over the copy at `exe`.
pub(super) async fn run(latest: &str, exe: &Path) -> anyhow::Result<()> {
let target = InstallTarget::for_binary(exe, InstallReceipt::load().as_ref())
.with_context(|| format!("could not tell which folder {} is in", exe.display()))?;
let scratch = tempfile::Builder::new()
.prefix("luxe-update-")
.tempdir()
.context("could not make a scratch folder for the installer")?;
let url = installer::installer_script_url(latest);
println!("Downloading the luxe {latest} installer from {url}");
let ran = match download(&url, scratch.path()).await {
Ok(script) => run_script(&script, &target, scratch.path(), &log_path()).await,
Err(error) => Err(error),
};
remove_scratch(scratch.keep()).await;
ran
}
/// Removes the updater older installers put beside the binary, once an update has made it
/// redundant. A failure only costs a stale file, so it is reported and the update still counts.
pub(super) fn remove_legacy_updater(exe: &Path) {
let name = format!("{LEGACY_UPDATER}{}", std::env::consts::EXE_SUFFIX);
let updater = exe.with_file_name(name);
match std::fs::remove_file(&updater) {
Ok(()) => println!("Removed {}, which `luxe update` replaces.", updater.display()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
println!("Couldn't remove {} ({error}); it's no longer used.", updater.display())
}
}
}
/// Where the script's output is kept: one file, replaced each run, beside luxe's other logs.
fn log_path() -> PathBuf {
luxe_core::user_dirs::luxe_state_dir().join("logs").join("update.log")
}
/// Downloads the script at `url` into `folder` and returns where it landed.
async fn download(url: &str, folder: &Path) -> anyhow::Result<PathBuf> {
// The same bare user agent as the release check: the request says nothing about this machine
let client = reqwest::Client::builder().timeout(DOWNLOAD_TIMEOUT).user_agent("luxe").build()?;
let response =
client.get(url).send().await.with_context(|| format!("could not download {url}"))?;
if !response.status().is_success() {
bail!("could not download {url}: it returned {}", response.status());
}
let body = crate::update_check::bounded_bytes(response, MAX_SCRIPT_BYTES)
.await
.map_err(|error| anyhow::anyhow!("could not download {url}: {error}"))?;
let script = folder.join(installer::installer_script_name());
std::fs::write(&script, body)
.with_context(|| format!("could not save the installer to {}", script.display()))?;
Ok(script)
}
/// Runs `script` for `target`, showing and logging what it prints. `scratch` is where it keeps its
/// temporary files.
async fn run_script(
script: &Path,
target: &InstallTarget,
scratch: &Path,
log: &Path,
) -> anyhow::Result<()> {
let mut command = script_command(script);
command
.envs(target.script_variables())
.envs(scratch_variables(scratch))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn().context("could not start the installer")?;
let mut log_file = open_log(log, script, target);
let status = relay(&mut child, &mut log_file).await?;
append(&mut log_file, &format!("exit: {status}"));
if !status.success() {
bail!(
"the installer failed ({status}), so luxe is unchanged; its output is in {}",
log.display()
);
}
Ok(())
}
/// The command that runs the script: Windows PowerShell for the `.ps1`, `sh` for the rest.
fn script_command(script: &Path) -> tokio::process::Command {
if !cfg!(windows) {
let mut command = tokio::process::Command::new("sh");
command.arg(script);
return command;
}
let shell = luxe_core::program::resolve("powershell").unwrap_or_else(|| "powershell".into());
let mut command = tokio::process::Command::new(shell);
// No profile, so nothing of the reader's own runs inside the install. And no `PSModulePath`:
// inherited from PowerShell 7 it points Windows PowerShell at modules it cannot load
// (PowerShell/PowerShell#18530)
command.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(script);
command.env_remove("PSModulePath");
command
}
/// Points every temp-folder variable the scripts consult at `scratch`: `TMP` and `TEMP` for
/// PowerShell's `GetTempPath`, `TMPDIR` for `mktemp`.
fn scratch_variables(scratch: &Path) -> [(&'static str, &Path); 3] {
[("TMP", scratch), ("TEMP", scratch), ("TMPDIR", scratch)]
}
/// Opens the log fresh and heads it with what ran, or `None` when it cannot be written, which
/// costs the record but not the update.
fn open_log(log: &Path, script: &Path, target: &InstallTarget) -> Option<std::fs::File> {
let opened = log.parent().map_or(Ok(()), std::fs::create_dir_all);
let file = match opened.and_then(|()| std::fs::File::create(log)) {
Ok(file) => file,
Err(error) => {
tracing::warn!(%error, path = %log.display(), "could not open the update log");
return None;
}
};
let header = format!(
"luxe {} running {}\ninstall folder: {}\n",
luxe_core::version::VERSION,
script.display(),
target.dir.display()
);
let mut log = Some(file);
append(&mut log, &header);
log
}
/// Adds `line` to the log. A log that stops taking writes is dropped with one warning rather than
/// failing the update it only records.
fn append(log: &mut Option<std::fs::File>, line: &str) {
let Some(file) = log.as_mut() else { return };
if let Err(error) = writeln!(file, "{line}") {
tracing::warn!(%error, "the update log stopped taking writes");
*log = None;
}
}
/// One line the script printed, and whether it came on stderr.
type ScriptLine = (bool, String);
/// Shows each line the child prints, as it prints it, and copies it to `log`, then waits for it.
async fn relay(
child: &mut tokio::process::Child,
log: &mut Option<std::fs::File>,
) -> anyhow::Result<ExitStatus> {
let (sender, mut lines) = mpsc::unbounded_channel::<ScriptLine>();
if let Some(stdout) = child.stdout.take() {
tokio::spawn(forward_lines(stdout, false, sender.clone()));
}
if let Some(stderr) = child.stderr.take() {
tokio::spawn(forward_lines(stderr, true, sender.clone()));
}
drop(sender);
while let Some((is_stderr, line)) = lines.recv().await {
match is_stderr {
true => eprintln!("{line}"),
false => println!("{line}"),
}
append(log, &line);
}
child.wait().await.context("lost track of the installer")
}
/// Sends `stream` line by line. Lossy rather than strict UTF-8: Windows PowerShell writes in the
/// console's code page, and one accented folder name must not end the relay.
async fn forward_lines(
stream: impl AsyncRead + Unpin,
is_stderr: bool,
to: mpsc::UnboundedSender<ScriptLine>,
) {
let mut reader = BufReader::new(stream);
let mut buffer = Vec::new();
while matches!(reader.read_until(b'\n', &mut buffer).await, Ok(read) if read > 0) {
let line = String::from_utf8_lossy(&buffer).trim_end_matches(['\r', '\n']).to_string();
buffer.clear();
if to.send((is_stderr, line)).is_err() {
return;
}
}
}
/// Deletes the scratch folder, trying again briefly before saying it is left over.
async fn remove_scratch(folder: PathBuf) {
for attempt in 1..=SCRATCH_REMOVE_TRIES {
match std::fs::remove_dir_all(&folder) {
Ok(()) => return,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
Err(_) if attempt < SCRATCH_REMOVE_TRIES => {
tokio::time::sleep(SCRATCH_REMOVE_PAUSE).await
}
Err(error) => println!(
"Couldn't remove the installer's scratch folder {} ({error}). Nothing in it is \
needed, so it's safe to delete.",
folder.display()
),
}
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,85 @@
use super::*;
/// A folder holding a stand-in installer script with `body`, a scratch folder, and a log path.
#[cfg(unix)]
fn stand_in(body: &str) -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
let dir = tempfile::tempdir().expect("tempdir");
let script = dir.path().join("installer.sh");
std::fs::write(&script, body).expect("the script");
let scratch = dir.path().join("scratch");
std::fs::create_dir(&scratch).expect("scratch");
let log = dir.path().join("logs").join("update.log");
(dir, script, scratch, log)
}
/// The script is told where to install and that `PATH` is left alone, keeps its temporary files in
/// the scratch folder, and everything it prints, stderr too, lands in the log.
#[cfg(unix)]
#[tokio::test]
async fn the_script_is_pointed_at_the_target_and_logged() {
let (_dir, script, scratch, log) = stand_in(
"echo \"dir=$LUXE_CLI_INSTALL_DIR path=$LUXE_CLI_NO_MODIFY_PATH tmp=$TMPDIR\"\n\
echo 'a warning' >&2\n",
);
let target = InstallTarget { dir: "/home/dev/.local/bin".into(), modify_path: false };
run_script(&script, &target, &scratch, &log).await.expect("the script succeeds");
let written = std::fs::read_to_string(&log).expect("the log");
let expected = format!("dir=/home/dev/.local/bin path=1 tmp={}", scratch.display());
assert!(written.contains(&expected), "{written}");
assert!(written.contains("a warning"), "stderr is kept: {written}");
assert!(written.contains("install folder: /home/dev/.local/bin"), "{written}");
assert!(written.trim_end().ends_with("exit: exit status: 0"), "{written}");
}
/// A script that fails is an error that says luxe is unchanged and where its output went.
#[cfg(unix)]
#[tokio::test]
async fn a_failed_script_names_its_log() {
let (_dir, script, scratch, log) = stand_in("echo 'could not download' >&2\nexit 3\n");
let target = InstallTarget { dir: "/tmp/bin".into(), modify_path: true };
let error = run_script(&script, &target, &scratch, &log).await.expect_err("it failed");
let message = error.to_string();
assert!(
message.contains("unchanged") && message.contains(&log.display().to_string()),
"{message}"
);
assert!(std::fs::read_to_string(&log).expect("the log").contains("could not download"));
}
/// Every temp variable either script reads points at the scratch folder. Without `TMP` and
/// `TEMP`, PowerShell's `GetTempPath` would put its folder in `%TEMP%` again.
#[test]
fn every_temp_variable_points_at_the_scratch_folder() {
let scratch = Path::new("/scratch");
let names: Vec<&str> = scratch_variables(scratch).iter().map(|(name, _)| *name).collect();
assert_eq!(names, ["TMP", "TEMP", "TMPDIR"]);
assert!(scratch_variables(scratch).iter().all(|(_, value)| *value == scratch));
}
/// The scratch folder goes, the downloaded archive and what was unpacked from it included.
#[tokio::test]
async fn the_scratch_folder_is_removed_with_everything_in_it() {
let dir = tempfile::tempdir().expect("tempdir");
let scratch = dir.path().join("luxe-update-x");
let unpacked = scratch.join("6f1b2c");
std::fs::create_dir_all(&unpacked).expect("nested");
std::fs::write(unpacked.join("luxe-cli.zip"), b"zip").expect("the archive");
remove_scratch(scratch.clone()).await;
assert!(!scratch.exists());
}
/// After an update the legacy updater beside the binary is removed, and nothing else is.
#[test]
fn the_legacy_updater_is_removed_and_nothing_else() {
let dir = tempfile::tempdir().expect("tempdir");
let exe = dir.path().join(format!("luxe{}", std::env::consts::EXE_SUFFIX));
let updater = dir.path().join(format!("{LEGACY_UPDATER}{}", std::env::consts::EXE_SUFFIX));
for path in [&exe, &updater] {
std::fs::write(path, b"").expect("a stand-in");
}
remove_legacy_updater(&exe);
assert!(!updater.exists());
assert!(exe.exists());
remove_legacy_updater(&exe);
}

View File

@@ -11,16 +11,15 @@ fn copies() -> (tempfile::TempDir, PathBuf, PathBuf) {
(dir, updated, other)
}
/// The installer's updater runs from beside the binary even off `PATH`; anything not there, cargo
/// or brew, is found by name.
/// An installer copy is updated by luxe running the script, a package manager's by its commands,
/// and nothing runs for a check or for a copy with no known owner.
#[test]
fn a_program_beside_the_binary_runs_from_there() {
let dir = tempfile::tempdir().expect("tempdir");
let updater = dir.path().join(format!("luxe-cli-update{}", std::env::consts::EXE_SUFFIX));
std::fs::write(&updater, b"").expect("a stand-in updater");
assert_eq!(program_path("luxe-cli-update", Some(dir.path())), updater);
assert_eq!(program_path("brew", Some(dir.path())), PathBuf::from("brew"));
assert_eq!(program_path("luxe-cli-update", None), PathBuf::from("luxe-cli-update"));
fn each_source_takes_its_own_route() {
assert_eq!(route(InstallSource::Installer, false), Some(Route::Installer));
let cargo = InstallSource::Cargo.update_steps().expect("cargo has steps");
assert_eq!(route(InstallSource::Cargo, false), Some(Route::Steps(cargo)));
assert_eq!(route(InstallSource::Archive, false), None, "no owner to ask");
assert_eq!(route(InstallSource::Installer, true), None, "a check runs nothing");
}
#[test]
@@ -69,13 +68,10 @@ 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}"
);
// No second command to offer beside it, so it isn't named twice
assert_eq!(instructions(InstallSource::Installer, true), "To update: `luxe update`.");
}

View File

@@ -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;

View File

@@ -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")

View File

@@ -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) {

View File

@@ -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);

View File

@@ -23,7 +23,9 @@ mod spend;
#[cfg(test)]
pub(crate) mod test_env;
use session::attach_session;
pub(crate) use session::{resumed_session, IssueBinding, ResumeMode, WorktreeBinding};
pub(crate) use session::{
open_elsewhere_now, resumed_session, IssueBinding, ResumeMode, WorktreeBinding,
};
pub(crate) use settings::{AgentSettings, CliOverrides};
pub(crate) use spend::LoopSpendSink;
mod tooling_summary;
@@ -57,6 +59,9 @@ pub(crate) struct EngineHandle {
pub(crate) session_id: luxe_core::SessionId,
/// How a front-end that is exiting lets the engine finish first.
pub(crate) closer: EngineCloser,
/// The claim on the session taken before the engine existed, so nobody else can take it
/// before the engine claims it too; dropping it leaves the engine's own
pub(crate) claim: Option<luxe_core::session::SessionClaim>,
}
/// What an idle engine needs to wind down with no `SessionEnd` hooks to wait on.
@@ -126,11 +131,11 @@ pub(crate) async fn build_engine(
let todo_root = prepare_state_dirs(settings).await?;
let mut store = open_session_store(&settings.state_root);
let session_id = attach_session(settings, &mut store)?;
let (session_id, claim) = attach_session(settings, &mut store)?;
let model = settings.launch_model();
// 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);
@@ -178,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(
@@ -218,7 +224,7 @@ pub(crate) async fn build_engine(
.map_err(|error| anyhow::anyhow!("engine channel closed: {error}"))?;
}
Ok(EngineHandle { actions, events, session_id: attached, closer })
Ok(EngineHandle { actions, events, session_id: attached, closer, claim })
}
/// Makes the directories a session writes into, and answers where its checklists go.
@@ -317,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()
}

View File

@@ -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()
}

View File

@@ -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.

View File

@@ -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]

View File

@@ -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> =

View File

@@ -2,7 +2,7 @@
use std::path::PathBuf;
use luxe_core::session::{SessionId, SessionStore};
use luxe_core::session::{SessionClaim, SessionError, SessionId, SessionStore};
use super::AgentSettings;
@@ -135,7 +135,7 @@ pub(crate) struct WorktreeBinding {
pub(super) fn attach_session(
settings: &AgentSettings,
store: &mut luxe_core::session::JsonlSessionStore,
) -> anyhow::Result<SessionId> {
) -> anyhow::Result<(SessionId, Option<SessionClaim>)> {
let session_id = match (&settings.resume, resumed_session(store, &settings.resume)) {
(ResumeMode::New, _) => store.create(&settings.state_root.to_string_lossy())?,
(_, Some(id)) => {
@@ -154,6 +154,8 @@ pub(super) fn attach_session(
anyhow::bail!("session '{id}' not found for this project")
}
};
// Before the records below, which are writes too
let claim = claim_session(store, &session_id)?;
// A session in a worktree says so in its own log, which is how resuming finds the worktree
if let Some(binding) = &settings.worktree {
record_worktree(store, &session_id, binding, &settings.state_root);
@@ -164,7 +166,50 @@ pub(super) fn attach_session(
if let Some((number, url)) = &settings.pull_request {
record_pull_request(store, &session_id, *number, url);
}
Ok(session_id)
Ok((session_id, claim))
}
/// Claim `session_id` for this process, or say which luxe has it open and how to get there.
fn claim_session(
store: &luxe_core::session::JsonlSessionStore,
session_id: &SessionId,
) -> anyhow::Result<Option<SessionClaim>> {
match store.claim(session_id) {
Ok(claim) => Ok(claim),
Err(SessionError::OpenElsewhere(id)) => anyhow::bail!(open_elsewhere(&id)),
Err(error) => Err(error.into()),
}
}
/// Why `session` can't be opened here right now, when another luxe has it open.
///
/// Asked before leaving the session that's running, so the reader stays where they are rather
/// than landing outside the TUI. This process's own claims don't count against it.
pub(crate) fn open_elsewhere_now(state_root: &std::path::Path, session: &str) -> Option<String> {
let store = super::open_session_store(state_root);
let id = SessionId(session.to_string());
match store.claim(&id) {
Err(SessionError::OpenElsewhere(id)) => Some(open_elsewhere(&id)),
// Any other failure meets the session's start, which reports it in full
Ok(_) | Err(_) => None,
}
}
/// Where the session is open, when the luxe that has it says so, and what to do about it.
fn open_elsewhere(id: &SessionId) -> String {
let runtime = luxe_core::user_dirs::luxe_runtime_dir();
let holder = luxe_core::local_endpoint::live_sessions(&runtime)
.into_iter()
.find(|live| live.session_id == id.0);
let place = match holder {
Some(live) => format!(" (process {}, in {})", live.pid, live.cwd),
None => String::new(),
};
// `luxe join` is not offered: it speaks the protocol, so a person running it sees JSON
format!(
"session {id} is already open in another luxe{place}. Carry on there, or close it \
there first"
)
}
#[cfg(test)]
@@ -229,4 +274,35 @@ mod tests {
assert_eq!(resumed_session(&store, &ResumeMode::Session("nope".into())), None);
assert_eq!(resumed_session(&store, &ResumeMode::PullRequest(9)), None);
}
/// A session another process holds is refused up front, with the way to reach it, and the
/// check made before leaving a running session says the same.
///
/// The break this catches: attaching without a claim, so a second `luxe --resume` opens a
/// second writer on the log, or a resume from inside the TUI that lands the reader outside it.
#[test]
fn a_session_open_in_another_process_is_refused_and_says_so() {
let dir = tempfile::tempdir().unwrap();
let mut store = open_session_store(dir.path());
let id = store.create("/work").unwrap();
let lock = store.session_path(&id).unwrap().with_extension("lock");
let other_process = std::fs::File::create(&lock).unwrap();
other_process.try_lock().unwrap();
let settings = {
let _env = super::super::test_env::ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _home = super::super::test_env::isolated_env();
let mut settings = AgentSettings::resolve(dir.path().to_path_buf(), Default::default());
settings.resume = ResumeMode::Session(id.0.clone());
settings
};
let refused = attach_session(&settings, &mut store).expect_err("held elsewhere");
let expected = format!("session {id} is already open in another luxe");
assert!(refused.to_string().contains(&expected), "{refused}");
assert!(open_elsewhere_now(dir.path(), &id.0).is_some());
drop(other_process);
assert!(open_elsewhere_now(dir.path(), &id.0).is_none());
}
}

View File

@@ -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.

View File

@@ -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(),

View File

@@ -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
@@ -252,7 +252,10 @@ pub(super) fn build_tool_registry(
clone_repositories: luxe_core::config::Config::load(state_root).tools.clone_repositories(),
..luxe_tools::web::WebConfig::from_env()
};
let read_tracker = luxe_tools::register_builtins(&mut registry, Some(todo_root), web);
// tree-sitter, so `grep` can say which function or type each match sits in
let outline = Arc::new(luxe_lsp::syntax::SyntaxOutline);
let read_tracker =
luxe_tools::register_builtins(&mut registry, Some(todo_root), web, Some(outline));
if loop_driven {
registry.register(Arc::new(luxe_tools::loop_control::LoopControlTool::new()));
}
@@ -341,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,

View File

@@ -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

View File

@@ -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() {

View File

@@ -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

View File

@@ -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() {

View File

@@ -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
});

View File

@@ -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(&notice("iteration 2 · phase 0"));
view.observe(&notice("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(&notice("phase 0 claimed complete — running the gate"));
view.observe(&Event::TurnEnded { reason: luxe_core::StopReason::EndTurn });
view.observe(&notice("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:?}");
}
}

View 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}");
}
}
}

View 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"));
}
}

View File

@@ -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.
@@ -153,6 +153,28 @@ pub(crate) fn build_menu(settings: &AgentSettings) -> ModelMenu {
ModelMenu { catalog: entries, active }
}
/// The models a client of the protocol can switch to: the `/model` menu in its order, leaving out
/// rows only guessed for an endpoint that hasn't said what it serves.
pub(crate) fn choices(settings: &AgentSettings) -> Vec<luxe_core::event::ModelChoice> {
offered(&build_menu(settings).catalog)
}
fn offered(menu: &[ModelEntry]) -> Vec<luxe_core::event::ModelChoice> {
menu.iter().filter(|entry| !entry.unverified).map(|entry| choice(&entry.info)).collect()
}
/// `info` as a client offers it, with the thinking levels it honors as they are, not clamped.
fn choice(info: &ModelInfo) -> luxe_core::event::ModelChoice {
let levels = luxe_core::provider::ThinkingLevel::ALL.iter().copied();
let honored = levels.filter(|level| info.effective_thinking_level(*level) == *level);
luxe_core::event::ModelChoice {
provider: info.r#ref.provider.clone(),
model: info.r#ref.id.clone(),
name: info.display().to_string(),
thinking_levels: honored.collect(),
}
}
/// Whether a provider needs no credential at all — a server on this machine.
///
/// Naming one on the command line is the whole statement of intent: there is no key to check, so

View File

@@ -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: {:?}",
@@ -223,3 +223,44 @@ fn an_unconfigured_machine_has_no_models_to_choose_between() {
);
drop(dir);
}
/// A choice names the model as `select_model` takes it, and offers the levels it honors as they
/// are: only `off` for a model that doesn't reason, and nothing it would quietly clamp.
///
/// The break this catches: offering every level for every model, so a phone sets `ultra` and the
/// engine silently runs `high`; or sending the display name where `select_model` wants the id.
#[test]
fn a_choice_offers_only_the_levels_its_model_honors() {
use luxe_core::provider::ThinkingLevel::{High, Low, Medium, Minimal, Off};
let mut info = ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("anthropic", "claude-sonnet-5"),
display_name: Some("Claude Sonnet 5".into()),
reasoning: false,
..Default::default()
};
let plain = choice(&info);
assert_eq!((plain.provider.as_str(), plain.model.as_str()), ("anthropic", "claude-sonnet-5"));
assert_eq!(plain.name, "Claude Sonnet 5");
assert_eq!(plain.thinking_levels, [Off]);
info.reasoning = true;
assert_eq!(choice(&info).thinking_levels, [Off, Minimal, Low, Medium, High]);
}
/// A row only guessed for an endpoint that hasn't said what it serves isn't offered.
///
/// The break this catches: a phone offering an Azure resource deployments it doesn't have, which
/// fail on the first turn.
#[test]
fn a_guessed_row_isnt_offered() {
let entry = |id: &str, unverified: bool| ModelEntry {
info: ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("azure", id),
..Default::default()
},
label: id.into(),
configured: false,
unverified,
};
let offered = offered(&[entry("served", false), entry("guessed", true)]);
assert_eq!(offered.iter().map(|choice| choice.model.as_str()).collect::<Vec<_>>(), ["served"]);
}

View File

@@ -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.
//!

View File

@@ -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.",

View File

@@ -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.

View File

@@ -137,7 +137,10 @@ async fn fetch_latest(url: &str) -> Result<String, String> {
if !response.status().is_success() {
return Err(format!("release manifest returned {}", response.status()));
}
let body = bounded_body(response).await?;
let body = bounded_bytes(response, MAX_BODY_BYTES)
.await
.map_err(|error| format!("release manifest: {error}"))?;
let body = String::from_utf8(body).map_err(|_| "release manifest was not UTF-8".to_string())?;
let parsed: serde_json::Value =
serde_json::from_str(&body).map_err(|error| error.to_string())?;
@@ -156,20 +159,24 @@ async fn fetch_latest(url: &str) -> Result<String, String> {
Ok(normalized.to_string())
}
/// Read a response body, refusing one that outgrows [`MAX_BODY_BYTES`].
async fn bounded_body(response: reqwest::Response) -> Result<String, String> {
/// Reads a response body, refusing one that outgrows `limit` bytes: what comes back is remote and
/// untrusted, so a server that streams forever is cut off rather than exhausting memory.
pub(crate) async fn bounded_bytes(
response: reqwest::Response,
limit: usize,
) -> Result<Vec<u8>, String> {
use futures::StreamExt;
let mut stream = response.bytes_stream();
let mut body = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|error| error.to_string())?;
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err("release manifest is implausibly large".to_string());
if body.len() + chunk.len() > limit {
return Err(format!("the response is larger than {limit} bytes"));
}
body.extend_from_slice(&chunk);
}
String::from_utf8(body).map_err(|_| "release manifest was not UTF-8".to_string())
Ok(body)
}
#[cfg(test)]

View File

@@ -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 {

View File

@@ -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)| {

View File

@@ -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)));

View File

@@ -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() {

View File

@@ -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,

View File

@@ -15,6 +15,21 @@ fn project_server(project: &Path) {
std::fs::write(project.join(".mcp.json"), config.to_string()).unwrap();
}
/// Whether luxe launched the project's server. The marker is the proof when the child gets that far,
/// but the child is this test binary starting up again, and on a slow runner luxe can give up on the
/// closed connection before that startup reaches the write; its report of the attempt is the proof
/// then. A refused server is never launched, so neither can appear.
fn started(project: &Path, stdout: &str) -> bool {
project.join("mcp-ran").exists() || stdout.contains("project-marker: failed to connect")
}
/// Whether luxe refused to start the project's server: it says so, naming it. Checked alongside the
/// absent marker, which alone would also pass for a server launched too slowly to have written it.
fn refused(project: &Path, stdout: &str) -> bool {
stdout.contains("Not starting project MCP servers: project-marker")
&& !project.join("mcp-ran").exists()
}
fn tools(project: &Path, home: &Path, trust: bool) -> String {
run_mcp(project, home, trust, "tools")
}
@@ -56,8 +71,8 @@ fn tools_does_not_start_an_untrusted_project_server() {
let home = tempfile::tempdir().unwrap();
project_server(project.path());
let stdout = tools(project.path(), home.path(), false);
assert!(!project.path().join("mcp-ran").exists(), "the project command ran: {stdout}");
assert!(stdout.contains("project-marker") && stdout.contains("--trust-project"), "{stdout}");
assert!(refused(project.path(), &stdout), "the project command ran: {stdout}");
assert!(stdout.contains("--trust-project"), "{stdout}");
}
/// Refusing every project server would silently discard the CLI's explicit trust grant.
@@ -67,7 +82,7 @@ fn tools_starts_a_project_server_with_explicit_trust() {
let home = tempfile::tempdir().unwrap();
project_server(project.path());
let stdout = tools(project.path(), home.path(), true);
assert!(project.path().join("mcp-ran").exists(), "the trusted command never ran: {stdout}");
assert!(started(project.path(), &stdout), "the trusted command never ran: {stdout}");
}
/// CLI tools must honor the same global opt-in the engine uses.
@@ -78,7 +93,7 @@ fn tools_honors_the_user_always_preference() {
project_server(project.path());
tooling_preference(&home.path().join("luxe"), "always");
let stdout = tools(project.path(), home.path(), false);
assert!(project.path().join("mcp-ran").exists(), "the user opt-in was ignored: {stdout}");
assert!(started(project.path(), &stdout), "the user opt-in was ignored: {stdout}");
}
/// Explicit trust must not override the user's global refusal to start project tooling.
@@ -89,7 +104,7 @@ fn tools_honors_the_user_never_preference_even_with_trust() {
project_server(project.path());
tooling_preference(&home.path().join("luxe"), "never");
let stdout = tools(project.path(), home.path(), true);
assert!(!project.path().join("mcp-ran").exists(), "the user refusal was ignored: {stdout}");
assert!(refused(project.path(), &stdout), "the user refusal was ignored: {stdout}");
}
/// A repository must not grant itself permission by setting the global-only tooling preference.
@@ -100,7 +115,7 @@ fn tools_ignores_a_project_always_preference() {
project_server(project.path());
tooling_preference(&project.path().join(".luxe"), "always");
let stdout = tools(project.path(), home.path(), false);
assert!(!project.path().join("mcp-ran").exists(), "the project granted itself trust: {stdout}");
assert!(refused(project.path(), &stdout), "the project granted itself trust: {stdout}");
}
/// The trust filter must not block a server declared by the user, outside the project.
@@ -112,5 +127,5 @@ fn tools_starts_a_user_server_without_project_trust() {
std::fs::create_dir_all(home.path().join("luxe")).unwrap();
std::fs::rename(project.path().join(".mcp.json"), home.path().join("luxe/mcp.json")).unwrap();
let stdout = tools(project.path(), home.path(), false);
assert!(project.path().join("mcp-ran").exists(), "the user command never ran: {stdout}");
assert!(started(project.path(), &stdout), "the user command never ran: {stdout}");
}

View File

@@ -28,6 +28,8 @@ fn run_rpc_with(flags: &[&str], input: &str) -> (String, String) {
.current_dir(project.path())
.env("HOME", home.path())
.env("XDG_CONFIG_HOME", home.path().join(".config"))
// it shares its session, and the developer's own sessions are listed in the real one
.env("LUXE_RUNTIME_DIR", home.path().join("runtime"))
.env_remove("LUXE_CONFIG_DIR")
.env_remove("LUXE_STATE_DIR")
// Offline and deterministic: a catalog refresh is best-effort anyway, and a test that
@@ -149,7 +151,7 @@ struct Live {
seen: std::cell::RefCell<Vec<String>>,
/// Where luxe writes its log, which a timeout prints
project: std::path::PathBuf,
_home: tempfile::TempDir,
home: tempfile::TempDir,
}
impl Live {
@@ -161,6 +163,7 @@ impl Live {
.current_dir(project)
.env("HOME", home.path())
.env("XDG_CONFIG_HOME", home.path().join(".config"))
.env("LUXE_RUNTIME_DIR", home.path().join("runtime"))
.env("LUXE_MODELS_DEV_REFRESH", "0")
.env("RUST_LOG", "debug")
// not a terminal multiplexer's pane, whatever the one running the tests is
@@ -190,10 +193,17 @@ impl Live {
frames,
seen: Default::default(),
project: project.to_path_buf(),
_home: home,
home,
}
}
/// What this luxe published about its session for others to join, if anything.
fn published(&self) -> Option<serde_json::Value> {
let record = self.home.path().join("runtime").join(format!("{}.json", self.child.id()));
let text = std::fs::read_to_string(record).ok()?;
Some(serde_json::from_str(&text).expect("the record is JSON"))
}
fn send(&mut self, frame: serde_json::Value) {
writeln!(self.stdin, "{frame}").expect("write a frame");
self.stdin.flush().expect("flush");
@@ -262,7 +272,7 @@ fn changed_repository() -> tempfile::TempDir {
};
git(&["init", "--quiet", "--initial-branch=main"]);
git(&["config", "user.email", "tests@example.invalid"]);
git(&["config", "user.name", "Luxe Tests"]);
git(&["config", "user.name", "luxe Tests"]);
std::fs::write(project.path().join("total.rs"), "fn total() -> u32 {\n 1\n}\n").unwrap();
git(&["add", "total.rs"]);
git(&["commit", "--quiet", "-m", "initial"]);
@@ -344,6 +354,21 @@ fn rpc_drives_a_review_from_comment_to_commit() {
assert_eq!(String::from_utf8_lossy(&log.stdout).lines().count(), 2, "the review's commit");
}
/// A session started over `--rpc` is shared like the terminal's, so the bridge can start one for a
/// phone and the phone can join it.
///
/// The break this catches: `run_rpc` not offering its session, which leaves a session started from
/// the phone running where nothing can reach it.
#[test]
fn rpc_shares_its_session() {
let project = tempfile::tempdir().expect("temp project");
let luxe = Live::start(project.path(), &[]);
let ready = luxe.wait("ready", |_| true);
let record = luxe.published().expect("a record in the runtime folder");
assert_eq!(record["session_id"], ready["session_id"]);
luxe.close();
}
/// A read-only session reviews and comments, but writes no history.
#[test]
fn rpc_read_only_refuses_to_commit_a_review() {

View File

@@ -3,7 +3,7 @@ name = "luxe-core"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Luxe's engine: the agent loop, session model, context assembly, permissions, and the Provider/Tool/Hook traits"
description = "luxe's engine: the agent loop, session model, context assembly, permissions, and the Provider/Tool/Hook traits"
repository.workspace = true
homepage.workspace = true
@@ -66,11 +66,23 @@ globset = "0.4"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["process", "stdio", "system"] }
# Pointing stdin at the null device on Windows, and keeping the pipe Luxe took out of every child:
# Pointing stdin at the null device on Windows, and keeping the pipe luxe took out of every child:
# no safe API does either, and without it every child of `luxe --rpc` stalls behind the protocol
# read. See `program::take_stdin`.
# read. See `program::take_stdin`. Job objects end a command's whole tree on a timeout, where
# Windows has no process group to signal; see `program::TreeGuard`. A session's named pipe needs a
# descriptor granting this user alone, the connected client's process and every process's parent;
# see `local_endpoint::windows`.
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_System_Console",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_JobObjects",
"Win32_System_Pipes",
"Win32_System_Threading",
] }
[dev-dependencies]
tempfile = "3"

View File

@@ -211,7 +211,7 @@ impl ToolActivity {
}
}
/// Whether a tool is Luxe's own housekeeping rather than work someone asked for.
/// Whether a tool is luxe's own housekeeping rather than work someone asked for.
///
/// Only [`crate::tool::ACTIVATE_TOOLS_NAME`], and only because *we* tier the registry: the model
/// asks for a deferred tool's schema before it can call it, which is a fact about our request
@@ -323,10 +323,12 @@ pub enum ToolActivityState {
/// distinction from `Running` is whose work it is: the model's rather than the tool's, which
/// is why the card's clock does not start until dispatch.
Composing,
/// The call has been written in full but has not started, because something else is running.
/// The call hasn't started because something else comes first: it's written in full and
/// waiting its turn, or still being written while an earlier call runs.
///
/// Tools are dispatched strictly one at a time, so **at most one call is ever `Running`** —
/// and a model writes the calls of one message in order, so at most one is ever `Composing`.
/// and a model writes the calls of one message in order, so at most one is ever `Composing`,
/// and never beside a `Running` one, since a call written while another runs waits behind it.
/// Between them that is the invariant a transcript has to show: exactly one card is working.
/// Drawing every un-finished call as running broke it in the obvious direction (two `bash`
/// cards spinning side by side, which reads as two shells at once); drawing them all as

View File

@@ -189,7 +189,7 @@ pub enum LoginScope {
/// Every configurable provider, with every method it offers.
#[default]
Any,
/// Providers whose subscription Luxe is allowed to sign in to.
/// Providers whose subscription luxe is allowed to sign in to.
Subscription,
/// Providers that take a key you already have.
ApiKey,
@@ -360,8 +360,6 @@ pub struct LoginOutcome {
/// A local server takes no credential, and "API key" would be a claim the file contradicts.
pub kind: Option<CredentialKind>,
pub account: Option<String>,
/// A model id worth defaulting to, when the flow learned one.
pub suggested_model: Option<String>,
/// Factual summary lines about what now exists (e.g. "17 models available").
pub notes: Vec<String>,
/// Advice that only makes sense once the credential exists, shown apart from the summary.

View File

@@ -1,7 +1,7 @@
//! Briefs — the messages Luxe writes to the agent itself, told apart from the reader's own.
//! Briefs — the messages luxe writes to the agent itself, told apart from the reader's own.
//!
//! A draft, a question from a review and a batch of review comments each reach the agent as a
//! user message Luxe composed: the instructions, the evidence, the IDs a report has to echo. The
//! user message luxe composed: the instructions, the evidence, the IDs a report has to echo. The
//! transcript is the reader's conversation, and a page of plumbing in their own colors reads as
//! something they said. So a front-end shows one line saying what happened instead — or, for a
//! question from a review, just the question, since those words *are* the reader's — and the
@@ -37,16 +37,24 @@ pub(crate) const RESUME_BRIEFING: &str = "## Resuming\n";
/// Those are only ever added after what the reader sent, so the first block is theirs whatever it
/// starts with: a pasted hook log is still a message.
pub fn readers_words(content: &[crate::message::ContentBlock]) -> Vec<(usize, String)> {
readers_texts(content.iter().map(|block| match block {
crate::message::ContentBlock::Text(text) => Some(text.as_str()),
_ => None,
}))
}
/// [`readers_words`] over each block's text, `None` for a block without any: for a front end that
/// has a message only as it arrived on the wire, an image's bytes left behind.
pub fn readers_texts<'a>(
blocks: impl IntoIterator<Item = Option<&'a str>>,
) -> Vec<(usize, String)> {
let for_the_model = |text: &str| {
let ours = [HOOK_CONTEXT, BRANCH_NOTE, RESUME_BRIEFING];
crate::mode::note(text).is_some() || ours.iter().any(|opener| text.starts_with(opener))
};
let text = content.iter().enumerate().filter_map(|(index, block)| match block {
crate::message::ContentBlock::Text(text) => Some((index, text)),
_ => None,
});
let text = blocks.into_iter().enumerate().filter_map(|(index, text)| Some((index, text?)));
text.filter(|(index, text)| *index == 0 || !for_the_model(text))
.map(|(index, text)| (index, text.clone()))
.map(|(index, text)| (index, text.to_string()))
.collect()
}
@@ -82,7 +90,7 @@ const FINDING_ID: &str = " Finding ID: ";
const EVIDENCE: &str = " Evidence: ";
const REVIEWER: &str = " Reviewer: ";
/// The lines that follow a comment's body; none of them is the reader's question.
const AFTER_BODY: [&str; 4] = [" Source: ", " Proposed fix: ", " Agent: ", " Luxe: "];
const AFTER_BODY: [&str; 4] = [" Source: ", " Proposed fix: ", " Agent: ", " luxe: "];
/// How review feedback closes.
const CLOSING: &str = "Do not rewrite unrelated code.";
@@ -150,7 +158,7 @@ pub fn review_questions(text: &str) -> Vec<ReviewQuestion> {
/// How a draft's fence opens, its newline included.
const DRAFT_FENCE: &str = "```luxe-draft\n";
/// An answer as the reader sees it: without what the agent wrote for Luxe to read.
/// An answer as the reader sees it: without what the agent wrote for luxe to read.
///
/// A fix's remediation report goes, since the review shows it comment by comment, and the prose
/// around it stays. An answer carrying a draft goes whole: the draft opens in the card or composer

View File

@@ -14,7 +14,7 @@
//!
//! # Design
//!
//! Same policy as Pi's, checked against Luxe's own ledgers:
//! Same policy as Pi's, checked against luxe's own ledgers:
//!
//! - **While a turn runs** the next request is certain, so a refresh pays whenever a read costs
//! less than the write it saves. Across 2,980 recorded Claude calls this rescued 12 of 14 waits

View File

@@ -15,16 +15,17 @@ mod planner;
mod prune;
mod summary;
pub(crate) use budget::IMAGE_TOKEN_ESTIMATE;
pub use budget::{
clamp_max_tokens_to_context, compaction_threshold, context_fullness_percent, context_tokens,
estimate_calibration, estimate_message_tokens, estimate_prefix_tokens, estimate_tokens,
last_observed_context_tokens, prompt_tokens, usable_context_window, ContextBudget,
CONTEXT_SAFETY_TOKENS,
};
pub(crate) use budget::{summary_max_tokens, IMAGE_TOKEN_ESTIMATE};
pub use context::{context_entries, context_messages};
pub use planner::find_compaction_point;
pub use prune::{prune_tool_outputs, ContextPressure};
pub(crate) use summary::SUMMARIZER_PROMPT;
pub use summary::{format_structured_summary, serialize_for_summary, summary_carries_content};
/// Settings controlling compaction behavior.

View File

@@ -5,6 +5,7 @@ use super::CompactionSettings;
use crate::message::{ContentBlock, Message, ToolOutput};
use crate::provider::ToolSchema;
use crate::session::Entry;
use std::borrow::Borrow;
use tracing::{debug, warn};
/// Estimate the token count for a set of entries.
@@ -15,8 +16,8 @@ use tracing::{debug, warn};
///
/// Still only an estimate. Where the provider has told us the real occupancy, prefer that:
/// [`ContextBudget::observed_tokens`] and [`last_observed_context_tokens`].
pub fn estimate_tokens(entries: &[Entry]) -> u64 {
entries.iter().map(entry_to_token_estimate).sum()
pub fn estimate_tokens<E: Borrow<Entry>>(entries: &[E]) -> u64 {
entries.iter().map(|entry| entry_to_token_estimate(entry.borrow())).sum()
}
/// Estimate the tokens a provider-facing message list occupies.
@@ -31,7 +32,7 @@ pub fn estimate_message_tokens(messages: &[Message]) -> u64 {
/// Estimate the tokens a request spends before any conversation: the system prompt and the tool
/// schemas.
///
/// Far from negligible — Luxe's harness plus two dozen JSON schemas is tens of thousands of
/// Far from negligible — luxe's harness plus two dozen JSON schemas is tens of thousands of
/// tokens, and leaving it out of a prompt figure is how a request that "fits" turns into a 400.
pub fn estimate_prefix_tokens(system: Option<&str>, tools: &[ToolSchema]) -> u64 {
let system = system.map(|text| text.len() as u64 / 4).unwrap_or(0);
@@ -100,15 +101,15 @@ fn block_token_estimate(block: &ContentBlock) -> u64 {
///
/// Returns `None` when the transcript has nothing measured to offer, and the caller falls back to
/// [`estimate_tokens`].
pub fn last_observed_context_tokens(entries: &[Entry]) -> Option<u64> {
pub fn last_observed_context_tokens<E: Borrow<Entry>>(entries: &[E]) -> Option<u64> {
last_observed_measurement(entries).map(|(_, occupancy)| occupancy)
}
/// [`last_observed_context_tokens`], plus where in the transcript it was measured, so a caller can
/// estimate only what has been appended since.
fn last_observed_measurement(entries: &[Entry]) -> Option<(usize, u64)> {
fn last_observed_measurement<E: Borrow<Entry>>(entries: &[E]) -> Option<(usize, u64)> {
for (index, entry) in entries.iter().enumerate().rev() {
match &entry.kind {
match &entry.borrow().kind {
crate::session::EntryKind::Compaction { .. } => return None,
crate::session::EntryKind::Usage { source, totals, .. }
if *source == crate::usage::UsageSource::Agent && totals.calls == 1 =>
@@ -130,7 +131,11 @@ fn last_observed_measurement(entries: &[Entry]) -> Option<(usize, u64)> {
/// schemas, plus an estimate of the entries appended since. With nothing measured (a fresh session,
/// or one whose last usage predates a compaction) it estimates [`context_entries`] plus the prefix:
/// what a compaction replaced is not sent, so it is not counted.
pub fn prompt_tokens(entries: &[Entry], system: Option<&str>, tools: &[ToolSchema]) -> u64 {
pub fn prompt_tokens<E: Borrow<Entry>>(
entries: &[E],
system: Option<&str>,
tools: &[ToolSchema],
) -> u64 {
match last_observed_measurement(entries) {
// The measurement already includes the prefix that call was sent with.
Some((index, observed)) => observed + estimate_tokens(&entries[index + 1..]),
@@ -140,7 +145,7 @@ pub fn prompt_tokens(entries: &[Entry], system: Option<&str>, tools: &[ToolSchem
/// Estimated tokens for the conversation a request would carry — [`estimate_tokens`] over
/// [`context_entries`].
pub fn context_tokens(entries: &[Entry]) -> u64 {
pub fn context_tokens<E: Borrow<Entry>>(entries: &[E]) -> u64 {
context_entries(entries).into_iter().map(entry_to_token_estimate).sum()
}
@@ -171,7 +176,7 @@ pub fn usable_context_window(context_window: u64, max_tokens: u32, reserve_token
/// percent on a 200K prompt is thousands of tokens out. Mirrors Pi's margin.
pub const CONTEXT_SAFETY_TOKENS: u32 = 4_096;
/// The smallest output cap Luxe will ask for once the window is full. Useless as an answer, but a
/// The smallest output cap luxe will ask for once the window is full. Useless as an answer, but a
/// request that asks for zero (or a negative) output is a hard rejection rather than a short reply.
const MIN_MAX_TOKENS: u32 = 1;
@@ -215,6 +220,28 @@ pub fn clamp_max_tokens_to_context(
Some(capped)
}
/// Output allowance for one summary, before the model's limit and the window cut it down.
///
/// Room for the six sections over a whole window's worth of transcript *and* for the reasoning a
/// model that always thinks spends first, even asked not to: that comes out of the same allowance,
/// and a summary that hits the ceiling is refused whole, so a tight one fails every time on exactly
/// the long sessions that need it. Generous because only what's written is billed, while a refused
/// summary has already paid for reading the whole window.
pub(crate) const SUMMARY_MAX_TOKENS: u32 = 32_768;
/// What one summary request may ask for: [`SUMMARY_MAX_TOKENS`], within `model`'s own output limit
/// (0 for unknown) and what `prompt_tokens` leaves of its window.
pub(crate) fn summary_max_tokens(
model: &crate::provider::ModelInfo,
prompt_tokens: u64,
) -> Option<u32> {
let ceiling = match model.max_tokens {
0 => SUMMARY_MAX_TOKENS,
limit => limit.min(SUMMARY_MAX_TOKENS),
};
clamp_max_tokens_to_context(model.context_window, prompt_tokens, ceiling)
}
/// Percent of the usable window currently occupied. Returns 0.0 when either input is 0 (e.g. no
/// usage observed yet), so callers read "unknown" as empty rather than full.
pub fn context_fullness_percent(used_tokens: u64, usable: u64) -> f64 {

View File

@@ -43,6 +43,27 @@ fn the_output_cap_never_claims_room_the_prompt_is_using() {
assert_eq!(clamp(8_192, 999_999, 32_000), Some(MIN_MAX_TOKENS));
}
/// A summary gets room to think and then write, within the model's limit and the window.
#[test]
fn a_summary_gets_room_beyond_what_reasoning_spends() {
let model = |context_window, max_tokens| crate::provider::ModelInfo {
context_window,
max_tokens,
..Default::default()
};
// Fails if the allowance drops back to the 16K a long session's summary ran out of
let roomy = summary_max_tokens(&model(1_000_000, 128_000), 880_000).expect("a cap");
assert!(roomy >= 32_000, "{roomy}");
// Fails if the model's own output limit is ignored
assert_eq!(summary_max_tokens(&model(1_000_000, 8_000), 10_000), Some(8_000));
// An unknown limit is no limit of its own
assert_eq!(summary_max_tokens(&model(1_000_000, 0), 10_000), Some(SUMMARY_MAX_TOKENS));
// Fails if the window clamp is skipped
let tight = 200_000 - 190_000 - CONTEXT_SAFETY_TOKENS;
assert_eq!(summary_max_tokens(&model(200_000, 128_000), 190_000), Some(tight));
}
/// The prompt figure the clamp runs on: measured where the provider told us, estimated only
/// for the tail it never saw.
#[test]
@@ -281,7 +302,7 @@ fn observed_occupancy_reads_the_last_agent_call_and_stops_at_a_compaction() {
// call measures its own context, not the turn's.
assert_eq!(last_observed_context_tokens(&[usage(UsageSource::Agent, 4, 200_000, 900)]), None);
assert_eq!(last_observed_context_tokens(&[usage(UsageSource::Review, 1, 50_000, 100)]), None);
assert_eq!(last_observed_context_tokens(&[]), None);
assert_eq!(last_observed_context_tokens::<Entry>(&[]), None);
// A call that measured nothing measured nothing — it is not an empty context. Reading it
// as one would report a full window as fresh and hand the next request the whole output

View File

@@ -2,6 +2,7 @@
use crate::message::Message;
use crate::session::Entry;
use std::borrow::Borrow;
/// How a compaction summary introduces itself to the model.
///
@@ -26,15 +27,16 @@ const SUMMARY_SUFFIX: &str = "\n</summary>";
/// what it summarized. That one reads first: it covers history older than the newest summary and
/// everything kept after it. A `first_kept` that isn't on the path (a hand-edited or partially
/// written log) degrades to summary-plus-everything-after rather than dropping the conversation.
pub fn context_entries(entries: &[Entry]) -> Vec<&Entry> {
pub fn context_entries<E: Borrow<Entry>>(entries: &[E]) -> Vec<&Entry> {
let entries: Vec<&Entry> = entries.iter().map(Borrow::borrow).collect();
let Some(cut) = entries
.iter()
.rposition(|entry| matches!(entry.kind, crate::session::EntryKind::Compaction { .. }))
else {
return entries.iter().collect();
return entries;
};
let crate::session::EntryKind::Compaction { first_kept, .. } = &entries[cut].kind else {
return entries.iter().collect();
return entries;
};
let kept_from = entries[..cut].iter().position(|entry| entry.id == *first_kept);
@@ -45,10 +47,10 @@ pub fn context_entries(entries: &[Entry]) -> Vec<&Entry> {
// what it stands for.
let is_summary =
|entry: &&Entry| matches!(entry.kind, crate::session::EntryKind::Compaction { .. });
context.extend(kept.iter().filter(is_summary));
context.push(&entries[cut]);
context.extend(kept.iter().filter(|entry| !is_summary(entry)));
context.extend(entries[cut + 1..].iter());
context.extend(kept.iter().copied().filter(is_summary));
context.push(entries[cut]);
context.extend(kept.iter().copied().filter(|entry| !is_summary(entry)));
context.extend(entries[cut + 1..].iter().copied());
context
}
@@ -57,7 +59,7 @@ pub fn context_entries(entries: &[Entry]) -> Vec<&Entry> {
///
/// The one place a transcript becomes a request, so the cut cannot be applied in some callers and
/// forgotten in others.
pub fn context_messages(entries: &[Entry]) -> Vec<Message> {
pub fn context_messages<E: Borrow<Entry>>(entries: &[E]) -> Vec<Message> {
context_entries(entries)
.into_iter()
.filter_map(|entry| match &entry.kind {

View File

@@ -27,8 +27,8 @@ impl ContextPressure {
///
/// Prefers the provider's own figures: the char/4 estimate reads a prompt of code as about two
/// thirds of its size, and a threshold hung off it fires late.
pub fn measure(
entries: &[Entry],
pub fn measure<E: std::borrow::Borrow<Entry>>(
entries: &[E],
system: Option<&str>,
tools: &[ToolSchema],
usable_window: u64,
@@ -54,10 +54,10 @@ impl ContextPressure {
/// measurement from before the cut describes a context that no longer exists, and count only
/// single-call records, because a batched flush's summed prompt tokens are not an occupancy figure
/// of anything.
fn observed_context_peak(entries: &[Entry]) -> Option<u64> {
fn observed_context_peak<E: std::borrow::Borrow<Entry>>(entries: &[E]) -> Option<u64> {
let mut peak = None;
for entry in entries.iter().rev() {
match &entry.kind {
match &entry.borrow().kind {
crate::session::EntryKind::Compaction { .. } => break,
crate::session::EntryKind::Usage { source, totals, .. }
if *source == crate::usage::UsageSource::Agent && totals.calls == 1 =>
@@ -138,13 +138,23 @@ fn elide_tool_output_before(messages: &mut [Message], boundary: u64) {
.collect();
for (mi, bi, tokens) in stale {
if let ContentBlock::ToolResult { content, .. } = &mut messages[mi].content[bi] {
*content = vec![ToolOutput::Text(format!(
"[{tokens} tokens of earlier tool output elided to save context]"
))];
*content = elided(std::mem::take(content), tokens);
}
}
}
/// A placeholder for `content`, keeping any nested instruction file it carried.
///
/// The saved log still holds the file, so it counts as delivered and won't go again; eliding it
/// here would leave the model without those rules for the rest of the session.
fn elided(content: Vec<ToolOutput>, tokens: u64) -> Vec<ToolOutput> {
let placeholder = format!("[{tokens} tokens of earlier tool output elided to save context]");
let notes = content.into_iter().filter(|output| {
matches!(output, ToolOutput::Text(text) if crate::instructions::nested::noted(text).is_some())
});
std::iter::once(ToolOutput::Text(placeholder)).chain(notes).collect()
}
/// Every non-empty tool result in the list as `(message, block, tokens)`, oldest first.
fn tool_output_tokens(messages: &[Message]) -> impl Iterator<Item = (usize, usize, u64)> + '_ {
messages.iter().enumerate().flat_map(|(mi, msg)| {

View File

@@ -302,3 +302,38 @@ fn the_elision_boundary_moves_in_whole_steps() {
assert_eq!(boundary(1_999), 500, "and it holds there until the next whole step");
assert_eq!(boundary(2_100), 1_000);
}
/// Eliding a stale result keeps the nested instruction file it carried, and only that.
///
/// The break this catches: the file going with the rest of the result. The saved log still holds
/// it, so it counts as delivered and is never sent again, and the model loses those rules.
#[test]
fn eliding_a_result_keeps_the_nested_instructions_it_carried() {
let settings =
CompactionSettings { prune_protect_tokens: 40, prune_min_tokens: 20, ..Default::default() };
let note = crate::instructions::nested::note("web/AGENTS.md", "- WEB-RULE");
let mut messages = [tool_msg("a", 1000, false), tool_msg("b", 100, false)]
.iter()
.map(msg_of)
.collect::<Vec<_>>();
if let ContentBlock::ToolResult { content, .. } = &mut messages[0].content[0] {
content.push(ToolOutput::Text(note.clone()));
content.push(ToolOutput::Text("[instructions: looks like one, isn't".to_string()));
}
prune_tool_outputs(&mut messages, &settings, under_pressure());
let ContentBlock::ToolResult { content, .. } = &messages[0].content[0] else {
panic!("expected a tool result");
};
let texts = texts_of(content);
assert!(texts[0].contains("elided to save context"), "not elided at all");
assert_eq!(texts[1..], [note.as_str()], "the note, and nothing else, kept");
}
/// The text blocks of a tool result.
fn texts_of(content: &[ToolOutput]) -> Vec<&str> {
let texts = content.iter().filter_map(|output| match output {
ToolOutput::Text(text) => Some(text.as_str()),
_ => None,
});
texts.collect()
}

View File

@@ -126,7 +126,7 @@ pub fn serialize_for_summary(entries: &[Entry]) -> String {
}
}
crate::session::EntryKind::Compaction { summary, .. } => {
output.push_str(&format!("[Compaction]: {summary}\n"));
output.push_str(&format!("[Compaction]: {}\n", without_file_list(summary)));
}
_ => {}
}
@@ -134,6 +134,26 @@ pub fn serialize_for_summary(entries: &[Entry]) -> String {
output
}
/// A previous summary as the summarizer reads it: everything but the file list.
///
/// The list is carried forward in code ([`files_listed_in`]) and rewritten on every summary, so
/// showing it to the summarizer only invites a copy: hundreds of lines on a long session, spent from
/// the output allowance the summary itself needs, and thrown away.
fn without_file_list(summary: &str) -> String {
let mut kept = String::new();
let mut inside = false;
for line in summary.lines() {
if let Some(heading) = line.trim().strip_prefix("## ") {
inside = FILE_SECTION_ALIASES.contains(&heading.trim());
}
if !inside {
kept.push_str(line);
kept.push('\n');
}
}
kept.trim_end().to_string()
}
/// Whether an entry puts anything into [`serialize_for_summary`]'s output.
///
/// The mirror of that function's `match`, and the reason it is a predicate rather than a length
@@ -201,6 +221,23 @@ const REQUIRED_SECTIONS: [&str; 6] = [
"Critical Context",
];
/// What the summarizer is told to write.
///
/// The `## Heading` shape is named because it is what the reply is parsed by: a model told only to
/// be "structured" may answer in JSON, and every section of it is then dropped as preamble. No file
/// list is asked for, since one is added from the transcript afterward, and a model asked for one
/// copies hundreds of paths out of the allowance the summary needs. The last sentence is there
/// because a smaller model will otherwise file *these rules* under `Constraints & Preferences` as
/// though they were the session's.
pub(crate) const SUMMARIZER_PROMPT: &str = "You are a session compactor. Summarize the \
conversation segment below so the work can continue from the summary alone. Write about the \
session's own goal, constraints, progress (done, in progress, blocked), decisions, next steps, \
and anything that would be expensive to rediscover. Answer in Markdown using exactly these \
headings, one `## ` heading per section with prose under it and nothing before the first: \
`## Goal`, `## Constraints & Preferences`, `## Progress`, `## Key Decisions`, `## Next Steps`, \
`## Critical Context`. Don't list the files touched; that list is kept separately. These \
formatting rules are not part of the session: never describe them in the summary.";
/// Shape the summarizer's prose into the sections a resumed session expects, and append the file
/// record it cannot write for itself.
///

View File

@@ -137,6 +137,66 @@ fn an_earlier_compaction_summary_reaches_the_summarizer() {
assert!(serialized.starts_with("[Compaction]: ## Goal"), "{serialized}");
}
/// The summarizer is asked for every section a summary carries, and for no file list.
///
/// The break this catches: the prompt asking for `## Files` again, which spends the summary's
/// allowance on a list that's replaced anyway, or naming fewer sections than the summary is filed
/// under, which leaves the missing ones empty on every compaction.
#[test]
fn the_summarizer_is_asked_for_every_section_but_the_files() {
for section in REQUIRED_SECTIONS {
assert!(SUMMARIZER_PROMPT.contains(&format!("`## {section}`")), "{section} not asked for");
}
for files in FILE_SECTION_ALIASES {
assert!(!SUMMARIZER_PROMPT.contains(&format!("## {files}")), "{files} asked for");
}
}
fn earlier_summary(summary: &str) -> String {
serialize_for_summary(&[Entry {
id: EntryId::new(),
parent_id: None,
ts: 0,
kind: EntryKind::Compaction {
summary: summary.to_string(),
first_kept: EntryId::new(),
tokens_before: 90_000,
},
}])
}
/// The summarizer reads an earlier summary's prose but not its file list, which code carries.
///
/// The break this catches: showing the list again, which a summarizer copies out path by path,
/// hundreds of them on a long session, until the summary stops short and the compaction fails.
#[test]
fn an_earlier_summarys_file_list_is_kept_from_the_summarizer() {
let read = earlier_summary("## Goal\n\nShip it.\n\n## Files\n\n- src/listed.rs\n");
assert!(read.contains("Ship it."), "{read}");
assert!(!read.contains("src/listed.rs"), "{read}");
}
/// A section after the file list still reaches the summarizer.
///
/// The break this catches: dropping everything from the first file heading on, which loses any
/// section a summary wrote after its list.
#[test]
fn a_section_after_the_file_list_still_reaches_the_summarizer() {
let read = earlier_summary("## Files\n\n- src/listed.rs\n\n## Next Steps\n\nRun the gate.");
assert!(read.contains("Run the gate."), "{read}");
}
/// The two file headings older builds wrote are kept from the summarizer too.
///
/// The break this catches: matching only today's heading, so a session compacted by an older build
/// shows its whole list once more and copies it into the next summary.
#[test]
fn an_older_summarys_file_lists_are_kept_from_the_summarizer() {
let read =
earlier_summary("## Read Files\n\n- src/old.rs\n\n## Modified Files\n\n- src/older.rs");
assert!(!read.contains("src/old"), "{read}");
}
/// The crash this cap used to be: slicing byte 1997 of a block whose 1997th byte is the middle
/// of a character panics, in the middle of a compaction the user never asked for.
#[test]

View File

@@ -2,7 +2,7 @@
//!
//! Loads `~/.config/luxe/config.json` (global) and `<repo>/.luxe/config.json`
//! (project-local), merges them (project wins), and falls back to defaults on any
//! parse error. Unknown fields are ignored so a newer Luxe's config keeps working
//! parse error. Unknown fields are ignored so a newer luxe's config keeps working
//! with an older build and vice versa.
//!
//! The schema is published via [`Config::schema_json`] for editor autocomplete
@@ -31,7 +31,7 @@ pub use integrations::*;
use merge::{merge_color_overrides, merge_disabled};
pub use write::{value_at, ConfigLayers, ConfigWriteError, Layer};
/// The theme a launch lands on when nothing else decides: Luxe's own.
/// The theme a launch lands on when nothing else decides: luxe's own.
///
/// A default theme is the product's face, so it is the one drawn for it rather than a neutral
/// stand-in. An explicit setting and a matching desktop theme both still win.
@@ -75,9 +75,12 @@ pub struct Config {
/// use default (silent), because a modern terminal turns a bell into a window-manager attention
/// request, which pulls focus off whatever the reader walked away to do.
pub bell: Option<bool>,
/// Report the agent's state to herdr when Luxe runs in one of its panes. `None` = use default
/// Report the agent's state to herdr when luxe runs in one of its panes. `None` = use default
/// (on).
pub herdr: Option<bool>,
/// Let another front-end on this machine join a running session. `None` = use default (on).
/// Only this user can connect, and a project file can turn it off but not back on.
pub joinable: Option<bool>,
/// Statusline module order and visibility
pub statusline: StatuslineConfig,
/// Conversation canvas and tool-detail preferences
@@ -102,9 +105,9 @@ pub struct Config {
pub compaction: CompactionConfig,
/// Language-server behavior
pub lsp: LspConfig,
/// Whether Luxe checks for a newer release
/// Whether luxe checks for a newer release
pub update: UpdateConfig,
/// How Luxe keeps up with GitHub
/// How luxe keeps up with GitHub
pub github: GithubConfig,
/// Whether sessions work in worktrees of their own
pub worktree: WorktreeConfig,
@@ -134,7 +137,7 @@ impl Config {
}
}
/// Whether Luxe opens on the start screen (default: yes).
/// Whether luxe opens on the start screen (default: yes).
pub fn dashboard_shown(&self) -> bool {
!matches!(self.dashboard, Some(DashboardSetting::Enabled(false)))
}
@@ -183,14 +186,23 @@ impl Config {
self.notifications.as_ref().is_some_and(Notifications::any)
}
/// Whether the agent's state is reported to herdr when Luxe runs inside it (default: yes).
/// Whether the agent's state is reported to herdr when luxe runs inside it (default: yes).
pub fn herdr(&self) -> bool {
self.herdr.unwrap_or(true)
}
/// Whether a running session can be joined from another front-end on this machine (default:
/// yes). `LUXE_JOINABLE=0` turns it off for one launch.
pub fn joinable(&self) -> bool {
let opted_out = std::env::var("LUXE_JOINABLE").is_ok_and(|value| {
matches!(value.trim().to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off")
});
!opted_out && self.joinable.unwrap_or(true)
}
/// Resolves the active theme name, falling back to the current desktop theme when known.
///
/// An explicit Luxe setting always wins. Without one, the desktop's theme is used when the
/// An explicit luxe setting always wins. Without one, the desktop's theme is used when the
/// registry carries one (Omarchy's, see [`crate::omarchy`]), because matching the desktop beats
/// showing off, and anything else lands on [`DEFAULT_THEME`].
pub fn resolved_theme_name(&self, registry: &ThemeRegistry) -> String {
@@ -230,7 +242,7 @@ impl Config {
resolved
}
/// The JSON Schema for the config files: the checked-in `config.schema.json`, which Luxe writes
/// The JSON Schema for the config files: the checked-in `config.schema.json`, which luxe writes
/// beside the user's config so an editor can complete and check every key.
pub fn schema_json() -> &'static str {
include_str!("config/config.schema.json")
@@ -337,7 +349,7 @@ mod activity_bar_config_tests {
assert_eq!(config.theme.as_deref(), Some("nord"), "and the rest of the file still lands");
}
/// A source's kind is the one set, or its name folded; it may not take one of Luxe's own tabs',
/// A source's kind is the one set, or its name folded; it may not take one of luxe's own tabs',
/// and it needs a program to run.
#[test]
fn a_mention_source_has_a_kind_of_its_own() {

View File

@@ -1,6 +1,6 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Luxe config",
"title": "luxe config",
"type": "object",
"properties": {
"$schema": {
@@ -9,7 +9,7 @@
},
"theme": {
"type": "string",
"description": "Theme name: a built-in (luxe, catppuccin, nord, tokyo-night, and more — /theme lists them all), the name of a file in themes/, or omarchy to follow the Omarchy desktop's theme. When omitted, Luxe follows Omarchy when it is running there, and uses luxe otherwise."
"description": "Theme name: a built-in (luxe, catppuccin, nord, tokyo-night, and more — /theme lists them all), the name of a file in themes/, or omarchy to follow the Omarchy desktop's theme. When omitted, luxe follows Omarchy when it is running there, and uses luxe otherwise."
},
"colors": {
"type": "object",
@@ -54,7 +54,7 @@
"type": "string",
"enum": ["auto", "nerd", "nerd_wide", "unicode", "ascii"],
"default": "auto",
"description": "How much glyph fidelity the TUI asks for. Icons are decoration \u2014 the words beside them carry the meaning \u2014 so every setting is fully usable. nerd draws Material Design icons from a Nerd Font (the look Luxe ships with); nerd_wide draws the same icons with a second cell of clearance, for a Nerd Font's non-Mono cut, whose icons carry two cells of ink behind a one-cell advance and so paint over the space after them; unicode uses Geometric Shapes and Arrows only, so no patched font is needed; ascii reduces to plain punctuation for a minimal or non-UTF-8 terminal. auto (default) picks nerd where those glyphs can actually be drawn \u2014 kitty bundles its own symbol font, and elsewhere fontconfig is asked whether any installed font provides them \u2014 and unicode otherwise. auto never picks nerd_wide: both cuts of a face report the same advance, so there is nothing to measure."
"description": "How much glyph fidelity the TUI asks for. Icons are decoration \u2014 the words beside them carry the meaning \u2014 so every setting is fully usable. nerd draws Material Design icons from a Nerd Font (the look luxe ships with); nerd_wide draws the same icons with a second cell of clearance, for a Nerd Font's non-Mono cut, whose icons carry two cells of ink behind a one-cell advance and so paint over the space after them; unicode uses Geometric Shapes and Arrows only, so no patched font is needed; ascii reduces to plain punctuation for a minimal or non-UTF-8 terminal. auto (default) picks nerd where those glyphs can actually be drawn \u2014 kitty bundles its own symbol font, and elsewhere fontconfig is asked whether any installed font provides them \u2014 and unicode otherwise. auto never picks nerd_wide: both cuts of a face report the same advance, so there is nothing to measure."
},
"images": {
"type": "string",
@@ -108,7 +108,12 @@
"herdr": {
"type": "boolean",
"default": true,
"description": "When Luxe runs in a herdr pane, report whether it is working, idle or waiting on you, so herdr's sidebar, notifications and `herdr agent wait` follow it. On by default; nothing is sent outside herdr."
"description": "When luxe runs in a herdr pane, report whether it is working, idle or waiting on you, so herdr's sidebar, notifications and `herdr agent wait` follow it. On by default; nothing is sent outside herdr."
},
"joinable": {
"type": "boolean",
"default": true,
"description": "Let another front-end on this machine join a running session, such as `luxe join` or the `luxe remote` bridge. It goes through a socket (a named pipe on Windows) only your user account can open, and commands the agent runs are turned away. On by default; false turns it off, as does LUXE_JOINABLE=0. A project's config can turn it off but not back on."
},
"diff": {
"type": "object",
@@ -142,7 +147,7 @@
"type": "array",
"items": { "type": "string" },
"default": [],
"description": "Project-relative globs a review leaves out, e.g. [\"PROGRESS.md\", \"docs/design/**\"]. Luxe's own .luxe/ directory is always excluded and needs no entry. Supports *, ** and ?; a trailing / matches a directory and everything under it. Excluded files are counted and named in the Brief, never silently dropped."
"description": "Project-relative globs a review leaves out, e.g. [\"PROGRESS.md\", \"docs/design/**\"]. luxe's own .luxe/ directory is always excluded and needs no entry. Supports *, ** and ?; a trailing / matches a directory and everything under it. Excluded files are counted and named in the Brief, never silently dropped."
}
},
"additionalProperties": false
@@ -178,7 +183,7 @@
"remember_model": {
"type": "boolean",
"default": true,
"description": "Remember the model and thinking level picked in a session and use them next launch. Precedence: --model/--thinking flag, then LUXE_MODEL/LUXE_PROVIDER, then what you last picked, then default_model in models.json — and nothing under that, because Luxe never picks a model for you. Set false to always start from the configured default."
"description": "Remember the model and thinking level picked in a session and use them next launch. Precedence: --model/--thinking flag, then LUXE_MODEL/LUXE_PROVIDER, then what you last picked, then default_model in models.json — and nothing under that, because luxe never picks a model for you. Set false to always start from the configured default."
},
"on_ask": {
"type": "string",
@@ -190,7 +195,7 @@
"type": "string",
"enum": ["off", "streaming", "idle"],
"default": "streaming",
"description": "When Luxe keeps a conversation's prompt cache alive through a long wait, by re-sending the last request with a one-token cap just before the cache entry expires (five minutes on Anthropic, unless supports_long_cache_retention asks for an hour). A refresh is a cache read of the prompt; the write it saves is usually ten times that. streaming (the default) does it while a turn is running — a slow tool, a permission prompt, a question — where the next request is certain. idle also does it for up to 30 minutes after a turn ends, where a reply is a guess, so a refresh is sent only on a conversation large enough to make the guess pay. off never does. Either way nothing is sent unless it is expected to save at least $0.05, never on a subscription plan, and its cost shows on /cost as cache warming. A project's config may turn this down and may not turn it up."
"description": "When luxe keeps a conversation's prompt cache alive through a long wait, by re-sending the last request with a one-token cap just before the cache entry expires (five minutes on Anthropic, unless supports_long_cache_retention asks for an hour). A refresh is a cache read of the prompt; the write it saves is usually ten times that. streaming (the default) does it while a turn is running — a slow tool, a permission prompt, a question — where the next request is certain. idle also does it for up to 30 minutes after a turn ends, where a reply is a guess, so a refresh is sent only on a conversation large enough to make the guess pay. off never does. Either way nothing is sent unless it is expected to save at least $0.05, never on a subscription plan, and its cost shows on /cost as cache warming. A project's config may turn this down and may not turn it up."
},
"default_mode": {
"type": "string",
@@ -284,7 +289,7 @@
},
"launchers": {
"type": "array",
"description": "Programs a key hands the terminal to — gh-dash, lazygit, anything that takes over a terminal and gives it back. Luxe keeps running underneath, a turn included, and redraws when the program exits; text the program writes to the file named by $LUXE_HANDOFF lands in the composer. Read from the global config only: a key that runs a program a repository named is arbitrary execution.",
"description": "Programs a key hands the terminal to — gh-dash, lazygit, anything that takes over a terminal and gives it back. luxe keeps running underneath, a turn included, and redraws when the program exits; text the program writes to the file named by $LUXE_HANDOFF lands in the composer. Read from the global config only: a key that runs a program a repository named is arbitrary execution.",
"items": {
"type": "object",
"properties": {
@@ -314,7 +319,7 @@
},
"github": {
"type": "object",
"description": "How Luxe keeps up with GitHub: the checked-out branch's pull request, and what /github lists. The refresh interval is read from the global config only — how often Luxe calls out on a timer is not a decision a repository you cloned makes; a project may add its own /github sections.",
"description": "How luxe keeps up with GitHub: the checked-out branch's pull request, and what /github lists. The refresh interval is read from the global config only — how often luxe calls out on a timer is not a decision a repository you cloned makes; a project may add its own /github sections.",
"properties": {
"refresh_secs": {
"type": "integer",
@@ -340,12 +345,12 @@
},
"update": {
"type": "object",
"description": "Whether Luxe checks for a newer release. Read from the global config only — whether Luxe reaches the network on your behalf is not a decision a repository you cloned makes.",
"description": "Whether luxe checks for a newer release. Read from the global config only — whether luxe reaches the network on your behalf is not a decision a repository you cloned makes.",
"properties": {
"check": {
"type": "boolean",
"default": true,
"description": "Look for a newer release, at most once a day, and mention it under the dashboard's footer. Luxe never updates itself; the notice names the command that matches how you installed it. The request sends nothing about you — no version, no platform, no identifier — and every failure is silent. Set false, or LUXE_UPDATE_CHECK=0, to turn it off."
"description": "Look for a newer release, at most once a day, and mention it under the dashboard's footer. luxe never updates itself; the notice names the command that matches how you installed it. The request sends nothing about you — no version, no platform, no identifier — and every failure is silent. Set false, or LUXE_UPDATE_CHECK=0, to turn it off."
}
},
"additionalProperties": false

View File

@@ -283,7 +283,7 @@ pub enum NotificationMethod {
/// The moments that send a desktop notification: all of them, none, or a list.
///
/// Read leniently, like every other key: a value that is neither a boolean nor a list is treated as
/// unset and a name Luxe does not know is skipped, so one typo never takes the whole config with it.
/// unset and a name luxe does not know is skipped, so one typo never takes the whole config with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum Notifications {

View File

@@ -3,7 +3,7 @@
use super::{known_or, Lenient};
use serde::{Deserialize, Serialize};
/// How a diff is drawn, wherever Luxe draws one.
/// How a diff is drawn, wherever luxe draws one.
///
/// One setting for three surfaces — the `edit`/`write` tool card, the peeked file beside the
/// conversation, and Guided Review. They differ only in how much room they have, and

Some files were not shown because too many files have changed in this diff Show More