Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ed87ee4e4 | ||
|
|
933c1195b4 | ||
|
|
7b460ab9c7 | ||
|
|
6501c5ed37 | ||
|
|
ab743ed98f | ||
|
|
c53b394bef | ||
|
|
f014ead3b9 |
18
CHANGELOG.md
18
CHANGELOG.md
@@ -9,6 +9,24 @@ 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.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.
|
||||
|
||||
@@ -16,6 +16,20 @@ option. Unless you explicitly state otherwise, any contribution intentionally su
|
||||
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
|
||||
|
||||
17
Cargo.lock
generated
17
Cargo.lock
generated
@@ -1626,7 +1626,7 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "luxe-cli"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -1656,7 +1656,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-core"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base16ct",
|
||||
@@ -1687,7 +1687,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-dap"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"luxe-core",
|
||||
@@ -1701,7 +1701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-lsp"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base16ct",
|
||||
@@ -1725,7 +1725,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-mcp"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -1745,7 +1745,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-providers"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64",
|
||||
@@ -1764,7 +1764,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-tools"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -1789,7 +1789,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-tui"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
@@ -1797,6 +1797,7 @@ dependencies = [
|
||||
"base64",
|
||||
"crossterm",
|
||||
"futures",
|
||||
"gif",
|
||||
"image",
|
||||
"luxe-core",
|
||||
"luxe-tui",
|
||||
|
||||
@@ -6,7 +6,7 @@ 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.1"
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/evanwhittaker/luxe"
|
||||
|
||||
19
README.md
19
README.md
@@ -1,4 +1,9 @@
|
||||
<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
|
||||
you choose, then reads back what it changed as a Guided Review, so you can comment, ask for fixes,
|
||||
@@ -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:
|
||||
@@ -156,6 +161,10 @@ 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 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.
|
||||
|
||||
|
||||
@@ -18,13 +18,13 @@ 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.1" }
|
||||
luxe-providers = { path = "../luxe-providers", version = "0.1.1" }
|
||||
luxe-tools = { path = "../luxe-tools", version = "0.1.1" }
|
||||
luxe-lsp = { path = "../luxe-lsp", version = "0.1.1" }
|
||||
luxe-dap = { path = "../luxe-dap", version = "0.1.1" }
|
||||
luxe-mcp = { path = "../luxe-mcp", version = "0.1.1" }
|
||||
luxe-tui = { path = "../luxe-tui", version = "0.1.1" }
|
||||
anyhow = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
shlex = { workspace = true }
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -2136,14 +2136,12 @@ On macOS and Linux, the install script puts `luxe` in `~/.local/bin`, or in `$LU
|
||||
when it is set, and adds that to your `PATH`:
|
||||
|
||||
```bash
|
||||
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
|
||||
```
|
||||
|
||||
On Windows, in PowerShell:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -c "irm https://github.com/evanwhittaker/luxe/releases/latest/download/luxe-cli-installer.ps1 | iex"
|
||||
```
|
||||
That address redirects to the script on the [latest
|
||||
release](https://github.com/evanwhittaker/luxe/releases/latest), the one it built and attested. To
|
||||
read it before running it, drop the `| sh`.
|
||||
|
||||
With Homebrew, on macOS or Linux:
|
||||
|
||||
@@ -2158,6 +2156,16 @@ one):
|
||||
cargo install --locked luxe-cli
|
||||
```
|
||||
|
||||
On Windows, in PowerShell:
|
||||
|
||||
```powershell
|
||||
powershell -c "irm https://luxe.dev/install.ps1 | iex"
|
||||
```
|
||||
|
||||
[That script](https://luxe.dev/install.ps1) is two lines: it lets this PowerShell window run the
|
||||
release's installer, which Windows' default execution policy would stop, then runs it. Nothing
|
||||
about your policy is saved.
|
||||
|
||||
Any of them installs the `luxe` command; `luxe --version` checks it worked.
|
||||
|
||||
To update, run `luxe update`, or `/update` inside Luxe. Luxe checks once a day for a newer release
|
||||
@@ -4544,7 +4552,7 @@ group: "Using Luxe"
|
||||
| `write`, `edit` | Write or change a file. A file must be read before it is edited, and the card shows the diff, after [formatting](#format-on-save). |
|
||||
| `bash` | Run a shell command. Long output is trimmed, and the untouched output saved under `.luxe/artifacts/`: each stream whole up to 8 MB, or its first and last 4 MB past that. |
|
||||
| `test` | Run the project's tests and report each failure with its `file:line`, and which tests your change broke. Output is saved as `bash`'s is. |
|
||||
| `grep`, `glob` | Search file contents and names, with capped output |
|
||||
| `grep`, `glob` | Search file contents and names, with capped output. `grep` names each file once with its matching lines under it, and can say which function or type each match sits in. |
|
||||
| `ast_grep` | Search and replace by code structure. Needs [ast-grep](https://ast-grep.github.io). |
|
||||
| `git` | Status, diffs, history, commits, branches, and GitHub pull requests, issues and CI checks through `gh` |
|
||||
| `todo` | The agent's checklist, shown in the dock's **PLAN** |
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
|
||||
@@ -391,7 +391,7 @@ async fn run_via_stdin(spec: &FormatterSpec, path: &Path) -> Result<(), Formatte
|
||||
if std::fs::read(&path)? != input {
|
||||
return Ok(false);
|
||||
}
|
||||
crate::fs_atomic::replace(&path, &formatted).map(|()| true)
|
||||
crate::fs_atomic::replace_keeping_mode(&path, &formatted).map(|()| true)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io(spec, "write the file")(std::io::Error::other(error)))?
|
||||
|
||||
@@ -62,6 +62,15 @@ pub fn replace_preserving_mode(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
replace_with_mode(path, bytes, existing_mode(path))
|
||||
}
|
||||
|
||||
/// Replace `path` with `bytes` as an editor saves a file: one that exists keeps its mode, an
|
||||
/// executable script included, and a new one gets the platform's default.
|
||||
///
|
||||
/// For the user's own files, which the edit and write tools and the formatter rewrite. A rename
|
||||
/// puts a new file in the old one's place, so a mode not carried over is the new file's default.
|
||||
pub fn replace_keeping_mode(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_then_rename(path, bytes, existing_mode(path))
|
||||
}
|
||||
|
||||
/// Replace `path` with `bytes` atomically but without syncing: a reader never sees half of it, and
|
||||
/// a power cut may lose it.
|
||||
///
|
||||
@@ -214,10 +223,18 @@ fn open_staging(path: &Path, mode: Option<u32>) -> io::Result<File> {
|
||||
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
// At creation too, so an owner-only file is never readable even for an instant
|
||||
if let Some(mode) = mode {
|
||||
options.mode(mode);
|
||||
}
|
||||
options.open(path)
|
||||
let file = options.open(path)?;
|
||||
// A mode given at creation is filtered through the umask; set it again so the file ends up
|
||||
// with exactly the mode asked for, a kept group-writable one included
|
||||
if let Some(mode) = mode {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
file.set_permissions(fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
@@ -252,125 +269,4 @@ fn restrict_dir(_path: &Path) -> io::Result<()> {
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An unsynced replace still lands whole and leaves no staging file behind.
|
||||
#[test]
|
||||
fn an_unsynced_replace_lands_whole_and_leaves_nothing_behind() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let target = dir.path().join("cache").join("shard.json");
|
||||
replace_unsynced(&target, b"first").unwrap();
|
||||
replace_unsynced(&target, b"second").unwrap();
|
||||
assert_eq!(fs::read(&target).unwrap(), b"second");
|
||||
let left: Vec<_> = fs::read_dir(target.parent().unwrap()).unwrap().flatten().collect();
|
||||
assert_eq!(left.len(), 1, "only the shard: {left:?}");
|
||||
}
|
||||
|
||||
/// Every directory `create_private_dir` makes is owner-only, not just the last one; one that was
|
||||
/// already there keeps its mode.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn every_directory_created_is_private() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let leaf = dir.path().join("a").join("b").join("c");
|
||||
create_private_dir(&leaf).unwrap();
|
||||
for created in [dir.path().join("a"), dir.path().join("a/b"), leaf] {
|
||||
assert_eq!(mode(&created), 0o700, "{}", created.display());
|
||||
}
|
||||
assert_eq!(mode(dir.path()), 0o755, "an existing parent is left alone");
|
||||
}
|
||||
|
||||
/// A fresh private directory refuses to adopt one that exists.
|
||||
#[test]
|
||||
fn a_new_private_directory_is_never_an_existing_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fresh = dir.path().join("fresh");
|
||||
create_private_dir_new(&fresh).unwrap();
|
||||
let error = create_private_dir_new(&fresh).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replacement_lands_and_leaves_no_staging_file_behind() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("state.json");
|
||||
replace(&path, b"first").unwrap();
|
||||
replace(&path, b"second").unwrap();
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"second");
|
||||
let strays: Vec<_> = fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||
.filter(|name| name != "state.json")
|
||||
.collect();
|
||||
assert!(strays.is_empty(), "left behind: {strays:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_parents_are_created() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("a").join("b").join("c.json");
|
||||
replace(&path, b"{}").unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"{}");
|
||||
}
|
||||
|
||||
/// The staging name has to survive a real extension, or `main.rs` and `main.md` stage to the
|
||||
/// same file and the last writer wins a race nobody knew they were in.
|
||||
#[test]
|
||||
fn two_files_sharing_a_stem_do_not_share_a_staging_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let rust = staging_path(&dir.path().join("main.rs"));
|
||||
let markdown = staging_path(&dir.path().join("main.md"));
|
||||
assert_ne!(rust, markdown);
|
||||
assert_eq!(rust.parent(), Some(dir.path()), "staging stays on the target's filesystem");
|
||||
}
|
||||
|
||||
/// Two writers of the *same* file must not collide on the staging name either — one would
|
||||
/// truncate the other's half-written bytes and then rename them into place.
|
||||
#[test]
|
||||
fn concurrent_writers_of_one_file_get_distinct_staging_names() {
|
||||
let path = Path::new("/tmp/luxe/thing.json");
|
||||
assert_ne!(staging_path(path), staging_path(path));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_private_replacement_is_owner_only_from_the_moment_it_exists() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("auth.json");
|
||||
replace_private(&path, b"secret").unwrap();
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
|
||||
let nested = dir.path().join("private");
|
||||
create_private_dir(&nested).unwrap();
|
||||
assert_eq!(fs::metadata(&nested).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
}
|
||||
|
||||
/// A failed write must not leave a stray staging file, and must not damage what was there.
|
||||
#[test]
|
||||
fn a_failure_leaves_the_previous_contents_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("kept.json");
|
||||
replace(&path, b"original").unwrap();
|
||||
|
||||
// A directory in the target's place: the rename cannot succeed.
|
||||
let blocked = dir.path().join("blocked.json");
|
||||
fs::create_dir(&blocked).unwrap();
|
||||
assert!(replace(&blocked, b"nope").is_err());
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"original");
|
||||
let strays: Vec<_> = fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||
.filter(|name| name.ends_with(".tmp"))
|
||||
.collect();
|
||||
assert!(strays.is_empty(), "left behind: {strays:?}");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
167
crates/luxe-core/src/fs_atomic/tests.rs
Normal file
167
crates/luxe-core/src/fs_atomic/tests.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn mode_of(path: &Path) -> u32 {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::metadata(path).unwrap().permissions().mode() & 0o777
|
||||
}
|
||||
|
||||
/// Editing a script keeps it a script. The rename puts a new file where the old one was, so a
|
||||
/// mode not carried over is lost: every edit of an executable left it unrunnable.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replace_keeping_mode_leaves_a_script_executable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = dir.path().join("run.sh");
|
||||
fs::write(&script, b"#!/bin/sh\n").unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
replace_keeping_mode(&script, b"#!/bin/sh\necho hi\n").unwrap();
|
||||
assert_eq!(mode_of(&script), 0o755);
|
||||
assert_eq!(fs::read(&script).unwrap(), b"#!/bin/sh\necho hi\n");
|
||||
}
|
||||
|
||||
/// The mode kept is the mode the file had, bit for bit, not one the umask trimmed on the way.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_kept_mode_is_exact_whatever_the_umask() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let shared = dir.path().join("shared");
|
||||
fs::write(&shared, b"a").unwrap();
|
||||
// World-writable on purpose: any umask that is not 000 strips at least one of these bits
|
||||
fs::set_permissions(&shared, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
replace_keeping_mode(&shared, b"b").unwrap();
|
||||
assert_eq!(mode_of(&shared), 0o777);
|
||||
}
|
||||
|
||||
/// A file that did not exist gets the mode any new file would, not the owner-only one secrets get.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_new_file_kept_mode_gets_the_ordinary_default() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ordinary = dir.path().join("ordinary");
|
||||
File::create(&ordinary).unwrap();
|
||||
let fresh = dir.path().join("fresh");
|
||||
replace_keeping_mode(&fresh, b"new").unwrap();
|
||||
assert_eq!(mode_of(&fresh), mode_of(&ordinary));
|
||||
}
|
||||
|
||||
/// An unsynced replace still lands whole and leaves no staging file behind.
|
||||
#[test]
|
||||
fn an_unsynced_replace_lands_whole_and_leaves_nothing_behind() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let target = dir.path().join("cache").join("shard.json");
|
||||
replace_unsynced(&target, b"first").unwrap();
|
||||
replace_unsynced(&target, b"second").unwrap();
|
||||
assert_eq!(fs::read(&target).unwrap(), b"second");
|
||||
let left: Vec<_> = fs::read_dir(target.parent().unwrap()).unwrap().flatten().collect();
|
||||
assert_eq!(left.len(), 1, "only the shard: {left:?}");
|
||||
}
|
||||
|
||||
/// Every directory `create_private_dir` makes is owner-only, not just the last one; one that was
|
||||
/// already there keeps its mode.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn every_directory_created_is_private() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let leaf = dir.path().join("a").join("b").join("c");
|
||||
create_private_dir(&leaf).unwrap();
|
||||
for created in [dir.path().join("a"), dir.path().join("a/b"), leaf] {
|
||||
assert_eq!(mode(&created), 0o700, "{}", created.display());
|
||||
}
|
||||
assert_eq!(mode(dir.path()), 0o755, "an existing parent is left alone");
|
||||
}
|
||||
|
||||
/// A fresh private directory refuses to adopt one that exists.
|
||||
#[test]
|
||||
fn a_new_private_directory_is_never_an_existing_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fresh = dir.path().join("fresh");
|
||||
create_private_dir_new(&fresh).unwrap();
|
||||
let error = create_private_dir_new(&fresh).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replacement_lands_and_leaves_no_staging_file_behind() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("state.json");
|
||||
replace(&path, b"first").unwrap();
|
||||
replace(&path, b"second").unwrap();
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"second");
|
||||
let strays: Vec<_> = fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||
.filter(|name| name != "state.json")
|
||||
.collect();
|
||||
assert!(strays.is_empty(), "left behind: {strays:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_parents_are_created() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("a").join("b").join("c.json");
|
||||
replace(&path, b"{}").unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"{}");
|
||||
}
|
||||
|
||||
/// The staging name has to survive a real extension, or `main.rs` and `main.md` stage to the
|
||||
/// same file and the last writer wins a race nobody knew they were in.
|
||||
#[test]
|
||||
fn two_files_sharing_a_stem_do_not_share_a_staging_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let rust = staging_path(&dir.path().join("main.rs"));
|
||||
let markdown = staging_path(&dir.path().join("main.md"));
|
||||
assert_ne!(rust, markdown);
|
||||
assert_eq!(rust.parent(), Some(dir.path()), "staging stays on the target's filesystem");
|
||||
}
|
||||
|
||||
/// Two writers of the *same* file must not collide on the staging name either — one would
|
||||
/// truncate the other's half-written bytes and then rename them into place.
|
||||
#[test]
|
||||
fn concurrent_writers_of_one_file_get_distinct_staging_names() {
|
||||
let path = Path::new("/tmp/luxe/thing.json");
|
||||
assert_ne!(staging_path(path), staging_path(path));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_private_replacement_is_owner_only_from_the_moment_it_exists() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("auth.json");
|
||||
replace_private(&path, b"secret").unwrap();
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
|
||||
let nested = dir.path().join("private");
|
||||
create_private_dir(&nested).unwrap();
|
||||
assert_eq!(fs::metadata(&nested).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
}
|
||||
|
||||
/// A failed write must not leave a stray staging file, and must not damage what was there.
|
||||
#[test]
|
||||
fn a_failure_leaves_the_previous_contents_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("kept.json");
|
||||
replace(&path, b"original").unwrap();
|
||||
|
||||
// A directory in the target's place: the rename cannot succeed.
|
||||
let blocked = dir.path().join("blocked.json");
|
||||
fs::create_dir(&blocked).unwrap();
|
||||
assert!(replace(&blocked, b"nope").is_err());
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"original");
|
||||
let strays: Vec<_> = fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||
.filter(|name| name.ends_with(".tmp"))
|
||||
.collect();
|
||||
assert!(strays.is_empty(), "left behind: {strays:?}");
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
mod standards;
|
||||
|
||||
pub use standards::{FunctionSize, OutlineSource};
|
||||
pub use standards::{FunctionSize, OutlineSource, Scope};
|
||||
|
||||
use crate::formatter::FormatterRegistry;
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
|
||||
@@ -20,6 +20,24 @@ const MAX_NAMED: usize = 5;
|
||||
pub trait OutlineSource: Send + Sync {
|
||||
/// The functions and methods in `source`, or `None` for a language it cannot parse.
|
||||
fn functions(&self, path: &Path, source: &str) -> Option<Vec<FunctionSize>>;
|
||||
|
||||
/// The named scopes in `source` that can hold code: functions, methods, types and modules,
|
||||
/// not fields or constants. `None` for a language it cannot parse, which is also the default.
|
||||
/// A search labels what it found with the scopes around it.
|
||||
fn scopes(&self, _path: &Path, _source: &str) -> Option<Vec<Scope>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// One named scope and the lines it spans, 0-based and inclusive.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Scope {
|
||||
/// The bare name, `delete` or `QuerySet`
|
||||
pub name: String,
|
||||
/// Its first line, where its declaration starts
|
||||
pub start_line: usize,
|
||||
/// Its last line
|
||||
pub end_line: usize,
|
||||
}
|
||||
|
||||
/// One function's name, qualified by its container where it has one, and its length.
|
||||
|
||||
@@ -225,7 +225,9 @@ const PATTERNS: [(&str, &str, SecretConfidence, &str); 11] = [
|
||||
r"AIza[0-9A-Za-z_\-]{35}",
|
||||
"[REDACTED_GOOGLE_KEY]",
|
||||
SecretConfidence::Format,
|
||||
"AIzaabcdefghijklmnopqrstuvwxyz012345678",
|
||||
// Joined at compile time so the source holds no key-shaped run: a Google key has no
|
||||
// checksum, so secret scanners flag any literal of its shape, invented ones included
|
||||
concat!("AIza", "abcdefghijklmnopqrstuvwxyz012345678"),
|
||||
),
|
||||
(
|
||||
r"(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{10,}",
|
||||
|
||||
@@ -11,7 +11,7 @@ homepage.workspace = true
|
||||
# Provides a native Debug Adapter Protocol client + the `debug` tool.
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -11,7 +11,7 @@ homepage.workspace = true
|
||||
# Provides a generic LSP client (rust-analyzer first).
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -247,6 +247,17 @@ fn symbol_kind(def_kind: &str, container_kind: Option<&str>) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds that can hold code, and so name where a line sits: not fields, variants or constants.
|
||||
const SCOPE_KINDS: [u32; 7] = [
|
||||
kinds::FUNCTION,
|
||||
kinds::METHOD,
|
||||
kinds::CLASS,
|
||||
kinds::STRUCT,
|
||||
kinds::ENUM,
|
||||
kinds::INTERFACE,
|
||||
kinds::MODULE,
|
||||
];
|
||||
|
||||
/// Function lengths for the size standards the edit hook holds, from the same outline
|
||||
/// `module_report` draws.
|
||||
pub struct SyntaxOutline;
|
||||
@@ -272,6 +283,25 @@ impl luxe_core::hooks::file_changed::OutlineSource for SyntaxOutline {
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn scopes(
|
||||
&self,
|
||||
path: &Path,
|
||||
source: &str,
|
||||
) -> Option<Vec<luxe_core::hooks::file_changed::Scope>> {
|
||||
let symbols = outline(path, source)?;
|
||||
Some(
|
||||
symbols
|
||||
.into_iter()
|
||||
.filter(|symbol| SCOPE_KINDS.contains(&symbol.kind))
|
||||
.map(|symbol| luxe_core::hooks::file_changed::Scope {
|
||||
name: symbol.name,
|
||||
start_line: symbol.start_line as usize,
|
||||
end_line: symbol.end_line as usize,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -337,6 +367,19 @@ mod tests {
|
||||
assert_eq!(method.kind, kinds::METHOD);
|
||||
}
|
||||
|
||||
/// The scopes a search labels with are the ones that hold code, with the lines they span: a
|
||||
/// class and its method, not the attribute beside them.
|
||||
#[test]
|
||||
fn scopes_are_the_code_holding_symbols_and_their_spans() {
|
||||
use luxe_core::hooks::file_changed::{OutlineSource, Scope};
|
||||
let src = "class QuerySet:\n model = None\n\n def delete(self):\n return 1\n";
|
||||
let scopes = SyntaxOutline.scopes(Path::new("query.py"), src).expect("python parses");
|
||||
let scope =
|
||||
|name: &str, start_line, end_line| Scope { name: name.into(), start_line, end_line };
|
||||
assert_eq!(scopes, vec![scope("QuerySet", 0, 4), scope("delete", 3, 4)]);
|
||||
assert_eq!(SyntaxOutline.scopes(Path::new("notes.md"), "# hi"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_language_returns_none() {
|
||||
assert!(outline(Path::new("notes.md"), "# hi").is_none());
|
||||
|
||||
@@ -13,7 +13,7 @@ homepage.workspace = true
|
||||
# no-HTTP rule forbids in core itself. The low-level stdio transport stays in luxe-core.
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -11,7 +11,7 @@ homepage.workspace = true
|
||||
# Provides LLM provider adapters (OpenAI-compat, Anthropic, Gemini).
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -11,7 +11,7 @@ homepage.workspace = true
|
||||
# Provides tool implementations (read, write, edit, bash, grep, glob, etc.).
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -442,10 +442,18 @@ mod tree_teardown {
|
||||
format!("(for _ in $(seq 1 40); do touch {}; sleep 0.25; done) & wait", marker.display())
|
||||
}
|
||||
|
||||
/// Whether anything is still touching `marker` after it is removed.
|
||||
/// Whether anything is still touching `marker`, the loop, once a touch that was already under
|
||||
/// way has had its moment.
|
||||
///
|
||||
/// The kill reaches the whole group at once, but a `touch` forked as it lands can finish one
|
||||
/// write after it, and on macOS's slower teardown that write can follow the first clear. One
|
||||
/// straggling write is not a survivor; a loop still running touches again within a quarter
|
||||
/// second of the second clear.
|
||||
async fn survivor_still_running(marker: &std::path::Path) -> bool {
|
||||
let _ = std::fs::remove_file(marker);
|
||||
tokio::time::sleep(Duration::from_millis(1_200)).await;
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let _ = std::fs::remove_file(marker);
|
||||
tokio::time::sleep(Duration::from_millis(1_000)).await;
|
||||
marker.exists()
|
||||
}
|
||||
|
||||
|
||||
@@ -428,7 +428,9 @@ impl Tool for EditTool {
|
||||
let diff = crate::diff_preview::ranges_diff(&content, &preview);
|
||||
let result = apply(&content, &planned);
|
||||
|
||||
if let Err(problem) = luxe_core::fs_atomic::replace(&full_path, result.as_bytes()) {
|
||||
if let Err(problem) =
|
||||
luxe_core::fs_atomic::replace_keeping_mode(&full_path, result.as_bytes())
|
||||
{
|
||||
warn!(path = %full_path.display(), error = %problem, "failed to write edited file");
|
||||
return ToolResultData::error(format!(
|
||||
"Error writing file '{}': {problem}",
|
||||
|
||||
@@ -78,6 +78,23 @@ async fn a_reformatted_edit_shows_the_file_as_it_is_now() {
|
||||
assert!(text.contains("+1 fn b() {}"), "{text}");
|
||||
}
|
||||
|
||||
/// An edited script stays executable. Saving by rename replaced the file with a new one at the
|
||||
/// default mode, so every edit of a script left it unrunnable.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_edited_script_stays_executable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = dir.path().join("run.sh");
|
||||
std::fs::write(&script, "#!/bin/sh\necho one\n").unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let args = json!({"path": "run.sh", "edits": [{"oldText": "one", "newText": "two"}]});
|
||||
let result = EditTool::new().run(args, &test_context(dir.path())).await;
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
let mode = std::fs::metadata(&script).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o755, "still executable after the edit");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edit_tool_basic() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
|
||||
@@ -4,16 +4,21 @@
|
||||
//! it is opened, and the approved files are scanned in parallel with `regex`. An external `rg`
|
||||
//! could not do the middle step, which is the one that keeps denied content out of the answer.
|
||||
//!
|
||||
//! The result is bounded `file:line:text`, with optional context lines and a glob filter — or,
|
||||
//! where the question is coarser than the lines, the files that match or a count per file.
|
||||
//! The rows are bounded `file:line:text`, with optional context lines and a glob filter — or,
|
||||
//! where the question is coarser than the lines, the files that match or a count per file. Lines
|
||||
//! reach the model grouped under their file: the path once rather than on every line. Asked to
|
||||
//! (`scopes`), each run of matches is labeled with the function or type around it, where an
|
||||
//! outline can say, so where a match sits needs no read to find out.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::hooks::file_changed::{OutlineSource, Scope};
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tracing::warn;
|
||||
|
||||
mod guarded;
|
||||
mod present;
|
||||
#[cfg(test)]
|
||||
mod read_policy_tests;
|
||||
|
||||
@@ -21,7 +26,9 @@ mod read_policy_tests;
|
||||
fn grep_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "grep".to_string(),
|
||||
description: "Search file *contents* by regex. Returns `file:line:text`, bounded \
|
||||
description: "Search file *contents* by regex. Returns each matching file's path once \
|
||||
with its `line:text` rows under it; `scopes: true` also names the function \
|
||||
or type around each match, as `[QuerySet › delete]`. Bounded \
|
||||
— a broad pattern says it was capped instead of flooding your context. Case \
|
||||
is sensitive unless the pattern says otherwise: prefix `(?i)`. Skips ignored \
|
||||
paths (`.gitignore`, `.git/`, build output); set `all: true` to include \
|
||||
@@ -50,7 +57,7 @@ fn grep_schema() -> ToolSchema {
|
||||
"outputMode": {
|
||||
"type": "string",
|
||||
"enum": ["content", "files", "count"],
|
||||
"description": "What to return: 'content' (file:line:text, the default), \
|
||||
"description": "What to return: 'content' (matching lines under each file, the default), \
|
||||
'files' (one path per matching file), or 'count' (file:count \
|
||||
of matching lines). Prefer 'files' when you only need to know \
|
||||
where to look."
|
||||
@@ -76,6 +83,13 @@ fn grep_schema() -> ToolSchema {
|
||||
"type": "boolean",
|
||||
"description": "Return the lines that do NOT match the pattern. Default false."
|
||||
},
|
||||
"scopes": {
|
||||
"type": "boolean",
|
||||
"description": "Name the function or type each match sits in, for code a \
|
||||
parser reads. Costs a row per change of scope; worth it \
|
||||
when *where* a match is matters, as for call sites. \
|
||||
Default false."
|
||||
},
|
||||
"all": {
|
||||
"type": "boolean",
|
||||
"description": "Include ignored files (build output, vendored deps). Default false."
|
||||
@@ -148,6 +162,44 @@ impl OutputMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// One row a search found, kept whole until the answer is laid out.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Hit {
|
||||
/// The file, relative to where the search ran
|
||||
file: std::sync::Arc<str>,
|
||||
kind: HitKind,
|
||||
/// 1-based line, for a match or a context row
|
||||
line: usize,
|
||||
/// The line itself, or the number of matching lines for [`HitKind::Count`]
|
||||
text: String,
|
||||
/// The scopes around a match, outermost first, `QuerySet › delete`, where an outline can say
|
||||
scope: Option<String>,
|
||||
}
|
||||
|
||||
/// What a [`Hit`] is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum HitKind {
|
||||
Match,
|
||||
Context,
|
||||
/// A file with a match, in the files mode
|
||||
File,
|
||||
/// A file's number of matching lines, in the count mode
|
||||
Count,
|
||||
}
|
||||
|
||||
impl Hit {
|
||||
/// The row as ripgrep prints it, which the caps measure: `file:line:text`, `file-line-text`
|
||||
/// for context, a bare path, or `file:count`.
|
||||
fn flat(&self) -> String {
|
||||
match self.kind {
|
||||
HitKind::Match => format!("{}:{}:{}", self.file, self.line, self.text),
|
||||
HitKind::Context => format!("{}-{}-{}", self.file, self.line, self.text),
|
||||
HitKind::File => self.file.to_string(),
|
||||
HitKind::Count => format!("{}:{}", self.file, self.text),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One parsed search.
|
||||
///
|
||||
/// `limit` is deliberately *not* consulted while searching. Stopping early would make the total the
|
||||
@@ -162,17 +214,22 @@ struct Search<'a> {
|
||||
after: usize,
|
||||
all: bool,
|
||||
invert: bool,
|
||||
/// Label each match with the scopes around it, where an outline can read the file
|
||||
scopes: bool,
|
||||
mode: OutputMode,
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
/// What `search` finds under `cwd`, unguarded, as the tests ask it.
|
||||
/// What `search` finds under `cwd`, unguarded and as ripgrep would print it, as the tests ask it.
|
||||
#[cfg(test)]
|
||||
fn native_search(cwd: &Path, search: &Search<'_>) -> Result<Vec<String>, String> {
|
||||
native_search_files(cwd, search, crate::walk::files(cwd, search.path, search.all), || false)
|
||||
let paths = crate::walk::files(cwd, search.path, search.all);
|
||||
let hits = native_search_files(cwd, search, paths, None, || false)?;
|
||||
Ok(hits.iter().map(Hit::flat).collect())
|
||||
}
|
||||
|
||||
/// Scans `paths` (relative to `cwd`) for `search`, in parallel, rows in path order.
|
||||
/// Scans `paths` (relative to `cwd`) for `search`, in parallel, rows in path order, each match
|
||||
/// labeled with its scopes where `outline` can parse the file.
|
||||
///
|
||||
/// Each worker takes a contiguous run of the sorted paths and the runs are joined in order, so the
|
||||
/// answer reads the same however many threads produced it. `stopped` is checked between files.
|
||||
@@ -180,8 +237,9 @@ fn native_search_files(
|
||||
cwd: &Path,
|
||||
search: &Search<'_>,
|
||||
paths: Vec<PathBuf>,
|
||||
outline: Option<&dyn OutlineSource>,
|
||||
stopped: impl Fn() -> bool + Sync,
|
||||
) -> Result<Vec<String>, String> {
|
||||
) -> Result<Vec<Hit>, String> {
|
||||
let regex = regex::Regex::new(search.pattern)
|
||||
.map_err(|error| format!("'{}' is not a valid regex: {error}", search.pattern))?;
|
||||
let prefilter = prefilter(search);
|
||||
@@ -199,7 +257,7 @@ fn native_search_files(
|
||||
let workers = std::thread::available_parallelism().map_or(1, usize::from).min(16);
|
||||
let run = paths.len().div_ceil(workers).max(1);
|
||||
// a worker is `Err` when it panicked, `Ok(None)` when it was stopped
|
||||
let scanned: Vec<std::thread::Result<Option<Vec<String>>>> = std::thread::scope(|scope| {
|
||||
let scanned: Vec<std::thread::Result<Option<Vec<Hit>>>> = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = paths
|
||||
.chunks(run)
|
||||
.map(|chunk| {
|
||||
@@ -210,7 +268,8 @@ fn native_search_files(
|
||||
if stopped() {
|
||||
return None;
|
||||
}
|
||||
rows.extend(search_file(cwd, relative, (regex, prefilter), search));
|
||||
let matcher = (regex, prefilter);
|
||||
rows.extend(search_file(cwd, relative, matcher, search, outline));
|
||||
}
|
||||
Some(rows)
|
||||
})
|
||||
@@ -223,9 +282,9 @@ fn native_search_files(
|
||||
|
||||
/// The workers' rows joined in order; a crashed worker is a failure, a stopped one a cancel.
|
||||
fn combine(
|
||||
scanned: Vec<std::thread::Result<Option<Vec<String>>>>,
|
||||
scanned: Vec<std::thread::Result<Option<Vec<Hit>>>>,
|
||||
stopped: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
) -> Result<Vec<Hit>, String> {
|
||||
if scanned.iter().any(Result::is_err) {
|
||||
return Err("a search worker failed; nothing it scanned is reported".into());
|
||||
}
|
||||
@@ -269,14 +328,15 @@ fn has_lone_carriage_return(text: &str) -> bool {
|
||||
bytes.iter().enumerate().any(|(at, byte)| *byte == b'\r' && bytes.get(at + 1) != Some(&b'\n'))
|
||||
}
|
||||
|
||||
/// The rows one file contributes, in the shape ripgrep prints them: `file:line:text` for a match,
|
||||
/// `file-line-text` for context, or the file's name or count for the coarser modes.
|
||||
/// The rows one file contributes: its matching and context lines, or its name or count for the
|
||||
/// coarser modes. A match is labeled with the scopes around it where `outline` parses the file.
|
||||
fn search_file(
|
||||
cwd: &Path,
|
||||
relative: &Path,
|
||||
(regex, prefilter): (®ex::Regex, Option<®ex::Regex>),
|
||||
search: &Search<'_>,
|
||||
) -> Vec<String> {
|
||||
outline: Option<&dyn OutlineSource>,
|
||||
) -> Vec<Hit> {
|
||||
let Ok(bytes) = std::fs::read(cwd.join(relative)) else { return Vec::new() };
|
||||
if bytes.iter().take(BINARY_SNIFF_BYTES).any(|byte| *byte == 0) {
|
||||
return Vec::new();
|
||||
@@ -287,7 +347,7 @@ fn search_file(
|
||||
if filtered.is_some_and(|prefilter| !prefilter.is_match(&text)) {
|
||||
return Vec::new();
|
||||
}
|
||||
let name = luxe_core::paths::display(relative);
|
||||
let file: std::sync::Arc<str> = luxe_core::paths::display(relative).into();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let matched: Vec<usize> = lines
|
||||
.iter()
|
||||
@@ -298,45 +358,78 @@ fn search_file(
|
||||
if matched.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let row = |kind, line, text: String| Hit { file: file.clone(), kind, line, text, scope: None };
|
||||
match search.mode {
|
||||
OutputMode::Files => vec![name],
|
||||
OutputMode::Count => vec![format!("{name}:{}", matched.len())],
|
||||
OutputMode::Files => vec![row(HitKind::File, 0, String::new())],
|
||||
OutputMode::Count => vec![row(HitKind::Count, 0, matched.len().to_string())],
|
||||
OutputMode::Content => {
|
||||
// Decide *which* lines to print and *what each one is* separately, then print each
|
||||
// once. Doing it per match instead conflates the two: a match inside an earlier
|
||||
// match's trailing context gets emitted as context and never as the answer.
|
||||
let mut shown = vec![false; lines.len()];
|
||||
for index in &matched {
|
||||
let first = index.saturating_sub(search.before);
|
||||
let last = (index + search.after + 1).min(lines.len());
|
||||
shown[first..last].iter_mut().for_each(|slot| *slot = true);
|
||||
}
|
||||
let is_match = |index: usize| matched.binary_search(&index).is_ok();
|
||||
lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| shown[*index])
|
||||
.map(|(index, line)| {
|
||||
// `-` marks a context line; the caller's parsers and the model both read the
|
||||
// `:` rows as the answer
|
||||
let separator = if is_match(index) { ':' } else { '-' };
|
||||
format!("{name}{separator}{}{separator}{line}", index + 1)
|
||||
let outline = outline.filter(|_| search.scopes);
|
||||
let scopes = outline.and_then(|outline| outline.scopes(relative, &text));
|
||||
line_hits(&lines, &matched, search)
|
||||
.map(|(index, is_match)| {
|
||||
let kind = if is_match { HitKind::Match } else { HitKind::Context };
|
||||
let mut hit = row(kind, index + 1, lines[index].to_string());
|
||||
hit.scope =
|
||||
scopes.as_deref().filter(|_| is_match).and_then(|s| scope_label(s, index));
|
||||
hit
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines to show and whether each is a match, in order.
|
||||
///
|
||||
/// Decides *which* lines to print and *what each one is* separately, then yields each once. Doing
|
||||
/// it per match instead conflates the two: a match inside an earlier match's trailing context gets
|
||||
/// emitted as context and never as the answer.
|
||||
fn line_hits<'a>(
|
||||
lines: &'a [&str],
|
||||
matched: &'a [usize],
|
||||
search: &Search<'_>,
|
||||
) -> impl Iterator<Item = (usize, bool)> + 'a {
|
||||
let mut shown = vec![false; lines.len()];
|
||||
for index in matched {
|
||||
let first = index.saturating_sub(search.before);
|
||||
let last = (index + search.after + 1).min(lines.len());
|
||||
shown[first..last].iter_mut().for_each(|slot| *slot = true);
|
||||
}
|
||||
(0..lines.len())
|
||||
.filter(move |index| shown[*index])
|
||||
.map(move |index| (index, matched.binary_search(&index).is_ok()))
|
||||
}
|
||||
|
||||
/// The scopes around 0-based line `line`, outermost first, as `QuerySet › delete`.
|
||||
///
|
||||
/// A scope whose declaration starts on the line is left out: the line itself names it, so
|
||||
/// `def delete(self):` is labeled `QuerySet`, not `QuerySet › delete`.
|
||||
fn scope_label(scopes: &[Scope], line: usize) -> Option<String> {
|
||||
let mut around: Vec<&Scope> =
|
||||
scopes.iter().filter(|scope| scope.start_line < line && line <= scope.end_line).collect();
|
||||
around.sort_by_key(|scope| (scope.start_line, std::cmp::Reverse(scope.end_line)));
|
||||
let names: Vec<&str> = around.iter().map(|scope| scope.name.as_str()).collect();
|
||||
(!names.is_empty()).then(|| names.join(" › "))
|
||||
}
|
||||
|
||||
/// The `grep` tool implementation.
|
||||
pub struct GrepTool {
|
||||
/// Shared read tracker; a file whose lines a search printed is recorded as read
|
||||
tracker: Option<std::sync::Arc<luxe_core::read_tracker::ReadTracker>>,
|
||||
/// What names the scopes a match sits in; without it lines come unlabeled
|
||||
outline: Option<std::sync::Arc<dyn OutlineSource>>,
|
||||
}
|
||||
|
||||
impl GrepTool {
|
||||
/// Create a new grep tool instance.
|
||||
pub fn new() -> Self {
|
||||
Self { tracker: None }
|
||||
Self { tracker: None, outline: None }
|
||||
}
|
||||
|
||||
/// Attach the outline that labels each match with the function or type around it, a parser
|
||||
/// that lives outside this crate.
|
||||
pub fn with_outline(mut self, outline: std::sync::Arc<dyn OutlineSource>) -> Self {
|
||||
self.outline = Some(outline);
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker, so the lines a search showed satisfy the edit guards the
|
||||
@@ -380,6 +473,8 @@ impl Tool for GrepTool {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod scope_tests;
|
||||
#[cfg(test)]
|
||||
mod search_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -48,6 +48,7 @@ pub(super) fn parse_search(args: &serde_json::Value) -> Result<Search<'_>, Strin
|
||||
after: side("after"),
|
||||
all: args.get("all").and_then(|value| value.as_bool()).unwrap_or(false),
|
||||
invert: args.get("invert").and_then(|value| value.as_bool()).unwrap_or(false),
|
||||
scopes: args.get("scopes").and_then(|value| value.as_bool()).unwrap_or(false),
|
||||
// camelCase is advertised; snake_case is what models reach for, and a silently ignored
|
||||
// mode returns the expensive answer
|
||||
mode: OutputMode::parse(
|
||||
@@ -106,16 +107,15 @@ async fn scan(
|
||||
args: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
paths: Vec<PathBuf>,
|
||||
stopped: Arc<AtomicBool>,
|
||||
) -> Result<String, String> {
|
||||
(outline, stopped): (Option<Arc<dyn OutlineSource>>, Arc<AtomicBool>),
|
||||
) -> Result<Vec<Hit>, String> {
|
||||
let cwd = cx.cwd.clone();
|
||||
let cancelled = cx.cancelled.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let search = parse_search(&args)?;
|
||||
super::native_search_files(&cwd, &search, paths, || {
|
||||
super::native_search_files(&cwd, &search, paths, outline.as_deref(), || {
|
||||
stopped.load(Ordering::Relaxed) || *cancelled.borrow()
|
||||
})
|
||||
.map(|rows| rows.join("\n"))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("grep scan worker failed: {error}"))?
|
||||
@@ -141,7 +141,7 @@ pub(super) async fn run(
|
||||
Ok(plan) => plan,
|
||||
Err(error) => return ToolResultData::error(error),
|
||||
};
|
||||
let found = scan(args.clone(), cx, plan.allowed, stopped).await;
|
||||
let found = scan(args.clone(), cx, plan.allowed, (tool.outline.clone(), stopped)).await;
|
||||
let mut result = finish(tool, cx, &search, found);
|
||||
if plan.denied + plan.asks > 0 {
|
||||
result.content.push(ContentBlock::Text(format!(
|
||||
@@ -159,20 +159,24 @@ pub(super) fn finish(
|
||||
tool: &GrepTool,
|
||||
cx: &ToolContext,
|
||||
search: &Search<'_>,
|
||||
found: Result<String, String>,
|
||||
found: Result<Vec<Hit>, String>,
|
||||
) -> ToolResultData {
|
||||
match found {
|
||||
Ok(matches) if matches.trim().is_empty() => ToolResultData::text("No matches found"),
|
||||
Ok(matches) => {
|
||||
let bounded = crate::output_limit::cap_lines_within(
|
||||
&matches,
|
||||
Ok(hits) if hits.is_empty() => ToolResultData::text("No matches found"),
|
||||
Ok(hits) if search.mode == OutputMode::Content => {
|
||||
let (text, shown) = super::present::content(&hits, search);
|
||||
record_matches(tool, cx, search, &hits[..shown]);
|
||||
ToolResultData::text(text)
|
||||
}
|
||||
Ok(hits) => {
|
||||
let rows: Vec<String> = hits.iter().map(Hit::flat).collect();
|
||||
ToolResultData::text(crate::output_limit::cap_lines_within(
|
||||
&rows.join("\n"),
|
||||
search.limit,
|
||||
GREP_MAX_CHARS,
|
||||
search.mode.unit(),
|
||||
search.mode.hint(),
|
||||
);
|
||||
record_matches(tool, cx, search, &bounded);
|
||||
ToolResultData::text(bounded)
|
||||
))
|
||||
}
|
||||
Err(problem) => {
|
||||
warn!(pattern = search.pattern, error = %problem, "grep failed");
|
||||
@@ -181,15 +185,18 @@ pub(super) fn finish(
|
||||
}
|
||||
}
|
||||
|
||||
fn record_matches(tool: &GrepTool, cx: &ToolContext, search: &Search<'_>, bounded: &str) {
|
||||
let (Some(tracker), OutputMode::Content) = (&tool.tracker, search.mode) else { return };
|
||||
/// Records as read every file a line of which the answer showed, the way a `read` of it would be.
|
||||
fn record_matches(tool: &GrepTool, cx: &ToolContext, search: &Search<'_>, shown: &[Hit]) {
|
||||
let Some(tracker) = &tool.tracker else { return };
|
||||
let searched = cx.cwd.join(search.path);
|
||||
let shown = if searched.is_file() {
|
||||
vec![searched]
|
||||
} else {
|
||||
crate::bash::seen::files_in_rows(bounded, &cx.cwd)
|
||||
let files: Vec<PathBuf> = match searched.is_file() {
|
||||
true => vec![searched],
|
||||
false => shown.iter().map(|hit| cx.cwd.join(&*hit.file)).collect(),
|
||||
};
|
||||
for path in shown {
|
||||
tracker.record(&cx.session_id, &path);
|
||||
let mut recorded = std::collections::HashSet::new();
|
||||
for path in files {
|
||||
if recorded.insert(path.clone()) {
|
||||
tracker.record(&cx.session_id, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
106
crates/luxe-tools/src/grep/present.rs
Normal file
106
crates/luxe-tools/src/grep/present.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
//! Present — a content search laid out for reading: each file named once, its lines under it, and
|
||||
//! the scope around a run of matches where an outline can say.
|
||||
//!
|
||||
//! The rows are counted and capped as ripgrep would print them, `file:line:text`, so the bounds and
|
||||
//! the totals are the ones the other modes keep. Only the layout changes. A path repeated on every
|
||||
//! line is a large share of a broad search, and the function a match sits in is what the next
|
||||
//! `read` would have gone to find out.
|
||||
|
||||
use super::{Hit, HitKind, Search, GREP_MAX_CHARS};
|
||||
|
||||
/// The capped, grouped answer, and how many of `hits` it shows.
|
||||
pub(super) fn content(hits: &[Hit], search: &Search<'_>) -> (String, usize) {
|
||||
let lengths = hits.iter().map(|hit| hit.flat().chars().count());
|
||||
let kept = crate::output_limit::lines_within(lengths, search.limit, GREP_MAX_CHARS);
|
||||
let shown = grouped(&hits[..kept], search.before + search.after > 0);
|
||||
let text = match kept < hits.len() {
|
||||
true => crate::output_limit::with_note(
|
||||
&shown,
|
||||
hits.len() - kept,
|
||||
hits.len(),
|
||||
search.mode.unit(),
|
||||
search.mode.hint(),
|
||||
),
|
||||
false => crate::output_limit::clamp(&shown),
|
||||
};
|
||||
(text, kept)
|
||||
}
|
||||
|
||||
/// `hits` under their files: the path, then `line:text` for a match and `line-text` for context,
|
||||
/// ` [Scope › name]` before a match whose scope differs from the last one's, and `--` where
|
||||
/// context leaves a gap.
|
||||
fn grouped(hits: &[Hit], context: bool) -> String {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut previous: Option<&Hit> = None;
|
||||
let mut scope: Option<&str> = None;
|
||||
for hit in hits {
|
||||
match previous {
|
||||
Some(last) if last.file == hit.file => {
|
||||
if context && hit.line > last.line + 1 {
|
||||
out.push("--".into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
out.push(hit.file.to_string());
|
||||
scope = None;
|
||||
}
|
||||
}
|
||||
if hit.kind == HitKind::Match && hit.scope.as_deref() != scope {
|
||||
out.push(scope_row(hit.scope.as_deref()));
|
||||
scope = hit.scope.as_deref();
|
||||
}
|
||||
let separator = if hit.kind == HitKind::Match { ':' } else { '-' };
|
||||
out.push(format!("{}{separator}{}", hit.line, hit.text));
|
||||
previous = Some(hit);
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// ` [QuerySet › delete]`, or ` [top level]` for a match that has left the scopes before it.
|
||||
fn scope_row(scope: Option<&str>) -> String {
|
||||
format!(" [{}]", scope.unwrap_or("top level"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hit(file: &str, kind: HitKind, line: usize, text: &str, scope: Option<&str>) -> Hit {
|
||||
let (file, text, scope) = (file.into(), text.to_string(), scope.map(String::from));
|
||||
Hit { file, kind, line, text, scope }
|
||||
}
|
||||
|
||||
/// Each file is named once, its lines under it, and a scope row comes only where it changes.
|
||||
#[test]
|
||||
fn matches_group_under_their_file_with_a_row_per_change_of_scope() {
|
||||
let hits = [
|
||||
hit("a.py", HitKind::Match, 3, " def delete(self):", Some("QuerySet")),
|
||||
hit("a.py", HitKind::Match, 9, " def delete_all(self):", Some("QuerySet")),
|
||||
hit("a.py", HitKind::Match, 20, "def delete(): pass", None),
|
||||
hit("b.py", HitKind::Match, 5, " delete()", Some("Model › save")),
|
||||
];
|
||||
let expected = "a.py\n [QuerySet]\n3: def delete(self):\n9: def delete_all(self):\n \
|
||||
[top level]\n20:def delete(): pass\nb.py\n [Model › save]\n5: delete()";
|
||||
assert_eq!(grouped(&hits, false), expected);
|
||||
}
|
||||
|
||||
/// A file no outline can read gets no scope rows at all, rather than a `[top level]` that
|
||||
/// would claim to know.
|
||||
#[test]
|
||||
fn an_unlabeled_file_gets_no_scope_rows() {
|
||||
let hits = [hit("notes.md", HitKind::Match, 1, "delete it", None)];
|
||||
assert_eq!(grouped(&hits, false), "notes.md\n1:delete it");
|
||||
}
|
||||
|
||||
/// Context lines take `-`, and a gap between runs of context is marked `--`.
|
||||
#[test]
|
||||
fn context_rows_take_a_dash_and_a_gap_is_marked() {
|
||||
let hits = [
|
||||
hit("a.rs", HitKind::Match, 2, "needle", None),
|
||||
hit("a.rs", HitKind::Context, 3, "after", None),
|
||||
hit("a.rs", HitKind::Match, 9, "needle", None),
|
||||
];
|
||||
assert_eq!(grouped(&hits, true), "a.rs\n2:needle\n3-after\n--\n9:needle");
|
||||
assert_eq!(grouped(&hits, false), "a.rs\n2:needle\n3-after\n9:needle", "no context asked");
|
||||
}
|
||||
}
|
||||
77
crates/luxe-tools/src/grep/scope_tests.rs
Normal file
77
crates/luxe-tools/src/grep/scope_tests.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use super::*;
|
||||
use luxe_core::hooks::file_changed::FunctionSize;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
/// A stand-in for the tree-sitter outline: in a `.py` file, a class over lines 1–9 (0-based 0–8)
|
||||
/// with a method over lines 3–6, and nothing it can read in any other file.
|
||||
struct OneClass;
|
||||
|
||||
impl OutlineSource for OneClass {
|
||||
fn functions(&self, _: &Path, _: &str) -> Option<Vec<FunctionSize>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn scopes(&self, path: &Path, _: &str) -> Option<Vec<Scope>> {
|
||||
let scope =
|
||||
|name: &str, start_line, end_line| Scope { name: name.into(), start_line, end_line };
|
||||
(path.extension()? == "py").then(|| vec![scope("QuerySet", 0, 8), scope("delete", 2, 5)])
|
||||
}
|
||||
}
|
||||
|
||||
fn context(cwd: &Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: cwd.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each match is labeled with the scopes around it, outermost first, and only where the label
|
||||
/// changes. The definition line takes its parent's label, since it names itself; a file no outline
|
||||
/// can read gets no label at all; and the path comes once, above its lines.
|
||||
#[tokio::test]
|
||||
async fn a_match_is_labeled_with_the_scopes_around_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python =
|
||||
"class QuerySet:\n \n def delete(self):\n self.delete_batch()\n \
|
||||
return self\n \n \nOTHER = 1\n \ndef delete():\n pass\n";
|
||||
std::fs::write(dir.path().join("a.py"), python).unwrap();
|
||||
std::fs::write(dir.path().join("notes.md"), "delete it\n").unwrap();
|
||||
let tool = GrepTool::new().with_outline(Arc::new(OneClass));
|
||||
let args = json!({"pattern": "delete", "scopes": true});
|
||||
let result = tool.run(args, &context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
let expected = "a.py\n [QuerySet]\n3: def delete(self):\n [QuerySet › delete]\n4: \
|
||||
self.delete_batch()\n [top level]\n10:def delete():\nnotes.md\n1:delete it";
|
||||
assert_eq!(text, expected);
|
||||
}
|
||||
|
||||
/// Labels cost a row each, so a search without `scopes` gets the grouped lines alone, outline or
|
||||
/// not.
|
||||
#[tokio::test]
|
||||
async fn a_search_is_unlabeled_unless_it_asks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("a.py"), "class A:\n \n def delete(self):\n").unwrap();
|
||||
let tool = GrepTool::new().with_outline(Arc::new(OneClass));
|
||||
let result = tool.run(json!({"pattern": "delete"}), &context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text, "a.py\n3: def delete(self):");
|
||||
}
|
||||
|
||||
/// The coarse modes have no lines to label, so they ask nothing of the outline.
|
||||
#[tokio::test]
|
||||
async fn the_files_mode_carries_no_scopes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("a.py"), "class A:\n def delete(self): pass\n").unwrap();
|
||||
let tool = GrepTool::new().with_outline(Arc::new(OneClass));
|
||||
let args = json!({"pattern": "delete", "outputMode": "files"});
|
||||
let result = tool.run(args, &context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.trim(), "a.py");
|
||||
}
|
||||
@@ -17,6 +17,7 @@ fn base(pattern: &str) -> Search<'_> {
|
||||
after: 0,
|
||||
all: false,
|
||||
invert: false,
|
||||
scopes: false,
|
||||
mode: OutputMode::Content,
|
||||
limit: 500,
|
||||
}
|
||||
@@ -147,10 +148,20 @@ fn the_prefilter_never_hides_a_matching_line() {
|
||||
/// A worker that crashed is a failure the caller hears about; one that was stopped is a cancel.
|
||||
#[test]
|
||||
fn a_crashed_worker_is_a_failure_not_a_cancel() {
|
||||
let rows = |row: &str| Ok(Some(vec![row.to_string()]));
|
||||
let crashed: std::thread::Result<Option<Vec<String>>> = Err(Box::new("boom"));
|
||||
let rows = |file: &str| {
|
||||
let hit = Hit {
|
||||
file: file.into(),
|
||||
kind: HitKind::File,
|
||||
line: 0,
|
||||
text: String::new(),
|
||||
scope: None,
|
||||
};
|
||||
Ok(Some(vec![hit]))
|
||||
};
|
||||
let crashed: std::thread::Result<Option<Vec<Hit>>> = Err(Box::new("boom"));
|
||||
let failed = combine(vec![rows("a"), crashed], false).unwrap_err();
|
||||
assert!(failed.contains("worker failed"), "{failed}");
|
||||
assert_eq!(combine(vec![rows("a"), Ok(None)], false).unwrap_err(), "grep cancelled");
|
||||
assert_eq!(combine(vec![rows("a"), rows("b")], false).unwrap(), ["a", "b"]);
|
||||
let joined = combine(vec![rows("a"), rows("b")], false).unwrap();
|
||||
assert_eq!(joined.iter().map(Hit::flat).collect::<Vec<_>>(), ["a", "b"]);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,13 @@ fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// The matching-line rows of a content answer, `12:text`, not the paths or scope rows around them.
|
||||
fn match_rows(text: &str) -> usize {
|
||||
text.lines()
|
||||
.filter(|line| line.split_once(':').is_some_and(|(n, _)| n.parse::<usize>().is_ok()))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// A plain content search of `.`, for a test to vary one field of.
|
||||
fn search<'a>(pattern: &'a str) -> Search<'a> {
|
||||
Search {
|
||||
@@ -27,6 +34,7 @@ fn search<'a>(pattern: &'a str) -> Search<'a> {
|
||||
after: 0,
|
||||
all: false,
|
||||
invert: false,
|
||||
scopes: false,
|
||||
mode: OutputMode::Content,
|
||||
limit: GREP_MAX_LINES,
|
||||
}
|
||||
@@ -246,7 +254,7 @@ async fn a_zero_limit_is_an_absent_limit() {
|
||||
.run(json!({"pattern": "needle", "limit": 0}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.lines().count(), 20, "every match, not none: {text}");
|
||||
assert_eq!(match_rows(text), 20, "every match, not none: {text}");
|
||||
assert!(!text.contains("not shown"), "and nothing was cut: {text}");
|
||||
}
|
||||
|
||||
@@ -282,16 +290,12 @@ async fn a_limit_can_only_tighten_the_cap() {
|
||||
|
||||
let sampled = GrepTool::new().run(json!({"pattern": "needle", "limit": 5}), &cx).await;
|
||||
let ContentBlock::Text(text) = &sampled.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.lines().filter(|line| line.contains("many.txt")).count(), 5, "{text}");
|
||||
assert_eq!(match_rows(text), 5, "{text}");
|
||||
assert!(text.contains("295 more matching lines not shown (300 total)"), "{text}");
|
||||
|
||||
let greedy = GrepTool::new().run(json!({"pattern": "needle", "limit": 5000}), &cx).await;
|
||||
let ContentBlock::Text(text) = &greedy.content[0] else { panic!("expected text") };
|
||||
assert_eq!(
|
||||
text.lines().filter(|line| line.contains("many.txt")).count(),
|
||||
GREP_MAX_LINES,
|
||||
"a limit past the ceiling is the ceiling: {text}"
|
||||
);
|
||||
assert_eq!(match_rows(text), GREP_MAX_LINES, "a limit past the ceiling is the ceiling: {text}");
|
||||
}
|
||||
|
||||
/// The count a capped result reports is the count that exists, not the count that was kept.
|
||||
|
||||
@@ -49,6 +49,9 @@ pub mod write;
|
||||
/// The `todo` tool requires a store root (e.g. `.luxe/todos`). Pass `None` to skip registering it.
|
||||
/// `web` configures `web_search` and `web_fetch`; [`web::WebConfig::from_env`] is the usual start.
|
||||
///
|
||||
/// `outline` labels each `grep` match with the function or type around it; it is a parser this
|
||||
/// crate cannot depend on (tree-sitter lives in `luxe-lsp`), and `None` leaves matches unlabeled.
|
||||
///
|
||||
/// Returns the shared [`luxe_core::read_tracker::ReadTracker`] backing the read-before-edit /
|
||||
/// staleness / blind-write guards, so the caller can also wire it into the LSP funnel reads
|
||||
/// (`read_symbol`, `module_report`) that see file content but live in a crate that can't depend
|
||||
@@ -57,6 +60,7 @@ pub fn register_builtins(
|
||||
registry: &mut luxe_core::ToolRegistry,
|
||||
todo_store_root: Option<std::path::PathBuf>,
|
||||
web: web::WebConfig,
|
||||
outline: Option<std::sync::Arc<dyn luxe_core::hooks::file_changed::OutlineSource>>,
|
||||
) -> std::sync::Arc<luxe_core::read_tracker::ReadTracker> {
|
||||
use std::sync::Arc;
|
||||
// One shared read tracker backs the read-before-edit + staleness + blind-write guards across
|
||||
@@ -76,7 +80,11 @@ pub fn register_builtins(
|
||||
registry.register(Arc::new(write::WriteTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(edit::EditTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(bash::BashTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(grep::GrepTool::new().with_tracker(read_tracker.clone())));
|
||||
let grep = grep::GrepTool::new().with_tracker(read_tracker.clone());
|
||||
registry.register(Arc::new(match outline {
|
||||
Some(outline) => grep.with_outline(outline),
|
||||
None => grep,
|
||||
}));
|
||||
registry.register(Arc::new(glob::GlobTool::new()));
|
||||
registry.register(Arc::new(question::QuestionTool::new(question::QuestionConfig::default())));
|
||||
registry.register(Arc::new(skill::SkillTool::new(skill::SkillConfig)));
|
||||
|
||||
@@ -37,24 +37,54 @@ pub(crate) fn cap_lines_within(
|
||||
hint: &str,
|
||||
) -> String {
|
||||
let total = text.lines().count();
|
||||
let mut kept_lines = 0usize;
|
||||
let mut spent = 0usize;
|
||||
for line in text.lines().take(max_lines) {
|
||||
let cost = line.chars().count().saturating_add(1);
|
||||
if kept_lines > 0 && spent.saturating_add(cost) > max_chars {
|
||||
break;
|
||||
}
|
||||
spent = spent.saturating_add(cost);
|
||||
kept_lines += 1;
|
||||
}
|
||||
let kept_lines =
|
||||
lines_within(text.lines().map(|line| line.chars().count()), max_lines, max_chars);
|
||||
if kept_lines >= total {
|
||||
return clamp_bytes(text);
|
||||
}
|
||||
let kept = text.lines().take(kept_lines).collect::<Vec<_>>().join("\n");
|
||||
let remaining = total - kept_lines;
|
||||
with_note(&kept, total - kept_lines, total, unit, hint)
|
||||
}
|
||||
|
||||
/// How many lines, given each one's length in characters, fit under both `max_lines` and
|
||||
/// `max_chars`; at least one when there is any, however long it is.
|
||||
///
|
||||
/// The cut [`cap_lines_within`] makes, for a tool that lays its lines out after choosing them.
|
||||
pub(crate) fn lines_within(
|
||||
lengths: impl IntoIterator<Item = usize>,
|
||||
max_lines: usize,
|
||||
max_chars: usize,
|
||||
) -> usize {
|
||||
let mut kept = 0usize;
|
||||
let mut spent = 0usize;
|
||||
for length in lengths.into_iter().take(max_lines) {
|
||||
let cost = length.saturating_add(1);
|
||||
if kept > 0 && spent.saturating_add(cost) > max_chars {
|
||||
break;
|
||||
}
|
||||
spent = spent.saturating_add(cost);
|
||||
kept += 1;
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// `kept`, then the note that `remaining` more of `total` were cut and how to see them, clamped to
|
||||
/// the byte backstop.
|
||||
pub(crate) fn with_note(
|
||||
kept: &str,
|
||||
remaining: usize,
|
||||
total: usize,
|
||||
unit: &str,
|
||||
hint: &str,
|
||||
) -> String {
|
||||
clamp_bytes(&format!("{kept}\n\n… {remaining} more {unit} not shown ({total} total). {hint}"))
|
||||
}
|
||||
|
||||
/// [`clamp_bytes`] for a tool that caps its own lines first.
|
||||
pub(crate) fn clamp(text: &str) -> String {
|
||||
clamp_bytes(text)
|
||||
}
|
||||
|
||||
/// Head+tail byte clamp for the rare single-huge-line case the line cap can't shrink.
|
||||
fn clamp_bytes(text: &str) -> String {
|
||||
if text.len() <= MAX_OUTPUT_BYTES {
|
||||
|
||||
@@ -182,7 +182,7 @@ impl Tool for WriteTool {
|
||||
Err(_) => std::borrow::Cow::Borrowed(content),
|
||||
};
|
||||
|
||||
match luxe_core::fs_atomic::replace(&full_path, content.as_bytes()) {
|
||||
match luxe_core::fs_atomic::replace_keeping_mode(&full_path, content.as_bytes()) {
|
||||
Ok(()) => {
|
||||
debug!(path = %full_path.display(), "file written successfully");
|
||||
self.after_write(cx, &full_path, &content, existed).await
|
||||
|
||||
@@ -30,6 +30,22 @@ async fn a_reformatted_write_shows_the_file_as_it_is_now() {
|
||||
assert!(text.contains("+1 fn sub(a: i32) {}") && !text.contains("a:i32"), "{text}");
|
||||
}
|
||||
|
||||
/// Overwriting a script keeps it executable, as an editor's save does.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_overwritten_script_stays_executable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = dir.path().join("run.sh");
|
||||
std::fs::write(&script, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let args = serde_json::json!({"path": "run.sh", "content": "#!/bin/sh\necho hi\n"});
|
||||
let result = WriteTool::new().run(args, &test_context(dir.path())).await;
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
let mode = std::fs::metadata(&script).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o755, "still executable after the write");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_tool_basic() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
|
||||
@@ -8,7 +8,7 @@ repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
# `unstable-rendered-line-info` enables Paragraph::line_count, used for precise wrapping-aware
|
||||
# mouse hit-testing over word-wrapped surfaces (guide/dock/conversation clicks). It adds no crate;
|
||||
# the API is marked unstable upstream but is stable within our pinned minor (re-check on upgrade).
|
||||
@@ -54,6 +54,8 @@ clipboard-images = ["clipboard"]
|
||||
# Integration tests link the library without `cfg(test)`; normal dependents keep fixtures off.
|
||||
luxe-tui = { path = ".", features = ["fixture"] }
|
||||
tempfile = "3"
|
||||
# The README's animated wordmark (examples/wordmark_gif). Already in the tree through `image`.
|
||||
gif = "0.14"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -71,6 +73,10 @@ test = true
|
||||
name = "wordmark_svg"
|
||||
test = true
|
||||
|
||||
[[example]]
|
||||
name = "wordmark_gif"
|
||||
test = true
|
||||
|
||||
[[example]]
|
||||
name = "theme_css"
|
||||
test = true
|
||||
|
||||
197
crates/luxe-tui/examples/wordmark_gif.rs
Normal file
197
crates/luxe-tui/examples/wordmark_gif.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! wordmark_gif — the logotype as the terminal lights it, as a looping GIF for the README.
|
||||
//!
|
||||
//! Every frame comes from [`Wordmark::lines_at`], the same rows and the same two lights the
|
||||
//! dashboard draws, so the recording cannot drift from the product. GitHub shows a README image on
|
||||
//! its own page background, light or dark, so the background is transparent: the art is hard-edged
|
||||
//! cells, which GIF's one-bit transparency draws exactly.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p luxe-tui --example wordmark_gif -- dark > web/src/assets/generated/wordmark-dark.gif
|
||||
//! cargo run -p luxe-tui --example wordmark_gif -- light > web/src/assets/generated/wordmark-light.gif
|
||||
//! ```
|
||||
|
||||
use luxe_tui::main_loop::ANIMATION_TICK;
|
||||
use luxe_tui::widgets::{
|
||||
Wordmark, WordmarkInk, DRIFT_FRAME_TICKS, DRIFT_PERIOD_TICKS, SHINE_CYCLE_TICKS,
|
||||
SHINE_SWEEP_TICKS,
|
||||
};
|
||||
use ratatui::style::Color;
|
||||
use std::borrow::Cow;
|
||||
use std::io::Write;
|
||||
|
||||
/// Pixels per cell: the 10×22 grid `wordmark_svg` draws, twice over so the mark stays sharp on a
|
||||
/// high-density screen when the README shows it at half size.
|
||||
const CELL_W: usize = 20;
|
||||
const CELL_H: usize = 44;
|
||||
|
||||
fn main() {
|
||||
let dark = match std::env::args().nth(1).as_deref() {
|
||||
Some("dark") => true,
|
||||
Some("light") => false,
|
||||
other => {
|
||||
eprintln!("usage: wordmark_gif dark|light (got {other:?})");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
write_gif(&mut out, ink(dark)).expect("encoding into memory cannot fail");
|
||||
std::io::stdout().write_all(&out).expect("write the GIF to stdout");
|
||||
}
|
||||
|
||||
/// The luxe theme's accent and canvas. `dark` sets how hard the shine pushes toward white: a light
|
||||
/// page washes the letters out sooner, so it gets the gentler peak the terminal uses on light
|
||||
/// themes. The canvas stays the dark one either way, so the drift deepens the brass on both.
|
||||
fn ink(dark: bool) -> WordmarkInk {
|
||||
let theme = luxe_core::theme::ThemeRegistry::new().resolve("luxe").expect("a built-in theme");
|
||||
let rgb = |token: &str| match theme.get(token) {
|
||||
Some(luxe_core::theme::ColorValue::Rgb(red, green, blue)) => {
|
||||
Color::Rgb(*red, *green, *blue)
|
||||
}
|
||||
other => panic!("the luxe theme's {token} is a color, not {other:?}"),
|
||||
};
|
||||
WordmarkInk { accent: rgb("accent"), canvas: Some(rgb("background")), dark }
|
||||
}
|
||||
|
||||
/// The ticks a frame is drawn at across one loop: every tick while the shine crosses, every drift
|
||||
/// frame while it rests, as the terminal repaints.
|
||||
///
|
||||
/// One loop is one drift period, which has to close on itself for the GIF to loop without a seam.
|
||||
/// The shine crosses once at its start and rests for the remainder.
|
||||
fn frame_ticks() -> Vec<u64> {
|
||||
(0..DRIFT_PERIOD_TICKS)
|
||||
.filter(|&tick| tick < SHINE_SWEEP_TICKS || tick % DRIFT_FRAME_TICKS == 0)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each frame's delay in hundredths of a second, rounded against the running clock so the loop
|
||||
/// totals the drift period rather than gaining a rounding error per frame.
|
||||
fn delays(ticks: &[u64]) -> Vec<u16> {
|
||||
let tick_ms = ANIMATION_TICK.as_millis() as f64;
|
||||
let at = |tick: u64| (tick as f64 * tick_ms / 10.0).round() as i64;
|
||||
let ends = ticks.iter().skip(1).copied().chain([DRIFT_PERIOD_TICKS]);
|
||||
ticks.iter().zip(ends).map(|(&start, end)| (at(end) - at(start)).max(1) as u16).collect()
|
||||
}
|
||||
|
||||
fn write_gif(out: &mut Vec<u8>, ink: WordmarkInk) -> Result<(), gif::EncodingError> {
|
||||
let size = Wordmark::Full;
|
||||
let (width, height) = (usize::from(size.width()) * CELL_W, usize::from(size.height()) * CELL_H);
|
||||
let mut encoder = gif::Encoder::new(out, width as u16, height as u16, &[])?;
|
||||
encoder.set_repeat(gif::Repeat::Infinite)?;
|
||||
let ticks = frame_ticks();
|
||||
for (&tick, delay) in ticks.iter().zip(delays(&ticks)) {
|
||||
// The shine's own cycle is shorter than the loop; past it the shine rests
|
||||
let shine = (tick < SHINE_CYCLE_TICKS).then_some(tick);
|
||||
let (pixels, palette) = render(size, ink, tick, shine, width);
|
||||
encoder.write_frame(&frame((width, height), pixels, palette, delay))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One whole-canvas frame, index 0 transparent.
|
||||
fn frame(
|
||||
(width, height): (usize, usize),
|
||||
pixels: Vec<u8>,
|
||||
palette: Vec<u8>,
|
||||
delay: u16,
|
||||
) -> gif::Frame<'static> {
|
||||
gif::Frame {
|
||||
width: width as u16,
|
||||
height: height as u16,
|
||||
buffer: Cow::Owned(pixels),
|
||||
palette: Some(palette),
|
||||
transparent: Some(0),
|
||||
delay,
|
||||
// Cleared between frames, or a cell turned transparent would keep the last frame's ink
|
||||
dispose: gif::DisposalMethod::Background,
|
||||
..gif::Frame::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame as palette indices and the palette, index 0 transparent.
|
||||
fn render(
|
||||
size: Wordmark,
|
||||
ink: WordmarkInk,
|
||||
drift: u64,
|
||||
shine: Option<u64>,
|
||||
width: usize,
|
||||
) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut palette = vec![0u8, 0, 0];
|
||||
let mut pixels = vec![0u8; width * usize::from(size.height()) * CELL_H];
|
||||
for (row, line) in size.lines_at(ink, drift, shine).iter().enumerate() {
|
||||
let cells = line
|
||||
.spans
|
||||
.iter()
|
||||
.flat_map(|span| span.content.chars().map(move |glyph| (glyph, span.style.fg)));
|
||||
for (column, (glyph, fg)) in cells.enumerate() {
|
||||
let Some(Color::Rgb(red, green, blue)) = fg else { continue };
|
||||
let index = palette_index(&mut palette, [red, green, blue]);
|
||||
ink_cell(&mut pixels, width, (column, row), glyph, index);
|
||||
}
|
||||
}
|
||||
(pixels, palette)
|
||||
}
|
||||
|
||||
/// Paints the part of cell `(column, row)` that `glyph` inks: all of it, or the top or bottom half.
|
||||
fn ink_cell(
|
||||
pixels: &mut [u8],
|
||||
width: usize,
|
||||
(column, row): (usize, usize),
|
||||
glyph: char,
|
||||
index: u8,
|
||||
) {
|
||||
let (top, bottom) = match glyph {
|
||||
'█' => (0, CELL_H),
|
||||
'▀' => (0, CELL_H / 2),
|
||||
'▄' => (CELL_H / 2, CELL_H),
|
||||
_ => return,
|
||||
};
|
||||
for y in row * CELL_H + top..row * CELL_H + bottom {
|
||||
pixels[y * width + column * CELL_W..][..CELL_W].fill(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// The palette slot for `color`, adding it the first time it is seen.
|
||||
fn palette_index(palette: &mut Vec<u8>, color: [u8; 3]) -> u8 {
|
||||
let existing = palette.chunks(3).position(|entry| entry == color);
|
||||
let index = existing.unwrap_or_else(|| {
|
||||
palette.extend_from_slice(&color);
|
||||
palette.len() / 3 - 1
|
||||
});
|
||||
u8::try_from(index).expect("a frame of one hue lit two ways stays far under 256 colors")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The loop is one drift period to the hundredth of a second, so it closes without a jump.
|
||||
#[test]
|
||||
fn the_frames_add_up_to_one_drift_period() {
|
||||
let total: u32 = delays(&frame_ticks()).iter().map(|&delay| u32::from(delay)).sum();
|
||||
let period_cs =
|
||||
(DRIFT_PERIOD_TICKS as f64 * ANIMATION_TICK.as_millis() as f64 / 10.0).round();
|
||||
assert_eq!(f64::from(total), period_cs);
|
||||
}
|
||||
|
||||
/// The shine crosses frame by frame, and the rest repaints at the drift's slower cadence.
|
||||
#[test]
|
||||
fn the_shine_gets_every_tick_and_the_rest_every_drift_frame() {
|
||||
let ticks = frame_ticks();
|
||||
assert!((0..SHINE_SWEEP_TICKS).all(|tick| ticks.contains(&tick)));
|
||||
assert!(ticks
|
||||
.iter()
|
||||
.filter(|&&tick| tick >= SHINE_SWEEP_TICKS)
|
||||
.all(|tick| tick % DRIFT_FRAME_TICKS == 0));
|
||||
}
|
||||
|
||||
/// The background is transparent and the letters are ink: a frame has both.
|
||||
#[test]
|
||||
fn a_frame_is_transparent_around_inked_letters() {
|
||||
let size = Wordmark::Full;
|
||||
let width = usize::from(size.width()) * CELL_W;
|
||||
let (pixels, palette) = render(size, ink(true), 0, None, width);
|
||||
assert!(pixels.contains(&0), "transparent background");
|
||||
assert!(pixels.iter().any(|&index| index != 0), "inked letters");
|
||||
assert!(palette.len() / 3 > 1);
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,11 @@ use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::interval;
|
||||
|
||||
/// The animation tick, about 30 a second: what every timed effect counts in, the wordmark's lights
|
||||
/// and the spinner included. Public so a recording of one, the README's wordmark, keeps the same
|
||||
/// time.
|
||||
pub const ANIMATION_TICK: Duration = Duration::from_millis(33);
|
||||
|
||||
/// Why the TUI returned control to the CLI.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TuiExit {
|
||||
@@ -181,7 +186,7 @@ pub async fn run(
|
||||
let mut sources = Sources {
|
||||
event_rx,
|
||||
terminal_events: Some(EventStream::new()),
|
||||
tick: interval(Duration::from_millis(33)), // ~30fps
|
||||
tick: interval(ANIMATION_TICK),
|
||||
// One listener for the run, rather than a fresh registration on every pass of a loop that
|
||||
// turns over as fast as the terminal can deliver keys.
|
||||
interrupted: Box::pin(tokio::signal::ctrl_c()),
|
||||
|
||||
@@ -19,25 +19,75 @@ use unicode_width::UnicodeWidthStr;
|
||||
/// there are others and that stepping is a thing you can do, which is what the footer's bracket
|
||||
/// keys then explain.
|
||||
pub(super) fn render_header(frame: &mut Frame, area: Rect, app: &App, view: &ChangesView) {
|
||||
let styles = &app.theme_styles;
|
||||
let entry = view.current();
|
||||
let width = usize::from(area.width);
|
||||
let line = header_line(app, view, area);
|
||||
frame.render_widget(Paragraph::new(line), Rect { height: 1, ..area });
|
||||
if area.height > 1 {
|
||||
frame.render_widget(
|
||||
Block::default().borders(Borders::TOP).border_style(app.theme_styles.border_muted),
|
||||
Rect { y: area.y + 1, height: 1, ..area },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let position = match (view.position(), view.files.len()) {
|
||||
/// Cells kept between the file's details and the FILE / DIFF switch, so its slab never touches them.
|
||||
const SWITCH_GAP: usize = 2;
|
||||
/// The least of a path worth showing: below this the position goes before the path does.
|
||||
const PATH_FLOOR: usize = 8;
|
||||
|
||||
/// The header's one line, laid out so it fits: every fixed part is measured first and the path gets
|
||||
/// what they leave. When even a stub of path will not fit, the position goes whole, never `8 of`.
|
||||
fn header_line(app: &App, view: &ChangesView, area: Rect) -> Line<'static> {
|
||||
let width = usize::from(area.width);
|
||||
let entry = view.current();
|
||||
let lead = lead_span(app, view, entry);
|
||||
let details = detail_spans(app, view, entry);
|
||||
let tabs = match view.changed() {
|
||||
true => view_tabs(view.view, app),
|
||||
false => ViewTabs::default(),
|
||||
};
|
||||
let mut position = position_label(view);
|
||||
let fixed = |position: &str| {
|
||||
let tail = tabs.width() + position_cells(position);
|
||||
cells(std::slice::from_ref(&lead)) + cells(&details) + tail + SWITCH_GAP
|
||||
};
|
||||
if fixed(&position) + PATH_FLOOR > width {
|
||||
position.clear();
|
||||
}
|
||||
// Cut from the left: the tail of a path is the file, which is the thing being named. A file
|
||||
// outside the project arrives absolute and is said the way a person would say it
|
||||
let budget = width.saturating_sub(fixed(&position)).max(PATH_FLOOR);
|
||||
let path = truncate_path_left(&home_relative(&view.path), budget);
|
||||
let mut spans =
|
||||
vec![lead, Span::styled(path, app.theme_styles.text.add_modifier(Modifier::BOLD))];
|
||||
spans.extend(details);
|
||||
push_tail(&mut spans, (app, area), tabs, position);
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// `8 of 14`, or nothing for a single file.
|
||||
fn position_label(view: &ChangesView) -> String {
|
||||
match (view.position(), view.files.len()) {
|
||||
(Some(index), total) if total > 1 => format!("{} of {total}", index + 1),
|
||||
_ => String::new(),
|
||||
};
|
||||
let counts = entry.and_then(count_label).unwrap_or_default();
|
||||
// Give the path whatever the fixed parts leave, and cut it from the left: the tail of a path
|
||||
// is the file, which is the thing being named. A file outside the project arrives absolute and
|
||||
// is said the way a person would say it, which is also what tells the reader at a glance that
|
||||
// they are not looking at project code.
|
||||
let reserved = position.chars().count() + counts.chars().count() + 6;
|
||||
let titled = home_relative(&view.path);
|
||||
let path = truncate_path_left(&titled, width.saturating_sub(reserved).max(8));
|
||||
}
|
||||
}
|
||||
|
||||
// A changed file leads with its git letter; any other file with the mark of its language
|
||||
let lead = match entry {
|
||||
/// The position's cells with the two that part it from the switch, or none when it is absent.
|
||||
fn position_cells(position: &str) -> usize {
|
||||
match position.is_empty() {
|
||||
true => 0,
|
||||
false => position.width() + 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn cells(spans: &[Span<'_>]) -> usize {
|
||||
spans.iter().map(|span| UnicodeWidthStr::width(span.content.as_ref())).sum()
|
||||
}
|
||||
|
||||
/// A changed file leads with its git letter; any other file with the mark of its language.
|
||||
fn lead_span(app: &App, view: &ChangesView, entry: Option<&ChangedFile>) -> Span<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
match entry {
|
||||
Some(file) => {
|
||||
Span::styled(format!("{} ", marker_of(file.status)), status_style(file.status, app))
|
||||
}
|
||||
@@ -49,10 +99,13 @@ pub(super) fn render_header(frame: &mut Frame, area: Rect, app: &App, view: &Cha
|
||||
crate::widgets::language_hue(icon, styles),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut spans = vec![lead];
|
||||
spans.push(Span::styled(path, styles.text.add_modifier(Modifier::BOLD)));
|
||||
// What the File view is showing: how long it is, and that it was cut short when it was
|
||||
}
|
||||
}
|
||||
|
||||
/// What follows the path: the File view's length (and that it was cut short), and `+6 −8`.
|
||||
fn detail_spans(app: &App, view: &ChangesView, entry: Option<&ChangedFile>) -> Vec<Span<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let mut spans = Vec::new();
|
||||
if let (PeekView::File, crate::changes::TextLoad::Ready(file)) = (view.view, &view.text) {
|
||||
let lines = file.text.lines().count();
|
||||
let mut meta = format!(" {lines} line{}", if lines == 1 { "" } else { "s" });
|
||||
@@ -66,39 +119,39 @@ pub(super) fn render_header(frame: &mut Frame, area: Rect, app: &App, view: &Cha
|
||||
spans.push(Span::styled(format!(" +{additions}"), styles.success));
|
||||
spans.push(Span::styled(format!(" −{deletions}"), styles.error));
|
||||
}
|
||||
// A changed file has two faces, and the one not showing is a click away
|
||||
let tabs = match view.changed() {
|
||||
true => view_tabs(view.view, app),
|
||||
false => ViewTabs::default(),
|
||||
};
|
||||
let tabs_width: usize = tabs.spans.iter().map(|span| span.content.width()).sum();
|
||||
let used: usize = spans.iter().map(|span| UnicodeWidthStr::width(span.content.as_ref())).sum();
|
||||
let tail = tabs_width + position.chars().count() + usize::from(!position.is_empty()) * 2;
|
||||
if tail > 0 {
|
||||
let pad = width.saturating_sub(used + tail);
|
||||
spans.push(Span::raw(" ".repeat(pad)));
|
||||
let tabs_at = used + pad;
|
||||
if let Some((start, cells)) = tabs.other {
|
||||
if let (Ok(x), Ok(cells)) = (u16::try_from(tabs_at + start), u16::try_from(cells)) {
|
||||
app.hit.borrow_mut().push(
|
||||
Rect::new(area.x + x, area.y, cells, 1),
|
||||
MouseTarget::ChangesFooter(ChangesFooterAction::ToggleView),
|
||||
);
|
||||
}
|
||||
}
|
||||
spans.extend(tabs.spans);
|
||||
if !position.is_empty() {
|
||||
spans.push(Span::raw(" "));
|
||||
spans.push(Span::styled(position, styles.muted));
|
||||
}
|
||||
}
|
||||
spans
|
||||
}
|
||||
|
||||
frame.render_widget(Paragraph::new(Line::from(spans)), Rect { height: 1, ..area });
|
||||
if area.height > 1 {
|
||||
frame.render_widget(
|
||||
Block::default().borders(Borders::TOP).border_style(styles.border_muted),
|
||||
Rect { y: area.y + 1, height: 1, ..area },
|
||||
);
|
||||
/// The switch and the position, pushed to the right edge with at least [`SWITCH_GAP`] before them,
|
||||
/// and the hidden face of the switch published as the click that flips the view.
|
||||
fn push_tail(
|
||||
spans: &mut Vec<Span<'static>>,
|
||||
(app, area): (&App, Rect),
|
||||
tabs: ViewTabs,
|
||||
position: String,
|
||||
) {
|
||||
let tail = tabs.width() + position_cells(&position);
|
||||
if tail == 0 {
|
||||
return;
|
||||
}
|
||||
let used = cells(spans);
|
||||
let pad = usize::from(area.width).saturating_sub(used + tail).max(SWITCH_GAP);
|
||||
spans.push(Span::raw(" ".repeat(pad)));
|
||||
publish_switch(app, area, used + pad, tabs.other);
|
||||
spans.extend(tabs.spans);
|
||||
if !position.is_empty() {
|
||||
spans.push(Span::raw(" "));
|
||||
spans.push(Span::styled(position, app.theme_styles.muted));
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes the switch's hidden face, `other` cells into a switch drawn at column `at`, as the
|
||||
/// click that flips the view.
|
||||
fn publish_switch(app: &App, area: Rect, at: usize, other: Option<(usize, usize)>) {
|
||||
let Some((start, width)) = other else { return };
|
||||
if let (Ok(x), Ok(width)) = (u16::try_from(at + start), u16::try_from(width)) {
|
||||
let target = MouseTarget::ChangesFooter(ChangesFooterAction::ToggleView);
|
||||
app.hit.borrow_mut().push(Rect::new(area.x + x, area.y, width, 1), target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +163,12 @@ struct ViewTabs {
|
||||
other: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl ViewTabs {
|
||||
fn width(&self) -> usize {
|
||||
cells(&self.spans)
|
||||
}
|
||||
}
|
||||
|
||||
/// `FILE DIFF`, both cut into badges: the showing face lit, the other on the idle surface.
|
||||
///
|
||||
/// Both in capitals and both slabs, so the pair reads as a switch with two positions rather than a
|
||||
@@ -160,12 +219,6 @@ pub(super) fn sentence(message: &str) -> String {
|
||||
})
|
||||
}
|
||||
|
||||
/// `+6 −8`, or nothing at all when git could not count (a binary blob).
|
||||
fn count_label(file: &ChangedFile) -> Option<String> {
|
||||
let (additions, deletions) = file.additions.zip(file.deletions)?;
|
||||
Some(format!(" +{additions} −{deletions}"))
|
||||
}
|
||||
|
||||
fn marker_of(status: luxe_core::FileChangeStatus) -> &'static str {
|
||||
use luxe_core::FileChangeStatus as Status;
|
||||
match status {
|
||||
|
||||
@@ -171,13 +171,13 @@ ChangesWide@100x30: frame=7f799b893667c928 hits=5ebcfa50c83c624f
|
||||
ChangesWide@64x20: frame=3531cf4c1d3f2402 hits=a39e334a4bdaa029
|
||||
ChangesNarrow@140x44: frame=4d45021ad9fb0fa7 hits=de2158bdae6d8dfb
|
||||
ChangesNarrow@100x30: frame=2ee7cc81d7896506 hits=6dca1cfbcba4056a
|
||||
ChangesNarrow@64x20: frame=903e59bd8b8a62f8 hits=98deec46c37135b8
|
||||
ChangesNarrow@64x20: frame=b82352043f680144 hits=65afb8e6ea7f4981
|
||||
ChangesFailed@140x44: frame=b8c525886e754d21 hits=88e878b841c4ee77
|
||||
ChangesFailed@100x30: frame=aba8595c8158cca4 hits=d3e7f3e0ab644214
|
||||
ChangesFailed@64x20: frame=69cdcefbe785c866 hits=27476cdcd9937bea
|
||||
ChangesFailed@64x20: frame=8d0caaba450a4f3a hits=e16f1ab1fbfea007
|
||||
ChangesExternal@140x44: frame=fc75aaae10ddb262 hits=d5c3115642e748ad
|
||||
ChangesExternal@100x30: frame=522c8250b0f50ac4 hits=3dd17e6200cfb4b5
|
||||
ChangesExternal@64x20: frame=a6d2706231364207 hits=6f0e8da295aaa965
|
||||
ChangesExternal@64x20: frame=d257ba5dbedfc85f hits=a8e0be5b4625e2bc
|
||||
ChatTools+palette: frame=85cc5ae977de2fa6 hits=ca2a2a735278a5bd
|
||||
ChatTools+slash: frame=a3ce4c3a7d03f8d0 hits=8adf06de80ecdcb2
|
||||
ChatTools+mention: frame=33c4a73f189a3dcc hits=c1b8d78b51a767b7
|
||||
@@ -219,7 +219,7 @@ ChatWideProse searching: frame=1878156c08a54641 hits=00e988aa75182c51
|
||||
ChatWideProse selecting: frame=8c1edde42c1f3700 hits=bddfef30519a2a3a
|
||||
ChatWideProse copied: frame=7757bb42f647c93e hits=bddfef30519a2a3a
|
||||
ChangesWide@180x44: frame=2f39ea02da654a31 hits=e9b01340cccc666e
|
||||
ChangesNarrow unwrapped: frame=d83dfbbe3d21abf8 hits=29eecb5dbf51e195
|
||||
ChangesNarrow unwrapped: frame=13da9745cf50215c hits=c84985bf30e3251e
|
||||
ChangesWide file: frame=4292536a789062da hits=da530d7bf2c94fdf
|
||||
ChangesWide file cursor: frame=aacfd7dfe8f072f0 hits=6293b97445fe71a6
|
||||
ChangesWide file unwrapped: frame=cbf79ee6830376c5 hits=316acbdf05625e0b
|
||||
|
||||
@@ -34,7 +34,8 @@ pub use slab::{
|
||||
pub use tool_glyph::{tool_glyph, tool_icon, GENERIC_TOOL};
|
||||
pub use wordmark::{
|
||||
banner_frame_due, render_wordmark, smoothstep, BannerClock, Wordmark, WordmarkInk, BAND,
|
||||
DRIFT_DEPTH, LEAN, PEAK_DARK, PEAK_LIGHT, SHINE_CYCLE_TICKS, SHINE_SWEEP_TICKS, STILL_TICK,
|
||||
DRIFT_DEPTH, DRIFT_FRAME_TICKS, DRIFT_PERIOD_TICKS, LEAN, PEAK_DARK, PEAK_LIGHT,
|
||||
SHINE_CYCLE_TICKS, SHINE_SWEEP_TICKS, STILL_TICK,
|
||||
};
|
||||
pub use wrap::{wrap_cells, wrap_line, wrap_lines, wrapped_row_starts};
|
||||
|
||||
|
||||
@@ -23,8 +23,11 @@
|
||||
//! wordmark in the flat accent and skip both rather than approximate them.
|
||||
|
||||
mod art;
|
||||
mod light;
|
||||
|
||||
use art::{column_groups, FULL_ART, LINE_ART, SMALL_ART};
|
||||
pub use light::smoothstep;
|
||||
use light::{blend_toward, Pass};
|
||||
use ratatui::layout::{Alignment, Rect};
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
@@ -194,14 +197,23 @@ impl Wordmark {
|
||||
/// A still is a frame of the same animation rather than a separate code path, so what a reader
|
||||
/// sees with `banner_animation = false` is a moment of what everyone else sees moving.
|
||||
pub fn lines(self, ink: WordmarkInk, tick: Option<u64>) -> Vec<Line<'static>> {
|
||||
let (tick, pass) = match tick {
|
||||
Some(tick) => (tick, Pass::at(self, ink, tick)),
|
||||
None => (STILL_TICK, None),
|
||||
};
|
||||
match tick {
|
||||
Some(tick) => self.lines_at(ink, tick, Some(tick)),
|
||||
None => self.lines_at(ink, STILL_TICK, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The logotype's rows with each light set on its own: the drift at `drift`, and the shine at
|
||||
/// `shine`, or none when that is `None`.
|
||||
///
|
||||
/// The terminal runs both from one clock and keeps them out of step on purpose, so its pattern
|
||||
/// takes minutes to repeat. A recording has to loop, so it sets the two to meet.
|
||||
pub fn lines_at(self, ink: WordmarkInk, drift: u64, shine: Option<u64>) -> Vec<Line<'static>> {
|
||||
let pass = shine.and_then(|tick| Pass::at(self, ink, tick));
|
||||
self.rows()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(row, text)| self.row_line(text, row as u16, ink, tick, pass.as_ref()))
|
||||
.map(|(row, text)| self.row_line(text, row as u16, ink, drift, pass.as_ref()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -412,78 +424,13 @@ pub fn render_wordmark(
|
||||
pub const SHINE_SWEEP_TICKS: u64 = SWEEP_TICKS;
|
||||
/// One pass plus its rest, in ticks.
|
||||
pub const SHINE_CYCLE_TICKS: u64 = CYCLE_TICKS;
|
||||
/// One whole pass of the drift, in ticks.
|
||||
pub const DRIFT_PERIOD_TICKS: u64 = DRIFT_TICKS;
|
||||
/// Ticks between drift frames while no shine runs.
|
||||
pub const DRIFT_FRAME_TICKS: u64 = DRIFT_FRAME;
|
||||
|
||||
fn shine_active(tick: u64) -> bool {
|
||||
tick % CYCLE_TICKS < SWEEP_TICKS
|
||||
}
|
||||
|
||||
/// One tick of one pass: where the highlight band sits, and how hard it pushes.
|
||||
struct Pass {
|
||||
center: f32,
|
||||
half: f32,
|
||||
peak: f32,
|
||||
lean: f32,
|
||||
}
|
||||
|
||||
impl Pass {
|
||||
/// The pass in flight at `tick`, or `None` while the logotype rests.
|
||||
fn at(size: Wordmark, ink: WordmarkInk, tick: u64) -> Option<Self> {
|
||||
let phase = tick % CYCLE_TICKS;
|
||||
if phase >= SWEEP_TICKS {
|
||||
return None;
|
||||
}
|
||||
let span = size.span();
|
||||
let half = (span * BAND).max(1.0);
|
||||
let travel = span + 2.0 * half;
|
||||
let progress = phase as f32 / SWEEP_TICKS as f32;
|
||||
|
||||
Some(Self {
|
||||
// The band starts and ends clear of the letters, so a pass arrives and leaves rather
|
||||
// than appearing half-drawn across them.
|
||||
center: -half + progress * travel,
|
||||
half,
|
||||
peak: if ink.dark { PEAK_DARK } else { PEAK_LIGHT },
|
||||
lean: LEAN,
|
||||
})
|
||||
}
|
||||
|
||||
/// How far this cell is lifted toward the highlight.
|
||||
fn lift(&self, column: u16, row: u16) -> f32 {
|
||||
let axis = f32::from(column) + self.lean * f32::from(row);
|
||||
let distance = ((axis - self.center).abs() / self.half).min(1.0);
|
||||
smoothstep(1.0 - distance) * self.peak
|
||||
}
|
||||
}
|
||||
|
||||
/// Smooth 0→1 with zero slope at both ends, so a band edge has no seam.
|
||||
///
|
||||
/// The shape of the highlight, and the whole reason it reads as light rather than as a stripe: a
|
||||
/// linear falloff leaves a crease along the ridge and a hard shoulder at each edge. Public so the
|
||||
/// website samples this curve rather than approximating it.
|
||||
pub fn smoothstep(t: f32) -> f32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// Alpha-blend `base` `amount` of the way toward `target`.
|
||||
///
|
||||
/// An ANSI/indexed palette has no channels to mix, so an unblendable color comes back untouched
|
||||
/// rather than as an invented RGB approximation of the terminal's own.
|
||||
fn blend_toward(base: Color, target: Color, amount: f32) -> Color {
|
||||
let (Color::Rgb(red, green, blue), Color::Rgb(tr, tg, tb)) = (base, target) else {
|
||||
return base;
|
||||
};
|
||||
if amount <= 0.0 {
|
||||
return base;
|
||||
}
|
||||
let amount = amount.clamp(0.0, 1.0);
|
||||
let lift = |channel: u8, toward: u8| {
|
||||
(f32::from(channel) + (f32::from(toward) - f32::from(channel)) * amount)
|
||||
.round()
|
||||
.clamp(0.0, 255.0) as u8
|
||||
};
|
||||
Color::Rgb(lift(red, tr), lift(green, tg), lift(blue, tb))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
75
crates/luxe-tui/src/widgets/wordmark/light.rs
Normal file
75
crates/luxe-tui/src/widgets/wordmark/light.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
//! Light — the shine's band, the curve it falls off along, and the blend both lights paint with.
|
||||
//!
|
||||
//! The math of the two lights on their own, apart from the art they land on: the parent decides
|
||||
//! which cells are ink and asks here how far each one is lifted.
|
||||
|
||||
use super::{Wordmark, WordmarkInk, BAND, CYCLE_TICKS, LEAN, PEAK_DARK, PEAK_LIGHT, SWEEP_TICKS};
|
||||
use ratatui::style::Color;
|
||||
|
||||
/// One tick of one pass: where the highlight band sits, and how hard it pushes.
|
||||
pub(super) struct Pass {
|
||||
center: f32,
|
||||
half: f32,
|
||||
peak: f32,
|
||||
lean: f32,
|
||||
}
|
||||
|
||||
impl Pass {
|
||||
/// The pass in flight at `tick`, or `None` while the logotype rests.
|
||||
pub(super) fn at(size: Wordmark, ink: WordmarkInk, tick: u64) -> Option<Self> {
|
||||
let phase = tick % CYCLE_TICKS;
|
||||
if phase >= SWEEP_TICKS {
|
||||
return None;
|
||||
}
|
||||
let span = size.span();
|
||||
let half = (span * BAND).max(1.0);
|
||||
let travel = span + 2.0 * half;
|
||||
let progress = phase as f32 / SWEEP_TICKS as f32;
|
||||
|
||||
Some(Self {
|
||||
// The band starts and ends clear of the letters, so a pass arrives and leaves rather
|
||||
// than appearing half-drawn across them.
|
||||
center: -half + progress * travel,
|
||||
half,
|
||||
peak: if ink.dark { PEAK_DARK } else { PEAK_LIGHT },
|
||||
lean: LEAN,
|
||||
})
|
||||
}
|
||||
|
||||
/// How far this cell is lifted toward the highlight.
|
||||
pub(super) fn lift(&self, column: u16, row: u16) -> f32 {
|
||||
let axis = f32::from(column) + self.lean * f32::from(row);
|
||||
let distance = ((axis - self.center).abs() / self.half).min(1.0);
|
||||
smoothstep(1.0 - distance) * self.peak
|
||||
}
|
||||
}
|
||||
|
||||
/// Smooth 0→1 with zero slope at both ends, so a band edge has no seam.
|
||||
///
|
||||
/// The shape of the highlight, and the whole reason it reads as light rather than as a stripe: a
|
||||
/// linear falloff leaves a crease along the ridge and a hard shoulder at each edge. Public so the
|
||||
/// website samples this curve rather than approximating it.
|
||||
pub fn smoothstep(t: f32) -> f32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// Alpha-blend `base` `amount` of the way toward `target`.
|
||||
///
|
||||
/// An ANSI/indexed palette has no channels to mix, so an unblendable color comes back untouched
|
||||
/// rather than as an invented RGB approximation of the terminal's own.
|
||||
pub(super) fn blend_toward(base: Color, target: Color, amount: f32) -> Color {
|
||||
let (Color::Rgb(red, green, blue), Color::Rgb(tr, tg, tb)) = (base, target) else {
|
||||
return base;
|
||||
};
|
||||
if amount <= 0.0 {
|
||||
return base;
|
||||
}
|
||||
let amount = amount.clamp(0.0, 1.0);
|
||||
let lift = |channel: u8, toward: u8| {
|
||||
(f32::from(channel) + (f32::from(toward) - f32::from(channel)) * amount)
|
||||
.round()
|
||||
.clamp(0.0, 255.0) as u8
|
||||
};
|
||||
Color::Rgb(lift(red, tr), lift(green, tg), lift(blue, tb))
|
||||
}
|
||||
@@ -517,3 +517,43 @@ fn the_pane_wraps_long_lines_without_being_asked() {
|
||||
assert!(!clipped.contains(tail), "clipped now: {clipped}");
|
||||
assert!(clipped.contains('…'), "and marked as clipped: {clipped}");
|
||||
}
|
||||
|
||||
/// The header's position is whole or absent, never `8 of`: the path is what gives way, and a gap
|
||||
/// always parts the line counts from the FILE / DIFF switch. The path used to be measured against
|
||||
/// everything but the switch, so the line ran long and lost its last part, the position.
|
||||
#[test]
|
||||
fn the_changes_header_keeps_its_position_whole_and_its_switch_apart() {
|
||||
use luxe_tui::fixture::FixtureScenario::{ChangesNarrow, ChangesWide};
|
||||
// Below about 128 columns the dock lies over the pane, so narrower widths drop the dock
|
||||
let wide = [(ChangesWide, 172u16), (ChangesWide, 140)];
|
||||
for (scenario, width) in wide.into_iter().chain((44..=110).map(|width| (ChangesNarrow, width)))
|
||||
{
|
||||
let (buffer, row, text) = changes_header(scenario, width);
|
||||
let end = text.trim_end();
|
||||
let cut = [" 8", " 8 o", " 8 of", " 8 of 1"].iter().any(|cut| end.ends_with(cut));
|
||||
assert!(!cut, "{width}: the position was cut: {text}");
|
||||
// Plain background in the two cells after the counts, before the FILE slab begins
|
||||
let counts = column_of(&text, "−9");
|
||||
let plain = buffer[(counts - 1, row)].bg;
|
||||
for x in counts + 2..counts + 4 {
|
||||
assert_eq!(buffer[(x, row)].bg, plain, "{width}: no gap before the switch: {text}");
|
||||
}
|
||||
}
|
||||
// As wide as the guide's shot, the position shows
|
||||
let wide = changes_header(ChangesWide, 172).2;
|
||||
assert!(wide.contains("8 of 14"), "{wide}");
|
||||
}
|
||||
|
||||
/// A guide diff scene at `width` columns: the frame, its header row, and that row's text.
|
||||
fn changes_header(
|
||||
scenario: luxe_tui::fixture::FixtureScenario,
|
||||
width: u16,
|
||||
) -> (ratatui::buffer::Buffer, u16, String) {
|
||||
let backend = test_backend(width, 50);
|
||||
let mut app = luxe_tui::fixture::seeded_app("luxe", scenario).expect("the fixture");
|
||||
app.update(Msg::TerminalResized { width, height: 50 });
|
||||
let buffer = render_app(&mut app, &backend);
|
||||
let row = row_containing(&buffer, "DIFF", width, 50);
|
||||
let text = row_text(&buffer, row, width);
|
||||
(buffer, row, text)
|
||||
}
|
||||
|
||||
@@ -11,14 +11,12 @@ On macOS and Linux, the install script puts `luxe` in `~/.local/bin`, or in `$LU
|
||||
when it is set, and adds that to your `PATH`:
|
||||
|
||||
```bash
|
||||
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
|
||||
```
|
||||
|
||||
On Windows, in PowerShell:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -c "irm https://github.com/evanwhittaker/luxe/releases/latest/download/luxe-cli-installer.ps1 | iex"
|
||||
```
|
||||
That address redirects to the script on the [latest
|
||||
release](https://github.com/evanwhittaker/luxe/releases/latest), the one it built and attested. To
|
||||
read it before running it, drop the `| sh`.
|
||||
|
||||
With Homebrew, on macOS or Linux:
|
||||
|
||||
@@ -33,6 +31,16 @@ one):
|
||||
cargo install --locked luxe-cli
|
||||
```
|
||||
|
||||
On Windows, in PowerShell:
|
||||
|
||||
```powershell
|
||||
powershell -c "irm https://luxe.dev/install.ps1 | iex"
|
||||
```
|
||||
|
||||
[That script](https://luxe.dev/install.ps1) is two lines: it lets this PowerShell window run the
|
||||
release's installer, which Windows' default execution policy would stop, then runs it. Nothing
|
||||
about your policy is saved.
|
||||
|
||||
Any of them installs the `luxe` command; `luxe --version` checks it worked.
|
||||
|
||||
To update, run `luxe update`, or `/update` inside Luxe. Luxe checks once a day for a newer release
|
||||
|
||||
@@ -13,7 +13,7 @@ group: "Using Luxe"
|
||||
| `write`, `edit` | Write or change a file. A file must be read before it is edited, and the card shows the diff, after [formatting](#format-on-save). |
|
||||
| `bash` | Run a shell command. Long output is trimmed, and the untouched output saved under `.luxe/artifacts/`: each stream whole up to 8 MB, or its first and last 4 MB past that. |
|
||||
| `test` | Run the project's tests and report each failure with its `file:line`, and which tests your change broke. Output is saved as `bash`'s is. |
|
||||
| `grep`, `glob` | Search file contents and names, with capped output |
|
||||
| `grep`, `glob` | Search file contents and names, with capped output. `grep` names each file once with its matching lines under it, and can say which function or type each match sits in. |
|
||||
| `ast_grep` | Search and replace by code structure. Needs [ast-grep](https://ast-grep.github.io). |
|
||||
| `git` | Status, diffs, history, commits, branches, and GitHub pull requests, issues and CI checks through `gh` |
|
||||
| `todo` | The agent's checklist, shown in the dock's **PLAN** |
|
||||
|
||||
54
scripts/aur-pkgbuild.sh
Executable file
54
scripts/aur-pkgbuild.sh
Executable file
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# aur-pkgbuild — writes the PKGBUILD for the `luxe-bin` AUR package from a release.
|
||||
#
|
||||
# Usage: scripts/aur-pkgbuild.sh <version> [out-dir] e.g. scripts/aur-pkgbuild.sh 0.1.0 /tmp/aur
|
||||
#
|
||||
# `luxe-bin` repackages the release's own Linux archives, checked against the release's `.sha256`
|
||||
# files, so it ships exactly what the release built and attested. It installs to /usr/bin, which
|
||||
# `luxe update` reads as a package manager's copy and leaves to pacman. The updater the install
|
||||
# script adds is left out for the same reason. Generate .SRCINFO from the result with
|
||||
# `makepkg --printsrcinfo > .SRCINFO`.
|
||||
set -euo pipefail
|
||||
|
||||
version="${1:?usage: aur-pkgbuild.sh <version> [out-dir]}"
|
||||
out="${2:-.}"
|
||||
release="https://github.com/evanwhittaker/luxe/releases/download/v${version}"
|
||||
|
||||
# The release's own checksum for one target's archive
|
||||
checksum() {
|
||||
curl -fsSL "${release}/luxe-cli-$1-unknown-linux-gnu.tar.xz.sha256" | cut -d' ' -f1
|
||||
}
|
||||
x86_64="$(checksum x86_64)"
|
||||
aarch64="$(checksum aarch64)"
|
||||
|
||||
mkdir -p "${out}"
|
||||
cat >"${out}/PKGBUILD" <<PKGBUILD
|
||||
# Maintainer: Evan Whittaker <contact@luxe.dev>
|
||||
# Generated by scripts/aur-pkgbuild.sh in https://github.com/evanwhittaker/luxe
|
||||
|
||||
pkgname=luxe-bin
|
||||
pkgver=${version}
|
||||
pkgrel=1
|
||||
pkgdesc="A terminal coding agent: streaming chat, tools, guided diff review, and LSP/DAP code intelligence"
|
||||
arch=('x86_64' 'aarch64')
|
||||
url="https://luxe.dev"
|
||||
license=('MIT' 'Apache-2.0')
|
||||
depends=('gcc-libs' 'glibc')
|
||||
provides=('luxe')
|
||||
conflicts=('luxe')
|
||||
# The release's binary as it was built and attested: not stripped again, no debug split
|
||||
options=('!strip' '!debug')
|
||||
source_x86_64=("luxe-cli-x86_64-\${pkgver}.tar.xz::https://github.com/evanwhittaker/luxe/releases/download/v\${pkgver}/luxe-cli-x86_64-unknown-linux-gnu.tar.xz")
|
||||
source_aarch64=("luxe-cli-aarch64-\${pkgver}.tar.xz::https://github.com/evanwhittaker/luxe/releases/download/v\${pkgver}/luxe-cli-aarch64-unknown-linux-gnu.tar.xz")
|
||||
sha256sums_x86_64=('${x86_64}')
|
||||
sha256sums_aarch64=('${aarch64}')
|
||||
|
||||
package() {
|
||||
cd "luxe-cli-\${CARCH}-unknown-linux-gnu"
|
||||
install -Dm755 luxe "\${pkgdir}/usr/bin/luxe"
|
||||
install -Dm644 LICENSE-MIT "\${pkgdir}/usr/share/licenses/\${pkgname}/LICENSE-MIT"
|
||||
install -Dm644 LICENSE-APACHE "\${pkgdir}/usr/share/licenses/\${pkgname}/LICENSE-APACHE"
|
||||
install -Dm644 README.md "\${pkgdir}/usr/share/doc/\${pkgname}/README.md"
|
||||
}
|
||||
PKGBUILD
|
||||
echo "wrote ${out}/PKGBUILD for luxe-bin ${version}"
|
||||
@@ -140,28 +140,9 @@ wordmark() { cargo run --quiet --release -p luxe-tui --example wordmark_svg -- "
|
||||
tokens() { cargo run --quiet --release -p luxe-tui --example theme_css; }
|
||||
catalog() { cargo run --quiet --release -p luxe-tui --example theme_css -- --json; }
|
||||
shiki() { cargo run --quiet --release -p luxe-tui --example shiki_theme -- "$@"; }
|
||||
|
||||
# The README's wordmark. GitHub shows an image on its own, where the CSS variables the site paints
|
||||
# the letters with do not exist and every letter would fall back to black, so this copy carries
|
||||
# the theme's own colors and its background: the same on GitHub's light pages as on its dark ones.
|
||||
banner() {
|
||||
python3 - "$1/wordmark.svg" "$1/tokens.css" <<'PY'
|
||||
import re, sys
|
||||
svg, css = (open(path).read() for path in sys.argv[1:])
|
||||
color = lambda name: re.search(rf"--luxe-{name}:\s*(#[0-9a-f]{{6}})", css).group(1)
|
||||
svg = re.sub(r"var\(--luxe-(wordmark-\d), currentColor\)", lambda m: color(m.group(1)), svg)
|
||||
width, height = (int(n) for n in re.search(r'viewBox="0 0 (\d+) (\d+)"', svg).groups())
|
||||
pad_x, pad_y = 120, 72
|
||||
box = (width + 2 * pad_x, height + 2 * pad_y)
|
||||
svg = re.sub(
|
||||
r'viewBox="[^"]*" width="\d+" height="\d+"',
|
||||
f'viewBox="{-pad_x} {-pad_y} {box[0]} {box[1]}" width="{box[0]}" height="{box[1]}"',
|
||||
svg,
|
||||
)
|
||||
background = f'<rect x="{-pad_x}" y="{-pad_y}" width="{box[0]}" height="{box[1]}" rx="16" fill="{color("background")}"/>'
|
||||
print(svg.replace("</title>", "</title>\n " + background, 1), end="")
|
||||
PY
|
||||
}
|
||||
# The README's wordmark, animated as the terminal lights it, transparent for GitHub's light and dark
|
||||
# pages alike. Two variants: a light page washes the shine out sooner, so it gets the gentler one
|
||||
wordmark_gif() { cargo run --quiet --release -p luxe-tui --example wordmark_gif -- "$@"; }
|
||||
|
||||
generate() {
|
||||
local target="$1" guide_target="$2"
|
||||
@@ -171,7 +152,8 @@ generate() {
|
||||
wordmark mark >"${target}/mark.svg"
|
||||
wordmark tile >"${target}/tile.svg"
|
||||
tokens >"${target}/tokens.css"
|
||||
banner "${target}" >"${target}/wordmark-banner.svg"
|
||||
wordmark_gif dark >"${target}/wordmark-dark.gif"
|
||||
wordmark_gif light >"${target}/wordmark-light.gif"
|
||||
catalog >"${target}/themes.json"
|
||||
facts "${target}" >"${target}/facts.json"
|
||||
shiki luxe >"${target}/shiki-luxe.json"
|
||||
@@ -211,7 +193,8 @@ print(','.join(['luxe'] + names))
|
||||
# One release build up front. Every generator is a separate `cargo run`, and letting each discover
|
||||
# that for itself turns a five-second job into a minute of cargo deciding it has nothing to do.
|
||||
cargo build --quiet --release -p luxe-tui --features fixture \
|
||||
--example fixture_svg --example wordmark_svg --example theme_css --example shiki_theme
|
||||
--example fixture_svg --example wordmark_svg --example wordmark_gif --example theme_css \
|
||||
--example shiki_theme
|
||||
|
||||
if [[ "${check}" == true ]]; then
|
||||
scratch="$(mktemp -d)"
|
||||
|
||||
@@ -24,6 +24,10 @@
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
Access-Control-Allow-Origin: *
|
||||
|
||||
# Text, so `irm` hands `iex` a script rather than bytes
|
||||
/install.ps1
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
|
||||
/*
|
||||
Cache-Control: public, max-age=0, must-revalidate
|
||||
X-Content-Type-Options: nosniff
|
||||
|
||||
@@ -3,3 +3,9 @@
|
||||
# The themes page folded into the homepage's gallery; a link to it lands on the gallery.
|
||||
/themes /#craft 301
|
||||
/themes/ /#craft 301
|
||||
|
||||
# The install script, at an address short enough to read: `curl -fsSL https://luxe.dev/install.sh | sh`.
|
||||
# It redirects to the latest release's own script, so luxe.dev never holds a copy that could drift
|
||||
# from what the release built and attested. 302, not 301: "latest" moves, so nothing may cache it.
|
||||
# /install.ps1 is a file instead (public/install.ps1): Windows needs a line run before the installer.
|
||||
/install.sh https://github.com/evanwhittaker/luxe/releases/latest/download/luxe-cli-installer.sh 302
|
||||
|
||||
14
web/public/install.ps1
Normal file
14
web/public/install.ps1
Normal file
@@ -0,0 +1,14 @@
|
||||
# Luxe's installer for Windows:
|
||||
#
|
||||
# powershell -c "irm https://luxe.dev/install.ps1 | iex"
|
||||
#
|
||||
# The installer each release ships refuses to run under Windows' default execution policy, which is
|
||||
# why its own instructions pass `-ExecutionPolicy ByPass`. This does the same for this PowerShell
|
||||
# process alone, with nothing saved and no admin needed, then runs the latest release's installer,
|
||||
# so the address never holds an installer that could drift from what the release built.
|
||||
#
|
||||
# A policy set by Group Policy outranks the process scope, as it outranks the command-line flag.
|
||||
# Setting it then fails, and that is let pass: where the enforced policy allows the installer it runs
|
||||
# anyway, and where it does not, the installer's own check says so and how to fix it.
|
||||
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue
|
||||
Invoke-RestMethod 'https://github.com/evanwhittaker/luxe/releases/latest/download/luxe-cli-installer.ps1' | Invoke-Expression
|
||||
@@ -5,14 +5,14 @@
|
||||
<rect x="100" y="0" width="10" height="22" fill="#aa9467"/>
|
||||
<rect x="110" y="0" width="10" height="22" fill="#786849"/>
|
||||
<rect x="120" y="0" width="10" height="22" fill="#453c2c"/>
|
||||
<rect x="860" y="0" width="70" height="22" fill="#2f2d2a"/>
|
||||
<rect x="930" y="0" width="10" height="22" fill="#282623"/>
|
||||
<rect x="940" y="0" width="10" height="22" fill="#211f1c"/>
|
||||
<rect x="950" y="0" width="10" height="22" fill="#191715"/>
|
||||
<rect x="970" y="0" width="70" height="22" fill="#8c7a55"/>
|
||||
<rect x="1040" y="0" width="10" height="22" fill="#6e6043"/>
|
||||
<rect x="1050" y="0" width="10" height="22" fill="#4f4532"/>
|
||||
<rect x="1060" y="0" width="10" height="22" fill="#312b20"/>
|
||||
<rect x="840" y="0" width="70" height="22" fill="#2f2d2a"/>
|
||||
<rect x="910" y="0" width="10" height="22" fill="#282623"/>
|
||||
<rect x="920" y="0" width="10" height="22" fill="#211f1c"/>
|
||||
<rect x="930" y="0" width="10" height="22" fill="#191715"/>
|
||||
<rect x="950" y="0" width="70" height="22" fill="#8c7a55"/>
|
||||
<rect x="1020" y="0" width="10" height="22" fill="#6e6043"/>
|
||||
<rect x="1030" y="0" width="10" height="22" fill="#4f4532"/>
|
||||
<rect x="1040" y="0" width="10" height="22" fill="#312b20"/>
|
||||
<rect x="0" y="88" width="70" height="22" fill="#8c7a55"/>
|
||||
<rect x="70" y="88" width="10" height="22" fill="#6e6043"/>
|
||||
<rect x="80" y="88" width="10" height="22" fill="#4f4532"/>
|
||||
@@ -552,7 +552,7 @@
|
||||
<path fill="none" stroke="#ddc084" stroke-width="1.25" d="M1705.00 1089.00L1710.00 1089.00M1705.00 1089.00L1700.00 1089.00"/>
|
||||
<path fill="none" stroke="#ddc084" stroke-width="1.25" d="M1715.00 1078.00Q1715.00 1089.00 1710.00 1089.00"/>
|
||||
</g>
|
||||
<text x="0" y="17.0" textLength="1720" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan fill="#12100e" font-weight="700">PROJECT</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan fill="#faaa51">M </tspan><tspan fill="#e4dfd6" font-weight="700">crates/luxe-tui/src/view/dock.rs</tspan><tspan fill="#81caa0"> +48</tspan><tspan fill="#e68485"> −9</tspan><tspan> </tspan><tspan fill="#97938c">FILE</tspan><tspan> </tspan><tspan fill="#e4dfd6" font-weight="700">DIFF</tspan><tspan> </tspan><tspan fill="#97938c">8 of </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
|
||||
<text x="0" y="17.0" textLength="1720" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan fill="#12100e" font-weight="700">PROJECT</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan fill="#faaa51">M </tspan><tspan fill="#e4dfd6" font-weight="700">…s/luxe-tui/src/view/dock.rs</tspan><tspan fill="#81caa0"> +48</tspan><tspan fill="#e68485"> −9</tspan><tspan> </tspan><tspan fill="#97938c">FILE</tspan><tspan> </tspan><tspan fill="#e4dfd6" font-weight="700">DIFF</tspan><tspan> </tspan><tspan fill="#97938c">8 of 14</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
|
||||
<text x="0" y="39.0" textLength="1720" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan fill="#e4dfd6"> luxe </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
|
||||
<text x="0" y="61.0" textLength="1720" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan fill="#97938c"> feature/context-dock *</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan fill="#ddc084">@@ -140,6 +140,8 @@ fn change_lines</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
|
||||
<text x="0" y="83.0" textLength="1720" lengthAdjust="spacingAndGlyphs" xml:space="preserve"><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan><tspan fill="#97938c">140 140 </tspan><tspan> </tspan><tspan fill="#d2a5cd">let</tspan><tspan fill="#e4dfd6"> seen </tspan><tspan fill="#97938c">=</tspan><tspan fill="#e4dfd6"> app.review.seen.</tspan><tspan fill="#ddc084">as_ref</tspan><tspan fill="#97938c">();</tspan><tspan> </tspan><tspan> </tspan><tspan> </tspan></text>
|
||||
|
||||
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 89 KiB |
@@ -1,9 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-120 -72 680 298" width="680" height="298" data-cell="10 22" role="img" aria-label="Luxe">
|
||||
<title>Luxe</title>
|
||||
<rect x="-120" y="-72" width="680" height="298" rx="16" fill="#12100e"/>
|
||||
<path fill="#6d5f43" d="M10 11h10v11h-10z M20 11h10v11h-10z M30 11h10v11h-10z M40 11h10v11h-10z M10 22h10v11h-10z M20 22h10v11h-10z M30 22h20v22h-20z M30 44h20v22h-20z M30 66h20v22h-20z M30 88h20v22h-20z M30 110h20v22h-20z M50 121h10v11h-10z M60 121h10v11h-10z M70 121h10v11h-10z M40 132h10v11h-10z M50 132h10v11h-10z M60 132h10v11h-10z M70 132h10v11h-10z"/>
|
||||
<path fill="#7e6d4d" d="M110 44h20v22h-20z M170 44h20v22h-20z M110 66h20v22h-20z M170 66h20v22h-20z M110 88h20v22h-20z M170 88h20v22h-20z M110 110h20v22h-20z M130 121h10v11h-10z M140 121h10v11h-10z M150 121h10v11h-10z M160 110h30v22h-30z M120 132h10v11h-10z M130 132h10v11h-10z M140 132h10v11h-10z M150 132h10v11h-10z M170 132h10v11h-10z M180 132h10v11h-10z"/>
|
||||
<path fill="#a59064" d="M210 44h10v11h-10z M220 44h20v22h-20z M260 44h20v22h-20z M280 44h10v11h-10z M230 66h40v22h-40z M230 99h10v11h-10z M240 88h20v22h-20z M260 99h10v11h-10z M220 121h10v11h-10z M230 110h10v22h-10z M240 110h10v11h-10z M250 110h10v11h-10z M260 110h10v22h-10z M270 121h10v11h-10z M210 132h10v11h-10z M220 132h10v11h-10z M230 132h10v11h-10z M260 132h10v11h-10z M270 132h10v11h-10z M280 132h10v11h-10z"/>
|
||||
<path fill="#cdb27a" d="M320 55h10v11h-10z M330 44h40v22h-40z M370 55h10v11h-10z M310 66h20v22h-20z M330 77h10v11h-10z M340 77h10v11h-10z M350 77h10v11h-10z M360 77h10v11h-10z M370 66h20v22h-20z M310 88h20v22h-20z M330 88h10v11h-10z M340 88h10v11h-10z M350 88h10v11h-10z M360 88h10v11h-10z M370 88h10v11h-10z M380 88h10v11h-10z M310 110h10v11h-10z M320 110h20v22h-20z M340 121h10v11h-10z M350 121h10v11h-10z M360 121h10v11h-10z M370 121h10v11h-10z M380 110h10v22h-10z M330 132h10v11h-10z M340 132h10v11h-10z M350 132h10v11h-10z M360 132h10v11h-10z M370 132h10v11h-10z"/>
|
||||
<path fill="#ddc084" d="M420 110h20v22h-20z M420 132h10v11h-10z M430 132h10v11h-10z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.0 KiB |
BIN
web/src/assets/generated/wordmark-dark.gif
Normal file
BIN
web/src/assets/generated/wordmark-dark.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 482 KiB |
BIN
web/src/assets/generated/wordmark-light.gif
Normal file
BIN
web/src/assets/generated/wordmark-light.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 478 KiB |
@@ -3,20 +3,13 @@
|
||||
|
||||
type Channel = { id: string; label: string; command: string; note?: string };
|
||||
|
||||
const releases = "https://github.com/evanwhittaker/luxe/releases/latest/download";
|
||||
// Most likely reader first. install.sh redirects to the latest release's script and install.ps1
|
||||
// runs it (web/public/_redirects, web/public/install.ps1)
|
||||
const channels: Channel[] = [
|
||||
{
|
||||
id: "shell",
|
||||
label: "shell",
|
||||
command: `curl --proto '=https' --tlsv1.2 -LsSf ${releases}/luxe-cli-installer.sh | sh`,
|
||||
},
|
||||
{ id: "shell", label: "shell", command: "curl -fsSL https://luxe.dev/install.sh | sh" },
|
||||
{ id: "brew", label: "brew", command: "brew install evanwhittaker/tap/luxe" },
|
||||
{
|
||||
id: "windows",
|
||||
label: "windows",
|
||||
command: `powershell -ExecutionPolicy Bypass -c "irm ${releases}/luxe-cli-installer.ps1 | iex"`,
|
||||
},
|
||||
{ id: "cargo", label: "cargo", command: "cargo install --locked luxe-cli" },
|
||||
{ id: "windows", label: "windows", command: 'powershell -c "irm https://luxe.dev/install.ps1 | iex"' },
|
||||
];
|
||||
|
||||
let active = $state(channels[0]);
|
||||
|
||||
@@ -31,8 +31,8 @@
|
||||
},
|
||||
"shellBytes": 4384,
|
||||
"shellLines": 56,
|
||||
"toolBytes": 4383,
|
||||
"toolLines": 56,
|
||||
"toolBytes": 3989,
|
||||
"toolLines": 100,
|
||||
"forwarded": {
|
||||
"pi": 4383,
|
||||
"opencode": 4383,
|
||||
|
||||
@@ -65,7 +65,7 @@ const groups: Group[] = [
|
||||
name: "grep",
|
||||
instead: "`grep -rn`, `rg`",
|
||||
bench: "grep",
|
||||
text: "Capped per file and overall, with long lines trimmed. It can return just the files that match or just the counts, and says so when there's more.",
|
||||
text: "Names each file once with its lines under it, where `rg` repeats the path on every line. Asked to, it says which function or type each match sits in. Skips what read policy denies, caps per file and overall, and says when there's more.",
|
||||
},
|
||||
{
|
||||
name: "ast_grep",
|
||||
@@ -249,7 +249,8 @@ const terminal = ["git", "module_report", "glob"].flatMap((id) => rows.get(id) ?
|
||||
|
||||
const times = (shell: number, tool: number) => {
|
||||
const ratio = shell / tool;
|
||||
if (ratio < 1.1) return "the same";
|
||||
// Under a tenth less, a multiple reads as "1.0×", so a real saving is given as a share
|
||||
if (ratio < 1.1) return tool <= shell * 0.95 ? `${Math.round((1 - tool / shell) * 100)}% less` : "the same";
|
||||
return ratio < 10 ? `${ratio.toFixed(1)}× less` : `${Math.round(ratio).toLocaleString("en-US")}× less`;
|
||||
};
|
||||
/** Luxe against the tightest cut another agent makes, said both ways round. */
|
||||
@@ -269,20 +270,20 @@ type CostRow = { model: string; luxe: { passed: number; runs: number } } & Parti
|
||||
Record<"claude" | "codex" | "opencode", Other>
|
||||
>;
|
||||
const costRows = agentCost.rows as CostRow[];
|
||||
const vendorAgent = (row: CostRow) => row.claude ?? row.codex;
|
||||
const multiple = (other?: Other) => (other ? `${other.cold.toFixed(2)}×` : "–");
|
||||
|
||||
/** The chart's scale: the costliest multiple, rounded up to a half, so 1× (Luxe) sits at a fixed mark. */
|
||||
const chartScale =
|
||||
Math.ceil(
|
||||
Math.max(...costRows.flatMap((row) => [vendorAgent(row)?.cold ?? 0, row.opencode?.cold ?? 0])) * 2,
|
||||
) / 2;
|
||||
const chartWidth = (multiple: number) => `${(multiple / chartScale) * 100}%`;
|
||||
/** Each model's bars: Luxe at 1×, then every agent that ran it. A vendor's agent runs only its own
|
||||
* vendor's models, so a model has Claude Code's bar or Codex's, never both. */
|
||||
const chartBars = (row: CostRow) =>
|
||||
[
|
||||
{ kind: "vendor", other: vendorAgent(row) },
|
||||
{ kind: "opencode", other: row.opencode },
|
||||
].flatMap(({ kind, other }) => (other ? [{ kind, cold: other.cold }] : []));
|
||||
{ kind: "luxe", label: "Luxe", cold: 1 },
|
||||
{ kind: "claude", label: "Claude Code", cold: row.claude?.cold },
|
||||
{ kind: "codex", label: "Codex", cold: row.codex?.cold },
|
||||
{ kind: "opencode", label: "OpenCode", cold: row.opencode?.cold },
|
||||
].flatMap((bar) => (bar.cold === undefined ? [] : [{ ...bar, cold: bar.cold }]));
|
||||
/** The chart's scale: the costliest multiple, rounded up to a half. */
|
||||
const chartScale = Math.ceil(Math.max(...costRows.flatMap(chartBars).map((bar) => bar.cold)) * 2) / 2;
|
||||
const chartWidth = (multiple: number) => `${(multiple / chartScale) * 100}%`;
|
||||
|
||||
/** A bar's share of its row, never so thin it disappears. */
|
||||
const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100, 0.6)}%`;
|
||||
@@ -361,11 +362,15 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
</p>
|
||||
</div>
|
||||
<div class="split split--tasks">
|
||||
{/* The table and its note are one column, so the note sits under what it qualifies rather
|
||||
than below whichever of table and chart runs longer */}
|
||||
<div class="tasks__data">
|
||||
<table class="costs">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Model</th>
|
||||
<th scope="col">Claude Code or Codex</th>
|
||||
<th scope="col">Claude Code</th>
|
||||
<th scope="col">Codex</th>
|
||||
<th scope="col">OpenCode</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -376,26 +381,33 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
<th scope="row">
|
||||
<code>{row.model}</code>
|
||||
</th>
|
||||
<td>{multiple(vendorAgent(row))}</td>
|
||||
<td>{multiple(row.claude)}</td>
|
||||
<td>{multiple(row.codex)}</td>
|
||||
<td>{multiple(row.opencode)}</td>
|
||||
</tr>
|
||||
))
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted note tasks__note">
|
||||
Every run is charged as a cold start, the way a session begins after a break. Run side by
|
||||
side on a warm cache, Claude Code and OpenCode cost up to 2.6× what Luxe does on Claude
|
||||
models. Claude Code runs only Claude models and Codex only OpenAI's, hence the dashes.
|
||||
Pass rates overlapped on every model. Graded on one machine rather than in
|
||||
SWE-bench's own containers, so these are not leaderboard scores. Measured at
|
||||
<code>{agentCost.commit}</code>.
|
||||
</p>
|
||||
</div>
|
||||
{/* The table's numbers drawn; hidden from screen readers, which have the table */}
|
||||
<figure class="chart" aria-hidden="true" style={`--one: ${chartWidth(1)}`}>
|
||||
<figcaption class="chart__legend">
|
||||
<span class="chart__key chart__key--vendor">Claude Code or Codex</span>
|
||||
<span class="chart__key chart__key--opencode">OpenCode</span>
|
||||
<span class="chart__key chart__key--luxe">Luxe, 1×</span>
|
||||
</figcaption>
|
||||
<figure class="chart" aria-hidden="true">
|
||||
<figcaption class="chart__caption">Cost of a whole task · lower is better</figcaption>
|
||||
{
|
||||
costRows.map((row) => (
|
||||
<div class="chart__group">
|
||||
<code class="chart__model">{row.model}</code>
|
||||
{chartBars(row).map(({ kind, cold }) => (
|
||||
{chartBars(row).map(({ kind, label, cold }) => (
|
||||
<div class={`chart__row chart__row--${kind}`}>
|
||||
<span class="chart__agent">{label}</span>
|
||||
<span class="chart__track">
|
||||
<span class="chart__bar" style={`width: ${chartWidth(cold)}`} />
|
||||
</span>
|
||||
@@ -407,14 +419,6 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
}
|
||||
</figure>
|
||||
</div>
|
||||
<div class="prose">
|
||||
<p class="muted note">
|
||||
Every run is charged as a cold start, the way a session begins after a break. Run side
|
||||
by side on a warm cache, Claude Code and OpenCode cost up to 2.6× what Luxe does on
|
||||
Claude models. Pass rates overlapped on every model. Graded on one machine rather than in SWE-bench's own containers, so these are not leaderboard
|
||||
scores. Measured at <code>{agentCost.commit}</code>.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{
|
||||
@@ -567,6 +571,18 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Four columns fit a phone only with less air between them */
|
||||
@media (max-width: 40rem) {
|
||||
.costs {
|
||||
font-size: var(--step--1);
|
||||
}
|
||||
|
||||
.costs th,
|
||||
.costs td {
|
||||
padding: var(--space-2);
|
||||
}
|
||||
}
|
||||
|
||||
.group__name {
|
||||
font-size: var(--step-2);
|
||||
margin-bottom: var(--space-5);
|
||||
@@ -622,6 +638,13 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
|
||||
.split--tasks .costs {
|
||||
margin-top: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* As wide as the table it qualifies, and no wider than a line should be */
|
||||
.tasks__note {
|
||||
max-width: var(--measure);
|
||||
margin: var(--space-4) 0 0;
|
||||
}
|
||||
|
||||
/* === The head's terminal === */
|
||||
@@ -647,12 +670,22 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
gap: 0.4em;
|
||||
}
|
||||
|
||||
/* macOS's window controls, in its own colors: close, minimize, zoom. Literal rather than theme
|
||||
tokens, since they draw a Mac window rather than Luxe */
|
||||
.terminal__dots i {
|
||||
display: inline-block;
|
||||
width: 0.6em;
|
||||
height: 0.6em;
|
||||
width: 0.7em;
|
||||
height: 0.7em;
|
||||
border-radius: 50%;
|
||||
background: var(--luxe-dim);
|
||||
background: #ff5f57;
|
||||
}
|
||||
|
||||
.terminal__dots i:nth-child(2) {
|
||||
background: #febc2e;
|
||||
}
|
||||
|
||||
.terminal__dots i:nth-child(3) {
|
||||
background: #28c840;
|
||||
}
|
||||
|
||||
.terminal__body {
|
||||
@@ -706,36 +739,10 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
font-size: var(--step--1);
|
||||
}
|
||||
|
||||
.chart__legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
.chart__caption {
|
||||
color: var(--luxe-muted);
|
||||
}
|
||||
|
||||
.chart__key::before {
|
||||
content: "";
|
||||
display: inline-block;
|
||||
width: 0.8em;
|
||||
height: 0.8em;
|
||||
margin-right: 0.5em;
|
||||
vertical-align: -0.05em;
|
||||
}
|
||||
|
||||
.chart__key--vendor::before {
|
||||
background: var(--luxe-dim);
|
||||
}
|
||||
|
||||
.chart__key--opencode::before {
|
||||
background: var(--luxe-muted);
|
||||
}
|
||||
|
||||
.chart__key--luxe::before {
|
||||
width: 2px;
|
||||
height: 1em;
|
||||
background: var(--luxe-accent);
|
||||
}
|
||||
|
||||
.chart__group {
|
||||
display: grid;
|
||||
gap: 0.3em;
|
||||
@@ -745,36 +752,42 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
|
||||
color: var(--luxe-accent);
|
||||
}
|
||||
|
||||
/* Each bar says whose it is, so no legend is needed to read it */
|
||||
.chart__row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 4rem;
|
||||
grid-template-columns: 7.5rem minmax(0, 1fr) 4rem;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.chart__agent {
|
||||
color: var(--luxe-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chart__row--luxe .chart__agent,
|
||||
.chart__row--luxe .chart__value {
|
||||
color: var(--luxe-accent);
|
||||
}
|
||||
|
||||
.chart__track {
|
||||
position: relative;
|
||||
height: 0.9rem;
|
||||
background: var(--luxe-user-msg-bg);
|
||||
}
|
||||
|
||||
/* Luxe's 1×, drawn through every row: each bar is read against it */
|
||||
.chart__track::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -0.2rem;
|
||||
bottom: -0.2rem;
|
||||
left: var(--one);
|
||||
width: 2px;
|
||||
background: var(--luxe-accent);
|
||||
}
|
||||
|
||||
.chart__bar {
|
||||
display: block;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.chart__row--vendor .chart__bar {
|
||||
.chart__row--luxe .chart__bar {
|
||||
background: var(--luxe-accent);
|
||||
}
|
||||
|
||||
/* A vendor's own agent; Claude Code and Codex never share a model, so they share a shade */
|
||||
.chart__row--claude .chart__bar,
|
||||
.chart__row--codex .chart__bar {
|
||||
background: var(--luxe-dim);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user