Compare commits
11 Commits
v0.1.5
...
feat/usage
| Author | SHA1 | Date | |
|---|---|---|---|
|
7f15a1a19f
|
|||
|
408d48783a
|
|||
|
|
44a62bcdd6 | ||
|
|
69b3314823 | ||
|
|
2a5ab000a0 | ||
|
|
6e0d7252a7 | ||
|
|
fe34822d57 | ||
|
|
3f43461e6c | ||
|
|
8472877340 | ||
|
|
9a59d61776 | ||
|
|
9194448459 |
85
.github/workflows/ci.yml
vendored
85
.github/workflows/ci.yml
vendored
@@ -51,6 +51,8 @@ jobs:
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
code: ${{ steps.diff.outputs.code }}
|
||||
web_playwright: ${{ steps.playwright.outputs.web }}
|
||||
app_playwright: ${{ steps.playwright.outputs.app }}
|
||||
steps:
|
||||
# Full history: the diff is taken from a merge base
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -67,6 +69,17 @@ jobs:
|
||||
env:
|
||||
BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
|
||||
# The browser suites run in Playwright's image, whose browsers only work with the Playwright
|
||||
# that matches its tag. Read from the lockfiles, so a Dependabot bump moves the image with it
|
||||
- name: Playwright versions
|
||||
id: playwright
|
||||
run: |
|
||||
for suite in web=web app=crates/luxe-remote/app-tests; do
|
||||
version=$(jq -r '.packages["node_modules/playwright"].version // empty' "${suite#*=}/package-lock.json")
|
||||
[ -n "$version" ] || { echo "::error::no playwright in ${suite#*=}/package-lock.json"; exit 1; }
|
||||
echo "${suite%%=*}=$version" >> "$GITHUB_OUTPUT"
|
||||
done
|
||||
|
||||
gate:
|
||||
name: build · test · clippy · fmt
|
||||
needs: changes
|
||||
@@ -165,18 +178,24 @@ jobs:
|
||||
# made `target/debug/luxe`: a job of its own would compile the workspace a second time, and
|
||||
# the binary is too large to hand between jobs cheaply. The app's types and unit tests need
|
||||
# no Rust, so they stay in `remote-app`.
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: crates/luxe-remote/app-tests/package-lock.json
|
||||
|
||||
#
|
||||
# In Playwright's image, which has WebKit and the Ubuntu libraries it loads, rather than
|
||||
# fetching those from Ubuntu's mirror on every run, where a slow mirror ran the job out of
|
||||
# time. The workspace is mounted at its own path, so the test finds `target/debug/luxe`
|
||||
# where it expects it, and runs as the runner's user, so what it writes stays cleanable.
|
||||
#
|
||||
# The build and test binaries leave the disk all but full, too full for the image, and
|
||||
# `target/` can't give any back because the cache step saves it after this. The Android SDK
|
||||
# the runner image ships is about 10 GB that nothing here uses.
|
||||
- name: Phone app end to end (WebKit)
|
||||
working-directory: crates/luxe-remote/app-tests
|
||||
run: |
|
||||
npm ci
|
||||
npx playwright install --with-deps webkit
|
||||
npm run e2e
|
||||
sudo rm -rf /usr/local/lib/android
|
||||
df -h / | tail -1
|
||||
docker run --rm --ipc=host --user "$(id -u):$(id -g)" -e HOME=/tmp/home \
|
||||
-v "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" -w "$GITHUB_WORKSPACE/crates/luxe-remote/app-tests" \
|
||||
"mcr.microsoft.com/playwright:v$PLAYWRIGHT-noble" sh -c 'npm ci && npm run e2e'
|
||||
env:
|
||||
PLAYWRIGHT: ${{ needs.changes.outputs.app_playwright }}
|
||||
|
||||
# Does it build and pass on the platforms nobody develops on? Linux above is the canonical gate —
|
||||
# `fmt` is an answer about the source, not about the OS, so running it three times would only
|
||||
@@ -337,15 +356,41 @@ jobs:
|
||||
- name: Render check
|
||||
run: ./scripts/site-check.sh --no-build
|
||||
|
||||
# One engine is not coverage. The render check above drives Chrome, and the site has since
|
||||
# shipped two defects that Chrome could not see — a demo player whose dynamic import Firefox
|
||||
# refused outright, and a layout that only Chrome's box metrics agreed with. WebKit is here
|
||||
# for Safari, which nothing else in this pipeline speaks for.
|
||||
#
|
||||
# `--with-deps` because the WebKit build wants Ubuntu's ICU and libxml2 sonames; a rolling
|
||||
# distro cannot supply them, which is why a contributor's local run skips it and CI does not.
|
||||
- name: Install browsers
|
||||
run: npx playwright install --with-deps chromium firefox webkit
|
||||
# One engine is not coverage. The render check above drives Chrome, and the site has since shipped
|
||||
# two defects that Chrome could not see — a demo player whose dynamic import Firefox refused
|
||||
# outright, and a layout that only Chrome's box metrics agreed with. WebKit is here for Safari,
|
||||
# which nothing else in this pipeline speaks for.
|
||||
#
|
||||
# Inside Playwright's own image, which carries all three browsers and the Ubuntu libraries they
|
||||
# load (WebKit wants Ubuntu's ICU and libxml2 sonames). `playwright install --with-deps` fetched
|
||||
# those from Ubuntu's mirror on every run, about 120 MB, and a slow mirror held the job past its
|
||||
# timeout. Its own job because the render check needs the runner's system Chrome, which the
|
||||
# image doesn't have.
|
||||
website-cross:
|
||||
name: web cross-browser
|
||||
needs: changes
|
||||
if: needs.changes.outputs.code == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v${{ needs.changes.outputs.web_playwright }}-noble
|
||||
# Firefox won't run as root in a home it doesn't own, and Actions' home is the runner user's
|
||||
options: --user 1001
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
- name: Install
|
||||
run: npm ci
|
||||
working-directory: web
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
working-directory: web
|
||||
|
||||
# The built site first — that is what a reader gets — then the dev server, which is where the
|
||||
@@ -393,7 +438,7 @@ jobs:
|
||||
# was cancelled, `changes` included, and passes when each one passed or had nothing to check.
|
||||
passed:
|
||||
name: CI passed
|
||||
needs: [changes, gate, portability, msrv, supply-chain, website, remote-app]
|
||||
needs: [changes, gate, portability, msrv, supply-chain, website, website-cross, remote-app]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
40
CHANGELOG.md
40
CHANGELOG.md
@@ -9,6 +9,46 @@ 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.7]
|
||||
|
||||
### Added
|
||||
|
||||
- The dock has a **USAGE** section between MODEL and SESSION while a ChatGPT or Copilot plan reports
|
||||
what is left of it. Each window the plan has gets a row with a bar, the share used and, when the
|
||||
provider says, the time until it resets, such as `weekly ▓▓▓░░░░░░░ 30% · 3d 4h`.
|
||||
|
||||
## [0.1.6]
|
||||
|
||||
### Added
|
||||
|
||||
- On macOS, `screenshot` with `mode=window` captures one window, even one on another desktop. It
|
||||
matches the window's title first, then its app's name, and with no title it takes the frontmost
|
||||
window. A miss lists the windows it saw.
|
||||
|
||||
### Changed
|
||||
|
||||
- The activity bar above the composer sweeps in plan's color while the session plans. A switch
|
||||
mid-turn recolors it once luxe has made the switch, the moment the agent's next tool call is held
|
||||
to the new mode.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The `git` tool's `checks` reads another repository's pull request when given `-R owner/name`.
|
||||
It used to drop the flag and answer with this checkout's pull request of the same number. It now
|
||||
refuses any argument it doesn't understand instead of skipping it.
|
||||
- On Windows, a pasted line break no longer sends the message. The console types a paste out one
|
||||
key at a time, so luxe gathers a burst of keys back into one paste.
|
||||
- On a scaled Windows display, `screenshot` captures the whole screen instead of its top-left
|
||||
corner.
|
||||
- On a Mac with fontconfig installed, the OpenAI and Claude marks fall back to the robot and cloud
|
||||
when no font has them, instead of drawing a box with a question mark.
|
||||
|
||||
### Security
|
||||
|
||||
- `clipboard-win` 5.4.3, since earlier releases were yanked: reading an HTML fragment with a bad
|
||||
offset from the Windows clipboard could read past the end of a buffer. luxe reads only text and
|
||||
images from the clipboard, so it never reached that code.
|
||||
|
||||
## [0.1.5]
|
||||
|
||||
### Added
|
||||
|
||||
22
Cargo.lock
generated
22
Cargo.lock
generated
@@ -408,9 +408,9 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
version = "5.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
|
||||
checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"
|
||||
dependencies = [
|
||||
"error-code",
|
||||
]
|
||||
@@ -1690,7 +1690,7 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "luxe-cli"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -1723,7 +1723,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-core"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base16ct",
|
||||
@@ -1754,7 +1754,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-dap"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"luxe-core",
|
||||
@@ -1768,7 +1768,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-lsp"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base16ct",
|
||||
@@ -1792,7 +1792,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-mcp"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -1812,7 +1812,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-providers"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64",
|
||||
@@ -1831,7 +1831,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-remote"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base16ct",
|
||||
@@ -1854,7 +1854,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-tools"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -1880,7 +1880,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luxe-tui"
|
||||
version = "0.1.5"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
|
||||
@@ -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.5"
|
||||
version = "0.1.7"
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/evanwhittaker/luxe"
|
||||
|
||||
@@ -18,14 +18,14 @@ name = "luxe"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.5" }
|
||||
luxe-providers = { path = "../luxe-providers", version = "0.1.5" }
|
||||
luxe-tools = { path = "../luxe-tools", version = "0.1.5" }
|
||||
luxe-lsp = { path = "../luxe-lsp", version = "0.1.5" }
|
||||
luxe-dap = { path = "../luxe-dap", version = "0.1.5" }
|
||||
luxe-mcp = { path = "../luxe-mcp", version = "0.1.5" }
|
||||
luxe-tui = { path = "../luxe-tui", version = "0.1.5" }
|
||||
luxe-remote = { path = "../luxe-remote", version = "0.1.5", optional = true }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
luxe-providers = { path = "../luxe-providers", version = "0.1.7" }
|
||||
luxe-tools = { path = "../luxe-tools", version = "0.1.7" }
|
||||
luxe-lsp = { path = "../luxe-lsp", version = "0.1.7" }
|
||||
luxe-dap = { path = "../luxe-dap", version = "0.1.7" }
|
||||
luxe-mcp = { path = "../luxe-mcp", version = "0.1.7" }
|
||||
luxe-tui = { path = "../luxe-tui", version = "0.1.7" }
|
||||
luxe-remote = { path = "../luxe-remote", version = "0.1.7", optional = true }
|
||||
# The pairing QR in the terminal. Without its defaults it is the encoder and text renderer alone,
|
||||
# with no dependencies.
|
||||
qrcode = { version = "0.14", default-features = false, optional = true }
|
||||
|
||||
@@ -2493,6 +2493,7 @@ conversation, or in its place below 80 columns.
|
||||
| **FILES** | The project as a tree, with what changed marked in it. Click a file to [preview](#preview) it. |
|
||||
| **ELSEWHERE** | Files the session changed outside the project, when there are any |
|
||||
| **MODEL** | The provider, model, thinking level and [mode](agent.md#plan-then-build). Click the provider or the model to change it, or the mode to switch it. |
|
||||
| **USAGE** | What is left of a ChatGPT or Copilot plan, one row for each window the plan has: a bar, the share used and, when the provider says, the time until it resets. It shows only once the plan has reported, after your first reply, and never on an API key. |
|
||||
| **SESSION** | Context used, tokens and cost, with what a review and compaction cost on rows of their own. A review's row shows its full cost once its guide or drafted summary is done. While a phone or another client has [joined](remote.md), a **joined** row names it. |
|
||||
|
||||
`alt+d` shows or hides the dock, and `/dock left` or `/dock right` moves it. To set it for good:
|
||||
@@ -3337,7 +3338,8 @@ Usage on a ChatGPT or Copilot subscription is counted in full but never added to
|
||||
`plan ≈$0.42 of usage over 12 calls, covered by your subscription`. On a
|
||||
ChatGPT plan, the statusline shows how much of the plan is used, such as `12% weekly`, and `/cost`
|
||||
shows when it resets. On a Copilot plan it shows the month's allowance the same way, such as `19%
|
||||
monthly`.
|
||||
monthly`. The dock's [USAGE section](interface.md#the-dock) shows the same windows as a bar, with the
|
||||
time until each resets when the provider says.
|
||||
|
||||
luxe prices Copilot usage at Copilot's per-token rates, so the figure matches what Copilot reports
|
||||
for each request. A Copilot plan billed by the token spends its monthly allowance at those rates.
|
||||
@@ -4676,8 +4678,9 @@ needed, such as a passwordless `sudo` rule for one program:
|
||||
|
||||
The `screenshot` tool's `url` mode renders a web page and captures only that. Its `fullscreen`,
|
||||
`region` and `window` modes capture whatever is on your screen, and the image goes to your model
|
||||
provider, so each **asks** first, and runs with nobody watching refuse them. To turn screen capture
|
||||
off entirely:
|
||||
provider, so each **asks** first, and runs with nobody watching refuse them. On macOS, `window` can
|
||||
also capture a window on another desktop, and when no window matches it tells the model the titles
|
||||
of the windows it saw. To turn screen capture off entirely:
|
||||
|
||||
```json title="~/.config/luxe/permissions.json"
|
||||
{ "permission": { "screenshot": { "fullscreen": "deny", "region": "deny", "window": "deny" } } }
|
||||
|
||||
@@ -48,6 +48,16 @@ impl PlanWindow {
|
||||
};
|
||||
Some(label)
|
||||
}
|
||||
|
||||
/// A fixed-width meter such as `▓▓▓░░░░░░░`, filled in proportion to the share used.
|
||||
///
|
||||
/// Rounds to the nearest cell so a nearly-full window never reads as empty, and clamps so a
|
||||
/// provider reporting over 100% can't draw past the edge.
|
||||
pub fn bar(&self, cells: usize) -> String {
|
||||
let share = (self.used_percent / 100.0).clamp(0.0, 1.0);
|
||||
let filled = ((share * cells as f32).round() as usize).min(cells);
|
||||
format!("{}{}", "▓".repeat(filled), "░".repeat(cells - filled))
|
||||
}
|
||||
}
|
||||
|
||||
/// A subscription's remaining headroom, as reported alongside a response.
|
||||
@@ -146,6 +156,18 @@ mod plan_tests {
|
||||
assert!(window(0.0, 60, None).reset_label().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bar_fills_in_proportion_and_never_overflows() {
|
||||
assert_eq!(window(0.0, 60, None).bar(10), "░░░░░░░░░░");
|
||||
assert_eq!(window(50.0, 60, None).bar(10), "▓▓▓▓▓░░░░░");
|
||||
assert_eq!(window(100.0, 60, None).bar(10), "▓▓▓▓▓▓▓▓▓▓");
|
||||
// over-reported and negative values clamp instead of panicking on the subtraction
|
||||
assert_eq!(window(250.0, 60, None).bar(4), "▓▓▓▓");
|
||||
assert_eq!(window(-5.0, 60, None).bar(4), "░░░░");
|
||||
// a window that is nearly spent must not round down to an empty-looking bar
|
||||
assert_eq!(window(96.0, 60, None).bar(10), "▓▓▓▓▓▓▓▓▓▓");
|
||||
}
|
||||
|
||||
/// The status line has room for one window, and it should be whichever is about to bite.
|
||||
#[test]
|
||||
fn the_tightest_window_wins_the_status_line() {
|
||||
|
||||
@@ -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.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
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.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -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.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
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.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -18,7 +18,7 @@ exclude = ["app-tests/"]
|
||||
# reqwest and the workspace's rustls.
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
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.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -78,7 +78,7 @@ impl Tool for GitTool {
|
||||
"args": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "What the action operates on: paths for `add`, a branch for `checkout`, a subcommand for `stash`, a `gh pr` command line for `pr` (e.g. [\"create\", \"--title\", \"...\", \"--body\", \"...\"]; the branch is pushed for you if it has no upstream), a `gh issue` command line for `issue` (e.g. [\"view\", \"12\", \"--comments\"]), a PR number for `checks` (default: this branch's), otherwise git's own flags. Never the commit message."
|
||||
"description": "What the action operates on: paths for `add`, a branch for `checkout`, a subcommand for `stash`, a `gh pr` command line for `pr` (e.g. [\"create\", \"--title\", \"...\", \"--body\", \"...\"]; the branch is pushed for you if it has no upstream), a `gh issue` command line for `issue` (e.g. [\"view\", \"12\", \"--comments\"]), a PR number for `checks` (default: this branch's), with `-R owner/name` for another repository's, otherwise git's own flags. Never the commit message."
|
||||
}
|
||||
},
|
||||
"required": ["action"]
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! cannot see. Reading only; re-running a job stays behind the permission engine's `ask`.
|
||||
|
||||
use luxe_core::github::{
|
||||
Branches, CheckLog, Checks, Discovery, FailingCheck, GitHubError, PullRequests,
|
||||
Branches, CheckLog, Checks, Discovery, FailingCheck, GitHubError, PullRequests, Repository,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
@@ -27,27 +27,23 @@ struct Target {
|
||||
pending: Option<usize>,
|
||||
}
|
||||
|
||||
/// What `checks` was asked about, read from its `args`.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Request {
|
||||
/// Pull request named, when one was
|
||||
number: Option<u64>,
|
||||
/// Repository named with `-R`, when it isn't this checkout's
|
||||
repository: Option<Repository>,
|
||||
}
|
||||
|
||||
/// Why checks are failing on the branch's pull request, on pull request `#n` when `args` names one,
|
||||
/// or on `HEAD` when the branch has no pull request.
|
||||
/// or on `HEAD` when the branch has no pull request. `-R owner/name` reads another repository's.
|
||||
pub(super) async fn checks(
|
||||
github: &(impl Discovery + PullRequests + Branches + Checks + ?Sized),
|
||||
cwd: &Path,
|
||||
args: &[String],
|
||||
) -> Result<String, String> {
|
||||
let repository = github.repository(cwd).await.map_err(|error| failure(&error))?;
|
||||
let target = match args.first().map(|arg| arg.trim_start_matches('#')) {
|
||||
Some(number) => {
|
||||
let number: u64 =
|
||||
number.parse().map_err(|_| format!("`{number}` is not a pull request number."))?;
|
||||
let pr = github.pull_request(&repository, number).await.map_err(|e| failure(&e))?;
|
||||
Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, luxe_core::github::untrusted(&pr.title, 120)),
|
||||
pending: Some(pr.checks.pending),
|
||||
}
|
||||
}
|
||||
None => branch_target(github, cwd, &repository).await?,
|
||||
};
|
||||
let (repository, target) = resolve(github, cwd, parse_request(args)?).await?;
|
||||
let failing = github
|
||||
.failing_checks(&repository, &target.oid, LOG_TAIL)
|
||||
.await
|
||||
@@ -55,11 +51,120 @@ pub(super) async fn checks(
|
||||
Ok(render(&target, &failing))
|
||||
}
|
||||
|
||||
/// Why `-R` alone is refused: the branch-to-pull-request lookup only knows this checkout.
|
||||
const REPO_NEEDS_NUMBER: &str = "Name the pull request as well as `-R`: the branch here belongs \
|
||||
to this checkout, not that repository.";
|
||||
|
||||
/// The repository and commit `request` asks about. A repository named with `-R` is named in the
|
||||
/// answer too, so it can't be mistaken for this checkout's.
|
||||
async fn resolve(
|
||||
github: &(impl Discovery + PullRequests + Branches + ?Sized),
|
||||
cwd: &Path,
|
||||
request: Request,
|
||||
) -> Result<(Repository, Target), String> {
|
||||
if let Some(repository) = request.repository {
|
||||
let number = request.number.ok_or(REPO_NEEDS_NUMBER)?;
|
||||
let mut target = named_target(github, &repository, number).await?;
|
||||
target.name = format!("{}{}", repository.slug(), target.name);
|
||||
return Ok((repository, target));
|
||||
}
|
||||
let repository = github.repository(cwd).await.map_err(|error| failure(&error))?;
|
||||
let target = match request.number {
|
||||
Some(number) => named_target(github, &repository, number).await?,
|
||||
None => branch_target(github, cwd, &repository).await?,
|
||||
};
|
||||
Ok((repository, target))
|
||||
}
|
||||
|
||||
/// The pull request number and `-R` repository in `args`. Anything else is refused rather than
|
||||
/// dropped: an argument skipped in silence answers a different question than the one asked.
|
||||
fn parse_request(args: &[String]) -> Result<Request, String> {
|
||||
let mut request = Request { number: None, repository: None };
|
||||
let mut args = args.iter().map(String::as_str);
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(slug) = repo_flag(arg, &mut args)? {
|
||||
request.repository = Some(repository_from_slug(slug)?);
|
||||
} else if request.number.replace(pull_request_number(arg)?).is_some() {
|
||||
return Err("`checks` reads one pull request at a time.".into());
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// The repository `arg` names when it is `-R`/`--repo` (taking the next argument) or `--repo=`.
|
||||
fn repo_flag<'a>(
|
||||
arg: &'a str,
|
||||
rest: &mut impl Iterator<Item = &'a str>,
|
||||
) -> Result<Option<&'a str>, String> {
|
||||
match arg {
|
||||
"-R" | "--repo" => {
|
||||
rest.next().map(Some).ok_or_else(|| "`-R` needs a repository: `-R owner/name`.".into())
|
||||
}
|
||||
other => Ok(other.strip_prefix("--repo=")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `arg` as a pull request number, `#` or not; a flag `checks` doesn't know is refused by name.
|
||||
fn pull_request_number(arg: &str) -> Result<u64, String> {
|
||||
if arg.starts_with('-') {
|
||||
return Err(format!(
|
||||
"`checks` doesn't take `{arg}`. It takes a pull request number, and `-R owner/name` \
|
||||
for a repository other than this checkout's."
|
||||
));
|
||||
}
|
||||
let number = arg.trim_start_matches('#');
|
||||
number.parse().map_err(|_| format!("`{number}` is not a pull request number."))
|
||||
}
|
||||
|
||||
/// The repository `owner/name` names on github.com, or `host/owner/name` on another host, as
|
||||
/// `gh -R` reads it.
|
||||
fn repository_from_slug(slug: &str) -> Result<Repository, String> {
|
||||
let (host, owner, name) = slug_parts(slug)
|
||||
.ok_or_else(|| format!("`{slug}` is not a repository: `-R` takes owner/name."))?;
|
||||
Ok(Repository {
|
||||
host: host.to_ascii_lowercase(),
|
||||
owner: owner.to_string(),
|
||||
name: name.to_string(),
|
||||
// Reading a pull request's checks never consults either, so neither is looked up
|
||||
default_branch: String::new(),
|
||||
remote: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Host, owner and name, when each part of `slug` is one GitHub would accept.
|
||||
fn slug_parts(slug: &str) -> Option<(&str, &str, &str)> {
|
||||
let valid = |part: &str| {
|
||||
!part.is_empty()
|
||||
&& part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||||
};
|
||||
let parts: Vec<&str> = slug.split('/').collect();
|
||||
let (host, owner, name) = match parts.as_slice() {
|
||||
[owner, name] => ("github.com", *owner, *name),
|
||||
[host, owner, name] => (*host, *owner, *name),
|
||||
_ => return None,
|
||||
};
|
||||
[host, owner, name].into_iter().all(valid).then_some((host, owner, name))
|
||||
}
|
||||
|
||||
/// Pull request `number`'s head, by its number and title.
|
||||
async fn named_target(
|
||||
github: &(impl PullRequests + ?Sized),
|
||||
repository: &Repository,
|
||||
number: u64,
|
||||
) -> Result<Target, String> {
|
||||
let pr = github.pull_request(repository, number).await.map_err(|e| failure(&e))?;
|
||||
Ok(Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, luxe_core::github::untrusted(&pr.title, 120)),
|
||||
pending: Some(pr.checks.pending),
|
||||
})
|
||||
}
|
||||
|
||||
/// The branch's pull request head, or `HEAD` when there is no pull request to ask about.
|
||||
async fn branch_target(
|
||||
github: &(impl Branches + ?Sized),
|
||||
cwd: &Path,
|
||||
repository: &luxe_core::github::Repository,
|
||||
repository: &Repository,
|
||||
) -> Result<Target, String> {
|
||||
let head = luxe_core::github::branch_head(cwd).await;
|
||||
if let Some(head) = head {
|
||||
|
||||
@@ -108,7 +108,8 @@ fn a_short_oid_is_seven_characters_or_all_of_it() {
|
||||
assert_eq!(short("abc"), "abc");
|
||||
}
|
||||
|
||||
/// A GitHub double with one pull request, #7, whose head has one failing Actions job.
|
||||
/// A GitHub double for this checkout's `me/app`, whose pull request #7 has one failing Actions job,
|
||||
/// and for `other/site`, whose #19 has one too: reachable only by naming that repository.
|
||||
struct Scripted {
|
||||
signed_in: bool,
|
||||
/// Whether the branch has a pull request
|
||||
@@ -148,15 +149,17 @@ impl luxe_core::github::Discovery for Scripted {
|
||||
impl luxe_core::github::PullRequests for Scripted {
|
||||
async fn pull_request(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
repository: &luxe_core::github::Repository,
|
||||
number: u64,
|
||||
) -> Result<luxe_core::github::PullRequest, GitHubError> {
|
||||
if number != 7 {
|
||||
return Err(GitHubError::NotFound);
|
||||
}
|
||||
let (title, head_oid) = match (repository.slug().as_str(), number) {
|
||||
("me/app", 7) => ("Topic", "7777777aaaa"),
|
||||
("other/site", 19) => ("Site", "1919191bbbb"),
|
||||
_ => return Err(GitHubError::NotFound),
|
||||
};
|
||||
Ok(luxe_core::github::PullRequest {
|
||||
number: 7,
|
||||
title: "Topic".into(),
|
||||
number,
|
||||
title: title.into(),
|
||||
body: String::new(),
|
||||
url: String::new(),
|
||||
author: luxe_core::github::Author { login: "me".into(), bot: false },
|
||||
@@ -165,7 +168,7 @@ impl luxe_core::github::PullRequests for Scripted {
|
||||
base_ref: "main".into(),
|
||||
base_oid: "b".into(),
|
||||
head_ref: "topic".into(),
|
||||
head_oid: "7777777aaaa".into(),
|
||||
head_oid: head_oid.into(),
|
||||
cross_repository: false,
|
||||
review_decision: None,
|
||||
checks: luxe_core::github::CheckRollup { pending: 1, ..Default::default() },
|
||||
@@ -261,14 +264,17 @@ impl luxe_core::github::Branches for Scripted {
|
||||
impl luxe_core::github::Checks for Scripted {
|
||||
async fn failing_checks(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
repository: &luxe_core::github::Repository,
|
||||
head_oid: &str,
|
||||
log_tail: usize,
|
||||
) -> Result<Vec<FailingCheck>, GitHubError> {
|
||||
assert_eq!(log_tail, LOG_TAIL);
|
||||
if head_oid != "7777777aaaa" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let owner = match head_oid {
|
||||
"7777777aaaa" => "me/app",
|
||||
"1919191bbbb" => "other/site",
|
||||
_ => return Ok(Vec::new()),
|
||||
};
|
||||
assert_eq!(repository.slug(), owner, "checks are read where the pull request lives");
|
||||
Ok(vec![check("test", CheckLog::NotRead)])
|
||||
}
|
||||
}
|
||||
@@ -292,6 +298,67 @@ async fn a_named_pull_request_reads_its_head() {
|
||||
assert!(error.contains("gh auth login"), "{error}");
|
||||
}
|
||||
|
||||
/// The break this catches: `-R` dropped in silence, which reads the same number in this checkout's
|
||||
/// repository instead, a different pull request entirely or none at all.
|
||||
#[tokio::test]
|
||||
async fn a_repository_named_with_r_is_the_one_read() {
|
||||
let github = Scripted { signed_in: true, pull_request: true };
|
||||
let spellings: [&[&str]; 3] = [
|
||||
&["19", "-R", "other/site"],
|
||||
&["--repo", "other/site", "#19"],
|
||||
&["--repo=other/site", "19"],
|
||||
];
|
||||
for args in spellings {
|
||||
let args: Vec<String> = args.iter().map(|arg| arg.to_string()).collect();
|
||||
let text = checks(&github, Path::new("."), &args).await.unwrap();
|
||||
assert!(text.starts_with("1 check failing on other/site#19 · Site (1919191)."), "{text}");
|
||||
}
|
||||
|
||||
let error = checks(&github, Path::new("."), &["19".into()]).await.unwrap_err();
|
||||
assert!(error.contains("never pushed has no checks"), "#19 isn't this checkout's: {error}");
|
||||
}
|
||||
|
||||
/// The break this catches: an argument `checks` doesn't understand skipped rather than refused.
|
||||
#[tokio::test]
|
||||
async fn an_argument_checks_does_not_take_is_refused() {
|
||||
let github = Scripted { signed_in: true, pull_request: true };
|
||||
let refused = |args: &[&str]| {
|
||||
let args: Vec<String> = args.iter().map(|arg| arg.to_string()).collect();
|
||||
let github = &github;
|
||||
async move { checks(github, Path::new("."), &args).await.unwrap_err() }
|
||||
};
|
||||
|
||||
let error = refused(&["7", "--json"]).await;
|
||||
assert!(error.contains("doesn't take `--json`"), "{error}");
|
||||
let error = refused(&["7", "8"]).await;
|
||||
assert!(error.contains("one pull request at a time"), "{error}");
|
||||
let error = refused(&["7", "-R"]).await;
|
||||
assert!(error.contains("`-R` needs a repository"), "{error}");
|
||||
let error = refused(&["-R", "other/site"]).await;
|
||||
assert_eq!(error, REPO_NEEDS_NUMBER, "no branch here belongs to that repository");
|
||||
let error = refused(&["7", "-R", "luxe"]).await;
|
||||
assert!(error.contains("`luxe` is not a repository"), "{error}");
|
||||
}
|
||||
|
||||
/// `-R` reads a repository the way `gh -R` does, and refuses what GitHub couldn't name.
|
||||
#[test]
|
||||
fn a_repository_is_owner_and_name_or_host_owner_and_name() {
|
||||
let on_github = repository_from_slug("evanwhittaker/luxe").unwrap();
|
||||
assert_eq!(
|
||||
(on_github.host.as_str(), on_github.slug().as_str()),
|
||||
("github.com", "evanwhittaker/luxe")
|
||||
);
|
||||
let elsewhere = repository_from_slug("GHE.example.com/team/app.rs").unwrap();
|
||||
assert_eq!(
|
||||
(elsewhere.host.as_str(), elsewhere.slug().as_str()),
|
||||
("ghe.example.com", "team/app.rs")
|
||||
);
|
||||
|
||||
for slug in ["luxe", "a/b/c/d", "owner/", "/name", "my owner/app", "owner/app?x=1", ""] {
|
||||
assert!(repository_from_slug(slug).is_err(), "`{slug}` names no repository");
|
||||
}
|
||||
}
|
||||
|
||||
/// With nothing named, the branch's own pull request is the one read.
|
||||
#[tokio::test]
|
||||
async fn the_branchs_pull_request_is_the_default() {
|
||||
|
||||
@@ -75,7 +75,7 @@ impl Tool for ScreenshotTool {
|
||||
},
|
||||
"window": {
|
||||
"type": "string",
|
||||
"description": "window mode: case-sensitive title substring; omit for the active window (Hyprland/X11 only)"
|
||||
"description": "window mode: case-sensitive title substring; omit for the active window. Hyprland, X11 and macOS only; on macOS this also captures a window on another desktop, matching the title or the app's name"
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//!
|
||||
//! Shells out to the platform's native tool rather than linking a capture crate, keeping the
|
||||
//! dependency surface tiny and the gate clean: grim (+ hyprctl) on Wayland, maim/scrot/ImageMagick
|
||||
//! on X11, `screencapture` on macOS, and PowerShell + System.Drawing on Windows. Each writes a PNG
|
||||
//! that the tool then reads and returns inline.
|
||||
//! on X11, `screencapture` (plus `osascript` to find windows) on macOS, and PowerShell +
|
||||
//! System.Drawing on Windows. Each writes a PNG that the tool then reads and returns inline.
|
||||
|
||||
mod macos;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use std::path::Path;
|
||||
@@ -282,9 +284,7 @@ async fn capture_macos(target: &CaptureTarget, out: &Path) -> Result<()> {
|
||||
let rect = format!("{},{},{},{}", r.x, r.y, r.w, r.h);
|
||||
run("screencapture", &["-x".into(), "-R".into(), rect, out]).await
|
||||
}
|
||||
CaptureTarget::Window { .. } => bail!(
|
||||
"per-window capture on macOS needs a window id; use mode=fullscreen or mode=region"
|
||||
),
|
||||
CaptureTarget::Window { title } => macos::capture_window(title.as_deref(), &out).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,6 +306,16 @@ async fn capture_windows(target: &CaptureTarget, out: &Path) -> Result<()> {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Opts the PowerShell process out of DPI virtualization, as a script prefix.
|
||||
///
|
||||
/// Without it Windows reports the scaled screen size (1371x914 on a 2400x1600 panel at 175%) and
|
||||
/// `CopyFromScreen` copies only that many physical pixels, cropping the capture to the top-left.
|
||||
/// It has to run before anything touches `System.Windows.Forms`, so it leads the script. Regions
|
||||
/// are then in physical pixels too, which is what the image the model sees is measured in.
|
||||
const WINDOWS_DPI_AWARE: &str = "Add-Type -TypeDefinition 'using System.Runtime.InteropServices; \
|
||||
public static class LuxeDpi { [DllImport(\"user32.dll\")] public static extern bool \
|
||||
SetProcessDPIAware(); }'; [void][LuxeDpi]::SetProcessDPIAware(); ";
|
||||
|
||||
/// Builds a PowerShell one-liner that captures the virtual screen (or `x,y,w,h`) to `out`.
|
||||
fn windows_capture_script(rect: &str, out: &str) -> String {
|
||||
let bounds = if rect == "virtual" {
|
||||
@@ -321,7 +331,7 @@ fn windows_capture_script(rect: &str, out: &str) -> String {
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"Add-Type -AssemblyName System.Windows.Forms,System.Drawing; {bounds}; \
|
||||
"{WINDOWS_DPI_AWARE}Add-Type -AssemblyName System.Windows.Forms,System.Drawing; {bounds}; \
|
||||
$bmp=New-Object System.Drawing.Bitmap($r.Width,$r.Height); \
|
||||
$g=[System.Drawing.Graphics]::FromImage($bmp); \
|
||||
$g.CopyFromScreen($r.Left,$r.Top,0,0,$bmp.Size); \
|
||||
@@ -439,6 +449,17 @@ mod tests {
|
||||
assert!(!which("definitely-not-a-real-binary-xyzzy"));
|
||||
}
|
||||
|
||||
/// Reading the screen size before opting into DPI awareness is what cropped Windows captures.
|
||||
#[test]
|
||||
fn windows_script_turns_on_dpi_awareness_before_reading_the_screen() {
|
||||
for rect in ["virtual", "0,0,800,600"] {
|
||||
let script = windows_capture_script(rect, "out.png");
|
||||
let aware = script.find("SetProcessDPIAware();").expect("calls SetProcessDPIAware");
|
||||
let forms = script.find("System.Windows.Forms").expect("loads Windows.Forms");
|
||||
assert!(aware < forms, "{rect}: DPI awareness must come first: {script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_label_is_stable() {
|
||||
assert_eq!(backend_label(DisplayBackend::X11), "X11");
|
||||
|
||||
214
crates/luxe-tools/src/screenshot/capture/macos.rs
Normal file
214
crates/luxe-tools/src/screenshot/capture/macos.rs
Normal file
@@ -0,0 +1,214 @@
|
||||
//! macOS window capture — finds a window on any desktop and hands its id to `screencapture -l`.
|
||||
//!
|
||||
//! `screencapture` takes a window by id and can photograph one on a desktop (Space) that isn't the
|
||||
//! one on screen, which a fullscreen or region capture never can. Ids come from CoreGraphics'
|
||||
//! window list, read through `osascript`'s JavaScript so nothing beyond the OS is needed.
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Lists every window on every desktop as JSON, front to back.
|
||||
///
|
||||
/// `kCGWindowListOptionAll` rather than on-screen only: that is what makes a window on another
|
||||
/// desktop visible to us at all.
|
||||
const LIST_WINDOWS_SCRIPT: &str = r#"
|
||||
ObjC.import('CoreGraphics');
|
||||
const raw = $.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll, 0);
|
||||
const list = ObjC.deepUnwrap(ObjC.castRefToObject(raw));
|
||||
JSON.stringify(list.map(w => ({
|
||||
id: w.kCGWindowNumber, owner: w.kCGWindowOwnerName || '', name: w.kCGWindowName || '',
|
||||
layer: w.kCGWindowLayer, w: w.kCGWindowBounds.Width, h: w.kCGWindowBounds.Height,
|
||||
on: !!w.kCGWindowIsOnscreen })));
|
||||
"#;
|
||||
|
||||
/// How long the window list may take; it answers in about a tenth of a second.
|
||||
const LIST_DEADLINE: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Windows narrower or shorter than this are the helper strips and offscreen buffers apps keep
|
||||
/// around (a terminal alone leaves ten), not something a person means by "that window".
|
||||
const MIN_SIDE: f64 = 100.0;
|
||||
|
||||
/// How many window names an unmatched search reports back.
|
||||
const SHOWN_ON_MISS: usize = 12;
|
||||
|
||||
/// One entry of the window list.
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq)]
|
||||
struct WindowInfo {
|
||||
id: u64,
|
||||
owner: String,
|
||||
name: String,
|
||||
layer: i64,
|
||||
w: f64,
|
||||
h: f64,
|
||||
on: bool,
|
||||
}
|
||||
|
||||
impl WindowInfo {
|
||||
/// A normal, sizeable application window: layer 0 is where apps draw, and the menu bar, the
|
||||
/// Dock and overlays sit above it.
|
||||
fn is_usable(&self) -> bool {
|
||||
self.layer == 0 && self.w >= MIN_SIDE && self.h >= MIN_SIDE
|
||||
}
|
||||
|
||||
fn label(&self) -> String {
|
||||
match self.name.is_empty() {
|
||||
true => self.owner.clone(),
|
||||
false => format!("{}: {}", self.owner, self.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures a window to `out`, wherever its desktop is. `title` matches a window's title, or
|
||||
/// failing that its app's name; `None` takes the frontmost window on screen.
|
||||
pub(super) async fn capture_window(title: Option<&str>, out: &str) -> Result<()> {
|
||||
let id = pick_window(&list_windows().await?, title)?;
|
||||
let args = ["-x", "-o", "-l", &id.to_string(), out].map(String::from);
|
||||
super::run("screencapture", &args).await
|
||||
}
|
||||
|
||||
async fn list_windows() -> Result<Vec<WindowInfo>> {
|
||||
let child = Command::new("osascript")
|
||||
.args(["-l", "JavaScript", "-e", LIST_WINDOWS_SCRIPT])
|
||||
.kill_on_drop(true)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output();
|
||||
let output = tokio::time::timeout(LIST_DEADLINE, child)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
anyhow!("`osascript` did not list windows within {}s", LIST_DEADLINE.as_secs())
|
||||
})?
|
||||
.context("failed to run `osascript` to list windows")?;
|
||||
if !output.status.success() {
|
||||
bail!("listing windows failed: {}", String::from_utf8_lossy(&output.stderr).trim());
|
||||
}
|
||||
serde_json::from_slice(&output.stdout).context("could not parse the window list")
|
||||
}
|
||||
|
||||
/// Chooses the window to capture. A title match beats an app-name match; among matches an
|
||||
/// on-screen window beats a hidden one and a bigger beats a smaller.
|
||||
fn pick_window(windows: &[WindowInfo], title: Option<&str>) -> Result<u64> {
|
||||
let usable = || windows.iter().filter(|window| window.is_usable());
|
||||
let Some(needle) = title else {
|
||||
let frontmost = usable().find(|window| window.on);
|
||||
return frontmost.map(|window| window.id).ok_or_else(|| anyhow!("no window is on screen"));
|
||||
};
|
||||
let titled = best(usable().filter(|window| window.name.contains(needle)));
|
||||
let by_app = || best(usable().filter(|window| window.owner.contains(needle)));
|
||||
titled.or_else(by_app).ok_or_else(|| no_match(windows, needle))
|
||||
}
|
||||
|
||||
fn best<'a>(matches: impl Iterator<Item = &'a WindowInfo>) -> Option<u64> {
|
||||
matches.max_by_key(|window| (window.on, (window.w * window.h) as u64)).map(|window| window.id)
|
||||
}
|
||||
|
||||
fn no_match(windows: &[WindowInfo], needle: &str) -> anyhow::Error {
|
||||
// Titled windows are what a search can name; with titles hidden, the apps are all there is
|
||||
let usable = || windows.iter().filter(|w| w.is_usable());
|
||||
let mut shown: Vec<&WindowInfo> = usable().filter(|w| !w.name.is_empty()).collect();
|
||||
if shown.is_empty() {
|
||||
shown = usable().collect();
|
||||
}
|
||||
let labels: Vec<String> =
|
||||
shown.into_iter().take(SHOWN_ON_MISS).map(WindowInfo::label).collect();
|
||||
anyhow!(
|
||||
"no window whose title or app contains '{needle}' (case-sensitive). Windows seen: {}. \
|
||||
Titles of other apps' windows need Screen Recording permission for the terminal.",
|
||||
labels.join(", ")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn window(id: u64, owner: &str, name: &str, size: (f64, f64), on: bool) -> WindowInfo {
|
||||
let (w, h) = size;
|
||||
WindowInfo { id, owner: owner.into(), name: name.into(), layer: 0, w, h, on }
|
||||
}
|
||||
|
||||
/// The Ghostty entries from a real listing: one real window among its helper strips.
|
||||
fn ghostty_with_helpers(real_is_on_screen: bool) -> Vec<WindowInfo> {
|
||||
vec![
|
||||
window(102536, "Ghostty", "", (500.0, 500.0), false),
|
||||
window(102535, "Ghostty", "luxe", (2539.0, 1391.0), real_is_on_screen),
|
||||
window(102534, "Ghostty", "", (3840.0, 30.0), false),
|
||||
window(102530, "Ghostty", "", (1728.0, 33.0), false),
|
||||
]
|
||||
}
|
||||
|
||||
/// Copied from `osascript -l JavaScript` output on macOS, so a renamed key fails here.
|
||||
#[test]
|
||||
fn the_window_list_parses_as_the_script_prints_it() {
|
||||
let line = r#"[{"id":102535,"owner":"Ghostty","name":"luxe","layer":0,"w":2539,"h":1391,"on":true}]"#;
|
||||
let parsed: Vec<WindowInfo> = serde_json::from_str(line).expect("parses");
|
||||
assert_eq!(parsed, vec![window(102535, "Ghostty", "luxe", (2539.0, 1391.0), true)]);
|
||||
}
|
||||
|
||||
/// Catches a title match falling through to the app name, which would also hit the helpers.
|
||||
#[test]
|
||||
fn a_title_picks_that_window() {
|
||||
assert_eq!(pick_window(&ghostty_with_helpers(true), Some("lux")).expect("found"), 102535);
|
||||
}
|
||||
|
||||
/// A window on another desktop is not on screen; it must still be found.
|
||||
#[test]
|
||||
fn a_window_on_another_desktop_is_found() {
|
||||
assert_eq!(pick_window(&ghostty_with_helpers(false), Some("luxe")).expect("found"), 102535);
|
||||
}
|
||||
|
||||
/// Two windows share a title: the one in front of the reader wins over a bigger one hidden away.
|
||||
#[test]
|
||||
fn an_on_screen_window_beats_a_bigger_hidden_one() {
|
||||
let windows = vec![
|
||||
window(1, "Ghostty", "luxe", (3000.0, 2000.0), false),
|
||||
window(2, "Ghostty", "luxe", (1000.0, 700.0), true),
|
||||
];
|
||||
assert_eq!(pick_window(&windows, Some("luxe")).expect("found"), 2);
|
||||
}
|
||||
|
||||
/// Without a title permission every name is empty; the app name still finds the big window,
|
||||
/// not the 500 by 500 offscreen buffer or the thin strips.
|
||||
#[test]
|
||||
fn an_app_name_picks_its_biggest_window_when_titles_are_hidden() {
|
||||
let mut windows = ghostty_with_helpers(false);
|
||||
windows[1].name.clear();
|
||||
assert_eq!(pick_window(&windows, Some("Ghostty")).expect("found"), 102535);
|
||||
}
|
||||
|
||||
/// A title beats an app match even when the app's other window is on screen and bigger.
|
||||
#[test]
|
||||
fn a_title_match_beats_an_app_match() {
|
||||
let windows = vec![
|
||||
window(1, "Safari", "docs", (1200.0, 800.0), true),
|
||||
window(2, "Ghostty", "docs", (900.0, 600.0), false),
|
||||
window(3, "docs", "", (2000.0, 1500.0), true),
|
||||
];
|
||||
assert_eq!(pick_window(&windows, Some("docs")).expect("found"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_is_case_sensitive_and_a_miss_lists_what_exists() {
|
||||
let message = pick_window(&ghostty_with_helpers(true), Some("LUXE"))
|
||||
.expect_err("no match")
|
||||
.to_string();
|
||||
assert!(message.contains("'LUXE'"), "{message}");
|
||||
assert!(message.contains("Ghostty: luxe"), "{message}");
|
||||
}
|
||||
|
||||
/// No title means the frontmost window on screen: the first usable one, in front-to-back order.
|
||||
#[test]
|
||||
fn no_title_takes_the_frontmost_window_on_screen() {
|
||||
let mut menu_bar = window(9, "Window Server", "Menubar", (3840.0, 30.0), true);
|
||||
menu_bar.layer = 24;
|
||||
let windows = vec![
|
||||
menu_bar,
|
||||
window(8, "Ghostty", "", (3840.0, 30.0), true),
|
||||
window(7, "Safari", "docs", (1200.0, 800.0), false),
|
||||
window(6, "Ghostty", "luxe", (2539.0, 1391.0), true),
|
||||
window(5, "Notes", "todo", (800.0, 600.0), true),
|
||||
];
|
||||
assert_eq!(pick_window(&windows, None).expect("found"), 6);
|
||||
assert!(pick_window(&windows[..3], None).is_err(), "nothing usable is on screen");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.5" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.7" }
|
||||
# `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).
|
||||
|
||||
@@ -137,6 +137,54 @@ fn the_activity_row_keeps_the_mode_button_at_its_left() {
|
||||
assert!(line[..hint].chars().count() > usize::from(column), "{line}");
|
||||
}
|
||||
|
||||
/// The colors the activity row is drawn in to the right of the mode button, at a frame with the
|
||||
/// comet's head mid-bar.
|
||||
fn activity_colors(app: &mut App) -> Vec<ratatui::style::Color> {
|
||||
app.status.spinner_frame = 24;
|
||||
let mode = app.status.mode.clone();
|
||||
let (text, buffer) = screen(app, 80, 20);
|
||||
let (column, row) = mode_badge_at(&text, &mode).expect("the mode button during a turn");
|
||||
let bar = column + mode.chars().count() as u16 + 1;
|
||||
(bar..80).map(|x| buffer[(x, row)].fg).collect()
|
||||
}
|
||||
|
||||
/// The engine moving to `mode` while a turn runs, which reports the turn as still streaming.
|
||||
fn switched_mid_turn(app: &mut App, mode: &str) {
|
||||
app.update(Msg::Engine(Event::StateChanged(luxe_core::event::EngineState {
|
||||
model: luxe_core::event::ModelRef::new("openai", "test-model"),
|
||||
streaming: true,
|
||||
status: format!("mode: {mode}"),
|
||||
mode: mode.into(),
|
||||
thinking: luxe_core::provider::ThinkingLevel::Off,
|
||||
})));
|
||||
}
|
||||
|
||||
/// The activity bar's comet wears the mode the engine reports, switched mid-turn too: that is the
|
||||
/// mode each tool call is judged by as it starts, so it is what the turn can do from here on.
|
||||
///
|
||||
/// The break this catches: a comet in the accent whatever the mode, or one that recolors on the
|
||||
/// keypress before the engine has moved the mode the calls are judged by.
|
||||
#[test]
|
||||
fn the_activity_bar_wears_the_mode_the_engine_reports() {
|
||||
let (mut app, _rx) = mode_app();
|
||||
in_mode(&mut app, "build");
|
||||
app.status.state = crate::app::AppState::Streaming;
|
||||
app.status.on_turn_start();
|
||||
let build = app.theme_styles.activity_trail[0].fg.unwrap();
|
||||
let plan = app.theme_styles.activity_trail_plan[0].fg.unwrap();
|
||||
assert_ne!(build, plan, "the theme has to tell the two comets apart");
|
||||
let colors = activity_colors(&mut app);
|
||||
assert!(colors.contains(&build) && !colors.contains(&plan), "build's comet: {colors:?}");
|
||||
|
||||
app.update(Msg::Key(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT)));
|
||||
let colors = activity_colors(&mut app);
|
||||
assert!(colors.contains(&build) && !colors.contains(&plan), "asked, not applied: {colors:?}");
|
||||
|
||||
switched_mid_turn(&mut app, "plan");
|
||||
let colors = activity_colors(&mut app);
|
||||
assert!(colors.contains(&plan) && !colors.contains(&build), "plan's comet: {colors:?}");
|
||||
}
|
||||
|
||||
/// Plan mode's color reaches the question the agent asks, and nothing further.
|
||||
#[test]
|
||||
fn plan_mode_tints_the_agent_s_question() {
|
||||
|
||||
@@ -73,7 +73,18 @@ fn fontconfig_has_all(wanted: impl IntoIterator<Item = char>) -> bool {
|
||||
.args([charset.as_str(), "family"])
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.is_ok_and(|probe| probe.status.success() && !probe.stdout.is_empty())
|
||||
.is_ok_and(|probe| probe.status.success() && names_a_real_font(&probe.stdout))
|
||||
}
|
||||
|
||||
/// Whether `fc-list`'s family listing names a font a reader could have chosen.
|
||||
///
|
||||
/// macOS lists `.LastResort`, whose job is to draw a placeholder box for every codepoint, so it
|
||||
/// answers yes to any charset question and the probe would never say no. Fonts the system hides
|
||||
/// from its pickers carry a leading dot; none of them is a face a terminal is set to.
|
||||
fn names_a_real_font(listing: &[u8]) -> bool {
|
||||
String::from_utf8_lossy(listing)
|
||||
.lines()
|
||||
.any(|family| !family.trim().is_empty() && !family.starts_with('.'))
|
||||
}
|
||||
|
||||
/// Whether the Material icons can actually be drawn on this machine.
|
||||
@@ -140,3 +151,25 @@ fn is_kitty() -> bool {
|
||||
let multiplexed = term.starts_with("tmux") || term.starts_with("screen");
|
||||
multiplexed && std::env::var_os("KITTY_WINDOW_ID").is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod probe_tests {
|
||||
use super::names_a_real_font;
|
||||
|
||||
/// Copied from `fc-list ":charset=ec82 ec81 ec1e" family` on a Mac with Nerd Fonts older than 3.5.
|
||||
#[test]
|
||||
fn the_macos_placeholder_font_is_not_a_font_with_the_glyph() {
|
||||
assert!(!names_a_real_font(b".LastResort\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_font_beside_a_real_one_still_counts_the_real_one() {
|
||||
assert!(names_a_real_font(b".LastResort\nHack Nerd Font\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_listing_names_no_font() {
|
||||
assert!(!names_a_real_font(b""));
|
||||
assert!(!names_a_real_font(b"\n"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ mod launch;
|
||||
mod mouse;
|
||||
mod pacing;
|
||||
mod paste;
|
||||
mod paste_burst;
|
||||
|
||||
use crate::app::{App, Msg};
|
||||
use crate::workspace_layout::Pane;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Frame pacing — how many queued events join a frame, and whether an iteration paints.
|
||||
|
||||
use super::keys::{apply_terminal_event, collect_exit};
|
||||
use super::keys::collect_exit;
|
||||
use super::paste_burst::apply_folding_pastes;
|
||||
use super::TuiExit;
|
||||
use crate::app::{App, Msg};
|
||||
use crossterm::event::{Event, EventStream};
|
||||
@@ -37,7 +38,7 @@ pub(super) async fn next_event(events: &mut Option<EventStream>) -> Option<std::
|
||||
///
|
||||
/// Polled with the loop's own waker rather than a throwaway one, so a stream that answers with
|
||||
/// nothing here still wakes the loop's `select!` when its event does land.
|
||||
async fn queued_event(events: Option<&mut EventStream>) -> Option<Event> {
|
||||
pub(super) async fn queued_event(events: Option<&mut EventStream>) -> Option<Event> {
|
||||
let events = events?;
|
||||
std::future::poll_fn(|context| {
|
||||
std::task::Poll::Ready(match events.poll_next_unpin(context) {
|
||||
@@ -80,13 +81,13 @@ pub(super) async fn apply_terminal_batch(
|
||||
first: Event,
|
||||
exit: &mut TuiExit,
|
||||
) -> (bool, usize) {
|
||||
let mut idle_motion = apply_terminal_event(app, first, exit);
|
||||
let mut idle_motion = apply_folding_pastes(app, events, first, exit).await;
|
||||
let mut coalesced = 0;
|
||||
while may_coalesce(app, coalesced) {
|
||||
let Some(event) = queued_event(events.as_mut()).await else {
|
||||
break;
|
||||
};
|
||||
idle_motion &= apply_terminal_event(app, event, exit);
|
||||
idle_motion &= apply_folding_pastes(app, events, event, exit).await;
|
||||
coalesced += 1;
|
||||
}
|
||||
(idle_motion, coalesced)
|
||||
|
||||
227
crates/luxe-tui/src/main_loop/paste_burst.rs
Normal file
227
crates/luxe-tui/src/main_loop/paste_burst.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
//! Paste burst — rebuilding a paste from the key presses a console delivers in its place.
|
||||
//!
|
||||
//! The Windows console has no bracketed paste: a paste arrives as one key press per character, and
|
||||
//! every line break as an Enter, which the composer would submit. A run of text keys that lands
|
||||
//! all at once is a paste, so it is folded back into one [`Event::Paste`] and meets the same code
|
||||
//! a bracketed paste does, chip and all.
|
||||
|
||||
use super::pacing::{next_event, queued_event};
|
||||
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Text keys that must arrive together before they read as a paste instead of fast typing.
|
||||
///
|
||||
/// A person cannot get this many keys into one batch, but a loop stalled on a slow frame can queue
|
||||
/// a few, so the bar sits above that.
|
||||
const MIN_BURST_KEYS: usize = 5;
|
||||
|
||||
/// How long a paste may go quiet before it is taken as finished.
|
||||
///
|
||||
/// The console hands a large paste over in chunks, and a tail that arrived alone would run its
|
||||
/// last Enter as a submit.
|
||||
const BURST_GAP: Duration = Duration::from_millis(30);
|
||||
|
||||
/// The longest one burst holds the loop, so a huge paste cannot starve the engine's events.
|
||||
const BURST_CEILING: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Whether this platform delivers a paste as keystrokes.
|
||||
pub(super) const fn pastes_as_keystrokes() -> bool {
|
||||
cfg!(windows)
|
||||
}
|
||||
|
||||
/// What one terminal event adds to a run of pasted text.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Piece {
|
||||
Text(char),
|
||||
/// A key release: part of the run, but no text
|
||||
Quiet,
|
||||
}
|
||||
|
||||
/// The text a key press stands for, or `None` when the event could not be part of a paste.
|
||||
fn piece(event: &Event) -> Option<Piece> {
|
||||
let Event::Key(key) = event else { return None };
|
||||
if !key.modifiers.difference(KeyModifiers::SHIFT).is_empty() {
|
||||
return None;
|
||||
}
|
||||
let character = match key.code {
|
||||
KeyCode::Char(character) => character,
|
||||
KeyCode::Enter => '\n',
|
||||
KeyCode::Tab => '\t',
|
||||
_ => return None,
|
||||
};
|
||||
Some(if key.kind == KeyEventKind::Release { Piece::Quiet } else { Piece::Text(character) })
|
||||
}
|
||||
|
||||
/// Consecutive text key events, kept both raw and as the text they spell.
|
||||
#[derive(Default)]
|
||||
struct Run {
|
||||
events: Vec<Event>,
|
||||
text: String,
|
||||
keys: usize,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn push(&mut self, event: Event, piece: Piece) {
|
||||
if let Piece::Text(character) = piece {
|
||||
self.text.push(character);
|
||||
self.keys += 1;
|
||||
}
|
||||
self.events.push(event);
|
||||
}
|
||||
|
||||
fn looks_pasted(&self) -> bool {
|
||||
self.keys >= MIN_BURST_KEYS
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `first`, folding it and the text keys behind it into one paste when they are one.
|
||||
///
|
||||
/// Answers like `apply_terminal_event`: whether everything applied was idle pointer motion.
|
||||
pub(super) async fn apply_folding_pastes(
|
||||
app: &mut crate::app::App,
|
||||
events: &mut Option<EventStream>,
|
||||
first: Event,
|
||||
exit: &mut super::TuiExit,
|
||||
) -> bool {
|
||||
use super::keys::apply_terminal_event;
|
||||
let Some(opening) = piece(&first).filter(|_| pastes_as_keystrokes()) else {
|
||||
return apply_terminal_event(app, first, exit);
|
||||
};
|
||||
let (run, stopper) = gather(events, first, opening).await;
|
||||
let mut idle = apply_run(app, run, exit);
|
||||
if let Some(event) = stopper {
|
||||
idle &= apply_terminal_event(app, event, exit);
|
||||
}
|
||||
idle
|
||||
}
|
||||
|
||||
/// Applies a run as one paste when it looks like one, and as the keys it was otherwise.
|
||||
fn apply_run(app: &mut crate::app::App, run: Run, exit: &mut super::TuiExit) -> bool {
|
||||
use super::keys::apply_terminal_event;
|
||||
if run.looks_pasted() {
|
||||
return apply_terminal_event(app, Event::Paste(run.text), exit);
|
||||
}
|
||||
let mut idle = true;
|
||||
for event in run.events {
|
||||
idle &= apply_terminal_event(app, event, exit);
|
||||
}
|
||||
idle
|
||||
}
|
||||
|
||||
/// Reads text keys until something else arrives or the run ends, returning that something.
|
||||
async fn gather(
|
||||
events: &mut Option<EventStream>,
|
||||
first: Event,
|
||||
opening: Piece,
|
||||
) -> (Run, Option<Event>) {
|
||||
let mut run = Run::default();
|
||||
run.push(first, opening);
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
let waiting = run.looks_pasted() && started.elapsed() < BURST_CEILING;
|
||||
let Some(event) = next_in_run(events, waiting).await else { return (run, None) };
|
||||
match piece(&event) {
|
||||
Some(piece) => run.push(event, piece),
|
||||
None => return (run, Some(event)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next event: one already queued, else one that lands within the gap when `waiting`.
|
||||
async fn next_in_run(events: &mut Option<EventStream>, waiting: bool) -> Option<Event> {
|
||||
if let Some(event) = queued_event(events.as_mut()).await {
|
||||
return Some(event);
|
||||
}
|
||||
match waiting {
|
||||
true => next_within_gap(events).await,
|
||||
false => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The next event if one lands within [`BURST_GAP`].
|
||||
async fn next_within_gap(events: &mut Option<EventStream>) -> Option<Event> {
|
||||
match tokio::time::timeout(BURST_GAP, next_event(events)).await {
|
||||
Ok(Some(Ok(event))) => Some(event),
|
||||
Ok(Some(Err(error))) => {
|
||||
tracing::warn!(%error, "terminal read failed while gathering a paste");
|
||||
None
|
||||
}
|
||||
Ok(None) | Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crossterm::event::KeyEvent;
|
||||
|
||||
fn key(code: KeyCode, modifiers: KeyModifiers) -> Event {
|
||||
Event::Key(KeyEvent::new(code, modifiers))
|
||||
}
|
||||
|
||||
fn run_of(events: Vec<Event>) -> Run {
|
||||
let mut run = Run::default();
|
||||
for event in events {
|
||||
let piece = piece(&event).expect("every event in these runs is a text key");
|
||||
run.push(event, piece);
|
||||
}
|
||||
run
|
||||
}
|
||||
|
||||
fn typed(text: &str) -> Vec<Event> {
|
||||
text.chars()
|
||||
.map(|character| match character {
|
||||
'\n' => key(KeyCode::Enter, KeyModifiers::NONE),
|
||||
other => key(KeyCode::Char(other), KeyModifiers::NONE),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_becomes_a_newline_and_tab_a_tab() {
|
||||
let run = run_of(typed("a\nb\tc"));
|
||||
assert_eq!(run.text, "a\nb\tc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_below_the_bar_is_typing() {
|
||||
assert!(!run_of(typed("ab\n")).looks_pasted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_at_the_bar_is_a_paste() {
|
||||
assert!(run_of(typed("ab\ncd")).looks_pasted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releases_spell_nothing_and_do_not_count() {
|
||||
let release = Event::Key(KeyEvent::new_with_kind(
|
||||
KeyCode::Char('a'),
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Release,
|
||||
));
|
||||
let mut events = typed("abcd");
|
||||
events.extend((0..10).map(|_| release.clone()));
|
||||
let run = run_of(events);
|
||||
assert_eq!(run.text, "abcd");
|
||||
assert!(!run.looks_pasted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shifted_capital_is_text() {
|
||||
assert_eq!(piece(&key(KeyCode::Char('A'), KeyModifiers::SHIFT)), Some(Piece::Text('A')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chord_is_never_part_of_a_paste() {
|
||||
assert_eq!(piece(&key(KeyCode::Char('c'), KeyModifiers::CONTROL)), None);
|
||||
assert_eq!(piece(&key(KeyCode::Enter, KeyModifiers::ALT)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigation_and_pointer_events_end_a_run() {
|
||||
assert_eq!(piece(&key(KeyCode::Up, KeyModifiers::NONE)), None);
|
||||
assert_eq!(piece(&key(KeyCode::Esc, KeyModifiers::NONE)), None);
|
||||
assert_eq!(piece(&Event::FocusGained), None);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,20 @@ pub(crate) fn accent(mode: &str, styles: &ThemeStyles) -> Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// The comet the activity bar sweeps while a turn runs in `mode`.
|
||||
///
|
||||
/// It follows the mode the engine reports, never the key just pressed: each tool call is judged
|
||||
/// against that mode as it starts, so the color says what the turn can do from here on.
|
||||
pub(crate) fn activity_trail<'a>(
|
||||
mode: &str,
|
||||
styles: &'a ThemeStyles,
|
||||
) -> &'a [Style; crate::theme::styles::ACTIVITY_TRAIL_LEN] {
|
||||
match mode {
|
||||
luxe_core::mode::PLAN => &styles.activity_trail_plan,
|
||||
_ => &styles.activity_trail,
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme, with the border accent swapped for the mode's color.
|
||||
///
|
||||
/// Borrowed in every mode but plan, so the surfaces that take it cost nothing until somebody plans.
|
||||
@@ -71,6 +85,7 @@ mod tests {
|
||||
assert!(matches!(icon("review"), Icon::ModeBuild));
|
||||
assert_eq!(accent("review", &theme), theme.border_accent);
|
||||
assert!(matches!(styles("review", &theme), Cow::Borrowed(_)));
|
||||
assert_eq!(activity_trail("review", &theme), &theme.activity_trail);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,8 +11,8 @@ use color::{blend_rgb, color_value_to_ratatui, plan_hue, rgb_color, rgb_token, t
|
||||
use luxe_core::theme::ColorValue;
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use shades::{
|
||||
shade_at, shade_ramp, Fade, COMET_FADE, CURSOR_LINE_WASH, GAUGE_FADE, PICK_WASH, RAIL_FADE,
|
||||
STREAM_FADE,
|
||||
derived_activity_shades, shade_at, shade_ramp, Fade, CURSOR_LINE_WASH, GAUGE_FADE, PICK_WASH,
|
||||
RAIL_FADE, STREAM_FADE,
|
||||
};
|
||||
pub use shades::{
|
||||
Depth, GaugeShades, SlabShades, ACTIVITY_TRAIL_LEN, SLAB_DEPTHS, STREAM_TRAIL_LEN,
|
||||
@@ -42,6 +42,8 @@ pub struct ThemeStyles {
|
||||
pub text: Style,
|
||||
/// Shades the activity comet wears, its leading cell first, fading toward the rail behind it.
|
||||
pub activity_trail: [Style; ACTIVITY_TRAIL_LEN],
|
||||
/// The comet plan mode wears: the same fade, from plan's hue rather than the accent.
|
||||
pub activity_trail_plan: [Style; ACTIVITY_TRAIL_LEN],
|
||||
/// Shades a spent unit wears as the comet's glow falls off it, nearest the comet first.
|
||||
///
|
||||
/// The last is the canvas itself but for a whisper, so the rail dissolves with distance instead
|
||||
@@ -134,8 +136,7 @@ impl ThemeStyles {
|
||||
diff_add_emphasis,
|
||||
diff_del_emphasis,
|
||||
} = derived_bands(&tokens, tint_base);
|
||||
let (activity_trail, activity_rail) =
|
||||
derived_activity_shades(&tokens, accent, tint_base, light);
|
||||
let activity = derived_activity_shades(&tokens, accent, tint_base, light);
|
||||
|
||||
ThemeStyles {
|
||||
accent,
|
||||
@@ -151,8 +152,9 @@ impl ThemeStyles {
|
||||
muted: fg("muted"),
|
||||
dim: fg("dim"),
|
||||
text: fg("text"),
|
||||
activity_trail,
|
||||
activity_rail,
|
||||
activity_trail: activity.trail,
|
||||
activity_trail_plan: activity.trail_plan,
|
||||
activity_rail: activity.rail,
|
||||
paste_indicator,
|
||||
chip,
|
||||
thinking_text: fg("thinkingText"),
|
||||
@@ -427,27 +429,6 @@ fn derived_bands(tokens: &Tokens<'_>, tint_base: Option<(u8, u8, u8)>) -> Bands
|
||||
}
|
||||
}
|
||||
|
||||
/// The activity comet's trail and the rail it sweeps over.
|
||||
///
|
||||
/// The comet fades from the accent into the rail, so its tail dissolves into the chrome instead of
|
||||
/// stopping at an edge.
|
||||
fn derived_activity_shades(
|
||||
tokens: &Tokens<'_>,
|
||||
accent: Style,
|
||||
tint_base: Option<(u8, u8, u8)>,
|
||||
light: bool,
|
||||
) -> ([Style; ACTIVITY_TRAIL_LEN], [Style; ACTIVITY_TRAIL_LEN]) {
|
||||
let resolved = tokens.0;
|
||||
let rail = rgb_token(resolved, "borderMuted")
|
||||
.or_else(|| rgb_token(resolved, "dim"))
|
||||
.or(tint_base)
|
||||
.unwrap_or(if light { (255, 255, 255) } else { (0, 0, 0) });
|
||||
let activity_trail = shade_ramp(accent, rail, light, COMET_FADE);
|
||||
let canvas = tint_base.unwrap_or(if light { (255, 255, 255) } else { (0, 0, 0) });
|
||||
let activity_rail = shade_ramp(tokens.fg("borderMuted"), canvas, light, RAIL_FADE);
|
||||
(activity_trail, activity_rail)
|
||||
}
|
||||
|
||||
/// Fraction of the status hue mixed into the canvas for a tool-call band. Deliberately low so the
|
||||
/// tint reads as a wash, not a fill.
|
||||
const TOOL_STATUS_TINT: f32 = 0.16;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Shades — fades, the slab and gauge ramps, depths and washes, derived from a theme's tokens.
|
||||
|
||||
use super::color::{blend_rgb, rgb_color};
|
||||
use super::color::{blend_rgb, plan_hue, rgb_color, rgb_token};
|
||||
use ratatui::style::{Color as RatatuiColor, Modifier, Style};
|
||||
|
||||
/// Shades in the activity comet's ramp, its leading cell first.
|
||||
@@ -15,6 +15,39 @@ pub const ACTIVITY_TRAIL_LEN: usize = 10;
|
||||
/// the text you are actually reading is at full contrast.
|
||||
pub const STREAM_TRAIL_LEN: usize = 16;
|
||||
|
||||
/// The activity comet's trails and the rail they sweep over.
|
||||
pub(super) struct ActivityShades {
|
||||
/// Build's comet, and every mode's but plan's: from the accent
|
||||
pub(super) trail: [Style; ACTIVITY_TRAIL_LEN],
|
||||
/// Plan's comet: from plan's hue
|
||||
pub(super) trail_plan: [Style; ACTIVITY_TRAIL_LEN],
|
||||
pub(super) rail: [Style; ACTIVITY_TRAIL_LEN],
|
||||
}
|
||||
|
||||
/// The comets for build and plan, and the rail under them.
|
||||
///
|
||||
/// Each comet fades from its hue into the rail, so its tail dissolves into the chrome instead of
|
||||
/// stopping at an edge. Both land on the one rail, so switching mode recolors the comet alone.
|
||||
pub(super) fn derived_activity_shades(
|
||||
tokens: &super::Tokens<'_>,
|
||||
accent: Style,
|
||||
tint_base: Option<(u8, u8, u8)>,
|
||||
light: bool,
|
||||
) -> ActivityShades {
|
||||
let resolved = tokens.0;
|
||||
let rail = rgb_token(resolved, "borderMuted")
|
||||
.or_else(|| rgb_token(resolved, "dim"))
|
||||
.or(tint_base)
|
||||
.unwrap_or(if light { (255, 255, 255) } else { (0, 0, 0) });
|
||||
let canvas = tint_base.unwrap_or(if light { (255, 255, 255) } else { (0, 0, 0) });
|
||||
let comet = |hue| shade_ramp(hue, rail, light, COMET_FADE);
|
||||
ActivityShades {
|
||||
trail: comet(accent),
|
||||
trail_plan: comet(plan_hue(resolved)),
|
||||
rail: shade_ramp(tokens.fg("borderMuted"), canvas, light, RAIL_FADE),
|
||||
}
|
||||
}
|
||||
|
||||
/// How a ramp fades: its curve, what it keeps at the far end, and the lift on its near end.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) struct Fade {
|
||||
|
||||
@@ -177,9 +177,9 @@ fn first_steps(app: &App, width: usize) -> Option<Line<'static>> {
|
||||
|
||||
/// One row of the sweeping activity bar, as spans that can share a line with text.
|
||||
///
|
||||
/// The comet sweeps in shades of the theme accent, and the rail it travels is lit by the comet
|
||||
/// rather than drawn at a fixed weight, so the indicator belongs to the chrome and the motion is the
|
||||
/// only thing that draws the eye.
|
||||
/// The comet sweeps in shades of the theme accent, or of plan's hue while the session plans, and the
|
||||
/// rail it travels is lit by the comet rather than drawn at a fixed weight, so the indicator belongs
|
||||
/// to the chrome and the motion is the only thing that draws the eye.
|
||||
fn activity_bar_spans(app: &App, width: usize) -> Vec<Span<'static>> {
|
||||
use crate::widgets::ActivityGlyphs;
|
||||
use luxe_core::config::ActivityBarStyle;
|
||||
@@ -197,7 +197,7 @@ fn activity_bar_spans(app: &App, width: usize) -> Vec<Span<'static>> {
|
||||
app.status.spinner_frame as u64,
|
||||
width,
|
||||
glyphs,
|
||||
&styles.activity_trail,
|
||||
crate::modes::activity_trail(&app.status.mode, styles),
|
||||
&styles.activity_rail,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ mod files;
|
||||
mod plan;
|
||||
mod telemetry;
|
||||
mod tree;
|
||||
mod usage;
|
||||
|
||||
use crate::app::App;
|
||||
use crate::workspace_dock::{DockPresentation, DockSectionModel};
|
||||
|
||||
@@ -65,6 +65,7 @@ pub(super) enum Section {
|
||||
Files,
|
||||
Elsewhere,
|
||||
Model,
|
||||
Usage,
|
||||
Session,
|
||||
}
|
||||
|
||||
@@ -77,6 +78,7 @@ impl Section {
|
||||
Self::Files => "FILES",
|
||||
Self::Elsewhere => "ELSEWHERE",
|
||||
Self::Model => "MODEL",
|
||||
Self::Usage => "USAGE",
|
||||
Self::Session => "SESSION",
|
||||
}
|
||||
}
|
||||
@@ -94,7 +96,7 @@ impl Section {
|
||||
match self {
|
||||
Self::Project | Self::Model => Depth::Hero,
|
||||
Self::Plan | Self::Files => Depth::Raised,
|
||||
Self::Elsewhere | Self::Session => Depth::Recessed,
|
||||
Self::Elsewhere | Self::Usage | Self::Session => Depth::Recessed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,6 +192,7 @@ pub(super) fn telemetry_lines(app: &App) -> Vec<Line<'static>> {
|
||||
let row = row_width(app);
|
||||
let column = telemetry_label_width(row, WIDEST_TELEMETRY_LABEL);
|
||||
let mut lines = model_telemetry(app, row, column);
|
||||
lines.extend(super::usage::usage_telemetry(app, column));
|
||||
lines.extend(session_telemetry(app, row, column));
|
||||
lines
|
||||
}
|
||||
@@ -386,7 +387,7 @@ fn review_spending(app: &App) -> bool {
|
||||
///
|
||||
/// `ink` is body text for a measurement, dim for a share of one above it, and the severity hue for
|
||||
/// the window, which is the one value that is also a warning.
|
||||
fn telemetry_row(
|
||||
pub(super) fn telemetry_row(
|
||||
label: &str,
|
||||
value: String,
|
||||
ink: ratatui::style::Style,
|
||||
|
||||
@@ -38,6 +38,42 @@ fn the_rail_reports_a_session_that_is_approving_its_own_asks() {
|
||||
assert!(row.contains("auto-approve"), "{row}");
|
||||
}
|
||||
|
||||
/// An API-key provider reports no allowance, and a USAGE heading over nothing would be noise.
|
||||
#[test]
|
||||
fn the_rail_has_no_usage_block_without_a_plan() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(!rendered.iter().any(|row| row.contains("USAGE")), "{rendered:?}");
|
||||
}
|
||||
|
||||
/// The point of the block: the share spent and the time left, one row per window the plan has.
|
||||
#[test]
|
||||
fn the_rail_shows_each_plan_window_with_its_meter_and_reset() {
|
||||
use luxe_core::provider::{PlanUsage, PlanWindow};
|
||||
let mut app = app();
|
||||
app.status.model = "gpt-5".into();
|
||||
app.status.plan_usage = Some(PlanUsage {
|
||||
primary: Some(PlanWindow {
|
||||
used_percent: 30.0,
|
||||
window_minutes: 10_080,
|
||||
resets_in_secs: Some(274_000),
|
||||
}),
|
||||
secondary: Some(PlanWindow {
|
||||
used_percent: 80.0,
|
||||
window_minutes: 300,
|
||||
resets_in_secs: Some(1_800),
|
||||
}),
|
||||
..PlanUsage::default()
|
||||
});
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(rendered.iter().any(|row| row.contains("USAGE")), "{rendered:?}");
|
||||
let weekly = rendered.iter().find(|row| row.starts_with("weekly")).expect("weekly row");
|
||||
assert!(weekly.contains("▓▓▓░░░░░░░ 30% · 3d 4h"), "{weekly}");
|
||||
let short = rendered.iter().find(|row| row.starts_with("5h")).expect("5h row");
|
||||
assert!(short.contains("▓▓▓▓▓▓▓▓░░ 80% · 30m"), "{short}");
|
||||
}
|
||||
|
||||
/// The surface behind the span carrying `needle` — the slab the badge is cut from.
|
||||
pub(super) fn surface_behind(line: &Line<'_>, needle: &str) -> Color {
|
||||
line.spans
|
||||
@@ -65,7 +101,7 @@ fn the_rail_is_anchored_at_both_ends_and_recedes_between_them() {
|
||||
for live in [Section::Plan, Section::Files] {
|
||||
assert_eq!(surface(live), shades.at(Depth::Raised), "{live:?} is one step back");
|
||||
}
|
||||
for ambient in [Section::Elsewhere, Section::Session] {
|
||||
for ambient in [Section::Elsewhere, Section::Usage, Section::Session] {
|
||||
assert_eq!(surface(ambient), shades.at(Depth::Recessed), "{ambient:?} is two");
|
||||
}
|
||||
// Or every assertion above passes on a theme with no ramp at all.
|
||||
|
||||
63
crates/luxe-tui/src/view/dock/usage.rs
Normal file
63
crates/luxe-tui/src/view/dock/usage.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! Dock usage — the USAGE block: how much of a subscription plan is spent, and when it resets.
|
||||
|
||||
use super::chrome::{section_heading_line, Section};
|
||||
use super::telemetry::telemetry_row;
|
||||
use crate::app::App;
|
||||
use luxe_core::provider::PlanWindow;
|
||||
use ratatui::text::Line;
|
||||
|
||||
/// Cells in the meter: ten reads in tenths, and leaves the percentage and countdown room beside it
|
||||
/// on the default rail.
|
||||
const BAR_CELLS: usize = 10;
|
||||
|
||||
/// The USAGE block, drawn only while the provider reports a plan window.
|
||||
///
|
||||
/// An API-key provider reports no allowance, so it gets no block at all rather than an empty one.
|
||||
/// Each window gets its own row: a plan with a 5h and a weekly window is limited by whichever
|
||||
/// fills first, and the reader can't steer by one they can't see.
|
||||
pub(super) fn usage_telemetry(app: &App, column: usize) -> Vec<Line<'static>> {
|
||||
let Some(plan) = app.status.plan_usage.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let windows: Vec<&PlanWindow> =
|
||||
[&plan.primary, &plan.secondary].into_iter().flatten().collect();
|
||||
if windows.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let styles = &app.theme_styles;
|
||||
let mut lines = vec![Line::default(), section_heading_line(Section::Usage, app)];
|
||||
for window in windows {
|
||||
let ink = styles.context_fill(window.used_percent.clamp(0.0, 100.0));
|
||||
lines.push(telemetry_row(&window.window_label(), window_value(window), ink, column, app));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// `▓▓▓░░░░░░░ 32% · 3d 4h`: the meter, the share, and the time left when the provider says.
|
||||
fn window_value(window: &PlanWindow) -> String {
|
||||
let mut value = format!("{} {:.0}%", window.bar(BAR_CELLS), window.used_percent);
|
||||
if let Some(reset) = window.reset_label() {
|
||||
value.push_str(&format!(" · {reset}"));
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn window(used: f32, resets: Option<u64>) -> PlanWindow {
|
||||
PlanWindow { used_percent: used, window_minutes: 10_080, resets_in_secs: resets }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_shows_meter_share_and_countdown() {
|
||||
assert_eq!(window_value(&window(30.0, Some(274_000))), "▓▓▓░░░░░░░ 30% · 3d 4h");
|
||||
}
|
||||
|
||||
/// Copilot reports no reset countdown, and the row must not invent one.
|
||||
#[test]
|
||||
fn a_window_without_a_reset_time_omits_the_countdown() {
|
||||
assert_eq!(window_value(&window(30.0, None)), "▓▓▓░░░░░░░ 30%");
|
||||
}
|
||||
}
|
||||
@@ -145,6 +145,7 @@ conversation, or in its place below 80 columns.
|
||||
| **FILES** | The project as a tree, with what changed marked in it. Click a file to [preview](#preview) it. |
|
||||
| **ELSEWHERE** | Files the session changed outside the project, when there are any |
|
||||
| **MODEL** | The provider, model, thinking level and [mode](agent.md#plan-then-build). Click the provider or the model to change it, or the mode to switch it. |
|
||||
| **USAGE** | What is left of a ChatGPT or Copilot plan, one row for each window the plan has: a bar, the share used and, when the provider says, the time until it resets. It shows only once the plan has reported, after your first reply, and never on an API key. |
|
||||
| **SESSION** | Context used, tokens and cost, with what a review and compaction cost on rows of their own. A review's row shows its full cost once its guide or drafted summary is done. While a phone or another client has [joined](remote.md), a **joined** row names it. |
|
||||
|
||||
`alt+d` shows or hides the dock, and `/dock left` or `/dock right` moves it. To set it for good:
|
||||
|
||||
@@ -146,7 +146,8 @@ Usage on a ChatGPT or Copilot subscription is counted in full but never added to
|
||||
`plan ≈$0.42 of usage over 12 calls, covered by your subscription`. On a
|
||||
ChatGPT plan, the statusline shows how much of the plan is used, such as `12% weekly`, and `/cost`
|
||||
shows when it resets. On a Copilot plan it shows the month's allowance the same way, such as `19%
|
||||
monthly`.
|
||||
monthly`. The dock's [USAGE section](interface.md#the-dock) shows the same windows as a bar, with the
|
||||
time until each resets when the provider says.
|
||||
|
||||
luxe prices Copilot usage at Copilot's per-token rates, so the figure matches what Copilot reports
|
||||
for each request. A Copilot plan billed by the token spends its monthly allowance at those rates.
|
||||
|
||||
@@ -256,8 +256,9 @@ needed, such as a passwordless `sudo` rule for one program:
|
||||
|
||||
The `screenshot` tool's `url` mode renders a web page and captures only that. Its `fullscreen`,
|
||||
`region` and `window` modes capture whatever is on your screen, and the image goes to your model
|
||||
provider, so each **asks** first, and runs with nobody watching refuse them. To turn screen capture
|
||||
off entirely:
|
||||
provider, so each **asks** first, and runs with nobody watching refuse them. On macOS, `window` can
|
||||
also capture a window on another desktop, and when no window matches it tells the model the titles
|
||||
of the windows it saw. To turn screen capture off entirely:
|
||||
|
||||
```json title="~/.config/luxe/permissions.json"
|
||||
{ "permission": { "screenshot": { "fullscreen": "deny", "region": "deny", "window": "deny" } } }
|
||||
|
||||
@@ -100,6 +100,13 @@ const MIME = {
|
||||
".wasm": "application/wasm",
|
||||
};
|
||||
|
||||
/**
|
||||
* Where both servers listen and every browser and probe connects: an address, not `localhost`.
|
||||
* In a container `localhost` can name `::1` to the server binding it and `127.0.0.1` to the
|
||||
* client dialing it, and in Playwright's image the dev server came up and refused every request.
|
||||
*/
|
||||
const LOOPBACK = "127.0.0.1";
|
||||
|
||||
/** Serves `web/dist` the way a static host would, including the `.wasm` type the player needs. */
|
||||
function serveBuilt(root) {
|
||||
return new Promise((resolve) => {
|
||||
@@ -123,7 +130,7 @@ function serveBuilt(root) {
|
||||
}
|
||||
response.writeHead(404).end("not found");
|
||||
});
|
||||
server.listen(0, () => resolve({ server, port: server.address().port }));
|
||||
server.listen(0, LOOPBACK, () => resolve({ server, port: server.address().port }));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,10 +151,35 @@ async function serveDev(port) {
|
||||
// shell that launched this with it. Spawned directly, `child.kill()` is the server.
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[join(web, "node_modules/astro/bin/astro.mjs"), "dev", "--port", String(port)],
|
||||
{ cwd: web, stdio: "ignore" },
|
||||
[join(web, "node_modules/astro/bin/astro.mjs"), "dev", "--host", LOOPBACK, "--port", String(port)],
|
||||
{ cwd: web, stdio: ["ignore", "pipe", "pipe"] },
|
||||
);
|
||||
return { child, port };
|
||||
return watchServer({ child, port, output: [], exit: null });
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the last of what `target`'s server prints, and how it ended, so a server that never
|
||||
* answers can say why. Read either way: a pipe nobody drains fills up and stalls its server.
|
||||
*/
|
||||
function watchServer(target) {
|
||||
const keep = (chunk) => {
|
||||
target.output.push(...String(chunk).split("\n").filter((line) => line.trim()));
|
||||
target.output.splice(0, Math.max(0, target.output.length - 30));
|
||||
};
|
||||
target.child.stdout.on("data", keep);
|
||||
target.child.stderr.on("data", keep);
|
||||
target.child.on("exit", (code, signal) => {
|
||||
target.exit = signal ?? `exit code ${code}`;
|
||||
});
|
||||
return target;
|
||||
}
|
||||
|
||||
/** Why `target`'s server never answered, with the last of what it printed. */
|
||||
function reportSilentServer(name, target) {
|
||||
const why = target.exit ? `it ended (${target.exit})` : "it was still running";
|
||||
console.log(`✗ ${name.padEnd(9)} the dev server never answered; ${why}`);
|
||||
console.log(` the last ask got: ${target.lastAnswer ?? "nothing yet"}`);
|
||||
for (const line of target.output) console.log(` ${line}`);
|
||||
}
|
||||
|
||||
function shutdown(target) {
|
||||
@@ -157,13 +189,15 @@ function shutdown(target) {
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForServer(port, seconds = 90) {
|
||||
for (let attempt = 0; attempt < seconds * 2; attempt += 1) {
|
||||
async function waitForServer(target, seconds = 90) {
|
||||
for (let attempt = 0; attempt < seconds * 2 && !target.exit; attempt += 1) {
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${port}/`);
|
||||
const response = await fetch(`http://${LOOPBACK}:${target.port}/`);
|
||||
if (response.ok) return true;
|
||||
} catch {
|
||||
/* not up yet */
|
||||
target.lastAnswer = `HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`;
|
||||
} catch (error) {
|
||||
// Not up yet, usually; the cause is what tells a refused port from a wrong address
|
||||
target.lastAnswer = `${error.message}${error.cause ? ` (${error.cause.code ?? error.cause.message})` : ""}`;
|
||||
}
|
||||
await new Promise((done) => setTimeout(done, 500));
|
||||
}
|
||||
@@ -210,7 +244,7 @@ async function demosFit(browser, port, path) {
|
||||
const tab = await context.newPage();
|
||||
const problems = [];
|
||||
try {
|
||||
await tab.goto(`http://localhost:${port}${path}`, { waitUntil: "networkidle" });
|
||||
await tab.goto(`http://${LOOPBACK}:${port}${path}`, { waitUntil: "networkidle" });
|
||||
await settleHero(tab);
|
||||
const demos = tab.locator(".demo");
|
||||
const count = await demos.count();
|
||||
@@ -279,7 +313,7 @@ async function checkEngine(engine, name, port) {
|
||||
noise.push(`request failed: ${request.url()} (${request.failure()?.errorText})`);
|
||||
});
|
||||
|
||||
await tab.goto(`http://localhost:${port}${page.path}`, { waitUntil: "networkidle" });
|
||||
await tab.goto(`http://${LOOPBACK}:${port}${page.path}`, { waitUntil: "networkidle" });
|
||||
await settleHero(tab);
|
||||
|
||||
if (page.demos) {
|
||||
@@ -366,8 +400,8 @@ for (const [name, engine] of [
|
||||
if (!built) {
|
||||
shutdown(current);
|
||||
current = await serveDev((port += 1));
|
||||
if (!(await waitForServer(current.port))) {
|
||||
console.log(`✗ ${name.padEnd(9)} the dev server never answered`);
|
||||
if (!(await waitForServer(current))) {
|
||||
reportSilentServer(name, current);
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
117
web/package-lock.json
generated
117
web/package-lock.json
generated
@@ -12,7 +12,7 @@
|
||||
"@astrojs/sitemap": "^3.7.4",
|
||||
"@astrojs/svelte": "^9.0.1",
|
||||
"asciinema-player": "^3.17.0",
|
||||
"astro": "^7.3.2",
|
||||
"astro": "^7.3.3",
|
||||
"svelte": "^5.57.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -711,9 +711,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workerd-darwin-64": {
|
||||
"version": "1.20261012.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261012.1.tgz",
|
||||
"integrity": "sha512-dkTL9aY3V4D40b+jBpGPCistWUPFQ/M61wlWi6i1o8MvHFFgEw7EQkcaYEv6Yd3bkPDD/3TFT4hRsMb2xVZSwQ==",
|
||||
"version": "1.20261019.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz",
|
||||
"integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -728,9 +728,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workerd-darwin-arm64": {
|
||||
"version": "1.20261012.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261012.1.tgz",
|
||||
"integrity": "sha512-2/nVGcKXjNNI+DhxKSepTKvFng9H7aN2WXv6Zu67iqgI6JrxypNt5kTPv4ZHosxrcfyKMci/2RfN7GIrN0BitQ==",
|
||||
"version": "1.20261019.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz",
|
||||
"integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -745,9 +745,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workerd-linux-64": {
|
||||
"version": "1.20261012.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261012.1.tgz",
|
||||
"integrity": "sha512-uMe7ONHnLxStD1Ye0YFHBO36uj4cStv5P53rW+5GVWXFT8BRjqVixlH0IqCAHe1Pmcwyd1+7fVoGde89MZSCJg==",
|
||||
"version": "1.20261019.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz",
|
||||
"integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -762,9 +762,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workerd-linux-arm64": {
|
||||
"version": "1.20261012.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261012.1.tgz",
|
||||
"integrity": "sha512-I0VMdcXk7ygG5vYDce0ePTBFdnBXC0i9WiBY5mWiv0iTinbfea6/rHqSQ7B1UMpjgrYVs9E0m4bZ9ufsk5GCFA==",
|
||||
"version": "1.20261019.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz",
|
||||
"integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -779,9 +779,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workerd-windows-64": {
|
||||
"version": "1.20261012.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261012.1.tgz",
|
||||
"integrity": "sha512-c5hQvNx574UEoknaCFvMa/NdLrrYiALNbe6sx1okW8uOiRYWxrFuA8WpXFnBJ5XJypm0TEAHYaUTGv3rRLpY7Q==",
|
||||
"version": "1.20261019.1",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz",
|
||||
"integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -2954,9 +2954,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/astro": {
|
||||
"version": "7.3.2",
|
||||
"resolved": "https://registry.npmjs.org/astro/-/astro-7.3.2.tgz",
|
||||
"integrity": "sha512-ysTcdpGP61XZpHoMRYC/CK19DQ94qkBvzXMtXEo0gEqPNkmOU/Tv++CtWmzaI4nF2Ck8RXFdiWvdlTWa2oOr9w==",
|
||||
"version": "7.3.3",
|
||||
"resolved": "https://registry.npmjs.org/astro/-/astro-7.3.3.tgz",
|
||||
"integrity": "sha512-NF08hk3edFkVmr9avf9HW/rQyf6NrpbVDyYj2cVN3JfijDhfJYh1ivWVTY5PUd5+rRZn/Vtu4iaeyNlP0Iv6mg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@astrojs/compiler-rs": "^0.4.0",
|
||||
@@ -2978,7 +2978,7 @@
|
||||
"dset": "^3.1.4",
|
||||
"es-module-lexer": "^2.0.0",
|
||||
"esbuild": "^0.28.0",
|
||||
"find-proc": "0.1.0",
|
||||
"find-proc": "0.2.0",
|
||||
"flattie": "^1.1.1",
|
||||
"fontace": "~0.4.1",
|
||||
"get-tsconfig": "5.0.0-beta.4",
|
||||
@@ -2997,16 +2997,16 @@
|
||||
"package-manager-detector": "^1.6.0",
|
||||
"piccolore": "^0.1.3",
|
||||
"picomatch": "^4.0.4",
|
||||
"semver": "^7.7.4",
|
||||
"shiki": "^4.0.2",
|
||||
"smol-toml": "^1.6.0",
|
||||
"svgo": "^4.0.1",
|
||||
"svgo": "^4.0.2",
|
||||
"tinyclip": "^0.1.12",
|
||||
"tinyexec": "^1.0.4",
|
||||
"tinyglobby": "^0.2.15",
|
||||
"ultrahtml": "^1.6.0",
|
||||
"unifont": "~0.7.5",
|
||||
"unstorage": "^1.17.5",
|
||||
"verkit": "^0.4.0",
|
||||
"vite": "^8.0.13",
|
||||
"vitefu": "^1.1.2",
|
||||
"xxhash-wasm": "^1.1.0",
|
||||
@@ -3812,9 +3812,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.8",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
|
||||
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
|
||||
"version": "3.1.9",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",
|
||||
"integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -3855,9 +3855,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/find-proc": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/find-proc/-/find-proc-0.1.0.tgz",
|
||||
"integrity": "sha512-OaOpEYv2PiQ7SQ5LIrl+deA1XaWcxEjnpM6VuWXTUvn+teIXxeFTLDmu18/zDQpFmHN4o3oDBX+BT0AGwEhemg==",
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/find-proc/-/find-proc-0.2.0.tgz",
|
||||
"integrity": "sha512-a6h2nTrgB3g5Wrn4au9Ux4kMk7IJtyF6oA8uGn+mk3weLZssUtc1cp6meHIzzuW2o1srrBAxzkmXLbqjRkgB6w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
@@ -5740,16 +5740,16 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/miniflare": {
|
||||
"version": "5.20261012.0-beta",
|
||||
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261012.0-beta.tgz",
|
||||
"integrity": "sha512-Cjrs+vHHQ7krLO4HYELYpYBJBuMhcnNZD/Z5z/UcQSnFqWSQY3DhtTCFalXgI1/yO1iK+YrRKK8EYkumrEopxg==",
|
||||
"version": "5.20261019.2-beta",
|
||||
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.2-beta.tgz",
|
||||
"integrity": "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-support": "0.8.1",
|
||||
"sharp": "0.35.5",
|
||||
"undici": "7.29.1",
|
||||
"workerd": "1.20261012.1",
|
||||
"workerd": "1.20261019.1",
|
||||
"ws": "8.21.0",
|
||||
"youch": "4.1.0-beta.10"
|
||||
},
|
||||
@@ -6603,6 +6603,7 @@
|
||||
"version": "7.8.5",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||
"devOptional": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
@@ -7063,9 +7064,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "8.11.2",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz",
|
||||
"integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==",
|
||||
"version": "8.12.3",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz",
|
||||
"integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22.19.0"
|
||||
@@ -7377,6 +7378,18 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/verkit": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/verkit/-/verkit-0.4.1.tgz",
|
||||
"integrity": "sha512-mMVzj0TXExtVdlDEq+Mzp0eyOuyznNpFobNM3uAqe3HVm/Ps2c+u17BligMkZjZCA6EiXpoon8iRTer3iu40SQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.12.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sxzz"
|
||||
}
|
||||
},
|
||||
"node_modules/vfile": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
|
||||
@@ -7816,9 +7829,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/workerd": {
|
||||
"version": "1.20261012.1",
|
||||
"resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261012.1.tgz",
|
||||
"integrity": "sha512-tEHoMPsMga0seVjxfsR8Pd3f8IRqYwkq++dTUKI5Gdgj6zuSDluYwisydq+dn90SsIACwBquJUQ1nBpcOqaWTA==",
|
||||
"version": "1.20261019.1",
|
||||
"resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz",
|
||||
"integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
@@ -7829,17 +7842,17 @@
|
||||
"node": ">=16"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@cloudflare/workerd-darwin-64": "1.20261012.1",
|
||||
"@cloudflare/workerd-darwin-arm64": "1.20261012.1",
|
||||
"@cloudflare/workerd-linux-64": "1.20261012.1",
|
||||
"@cloudflare/workerd-linux-arm64": "1.20261012.1",
|
||||
"@cloudflare/workerd-windows-64": "1.20261012.1"
|
||||
"@cloudflare/workerd-darwin-64": "1.20261019.1",
|
||||
"@cloudflare/workerd-darwin-arm64": "1.20261019.1",
|
||||
"@cloudflare/workerd-linux-64": "1.20261019.1",
|
||||
"@cloudflare/workerd-linux-arm64": "1.20261019.1",
|
||||
"@cloudflare/workerd-windows-64": "1.20261019.1"
|
||||
}
|
||||
},
|
||||
"node_modules/wrangler": {
|
||||
"version": "4.151.0",
|
||||
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.151.0.tgz",
|
||||
"integrity": "sha512-ra8MpzSR+ClkbGofu9S+AmAKjytS60MqSuayXKpa1CAYIzP+NIc8q6EiF55Gz5PS3lxT4qcvMuPHihCNhTPpDg==",
|
||||
"version": "4.152.0",
|
||||
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.152.0.tgz",
|
||||
"integrity": "sha512-lmXTF1sCDEqBaEMpreGczvg/x3AIh1d/qxc4BN7utQ4jEDwdA4YG0L6kr3ev0TtVLHRb6QLySNAOAunwn+dHeA==",
|
||||
"dev": true,
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"dependencies": {
|
||||
@@ -7847,10 +7860,10 @@
|
||||
"@cloudflare/unenv-preset": "2.16.2",
|
||||
"blake3-wasm": "2.1.5",
|
||||
"esbuild": "0.28.2",
|
||||
"miniflare": "5.20261012.0-beta",
|
||||
"miniflare": "5.20261019.2-beta",
|
||||
"path-to-regexp": "6.3.0",
|
||||
"unenv": "2.0.0-rc.24",
|
||||
"workerd": "1.20261012.1"
|
||||
"workerd": "1.20261019.1"
|
||||
},
|
||||
"bin": {
|
||||
"cf-wrangler": "bin/cf-wrangler.js",
|
||||
@@ -7864,7 +7877,7 @@
|
||||
"fsevents": "2.3.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@cloudflare/workers-types": "^5.20261006.1"
|
||||
"@cloudflare/workers-types": "^5.20261019.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@cloudflare/workers-types": {
|
||||
@@ -8079,9 +8092,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.6.5",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
|
||||
"integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
|
||||
"version": "4.6.7",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
|
||||
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"@astrojs/sitemap": "^3.7.4",
|
||||
"@astrojs/svelte": "^9.0.1",
|
||||
"asciinema-player": "^3.17.0",
|
||||
"astro": "^7.3.2",
|
||||
"astro": "^7.3.3",
|
||||
"svelte": "^5.57.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Reference in New Issue
Block a user