diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a312567..3aa35c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -136,9 +136,7 @@ jobs: - name: Webfonts cover the assets run: scripts/site-fonts.sh --check - # The one part of docs/brand/voice.md a machine can judge. Everything else in it — evidence - # with claims, naming the trade-off — is a human's call, and a checker that pretended otherwise - # would be one nobody trusts. + # The part of docs/brand/voice.md a machine can judge: banned words and British spellings - name: Voice run: python3 scripts/voice-check.py @@ -162,6 +160,24 @@ jobs: env: RUSTDOCFLAGS: -D warnings + # The phone app's end-to-end test drives a real `luxe` (a session, the bridge, pairing) in + # WebKit, the only engine an iPhone has. It runs here because the Build step above already + # made `target/debug/luxe`: a job of its own would compile the workspace a second time, and + # the binary is too large to hand between jobs cheaply. The app's types and unit tests need + # no Rust, so they stay in `remote-app`. + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + cache: npm + cache-dependency-path: crates/luxe-remote/app-tests/package-lock.json + + - name: Phone app end to end (WebKit) + working-directory: crates/luxe-remote/app-tests + run: | + npm ci + npx playwright install --with-deps webkit + npm run e2e + # Does it build and pass on the platforms nobody develops on? Linux above is the canonical gate — # `fmt` is an answer about the source, not about the OS, so running it three times would only # triple the noise from one rule. What cannot be known without a real runner is whether the code @@ -342,12 +358,42 @@ jobs: run: node ../scripts/site-cross.mjs --require webkit working-directory: web + # The phone app `luxe remote` serves. It ships as written, with no build step, so this is where a + # type error gets caught: its JSDoc checked by tsc, and its folds unit-tested. The end-to-end + # test, one whole turn in WebKit, runs in `gate`, which already has a `luxe` built. + remote-app: + name: phone app + needs: changes + if: needs.changes.outputs.code == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + defaults: + run: + working-directory: crates/luxe-remote/app-tests + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + cache: npm + cache-dependency-path: crates/luxe-remote/app-tests/package-lock.json + + - name: Install + run: npm ci + + - name: Types + run: npm run check + + - name: Unit tests + run: npm test + # The one check a ruleset requires. A skipped job reports as passing but a skipped matrix job # reports under no name a ruleset can hold, so this sums them up: it fails when any job failed or # was cancelled, `changes` included, and passes when each one passed or had nothing to check. passed: name: CI passed - needs: [changes, gate, portability, msrv, supply-chain, website] + needs: [changes, gate, portability, msrv, supply-chain, website, remote-app] if: always() runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/.gitignore b/.gitignore index 36c773f..a3f78a3 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,9 @@ web/node_modules/ web/dist/ # Wrangler's dev-server scratch: caches, a shim worker, and its source maps. web/.wrangler/ + +# The phone app's type checker, test libraries and browser driver +crates/luxe-remote/app-tests/node_modules/ web/.astro/ # cargo-mutants scratch output diff --git a/AGENTS.md b/AGENTS.md index 5e2f2f9..236e252 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,27 +1,27 @@ -# AGENTS.md — Luxe +# AGENTS.md -Rules for working in this repository. Each line is something a capable engineer would get wrong -without being told; anything the code already shows is left out, because this file rides in every -request. Process, tooling and the long explanations are in [`CONTRIBUTING.md`](CONTRIBUTING.md). +Rules for working on Luxe: only what you'd get wrong without being told. It's sent with every +request, so keep it short; the long version is [`CONTRIBUTING.md`](CONTRIBUTING.md). ## Commands ```bash -cargo check -p # the inner loop -cargo nextest run --workspace # ~15s once compiled +cargo check -p # quick loop +cargo nextest run --workspace # ~15s once built cargo clippy --workspace --all-targets -- -D warnings cargo fmt --all --check cargo deny check RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps # a broken doc link fails CI -cargo test --workspace --examples # nextest does NOT run these -python3 scripts/size-check.py # file-size ratchet (--report lists) -python3 scripts/fn-length-check.py # function-length ratchet -python3 scripts/voice-check.py # reads source comments too -python3 scripts/docs-check.py # the guide's links, frontmatter, voice +cargo test --workspace --examples # nextest skips these +python3 scripts/size-check.py # file size limit +python3 scripts/fn-length-check.py # function length limit +python3 scripts/voice-check.py # banned words, British spelling +python3 scripts/docs-check.py # guide links, frontmatter, words +python3 scripts/version-check.py # a shipped change bumps one step scripts/guide-bundle.sh # after editing docs/guide scripts/site-assets.sh --check # generated web assets are current -scripts/site-fonts.sh --check # webfonts cover those assets -(cd web && npm run cross) # the demos boot in every engine +scripts/site-fonts.sh --check # web fonts cover those assets +(cd web && npm run cross) # site demos run in every browser engine scripts/win-check.sh [--clippy] # the suite for Windows, under wine scripts/install-dev.sh # rebuild the release binary on PATH @@ -29,160 +29,144 @@ cargo run -p luxe-cli -- # the TUI cargo run -p luxe-cli -- --headless -p "..." # one prompt, no UI ``` -Run the whole gate before calling work done, and `scripts/win-check.sh` in **both modes** before -calling anything cross-platform done: CI also lints the Windows target, and a `#[cfg(unix)]` helper -left unused there is a `-D warnings` error the default run cannot see. The voice check reads -**source comments**, so one British spelling in a doc comment fails the build (it checks itself; -do not quote the words it bans). A new glyph that reaches a captured surface needs -`scripts/site-fonts.sh` after `site-assets.sh`, or it ships as tofu. +## Before you call it done -- **Never run two builds or test runs at once.** They thrash and both take longer. Wrap unattended - runs in `timeout `; never poll with `while pgrep cargo`. -- **A slow run is compiling, not hanging.** `.config/nextest.toml` kills any test over ~120s. -- **`luxe` on `PATH` is `target/release/luxe`, and nothing above builds release.** When a reported - defect contradicts the source, check the binary's date against the fix before re-debugging. +- Run the whole list. For anything cross-platform, run `scripts/win-check.sh` with and without + `--clippy`: CI lints Windows, and an unused `#[cfg(unix)]` helper fails there. +- One build or test run at a time. Wrap unattended runs in `timeout `; never poll with + `while pgrep cargo`. A slow run is compiling, not stuck: nextest kills tests over ~120s. +- `luxe` on `PATH` is `target/release/luxe`, and only `install-dev.sh` rebuilds it. If a bug report + contradicts the source, check the binary's date first. +- The voice check reads code comments too: one British spelling in a doc comment fails CI. +- A new glyph on a captured screen needs `site-assets.sh`, then `site-fonts.sh`, or it shows as a + box. -## Architecture boundaries +## Architecture -- **Dependencies point inward to `luxe-core`.** Allowed: `providers`, `tools`, `lsp`, `dap`, `mcp` - and `tui` → `core`; `cli` → all of them. Forbidden: `core` → anything in-workspace; `tui` → - `providers`/`tools` (go through core traits). -- **`core` is pure logic and traits: no UI, no HTTP.** No `reqwest`, no `ratatui`. Spawning a - process is fine (git, hooks, formatters, the MCP stdio transport); network I/O lives in - `luxe-providers`, `luxe-tools`' web tools and `luxe-cli`, with any policy (`luxe-core::update`) - kept in core. -- **UI talks to core only over channels.** `Action` in, `Event` out. A UI never calls a provider or - a tool directly and never blocks the runtime. -- **Cross-cutting behavior is a `Hook`**, not a special case threaded through the loop. +- Dependencies point in, to `luxe-core`. `providers`, `tools`, `lsp`, `dap`, `mcp`, `remote` and + `tui` may use `core`; `cli` may use all of them. `core` uses no workspace crate, and `tui` never + uses `providers` or `tools` (go through core traits). +- `core` is logic and traits: no UI, no HTTP, no `reqwest` or `ratatui`. Spawning processes is + fine. Network code lives in `luxe-providers`, `luxe-tools`' web tools, `luxe-remote` and + `luxe-cli`; its policy (like `luxe-core::update`) stays in core. +- A UI talks to core over channels only: `Action` in, `Event` out. It never calls a provider or a + tool and never blocks the runtime. +- Behavior that cuts across the loop is a `Hook`, not a special case in the loop. +- One owner per platform question: `user_dirs` (home and Luxe's folders), `program` (finding + programs and shells, detaching, killing a process tree), `paths` (path to string), `fs_atomic` + (safe file replace), `luxe-lsp::uri` (`file://` URLs). -## Rust conventions +## Rust -- **Modules:** `foo.rs` beside `foo/`, never `foo/mod.rs`, except `luxe-core/tests/common/`, since - each top-level file under `tests/` is its own binary. -- **Errors:** `thiserror` enums in libraries, `anyhow` only in `luxe-cli`. No `unwrap()`/`expect()` - on a fallible path; `expect()` is for real invariants and says why. **Branch on the variant, - never on the message**: a `to_string()` match turns rewording an error into a silent behavior - change. Messages are lowercase with no trailing period. -- **Async:** `tokio`; `spawn_blocking` for blocking work. **Turns must be abortable**: cancellation - drops the future, so anything spawned needs `kill_on_drop` or its own process-group guard. -- **Logging:** `tracing`, structured fields over interpolation, secrets through the redaction - layer. `info` is routine behavior worth reading, `debug` detail you go looking for, `warn` an - oddity the run coped with, `error` a real failure. Don't name the module; `target` does. -- **Size:** at most 500 lines of production code per file (split by responsibility) and 80 lines - per function (4 to 20 for new code). A wide `match` with thin arms is fine; a fat arm is not. - `scripts/size-check.py` and `scripts/fn-length-check.py` are ratchets: an allowlisted entry may - shrink, never grow, and a new one needs a reason a reviewer accepts. -- **Visibility:** `pub` means used from another crate; everything else is `pub(crate)` or - narrower. `unreachable_pub` checks items but not fields, so narrow fields by hand. -- **Tests:** unit tests in-module; an inline test module past 150 lines moves to a sibling - `foo/tests.rs`. Integration tests group into one binary per area (`tests//main.rs` plus - modules). `core` is fully testable headless: mock providers and temp dirs, no UI, no network. A - test in `examples/` runs only if its `[[example]]` declares `test = true`. -- **A test earns its place by being able to fail.** Watch a regression test fail on the unfixed - code. `scripts/mutants.sh -f ` finds the tests that cannot fail; use it on anything - security- or format-critical. A round-trip cannot catch a rename, so a persisted shape is pinned - against a literal copied from real output (a `.luxe/sessions/*.jsonl` line, a real `gh` reply). -- **Every public item has a `///` doc.** +- `foo.rs` next to `foo/`, never `foo/mod.rs` (except `luxe-core/tests/common/`). +- Errors: `thiserror` enums in libraries, `anyhow` only in `luxe-cli`. No `unwrap()` or `expect()` + on anything that can fail; `expect()` is for things that can't, and says why. Match on the error + variant, never its message. Messages are lowercase with no trailing period. +- Turns must be cancelable. Cancel drops the future, so anything spawned needs `kill_on_drop` or + its own process-group guard. Blocking work goes in `spawn_blocking`. +- Logging is `tracing`, with fields instead of formatted strings and secrets through the redaction + layer. `info` is routine, `debug` is detail, `warn` is something odd the run handled, `error` is a + real failure. Don't put the module name in the message. +- New functions are 4 to 20 lines (80 max); files are 500 lines of production code max. The size + scripts are ratchets: an allowlisted entry can shrink, never grow, and a new one needs a reason. +- `pub` means another crate uses it; everything else is `pub(crate)` or narrower. The lint skips + fields, so narrow those by hand. +- Every public item gets a `///` doc. + +## Tests + +- Unit tests live in the module; past 150 lines they move to a sibling `foo/tests.rs`. Integration + tests are one binary per area: `tests//main.rs` plus modules. +- `core` tests run headless: mock providers, temp dirs, no UI, no network. +- An example's tests only run if its `[[example]]` sets `test = true`. +- A test has to be able to fail. Watch a regression test fail on the old code first. + `scripts/mutants.sh -f ` finds tests that can't fail; use it on security and format code. +- Pin anything saved or sent against a literal copied from real output (a `.luxe/sessions/*.jsonl` + line, a real `gh` reply). A round-trip test can't catch a rename. ## Comments and docs -Lean, casual, senior-dev voice. **Less is more.** Comment the *why*: intent, trade-offs, gotchas, -constraints a reader would not guess. Never restate what the code says; a comment that paraphrases -the next line goes. If a block needs a comment to say *what* it does, extract a named function. +- Comment the why: intent, trade-offs, gotchas. Never restate the code. If a block needs a comment + to say what it does, make it a named function. +- `//!` module docs: `Name — short description.`, a blank line, then how it fits. +- `///` item docs: sentences ending in a period (what, why, edge cases). Variants with a payload get + an `Args:` line. Short field and variant docs are fragments with no period. +- `//` inline: short fragments, no period. Reserved prefixes: `LEARN:`, `NOTE:`, `TODO:`. +- Describe the code as it is: no history, ticket numbers or plan references. That's for the commit. +- No docs that echo the name (`/// Session ID` on `session_id`), no banners, no commented-out code. +- Prose people read follows [`docs/brand/voice.md`](docs/brand/voice.md). How the agent talks lives + in `luxe-core::context`'s base harness, never in a mode or tool description. -- **Module docs (`//!`)**: `Name — short description.`, a blank line, then prose framing the - module in the architecture. -- **Item docs (`///`)**: sentences ending in a period: what, then why, then edge cases. - Payload-carrying variants get an `Args:` line. Label-style field and variant docs are fragments - with no period (`/// Configured accounts`). -- **Inline (`//`)**: terse fragments, no period. Reserved prefixes: `LEARN:`, `NOTE:`, `TODO:`. -- **Shipped source describes the code as it is.** No history ("used to", the incident that taught - it), no phase numbers, ticket ids or design-note citations; the story goes in the commit message. - Keep the one sentence of why the rule exists. -- Flag: docs that echo a name (`/// Session ID` on `session_id`), banners around trivial code, - commented-out code, tutorial narration of language basics. +## Security -## Security invariants +Enforce these in code (the permission engine or a hook), never in prompt text. -- **Permissive by default, with always-on guardrails unless `--yolo`:** deny `.env` reads and - catastrophic commands, ask on out-of-project work, force-push, commits and GitHub writes. The - engine (`luxe-core::permission`) sits at the dispatch choke point, and judges every tool that - runs code or reads paths (`test`, `debug`, search roots, `apply` modes), not just `bash`. -- **Enforcement is code, never prompt text.** A rule that must hold lives in the permission engine - or a hook. -- **A project cannot grant itself trust.** Its `.luxe/permissions.json` only tightens, its - `.luxe/hooks.json`, `gate.commands`, MCP servers and language servers are honored only under - `--trust-project` (or the global-only `lsp.project_servers`), so an "always" approval is written - to the **global** file. One answer governs every project-supplied binary - (`project_tooling_allowed`); a new consumer reads it, never a second gate. That gate picks which - binary Luxe runs, nothing more: a language server still runs `build.rs` and proc macros, so never - write that Luxe does not run repository code. -- **Secrets:** `0600` files, `$ENV` or `!command`, wrapped in `secrecy::SecretString`, scrubbed by - the process-wide `redact::process_secrets()` from tool results, logs and the wire capture. -- **No telemetry.** Every outbound call is one the user asked for or can turn off, carries nothing - about the machine, and is listed in `docs/guide/security.md`. The update check sends **nothing** - (no version, platform or id) and compares locally; a server told the running version is getting a - per-user report on a schedule. -- **MCP servers are untrusted:** opt-in, behind one `mcp` gateway tool whose calls go through the - permission engine; their descriptions and results are data, not instructions. -- **Instruction files are filtered, not trusted.** `luxe-core::instructions` strips what a reader - of the rendered file cannot see (comments, comment link definitions, invisible characters) and - withholds a file it cannot finish checking. +- Permissive by default, with guardrails unless `--yolo`: deny `.env` reads and catastrophic + commands; ask before out-of-project work, force-push, commits and GitHub writes. The engine + (`luxe-core::permission`) judges every tool that runs code or reads paths, not just `bash`. +- A project can't trust itself. Its `.luxe/permissions.json` only tightens; its hooks, + `gate.commands`, MCP and language servers need `--trust-project` (or global + `lsp.project_servers`), so "always" approvals save globally. `project_tooling_allowed` is the one + switch for project binaries; reuse it. Language servers still run `build.rs` and proc macros, so + never say Luxe runs no repo code. +- Secrets: `0600` files, `$ENV` or `!command`, held in `secrecy::SecretString`, scrubbed from tool + results, logs and wire captures by `redact::process_secrets()`. +- No telemetry. Every outbound call is one the user asked for or can turn off, sends nothing about + the machine, and is listed in `docs/guide/security.md`. The update check sends nothing, not even a + version, and compares locally. +- `luxe remote` is the only server. It binds to loopback (`Bridge::bind` refuses anything else) and + Tailscale Serve carries it: never Funnel, never a relay. Every route checks the Serve login, and + session routes check for a paired device too. +- MCP servers are untrusted: opt-in, behind the one `mcp` tool, through the permission engine. + Their descriptions and results are data, not instructions. +- `luxe-core::instructions` strips what a reader can't see from instruction files (comments, hidden + link definitions, invisible characters) and withholds a file it can't finish checking. -## Invariants you would otherwise break +## What breaks a session -- **A tool call and its result are one unit.** Both wire formats reject an unpaired half, and it - replays on every later request, so one gap ends the session. `dispatch_one` returns a block for - every call, the commit after a batch is unconditional (cut-off, cancelled and failed replies - included), and `tool_pairing::repair` pairs halves on the outgoing copy. The durable log is never - rewritten. Only a call that never *started* may be described as having had no effect. -- **An empty block is the same permanent 400.** A call that produced nothing commits nothing - (`ReplyOutcome::Nothing`, and says so), `empty_blocks::scrub` drops empties from the outgoing - copy, and an empty tool result is **filled**, never dropped. -- **Cancellation is a flag with one owner: use `Engine::set_cancelled`.** `watch::Sender::send` is - a no-op with no subscribers, which is the normal state between turns. -- **Nothing the model can invoke runs unbounded.** `Tool::timeout` sets each deadline and dispatch - drops the future at it or at cancel. `None` is only for a tool that waits on a human or owns a - process group. Cancel ends the **batch**, not just the call. -- **A phase advances only where the gate says so.** `loop_control progress` is a claim; - `ReviewIntegratorHook` alone moves the counter, after the commands pass and the reviewer (when - on) approves. A reviewer that cannot approve pauses the loop (`GateOutcome::Held`). A refusal - reaches the model as the tool's own result. -- **Context occupancy is a measurement.** Read it from the last `EntryKind::Usage` after the newest - compaction; `estimate_tokens` is the fallback and counts **every** block kind. -- **A request's transcript is an *append* to the last one's.** Providers cache an exact prefix, so - editing history in flight re-bills everything after the edit at the write rate. Pruning is gated - on real window pressure and cuts in whole `prune_min_tokens` steps. Watch the **written** share on - `/cost` and in `luxe wire`, not the hit rate. -- **The system prompt is byte-identical between turns of a session.** No volatile fact enters it; - one-time context is **appended**. Reason about what reaches the model from a capture - (`LUXE_WIRE_LOG` plus `luxe wire`), not from source. -- **`Action` and `Event` are a published protocol.** `luxe --rpc` streams them to clients nobody - here compiles, and an unknown tag degrades to `Other`, so a rename breaks every client and no - compiler notices. Adding is free; removing or retagging moves `PROTOCOL_VERSION`. Pinned literals - in `tests/event_serialization.rs` hold it. -- **`AGENTS.md` is the only project document in the prompt.** Anything else is pointed at. -- **A tool must beat the shell command it replaces** (bounded output, fewer round trips, correct - defaults, or a capability the shell lacks), and its description names the sibling for the - adjacent question. -- **Glyphs are polish, never meaning.** Every icon sits beside the words it labels; prefer block +- **A tool call and its result are a pair.** Providers reject half a pair on every later request, + so one gap ends the session. `dispatch_one` returns a result for every call, a batch always + commits (cut off, cancelled or failed too), and `tool_pairing::repair` fixes the outgoing copy. + Never rewrite the saved log. Only a call that never started had no effect. +- **An empty block is the same permanent 400.** An empty reply commits nothing + (`ReplyOutcome::Nothing`), `empty_blocks::scrub` drops empties from the outgoing copy, and an + empty tool result is filled, never dropped. +- **Cancel with `Engine::set_cancelled`.** `watch::Sender::send` does nothing without subscribers, + which is normal between turns. +- **Nothing the model runs is unbounded.** `Tool::timeout` sets each deadline; dispatch drops the + future at it or on cancel. `None` is only for a tool that waits on a person or owns a process + group. Cancel ends the whole batch. +- **Only the gate moves a phase.** `loop_control progress` is a claim; `ReviewIntegratorHook` moves + the counter once the commands pass and the reviewer (if on) approves, and pauses the loop + (`GateOutcome::Held`) if it can't. A refusal reaches the model as the tool's result. +- **Context use is measured.** Read it from the last `EntryKind::Usage` after the newest + compaction. `estimate_tokens` is the fallback and counts every block kind. +- **Each request appends to the last.** Providers cache an exact prefix, so editing history + re-bills everything after the edit. Pruning waits for real window pressure and cuts in whole + `prune_min_tokens` steps. Watch the written share on `/cost` and in `luxe wire`, not the hit rate. +- **The system prompt never changes mid-session.** Nothing volatile goes in it; one-time context is + appended. Judge what reaches the model from a capture (`LUXE_WIRE_LOG` plus `luxe wire`). +- **`Action` and `Event` are a public protocol.** `luxe --rpc` streams them to clients built + elsewhere, and an unknown tag becomes `Other`, so a rename breaks them silently. Adding is free; + removing or renaming bumps `PROTOCOL_VERSION`. `tests/event_serialization.rs` pins the literals. + +## Product rules + +- `AGENTS.md` is the only project document in the prompt. Point at anything else. +- A tool must beat the shell command it replaces (bounded output, fewer round trips, better + defaults, or something the shell can't do), and its description names the sibling tool for the + next question. +- Glyphs decorate; they never carry meaning alone. Every icon sits beside its words. Prefer block elements, which every terminal draws. -- **Platform questions have one owner each:** `user_dirs` (home and Luxe's directories), `program` - (finding programs, shells, detaching, killing a process tree), `paths` (path to string), - `fs_atomic` (durable replace), `luxe-lsp::uri` (`file://` URLs). -- **Generated assets are generated; captures are recorded.** `web/src/assets/generated/` comes from - the Rust source and CI checks it. `web/src/assets/captures/` are real sessions recorded by - `scripts/site-record.sh`, which nothing can verify; change how Luxe looks and you owe both a - `site-assets.sh` and a re-record. -- **The wordmark constants are the art** (`luxe-tui/src/widgets/wordmark/art.rs`): one drawing, no +- `web/src/assets/generated/` comes from Rust and CI checks it; `captures/` are real sessions from + `scripts/site-record.sh`. Change how Luxe looks and you owe a `site-assets.sh` run and a + re-record. +- The wordmark constants in `luxe-tui/src/widgets/wordmark/art.rs` are the logo: one drawing, no alternatives. -- **Two voices, two homes.** Prose a person reads follows `docs/brand/voice.md`; how the agent - writes lives in `luxe-core::context`'s base harness, never in a mode or a tool description. ## Where things live -- `CONTRIBUTING.md`: process, tooling, publishing. `docs/guide/`: the user guide, also embedded in - the binary for `luxe docs`. -- `.luxe/todos/.json`: the `todo` tool's checklist, one file per session. -- A development checkout also has `PROJECT.md` (what must stay true; read it when a design call is - ambiguous), `ROADMAP.md`, `PROGRESS.md`, `PLAN.md` and design notes, all excluded from releases. +- `CONTRIBUTING.md`: process, tooling, publishing. `docs/guide/`: the user guide, also in + `luxe docs`. `.luxe/todos/.json`: the `todo` checklist. +- A dev checkout also has `PROJECT.md` (what must stay true; read it when a design call is + unclear), `ROADMAP.md`, `PROGRESS.md`, `PLAN.md` and design notes. None of them ship. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3de47c9..35aa74d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,167 @@ 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.3] + +### Added + +- A session open in the interface can be joined by another program on the same machine while you + keep working: `luxe join` speaks the [RPC protocol](docs/guide/rpc.md#join-a-running-session) + over a local socket (a named pipe on Windows) only your account can open. A joined client gets + the session so far, then every live event, and can answer prompts. It can't switch or end the + session, publish to GitHub, or be a program the agent started. `"joinable": false` or + `LUXE_JOINABLE=0` turns it off. +- A `prompt_closed` event tells every front end when a permission prompt or question stops + waiting, so one answered elsewhere comes down everywhere. +- `luxe remote` puts the sessions running on your computer in reach of your own phone or tablet, + over [Tailscale](docs/guide/remote.md). It listens on this machine only, Tailscale Serve carries + it to your devices, and it lets in your own Tailscale login from a device you paired with a QR + code. `luxe remote setup` checks Tailscale, publishes the bridge, runs it at sign-in as a user + service (systemd, launchd, or the Windows Run key, none needing an administrator), and shows the + code. `luxe remote devices` lists and revokes devices. +- The bridge can start Luxe in a folder a device picks: in a herdr pane when herdr is running, so + the session waits at your desk, or as its own `luxe --rpc` otherwise. +- A session started with `luxe --rpc` can be joined, like one in the interface. +- An `introduce` action lets a joined client name itself, so the interface says "iPhone joined + this session" and "Approved from iPhone" rather than a process id. +- The bridge renders messages for the phone app the way the interface draws them: markdown, + highlighted code in your theme's colors with a copy control, tool icons, and your own messages + without the notes Luxe adds for the agent. The phone parses nothing itself. +- From the phone app you can write to a session, steer or stop a running turn, and answer its + permission prompts and questions. Like the interface's, a prompt holds every answer but Reject + for a moment after it appears, so a tap meant for something else can't grant anything. +- The phone app's status line shows the mode behind the interface's mark for it, which a tap + switches, and the context, thinking level and model, worded as the interface's status bar words + them. A tap on those opens the session's details, where you can switch the model or thinking + level and see the cost. +- The phone app is set in the same monospace at a size that fits more on a phone, and its session + list wears the Luxe wordmark, lit by the same slow drift as the interface's. +- The phone app's header names the session's folder and the branch it's on, behind the interface's + folder and branch marks, starred when the tree has changes. A long branch is cut first. +- The phone app can start a session in a folder you've worked in, or any other you type, and opens + it once it's ready. **New** on the session list opens a page for it, where what you type narrows + the folders it offers. +- The phone app can send photos, from the camera or the library, scaled down on the phone first so + they're quick to send. +- The phone app's composer has icon buttons for attaching a photo (a paperclip), sending (an arrow + in the accent color, dim until there's something to send) and stopping, and a line over the box + while a turn runs that says whether sending steers it or waits for it to end. +- The phone app offers the slash commands it can carry out (`/compact`, `/cost`, `/dock`, `/mode`, + `/model` and `/thinking`) as you type a `/`, and project files to mention as you type an `@`. +- The phone app shows the Context Dock, with the session's plan and changed files: a rail beside + the conversation on an iPad or an open iPhone Duo, on the side your `dock` settings choose, + which a header button and `/dock` show and hide. On a phone the header keeps to one menu button, + and the dock is the first tab of the panel it opens. A long plan scrolls in a box of its own + that keeps the work in hand in view, as the interface's rail does. Tapping a file opens its diff. +- The phone app has a project panel, behind the header's menu button. Its Files tab is the + interface's FILES tree, with its guides, icons and change marks, and shows a file highlighted + as the interface shows it, with a button that mentions it in your message. On a wide screen the + panel is a rail in the dock's place, and a file or a diff opens beside it, with the conversation + still in view where there's room, as the interface peeks beside its dock. +- The phone app's project panel has a GitHub tab: `/github`'s sections and rows, and a pull + request or issue opened beside them with its overview and conversation, drawn as the interface + draws them. It reads only, and **Mention** adds the item to your message. +- The phone app's project panel has a Review tab: the open Guided Review's guide, a chapter opened + beside it with the guide's notes over its diffs, and **Reviewed** and **Next** to walk it. It + joins the review the interface has open, through the new `show_open_review` RPC action, whose + answer also says what each chapter asks of the reader. The panel's bar names the project and its + branch with the interface's marks, as the interface's PROJECT section does. +- The phone app asks about picked lines, as the interface's File view does, in a file, a diff or a + review chapter: tap line numbers to pick them, or select text the phone's way, down to part of a + line, and **Ask** adds the path and lines to your message in the interface's words. +- The phone app comments on a review chapter: on a picked line or run of lines, or on the chapter, + as a comment or a question, saved or sent at once. Comments show under what they're about with + the agent's replies, and take a reply, resolve, send or delete; the guide sends everything unsent. +- The phone app is named for the computer it reaches, as Tailscale names it: on the Home Screen, + beside the Luxe mark in the session list, and after the project in notifications. One phone can + keep an app for each of several computers and tell them apart. +- Your own phone joining a session no longer adds "joined" and "left" lines to the conversation + each time it reconnects: the dock's SESSION block names who's joined instead. Someone else's + device is still announced. +- Escape on an iPad keyboard closes the phone app's sheet straight after a pane opens or closes, + where it used to be lost for a frame. +- The phone app's icon buttons (close, project, dock) are square, 44 points to tap, and a press or + a keyboard's focus shows Luxe's own square rather than the browser's rounded highlight. +- The phone app's headings are the interface's badges (PROJECT, PLAN, FILES, MODEL, SESSION), cut + the same way at the same depths, or bold words when `statusline.style` is flat. +- The phone app can be added to the home screen, where it opens full screen with the Luxe mark in + your theme's colors as its icon. An app on the home screen keeps its own sign-in apart from + Safari's, so one that needs pairing again takes the invitation link pasted in. +- The phone app can [notify you](docs/guide/remote.md#notifications) when a session waits on an + answer or finishes a long turn. It's off until you turn it on, one device at a time, and a + notification says only what's waiting and where. The bridge seals each one for your device and + posts it to your device's own push service, with no Luxe server in between. +- The protocol sends [`turn_started`](docs/guide/rpc.md) when a turn begins, from any client, and a + client joining mid-turn gets it while catching up. A turn sent from your phone shows as running + in the terminal right away, not from its first word. +- The protocol answers [`list_models`](docs/guide/rpc.md) with the models you can switch to, and + the thinking levels each one honors, so a client can offer the same choices as `/model`. +- A joined client can introduce itself with `watch_only`, to read a session without the interface + announcing it. Luxe drops anything else it sends. The bridge watches for notifications this way. +- An `AGENTS.md` in a folder the agent works in now reaches it, even when Luxe started somewhere + else in the repository. It's added to the first tool result that reaches the folder, once, so + the system prompt and the provider's cache are untouched. Luxe shows "Following" and the file. + See [Project context](docs/guide/project-context.md#folders-the-agent-works-in); + `LUXE_NESTED_INSTRUCTIONS=0` turns it off. + +### Changed + +- A session is open in one Luxe at a time. Resuming one that another Luxe has open is refused, and + the message says which process has it, rather than two of them writing the same history. +- `message_committed` now announces the messages you send too, as the protocol guide always said + it did, so a joined client sees the question as well as the answer, and the interface shows a + message a joined client sent. A `--rpc` client gets its own message back once Luxe saves it. +- The turn timer reads like a tool card's time: `42s`, then `3m 07s`, then `1h 05m`. +- `luxe --help` opens with "A beautiful coding agent for your terminal." + +### Fixed + +- A tool call the model writes while an earlier one is still running shows as waiting, not as a + second spinner. Only one card spins at a time again. +- A running `bash` card is titled with what the command is for, as soon as the model has written + that. It used to show the command in both the title and the body until the command finished. +- A message with an image, sent while a turn runs, is queued for its own turn. Steering it + delivered the words and dropped the image. +- A compaction is in the conversation from the moment it starts ("Compacting the conversation — + 579.4k of context…"), and that line becomes the result when it ends. A minute of summary showed + nothing but the activity bar while the dock was open. The phone app shows it too. +- Typing in the phone app keeps up in a long session. It drew every item the session ever had, + and Safari slows each keystroke as a page passes a few thousand (a 9,000-item session took about + 100ms a key on a desktop). It now draws the latest 300, with **Show earlier** for the rest. +- A long session no longer stalls before every model call. Luxe re-read and parsed the whole + session file each time, about 70ms on a 68 MB session. It now keeps the session it's writing in + memory and reads only what was added, about 10ms. +- A turn no longer spends seconds saving the project for **Last Turn** review. Every turn saved + two full copies of every file, synced to disk one by one (about 11 seconds a turn in a project + of 4,000 files), and never deleted any, so one project's `.luxe/reviews/turn-baselines` reached + 18 GB. A copy now links the files the last one already holds, which takes under a second, and + copies the last turn doesn't need are deleted once they're an hour old. +- A long session's memory climbs much more slowly. Every model call copied the whole + conversation, every tool result included, to send the part after the last compaction. It now + copies only what it sends: over 20 turns on a 68 MB session, Luxe grew by 65 MB instead of + 338 MB. +- Drawing a long session with screenshots in it is cheaper while a reply streams. Every tool + card holding an image was laid out again on every frame, even scrolled far out of view, which + in a session with a hundred screenshots was most of what the terminal UI allocated. A card is + now laid out again only when its image changes. +- A phone joining a long session costs the computer less. Each join copied the whole + conversation, then built the message carrying it in one buffer that doubled as it grew. It's + now sent from the copy Luxe already keeps, in pieces: over 120 joins of a 68 MB session, 26 GB + less allocated, and each join about 20ms faster. +- Compaction no longer fails more often the longer a session runs. The summarizer was asked for a + list of every file the session touched and shown the last summary's list to copy, though Luxe + keeps that list itself and replaced whatever the summarizer wrote. On a long session the list + grew to over 500 paths, and copying it used up the summary's output limit, so the compaction + failed with "the summary stopped short". The summarizer now writes only the prose, and its + output limit is 32K tokens, up from 16K. +- `web_search` with several phrasings gives each its share of the results. Without a key, they + went to Exa as one search ranked against the first phrasing, so the others rarely showed. Each + phrasing is now its own search, and the results take turns: the top of each, then the next. +- `web_search` says when Exa's free search is rate limited, and which phrasing it turned away. The + notice used to read as a search that found nothing. +- A `grep` glob starting with `!` excludes, as `rg -g '!target/**'` does. It used to match no file, + so the search came back empty. + ## [0.1.2] ### Fixed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 08e3277..3426989 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -295,6 +295,47 @@ cd web && npm run build && npm run check cd web && npm run deploy # needs `wrangler login` once ``` +## The phone app + +`luxe remote`'s app is plain HTML, CSS and ES modules in `crates/luxe-remote/app/`, with nothing +built. A debug build reads that folder from disk, so run `cargo run -p luxe-cli -- remote` and +reload. Preact, htm and Signals are vendored byte for byte, and a test holds them to +`app/vendor/manifest.json`: + +```bash +scripts/remote-vendor.sh # fetch the pinned versions again (needs npm) +scripts/remote-fonts.sh # subset the fonts again (after site-fonts.sh) +``` + +Colors come from `/theme.css`, the active theme read through `luxe_core::theme::css`, the same +mapping the website's theme CSS uses. Each `var(--luxe-*)` in the app's stylesheet keeps a fallback +for a theme that leaves a color to the terminal. `app/generated/wordmark.svg` comes from the TUI's +art through `scripts/site-assets.sh`, which checks it with the website's assets. + +The transcript is a pure fold of the session's frames (`app/transcript.js`), tested with Node's +own runner against a session recorded through the bridge (`app-tests/fixtures/turn.jsonl`). The +tests resolve imports through `index.html`'s import map, so they run the vendored files the phone +runs. The app's types are JSDoc, checked by `tsc` in strict mode; the tests get a looser config. +`tsc` reads expressions inside a template but not the props `htm` hands a component, so a +component's `@param` is what it promises, not something checked at the call. The end-to-end test +starts a session against a mock model, a bridge and a pairing, then drives a whole turn in WebKit, +permission and diff included. CI runs all three in its `phone app` job: + +```bash +cd crates/luxe-remote/app-tests +npm ci # TypeScript, Playwright, and the vendored libraries' types +npm run check # tsc +npm test # unit tests +cargo build -p luxe-cli && npm run e2e # end to end; LUXE_BIN picks another luxe +``` + +Every iOS browser is WebKit, so check the app there. Playwright's WebKit build wants Ubuntu's ICU, +libxml2 and flite, which a rolling distro doesn't have. Without root, unpack those three `.deb`s +from the Ubuntu archive into the `minibrowser-wpe/sys/lib` of a copy of +`~/.cache/ms-playwright/webkit-*`, and point `PLAYWRIGHT_BROWSERS_PATH` at the copy. A screenshot +adds a ` + + +

Pair this device with Luxe

+
+ + +
+

+ + + diff --git a/crates/luxe-remote/src/pairing.rs b/crates/luxe-remote/src/pairing.rs new file mode 100644 index 0000000..d7542ff --- /dev/null +++ b/crates/luxe-remote/src/pairing.rs @@ -0,0 +1,88 @@ +//! Pairing — a device trades an invitation for a credential of its own. + +use std::sync::Arc; + +use axum::extract::State; +use axum::http::{header, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::{Extension, Json}; +use serde::Deserialize; + +use crate::access::{credential_cookie, Login}; +use crate::routes::Bridged; +use crate::RemoteError; + +/// Longest name a device keeps; it is a label in a list, not a description. +const NAME_LIMIT: usize = 40; + +/// What the pairing page sends. +#[derive(Debug, Deserialize)] +pub(crate) struct PairRequest { + invitation: String, + #[serde(default)] + name: String, +} + +/// Redeems the invitation and sets the device's credential as a cookie the page never sees. +pub(crate) async fn pair( + State(bridged): State>, + Extension(Login(login)): Extension, + Json(request): Json, +) -> Response { + let devices = bridged.devices.clone(); + let name = device_name(&request.name); + let paired = + tokio::task::spawn_blocking(move || devices.pair(request.invitation.trim(), &name, &login)) + .await; + match paired { + Ok(outcome) => answer(outcome), + Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), + } +} + +fn answer(paired: Result<(crate::devices::Device, String), RemoteError>) -> Response { + match paired { + Ok((device, credential)) => { + tracing::info!(device = %device.name, id = %device.id, "a device paired"); + let cookie = [(header::SET_COOKIE, credential_cookie(&credential))]; + let body = serde_json::json!({ "id": device.id, "name": device.name }); + (cookie, Json(body)).into_response() + } + Err(RemoteError::Pairing(refused)) => { + (StatusCode::BAD_REQUEST, refused.to_string()).into_response() + } + Err(error) => { + tracing::error!(%error, "could not record a paired device"); + (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() + } + } +} + +/// The name a device asked for, made fit for a list: one line, bounded, never empty. +fn device_name(asked: &str) -> String { + let name: String = + asked.chars().map(|c| if c.is_control() { ' ' } else { c }).take(NAME_LIMIT).collect(); + let name = name.trim(); + if name.is_empty() { + "Device".to_string() + } else { + name.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A device's name is a single bounded line, so `luxe remote devices` stays a list. + /// + /// The break this catches: storing the name as sent, so a newline forges a second row in the + /// listing, or an empty one leaves a row with nothing to recognize it by. + #[test] + fn a_device_name_is_one_short_line() { + assert_eq!(device_name("Evan's iPhone"), "Evan's iPhone"); + assert_eq!(device_name("phone\nabc1234 Fake"), "phone abc1234 Fake"); + assert_eq!(device_name(" "), "Device"); + assert_eq!(device_name(&"x".repeat(100)).len(), NAME_LIMIT); + } +} diff --git a/crates/luxe-remote/src/push.rs b/crates/luxe-remote/src/push.rs new file mode 100644 index 0000000..ee3d125 --- /dev/null +++ b/crates/luxe-remote/src/push.rs @@ -0,0 +1,153 @@ +//! Push — notifications on your devices when a session wants you, sent by the bridge itself. +//! +//! Web Push, as iOS has offered it to home-screen web apps since 16.4: a device that opted in +//! gives the bridge a subscription, and the bridge posts each notification, sealed so only that +//! device can read it, straight to the push service the subscription names (Apple's, for an +//! iPhone). There is no Luxe server in between, and the push service sees when, not what. +//! +//! [`watch`] hears what the sessions are waiting for, and [`notify`] takes each notice to every +//! subscribed device that doesn't have that session open in front of it. + +use std::path::PathBuf; +use std::sync::Arc; + +use tokio::sync::mpsc; + +pub(crate) mod api; +mod encryption; +mod notice; +mod presence; +mod subscription; +mod vapid; +mod watch; +mod web_push; + +pub(crate) use presence::Presence; +pub(crate) use subscription::Subscription; +#[cfg(test)] +pub(crate) use subscription::{tests::FROM_SAFARI, SubscriptionKeys}; +#[cfg(test)] +pub(crate) use tests::Recording; +pub(crate) use vapid::{Vapid, VapidError}; +pub(crate) use web_push::Courier; + +use crate::devices::{Device, DeviceBook}; +use notice::Notice; +use web_push::{Delivery, WebPush}; + +/// Notices heard but not yet posted. A few sessions, each with a prompt or two at a time. +const NOTICE_BUFFER: usize = 64; + +/// Notifications from the sessions under `runtime_dir` to the devices in `devices`, until the +/// returned guard drops. They go through `courier`, or Web Push signed with the bridge's key, each +/// titled with `machine` when the bridge has a name. +pub(crate) fn start( + runtime_dir: PathBuf, + devices: DeviceBook, + presence: Presence, + courier: Option>, + machine: Option, +) -> watch::Watcher { + watch::Watcher(tokio::spawn(notify(runtime_dir, devices, presence, courier, machine))) +} + +async fn notify( + runtime_dir: PathBuf, + devices: DeviceBook, + presence: Presence, + mut courier: Option>, + machine: Option, +) { + let (heard, mut notices) = mpsc::channel(NOTICE_BUFFER); + let watching = watch::watch_sessions(runtime_dir, devices.clone(), heard); + let _watching = watch::Watcher(tokio::spawn(watching)); + while let Some(notice) = notices.recv().await { + let Some(courier) = courier_for(&mut courier, &devices).await else { continue }; + let notice = on_machine(notice, machine.as_deref()); + dispatch(&devices, &presence, &*courier, ¬ice).await; + } +} + +/// `notice` titled with the computer it came from as well as the project, so a phone paired with +/// two computers can tell which one wants it: `luxe · desk`. +fn on_machine(mut notice: Notice, machine: Option<&str>) -> Notice { + if let Some(machine) = machine { + notice.title = format!("{} \u{00b7} {machine}", notice.title); + } + notice +} + +/// The courier, made on first use: the key is made when a device first subscribes, so it's there +/// by the time anything is heard. +async fn courier_for( + kept: &mut Option>, + devices: &DeviceBook, +) -> Option> { + if let Some(courier) = kept { + return Some(courier.clone()); + } + match web_push(devices.clone()).await { + Ok(courier) => Some(kept.insert(Arc::new(courier)).clone()), + Err(error) => { + tracing::error!(%error, "couldn't set up notifications"); + None + } + } +} + +/// Web Push with the bridge's key, for logging when it can't be had. +async fn web_push(devices: DeviceBook) -> Result { + match tokio::task::spawn_blocking(move || devices.push_key()).await { + Ok(Ok(vapid)) => WebPush::new(vapid).map_err(|error| error.to_string()), + Ok(Err(error)) => Err(error.to_string()), + Err(error) => Err(error.to_string()), + } +} + +/// Posts `notice` to every subscribed device that doesn't have its session open. +async fn dispatch( + devices: &DeviceBook, + presence: &Presence, + courier: &dyn Courier, + notice: &Notice, +) { + let reader = devices.clone(); + let paired = tokio::task::spawn_blocking(move || reader.devices()).await.unwrap_or_default(); + for device in &paired { + let Some(subscription) = device.subscription() else { continue }; + if presence.is_here(&device.id, ¬ice.session) { + tracing::debug!(device = %device.name, "not notifying a device looking at the session"); + continue; + } + let delivered = courier.deliver(subscription, notice).await; + settle(devices, device, &subscription.endpoint, delivered).await; + } +} + +/// Logs how a post went, and forgets a subscription its push service says is gone. +async fn settle( + devices: &DeviceBook, + device: &Device, + endpoint: &str, + delivered: Result, +) { + match delivered { + Ok(Delivery::Taken) => tracing::debug!(device = %device.name, "sent a notification"), + Ok(Delivery::Gone) => { + tracing::info!(device = %device.name, "a device's notifications ended at its push service"); + forget(devices.clone(), device.id.clone(), endpoint.to_string()).await; + } + Err(error) => tracing::warn!(%error, device = %device.name, "couldn't send a notification"), + } +} + +/// Drops the device's subscription, unless it has since subscribed somewhere new. +async fn forget(devices: DeviceBook, id: String, endpoint: String) { + let forgot = tokio::task::spawn_blocking(move || devices.forget_endpoint(&id, &endpoint)); + if let Ok(Err(error)) = forgot.await { + tracing::warn!(%error, "couldn't forget an ended subscription"); + } +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/luxe-remote/src/push/api.rs b/crates/luxe-remote/src/push/api.rs new file mode 100644 index 0000000..981e8bb --- /dev/null +++ b/crates/luxe-remote/src/push/api.rs @@ -0,0 +1,87 @@ +//! The routes a device turns its notifications on and off with, behind the paired-device check. +//! +//! `GET /api/push` gives the key to subscribe with and whether this device is subscribed, +//! `PUT /api/push` takes the subscription the browser made, and `DELETE /api/push` stops them. + +use std::sync::Arc; + +use axum::extract::State; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use axum::{Extension, Json}; + +use super::Subscription; +use crate::access::Refusal; +use crate::devices::Device; +use crate::routes::Bridged; + +/// What the app needs to subscribe, or to show that it has. +#[derive(serde::Serialize)] +struct PushStatus { + /// The bridge's public key, base64url, for `PushManager.subscribe` + key: String, + /// Whether the bridge has a subscription for this device + subscribed: bool, +} + +/// The bridge's push key, and whether this device is subscribed. +pub(crate) async fn status( + State(bridged): State>, + Extension(device): Extension, +) -> Response { + let devices = bridged.devices.clone(); + let key = tokio::task::spawn_blocking(move || devices.push_key()).await; + match key { + Ok(Ok(vapid)) => { + let subscribed = device.subscription().is_some(); + Json(PushStatus { key: vapid.public_key(), subscribed }).into_response() + } + Ok(Err(error)) => failed(&error), + Err(error) => failed(&error), + } +} + +/// Sends this device's notifications to the subscription its browser made. +pub(crate) async fn subscribe( + State(bridged): State>, + Extension(device): Extension, + Json(subscription): Json, +) -> Response { + match subscription.checked() { + Ok(subscription) => keep(&bridged, &device, Some(subscription)).await, + Err(refused) => { + tracing::warn!(device = %device.name, %refused, "refused a push subscription"); + (StatusCode::BAD_REQUEST, refused.to_string()).into_response() + } + } +} + +/// Stops this device's notifications. +pub(crate) async fn unsubscribe( + State(bridged): State>, + Extension(device): Extension, +) -> Response { + keep(&bridged, &device, None).await +} + +async fn keep(bridged: &Bridged, device: &Device, subscription: Option) -> Response { + let (devices, id) = (bridged.devices.clone(), device.id.clone()); + let on = subscription.is_some(); + let kept = tokio::task::spawn_blocking(move || devices.subscribe(&id, subscription)).await; + match kept { + Ok(Ok(true)) => { + tracing::info!(device = %device.name, on, "a device changed its notifications"); + StatusCode::NO_CONTENT.into_response() + } + // revoked since the request was let in + Ok(Ok(false)) => Refusal::NotPaired.into_response(), + Ok(Err(error)) => failed(&error), + Err(error) => failed(&error), + } +} + +fn failed(error: &dyn std::error::Error) -> Response { + tracing::error!(%error, "couldn't read or keep a push subscription"); + let reason = format!("couldn't keep notifications: {error}"); + (StatusCode::INTERNAL_SERVER_ERROR, reason).into_response() +} diff --git a/crates/luxe-remote/src/push/encryption.rs b/crates/luxe-remote/src/push/encryption.rs new file mode 100644 index 0000000..d0897bd --- /dev/null +++ b/crates/luxe-remote/src/push/encryption.rs @@ -0,0 +1,120 @@ +//! Encryption — a push message sealed for one device, as RFC 8291 has it. +//! +//! The push service carries the message and can't read it: each one is sealed with a key agreed +//! between a throwaway key of the bridge's and the key the device's browser made when it +//! subscribed, mixed with the subscription's own secret. + +use ring::rand::SecureRandom; +use ring::{aead, agreement, hkdf, rand}; + +/// The record size a message declares. One record holds the whole message, which a push service +/// caps at 4 KiB anyway. +const RECORD_SIZE: u32 = 4096; + +/// Bytes a record adds to its message: the delimiter that ends the last record, and the AES-GCM +/// tag. +const RECORD_OVERHEAD: usize = 1 + 16; + +/// Why a message couldn't be sealed. +#[derive(Debug, thiserror::Error)] +pub(crate) enum EncryptionError { + /// The subscription's key isn't a P-256 point + #[error("the subscription's key isn't a P-256 public key")] + BadSubscriptionKey, + /// The message won't fit one record + #[error("a push message of {0} bytes is too long for one record")] + TooLong(usize), + /// The system's randomness failed + #[error("the system's random number source failed")] + Random, +} + +/// The two secrets a message is sealed with. +#[derive(Debug, PartialEq, Eq)] +struct ContentKeys { + key: [u8; 16], + nonce: [u8; 12], +} + +/// `message` sealed for the subscription with public key `device_key` and secret `auth`, as the +/// body of an `aes128gcm` push request. +pub(crate) fn encrypt( + message: &[u8], + device_key: &[u8], + auth: &[u8], +) -> Result, EncryptionError> { + if message.len() + RECORD_OVERHEAD > RECORD_SIZE as usize { + return Err(EncryptionError::TooLong(message.len())); + } + let random = rand::SystemRandom::new(); + let (ours, our_key) = throwaway_key(&random)?; + let mut salt = [0u8; 16]; + random.fill(&mut salt).map_err(|_| EncryptionError::Random)?; + let theirs = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, device_key); + let keys = agreement::agree_ephemeral(ours, &theirs, |shared| { + content_keys(shared, auth, device_key, our_key.as_ref(), &salt) + }) + .map_err(|_| EncryptionError::BadSubscriptionKey)?; + Ok(seal(&keys, &salt, our_key.as_ref(), message)) +} + +/// A key pair for one message, so a message read once its key leaks says nothing of the others. +fn throwaway_key( + random: &rand::SystemRandom, +) -> Result<(agreement::EphemeralPrivateKey, agreement::PublicKey), EncryptionError> { + let ours = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, random) + .map_err(|_| EncryptionError::Random)?; + let public = ours.compute_public_key().map_err(|_| EncryptionError::Random)?; + Ok((ours, public)) +} + +/// The content keys from the agreed secret, RFC 8291 section 3.4: the subscription's secret and +/// both public keys are mixed in first, then the message's salt. +fn content_keys( + shared: &[u8], + auth: &[u8], + device_key: &[u8], + our_key: &[u8], + salt: &[u8], +) -> ContentKeys { + let key_info = [b"WebPush: info\0".as_slice(), device_key, our_key].concat(); + let combined = hkdf::Salt::new(hkdf::HKDF_SHA256, auth).extract(shared); + let keying: [u8; 32] = expand(&combined, &key_info); + let content = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(&keying); + ContentKeys { + key: expand(&content, b"Content-Encoding: aes128gcm\0"), + nonce: expand(&content, b"Content-Encoding: nonce\0"), + } +} + +/// The header (salt, record size, the bridge's key) and then the one sealed record. +fn seal(keys: &ContentKeys, salt: &[u8; 16], our_key: &[u8], message: &[u8]) -> Vec { + let mut record = [message, &[2]].concat(); + let unbound = + aead::UnboundKey::new(&aead::AES_128_GCM, &keys.key).expect("16 bytes is an AES-128 key"); + let nonce = aead::Nonce::assume_unique_for_key(keys.nonce); + aead::LessSafeKey::new(unbound) + .seal_in_place_append_tag(nonce, aead::Aad::empty(), &mut record) + .expect("one record is far below AES-GCM's length limit"); + let key_length = u8::try_from(our_key.len()).expect("a P-256 point is 65 bytes"); + let header = [salt.as_slice(), &RECORD_SIZE.to_be_bytes(), &[key_length], our_key].concat(); + [header, record].concat() +} + +/// `N` bytes of HKDF output. +fn expand(key: &hkdf::Prk, info: &[u8]) -> [u8; N] { + struct Length(usize); + impl hkdf::KeyType for Length { + fn len(&self) -> usize { + self.0 + } + } + let mut out = [0u8; N]; + key.expand(&[info], Length(N)) + .and_then(|okm| okm.fill(&mut out)) + .expect("HKDF-SHA-256 gives up to 8160 bytes"); + out +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/luxe-remote/src/push/encryption/tests.rs b/crates/luxe-remote/src/push/encryption/tests.rs new file mode 100644 index 0000000..d583f2c --- /dev/null +++ b/crates/luxe-remote/src/push/encryption/tests.rs @@ -0,0 +1,105 @@ +use super::*; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; + +/// RFC 8291 Appendix A, whose values every test here is held to. +mod rfc { + pub(super) const MESSAGE: &str = "When I grow up, I want to be a watermelon"; + pub(super) const OUR_KEY: &str = + "BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8"; + pub(super) const DEVICE_KEY: &str = + "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"; + pub(super) const SALT: &str = "DGv6ra1nlYgDCS1FRnbzlw"; + pub(super) const AUTH: &str = "BTBZMqHH6r4Tts7J_aSIgg"; + pub(super) const SHARED: &str = "kyrL1jIIOHEzg3sM2ZWRHDRB62YACZhhSlknJ672kSs"; + pub(super) const CONTENT_KEY: &str = "oIhVW04MRdy2XN9CiKLxTg"; + pub(super) const NONCE: &str = "4h_95klXJ5E_qnoN"; + pub(super) const HEADER: &str = "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8"; + pub(super) const SEALED: &str = + "8pfeW0KbunFT06SuDKoJH9Ql87S1QUrdirN6GcG7sFz1y1sqLgVi1VhjVkHsUoEsbI_0LpXMuGvnzQ"; +} + +fn bytes(base64url: &str) -> Vec { + URL_SAFE_NO_PAD.decode(base64url).expect("the RFC's values are base64url") +} + +fn rfc_keys() -> ContentKeys { + let (shared, auth) = (bytes(rfc::SHARED), bytes(rfc::AUTH)); + let (device, ours, salt) = (bytes(rfc::DEVICE_KEY), bytes(rfc::OUR_KEY), bytes(rfc::SALT)); + content_keys(&shared, &auth, &device, &ours, &salt) +} + +/// The key and nonce come out as the RFC's do from its agreed secret. +/// +/// The break this catches: any slip in the key schedule (the info strings, which key goes first, +/// salt and secret swapped), each of which a device rejects as a message it can't open. +#[test] +fn the_content_keys_are_the_rfcs() { + let keys = rfc_keys(); + assert_eq!(keys.key.as_slice(), bytes(rfc::CONTENT_KEY)); + assert_eq!(keys.nonce.as_slice(), bytes(rfc::NONCE)); +} + +/// The sealed body is the RFC's header and ciphertext, byte for byte. +/// +/// The break this catches: a wrong header field (record size, key length, the device's key where +/// ours belongs) or a missing end-of-record delimiter. +#[test] +fn a_message_is_sealed_as_the_rfcs() { + let salt: [u8; 16] = bytes(rfc::SALT).try_into().expect("16 bytes"); + let body = seal(&rfc_keys(), &salt, &bytes(rfc::OUR_KEY), rfc::MESSAGE.as_bytes()); + assert_eq!(body, [bytes(rfc::HEADER), bytes(rfc::SEALED)].concat()); +} + +/// A device opens what `encrypt` sealed for it, agreeing its key with the one in the header. +/// +/// The break this catches: `encrypt` mixing the keys in the wrong order or putting the wrong key +/// in the header, which the pinned halves above can't see. +#[test] +fn a_device_opens_what_was_sealed_for_it() { + let random = rand::SystemRandom::new(); + let device = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &random).unwrap(); + let device_key = device.compute_public_key().unwrap(); + let auth = [7u8; 16]; + let body = encrypt(b"Approve bash", device_key.as_ref(), &auth).unwrap(); + assert_eq!(open(device, device_key.as_ref(), &auth, &body), b"Approve bash\x02"); +} + +/// What the device with private key `device` reads from `body`, as its browser would: the key in +/// the header agreed with its own, and the one record opened, delimiter and all. +pub(crate) fn open( + device: agreement::EphemeralPrivateKey, + device_key: &[u8], + auth: &[u8], + body: &[u8], +) -> Vec { + let (salt, our_key, sealed) = (&body[..16], &body[21..86], &body[86..]); + let ours = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, our_key); + let keys = agreement::agree_ephemeral(device, &ours, |shared| { + content_keys(shared, auth, device_key, our_key, salt) + }) + .expect("the header's key is on the curve"); + let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &keys.key).unwrap()); + let mut record = sealed.to_vec(); + let nonce = aead::Nonce::assume_unique_for_key(keys.nonce); + key.open_in_place(nonce, aead::Aad::empty(), &mut record).expect("it opens").to_vec() +} + +/// The break this catches: sealing a message longer than its record says, which the push service +/// refuses, rather than saying why here. +#[test] +fn a_message_too_long_for_one_record_is_refused() { + let device = [4u8; 65]; + let longest = vec![b'x'; RECORD_SIZE as usize - RECORD_OVERHEAD]; + assert!(!matches!(encrypt(&longest, &device, &[0; 16]), Err(EncryptionError::TooLong(_)))); + let longer = vec![b'x'; longest.len() + 1]; + assert!(matches!(encrypt(&longer, &device, &[0; 16]), Err(EncryptionError::TooLong(_)))); +} + +/// The break this catches: a key that isn't on the curve sealed for anyway, sending a message no +/// device can open. +#[test] +fn a_key_off_the_curve_is_refused() { + let sealed = encrypt(b"hi", &[4u8; 65], &[0; 16]); + assert!(matches!(sealed, Err(EncryptionError::BadSubscriptionKey))); +} diff --git a/crates/luxe-remote/src/push/notice.rs b/crates/luxe-remote/src/push/notice.rs new file mode 100644 index 0000000..3926816 --- /dev/null +++ b/crates/luxe-remote/src/push/notice.rs @@ -0,0 +1,118 @@ +//! Notice — what a notification says, read from one session's events. +//! +//! A notification says what is waiting and where, never the detail: "Approve bash" with the +//! folder's name, not the command, and opening it leads to the prompt. Answering takes the app. +//! +//! Two rules keep it from buzzing at someone sitting at their desk. A prompt is held for a few +//! seconds first, and one answered meanwhile is never sent. A turn's end is only news when the +//! turn ran long enough for someone to have walked away. + +use luxe_core::{Event, StopReason}; +use std::time::Duration; +use tokio::time::Instant; + +/// How long a prompt waits before it's sent, for an answer at the desk to beat it. +pub(crate) const PROMPT_GRACE: Duration = Duration::from_secs(10); + +/// The shortest turn whose end is sent: a quick reply is read where it was asked for. +pub(crate) const LONG_TURN: Duration = Duration::from_secs(30); + +/// One notification, as the service worker shows it. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub(crate) struct Notice { + /// The project folder's name + pub(crate) title: String, + /// What's waiting, in a few words + pub(crate) body: String, + /// The session it opens + pub(crate) session: String, + /// Whether to deliver now rather than when the device saves power + #[serde(skip)] + pub(crate) urgent: bool, +} + +/// What an event means for notifications. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Heard { + /// Send this now + Now(Notice), + /// Send this unless prompt `id` closes within [`PROMPT_GRACE`] + Prompt(String, Notice), + /// Prompt `id` was answered, wherever + Closed(String), +} + +/// One session's stream, read for what's worth a notification. +pub(crate) struct Reading { + session: String, + folder: String, + turn_began: Option, +} + +impl Reading { + /// A reading of the session `session` running in `cwd`. + pub(crate) fn new(session: &str, cwd: &str) -> Self { + let folder = std::path::Path::new(cwd).file_name().map(|name| name.to_string_lossy()); + let folder = folder.map_or_else(|| cwd.to_string(), |name| name.into_owned()); + Self { session: session.to_string(), folder, turn_began: None } + } + + /// What `event`, seen at `now`, means. + pub(crate) fn read(&mut self, event: &Event, now: Instant) -> Option { + if is_turn_sign(event) { + self.turn_began.get_or_insert(now); + } + match event { + Event::Ready { session_id, .. } | Event::SessionLoaded { session_id, .. } => { + self.session.clone_from(session_id); + None + } + Event::PermissionRequested { .. } | Event::QuestionAsked { .. } => self.prompt(event), + Event::PromptClosed { id } => Some(Heard::Closed(id.clone())), + Event::TurnEnded { reason } => self.turn_ended(reason, now).map(Heard::Now), + _ => None, + } + } + + fn prompt(&self, event: &Event) -> Option { + let (id, body) = match event { + Event::PermissionRequested { id, tool, .. } => (id.as_str(), format!("Approve {tool}")), + Event::QuestionAsked { id, .. } => (id.as_str(), "Luxe has a question".to_string()), + _ => return None, + }; + Some(Heard::Prompt(id.to_string(), self.notice(body, true))) + } + + fn turn_ended(&mut self, reason: &StopReason, now: Instant) -> Option { + let began = self.turn_began.take()?; + if now.duration_since(began) < LONG_TURN { + return None; + } + let body = match reason { + StopReason::EndTurn | StopReason::ToolCall => "Finished, and waiting for you", + StopReason::Other(_) => "Stopped", + }; + Some(self.notice(body.into(), false)) + } + + fn notice(&self, body: String, urgent: bool) -> Notice { + Notice { title: self.folder.clone(), body, session: self.session.clone(), urgent } + } +} + +/// Whether `event` shows a turn running. The engine says so with `TurnStarted`, which comes +/// first; the message that opened the turn, or anything it streams, stands in for it from a +/// session whose Luxe predates that event. +fn is_turn_sign(event: &Event) -> bool { + match event { + Event::TurnStarted + | Event::TokenDelta { .. } + | Event::ThinkingDelta { .. } + | Event::ToolCallComposing { .. } => true, + Event::MessageCommitted { message, .. } => message.role == luxe_core::message::Role::User, + _ => false, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/push/notice/tests.rs b/crates/luxe-remote/src/push/notice/tests.rs new file mode 100644 index 0000000..7b4e61f --- /dev/null +++ b/crates/luxe-remote/src/push/notice/tests.rs @@ -0,0 +1,126 @@ +use super::*; +use luxe_core::Message; + +/// Frames as a session sends them, copied from core's pinned wire shapes. +const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#; +const QUESTION: &str = r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"session-1","prompt":"Which database?","options":[{"label":"postgres","description":"Relational, boring, correct","recommended":true}],"multi":false}}"#; +const CLOSED: &str = r#"{"kind":"prompt_closed","content":{"id":"perm:1"}}"#; +const DELTA: &str = r#"{"kind":"token_delta","content":{"block":0,"delta":"hello"}}"#; +const FINISHED: &str = r#"{"kind":"turn_ended","content":{"reason":"end_turn"}}"#; + +fn event(line: &str) -> Event { + serde_json::from_str(line).expect("a protocol frame") +} + +fn committed(message: Message) -> Event { + let frame = serde_json::json!({ + "kind": "message_committed", + "content": { "session_id": "session-1", "entry_id": "e1", "message": message }, + }); + serde_json::from_value(frame).expect("a committed message") +} + +fn reading() -> Reading { + Reading::new("session-1", "/home/alex/work/luxe-dev") +} + +/// A notice for `body` from the reading above. +fn notice(body: &str, urgent: bool) -> Notice { + let (title, session) = ("luxe-dev".into(), "session-1".into()); + Notice { title, body: body.into(), session, urgent } +} + +/// The break this catches: the command, the question's text or its options in the notification, +/// where a lock screen shows them to whoever is looking. +#[test] +fn a_prompt_says_what_waits_and_never_the_detail() { + let now = Instant::now(); + let asked = reading().read(&event(PERMISSION), now); + assert_eq!(asked, Some(Heard::Prompt("perm:1".into(), notice("Approve bash", true)))); + let asked = reading().read(&event(QUESTION), now); + let expected = Heard::Prompt("ask:1".into(), notice("Luxe has a question", true)); + assert_eq!(asked, Some(expected)); + assert_eq!(reading().read(&event(CLOSED), now), Some(Heard::Closed("perm:1".into()))); +} + +/// The break this catches: a quick reply at the desk buzzing the phone, or a long turn ending +/// without a word to someone who walked away. +#[test] +fn only_a_long_turns_end_is_news() { + let start = Instant::now(); + let mut quick = reading(); + quick.read(&committed(Message::user("hi")), start); + assert_eq!(quick.read(&event(FINISHED), start + LONG_TURN - Duration::from_secs(1)), None); + let mut long = reading(); + long.read(&committed(Message::user("refactor it")), start); + let ended = long.read(&event(FINISHED), start + LONG_TURN); + assert_eq!(ended, Some(Heard::Now(notice("Finished, and waiting for you", false)))); +} + +/// The break this catches: timing a turn from its first sign each time it shows (every delta), +/// so no turn is ever long; or from a reply the model committed, which isn't a turn starting. +#[test] +fn a_turn_is_timed_from_its_first_sign() { + let start = Instant::now(); + let mut reading = reading(); + reading.read(&event(DELTA), start); + reading.read(&event(DELTA), start + LONG_TURN); + assert!(reading.read(&event(FINISHED), start + LONG_TURN).is_some(), "timed from the first"); + + let mut replies = super::tests::reading(); + replies.read(&committed(Message::assistant("done")), start); + assert_eq!(replies.read(&event(FINISHED), start + LONG_TURN), None, "a reply isn't a start"); +} + +/// A turn is timed from `turn_started`, ahead of anything it streams. +/// +/// The break this catches: ignoring `turn_started`, so a turn that spends its first seconds +/// waiting on the model is timed short, and its end isn't news. +#[test] +fn a_turn_is_timed_from_when_it_started() { + let start = Instant::now(); + let mut reading = reading(); + reading.read(&event(r#"{"kind":"turn_started"}"#), start); + reading.read(&event(DELTA), start + Duration::from_secs(20)); + assert!(reading.read(&event(FINISHED), start + LONG_TURN).is_some()); +} + +/// The break this catches: a turn's start carried past its end, so the next quick turn looks long. +#[test] +fn each_turn_is_timed_on_its_own() { + let start = Instant::now(); + let mut reading = reading(); + reading.read(&event(DELTA), start); + reading.read(&event(FINISHED), start + Duration::from_secs(1)); + reading.read(&event(DELTA), start + LONG_TURN); + assert_eq!(reading.read(&event(FINISHED), start + LONG_TURN + Duration::from_secs(1)), None); +} + +/// The break this catches: reading a stop's free-text reason (ruled out), or calling a cancelled +/// or failed turn finished. +#[test] +fn a_turn_that_stopped_says_so() { + let start = Instant::now(); + let mut reading = reading(); + reading.read(&event(DELTA), start); + let stopped = Event::TurnEnded { reason: StopReason::Other("cancelled".into()) }; + assert_eq!( + reading.read(&stopped, start + LONG_TURN), + Some(Heard::Now(notice("Stopped", false))) + ); +} + +/// The break this catches: a notice naming the session the watcher joined after the terminal +/// moved to another one, so opening it lands on a session that isn't running. +#[test] +fn a_notice_names_the_session_now_running() { + let mut reading = reading(); + let loaded = serde_json::json!({ + "kind": "session_loaded", "content": { "session_id": "session-2", "messages": [] }, + }); + reading.read(&serde_json::from_value(loaded).unwrap(), Instant::now()); + let Some(Heard::Prompt(_, asked)) = reading.read(&event(PERMISSION), Instant::now()) else { + panic!("a prompt is heard"); + }; + assert_eq!(asked.session, "session-2"); +} diff --git a/crates/luxe-remote/src/push/presence.rs b/crates/luxe-remote/src/push/presence.rs new file mode 100644 index 0000000..8ad0137 --- /dev/null +++ b/crates/luxe-remote/src/push/presence.rs @@ -0,0 +1,72 @@ +//! Presence — which devices have which session open right now. +//! +//! The app closes its socket when it's hidden, so an open socket means the session is on that +//! device's screen, and a notification about it would only repeat what's in front of you. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +/// A device id and a session id. +type Visit = (String, String); + +/// The sockets open now, counted per device and session. +#[derive(Debug, Clone, Default)] +pub(crate) struct Presence { + open: Arc>>, +} + +impl Presence { + /// Counts `device` as looking at `session` until the returned guard drops. + pub(crate) fn arrive(&self, device: &str, session: &str) -> Here { + let visit = (device.to_string(), session.to_string()); + *self.lock().entry(visit.clone()).or_default() += 1; + Here { presence: self.clone(), visit } + } + + /// Whether `device` has `session` open. + pub(crate) fn is_here(&self, device: &str, session: &str) -> bool { + self.lock().contains_key(&(device.to_string(), session.to_string())) + } + + // a panic elsewhere can't leave a count half-changed, so a poisoned lock is still right + fn lock(&self) -> MutexGuard<'_, HashMap> { + self.open.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// One open socket, counted while it lives. +pub(crate) struct Here { + presence: Presence, + visit: Visit, +} + +impl Drop for Here { + fn drop(&mut self) { + let mut open = self.presence.lock(); + let Some(count) = open.get_mut(&self.visit) else { return }; + *count -= 1; + if *count == 0 { + open.remove(&self.visit); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The break this catches: the first socket to close clearing the device, though the session + /// is still open in another tab or a second socket, or one device's socket covering another. + #[test] + fn a_device_is_here_while_any_of_its_sockets_is_open() { + let presence = Presence::default(); + let first = presence.arrive("phone", "s1"); + let second = presence.arrive("phone", "s1"); + assert!(!presence.is_here("tablet", "s1"), "another device"); + assert!(!presence.is_here("phone", "s2"), "another session"); + drop(first); + assert!(presence.is_here("phone", "s1"), "one socket is still open"); + drop(second); + assert!(!presence.is_here("phone", "s1")); + } +} diff --git a/crates/luxe-remote/src/push/subscription.rs b/crates/luxe-remote/src/push/subscription.rs new file mode 100644 index 0000000..51da629 --- /dev/null +++ b/crates/luxe-remote/src/push/subscription.rs @@ -0,0 +1,92 @@ +//! Subscription — where a device asked to be sent notifications, and the keys to seal them with. +//! +//! The device names the address the bridge will post to, so the address is held to the push +//! services browsers use: HTTPS, on a known host. Anything else would let a paired device point +//! the bridge at a machine on your network. + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use serde::{Deserialize, Serialize}; + +/// The push services a subscription may name, each with its subdomains: Apple's (Safari, every +/// browser on iOS), Google's (Chrome), Mozilla's (Firefox) and Microsoft's (Edge). +const PUSH_SERVICES: &[&str] = + &["push.apple.com", "fcm.googleapis.com", "push.services.mozilla.com", "notify.windows.com"]; + +/// A device's push subscription, as `PushSubscription.toJSON()` gives it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Subscription { + /// Where the push service takes this device's notifications + pub(crate) endpoint: String, + /// The keys the browser made for it + pub(crate) keys: SubscriptionKeys, +} + +/// The browser's half of the encryption, base64url. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct SubscriptionKeys { + /// Its P-256 public key + pub(crate) p256dh: String, + /// The secret shared with the bridge alone + pub(crate) auth: String, +} + +/// Why a subscription was turned down. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub(crate) enum SubscriptionError { + /// The endpoint isn't an HTTPS URL on the default port + #[error("a push endpoint must be an https:// address")] + NotHttps, + /// The endpoint's host isn't a push service a browser uses + #[error("{0} isn't a push service this bridge sends to")] + UnknownService(String), + /// The keys aren't a P-256 point and a 16-byte secret + #[error("the subscription's keys aren't the ones Web Push uses")] + BadKeys, +} + +impl Subscription { + /// This subscription, if it names a push service and carries usable keys. + pub(crate) fn checked(self) -> Result { + let host = push_host(&self.endpoint)?; + if !PUSH_SERVICES.iter().any(|service| is_within(&host, service)) { + return Err(SubscriptionError::UnknownService(host)); + } + let (public, auth) = self.key_bytes().ok_or(SubscriptionError::BadKeys)?; + if public.len() != 65 || public[0] != 4 || auth.len() != 16 { + return Err(SubscriptionError::BadKeys); + } + Ok(self) + } + + /// The browser's public key and the shared secret, decoded. + pub(crate) fn key_bytes(&self) -> Option<(Vec, Vec)> { + let public = URL_SAFE_NO_PAD.decode(&self.keys.p256dh).ok()?; + let auth = URL_SAFE_NO_PAD.decode(&self.keys.auth).ok()?; + Some((public, auth)) + } + + /// The push service's origin, which a VAPID token must name. + pub(crate) fn audience(&self) -> Option { + let url = reqwest::Url::parse(&self.endpoint).ok()?; + Some(url.origin().ascii_serialization()) + } +} + +/// The host of `endpoint`, when it's HTTPS on the default port. +fn push_host(endpoint: &str) -> Result { + let url = reqwest::Url::parse(endpoint).map_err(|_| SubscriptionError::NotHttps)?; + if url.scheme() != "https" || url.port().is_some() { + return Err(SubscriptionError::NotHttps); + } + let host = url.host_str().ok_or(SubscriptionError::NotHttps)?; + Ok(host.to_ascii_lowercase()) +} + +/// Whether `host` is `service` or one of its subdomains. +fn is_within(host: &str, service: &str) -> bool { + host == service || host.strip_suffix(service).is_some_and(|rest| rest.ends_with('.')) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/luxe-remote/src/push/subscription/tests.rs b/crates/luxe-remote/src/push/subscription/tests.rs new file mode 100644 index 0000000..8a60d3a --- /dev/null +++ b/crates/luxe-remote/src/push/subscription/tests.rs @@ -0,0 +1,70 @@ +use super::*; + +/// A subscription in the shape the Push API gives `PushSubscription.toJSON()`, with an endpoint +/// on Apple's push service and RFC 8291's example keys. Not captured from a device: swap in a real +/// one when there is one. +pub(crate) const FROM_SAFARI: &str = r#"{"endpoint":"https://web.push.apple.com/QGuQyavXutnMH8nrLlUjPZe_eVbc4ndHqoGAHGBrP2bIG7WY_DuCO7B0fhd7QAEXMaChjqCnDiuWvDEvkFvYg1vbqgxQp9zc5uj2BLsdLUn6R7Kp5YnWzMw6V_Ekd8CKk8Q3t6c2RU1yhp9eu5fcWkoUd3pUwP7sOTzmjVPCQCmY","keys":{"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4","auth":"BTBZMqHH6r4Tts7J_aSIgg"},"expirationTime":null}"#; + +fn safari() -> Subscription { + serde_json::from_str(FROM_SAFARI).expect("Safari's shape reads") +} + +fn at(endpoint: &str) -> Subscription { + Subscription { endpoint: endpoint.into(), ..safari() } +} + +/// The break this catches: reading only some other browser's shape, so Safari's subscription +/// (the one an iPhone sends) is refused or loses its keys. +#[test] +fn a_subscription_from_safari_is_taken() { + let subscription = safari().checked().expect("it's Apple's push service"); + assert_eq!(subscription.audience().as_deref(), Some("https://web.push.apple.com")); +} + +/// The break this catches: a host check that's a plain suffix or substring match, so a name +/// that only ends like a push service's (or contains one) is posted to. +#[test] +fn only_a_push_services_own_hosts_are_taken() { + for endpoint in [ + "https://fcm.googleapis.com/fcm/send/abc", + "https://updates.push.services.mozilla.com/wpush/v2/abc", + "https://wns2-par02p.notify.windows.com/w/?token=abc", + ] { + assert!(at(endpoint).checked().is_ok(), "{endpoint}"); + } + for endpoint in [ + "https://evilpush.apple.com.example.net/x", + "https://notpush.apple.com/x", + "https://example.net/web.push.apple.com", + "https://192.168.1.1/push", + ] { + let refused = at(endpoint).checked(); + assert!(matches!(refused, Err(SubscriptionError::UnknownService(_))), "{endpoint}"); + } +} + +/// The break this catches: posting over plain HTTP, or to a push service's host on another port, +/// where something other than the push service may be listening. +#[test] +fn an_endpoint_must_be_https_on_its_usual_port() { + for endpoint in ["http://web.push.apple.com/x", "https://web.push.apple.com:8443/x", "nonsense"] + { + assert_eq!(at(endpoint).checked(), Err(SubscriptionError::NotHttps), "{endpoint}"); + } +} + +/// The break this catches: taking keys that can't seal a message, so every notification to the +/// device fails later, with nothing said when it subscribed. +#[test] +fn keys_that_cant_seal_a_message_are_refused() { + let bad = |p256dh: &str, auth: &str| { + let keys = SubscriptionKeys { p256dh: p256dh.into(), auth: auth.into() }; + Subscription { keys, ..safari() }.checked() + }; + let good = safari().keys; + assert_eq!(bad("not base64!", &good.auth), Err(SubscriptionError::BadKeys)); + assert_eq!(bad(&good.p256dh[..60], &good.auth), Err(SubscriptionError::BadKeys)); + assert_eq!(bad(&good.p256dh, "c2hvcnQ"), Err(SubscriptionError::BadKeys)); + let compressed = URL_SAFE_NO_PAD.encode([[2u8].as_slice(), &[9; 64]].concat()); + assert_eq!(bad(&compressed, &good.auth), Err(SubscriptionError::BadKeys)); +} diff --git a/crates/luxe-remote/src/push/tests.rs b/crates/luxe-remote/src/push/tests.rs new file mode 100644 index 0000000..a8ad691 --- /dev/null +++ b/crates/luxe-remote/src/push/tests.rs @@ -0,0 +1,121 @@ +use super::*; +use std::future::Future; +use std::pin::Pin; +use std::sync::Mutex; + +/// Posts nowhere: keeps the endpoints it was handed and the titles it was asked to show, and +/// answers each with `reply`. +pub(crate) struct Recording { + sent: Mutex>, + titles: Mutex>, + reply: Delivery, +} + +impl Recording { + fn answering(reply: Delivery) -> Self { + Self { sent: Mutex::default(), titles: Mutex::default(), reply } + } + + /// The titles of the notices posted, in order. + pub(crate) fn titles(&self) -> Vec { + self.titles.lock().unwrap().clone() + } + + /// One whose every post goes through. + pub(crate) fn taking() -> Self { + Self::answering(Delivery::Taken) + } + + /// The endpoints posted to, in order. + pub(crate) fn sent(&self) -> Vec { + self.sent.lock().unwrap().clone() + } +} + +impl Courier for Recording { + fn deliver<'a>( + &'a self, + subscription: &'a Subscription, + notice: &'a Notice, + ) -> Pin> + Send + 'a>> { + self.sent.lock().unwrap().push(subscription.endpoint.clone()); + self.titles.lock().unwrap().push(notice.title.clone()); + let reply = self.reply; + Box::pin(async move { Ok(reply) }) + } +} + +fn notice() -> Notice { + let (title, body, session) = ("luxe-dev".into(), "Approve bash".into(), "session-1".into()); + Notice { title, body, session, urgent: true } +} + +/// Pairs a device named `name`, subscribed at `endpoint` when there is one, and returns its id. +fn device(book: &DeviceBook, name: &str, endpoint: Option<&str>) -> String { + let token = book.invite().unwrap(); + let (device, _) = book.pair(&token, name, "alex@github").unwrap(); + let keys = SubscriptionKeys { + p256dh: "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4" + .into(), + auth: "BTBZMqHH6r4Tts7J_aSIgg".into(), + }; + let subscription = endpoint.map(|endpoint| Subscription { endpoint: endpoint.into(), keys }); + book.subscribe(&device.id, subscription).unwrap(); + device.id +} + +fn book() -> (tempfile::TempDir, DeviceBook) { + let dir = tempfile::tempdir().unwrap(); + let book = DeviceBook::at(dir.path().join("remote.json")); + (dir, book) +} + +/// The break this catches: a notice sent to a device with that very session on screen, to one +/// that never opted in, or held back from a device that's only looking at another session. +#[tokio::test] +async fn a_notice_reaches_each_subscribed_device_not_looking_at_it() { + let (_dir, book) = book(); + let presence = Presence::default(); + let elsewhere = device(&book, "iPhone", Some("https://web.push.apple.com/phone")); + let looking = device(&book, "iPad", Some("https://web.push.apple.com/ipad")); + device(&book, "Laptop", None); + let _phone = presence.arrive(&elsewhere, "session-2"); + let _ipad = presence.arrive(&looking, "session-1"); + + let courier = Recording::answering(Delivery::Taken); + dispatch(&book, &presence, &courier, ¬ice()).await; + assert_eq!(courier.sent(), ["https://web.push.apple.com/phone"]); +} + +fn kept(book: &DeviceBook, id: &str) -> Option { + let devices = book.devices(); + let device = devices.iter().find(|device| device.id == id)?; + Some(device.subscription()?.endpoint.clone()) +} + +/// The break this catches: a subscription Apple has dropped posted to forever (each one a wasted +/// request, and a 410 in the log), or one forgotten after a post that went through. +#[tokio::test] +async fn a_subscription_is_forgotten_only_when_its_service_says_it_is_gone() { + let (_dir, book) = book(); + let id = device(&book, "iPhone", Some("https://web.push.apple.com/phone")); + let presence = Presence::default(); + + dispatch(&book, &presence, &Recording::answering(Delivery::Taken), ¬ice()).await; + assert_eq!(kept(&book, &id).as_deref(), Some("https://web.push.apple.com/phone")); + dispatch(&book, &presence, &Recording::answering(Delivery::Gone), ¬ice()).await; + assert_eq!(kept(&book, &id), None); +} + +/// A named bridge's notice says which computer it's from, after the project; an unnamed one is +/// left as the session wrote it. +/// +/// The break this catches: a phone paired with two computers told "luxe-dev" wants it, with no +/// way to know which computer to open, or the body or session changed along with the title. +#[test] +fn a_notice_names_the_computer_it_came_from() { + let named = on_machine(notice(), Some("desk")); + assert_eq!(named.title, "luxe-dev \u{00b7} desk"); + assert_eq!((named.body.as_str(), named.session.as_str()), ("Approve bash", "session-1")); + assert_eq!(on_machine(notice(), None).title, "luxe-dev"); +} diff --git a/crates/luxe-remote/src/push/vapid.rs b/crates/luxe-remote/src/push/vapid.rs new file mode 100644 index 0000000..318b968 --- /dev/null +++ b/crates/luxe-remote/src/push/vapid.rs @@ -0,0 +1,74 @@ +//! VAPID — how the bridge proves to a push service that it's the server a device subscribed to. +//! +//! A device subscribes with the bridge's public key, and each push carries a short token signed +//! with the private one (RFC 8292). The token names the push service it's for and when it +//! expires, and as its contact the project's homepage: nothing about this machine or its owner. + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use ring::rand::SystemRandom; +use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_FIXED_SIGNING}; + +/// The contact a token names. A push service wants a URL or `mailto:` there. +const CONTACT: &str = env!("CARGO_PKG_HOMEPAGE"); + +/// Why the bridge's push key couldn't be made, read or used. +#[derive(Debug, thiserror::Error)] +pub(crate) enum VapidError { + /// The stored key isn't a P-256 key in PKCS#8 + #[error("the stored push key isn't a P-256 private key")] + Unreadable, + /// The system's randomness failed + #[error("the system's random number source failed")] + Random, +} + +/// The bridge's push signing key. +pub(crate) struct Vapid { + pair: EcdsaKeyPair, + random: SystemRandom, +} + +impl Vapid { + /// A new key, and the PKCS#8 document to keep it in. + pub(crate) fn generate() -> Result<(Self, Vec), VapidError> { + let random = SystemRandom::new(); + let document = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &random) + .map_err(|_| VapidError::Random)?; + let kept = document.as_ref().to_vec(); + Ok((Self::from_pkcs8(&kept)?, kept)) + } + + /// The key kept in `document`. + pub(crate) fn from_pkcs8(document: &[u8]) -> Result { + let random = SystemRandom::new(); + let pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, document, &random) + .map_err(|_| VapidError::Unreadable)?; + Ok(Self { pair, random }) + } + + /// The public key, base64url, as a device passes it to `PushManager.subscribe`. + pub(crate) fn public_key(&self) -> String { + URL_SAFE_NO_PAD.encode(self.pair.public_key().as_ref()) + } + + /// The `Authorization` header for the push service at origin `audience`, good until + /// `expires_at` (seconds since the Unix epoch). + pub(crate) fn authorization( + &self, + audience: &str, + expires_at: u64, + ) -> Result { + let header = URL_SAFE_NO_PAD.encode(br#"{"typ":"JWT","alg":"ES256"}"#); + let claims = serde_json::json!({ "aud": audience, "exp": expires_at, "sub": CONTACT }); + let claims = URL_SAFE_NO_PAD.encode(claims.to_string()); + let signed = format!("{header}.{claims}"); + let signature = + self.pair.sign(&self.random, signed.as_bytes()).map_err(|_| VapidError::Random)?; + let signature = URL_SAFE_NO_PAD.encode(signature.as_ref()); + Ok(format!("vapid t={signed}.{signature}, k={}", self.public_key())) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/push/vapid/tests.rs b/crates/luxe-remote/src/push/vapid/tests.rs new file mode 100644 index 0000000..f890c20 --- /dev/null +++ b/crates/luxe-remote/src/push/vapid/tests.rs @@ -0,0 +1,68 @@ +use super::*; +use ring::signature::{UnparsedPublicKey, ECDSA_P256_SHA256_FIXED}; + +const APPLE: &str = "https://web.push.apple.com"; + +/// The token and key out of an `Authorization` header. +fn parts(header: &str) -> (String, Vec) { + let rest = header.strip_prefix("vapid t=").expect("a vapid header"); + let (token, key) = rest.split_once(", k=").expect("a token and a key"); + (token.to_string(), URL_SAFE_NO_PAD.decode(key).expect("the key is base64url")) +} + +fn decoded(segment: &str) -> serde_json::Value { + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).unwrap()).unwrap() +} + +/// The token says what Apple checks: ES256, the push service it's for, the expiry, and a URL to +/// reach the sender. +/// +/// The break this catches: a claim renamed or dropped, or a contact that isn't a URL, which Apple +/// answers with 403 `BadJwtToken` for every push. +#[test] +fn the_token_carries_what_apple_checks() { + let (vapid, _) = Vapid::generate().unwrap(); + let (token, _) = parts(&vapid.authorization(APPLE, 1_800_000_000).unwrap()); + let segments: Vec<&str> = token.split('.').collect(); + assert_eq!(segments.len(), 3, "{token}"); + assert_eq!(decoded(segments[0]), serde_json::json!({ "typ": "JWT", "alg": "ES256" })); + let claims = + serde_json::json!({ "aud": APPLE, "exp": 1_800_000_000u64, "sub": "https://luxe.dev" }); + assert_eq!(decoded(segments[1]), claims); +} + +/// The signature checks out against the key the header gives, with ring's verifier rather than +/// anything of the bridge's. +/// +/// The break this catches: signing other bytes than the token's first two parts, a DER signature +/// where JWS wants the fixed 64 bytes, or the header naming another key. +#[test] +fn the_token_is_signed_by_the_key_it_names() { + let (vapid, _) = Vapid::generate().unwrap(); + let (token, key) = parts(&vapid.authorization(APPLE, 1_800_000_000).unwrap()); + let (signed, signature) = token.rsplit_once('.').unwrap(); + let signature = URL_SAFE_NO_PAD.decode(signature).unwrap(); + let verifier = UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, &key); + assert!(verifier.verify(signed.as_bytes(), &signature).is_ok()); + assert_eq!(URL_SAFE_NO_PAD.encode(&key), vapid.public_key()); +} + +/// The key a device subscribed with is the one the bridge signs with after a restart. +/// +/// The break this catches: the kept document not being the key in use, so every subscription is +/// refused (`VapidPkHashMismatch`) once the bridge restarts. +#[test] +fn a_kept_key_is_the_same_key() { + let (vapid, document) = Vapid::generate().unwrap(); + let kept = Vapid::from_pkcs8(&document).unwrap(); + assert_eq!(kept.public_key(), vapid.public_key()); + let key = URL_SAFE_NO_PAD.decode(kept.public_key()).unwrap(); + assert_eq!((key.len(), key[0]), (65, 4), "an uncompressed P-256 point"); +} + +/// The break this catches: a damaged key file taken for a key, or a panic, rather than an error +/// the bridge can report. +#[test] +fn a_damaged_key_is_an_error() { + assert!(matches!(Vapid::from_pkcs8(b"not a key"), Err(VapidError::Unreadable))); +} diff --git a/crates/luxe-remote/src/push/watch.rs b/crates/luxe-remote/src/push/watch.rs new file mode 100644 index 0000000..c55d50c --- /dev/null +++ b/crates/luxe-remote/src/push/watch.rs @@ -0,0 +1,162 @@ +//! Watch — the bridge's own reader on every running session, while any device wants notifications. +//! +//! A phone's socket lasts only while the app is on screen, so nothing would hear a prompt +//! arrive while it's in a pocket. Instead the bridge joins each running session itself, as a +//! watch-only client, which the terminal doesn't announce and which can't act. It reads the +//! stream and sends nothing back. With no device subscribed it joins nothing, and leaves what it +//! had joined. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::time::Duration; + +use luxe_core::local_endpoint::{self, LiveSession}; +use luxe_core::Event; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::sync::mpsc; +use tokio::time::Instant; + +use super::notice::{Heard, Notice, Reading, PROMPT_GRACE}; +use crate::devices::DeviceBook; + +/// How often the running sessions and the subscriptions are looked at again. +pub(crate) const WATCH_CHECK: Duration = Duration::from_secs(5); + +/// Who the watcher joins as: unannounced, so its name shows only in the session's log. +pub(crate) const WATCHER: crate::relay::Introduction<'static> = + crate::relay::Introduction { name: "Notifications", watch_only: true, yours: false }; + +/// Keeps a reader on each running session while any device is subscribed, sending what they hear +/// to `notices`, until the task is dropped. +pub(crate) async fn watch_sessions( + runtime_dir: PathBuf, + devices: DeviceBook, + notices: mpsc::Sender, +) { + let mut watching: HashMap = HashMap::new(); + loop { + let running = if anyone_subscribed(&devices).await { + running(runtime_dir.clone()).await + } else { + Vec::new() + }; + keep_watching(&mut watching, running, ¬ices); + tokio::time::sleep(WATCH_CHECK).await; + } +} + +/// Stops the readers of sessions no longer running (and of any that quit), and starts one on each +/// session that has none, keyed by endpoint: a session's id changes when the terminal switches. +fn keep_watching( + watching: &mut HashMap, + running: Vec, + notices: &mpsc::Sender, +) { + let live = |address: &String| running.iter().any(|session| &session.address == address); + watching.retain(|address, watcher| live(address) && !watcher.0.is_finished()); + for session in running { + let notices = notices.clone(); + watching + .entry(session.address.clone()) + .or_insert_with(|| Watcher(tokio::spawn(watch_session(session, notices)))); + } +} + +/// A task stopped when dropped: a session's reader, or the notifications as a whole. +pub(crate) struct Watcher(pub(super) tokio::task::JoinHandle<()>); + +impl Drop for Watcher { + fn drop(&mut self) { + self.0.abort(); + } +} + +async fn anyone_subscribed(devices: &DeviceBook) -> bool { + let devices = devices.clone(); + let paired = tokio::task::spawn_blocking(move || devices.devices()).await; + paired.is_ok_and(|paired| paired.iter().any(|device| device.subscription().is_some())) +} + +async fn running(runtime_dir: PathBuf) -> Vec { + // reads a folder and, on Windows, asks `tasklist` about each pid + let found = tokio::task::spawn_blocking(move || local_endpoint::running_sessions(&runtime_dir)); + found.await.unwrap_or_default() +} + +/// Reads `session` until it ends, sending its notices on, each prompt only once it's waited +/// [`PROMPT_GRACE`] unanswered. +pub(crate) async fn watch_session(session: LiveSession, notices: mpsc::Sender) { + let Some(mut lines) = join(&session).await else { return }; + let mut reading = Reading::new(&session.session_id, &session.cwd); + let mut held = Held::default(); + loop { + // both are cancel-safe: a line stays buffered, and a held prompt is taken only once due + let heard = tokio::select! { + line = lines.next_line() => match line { + Ok(Some(line)) => { + decode(&line).and_then(|event| reading.read(&event, Instant::now())) + } + Ok(None) | Err(_) => return, + }, + notice = held.due() => Some(Heard::Now(notice)), + }; + if !held.take(heard, ¬ices).await { + return; + } + } +} + +/// The session's stream, joined as the watcher. +async fn join( + session: &LiveSession, +) -> Option>> { + match crate::routes::open(&session.address, &WATCHER).await { + Ok(stream) => Some(BufReader::new(stream).lines()), + Err(error) => { + tracing::warn!(%error, session = %session.session_id, "couldn't watch a session"); + None + } + } +} + +fn decode(line: &str) -> Option { + serde_json::from_str(line) + .inspect_err(|error| tracing::debug!(%error, "a session line that isn't an event")) + .ok() +} + +/// Prompts waiting out their grace. +#[derive(Default)] +struct Held { + prompts: Vec<(Instant, String, Notice)>, +} + +impl Held { + /// Acts on what was heard: sends it, holds it or lets one go. False once nobody's listening. + async fn take(&mut self, heard: Option, notices: &mpsc::Sender) -> bool { + match heard { + Some(Heard::Now(notice)) => return notices.send(notice).await.is_ok(), + Some(Heard::Prompt(id, notice)) => { + self.prompts.push((Instant::now() + PROMPT_GRACE, id, notice)); + } + Some(Heard::Closed(id)) => self.prompts.retain(|(_, held, _)| *held != id), + None => {} + } + true + } + + /// The next prompt to come due, once it has; never, with none held. + async fn due(&mut self) -> Notice { + let Some(next) = self.prompts.iter().map(|(due, ..)| *due).min() else { + return std::future::pending().await; + }; + tokio::time::sleep_until(next).await; + let at = self.prompts.iter().position(|(due, ..)| *due == next); + // only `take` drops a prompt, and it can't run while this waits + let at = at.expect("a due prompt is still held"); + self.prompts.remove(at).2 + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/push/watch/tests.rs b/crates/luxe-remote/src/push/watch/tests.rs new file mode 100644 index 0000000..74d2738 --- /dev/null +++ b/crates/luxe-remote/src/push/watch/tests.rs @@ -0,0 +1,145 @@ +use super::*; +use luxe_core::event::Action; +use luxe_core::local_endpoint::{EndpointListener, Joined, Publication}; +use tokio::io::AsyncWriteExt; + +const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#; +const QUESTION: &str = r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"session-1","prompt":"Which database?","options":[],"multi":false}}"#; +const CLOSED: &str = r#"{"kind":"prompt_closed","content":{"id":"perm:1"}}"#; + +/// A session's endpoint, and the folder it's published in. +struct Session { + listener: EndpointListener, + live: LiveSession, + runtime: tempfile::TempDir, +} + +fn session() -> Session { + let runtime = tempfile::tempdir().unwrap(); + let listener = EndpointListener::bind(runtime.path()).unwrap(); + let live = LiveSession { + pid: std::process::id(), + session_id: "session-1".into(), + cwd: "/work/luxe-dev".into(), + address: listener.address().to_string(), + luxe_version: "0.1.3".into(), + }; + Session { listener, live, runtime } +} + +/// Starts a watcher on `session`, and takes its notices and the session's end of the stream. +async fn watched(session: &mut Session) -> (mpsc::Receiver, Joined, Watcher) { + let (notices, heard) = mpsc::channel(8); + let watcher = Watcher(tokio::spawn(watch_session(session.live.clone(), notices))); + let joined = session.listener.accept().await.unwrap(); + (heard, joined, watcher) +} + +async fn say(joined: &mut Joined, lines: &[&str]) { + let text: String = lines.iter().map(|line| format!("{line}\n")).collect(); + joined.stream.write_all(text.as_bytes()).await.unwrap(); +} + +/// The watcher opens as watch-only, so the terminal doesn't announce it, and then says nothing. +/// +/// The break this catches: a watcher that joins as an ordinary client (the terminal says +/// "Notifications joined this session" in every session) or that sends the session anything else, +/// an answer included. +#[tokio::test(start_paused = true)] +async fn the_watcher_introduces_itself_and_says_nothing_else() { + let mut session = session(); + let (_heard, joined, _watcher) = watched(&mut session).await; + let mut lines = BufReader::new(joined.stream).lines(); + let first = lines.next_line().await.unwrap().unwrap(); + let introduced: Action = serde_json::from_str(&first).unwrap(); + let watcher = + Action::Introduce { name: "Notifications".into(), watch_only: true, yours: false }; + assert_eq!(introduced, watcher); + let more = tokio::time::timeout(Duration::from_secs(60), lines.next_line()).await; + assert!(more.is_err(), "the watcher sent {more:?}"); +} + +/// The break this catches: a prompt sent the moment it's asked, buzzing a phone while you answer +/// at the desk, or never sent at all. +#[tokio::test(start_paused = true)] +async fn a_prompt_is_sent_once_it_has_waited() { + let mut session = session(); + let (mut heard, mut joined, _watcher) = watched(&mut session).await; + let asked = Instant::now(); + say(&mut joined, &[PERMISSION]).await; + let notice = heard.recv().await.expect("a notice"); + assert_eq!((notice.title.as_str(), notice.body.as_str()), ("luxe-dev", "Approve bash")); + assert!(asked.elapsed() >= PROMPT_GRACE, "sent after {:?}", asked.elapsed()); +} + +/// The break this catches: a prompt answered at the desk still reaching the phone, or one answer +/// letting every held prompt go. +#[tokio::test(start_paused = true)] +async fn a_prompt_answered_in_time_is_never_sent() { + let mut session = session(); + let (mut heard, mut joined, _watcher) = watched(&mut session).await; + say(&mut joined, &[PERMISSION, QUESTION, CLOSED]).await; + let notice = heard.recv().await.expect("a notice"); + assert_eq!(notice.body, "Luxe has a question"); + tokio::time::sleep(PROMPT_GRACE * 2).await; + assert!(heard.try_recv().is_err(), "the answered prompt was sent"); +} + +/// The break this catches: a watcher that outlives its session, holding a task (and in time a +/// file handle) for every session that ever ran. +#[tokio::test(start_paused = true)] +async fn the_watcher_ends_with_its_session() { + let mut session = session(); + let (_heard, joined, watcher) = watched(&mut session).await; + // once it has introduced itself it's reading, rather than failing to join + let mut lines = BufReader::new(joined.stream).lines(); + lines.next_line().await.unwrap().expect("an introduction"); + drop(lines); + tokio::time::timeout(Duration::from_secs(5), async { + while !watcher.0.is_finished() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the watcher stopped"); +} + +/// A book with one paired device, and that device's id. +fn paired() -> (tempfile::TempDir, DeviceBook, String) { + let dir = tempfile::tempdir().unwrap(); + let book = DeviceBook::at(dir.path().join("remote.json")); + let token = book.invite().unwrap(); + let (device, _) = book.pair(&token, "iPhone", "alex@github").unwrap(); + (dir, book, device.id) +} + +fn subscribe(book: &DeviceBook, id: &str, on: bool) { + let subscription = on.then(|| serde_json::from_str(crate::push::FROM_SAFARI).unwrap()); + book.subscribe(id, subscription).unwrap(); +} + +/// Whether the watcher joins `session` within a few checks. +async fn joins(session: &mut Session) -> Option { + tokio::time::timeout(WATCH_CHECK * 3, session.listener.accept()).await.ok()?.ok() +} + +/// The break this catches: a bridge that sits in every session whether or not anyone wants +/// notifications (a "Notifications joined" line in every terminal), or that never joins. +#[tokio::test(start_paused = true)] +async fn sessions_are_watched_only_while_a_device_is_subscribed() { + let mut session = session(); + let _record: Publication = session.live.publish(session.runtime.path()).unwrap(); + let (_dir, book, id) = paired(); + let (notices, _heard) = mpsc::channel(8); + let runtime = session.runtime.path().to_path_buf(); + let _watching = Watcher(tokio::spawn(watch_sessions(runtime, book.clone(), notices))); + assert!(joins(&mut session).await.is_none(), "joined with nobody subscribed"); + + subscribe(&book, &id, true); + let joined = joins(&mut session).await.expect("joined once a device subscribed"); + subscribe(&book, &id, false); + let mut lines = BufReader::new(joined.stream).lines(); + let _introduction = lines.next_line().await.unwrap(); + let ended = tokio::time::timeout(WATCH_CHECK * 3, lines.next_line()).await; + assert!(matches!(ended, Ok(Ok(None))), "still watching after the last device left: {ended:?}"); +} diff --git a/crates/luxe-remote/src/push/web_push.rs b/crates/luxe-remote/src/push/web_push.rs new file mode 100644 index 0000000..71d40f3 --- /dev/null +++ b/crates/luxe-remote/src/push/web_push.rs @@ -0,0 +1,177 @@ +//! Web push — one notification posted to the push service a device subscribed through (RFC 8030). + +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Mutex, PoisonError}; +use std::time::Duration; + +use super::encryption::{encrypt, EncryptionError}; +use super::notice::Notice; +use super::{Subscription, Vapid, VapidError}; + +/// How long a push service keeps a notification for a device that's offline, in seconds. Past an +/// hour, what it says has likely changed. +const TIME_TO_LIVE: u32 = 3600; + +/// How long a signed token is good for. Apple takes up to a day. +const TOKEN_LIFETIME_SECS: u64 = 12 * 3600; + +/// A token is signed again once it has less than this left. Apple asks for no new token more +/// often than hourly, which this keeps to. +const TOKEN_RENEWAL_SECS: u64 = 3600; + +/// The longest a post to a push service may take, so a stalled one can't hold the rest back. +const POST_TIMEOUT: Duration = Duration::from_secs(15); + +/// What a push service did with a notification. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Delivery { + /// Taken for delivery + Taken, + /// The subscription has expired or been withdrawn, and won't take any more + Gone, +} + +/// Why a notification wasn't posted. +#[derive(Debug, thiserror::Error)] +pub(crate) enum PushError { + /// It couldn't be sealed for the device + #[error(transparent)] + Encryption(#[from] EncryptionError), + /// The token couldn't be signed + #[error(transparent)] + Key(#[from] VapidError), + /// The push service couldn't be reached + #[error("couldn't reach the push service: {0}")] + Network(#[from] reqwest::Error), + /// The push service turned it down + #[error("the push service refused it with {status}: {reason}")] + Refused { + /// Its status code + status: u16, + /// What it said, cut short + reason: String, + }, + /// The subscription's endpoint or keys don't read + #[error("the subscription doesn't read")] + BadSubscription, +} + +/// What posts a notification. The bridge's is [`WebPush`]; tests post nowhere. +pub(crate) trait Courier: Send + Sync { + /// Posts `notice` to `subscription`. + fn deliver<'a>( + &'a self, + subscription: &'a Subscription, + notice: &'a Notice, + ) -> Pin> + Send + 'a>>; +} + +/// A signed token, and when it expires. +struct Token { + header: String, + expires_at: u64, +} + +/// The bridge's courier: Web Push over HTTPS, signed with the bridge's key. +pub(crate) struct WebPush { + client: reqwest::Client, + vapid: Vapid, + tokens: Mutex>, +} + +impl WebPush { + /// A courier signing with `vapid`. + pub(crate) fn new(vapid: Vapid) -> Result { + let client = reqwest::Client::builder().timeout(POST_TIMEOUT).build()?; + Ok(Self { client, vapid, tokens: Mutex::new(HashMap::new()) }) + } + + /// The post for `notice` to `subscription`, as of `now` (seconds since the Unix epoch). + pub(crate) fn request( + &self, + subscription: &Subscription, + notice: &Notice, + now: u64, + ) -> Result { + let audience = subscription.audience().ok_or(PushError::BadSubscription)?; + let body = sealed(subscription, notice)?; + let urgency = if notice.urgent { "high" } else { "normal" }; + let mut post = self.client.post(&subscription.endpoint).body(body); + post = post.header("TTL", TIME_TO_LIVE).header("Urgency", urgency); + post = post.header("Content-Encoding", "aes128gcm"); + post = post.header("Content-Type", "application/octet-stream"); + post = post.header("Authorization", self.authorization(&audience, now)?); + post = post.header("Topic", topic(¬ice.session)); + Ok(post.build()?) + } + + /// The `Authorization` header for `audience`, reusing a token that has an hour left. + fn authorization(&self, audience: &str, now: u64) -> Result { + let mut tokens = self.tokens.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(token) = tokens.get(audience) { + if token.expires_at > now + TOKEN_RENEWAL_SECS { + return Ok(token.header.clone()); + } + } + let expires_at = now + TOKEN_LIFETIME_SECS; + let header = self.vapid.authorization(audience, expires_at)?; + tokens.insert(audience.to_string(), Token { header: header.clone(), expires_at }); + Ok(header) + } + + async fn post( + &self, + subscription: &Subscription, + notice: &Notice, + ) -> Result { + let request = self.request(subscription, notice, unix_now())?; + let response = self.client.execute(request).await?; + let status = response.status(); + if status.is_success() { + return Ok(Delivery::Taken); + } + if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::GONE { + return Ok(Delivery::Gone); + } + let reason = response.text().await.unwrap_or_default().chars().take(200).collect(); + Err(PushError::Refused { status: status.as_u16(), reason }) + } +} + +impl Courier for WebPush { + fn deliver<'a>( + &'a self, + subscription: &'a Subscription, + notice: &'a Notice, + ) -> Pin> + Send + 'a>> { + Box::pin(self.post(subscription, notice)) + } +} + +/// `notice` as the service worker reads it, sealed for the subscription's device. +fn sealed(subscription: &Subscription, notice: &Notice) -> Result, PushError> { + let (device_key, auth) = subscription.key_bytes().ok_or(PushError::BadSubscription)?; + let message = serde_json::to_vec(notice).expect("a notice is plain strings"); + Ok(encrypt(&message, &device_key, &auth)?) +} + +/// The `Topic` for a session's notifications, so a push service holding several for an offline +/// device passes on only the newest. Apple takes at most 32 base64url characters and reads them as +/// base64, refusing some lengths, so it's always 32: a hash of the id, which also keeps the id +/// itself from the push service. +fn topic(session: &str) -> String { + use base64::Engine as _; + use sha2::Digest as _; + let digest = sha2::Sha256::digest(session.as_bytes()); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..24]) +} + +fn unix_now() -> u64 { + let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH); + since.map(|elapsed| elapsed.as_secs()).unwrap_or(0) +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/push/web_push/tests.rs b/crates/luxe-remote/src/push/web_push/tests.rs new file mode 100644 index 0000000..fe11f3f --- /dev/null +++ b/crates/luxe-remote/src/push/web_push/tests.rs @@ -0,0 +1,126 @@ +use super::*; +use crate::push::encryption::tests::open; +use crate::push::SubscriptionKeys; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use ring::agreement::{EphemeralPrivateKey, ECDH_P256}; + +const NOW: u64 = 1_800_000_000; +const SESSION: &str = "5898d57b-0000-4000-8000-000000000001"; + +/// A device's private key and the subscription its browser would make with it. +fn device() -> (EphemeralPrivateKey, Subscription) { + let private = EphemeralPrivateKey::generate(&ECDH_P256, &ring::rand::SystemRandom::new()); + let private = private.unwrap(); + let public = private.compute_public_key().unwrap(); + let keys = SubscriptionKeys { + p256dh: URL_SAFE_NO_PAD.encode(public.as_ref()), + auth: URL_SAFE_NO_PAD.encode([7u8; 16]), + }; + (private, Subscription { endpoint: "https://web.push.apple.com/abc".into(), keys }) +} + +fn courier() -> WebPush { + WebPush::new(Vapid::generate().unwrap().0).unwrap() +} + +fn notice(urgent: bool) -> Notice { + let (title, body) = ("luxe-dev".into(), "Approve bash".into()); + Notice { title, body, session: SESSION.into(), urgent } +} + +fn header<'a>(request: &'a reqwest::Request, name: &str) -> &'a str { + request.headers()[name].to_str().unwrap() +} + +/// The post goes to the subscription with the headers a push service requires, and the device +/// opens the body to the notice the service worker shows. +/// +/// The break this catches: a missing `TTL` (Apple's `BadTtl`) or encoding, the wrong urgency, or a +/// body sealed for someone else or carrying fields the worker doesn't read. +#[test] +fn a_post_carries_what_the_push_service_and_the_device_need() { + let (private, subscription) = device(); + let request = courier().request(&subscription, ¬ice(true), NOW).unwrap(); + assert_eq!(request.url().as_str(), subscription.endpoint); + assert_eq!(header(&request, "TTL"), "3600"); + assert_eq!(header(&request, "Urgency"), "high"); + assert_eq!(header(&request, "Content-Encoding"), "aes128gcm"); + assert_eq!(header(&request, "Topic"), "DJZtLYoay56CTZC7EDzavnWaSjSnBF8s"); + assert!(header(&request, "Authorization").starts_with("vapid t=")); + let body = request.body().and_then(reqwest::Body::as_bytes).unwrap(); + let (device_key, auth) = subscription.key_bytes().unwrap(); + let opened = open(private, &device_key, &auth, body); + let shown: serde_json::Value = serde_json::from_slice(&opened[..opened.len() - 1]).unwrap(); + let expected = + serde_json::json!({ "title": "luxe-dev", "body": "Approve bash", "session": SESSION }); + assert_eq!(shown, expected); + let later = courier().request(&subscription, ¬ice(false), NOW).unwrap(); + assert_eq!(header(&later, "Urgency"), "normal"); +} + +/// The claims inside a request's token. +fn claims(request: &reqwest::Request) -> serde_json::Value { + let token = header(request, "Authorization").strip_prefix("vapid t=").unwrap(); + let claims = token.split('.').nth(1).unwrap(); + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims).unwrap()).unwrap() +} + +/// The break this catches: a token signed for every post, which Apple asks servers not to do more +/// than hourly, or one kept past its expiry, which it refuses; or a token for the wrong service. +#[test] +fn a_token_is_reused_until_it_has_an_hour_left() { + let (_, subscription) = device(); + let courier = courier(); + let first = courier.request(&subscription, ¬ice(true), NOW).unwrap(); + let token = |request: &reqwest::Request| header(request, "Authorization").to_string(); + let expected = serde_json::json!({ "aud": "https://web.push.apple.com", "exp": NOW + TOKEN_LIFETIME_SECS, "sub": "https://luxe.dev" }); + assert_eq!(claims(&first), expected); + let renew_at = NOW + TOKEN_LIFETIME_SECS - TOKEN_RENEWAL_SECS; + let reused = courier.request(&subscription, ¬ice(true), renew_at - 1).unwrap(); + assert_eq!(token(&reused), token(&first)); + let renewed = courier.request(&subscription, ¬ice(true), renew_at).unwrap(); + assert_eq!(claims(&renewed)["exp"], renew_at + TOKEN_LIFETIME_SECS); +} + +/// The topic is 32 base64url characters whatever the id, and differs between sessions. +/// +/// The break this catches: a session id passed through whole, whose 36 characters Apple refuses +/// (`BadWebPushTopic`), a shorter one at a length Apple can't read as base64, or one topic for +/// every session, so a newer notice from one session replaces another's. +#[test] +fn a_topic_is_always_32_url_safe_characters() { + assert_eq!(topic(SESSION), "DJZtLYoay56CTZC7EDzavnWaSjSnBF8s"); + assert_eq!(topic("short-1"), "GA5_ZXQcTDu9kMi-CVbgVxwQ_TCZQ-fp"); + assert_eq!(topic("").len(), 32); +} + +/// A push service on this machine that answers every post with the status in its path. +async fn push_service() -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let answer = |axum::extract::Path(status): axum::extract::Path| async move { + (axum::http::StatusCode::from_u16(status).unwrap(), "BadDeviceToken") + }; + let app = axum::Router::new().route("/{status}", axum::routing::post(answer)); + tokio::spawn(async move { axum::serve(listener, app).await }); + format!("http://{address}") +} + +async fn delivered(courier: &WebPush, service: &str, status: u16) -> String { + let (_, mut subscription) = device(); + subscription.endpoint = format!("{service}/{status}"); + format!("{:?}", courier.deliver(&subscription, ¬ice(false)).await) +} + +/// The break this catches: a dropped subscription (404 or 410) taken as a failure, so it's posted +/// to forever, or any other refusal taken as gone, so one bad request forgets a working device. +#[tokio::test] +async fn what_the_push_service_answers_is_told_apart() { + let (courier, service) = (courier(), push_service().await); + assert_eq!(delivered(&courier, &service, 201).await, "Ok(Taken)"); + assert_eq!(delivered(&courier, &service, 404).await, "Ok(Gone)"); + assert_eq!(delivered(&courier, &service, 410).await, "Ok(Gone)"); + let refused = delivered(&courier, &service, 400).await; + assert!(refused.contains("status: 400") && refused.contains("BadDeviceToken"), "{refused}"); +} diff --git a/crates/luxe-remote/src/relay.rs b/crates/luxe-remote/src/relay.rs new file mode 100644 index 0000000..b071049 --- /dev/null +++ b/crates/luxe-remote/src/relay.rs @@ -0,0 +1,203 @@ +//! Relay — one device's WebSocket piped to one session's local endpoint. +//! +//! The protocol is a JSON object per line, and a WebSocket already frames messages, so a line +//! becomes a text frame and a text frame becomes a line. Nothing the device sends is parsed: the +//! session answers a bad frame itself, with `action_rejected`, as it would for any client. The one +//! line held back is a session refusing the bridge's own `introduce`, which the device never sent. + +use axum::extract::ws::{close_code, CloseFrame, Message, WebSocket}; +use luxe_core::local_endpoint::LocalStream; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, WriteHalf}; + +/// The close code a device gets when it is unpaired while connected, from the range RFC 6455 leaves +/// to applications, so the app can say so instead of trying again. +pub(crate) const UNPAIRED: u16 = 4001; + +/// How long to wait for the device to answer the bridge's close before dropping the connection. +const CLOSE_WAIT: Duration = Duration::from_secs(2); + +/// Why a relay stopped, which decides how the device's socket is closed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Ending { + /// The device closed its socket, or lost it + DeviceLeft, + /// The session's endpoint closed + SessionEnded, + /// The device was unpaired while connected + Unpaired, +} + +/// Tells the session who is joining, so it can say "Approved from iPhone" rather than naming the +/// bridge's process. +pub(crate) async fn introduce( + session: &mut LocalStream, + introduction: &Introduction<'_>, +) -> std::io::Result<()> { + let frame = luxe_core::event::Action::Introduce { + name: introduction.name.to_string(), + watch_only: introduction.watch_only, + yours: introduction.yours, + }; + let frame = serde_json::to_string(&frame).map_err(std::io::Error::other)?; + session.write_all(one_line(&frame).as_bytes()).await +} + +/// Who the bridge joins a session as. +pub(crate) struct Introduction<'a> { + /// The device it relays for, or the watcher's name + pub(crate) name: &'a str, + /// Joins unannounced and can't act, as the notification watcher does + pub(crate) watch_only: bool, + /// The device was paired by the computer's owner, the person at its terminal + pub(crate) yours: bool, +} + +/// Pipes `socket` and `session` both ways until either side ends, or `until` resolves (the device +/// was revoked), then ends both. +pub(crate) async fn relay( + mut socket: WebSocket, + session: LocalStream, + until: impl std::future::Future, +) { + let (from_session, mut to_session) = tokio::io::split(session); + let ending = pump(&mut socket, from_session, &mut to_session, until).await; + let _ = to_session.shutdown().await; + close(socket, ending).await; +} + +/// Carries lines and frames across until one side stops, and says which. +async fn pump( + socket: &mut WebSocket, + from_session: tokio::io::ReadHalf, + to_session: &mut WriteHalf, + until: impl std::future::Future, +) -> Ending { + let mut lines = BufReader::new(from_session).lines(); + tokio::pin!(until); + // Both reads are cancel-safe, so a line or frame the other branch beat is never lost + loop { + let stopped = tokio::select! { + line = lines.next_line() => line_to_device(socket, line).await, + message = socket.recv() => frame_to_session(to_session, message).await, + () = &mut until => Some(Ending::Unpaired), + }; + if let Some(ending) = stopped { + return ending; + } + } +} + +async fn line_to_device( + socket: &mut WebSocket, + line: std::io::Result>, +) -> Option { + match line { + Ok(Some(line)) if refuses_introduction(&line) => None, + Ok(Some(line)) => { + socket.send(Message::Text(line.into())).await.err().map(|_| Ending::DeviceLeft) + } + Ok(None) => Some(Ending::SessionEnded), + Err(error) => { + tracing::warn!(%error, "stopped reading the session"); + Some(Ending::SessionEnded) + } + } +} + +/// Whether `line` is the session refusing the bridge's `introduce`. Only a session started before +/// its Luxe knew the action does, and it carries on without the device's name; the refusal is of a +/// frame the device never sent, so showing it there reads as a fault. Decoded only when it could +/// be one, so every other line still passes untouched. +fn refuses_introduction(line: &str) -> bool { + if !line.contains("action_rejected") { + return false; + } + matches!( + serde_json::from_str::(line), + Ok(luxe_core::event::Event::ActionRejected { kind: Some(kind), .. }) if kind == "introduce" + ) +} + +async fn frame_to_session( + to_session: &mut WriteHalf, + message: Option>, +) -> Option { + let text = match message { + Some(Ok(Message::Text(text))) => text, + // Pings are answered by axum; binary has no meaning in a line protocol + Some(Ok(Message::Binary(_) | Message::Ping(_) | Message::Pong(_))) => return None, + Some(Ok(Message::Close(_)) | Err(_)) | None => return Some(Ending::DeviceLeft), + }; + let written = to_session.write_all(one_line(&text).as_bytes()).await; + written.err().map(|_| Ending::SessionEnded) +} + +/// Closes the device's socket the way `ending` calls for, so the app can tell leaving, a session +/// that ended and being unpaired apart from a dropped connection, which is the one worth retrying. +async fn close(mut socket: WebSocket, ending: Ending) { + let frame = |code, reason: &str| Some(CloseFrame { code, reason: reason.into() }); + let frame = match ending { + // tungstenite refuses to send once the device has closed; it queued its own answer, and + // the read below sends it + Ending::DeviceLeft => None, + Ending::SessionEnded => frame(close_code::NORMAL, "the session ended"), + Ending::Unpaired => frame(UNPAIRED, "this device was unpaired"), + }; + if frame.is_some() && socket.send(Message::Close(frame)).await.is_err() { + return; + } + let answered = async { while let Some(Ok(_)) = socket.recv().await {} }; + let _ = tokio::time::timeout(CLOSE_WAIT, answered).await; +} + +/// `frame` as exactly one protocol line. +/// +/// JSON can hold a raw line break only as whitespace between tokens (inside a string it is +/// escaped), so turning breaks into spaces keeps a pretty-printed frame one action instead of +/// several broken ones. +fn one_line(frame: &str) -> String { + let mut line: String = + frame.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); + line.push('\n'); + line +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A pretty-printed frame reaches the session as the one line it is. + /// + /// The break this catches: writing the frame as it came, so a client that sends indented JSON + /// gets several `action_rejected` answers and nothing done. + /// An older session's refusal of the bridge's `introduce` is held back, and every other + /// refusal goes through. + /// + /// The break this catches: a device joining a session that predates `introduce` shown + /// "Refused: no such action `introduce`" for a frame it never sent, or the device's own + /// refused frames (and the message words alone) swallowed too. + #[test] + fn only_the_refusal_of_the_introduction_is_held_back() { + let refused = |kind: &str| { + format!("{{\"kind\":\"action_rejected\",\"content\":{{\"kind\":\"{kind}\",\"reason\":\"no such action `{kind}`\"}}}}") + }; + assert!(refuses_introduction(&refused("introduce"))); + assert!(!refuses_introduction(&refused("submit_user_message"))); + let unparsed = + r#"{"kind":"action_rejected","content":{"reason":"no such action `introduce`"}}"#; + assert!( + !refuses_introduction(unparsed), + "the words alone don't make it the introduction's" + ); + assert!(!refuses_introduction(r#"{"kind":"turn_started"}"#)); + } + + #[test] + fn a_frame_is_one_line_however_it_was_printed() { + let pretty = "{\n \"kind\": \"cancel\"\r\n}"; + assert_eq!(one_line(pretty), "{ \"kind\": \"cancel\" }\n"); + let text = r#"{"kind":"submit_user_message","content":{"text":"a\nb"}}"#; + assert_eq!(one_line(text), format!("{text}\n"), "an escaped break is not a break"); + } +} diff --git a/crates/luxe-remote/src/render.rs b/crates/luxe-remote/src/render.rs new file mode 100644 index 0000000..8ac79ad --- /dev/null +++ b/crates/luxe-remote/src/render.rs @@ -0,0 +1,420 @@ +//! Render — a message as the app shows it, made on the host so the app parses nothing. +//! +//! Markdown, highlighted code, tool glyphs and the status line's wording are the TUI's, and the +//! bridge doesn't depend on the TUI, so `luxe-cli` hands one in as a [`Renderer`]. What a user +//! message shows (the reader's own words, and a brief Luxe wrote to the agent as one line saying +//! so) is core's call (`luxe_core::briefs`), so that is made here. The bridge keeps no session +//! state, so the app asks: once for a finished message, and a few times a second for one still +//! growing or a status that changed. + +mod diff; +mod file; +mod github; +mod review; +mod tree; +mod workspace; + +pub use github::GithubMarks; +pub use tree::{FileMark, MarkHue}; + +use luxe_core::briefs; +use luxe_core::file_diff::{FileDiff, FileDiffFailure}; +use luxe_core::github::overview::{ConversationEntry, Overview}; +use luxe_core::github::ListedSection; +use luxe_core::guided_review::{ + ChapterId, ChapterReading, GuidedReview, ReviewChapter, ReviewFile, ReviewFinding, +}; +use luxe_core::project_files::{ProjectFile, ProjectFileFailure}; +use luxe_core::provider::{PlanUsage, ThinkingLevel}; +use luxe_core::usage::SessionUsage; +use luxe_core::workspace::{FileChangeStatus, TodoSummary, WorkspaceChangesSummary}; +use luxe_core::ModelRef; +use luxe_core::TodoSummaryStatus; + +/// Turns model text into the app's HTML, and draws the app's icon from the same art the TUI's +/// wordmark is. +pub trait Renderer: Send + Sync { + /// `text` as HTML, for `voice`. Everything in `text` is data: it must come back escaped. + fn markdown(&self, text: &str, voice: Voice) -> String; + /// The glyph a tool's card wears, as plain text. + fn tool_glyph(&self, tool: &str) -> String; + /// The status line's facts, worded as the TUI's bar words them. + fn status(&self, facts: &StatusFacts) -> Vec; + /// The glyph beside a user message's "image(s) attached" line, as plain text. + fn image_glyph(&self) -> String { + String::new() + } + /// One line of source as HTML, highlighted for `language`. It must come back escaped. + fn code_line(&self, text: &str, _language: Option<&str>) -> String { + escape(text) + } + /// The mark the dock puts beside a todo, as plain text. + fn todo_mark(&self, _status: TodoSummaryStatus) -> String { + String::new() + } + /// The mark the dock puts beside a changed file, as plain text. + fn change_mark(&self, _status: FileChangeStatus) -> String { + String::new() + } + /// The mark the file tree puts before a file named `name`, by its language. + fn file_mark(&self, _name: &str) -> FileMark { + FileMark::default() + } + /// The mark the file tree puts before a folder, as plain text. + fn folder_mark(&self) -> String { + String::new() + } + /// The mark before the checked-out branch, as the TUI's project section has it. + fn branch_mark(&self) -> String { + String::new() + } + /// The mark beside `mode`'s name, as the TUI's composer title has it, as plain text. + fn mode_mark(&self, _mode: &str) -> String { + String::new() + } + /// The marks `/github` draws, as plain text. + fn github_marks(&self) -> GithubMarks { + GithubMarks::default() + } + /// How long before `now` `at` was, both in seconds since the Unix epoch, as plain text: `3h + /// ago`. Empty from a renderer without the TUI's words for it. + fn ago(&self, _at: u64, _now: u64) -> String { + String::new() + } + /// A GitHub body with the HTML people and bots put in it reduced to the markdown it amounts + /// to, as GitHub shows it. The result goes through [`Renderer::markdown`]. + fn github_readable(&self, body: &str) -> String { + body.to_owned() + } + /// The home-screen icon, `side` pixels square, in `colors`, as PNG bytes; none from a + /// renderer with no art to draw it from. + fn home_icon(&self, _side: u32, _colors: TileColors) -> Option> { + None + } +} + +/// The icon's two colors: the theme's background for the plate, its accent for the letter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TileColors { + /// The square behind the letter + pub plate: [u8; 3], + /// The letter + pub ink: [u8; 3], +} + +/// What a session last reported about itself, as the app forwards it from the frames. +#[derive(Debug, Default, serde::Deserialize)] +pub struct StatusFacts { + /// From `state_changed` + pub model: Option, + /// From `state_changed` + pub thinking: Option, + /// From `context_usage` + pub context: Option, + /// From `plan_usage` + pub plan: Option, + /// From `session_usage` + pub session: Option, +} + +/// A `context_usage` frame's content. +#[derive(Debug, Clone, Copy, serde::Deserialize)] +pub struct ContextUsage { + /// Tokens in the window + pub used_tokens: u32, + /// The window's size + pub context_window: u32, +} + +/// One fact on the status line, as words; the bridge escapes them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StatusSegment { + /// Which fact, as the class the app styles it by: `context`, `cost`, `thinking` or `model` + pub kind: &'static str, + /// The mark in front of it, if any + pub glyph: Option, + /// The words + pub label: String, + /// How loudly to color it + pub tone: StatusTone, +} + +/// How loudly a status segment is colored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StatusTone { + /// Body text + Plain, + /// The theme's warning color + Warning, + /// The theme's error color + Error, +} + +/// Which reader model text is rendered for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Voice { + /// An answer + Answer, + /// Model reasoning, which keeps its line breaks and leaves its code plain + Reasoning, +} + +/// The renderer a bridge has until it is handed the TUI's: every word shown, escaped, with no +/// formatting and no glyphs. +pub(crate) struct PlainText; + +impl Renderer for PlainText { + fn markdown(&self, text: &str, _voice: Voice) -> String { + format!("

{}

", escape(text)) + } + + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + + fn status(&self, facts: &StatusFacts) -> Vec { + let model = facts.model.as_ref().map(|model| model.display().to_string()); + let segment = + |label| StatusSegment { kind: "model", glyph: None, label, tone: StatusTone::Plain }; + model.into_iter().map(segment).collect() + } +} + +/// What the app asks to have rendered, in one round trip. +#[derive(Debug, serde::Deserialize)] +pub(crate) struct RenderRequest { + pub(crate) pieces: Vec, +} + +/// One thing to render. +#[derive(Debug, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(crate) enum Piece { + /// An answer's text + Answer { text: String }, + /// Reasoning's text + Reasoning { text: String }, + /// A user message's content blocks, as the wire carries them + User { content: Vec }, + /// A tool, by name + Tool { name: String }, + /// The status line + Status(Box), + /// The todos from `workspace_updated`, as the dock's PLAN shows them + Plan { todos: Box }, + /// The changed files from `workspace_updated`, each a way into its diff + Changes { changes: Box }, + /// A `file_diff_loaded` frame's diff + Diff { diff: Box }, + /// A `file_diff_failed` frame's reason + DiffFailed { error: FileDiffFailure }, + /// A `project_file_read` frame's file + File { file: Box }, + /// A `project_file_read_failed` frame's reason + FileFailed { error: ProjectFileFailure }, + /// The Files tab's rows, marked from the changes the dock has + Tree { rows: Vec, changes: Option> }, + /// The project panel's bar: the session's folder name behind the tree's folder mark, then the + /// branch from a `workspace_updated` frame, marked when the tree is dirty + ProjectName { + name: String, + #[serde(default)] + branch: Option, + #[serde(default)] + dirty: bool, + }, + /// The status line's mode button: the mode's name behind its mark + ModeName { mode: String }, + /// A `github_listed` section, as `/github`'s list draws it. Args: `now`, the app's clock in + /// seconds since the Unix epoch, as in the pieces below + GithubList { repository: Option, section: Box, now: u64 }, + /// A `github_overview_read` overview's header, above the detail's tabs + GithubHeader { overview: Box, now: u64 }, + /// Its Overview tab + GithubOverview { overview: Box, now: u64 }, + /// A `github_conversation_read` frame's entries, `opened_by_you` from the overview + GithubConversation { + entries: Vec, + now: u64, + #[serde(default)] + opened_by_you: bool, + }, + /// An `open_review_shown` review as the guide, with `reading` from the same frame. The app + /// sends the review without its hunks' lines, which the guide doesn't show + ReviewGuide { + review: Box, + #[serde(default)] + reading: Vec, + #[serde(default)] + walked: Vec, + }, + /// One chapter opened. Args: `files`, only the files it names, holding only its hunks + ReviewChapter { + chapter: Box, + files: Vec, + place: review::Place, + reading: Option, + /// The open session's comments; the chapter shows the ones on it + #[serde(default)] + findings: Vec, + }, +} + +/// A content block as the wire carries it, where only text is read. The app sends any other block +/// as just its type, so a photo's bytes don't make the round trip. +#[derive(Debug, serde::Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub(crate) enum WireBlock { + /// Text + Text(String), + /// An image, counted + Image, + /// Anything else + #[serde(other)] + Other, +} + +/// The pieces' HTML, in the order they were asked for. +#[derive(Debug, serde::Serialize)] +pub(crate) struct Rendered { + pub(crate) html: Vec, +} + +/// `piece` as the app's HTML. +pub(crate) fn render(renderer: &dyn Renderer, piece: &Piece) -> String { + match piece { + // what the agent wrote for Luxe to read (a remediation report, a draft) isn't the reader's + Piece::Answer { text } => renderer.markdown(&briefs::for_the_reader(text), Voice::Answer), + Piece::Reasoning { text } => renderer.markdown(text, Voice::Reasoning), + Piece::User { content } => user_message(content) + &images_attached(renderer, content), + Piece::Tool { name } => escape(&renderer.tool_glyph(name)), + Piece::Status(facts) => renderer.status(facts).iter().map(status_segment).collect(), + Piece::Plan { todos } => workspace::plan(renderer, todos), + Piece::Changes { changes } => workspace::changes(renderer, changes), + Piece::Diff { diff } => diff::file(renderer, diff), + Piece::DiffFailed { error } => diff::failed(error), + Piece::File { file } => file::file(renderer, file), + Piece::FileFailed { error } => file::failed(error), + Piece::Tree { rows, changes } => tree::tree(renderer, rows, changes.as_deref()), + Piece::ProjectName { name, branch, dirty } => { + tree::project_name(renderer, name, branch.as_deref(), *dirty) + } + Piece::ModeName { mode } => mode_name(renderer, mode), + Piece::GithubList { .. } + | Piece::GithubHeader { .. } + | Piece::GithubOverview { .. } + | Piece::GithubConversation { .. } => github_piece(renderer, piece), + Piece::ReviewGuide { review, reading, walked } => { + review::guide(renderer, review, reading, walked) + } + Piece::ReviewChapter { chapter, files, place, reading, findings } => { + review::chapter(renderer, chapter, files, place, reading.as_ref(), findings) + } + } +} + +fn github_piece(renderer: &dyn Renderer, piece: &Piece) -> String { + let cx = |now: &u64| github::Context::new(renderer, *now); + match piece { + Piece::GithubList { repository, section, now } => { + github::list(&cx(now), repository.as_deref(), section) + } + Piece::GithubHeader { overview, now } => github::header(&cx(now), overview), + Piece::GithubOverview { overview, now } => github::overview(&cx(now), overview), + Piece::GithubConversation { entries, now, opened_by_you } => { + github::conversation(&cx(now), entries, *opened_by_you) + } + _ => String::new(), + } +} + +/// `mode` behind its mark, or alone from a renderer without one. +fn mode_name(renderer: &dyn Renderer, mode: &str) -> String { + let mark = renderer.mode_mark(mode); + if mark.is_empty() { + return escape(mode); + } + format!( + "{} {}", + escape(&mark), + escape(mode) + ) +} + +fn status_segment(segment: &StatusSegment) -> String { + let tone = match segment.tone { + StatusTone::Plain => "", + StatusTone::Warning => " tone-warning", + StatusTone::Error => " tone-error", + }; + let glyph = segment.glyph.as_deref().map(|glyph| { + format!("{} ", escape(glyph)) + }); + format!( + "{}{}", + segment.kind, + glyph.unwrap_or_default(), + escape(&segment.label) + ) +} + +/// A user message as the transcript shows it: the reader's words as they wrote them, without the +/// notes that ride along for the model, and each brief as one line. +fn user_message(content: &[WireBlock]) -> String { + let texts = content.iter().map(|block| match block { + WireBlock::Text(text) => Some(text.as_str()), + WireBlock::Image | WireBlock::Other => None, + }); + briefs::readers_texts(texts).iter().map(|(_, text)| user_block(text)).collect() +} + +/// The line the TUI puts under a message that carried images. +fn images_attached(renderer: &dyn Renderer, content: &[WireBlock]) -> String { + let count = content.iter().filter(|block| matches!(block, WireBlock::Image)).count(); + if count == 0 { + return String::new(); + } + let glyph = renderer.image_glyph(); + let glyph = if glyph.is_empty() { glyph } else { format!("{} ", escape(&glyph)) }; + format!("

{glyph}{count} image(s) attached

") +} + +/// One block of a user message. A question from a review is the reader's own words, so it shows +/// what they asked under where they asked it. +fn user_block(text: &str) -> String { + let asked = briefs::review_questions(text); + if !asked.is_empty() { + return asked.iter().map(asked_in_review).collect(); + } + match briefs::label(text) { + Some(label) => format!("

{}

", escape(label)), + None => format!("

{}

", escape(text)), + } +} + +fn asked_in_review(asked: &briefs::ReviewQuestion) -> String { + format!( + "

Asked in review \u{b7} {}\n{}

", + escape(&asked.location), + escape(&asked.question) + ) +} + +/// `text` with everything that means something in HTML escaped. +pub(crate) fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for character in text.chars() { + match character { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(character), + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/diff.rs b/crates/luxe-remote/src/render/diff.rs new file mode 100644 index 0000000..6a3de35 --- /dev/null +++ b/crates/luxe-remote/src/render/diff.rs @@ -0,0 +1,93 @@ +//! One file's diff, as the app shows it when a changed file is tapped. +//! +//! Unified, since a phone has no room for two columns, with each line's numbers, its sign and its +//! code highlighted the way the TUI's diff views highlight it. The row colors are the theme's diff +//! tints, applied by the app's stylesheet. + +use super::{escape, Renderer}; +use luxe_core::file_diff::{FileDiff, FileDiffFailure}; +use luxe_core::guided_review::{ReviewFile, ReviewHunk, ReviewLine, ReviewLineKind}; + +/// The whole diff, or a line saying why there are no lines to show. +pub(super) fn file(renderer: &dyn Renderer, diff: &FileDiff) -> String { + let Some(file) = diff.file.as_deref() else { + return note("No change: the file matches the last commit."); + }; + whole(renderer, file) +} + +/// Every hunk of `file`, or a line saying why there are no lines to show. +pub(super) fn whole(renderer: &dyn Renderer, file: &ReviewFile) -> String { + if !file.is_text() { + return note("This change isn't text, so there are no lines to show."); + } + let hunks: String = file.hunks.iter().map(|hunk| hunk_html(renderer, file, hunk)).collect(); + format!("{}{hunks}", opening(file)) +} + +/// A diff block's opening tag, naming the file its lines can be picked in: the new side's path, +/// since a pick points at the file as it is now. A deleted file has nothing to point at. +pub(super) fn opening(file: &ReviewFile) -> String { + match file.new_path.as_deref() { + Some(path) => { + format!("
", escape(&path.display().to_string())) + } + None => "
".to_owned(), + } +} + +/// Why the diff couldn't be captured, in core's words. +pub(super) fn failed(error: &FileDiffFailure) -> String { + note(&escape(&error.to_string())) +} + +/// One hunk under its `@@` line. +pub(super) fn hunk_html(renderer: &dyn Renderer, file: &ReviewFile, hunk: &ReviewHunk) -> String { + let (old, new) = (hunk.old_range, hunk.new_range); + let heading = hunk.heading.as_deref().map(|heading| format!(" {}", escape(heading))); + let mut out = format!( + "

@@ -{},{} +{},{} @@{}

", + old.start, + old.count, + new.start, + new.count, + heading.unwrap_or_default() + ); + for line in &hunk.lines { + out.push_str(&line_html(renderer, file.language.as_deref(), line)); + } + out + "
" +} + +fn line_html(renderer: &dyn Renderer, language: Option<&str>, line: &ReviewLine) -> String { + let (kind, sign) = match line.kind { + ReviewLineKind::Context => ("context", " "), + ReviewLineKind::Deletion => ("deletion", "-"), + ReviewLineKind::Addition => ("addition", "+"), + // a note about the file, not a line of it, so it isn't code either + ReviewLineKind::NoNewlineMarker => { + return format!("

{}

", escape(&line.text)); + } + }; + // only a line the file still has can be picked; a deleted one has no number to point at + let picks = line.new_line.map(|line| format!(" data-line=\"{line}\"")).unwrap_or_default(); + format!( + "

{}{}\ + {sign}{}

", + number(line.old_line), + number(line.new_line), + renderer.code_line(&line.text, language) + ) +} + +fn number(line: Option) -> String { + line.map(|line| line.to_string()).unwrap_or_default() +} + +/// A line about the file rather than of it; `words` must already be escaped. +pub(super) fn note(words: &str) -> String { + format!("

{words}

") +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/diff/tests.rs b/crates/luxe-remote/src/render/diff/tests.rs new file mode 100644 index 0000000..f010adb --- /dev/null +++ b/crates/luxe-remote/src/render/diff/tests.rs @@ -0,0 +1,107 @@ +use super::{failed, file}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; +use luxe_core::file_diff::FileDiff; +use luxe_core::file_diff::FileDiffFailure; + +/// Code that shows the language it was highlighted for, escaped. +struct Bracketed; + +impl Renderer for Bracketed { + fn markdown(&self, text: &str, _voice: Voice) -> String { + escape(text) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn code_line(&self, text: &str, language: Option<&str>) -> String { + format!("[{}:{}]", language.unwrap_or("-"), escape(text)) + } +} + +/// A `file_diff_loaded` frame's `diff`, copied from a live session. +const ADDED: &str = r#"{"path": "notes.txt", "file": {"id": "file:bebf0714d086bce43fab95f77103f6ec03bf140a484e7bc0eabaad1e0fc6c2fa", "old_path": null, "new_path": "notes.txt", "status": "added", "language": "txt", "additions": 1, "deletions": 0, "hunks": [{"id": "hunk:a6cc64dc21d9131afb5ce63a2d7f2eec2a826f3660d3f0d4b1d43295fa97babd", "old_range": {"start": 0, "count": 0}, "new_range": {"start": 1, "count": 1}, "heading": null, "symbol": null, "lines": [{"old_line": null, "new_line": 1, "kind": "addition", "text": "hello"}], "noise": "semantic"}], "binary": false, "generated": false, "non_text": null}, "untracked": false}"#; + +/// One line of each kind, for a hunk built on [`ADDED`]. +const EVERY_KIND: &str = r#"[{"old_line": 4, "new_line": 4, "kind": "context", "text": "fn a() {"}, {"old_line": 5, "new_line": null, "kind": "deletion", "text": " x < y"}, {"old_line": null, "new_line": 5, "kind": "addition", "text": " x > y"}, {"old_line": null, "new_line": null, "kind": "no_newline_marker", "text": "\\ No newline at end of file"}]"#; + +fn diff(json: &str) -> FileDiff { + serde_json::from_str(json).expect("a file diff as core sends it") +} + +/// The break this catches: the hunk's range, a line's numbers, sign or kind wrong, its code not +/// highlighted for the file's language, or the block and the line not saying what a pick of it +/// points at. +#[test] +fn an_added_file_shows_its_line() { + let expected = "
\ +

@@ -0,0 +1,1 @@

\ + 1+\ + [txt:hello]

"; + assert_eq!(file(&Bracketed, &diff(ADDED)), expected); +} + +/// The break this catches: a deletion signed or numbered as an addition or as context, a hunk's +/// heading dropped or unescaped, or the no-newline note drawn as a line of code. +#[test] +fn each_kind_of_line_keeps_its_sign_and_numbers() { + let modified = ADDED.replace(r#""heading": null"#, r#""heading": "impl ""#).replace( + r#"[{"old_line": null, "new_line": 1, "kind": "addition", "text": "hello"}]"#, + EVERY_KIND, + ); + let html = file(&Bracketed, &diff(&modified)); + // a deleted line names no line to pick: the file doesn't have it any more + let row = |kind: &str, old: &str, new: &str, sign: &str, code: &str| { + let picks = if new.is_empty() { String::new() } else { format!(" data-line=\"{new}\"") }; + format!( + "

{old}{new}{sign}[txt:{code}]

" + ) + }; + let expected = format!( + "

@@ -0,0 +1,1 @@ impl <A>

{}{}{}\ +

\\ No newline at end of file

", + row("context", "4", "4", " ", "fn a() {"), + row("deletion", "5", "", "-", " x < y"), + row("addition", "", "5", "+", " x > y"), + ); + assert!(html.contains(&expected), "{html}"); +} + +/// A deleted file's block names no file to pick in, and a path is text in its attribute. +/// +/// The break this catches: Ask offered on a file that's gone (the old path points at nothing), or a +/// path with a quote closing the attribute early. +#[test] +fn only_a_file_that_is_still_there_can_be_picked_in() { + let deleted = ADDED.replace( + r#""old_path": null, "new_path": "notes.txt""#, + r#""old_path": "notes.txt", "new_path": null"#, + ); + assert!(file(&Bracketed, &diff(&deleted)).starts_with("
"), "{html}"); +} + +/// The break this catches: a failure shown as nothing, or Git's words written into the page +/// unescaped. +#[test] +fn a_failure_says_why_in_cores_words() { + let git: FileDiffFailure = + serde_json::from_str(r#"{"git": "bad "}"#).expect("core's shape"); + let expected = "

git could not describe this file: bad <ref>

"; + assert_eq!(failed(&git), expected); +} + +/// The break this catches: a file that matches its base, or a binary one, drawn as an empty diff +/// with nothing saying why. +#[test] +fn a_diff_with_no_lines_says_why() { + let unchanged = r#"{"path": "notes.txt", "file": null, "untracked": false}"#; + assert!(file(&Bracketed, &diff(unchanged)).contains("matches the last commit")); + let binary = ADDED.replace(r#""binary": false"#, r#""binary": true"#); + assert!(file(&Bracketed, &diff(&binary)).contains("isn't text")); +} diff --git a/crates/luxe-remote/src/render/file.rs b/crates/luxe-remote/src/render/file.rs new file mode 100644 index 0000000..c170e68 --- /dev/null +++ b/crates/luxe-remote/src/render/file.rs @@ -0,0 +1,61 @@ +//! One project file, as the app's Files tab shows it. +//! +//! Each line numbered and highlighted the way a diff's lines are, so a file reads like the context +//! lines of its diff, and like those it keeps its indentation and scrolls sideways. + +use super::diff::note; +use super::{escape, Renderer}; +use luxe_core::project_files::{ProjectFile, ProjectFileFailure}; +use std::path::Path; + +/// The file's lines, or a line saying why there are none, with a note when the text stops short. +pub(super) fn file(renderer: &dyn Renderer, file: &ProjectFile) -> String { + if file.binary { + return note("Binary file"); + } + if file.text.is_empty() { + return note("Empty file"); + } + // core labels a diff's language by its extension, so a file's is the same + let language = Path::new(&file.path).extension().and_then(|extension| extension.to_str()); + let lines: String = file + .text + .lines() + .enumerate() + .map(|(index, line)| line_html(renderer, language, index + 1, line)) + .collect(); + let path = escape(&file.path); + format!("
{lines}
{}", cut_short(file)) +} + +/// Why the file couldn't be read, in core's words. +pub(super) fn failed(error: &ProjectFileFailure) -> String { + note(&escape(&error.to_string())) +} + +fn line_html(renderer: &dyn Renderer, language: Option<&str>, number: usize, text: &str) -> String { + format!( + "

{number}{}

", + renderer.code_line(text, language) + ) +} + +fn cut_short(file: &ProjectFile) -> String { + if !file.truncated { + return String::new(); + } + note(&format!("First {} of {}", size(file.text.len() as u64), size(file.bytes))) +} + +/// Bytes the way a person reads them: `900 B`, `12 KB`, `3.4 MB`. +fn size(bytes: u64) -> String { + const KB: u64 = 1024; + match bytes { + 0..KB => format!("{bytes} B"), + KB..1_048_576 => format!("{} KB", bytes / KB), + _ => format!("{:.1} MB", bytes as f64 / 1_048_576.0), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/file/tests.rs b/crates/luxe-remote/src/render/file/tests.rs new file mode 100644 index 0000000..a697098 --- /dev/null +++ b/crates/luxe-remote/src/render/file/tests.rs @@ -0,0 +1,93 @@ +use super::{failed, file, size}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; +use luxe_core::project_files::{ProjectFile, ProjectFileFailure}; + +/// Code that shows the language it was highlighted for, escaped. +struct Bracketed; + +impl Renderer for Bracketed { + fn markdown(&self, text: &str, _voice: Voice) -> String { + escape(text) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn code_line(&self, text: &str, language: Option<&str>) -> String { + format!("[{}:{}]", language.unwrap_or("-"), escape(text)) + } +} + +/// A `project_file_read` frame's `file`, copied from `luxe --rpc`. +const READ: &str = r#"{"path":"a.rs","text":"fn main() {\n\tprintln!(\"\");\n}\n","bytes":33,"truncated":false,"binary":false}"#; + +fn read(edit: impl FnOnce(&mut ProjectFile)) -> ProjectFile { + let mut file = serde_json::from_str(READ).expect("a project file as core sends it"); + edit(&mut file); + file +} + +/// The break this catches: lines numbered from zero or out of order, a line dropped, the trailing +/// newline drawn as an empty last line, the code not highlighted for the file's extension, or a +/// line not saying which file and line a pick of it points at. +#[test] +fn a_file_shows_each_line_numbered_and_highlighted() { + let expected = "
\ +

1[rs:fn main() {]

\ +

2\ + [rs:\tprintln!("<hi>");]

\ +

3[rs:}]

"; + assert_eq!(file(&Bracketed, &read(|_| ())), expected); +} + +/// The break this catches: a file with no extension highlighted as some language anyway. +#[test] +fn a_file_without_an_extension_is_highlighted_as_nothing() { + let html = file(&Bracketed, &read(|file| file.path = "Makefile".into())); + assert!(html.contains("[-:fn main() {]"), "{html}"); +} + +/// The break this catches: a cut-short file shown as if it were whole, or the note's sizes swapped. +#[test] +fn a_cut_short_file_says_how_much_is_shown() { + let html = file( + &Bracketed, + &read(|file| { + file.truncated = true; + file.bytes = 3 * 1_048_576; + }), + ); + assert!(html.ends_with("

First 33 B of 3.0 MB

"), "{html}"); +} + +/// The break this catches: a binary file's empty text drawn as an empty file, or the reverse. +#[test] +fn a_binary_file_and_an_empty_one_each_say_so() { + let binary = read(|file| { + file.binary = true; + file.text.clear(); + }); + let empty = read(|file| file.text.clear()); + assert_eq!(file(&Bracketed, &binary), "

Binary file

"); + assert_eq!(file(&Bracketed, &empty), "

Empty file

"); +} + +/// The break this catches: a failure's reason left out, or a path in it not escaped. +#[test] +fn a_failure_says_why_in_cores_words() { + let not_found: ProjectFileFailure = serde_json::from_str(r#""not_found""#).expect("a failure"); + let unreadable = ProjectFileFailure::Unreadable("".into()); + assert_eq!(failed(¬_found), "

nothing is there any more

"); + assert!(failed(&unreadable).contains("<denied>")); +} + +/// The break this catches: a boundary in the wrong unit, so 1024 bytes reads `1024 B`. +#[test] +fn sizes_read_in_the_unit_a_person_expects() { + assert_eq!(size(1023), "1023 B"); + assert_eq!(size(1024), "1 KB"); + assert_eq!(size(1_048_575), "1023 KB"); + assert_eq!(size(1_048_576), "1.0 MB"); +} diff --git a/crates/luxe-remote/src/render/github.rs b/crates/luxe-remote/src/render/github.rs new file mode 100644 index 0000000..29f0029 --- /dev/null +++ b/crates/luxe-remote/src/render/github.rs @@ -0,0 +1,133 @@ +//! GitHub — `/github`'s list, overview and conversation, drawn as the TUI draws them. +//! +//! The engine fetched everything and the app hands it back as pieces, so the bridge stays +//! stateless. Every fact is a word beside its mark, as in the TUI, so a missing glyph loses polish +//! and nothing else. Titles and bodies are strangers' words: sanitized by core, reduced from +//! GitHub's HTML by the renderer, and rendered escaped. Nothing here offers a write: a joined +//! session runs with GitHub writes off. + +mod conversation; +mod list; +mod overview; + +pub(super) use conversation::conversation; +pub(super) use list::list; +pub(super) use overview::{header, overview}; + +use luxe_core::github::PullRequestState; + +use super::{escape, Renderer, Voice}; + +/// Characters of a body rendered before it's cut, as the TUI's detail cuts it. +const BODY_MAX_CHARS: usize = 20_000; + +/// Characters of a title shown, as the TUI's header shows it. +const TITLE_MAX_CHARS: usize = 300; + +/// The separator between facts on a line. +const DOT: &str = " \u{b7} "; + +/// The marks `/github` draws, as plain text. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GithubMarks { + /// Before a pull request's row + pub pull_request: String, + /// Before an issue's row + pub issue: String, + /// Passed or approved + pub yes: String, + /// Failed or refused + pub no: String, + /// Running or waiting on someone + pub waiting: String, + /// Before a count of lines left out + pub elision: String, +} + +/// What every GitHub view draws with: the renderer, its marks, and the app's clock, which the app +/// sends so a piece renders the same whenever it's asked. +pub(super) struct Context<'a> { + renderer: &'a dyn Renderer, + marks: GithubMarks, + now: u64, +} + +impl<'a> Context<'a> { + pub(super) fn new(renderer: &'a dyn Renderer, now: u64) -> Self { + Self { renderer, marks: renderer.github_marks(), now } + } + + /// How long ago `at` was, in the TUI's words, escaped; empty from a renderer without them. + fn ago(&self, at: u64) -> String { + escape(&self.renderer.ago(at, self.now)) + } + + /// A stranger's markdown as HTML: sanitized, its HTML reduced, rendered escaped. + fn body(&self, text: &str) -> String { + let clean = luxe_core::github::untrusted(text, BODY_MAX_CHARS); + let readable = self.renderer.github_readable(&clean); + if readable.trim().is_empty() { + return String::new(); + } + self.renderer.markdown(&readable, Voice::Answer) + } +} + +/// A title, sanitized and escaped. +fn title(text: &str) -> String { + escape(&luxe_core::github::untrusted(text, TITLE_MAX_CHARS)) +} + +/// The state's word and the class that colors it, shared by a row's mark and the state chip. +fn state_word(state: PullRequestState, draft: bool, issue: bool) -> (&'static str, &'static str) { + match (state, draft) { + (PullRequestState::Open, true) => ("draft", "hue-muted"), + (PullRequestState::Open, false) => ("open", "hue-success"), + (PullRequestState::Merged, _) => ("merged", "hue-secondary"), + (PullRequestState::Closed, _) if issue => ("closed", "hue-secondary"), + (PullRequestState::Closed, _) => ("closed", "hue-error"), + } +} + +/// `mara`, or `dependabot bot` with the word quiet: a bot is named as one. `ghost` for a +/// deleted account. +fn login(login: &str, bot: bool) -> String { + let login = login.trim_end_matches("[bot]"); + match (login.is_empty(), bot) { + (true, _) => "ghost".to_owned(), + (false, true) => format!( + "{} bot", + escape(login) + ), + (false, false) => format!("{}", escape(login)), + } +} + +/// `+50 −12` in the diff colors. +fn counts(additions: u64, deletions: u64) -> String { + format!( + "+{additions} \u{2212}{deletions}" + ) +} + +/// `words` after `glyph` in `class`, the glyph left out when the renderer has none. +fn marked(glyph: &str, words: &str, class: &str) -> String { + let lead = if glyph.is_empty() { String::new() } else { format!("{} ", escape(glyph)) }; + format!("{lead}{}", escape(words)) +} + +/// `count` with its thousands set apart: `3,250`. +fn grouped(count: u64) -> String { + let digits = count.to_string(); + let mut out = String::new(); + for (index, digit) in digits.chars().enumerate() { + if index > 0 && (digits.len() - index).is_multiple_of(3) { + out.push(','); + } + out.push(digit); + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/github/conversation.rs b/crates/luxe-remote/src/render/github/conversation.rs new file mode 100644 index 0000000..567db57 --- /dev/null +++ b/crates/luxe-remote/src/render/github/conversation.rs @@ -0,0 +1,203 @@ +//! The Conversation: everything said, oldest first, each entry a card of its own. +//! +//! The cards are the TUI's: the tone says what kind of thing was said (an open thread in the info +//! color, changes requested in the error color, a bot quieter than a person), a long comment folds +//! to its first lines, and a thread shows its last word until it's opened. + +use luxe_core::github::overview::{by_bot_login, ConversationEntry, Verdict}; +use luxe_core::github::{rfc3339_seconds, ConversationComment, ReviewThread, ThreadComment}; + +use super::{Context, BODY_MAX_CHARS, DOT}; +use crate::render::escape; + +/// Lines of a comment's source past which it folds. Agents write long, and a timeline of whole +/// comments is a wall; a fold that hides one line costs the line it saves. +const FOLD_LINES: usize = 7; + +/// Characters of a thread's last word shown while it's folded, as the TUI shows it. +const LAST_WORD_CHARS: usize = 400; + +/// The conversation's cards. `opened_by_you` names the description as yours when you wrote it. +pub(in crate::render) fn conversation( + cx: &Context, + entries: &[ConversationEntry], + opened_by_you: bool, +) -> String { + let cards: String = entries.iter().map(|entry| card(cx, entry, opened_by_you)).collect(); + format!("
{cards}
") +} + +fn card(cx: &Context, entry: &ConversationEntry, opened_by_you: bool) -> String { + match entry { + ConversationEntry::Opening { author, body, at } => { + let title = speaker(&author.login, author.bot, opened_by_you) + + &said("opened", "hue-muted") + + &said(&cx.ago(*at), "hue-muted"); + said_card(cx, if author.bot { "quiet" } else { "person" }, &title, body) + } + ConversationEntry::Comment(comment) => { + let title = speaker(&comment.author, comment.bot, comment.mine) + + &said("commented", "hue-muted") + + &when(cx, &comment.created_at); + said_card(cx, if comment.bot { "quiet" } else { "person" }, &title, &comment.body) + } + ConversationEntry::Review { comment, verdict, line_comments } => { + review_card(cx, comment, *verdict, *line_comments) + } + ConversationEntry::Thread(thread) => thread_card(cx, thread), + } +} + +/// `@mara` naming a speaker: yours in the accent, a bot's quiet and named as one, anyone else's +/// in the color a reviewer wears. +fn speaker(login: &str, bot: bool, mine: bool) -> String { + let login = login.trim_end_matches("[bot]"); + if login.is_empty() { + return "@ghost".to_owned(); + } + let name = escape(&format!("@{login}")); + match (mine, bot) { + (true, _) => format!("{name}"), + (false, true) => { + format!("{name} bot") + } + (false, false) => format!("{name}"), + } +} + +/// ` · words` in `class`. +fn said(words: &str, class: &str) -> String { + format!("{DOT}{}", escape(words)) +} + +/// ` · 3h ago` from GitHub's timestamp, or nothing when it can't be read. +fn when(cx: &Context, created_at: &str) -> String { + rfc3339_seconds(created_at).map(|at| said(&cx.ago(at), "hue-muted")).unwrap_or_default() +} + +/// A review's summary card, toned by its verdict unless a bot gave it. +fn review_card( + cx: &Context, + comment: &ConversationComment, + verdict: Verdict, + lines: usize, +) -> String { + let (words, class, tone) = match verdict { + Verdict::Approved => ("approved", "hue-success", "approved"), + Verdict::ChangesRequested => ("requested changes", "hue-error", "changes"), + Verdict::Commented => ("reviewed", "hue-muted", "person"), + Verdict::Dismissed => ("review dismissed", "hue-muted", "person"), + Verdict::Requested => ("asked to review", "hue-warning", "person"), + }; + let title = speaker(&comment.author, comment.bot, comment.mine) + + &said(words, class) + + &line_comments(lines) + + &when(cx, &comment.created_at); + said_card(cx, if comment.bot { "quiet" } else { tone }, &title, &comment.body) +} + +fn line_comments(count: usize) -> String { + match count { + 0 => String::new(), + 1 => said("1 line comment", "hue-muted"), + n => said(&format!("{n} line comments"), "hue-muted"), + } +} + +/// A card for something said: its title, then its body, folded when it runs long. +fn said_card(cx: &Context, tone: &str, title: &str, body: &str) -> String { + let rendered = cx.body(body); + let fold = folds(body); + let (class, unfold) = match fold { + true => (" folded", unfold_button(cx)), + false => ("", String::new()), + }; + format!( + "

{title}

\ +
{rendered}
{unfold}
" + ) +} + +/// Whether a body says more lines than a card shows before it folds. +fn folds(body: &str) -> bool { + let clean = luxe_core::github::untrusted(body, BODY_MAX_CHARS); + clean.lines().filter(|line| !line.trim().is_empty()).count() > FOLD_LINES +} + +fn unfold_button(cx: &Context) -> String { + let lead = match cx.marks.elision.is_empty() { + true => String::new(), + false => format!("{} ", escape(&cx.marks.elision)), + }; + format!("") +} + +/// A review thread: who started it, where, whether it's settled, then its last word folded or +/// every comment open, as a native disclosure so it opens without the app. +fn thread_card(cx: &Context, thread: &ReviewThread) -> String { + let first = thread.comments.first(); + let starter = first.map(|comment| comment.author.as_str()).unwrap_or_default(); + let (state, class, tone) = match (thread.resolved, thread.outdated) { + (true, _) => ("resolved", "dim", "person"), + (false, true) => ("outdated", "dim", "person"), + (false, false) => ("unresolved", "hue-info", "unresolved"), + }; + let title = speaker(starter, first.is_some_and(by_bot_login), false) + + &format!("{DOT}{}", escape(&place(thread))) + + &said(state, class) + + &replies(thread.total_comments); + let comments: String = + thread.comments.iter().map(|comment| thread_comment(cx, comment)).collect(); + format!( + "
\ + {title}{}{comments}
", + last_word(thread) + ) +} + +/// `src/api/webhook.rs:42`, the path cut to its last two parts when it's long. +fn place(thread: &ReviewThread) -> String { + let parts: Vec<&str> = thread.path.split('/').collect(); + let path = match parts.len() { + 0..=3 => thread.path.clone(), + n => format!("\u{2026}/{}", parts[n - 2..].join("/")), + }; + match thread.line { + Some(line) => format!("{path}:{line}"), + None => path, + } +} + +fn replies(total: usize) -> String { + match total.saturating_sub(1) { + 0 => String::new(), + 1 => said("1 reply", "hue-muted"), + n => said(&format!("{n} replies"), "hue-muted"), + } +} + +/// What a folded thread shows: the last comment, on one line. +fn last_word(thread: &ReviewThread) -> String { + let Some(comment) = thread.comments.last() else { + return String::new(); + }; + let words = luxe_core::github::untrusted(&comment.body, LAST_WORD_CHARS); + let words = words.split_whitespace().collect::>().join(" "); + let who = format!("@{}: ", comment.author.trim_end_matches("[bot]")); + format!( + "{}{}", + escape(&who), + escape(&words) + ) +} + +/// One comment in an opened thread: who and when, then what they said. +fn thread_comment(cx: &Context, comment: &ThreadComment) -> String { + let head = + speaker(&comment.author, by_bot_login(comment), false) + &when(cx, &comment.created_at); + format!( + "

{head}

{}
", + cx.body(&comment.body) + ) +} diff --git a/crates/luxe-remote/src/render/github/list.rs b/crates/luxe-remote/src/render/github/list.rs new file mode 100644 index 0000000..1ff6870 --- /dev/null +++ b/crates/luxe-remote/src/render/github/list.rs @@ -0,0 +1,146 @@ +//! The list side of `/github`: how many a tab's search found, then each pull request or issue on +//! the TUI's two lines. +//! +//! Line one is what it is: a state mark, the number, the title, how long ago it changed. Line two +//! is where it stands, quiet: who opened it, how big it is, and on the right its status in words. +//! A row is a button whose data says which item to open; the app owns the tap. + +use luxe_core::github::overview::RowFacts; +use luxe_core::github::{ + rfc3339_seconds, ListItem, ListedSection, PullRequestState, ReviewDecision, +}; + +use super::{counts, grouped, login, marked, state_word, title, Context, DOT}; +use crate::render::escape; + +/// A tab's rows, or why it has none. `repository` is the checkout's, which a row from elsewhere +/// names its own beside. +pub(in crate::render) fn list( + cx: &Context, + repository: Option<&str>, + section: &ListedSection, +) -> String { + if let Some(error) = §ion.error { + return format!("

{}

", escape(error)); + } + if section.items.is_empty() { + return "

Nothing matches this search

".to_owned(); + } + let rows: String = section.items.iter().map(|item| row(cx, item, repository)).collect(); + format!("

{}

{rows}
", shown(section)) +} + +/// How many are here of how many there are. The rest are GitHub's to show: paging needs the +/// section's query, which the listing doesn't carry. +fn shown(section: &ListedSection) -> String { + let loaded = section.items.len() as u64; + match section.total { + Some(total) if total > loaded => format!("{} of {}", grouped(loaded), grouped(total)), + _ => format!("{} shown", grouped(loaded)), + } +} + +fn row(cx: &Context, item: &ListItem, repository: Option<&str>) -> String { + let age = rfc3339_seconds(&item.updated_at).map(|at| cx.ago(at)).unwrap_or_default(); + format!( + "", + item.number, + item.pull_request, + escape(&item.repository), + escape(&item.url), + row_mark(cx, item), + item.number, + title(&item.title), + age.trim_end_matches(" ago"), + second_line(cx, item, repository.is_some_and(|here| here != item.repository)) + ) +} + +/// A pull request's or an issue's mark, in its state's color. +fn row_mark(cx: &Context, item: &ListItem) -> String { + let issue = !item.pull_request; + let glyph = if issue { &cx.marks.issue } else { &cx.marks.pull_request }; + if glyph.is_empty() { + return String::new(); + } + let (_, class) = state_word(item.state, item.draft, issue); + format!("{}", escape(glyph)) +} + +/// Who opened it, from where when it's another repository, and how big it is, then its status. +fn second_line(cx: &Context, item: &ListItem, elsewhere: bool) -> String { + let facts = item.facts.as_ref(); + let mut left = login(&item.author, facts.is_some_and(|facts| facts.author_bot)); + if elsewhere { + left += &format!("{DOT}{}", escape(&item.repository)); + } + if let Some(facts) = facts { + left += &size(facts, item.pull_request); + } + format!( + "{left}\ + {}", + status(cx, item, facts).join(DOT) + ) +} + +/// A pull request's diff counts, or an issue's labels, after a separator; nothing for an issue +/// without labels. +fn size(facts: &RowFacts, pull_request: bool) -> String { + if pull_request { + return format!("{DOT}{}", counts(facts.additions, facts.deletions)); + } + if facts.labels.is_empty() { + return String::new(); + } + let names: Vec<&str> = facts.labels.iter().map(|label| label.name.as_str()).collect(); + format!("{DOT}{}", escape(&names.join(", "))) +} + +/// Where it stands, in words: `✗ 1 failing · changes requested`. +fn status(cx: &Context, item: &ListItem, facts: Option<&RowFacts>) -> Vec { + let mut parts = Vec::new(); + let (word, class) = state_word(item.state, item.draft, !item.pull_request); + if item.draft || item.state != PullRequestState::Open { + parts.push(marked("", word, class)); + } + let Some(facts) = facts else { + return parts; + }; + match item.pull_request { + true => parts.extend(pull_request_status(cx, facts)), + false => parts.extend(issue_status(cx, facts)), + } + parts +} + +fn issue_status(cx: &Context, facts: &RowFacts) -> Option { + if let Some(number) = facts.linked_pull_request { + return Some(marked(&cx.marks.waiting, &format!("PR #{number}"), "hue-warning")); + } + let noun = if facts.comments == 1 { "comment" } else { "comments" }; + (facts.comments > 0).then(|| marked("", &format!("{} {noun}", facts.comments), "hue-muted")) +} + +fn pull_request_status(cx: &Context, facts: &RowFacts) -> Vec { + let checks = &facts.checks; + let mut parts = Vec::new(); + if checks.failed > 0 { + parts.push(marked(&cx.marks.no, &format!("{} failing", checks.failed), "hue-error")); + } else if checks.pending > 0 { + parts.push(marked(&cx.marks.waiting, "running", "hue-warning")); + } else if checks.passed > 0 { + parts.push(marked(&cx.marks.yes, "checks", "hue-success")); + } + let review = match facts.review_decision { + Some(ReviewDecision::ChangesRequested) => Some(("changes requested", "hue-error")), + Some(ReviewDecision::Approved) => Some(("approved", "hue-success")), + Some(ReviewDecision::ReviewRequired) => Some(("needs review", "hue-muted")), + None => None, + }; + parts.extend(review.map(|(word, class)| marked("", word, class))); + parts +} diff --git a/crates/luxe-remote/src/render/github/overview.rs b/crates/luxe-remote/src/render/github/overview.rs new file mode 100644 index 0000000..e39371a --- /dev/null +++ b/crates/luxe-remote/src/render/github/overview.rs @@ -0,0 +1,279 @@ +//! The detail's header and its Overview: what stands between a pull request and merged, or who +//! is on an issue, then the start of the description. +//! +//! The merge checks are core's (`merge_checks`), so the phone and the TUI agree on what blocks a +//! merge. Their actions are GitHub writes or agent work, which a joined session doesn't take, so a +//! row shows its evidence and no key; only "open #N", which reads, is offered. + +use luxe_core::github::overview::{ + blocking, merge_checks, CheckAction, CheckMark, IssueOverview, Label, LinkedPullRequest, + MergeCheck, Overview, PullRequestOverview, Reviewer, ReviewerKind, Verdict, +}; +use luxe_core::github::{Author, PullRequestState}; + +use super::{counts, login, state_word, title, Context, BODY_MAX_CHARS, DOT}; +use crate::render::escape; + +/// Lines of the description the Overview quotes before pointing at Conversation. +const EXCERPT_LINES: usize = 5; + +/// Labels the header shows, as the TUI's does. +const HEADER_LABELS: usize = 4; + +/// `#182 Title`, then who, where and how big, then the state and labels as chips. +pub(in crate::render) fn header(cx: &Context, overview: &Overview) -> String { + let (head, meta) = match overview { + Overview::PullRequest(pr) => (heading_facts(pr), pull_request_meta(pr)), + Overview::Issue(issue) => (issue_facts(issue), String::new()), + }; + format!( + "

#{} {}

\ +

{}{meta}{DOT}{}

\ +

{}

", + overview.number(), + title(head.title), + login(&head.author.login, head.author.bot), + cx.ago(head.updated_at), + chips(&head) + ) +} + +/// What the header says about either kind. +struct HeadFacts<'a> { + title: &'a str, + author: &'a Author, + state: PullRequestState, + draft: bool, + issue: bool, + labels: &'a [Label], + updated_at: u64, +} + +fn heading_facts(pr: &PullRequestOverview) -> HeadFacts<'_> { + let (title, author, labels) = (&pr.title, &pr.author, &pr.labels); + HeadFacts { + title, + author, + state: pr.state, + draft: pr.draft, + issue: false, + labels, + updated_at: pr.updated_at, + } +} + +fn issue_facts(issue: &IssueOverview) -> HeadFacts<'_> { + let (title, author, labels) = (&issue.title, &issue.author, &issue.labels); + HeadFacts { + title, + author, + state: issue.state, + draft: false, + issue: true, + labels, + updated_at: issue.updated_at, + } +} + +/// ` · master ← feature · +8 −8 in 4 files`. +fn pull_request_meta(pr: &PullRequestOverview) -> String { + let files = if pr.changed_files == 1 { "file" } else { "files" }; + format!( + "{DOT}{} \u{2190} {}{DOT}{} \ + in {} {files}", + escape(&pr.base_ref), + escape(&pr.head_ref), + counts(pr.additions, pr.deletions), + pr.changed_files + ) +} + +/// The state as a filled chip cut from its own color, then up to four labels on the chip surface. +fn chips(head: &HeadFacts) -> String { + let (word, class) = state_word(head.state, head.draft, head.issue); + let mut out = format!("{word}"); + for label in head.labels.iter().take(HEADER_LABELS) { + let name = escape(&luxe_core::github::untrusted(&label.name, 40)); + out += &format!(" \u{25cf} {name}"); + } + out +} + +/// The Overview's sections, under the header. +pub(in crate::render) fn overview(cx: &Context, overview: &Overview) -> String { + match overview { + Overview::PullRequest(pr) => { + status_section(cx, pr) + &reviewers_section(cx, pr) + &excerpt(cx, &pr.body) + } + Overview::Issue(issue) => issue_section(cx, issue) + &excerpt(cx, &issue.body), + } +} + +/// A section's heading, with a quiet note against the far edge. +fn section_heading(text: &str, note: Option) -> String { + let note = note.map(|note| format!("{}", escape(¬e))); + format!("

{text}{}

", note.unwrap_or_default()) +} + +/// One row: its mark, a label in the label column, then the evidence. +fn check_row(cx: &Context, mark: CheckMark, label: &str, detail: &str) -> String { + let (glyph, class) = match mark { + CheckMark::Pass => (cx.marks.yes.as_str(), "hue-success"), + CheckMark::Fail => (cx.marks.no.as_str(), "hue-error"), + CheckMark::Wait => (cx.marks.waiting.as_str(), "hue-warning"), + CheckMark::Note => ("\u{2013}", "hue-muted"), + }; + format!( + "

{}\ + {}{detail}

", + escape(glyph), + escape(label) + ) +} + +/// The checks between the pull request and merged, blockers first. +fn status_section(cx: &Context, pr: &PullRequestOverview) -> String { + let checks = merge_checks(pr); + if checks.is_empty() { + return String::new(); + } + let note = match blocking(&checks) { + 0 => None, + count => Some(format!("{count} incomplete")), + }; + let rows: String = checks.iter().map(|check| merge_row(cx, check)).collect(); + section_heading("Status", note) + &rows +} + +/// A merge check's row: a failure's evidence in body text, the rest quiet, and a way to the pull +/// request below it in a stack, the one action that only reads. +fn merge_row(cx: &Context, check: &MergeCheck) -> String { + let tone = if check.mark == CheckMark::Fail { "" } else { "hue-muted" }; + let mut detail = format!("{}", escape(&check.detail)); + if let Some(CheckAction::OpenBelow(number)) = check.action { + detail += &format!( + " " + ); + } + check_row(cx, check.mark, check.label, &detail) +} + +/// Each reviewer, with what they said and when. +fn reviewers_section(cx: &Context, pr: &PullRequestOverview) -> String { + if pr.reviewers.is_empty() { + return String::new(); + } + let approved = pr.reviewers.iter().filter(|r| r.verdict == Verdict::Approved).count(); + let note = format!("{approved} of {} approved", pr.reviewers.len()); + let rows: String = pr.reviewers.iter().map(|reviewer| reviewer_row(cx, reviewer)).collect(); + section_heading("Reviewers", Some(note)) + &rows +} + +fn reviewer_row(cx: &Context, reviewer: &Reviewer) -> String { + let (mark, said, class) = match reviewer.verdict { + Verdict::Approved => (CheckMark::Pass, "approved", "hue-success"), + Verdict::ChangesRequested => (CheckMark::Fail, "changes requested", "hue-error"), + Verdict::Commented => (CheckMark::Note, "commented", "hue-muted"), + Verdict::Dismissed => (CheckMark::Note, "dismissed", "hue-muted"), + Verdict::Requested => (CheckMark::Wait, "requested", "hue-warning"), + }; + let kind = match reviewer.kind { + ReviewerKind::Team => " \u{b7} team", + ReviewerKind::Bot => " \u{b7} bot", + ReviewerKind::User => "", + }; + let when = reviewer.at.map(|at| format!(" \u{b7} {}", cx.ago(at))).unwrap_or_default(); + let detail = format!( + "{said}{kind}\ + {when}" + ); + check_row(cx, mark, &reviewer.login, &detail) +} + +/// Who's on an issue, which pull requests close it, and its milestone. +fn issue_section(cx: &Context, issue: &IssueOverview) -> String { + let assignees = match issue.assignees.as_slice() { + [] => "unassigned".to_owned(), + logins => format!("{}", escape(&logins.join(", "))), + }; + let mut rows = check_row(cx, CheckMark::Note, "Assignees", &assignees); + rows += &closing_rows(cx, issue); + if let Some(milestone) = &issue.milestone { + rows += &check_row(cx, CheckMark::Note, "Milestone", &escape(milestone)); + } + section_heading("Status", None) + &rows +} + +/// The pull requests that close the issue when they merge, each a way to open it. +fn closing_rows(cx: &Context, issue: &IssueOverview) -> String { + let closing: Vec<_> = issue.linked.iter().filter(|linked| linked.closes).collect(); + if closing.is_empty() { + let none = "none yet"; + return check_row(cx, CheckMark::Note, "Pull requests", none); + } + let label = |index| if index == 0 { "Pull requests" } else { "" }; + closing + .iter() + .enumerate() + .map(|(index, linked)| closing_row(cx, label(index), linked)) + .collect() +} + +/// Which pull request, how far along, and whose: the question the row answers is whether +/// somebody is already on it. +fn closing_row(cx: &Context, label: &str, linked: &LinkedPullRequest) -> String { + let (word, class) = state_word(linked.state, linked.draft, false); + let mark = match linked.state { + PullRequestState::Open => CheckMark::Wait, + PullRequestState::Merged => CheckMark::Pass, + PullRequestState::Closed => CheckMark::Note, + }; + let detail = format!( + "{DOT}{word}{DOT}{1}", + linked.number, + login(&linked.author, false) + ); + check_row(cx, mark, label, &detail) +} + +/// A heading and the first lines of the description, pointing at Conversation for the rest. +fn excerpt(cx: &Context, body: &str) -> String { + let heading = section_heading("Description", None); + let readable = cx.renderer.github_readable(&luxe_core::github::untrusted(body, BODY_MAX_CHARS)); + let (kept, hidden) = first_lines(&readable, EXCERPT_LINES); + if kept.trim().is_empty() { + return heading + "

No description

"; + } + let rendered = cx.renderer.markdown(&kept, crate::render::Voice::Answer); + let more = match hidden { + 0 => String::new(), + hidden => format!( + "", + escape(&cx.marks.elision) + ), + }; + format!("{heading}
{rendered}
{more}") +} + +/// The first `keep` lines of `text` that say something, with the blank lines between them, and +/// how many lines that say something are left: a paragraph break isn't worth one of the five. +fn first_lines(text: &str, keep: usize) -> (String, usize) { + let mut said = 0; + let mut kept = String::new(); + let mut lines = text.lines(); + for line in lines.by_ref() { + if !line.trim().is_empty() { + if said == keep { + let hidden = 1 + lines.filter(|line| !line.trim().is_empty()).count(); + return (kept, hidden); + } + said += 1; + } + kept += line; + kept.push('\n'); + } + (kept, 0) +} diff --git a/crates/luxe-remote/src/render/github/tests.rs b/crates/luxe-remote/src/render/github/tests.rs new file mode 100644 index 0000000..1ded32b --- /dev/null +++ b/crates/luxe-remote/src/render/github/tests.rs @@ -0,0 +1,47 @@ +use super::{Context, GithubMarks}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; + +mod conversation; +mod list; +mod overview; + +/// The marks as words and ages in seconds, so a test reads which mark and which clock landed +/// where. Bodies come back marked twice, `R:…`, to show they were made readable first. +struct Worded; + +impl Renderer for Worded { + fn markdown(&self, text: &str, _voice: Voice) -> String { + format!("{}", escape(text)) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn github_marks(&self) -> GithubMarks { + let word = |word: &str| word.to_owned(); + GithubMarks { + pull_request: word("PR"), + issue: word("IS"), + yes: word("Y"), + no: word("N"), + waiting: word("W"), + elision: word("…"), + } + } + fn ago(&self, at: u64, now: u64) -> String { + format!("{}s ago", now.saturating_sub(at)) + } + fn github_readable(&self, body: &str) -> String { + match body.trim().is_empty() { + true => body.to_owned(), + false => format!("R:{body}"), + } + } +} + +/// An hour after `at`, by the app's clock. +fn an_hour_after(at: u64) -> Context<'static> { + Context::new(&Worded, at + 3600) +} diff --git a/crates/luxe-remote/src/render/github/tests/conversation.rs b/crates/luxe-remote/src/render/github/tests/conversation.rs new file mode 100644 index 0000000..d1e0529 --- /dev/null +++ b/crates/luxe-remote/src/render/github/tests/conversation.rs @@ -0,0 +1,141 @@ +use super::an_hour_after; +use crate::render::github::conversation; +use luxe_core::github::overview::ConversationEntry; +use serde_json::{json, Value}; + +/// A `github_conversation_read` frame's opening entry, copied from a live session, its long +/// dependabot body cut to its first line. +const OPENING: &str = r#"{"kind": "opening", "author": {"login": "dependabot", "bot": true}, "body": "Bumps the actions group with 2 updates in the / directory.", "at": 1792259399}"#; + +const CHANGED: u64 = 1_792_259_399; + +/// When `CHANGED` was, as GitHub writes a comment's time. +const CHANGED_TEXT: &str = "2026-10-17T17:49:59Z"; + +fn drawn(entries: Vec, opened_by_you: bool) -> String { + let entries: Vec = + serde_json::from_value(json!(entries)).expect("entries as core sends them"); + conversation(&an_hour_after(CHANGED), &entries, opened_by_you) +} + +fn comment(author: &str, bot: bool, mine: bool, body: &str) -> Value { + json!({"id": "IC_1", "author": author, "bot": bot, "mine": mine, "body": body, + "created_at": CHANGED_TEXT, "url": "https://github.com/o/r/pull/1#issuecomment-1"}) +} + +/// A comment as the timeline's own entry. +fn said(author: &str, bot: bool, mine: bool, body: &str) -> Value { + let mut entry = comment(author, bot, mine, body); + entry["kind"] = json!("comment"); + entry +} + +fn review(verdict: &str, line_comments: usize, bot: bool) -> Value { + let comment = comment("mara", bot, false, "Looks fine."); + json!({"kind": "review", "comment": comment, "verdict": verdict, "line_comments": line_comments}) +} + +fn thread(path: &str, resolved: bool, outdated: bool, said: &[(&str, &str)]) -> Value { + let comments: Vec = said + .iter() + .map(|(author, body)| { + json!({"author": author, + "body": body, "created_at": CHANGED_TEXT, "url": "https://github.com/o/r/pull/1#r1"}) + }) + .collect(); + json!({"kind": "thread", "id": "PRRT_1", "path": path, "line": 42, "start_line": null, + "side": "right", "outdated": outdated, "resolved": resolved, "file_level": false, + "comments": comments, "total_comments": said.len(), "anchor_text": null, + "can_reply": false, "can_resolve": false}) +} + +/// The break this catches: the real opening entry drawn as a person's, without its age, or with +/// its body rendered before its HTML was made readable. +#[test] +fn the_opening_reads_as_the_tuis() { + let opening: Value = serde_json::from_str(OPENING).expect("an opening as core sends it"); + let html = drawn(vec![opening], false); + assert!(html.contains("
"), "{html}"); + let bot = "@dependabot bot"; + assert!(html.contains(bot), "{html}"); + assert!(html.contains(">opened"), "{html}"); + assert!(html.contains(">3600s ago"), "{html}"); + assert!(html.contains("R:Bumps the actions group"), "{html}"); +} + +/// The break this catches: your own description or comment not named as yours, a person's +/// comment drawn quiet, or a comment's time dropped. +#[test] +fn a_comment_names_its_speaker() { + let opening = json!({"kind": "opening", "author": {"login": "me", "bot": false}, "body": "x", "at": CHANGED}); + let html = drawn(vec![opening], true); + assert!(html.contains("@me"), "{html}"); + let html = drawn(vec![said("jo", false, false, "Hi.")], false); + assert!(html.contains("
"), "{html}"); + assert!(html.contains("@jo"), "{html}"); + assert!(html.contains(">commented"), "{html}"); + assert!(html.contains(">3600s ago"), "{html}"); + let html = drawn(vec![said("me", false, true, "Hi.")], false); + assert!(html.contains("@me"), "{html}"); + let html = drawn(vec![said("", false, false, "Hi.")], false); + assert!(html.contains("@ghost"), "{html}"); +} + +/// The break this catches: a verdict in the wrong words or tone, a bot's review toned like a +/// person's, or the line comments miscounted. +#[test] +fn a_review_is_toned_by_its_verdict() { + let html = drawn(vec![review("approved", 0, false)], false); + assert!(html.contains("tone-approved"), "{html}"); + assert!(html.contains("approved"), "{html}"); + assert!(!html.contains("line comment"), "{html}"); + let html = drawn(vec![review("changes_requested", 1, false)], false); + assert!(html.contains("tone-changes"), "{html}"); + assert!(html.contains("requested changes"), "{html}"); + assert!(html.contains(">1 line comment"), "{html}"); + let html = drawn(vec![review("changes_requested", 3, true)], false); + assert!(html.contains("tone-quiet"), "{html}"); + assert!(html.contains(">3 line comments"), "{html}"); +} + +/// The break this catches: a long comment drawn whole, or a short one folded behind a button. +#[test] +fn a_long_comment_folds() { + let long = (1..=8).map(|n| format!("line {n}")).collect::>().join("\n"); + let html = drawn(vec![said("jo", false, false, &long)], false); + assert!(html.contains("tone-person folded"), "{html}"); + assert!(html.contains("")); + let short = (1..=7).map(|n| format!("line {n}\n")).collect::(); + let html = drawn(vec![said("jo", false, false, &short)], false); + assert!(!html.contains("folded") && !html.contains("gh-unfold"), "{html}"); +} + +/// The break this catches: an open thread not in the info tone, its place or reply count wrong, +/// its last word missing while folded, or a reply left out once it's opened. +#[test] +fn an_open_thread_shows_its_last_word() { + let said = [("mara", "Why\nthis?"), ("jo", "Because.")]; + let html = drawn(vec![thread("src/api/v1/hook.rs", false, false, &said)], false); + assert!(html.contains("
"), "{html}"); + assert!(html.contains("@mara"), "{html}"); + assert!(html.contains(" \u{b7} \u{2026}/v1/hook.rs:42"), "{html}"); + assert!(html.contains("unresolved"), "{html}"); + assert!(html.contains(">1 reply"), "{html}"); + let last = "@jo: Because."; + assert!(html.contains(last), "{html}"); + assert!(html.contains("R:Why\nthis?"), "{html}"); +} + +/// The break this catches: a settled thread still toned as open, or a short path cut. +#[test] +fn a_settled_thread_is_quiet() { + let said = [("mara", "Fixed.")]; + let html = drawn(vec![thread("crates/x/hook.rs", true, false, &said)], false); + assert!(html.contains("tone-person"), "{html}"); + assert!(html.contains("crates/x/hook.rs:42"), "{html}"); + assert!(html.contains("resolved"), "{html}"); + assert!(!html.contains(" reply<"), "{html}"); + let html = drawn(vec![thread("src/hook.rs", false, true, &said)], false); + assert!(html.contains("outdated"), "{html}"); + assert!(html.contains("tone-person"), "{html}"); +} diff --git a/crates/luxe-remote/src/render/github/tests/list.rs b/crates/luxe-remote/src/render/github/tests/list.rs new file mode 100644 index 0000000..2d7a929 --- /dev/null +++ b/crates/luxe-remote/src/render/github/tests/list.rs @@ -0,0 +1,146 @@ +use super::an_hour_after; +use crate::render::github::list; +use luxe_core::github::{rfc3339_seconds, ListedSection}; +use serde_json::{json, Value}; + +/// A `github_listed` item, copied from a live session's "Pull requests" section. +const ITEM: &str = r#"{"pull_request": true, "number": 211, "title": "chore: refresh the embedded models.dev snapshot", "url": "https://github.com/nora-quinn/luxe-dev/pull/211", "repository": "nora-quinn/luxe-dev", "author": "github-actions", "draft": false, "updated_at": "2026-10-19T12:25:08Z", "state": "open", "facts": {"author_bot": true, "additions": 2, "deletions": 2, "checks": {"passed": 0, "failed": 0, "pending": 0, "skipped": 0}, "review_decision": null, "comments": 0, "labels": [], "linked_pull_request": null}}"#; + +const HERE: Option<&str> = Some("nora-quinn/luxe-dev"); + +fn item() -> Value { + serde_json::from_str(ITEM).expect("a listed item as core sends it") +} + +fn section(items: Vec, total: Option) -> ListedSection { + let section = json!({"name": "Pull requests", "items": items, "error": null, "total": total}); + serde_json::from_value(section).expect("a listed section as core sends it") +} + +/// When `ITEM` last changed. +fn changed() -> u64 { + rfc3339_seconds("2026-10-19T12:25:08Z").expect("the item's time reads") +} + +/// One section holding `item`, drawn an hour after it changed. +fn drawn(item: Value) -> String { + list(&an_hour_after(changed()), HERE, §ion(vec![item], Some(1))) +} + +/// The break this catches: a row the app can't open (number, kind or link missing), the mark in +/// the wrong state color, a bot named as a person, the age keeping its "ago", or the diff counts +/// dropped from line two. +#[test] +fn a_pull_request_row_reads_as_the_tuis() { + let html = drawn(item()); + assert!(html.contains("data-number=\"211\" data-pull=\"true\""), "{html}"); + assert!(html.contains("data-url=\"https://github.com/nora-quinn/luxe-dev/pull/211\"")); + assert!(html.contains("PR"), "{html}"); + assert!(html.contains("#211 "), "{html}"); + assert!(html.contains("refresh the embedded models.dev snapshot"), "{html}"); + let bot = "github-actions bot"; + assert!(html.contains(bot), "{html}"); + assert!(html.contains("3600s"), "{html}"); + assert!(html.contains("+2"), "{html}"); + assert!(!html.contains(">open<"), "an open pull request doesn't say so: {html}"); +} + +/// The break this catches: the checks or the review left out of line two, or their marks crossed. +#[test] +fn a_pull_request_row_says_where_it_stands() { + let mut failing = item(); + failing["facts"]["checks"] = json!({"passed": 3, "failed": 1, "pending": 2, "skipped": 0}); + failing["facts"]["review_decision"] = json!("changes_requested"); + let html = drawn(failing); + assert!(html.contains("N 1 failing"), "{html}"); + assert!(html.contains("changes requested"), "{html}"); + let mut running = item(); + running["facts"]["checks"] = json!({"passed": 3, "failed": 0, "pending": 2, "skipped": 0}); + running["facts"]["review_decision"] = json!("approved"); + let html = drawn(running); + assert!(html.contains("W running"), "{html}"); + assert!(html.contains("approved"), "{html}"); + let mut passed = item(); + passed["facts"]["checks"] = json!({"passed": 3, "failed": 0, "pending": 0, "skipped": 0}); + assert!(drawn(passed).contains("Y checks")); +} + +/// The break this catches: a draft or a merged pull request that doesn't say so, or its mark in +/// the open color. +#[test] +fn a_row_names_any_state_but_open() { + let mut draft = item(); + draft["draft"] = json!(true); + let html = drawn(draft); + assert!(html.contains("PR"), "{html}"); + assert!(html.contains("draft"), "{html}"); + let mut merged = item(); + merged["state"] = json!("merged"); + assert!(drawn(merged).contains("merged")); +} + +/// The break this catches: an issue drawn with a pull request's mark or diff counts, its labels +/// left out, or the pull request on it not named. +#[test] +fn an_issue_row_shows_its_labels_and_its_pull_request() { + let mut issue = item(); + issue["pull_request"] = json!(false); + issue["facts"]["labels"] = json!([{"name": "bug", "color": "d73a4a"}]); + issue["facts"]["linked_pull_request"] = json!(9); + let html = drawn(issue.clone()); + assert!(html.contains("data-pull=\"false\""), "{html}"); + assert!(html.contains(">IS"), "{html}"); + assert!(html.contains("bug"), "{html}"); + assert!(html.contains("W PR #9"), "{html}"); + assert!(!html.contains("class=\"add\""), "an issue has no diff: {html}"); + issue["facts"]["linked_pull_request"] = json!(null); + issue["facts"]["comments"] = json!(1); + assert!(drawn(issue).contains("1 comment")); +} + +/// The break this catches: a row from another repository that doesn't say which, or one from +/// this checkout that names it anyway. +#[test] +fn a_row_names_its_repository_only_when_it_is_elsewhere() { + let one = section(vec![item()], Some(1)); + let here = list(&an_hour_after(changed()), HERE, &one); + assert!(!here.contains("nora-quinn/luxe-dev"), "{here}"); + let elsewhere = list(&an_hour_after(changed()), Some("someone/else"), &one); + let named = "nora-quinn/luxe-dev"; + assert!(elsewhere.contains(named), "{elsewhere}"); +} + +/// The break this catches: a count that hides how many more GitHub has, says "of" when there +/// are no more, or runs a big number together. +#[test] +fn the_count_says_how_many_of_how_many() { + let cx = an_hour_after(0); + let count = |total| list(&cx, HERE, §ion(vec![item()], total)); + assert!(count(Some(3250)).contains(">1 of 3,250

"), "{}", count(Some(3250))); + assert!(count(Some(120_000)).contains(">1 of 120,000

"), "{}", count(Some(120_000))); + assert!(count(Some(1)).contains(">1 shown

"), "{}", count(Some(1))); + assert!(count(None).contains(">1 shown

"), "{}", count(None)); +} + +/// The break this catches: an empty tab drawn as a blank, or a failed search's reason lost or +/// let through unescaped. +#[test] +fn an_empty_or_failed_tab_says_so() { + let cx = an_hour_after(0); + let empty = list(&cx, HERE, §ion(Vec::new(), Some(0))); + assert_eq!(empty, "

Nothing matches this search

"); + let mut failed = section(Vec::new(), None); + failed.error = Some("gh failed".into()); + let html = list(&cx, HERE, &failed); + assert_eq!(html, "

gh <auth> failed

"); +} + +/// The break this catches: a stranger's title reaching the page as markup. +#[test] +fn a_title_is_escaped() { + let mut hostile = item(); + hostile["title"] = json!(""); + let html = drawn(hostile); + assert!(html.contains("<img"), "{html}"); + assert!(!html.contains(" Value { + serde_json::from_str(json).expect("an overview as core sends it") +} + +fn parsed(value: Value) -> Overview { + serde_json::from_value(value).expect("an overview as core sends it") +} + +fn headed(value: Value) -> String { + header(&an_hour_after(CHANGED), &parsed(value)) +} + +fn sections(value: Value) -> String { + overview(&an_hour_after(CHANGED), &parsed(value)) +} + +/// The break this catches: the number, title, author, branches, size or age left out of the +/// header, a bot named as a person, or the state chip in the wrong color. +#[test] +fn a_pull_requests_header_reads_as_the_tuis() { + let html = headed(value(PULL_REQUEST)); + assert!(html.contains("#235 ci: bump the actions group"), "{html}"); + let bot = "dependabot bot"; + assert!(html.contains(bot), "{html}"); + let branches = "master \u{2190} dependabot/github_actions"; + assert!(html.contains(branches), "{html}"); + assert!(html.contains("+8"), "{html}"); + assert!(html.contains("in 4 files"), "{html}"); + assert!(html.contains("3600s ago"), "{html}"); + assert!(html.contains("open"), "{html}"); + assert!(html.contains("\u{25cf} dependencies"), "{html}"); +} + +/// The break this catches: "1 files", or a header that shows every label however many there are. +#[test] +fn the_header_counts_one_file_and_caps_its_labels() { + let mut pull_request = value(PULL_REQUEST); + pull_request["overview"]["changed_files"] = json!(1); + let labels: Vec = + (1..=5).map(|n| json!({"name": format!("l{n}"), "color": "000000"})).collect(); + pull_request["overview"]["labels"] = json!(labels); + let html = headed(pull_request); + assert!(html.contains("in 1 file"), "{html}"); + assert!(html.contains("> l4"), "{html}"); + assert!(!html.contains("> l5"), "{html}"); +} + +/// The break this catches: an issue's header drawn with a pull request's branches, or its closed +/// state in the pull request's red. +#[test] +fn an_issues_header_has_no_branches() { + let mut issue = value(ISSUE); + issue["overview"]["state"] = json!("closed"); + let html = headed(issue); + assert!(html.contains("#41 Crash on start"), "{html}"); + assert!(!html.contains('\u{2190}'), "{html}"); + assert!(html.contains("closed"), "{html}"); +} + +/// The break this catches: a blocker drawn with a passing mark or quiet, the count of what's +/// incomplete dropped, or the stack's "open #N" (the one action that only reads) missing. +#[test] +fn the_status_marks_what_blocks_a_merge() { + let mut draft = value(PULL_REQUEST); + draft["overview"]["draft"] = json!(true); + draft["overview"]["stack"] = json!({"trunk": "master", "trunk_is_default": true, "above": [], + "below": [{"number": 230, "title": "base", "head_ref": "base", "draft": false, "checked": true}]}); + let html = sections(draft); + assert!( + html.contains("

Status"), + "{html}" + ); + assert!(html.contains("incomplete

"), "{html}"); + let blocker = "NDraft\ + still a draft"; + assert!(html.contains(blocker), "{html}"); + let open = ""; + assert!(html.contains(open), "{html}"); +} + +/// The break this catches: a passing check drawn as a blocker, or "0 incomplete" on a pull +/// request with nothing left to do. +#[test] +fn a_passing_check_is_quiet() { + let mut ready = value(PULL_REQUEST); + ready["overview"]["merge_status"] = json!("clean"); + let html = sections(ready); + assert!(html + .contains("YChecks")); + assert!(html.contains(""), "{html}"); + assert!(!html.contains("incomplete"), "{html}"); +} + +/// The break this catches: the approval count wrong, a verdict in the wrong color, a team not +/// named as one, or a Reviewers heading over nobody. +#[test] +fn reviewers_say_what_they_said() { + let mut reviewed = value(PULL_REQUEST); + reviewed["overview"]["reviewers"] = json!([ + {"login": "mara", "kind": "user", "verdict": "approved", "at": CHANGED}, + {"login": "core", "kind": "team", "verdict": "changes_requested", "at": null} + ]); + let html = sections(reviewed); + assert!(html.contains(">1 of 2 approved"), "{html}"); + assert!(html.contains("mara"), "{html}"); + assert!(html.contains("approved"), "{html}"); + assert!(html.contains("\u{b7} 3600s ago"), "{html}"); + assert!(html.contains( + "changes requested \u{b7} team" + )); + assert!(!sections(value(PULL_REQUEST)).contains("Reviewers")); +} + +/// The break this catches: the excerpt quoting more or fewer than five lines that say something, +/// a blank line spending one of the five, the count of the rest wrong, or a body rendered without +/// its HTML made readable first. +#[test] +fn the_description_quotes_five_lines() { + let body = |text: &str| { + let mut pull_request = value(PULL_REQUEST); + pull_request["overview"]["body"] = json!(text); + sections(pull_request) + }; + let long = body("one\n\ntwo\nthree\nfour\nfive\nsix\nseven"); + assert!(long.contains("R:one\n\ntwo\nthree\nfour\nfive\n"), "{long}"); + let more = "data-tab=\"conversation\">… 2 more lines in Conversation"; + assert!(long.contains(more), "{long}"); + let short = body("one\ntwo\nthree\nfour\nfive"); + assert!(short.contains("five\n") && !short.contains("gh-more"), "{short}"); + assert!(body(" ").contains("

No description

")); +} + +/// The break this catches: an issue's assignees, closing pull requests or milestone left out, +/// a pull request that only mentions the issue listed as closing it, or nothing said when nobody +/// is on it. +#[test] +fn an_issue_says_who_is_on_it() { + let html = sections(value(ISSUE)); + assert!(html.contains("unassigned"), "{html}"); + assert!(html.contains("none yet"), "{html}"); + assert!(!html.contains("Milestone"), "{html}"); + let mut staffed = value(ISSUE); + staffed["overview"]["assignees"] = json!(["mara", "jo"]); + staffed["overview"]["milestone"] = json!("v1"); + staffed["overview"]["linked"] = json!([ + {"number": 7, "title": "Fix", "state": "open", "draft": false, "author": "jo", "closes": true}, + {"number": 8, "title": "See", "state": "open", "draft": false, "author": "jo", "closes": false} + ]); + let html = sections(staffed); + assert!(html.contains("mara, jo"), "{html}"); + assert!(html.contains("data-number=\"7\" data-pull=\"true\">#7"), "{html}"); + assert!(!html.contains("data-number=\"8\""), "{html}"); + assert!( + html.contains("Milestonev1") + ); +} diff --git a/crates/luxe-remote/src/render/review.rs b/crates/luxe-remote/src/render/review.rs new file mode 100644 index 0000000..727af2b --- /dev/null +++ b/crates/luxe-remote/src/render/review.rs @@ -0,0 +1,314 @@ +//! Review — the open Guided Review as the app shows it: the guide, then one chapter at a time. +//! +//! The guide is the TUI's guide pane as a page: the brief, then each chapter's number, kind and +//! title, with either its rationale and files or the one line saying nothing in it needs the +//! reader. That call is the host's (`open_review_shown`'s reading), since it's decided from lines +//! the app doesn't send back. A chapter is its items in order, grouped under the file they're in, +//! each with the guide's sentence for it above its diff, as the TUI's narration band puts it. + +use super::{diff, escape, Renderer, Voice}; +use luxe_core::guided_review::{ + ChapterId, ChapterKind, ChapterReading, GuidedReview, ReviewChapter, ReviewFile, + ReviewFileStatus, ReviewFinding, ReviewItemRef, +}; +use std::collections::HashMap; + +mod findings; + +/// File rows a chapter lists in the guide before the rest are counted, as the TUI windows them. +const FILE_ROWS: usize = 8; + +/// The whole guide: the brief, then every chapter. +pub(super) fn guide( + renderer: &dyn Renderer, + review: &GuidedReview, + reading: &[ChapterReading], + walked: &[ChapterId], +) -> String { + let owners = Owners::of(&review.files); + let total = review.chapters.len(); + let chapters: String = review + .chapters + .iter() + .enumerate() + .map(|(index, chapter)| { + let place = Place { number: index + 1, total, walked: walked.contains(&chapter.id) }; + let reading = reading.iter().find(|it| it.chapter_id == chapter.id); + guide_chapter(renderer, chapter, &place, reading, &owners.files_of(chapter)) + }) + .collect(); + format!("
{}{chapters}
", brief(renderer, review)) +} + +/// One chapter opened: its heading, then its items with their notes and diffs. +pub(super) fn chapter( + renderer: &dyn Renderer, + chapter: &ReviewChapter, + files: &[ReviewFile], + place: &Place, + reading: Option<&ChapterReading>, + findings: &[ReviewFinding], +) -> String { + let mut out = format!("
{}", heading(chapter, place, reading)); + out.push_str(&prose(renderer, chapter, reading)); + out.push_str("
"); + out.push_str(&findings::on_chapter(renderer, findings, &chapter.id)); + out.push_str(&items_html(renderer, chapter, files, findings)); + format!("
{out}
") +} + +/// A chapter's items in its order, with a file's path said once above the run of items in it and +/// the comments on a hunk under it. +fn items_html( + renderer: &dyn Renderer, + chapter: &ReviewChapter, + files: &[ReviewFile], + findings: &[ReviewFinding], +) -> String { + let mut out = String::new(); + let mut current: Option<&str> = None; + for item in &chapter.items { + let Some((file, hunk)) = locate(files, item) else { continue }; + if current != Some(file.id.as_str()) { + current = Some(file.id.as_str()); + out.push_str(&format!("

{}

", escape(&path_of(file)))); + } + out.push_str(&item_html(renderer, chapter, file, hunk)); + let comments = hunk.map(|hunk| findings::on_hunk(renderer, findings, &hunk.id)); + out.push_str(&comments.unwrap_or_default()); + } + out +} + +/// Where a chapter sits: `number` of `total`, and whether the reader has walked it. +#[derive(Debug, Clone, Copy, serde::Deserialize)] +pub(crate) struct Place { + pub(crate) number: usize, + pub(crate) total: usize, + #[serde(default)] + pub(crate) walked: bool, +} + +/// The guide's opening: the summary's intent and claims, or the agent's own words when no summary +/// was written. +fn brief(renderer: &dyn Renderer, review: &GuidedReview) -> String { + let words = match review.brief.as_ref() { + Some(brief) => { + let claims: String = + brief.account.iter().map(|claim| bullet(renderer, claim)).collect(); + let claims = if claims.is_empty() { claims } else { format!("
    {claims}
") }; + renderer.markdown(&brief.intent, Voice::Answer) + &claims + } + None => agents_words(renderer, review), + }; + if words.is_empty() { + return String::new(); + } + format!("
{words}
") +} + +fn bullet(renderer: &dyn Renderer, claim: &str) -> String { + format!("
  • {}
  • ", renderer.markdown(claim, Voice::Answer)) +} + +/// What the turn was asked and what it said it did, with the TUI's line saying so. +fn agents_words(renderer: &dyn Renderer, review: &GuidedReview) -> String { + let Some(provenance) = review.provenance.as_ref() else { + return String::new(); + }; + let mut out: String = + provenance.requests.iter().map(|it| renderer.markdown(it, Voice::Answer)).collect(); + if let Some(account) = provenance.account.as_deref() { + out.push_str(&renderer.markdown(account, Voice::Answer)); + out.push_str( + "

    the agent\u{2019}s own words \u{2014} no summary was written for \ + this review

    ", + ); + } + out +} + +fn guide_chapter( + renderer: &dyn Renderer, + chapter: &ReviewChapter, + place: &Place, + reading: Option<&ChapterReading>, + files: &[&ReviewFile], +) -> String { + let quiet = if needs_nothing(reading) { " quiet" } else { "" }; + let rows = if needs_nothing(reading) { String::new() } else { file_rows(files) }; + format!( + "
    {}{}{rows}
    ", + escape(chapter.id.as_str()), + heading(chapter, place, reading), + prose(renderer, chapter, reading), + ) +} + +/// `01 / 05 CORE reviewed`, then the title, which opens the chapter. +fn heading(chapter: &ReviewChapter, place: &Place, reading: Option<&ChapterReading>) -> String { + let walked = if place.walked { "reviewed" } else { "" }; + let quiet = if needs_nothing(reading) { " quiet" } else { "" }; + format!( + "

    {:02} / {:02}{}{walked}

    \ + ", + place.number, + place.total, + kind_label(chapter.kind), + escape(chapter.id.as_str()), + escape(&chapter.title), + ) +} + +/// The rationale and impact, or the one line that says why there's nothing to read. +fn prose( + renderer: &dyn Renderer, + chapter: &ReviewChapter, + reading: Option<&ChapterReading>, +) -> String { + if needs_nothing(reading) { + let reason = reading.and_then(|it| it.reason.as_deref()); + let words = reason.map_or_else( + || "nothing here needs you".to_owned(), + |reason| format!("{reason} \u{2014} nothing here needs you"), + ); + return format!("

    {}

    ", escape(&words)); + } + let rationale = renderer.markdown(&chapter.rationale, Voice::Answer); + let impact = chapter.impact.as_deref().map(|impact| { + format!("
    {}
    ", renderer.markdown(impact, Voice::Answer)) + }); + format!("
    {rationale}{}
    ", impact.unwrap_or_default()) +} + +/// A chapter the host found nothing in for the reader. No reading means the host didn't say, and +/// that's not the same as nothing. +fn needs_nothing(reading: Option<&ChapterReading>) -> bool { + reading.is_some_and(|reading| reading.needs_review == 0) +} + +fn kind_label(kind: ChapterKind) -> &'static str { + match kind { + ChapterKind::Core => "CORE", + ChapterKind::Consequence => "CONSEQUENCE", + ChapterKind::Test => "TESTS", + ChapterKind::Supporting => "SUPPORTING", + ChapterKind::Generated => "GENERATED", + } +} + +fn file_rows(files: &[&ReviewFile]) -> String { + let rows: String = files.iter().take(FILE_ROWS).map(|file| file_row(file)).collect(); + let more = files.len().saturating_sub(FILE_ROWS); + let more = if more > 0 { + format!("
  • \u{2026} {more} more
  • ") + } else { + String::new() + }; + format!("
      {rows}{more}
    ") +} + +/// `M path +12 −3`, or what the change was for a file with no lines to count. +fn file_row(file: &ReviewFile) -> String { + let (letter, tone) = status(file.status); + let change = match (file.non_text.as_ref(), file.additions, file.deletions) { + (Some(change), _, _) => format!("{}", escape(&change.summary)), + (None, Some(added), Some(deleted)) => format!( + "+{added}\u{2212}{deleted}" + ), + _ => String::new(), + }; + format!( + "
  • {letter}{}\ + {change}
  • ", + escape(&path_of(file)) + ) +} + +fn status(status: ReviewFileStatus) -> (&'static str, &'static str) { + match status { + ReviewFileStatus::Added => ("A", "tone-added"), + ReviewFileStatus::Untracked => ("?", "tone-added"), + ReviewFileStatus::Modified => ("M", "tone-modified"), + ReviewFileStatus::Deleted => ("D", "tone-deleted"), + ReviewFileStatus::Renamed => ("R", "tone-moved"), + ReviewFileStatus::Copied => ("C", "tone-moved"), + } +} + +/// One item: the hunk's symbol and the guide's sentence for it, then its lines. +fn item_html( + renderer: &dyn Renderer, + chapter: &ReviewChapter, + file: &ReviewFile, + hunk: Option<&luxe_core::guided_review::ReviewHunk>, +) -> String { + let Some(hunk) = hunk else { + let note = chapter.note_for(&ReviewItemRef::File(file.id.clone())); + return note_html(note) + &diff::whole(renderer, file); + }; + let symbol = hunk.symbol.as_ref().and_then(|symbol| symbol.name.as_deref()); + let symbol = symbol.map(|it| format!("

    {}

    ", escape(it))); + let note = note_html(chapter.note_for_hunk(&hunk.id)); + let lines = diff::hunk_html(renderer, file, hunk); + format!("{}{note}{}{lines}
    ", symbol.unwrap_or_default(), diff::opening(file)) +} + +fn note_html(note: Option<&str>) -> String { + note.map(|note| format!("

    {}

    ", escape(note))).unwrap_or_default() +} + +/// The file an item is in and, for a hunk, the hunk; `None` when the app didn't send it. +fn locate<'a>( + files: &'a [ReviewFile], + item: &ReviewItemRef, +) -> Option<(&'a ReviewFile, Option<&'a luxe_core::guided_review::ReviewHunk>)> { + match item { + ReviewItemRef::File(id) => files.iter().find(|file| &file.id == id).map(|it| (it, None)), + ReviewItemRef::Hunk(id) => files.iter().find_map(|file| { + file.hunks.iter().find(|hunk| &hunk.id == id).map(|hunk| (file, Some(hunk))) + }), + } +} + +fn path_of(file: &ReviewFile) -> String { + let path = file.new_path.as_deref().or(file.old_path.as_deref()); + path.map_or_else(|| "(unknown path)".to_owned(), |path| path.display().to_string()) +} + +/// Which file holds each id a chapter can name, built once per guide rather than scanned per item. +struct Owners<'a> { + by_id: HashMap<&'a str, &'a ReviewFile>, +} + +impl<'a> Owners<'a> { + fn of(files: &'a [ReviewFile]) -> Self { + let mut by_id = HashMap::new(); + for file in files { + by_id.insert(file.id.as_str(), file); + for hunk in &file.hunks { + by_id.insert(hunk.id.as_str(), file); + } + } + Self { by_id } + } + + /// A chapter's files in the order it names them, each once. + fn files_of(&self, chapter: &ReviewChapter) -> Vec<&'a ReviewFile> { + let mut files: Vec<&ReviewFile> = Vec::new(); + for item in &chapter.items { + let id = match item { + ReviewItemRef::File(id) => id.as_str(), + ReviewItemRef::Hunk(id) => id.as_str(), + }; + let Some(file) = self.by_id.get(id) else { continue }; + if !files.iter().any(|seen| seen.id == file.id) { + files.push(file); + } + } + files + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/review/findings.rs b/crates/luxe-remote/src/render/review/findings.rs new file mode 100644 index 0000000..8d53c92 --- /dev/null +++ b/crates/luxe-remote/src/render/review/findings.rs @@ -0,0 +1,151 @@ +//! Findings — the reader's comments, as cards under the hunk or chapter they're about. +//! +//! Each card is the TUI's: its label, what kind of comment it is and where it stands in the TUI's +//! words, the comment, then the thread that followed. The phone has no thread window, so the whole +//! thread is on the card. The buttons carry `data-act` for the app to send the edit; which ones a +//! card has follows what the review desk accepts in that state. + +use super::super::{escape, Renderer, Voice}; +use luxe_core::guided_review::{ + ChapterId, DiffSide, FindingAnchor, FindingMessageAuthor, FindingSeverity, FindingState, + HunkId, ReviewFinding, +}; + +/// Cards for the comments on lines of `hunk`, or on the hunk itself. +pub(super) fn on_hunk( + renderer: &dyn Renderer, + findings: &[ReviewFinding], + hunk: &HunkId, +) -> String { + let on = |finding: &&ReviewFinding| match &finding.anchor { + FindingAnchor::Line { hunk_id, .. } | FindingAnchor::Hunk { hunk_id, .. } => { + hunk_id == hunk + } + _ => false, + }; + findings.iter().filter(on).map(|finding| card(renderer, finding)).collect() +} + +/// Cards for the comments on the chapter as a whole. +pub(super) fn on_chapter( + renderer: &dyn Renderer, + findings: &[ReviewFinding], + chapter: &ChapterId, +) -> String { + let on = |finding: &&ReviewFinding| matches!(&finding.anchor, FindingAnchor::Chapter { chapter_id } if chapter_id == chapter); + findings.iter().filter(on).map(|finding| card(renderer, finding)).collect() +} + +fn card(renderer: &dyn Renderer, finding: &ReviewFinding) -> String { + let (state, tone) = state_words(finding); + format!( + "

    \ + {}{}{state}{}\ +

    {}
    {}{}
    ", + escape(finding.id.as_str()), + escape(&finding.label), + kind(finding), + place(&finding.anchor), + renderer.markdown(&finding.body, Voice::Answer), + thread(renderer, finding), + actions(finding), + ) +} + +/// What kind of comment it is, as the TUI's comment window heads it. +fn kind(finding: &ReviewFinding) -> &'static str { + match finding.severity { + FindingSeverity::Question => "question", + _ if finding.github_thread.is_some() => "reviewer comment", + _ => "comment", + } +} + +/// The line a line comment is on; the old side says so, since its number isn't the file's now. +fn place(anchor: &FindingAnchor) -> String { + match anchor { + FindingAnchor::Line { side: DiffSide::Old, line, .. } => { + format!("removed line {line}") + } + FindingAnchor::Line { line, .. } => format!("line {line}"), + _ => String::new(), + } +} + +/// Where it stands, in the TUI's words without its key hints, and the tone it's drawn in. +fn state_words(finding: &ReviewFinding) -> (&'static str, &'static str) { + let last = finding.thread.last().map(|message| message.author); + let question = finding.severity == FindingSeverity::Question; + match finding.state { + FindingState::Draft | FindingState::Open if finding.posted.is_some() => { + ("on GitHub", "dim") + } + FindingState::Draft => ("unsent", "warning"), + FindingState::Open if question && last == Some(FindingMessageAuthor::Agent) => { + ("answered", "success") + } + FindingState::Open if last == Some(FindingMessageAuthor::System) => { + ("no word from the agent", "warning") + } + FindingState::Open if last == Some(FindingMessageAuthor::Agent) => { + ("the agent replied", "info") + } + FindingState::Open => ("sent \u{00b7} waiting on the agent", "dim"), + FindingState::NeedsVerification => ("to verify", "info"), + FindingState::Resolved => ("verified", "success"), + FindingState::Stale => ("the code moved", "dim"), + } +} + +/// Every word after the comment, each said by who said it. The reader's opening message is the +/// comment itself, so it isn't said twice. +fn thread(renderer: &dyn Renderer, finding: &ReviewFinding) -> String { + let said: String = finding + .thread + .iter() + .skip_while(|message| { + message.author == FindingMessageAuthor::Reviewer && message.body == finding.body + }) + .map(|message| { + let who = match message.author { + FindingMessageAuthor::Reviewer => "you", + FindingMessageAuthor::Agent => "agent", + FindingMessageAuthor::System => "luxe", + }; + let words = renderer.markdown(&message.body, Voice::Answer); + format!("

    {who}

    {words}
    ") + }) + .collect(); + said +} + +/// The edits the review desk takes in this state: a draft is sent or deleted, an open comment +/// answered or resolved, a resolved one reopened. A moved one is the TUI's to re-anchor. +fn acts(finding: &ReviewFinding) -> &'static [(&'static str, &'static str)] { + match finding.state { + _ if finding.posted.is_some() => &[], + FindingState::Draft => &[("send", "Send"), ("delete", "Delete")], + FindingState::Open | FindingState::NeedsVerification => { + &[("reply", "Reply"), ("resolve", "Resolve")] + } + FindingState::Resolved => &[("reopen", "Reopen")], + FindingState::Stale => &[], + } +} + +fn actions(finding: &ReviewFinding) -> String { + let acts = acts(finding); + if acts.is_empty() { + return String::new(); + } + let buttons: String = acts + .iter() + .map(|(act, words)| { + format!("") + }) + .collect(); + format!("

    {buttons}

    ") +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/review/findings/scratch.json b/crates/luxe-remote/src/render/review/findings/scratch.json new file mode 100644 index 0000000..e818368 --- /dev/null +++ b/crates/luxe-remote/src/render/review/findings/scratch.json @@ -0,0 +1 @@ +{"review":{"id":"review:d99c1f45-e9f9-44e2-8e34-d5d28da37eb7","revision_id":"revision:2725a9262f2a20b9384fd34815f4c078d000aa46532d273ec949648d8fc35ca0","target":{"kind":"working_tree"},"source":{"base":{"kind":"head","oid":"a259681d8fab17fc77922c7fd5646eb60ab91a29"},"content_digest":"revision:2725a9262f2a20b9384fd34815f4c078d000aa46532d273ec949648d8fc35ca0","includes_staged":false,"includes_unstaged":true,"included_untracked_files":0,"captured_at_ms":1792442788572},"context":{"title":"Guided Review","goal":null,"phase_index":null,"phase_title":null,"planning_excerpt":null,"acceptance_excerpt":null,"source_intent":null,"source_commits":0},"files":[{"id":"file:f8c40bfe747fc99f88dd0ab57dc05fce0c80c39442da35d02395336d1c40a2f4","old_path":"config.rs","new_path":"config.rs","status":"modified","language":"rs","additions":3,"deletions":2,"hunks":[{"id":"hunk:4a6ae38e19f2513e9025942160970e253b6f89ca60b6c84880626b3c66c3f0cf","old_range":{"start":1,"count":2},"new_range":{"start":1,"count":3},"heading":null,"symbol":null,"lines":[{"old_line":1,"new_line":null,"kind":"deletion","text":"pub const PORT: u16 = 4000;"},{"old_line":2,"new_line":null,"kind":"deletion","text":"pub const HOST: &str = \"localhost\";"},{"old_line":null,"new_line":1,"kind":"addition","text":"pub const PORT: u16 = 4519;"},{"old_line":null,"new_line":2,"kind":"addition","text":"pub const HOST: &str = \"luxe.local\";"},{"old_line":null,"new_line":3,"kind":"addition","text":"pub const RETRIES: u32 = 2;"}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null}],"chapters":[{"id":"chapter:de5954563943cbdb6abfe21d1eda0812f1dbe9c7bebfa9f73bd8f479846e4ef7","title":"Core implementation","rationale":"Groups source-backed implementation changes.","impact":null,"kind":"core","items":[{"kind":"hunk","id":"hunk:4a6ae38e19f2513e9025942160970e253b6f89ca60b6c84880626b3c66c3f0cf"}],"notes":[]}],"checks":{"checks":[]},"stats":{"files":1,"hunks":1,"additions":3,"deletions":2,"binary_files":0,"non_text_files":0,"excluded_files":0},"generated_at_ms":1792442788572,"insight":null,"provenance":null,"seen":null,"brief":null},"findings":[{"id":"finding:06d4fc78-b794-463e-9e4d-55dfe9113425","label":"R1","anchor":{"kind":"line","file_id":"file:f8c40bfe747fc99f88dd0ab57dc05fce0c80c39442da35d02395336d1c40a2f4","hunk_id":"hunk:4a6ae38e19f2513e9025942160970e253b6f89ca60b6c84880626b3c66c3f0cf","side":"new","line":1,"context_hash":"sha256:6727922be2c161f00b05c06516fe62ac4247f363580a567aa1aa2edac94cf645"},"severity":"question","title":"Why 4519?","body":"Why 4519?","proposed_fix":null,"state":"draft","thread":[]},{"id":"finding:e862bf84-8257-44ad-b587-d22a95320bbc","label":"R2","anchor":{"kind":"chapter","chapter_id":"chapter:de5954563943cbdb6abfe21d1eda0812f1dbe9c7bebfa9f73bd8f479846e4ef7"},"severity":"issue","title":"Keep the old host as a fallback.","body":"Keep the old host as a fallback.","proposed_fix":null,"state":"draft","thread":[]}]} \ No newline at end of file diff --git a/crates/luxe-remote/src/render/review/findings/tests.rs b/crates/luxe-remote/src/render/review/findings/tests.rs new file mode 100644 index 0000000..e9ba869 --- /dev/null +++ b/crates/luxe-remote/src/render/review/findings/tests.rs @@ -0,0 +1,190 @@ +use super::super::{chapter, Place}; +use super::{acts, state_words}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; +use luxe_core::guided_review::{ + FindingMessage, FindingMessageAuthor, FindingSeverity, FindingState, GuidedReview, + ReviewFinding, +}; + +/// Prose marked so a test can tell it went through the markdown hook. +struct Marked; + +impl Renderer for Marked { + fn markdown(&self, text: &str, _voice: Voice) -> String { + format!("

    md:{}

    ", escape(text)) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn code_line(&self, text: &str, _language: Option<&str>) -> String { + escape(text) + } +} + +/// A real review of a scratch project and the two comments made on it over RPC: a question on its +/// first added line (R1) and an issue on its chapter (R2), both unsent. +fn captured() -> (GuidedReview, Vec) { + #[derive(serde::Deserialize)] + struct Scratch { + review: GuidedReview, + findings: Vec, + } + let scratch: Scratch = + serde_json::from_str(include_str!("scratch.json")).expect("the captured comments parse"); + (scratch.review, scratch.findings) +} + +fn open(review: &GuidedReview, findings: &[ReviewFinding]) -> String { + let place = Place { number: 1, total: 1, walked: false }; + chapter(&Marked, &review.chapters[0], &review.files, &place, None, findings) +} + +/// A line comment sits under its hunk, and a chapter comment above the chapter's first hunk. +/// +/// The break this catches: comments dropped from the chapter, or drawn away from what they're +/// about, so the reader can't tell which line was asked about. +#[test] +fn comments_sit_under_what_they_are_about() { + let (review, findings) = captured(); + let html = open(&review, &findings); + let hunk = html.find("
    ").expect("the hunk"); + let r1 = html.find("data-finding=\"finding:06d4fc78").expect("the line comment"); + let r2 = html.find(">R2<").expect("the chapter comment"); + assert!(r2 < hunk && hunk < r1, "{html}"); +} + +/// A card says what it is, where it is and where it stands, then the comment through the +/// markdown hook, with the edits an unsent one takes. +/// +/// The break this catches: a card missing its label, kind, line or state, the comment shown raw, +/// or an unsent comment that can't be sent or deleted from the phone. +#[test] +fn an_unsent_card_says_what_and_where_and_offers_send() { + let (review, findings) = captured(); + let html = open(&review, &findings[..1]); + let head = "R1question\ + unsentline 1"; + assert!(html.contains(head), "{html}"); + assert!(html.contains("

    md:Why 4519?

    ")); + assert!(html.contains("data-act=\"send\">Send")); + assert!(html.contains("data-act=\"delete\">Delete")); + assert!(html.contains("rv-finding rv-tone-warning")); +} + +/// Comments on another hunk or chapter stay off this one. +/// +/// The break this catches: every comment in the review piled onto whichever chapter is open. +#[test] +fn comments_elsewhere_stay_off_the_chapter() { + let (review, mut findings) = captured(); + for finding in &mut findings { + let mut anchor = serde_json::to_value(&finding.anchor).expect("an anchor"); + let field = if anchor.get("hunk_id").is_some() { "hunk_id" } else { "chapter_id" }; + anchor[field] = serde_json::json!(format!("{field}:elsewhere")); + finding.anchor = serde_json::from_value(anchor).expect("an anchor elsewhere"); + } + assert!(!open(&review, &findings).contains("rv-finding")); +} + +/// A finding in `state`, its thread ending with a word from `last`. +fn finding( + state: FindingState, + severity: FindingSeverity, + last: Option, +) -> ReviewFinding { + let (_, mut findings) = captured(); + let mut finding = findings.remove(0); + finding.state = state; + finding.severity = severity; + finding.thread = last.map(|author| said(author, "reply")).into_iter().collect(); + finding +} + +fn said(author: FindingMessageAuthor, body: &str) -> FindingMessage { + FindingMessage { author, body: body.into(), created_at_ms: 1 } +} + +/// Where a sent comment stands, in the TUI's words. +/// +/// The break this catches: the phone saying "waiting" when the agent has answered, or calling an +/// answer to a comment an answer to a question, which is what tells the reader to follow up. +#[test] +fn a_sent_comment_says_whether_the_agent_has_answered() { + use FindingMessageAuthor::{Agent, System}; + use FindingSeverity::{Issue, Question}; + let words = |state, severity, last| state_words(&finding(state, severity, last)).0; + assert_eq!(words(FindingState::Open, Question, Some(Agent)), "answered"); + assert_eq!(words(FindingState::Open, Issue, Some(Agent)), "the agent replied"); + assert_eq!(words(FindingState::Open, Issue, Some(System)), "no word from the agent"); + assert_eq!(words(FindingState::Open, Issue, None), "sent \u{00b7} waiting on the agent"); + assert_eq!(words(FindingState::NeedsVerification, Issue, None), "to verify"); + assert_eq!(words(FindingState::Resolved, Issue, None), "verified"); + assert_eq!(words(FindingState::Stale, Issue, None), "the code moved"); +} + +/// Each state offers only the edits the review desk takes in it. +/// +/// The break this catches: Delete offered on a sent comment (refused), Reply on an unsent one, or +/// a button on a moved comment, whose re-anchoring is the TUI's. +#[test] +fn each_state_offers_the_edits_it_takes() { + let names = |state| -> Vec<&str> { + acts(&finding(state, FindingSeverity::Issue, None)).iter().map(|(act, _)| *act).collect() + }; + assert_eq!(names(FindingState::Draft), ["send", "delete"]); + assert_eq!(names(FindingState::Open), ["reply", "resolve"]); + assert_eq!(names(FindingState::NeedsVerification), ["reply", "resolve"]); + assert_eq!(names(FindingState::Resolved), ["reopen"]); + assert!(names(FindingState::Stale).is_empty()); +} + +/// A comment posted to GitHub is GitHub's now: it says so and offers nothing. +/// +/// The break this catches: Send offered on a comment already posted, which would post it twice. +#[test] +fn a_posted_comment_is_on_github() { + let mut posted = finding(FindingState::Draft, FindingSeverity::Issue, None); + posted.posted = serde_json::from_value(serde_json::json!({"review_id": 7, "url": "https://x"})) + .expect("a posted comment"); + assert_eq!(state_words(&posted).0, "on GitHub"); + assert!(acts(&posted).is_empty()); +} + +/// The thread follows the comment, each word by who said it, the reader's opening not repeated. +/// +/// The break this catches: the agent's answer missing from the card (the phone has no thread +/// window), told as the reader's, or the comment said twice. +#[test] +fn the_thread_follows_the_comment_by_who_said_it() { + let (review, mut findings) = captured(); + let body = findings[0].body.clone(); + findings[0].state = FindingState::Open; + findings[0].thread = vec![ + said(FindingMessageAuthor::Reviewer, &body), + said(FindingMessageAuthor::Agent, "It is the bridge port"), + said(FindingMessageAuthor::Reviewer, "Say so in a comment"), + ]; + let html = open(&review, &findings[..1]); + assert_eq!(html.matches("md:Why 4519?").count(), 1, "{html}"); + let word = |who: &str, words: &str| { + html.find(&format!("

    {who}

    md:{words}")) + }; + let (agent, you) = (word("agent", "It is the bridge port"), word("you", "Say so in a comment")); + assert!(agent.zip(you).is_some_and(|(agent, you)| agent < you), "{html}"); +} + +/// A comment on a removed line says so: its number is the old file's. +/// +/// The break this catches: a removed line's comment saying "line 12" of a file whose line 12 is +/// something else now. +#[test] +fn a_comment_on_a_removed_line_says_removed() { + let (review, mut findings) = captured(); + let mut anchor = serde_json::to_value(&findings[0].anchor).expect("an anchor"); + anchor["side"] = serde_json::json!("old"); + findings[0].anchor = serde_json::from_value(anchor).expect("an old-side anchor"); + assert!(open(&review, &findings[..1]).contains("removed line 1")); +} diff --git a/crates/luxe-remote/src/render/review/pr-230.json b/crates/luxe-remote/src/render/review/pr-230.json new file mode 100644 index 0000000..8bc4db8 --- /dev/null +++ b/crates/luxe-remote/src/render/review/pr-230.json @@ -0,0 +1 @@ +{"review":{"id":"review:88f59ed0-d905-4df5-bb46-1617827c81c7","revision_id":"revision:af8fe36447f7b1bcceec9cd08a2817f6b1b90b450953459024343e047442410d","target":{"kind":"pull_request","number":230},"source":{"base":{"kind":"pull_request","number":230,"repository":"nora-quinn/luxe-dev","base_ref":"master","head_ref":"feat/rpc-review-and-github","merge_base":"23c3bb6769784327eb6bbdd81a70d289a8441dcd","head_oid":"30c314cfda8e0218a5354c3cd31211b0c8afdbd8"},"content_digest":"revision:af8fe36447f7b1bcceec9cd08a2817f6b1b90b450953459024343e047442410d","includes_staged":false,"includes_unstaged":false,"included_untracked_files":0,"captured_at_ms":1791417606327},"context":{"title":"The RPC protocol drives Guided Review and GitHub","goal":null,"phase_index":null,"phase_title":null,"planning_excerpt":"","acceptance_excerpt":null,"source_intent":"","source_commits":2,"pull_request":null},"files":[{"id":"file:677b483c517d053843fe1b0f9fb0e76d54ef3c34136871a03483eb6c7df27e73","old_path":"PROGRESS.md","new_path":"PROGRESS.md","status":"modified","language":"md","additions":53,"deletions":0,"hunks":[{"id":"hunk:8c166d70899616124dd65020d6b364adeaab1e6b9c06f712d8c5ab193fcfab67","old_range":{"start":7287,"count":3},"new_range":{"start":7287,"count":56},"heading":"narrow. A tab scoped to `{repo}` drops any `repo:`/`org:`/`user:` typed into it,","symbol":null,"lines":[{"old_line":7287,"new_line":7287,"kind":"context","text":"Notes on the change."},{"old_line":7288,"new_line":7288,"kind":"context","text":"Notes on the change."},{"old_line":7289,"new_line":7289,"kind":"context","text":"Notes on the change."},{"old_line":null,"new_line":7290,"kind":"addition","text":""}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null},{"id":"file:b43d826cab2837e8f7ec69c3a7d7961fe531b4d63a70eb0603b98e61a3bf4c57","old_path":"README.md","new_path":"README.md","status":"modified","language":"md","additions":1,"deletions":1,"hunks":[{"id":"hunk:d1203ebf52b3b4a830f6b7958f1e5da7425500882969d41d1801a0b620be53b6","old_range":{"start":7,"count":7},"new_range":{"start":7,"count":7},"heading":"A fast, lean, security-conscious agentic coding harness written in Rust, with a","symbol":null,"lines":[{"old_line":7,"new_line":7,"kind":"context","text":"- **Fast & Lean**: Built in Rust for maximum performance with minimal resource usage"},{"old_line":8,"new_line":8,"kind":"context","text":"- **TUI-first**: Interactive ratatui TUI (a complementary Iced GUI is planned for later)"},{"old_line":9,"new_line":9,"kind":"context","text":"- **Secure**: Permissive by default with always-on guardrails, an allow/ask/deny permission model (config + modes), SSRF-guarded web tools, `secrecy`-wrapped keys, and Rust with `unsafe` denied (one audited line: starting a command away from the terminal)"},{"old_line":10,"new_line":null,"kind":"deletion","text":"- **Extensible**: Hooks, skills, config-driven command-hooks (run external commands at loop points, e.g. gate/observe tool calls), MCP client support, and a published [RPC protocol](docs/guide/rpc.md) (`luxe --rpc`) for driving the whole agent from your own program \u2014 extend Luxe with *data + external processes*, never in-process plugin code (a deliberate supply-chain-safer trade-off: no plugin can read your SSH keys, because no plugin runs in-process)"}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null},{"id":"file:560067f3fef48486c14086caeb96d20e48e5bd36052027730b76c7badb370857","old_path":"ROADMAP.md","new_path":"ROADMAP.md","status":"modified","language":"md","additions":0,"deletions":5,"hunks":[{"id":"hunk:fd5441f86e56882a58860d9fd4b6726049b01e9f7446bcb779952c372cad95ee","old_range":{"start":309,"count":11},"new_range":{"start":309,"count":6},"heading":"Kept here so the question stays answered rather than being reopened.","symbol":null,"lines":[{"old_line":309,"new_line":309,"kind":"context","text":"Notes on the change."},{"old_line":310,"new_line":310,"kind":"context","text":"Notes on the change."},{"old_line":311,"new_line":311,"kind":"context","text":""},{"old_line":312,"new_line":null,"kind":"deletion","text":"Notes on the change."}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null},{"id":"file:875b560400698d0e5113dded88400fa640e326494f0be2e27c518fa265f22880","old_path":"crates/luxe-cli/src/cli.rs","new_path":"crates/luxe-cli/src/cli.rs","status":"modified","language":"rs","additions":8,"deletions":1,"hunks":[{"id":"hunk:57a7810f837ccd2107a1244475623d98813cb7eff7424af5c304b105c076c473","old_range":{"start":68,"count":6},"new_range":{"start":68,"count":13},"heading":"pub async fn run(mut args: Args) -> anyhow::Result<()> {","symbol":null,"lines":[{"old_line":68,"new_line":68,"kind":"context","text":" }"},{"old_line":69,"new_line":69,"kind":"context","text":" settings.on_ask = on_ask.into();"},{"old_line":70,"new_line":70,"kind":"context","text":" }"},{"old_line":null,"new_line":71,"kind":"addition","text":" if args.github_writes_misplaced() {"}],"noise":"semantic"},{"id":"hunk:56593fec6917327ca3da8a11e6cdd828cba61e24fb4aafdff2c9ec01ba0f3abd","old_range":{"start":136,"count":7},"new_range":{"start":143,"count":7},"heading":"pub async fn run(mut args: Args) -> anyhow::Result<()> {","symbol":null,"lines":[{"old_line":136,"new_line":143,"kind":"context","text":" }"},{"old_line":137,"new_line":144,"kind":"context","text":""},{"old_line":138,"new_line":145,"kind":"context","text":" if args.rpc {"},{"old_line":139,"new_line":null,"kind":"deletion","text":" rpc::run_rpc(settings).await?;"}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null},{"id":"file:f751eca33f87b7fa69ef93bd62df2460a449a677ddd0edc6f6340192f2a4e6c2","old_path":"crates/luxe-cli/src/cli/args.rs","new_path":"crates/luxe-cli/src/cli/args.rs","status":"modified","language":"rs","additions":37,"deletions":0,"hunks":[{"id":"hunk:9df31909889d39d139e3dabbd46d8816355b06d46ceb885312a0d6a490ee58e4","old_range":{"start":20,"count":6},"new_range":{"start":20,"count":14},"heading":"pub struct Args {","symbol":null,"lines":[{"old_line":20,"new_line":20,"kind":"context","text":" #[arg(long, conflicts_with = \"headless\")]"},{"old_line":21,"new_line":21,"kind":"context","text":" pub rpc: bool,"},{"old_line":22,"new_line":22,"kind":"context","text":""},{"old_line":null,"new_line":23,"kind":"addition","text":" /// Let an `--rpc` client publish to GitHub: post comments and reviews, answer threads, and open,"}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null},{"id":"file:10b31e2adcd77aa4553471c09f0cd18bceb0939f955c2c48c69c0ac39cfd80ff","old_path":"crates/luxe-cli/tests/rpc_stdio.rs","new_path":"crates/luxe-cli/tests/rpc_stdio.rs","status":"modified","language":"rs","additions":227,"deletions":0,"hunks":[{"id":"hunk:d705bbc6457917968814af5e974f75f655dfe80729098f8bb053b875d5e592f1","old_range":{"start":14,"count":11},"new_range":{"start":14,"count":17},"heading":"use std::process::{Command, Stdio};","symbol":null,"lines":[{"old_line":14,"new_line":14,"kind":"context","text":"/// Isolated because the developer's real `~/.config/luxe` must not decide whether a test passes,"},{"old_line":15,"new_line":15,"kind":"context","text":"/// and because a run against a real project would emit that project's workspace snapshot."},{"old_line":16,"new_line":16,"kind":"context","text":"fn run_rpc(input: &str) -> (String, String) {"},{"old_line":null,"new_line":17,"kind":"addition","text":" run_rpc_with(&[], input)"}],"noise":"semantic"},{"id":"hunk:c855fd07febccc2cbb0f4906da63ce65eb12e0d6f02a5c32f83772a54b55ec93","old_range":{"start":96,"count":3},"new_range":{"start":102,"count":224},"heading":"fn rpc_refuses_a_bad_frame_and_keeps_going() {","symbol":null,"lines":[{"old_line":96,"new_line":102,"kind":"context","text":" \"a frame that named itself is refused by that name\""},{"old_line":97,"new_line":103,"kind":"context","text":" );"},{"old_line":98,"new_line":104,"kind":"context","text":"}"},{"old_line":null,"new_line":105,"kind":"addition","text":""}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null},{"id":"file:fa536cf0db4875d194113de8d14e258aa7a6d7f7f211ec8258d64692bbd3b32f","old_path":"crates/luxe-core/tests/event_serialization.rs","new_path":"crates/luxe-core/tests/event_serialization.rs","status":"modified","language":"rs","additions":24,"deletions":5,"hunks":[{"id":"hunk:977a47effe55c31ff5c4f37494f889baca9640c1a383399dabaa48e707730486","old_range":{"start":67,"count":6},"new_range":{"start":67,"count":19},"heading":"fn empty_guided_review() -> GuidedReview {","symbol":null,"lines":[{"old_line":67,"new_line":67,"kind":"context","text":" }"},{"old_line":68,"new_line":68,"kind":"context","text":"}"},{"old_line":69,"new_line":69,"kind":"context","text":""},{"old_line":null,"new_line":70,"kind":"addition","text":"/// A `ready` from a build that predates `github_writes` reads as a session that refuses writes."}],"noise":"semantic"}],"binary":false,"generated":false,"non_text":null}],"chapters":[{"id":"chapter:89136a98be06d45add90a01041fc5a70160b5d3b52458d8ad501f0ae09b3d196","title":"Core implementation","rationale":"Groups source-backed implementation changes.","impact":null,"kind":"core","items":[{"kind":"hunk","id":"hunk:57a7810f837ccd2107a1244475623d98813cb7eff7424af5c304b105c076c473"},{"kind":"hunk","id":"hunk:56593fec6917327ca3da8a11e6cdd828cba61e24fb4aafdff2c9ec01ba0f3abd"},{"kind":"hunk","id":"hunk:9df31909889d39d139e3dabbd46d8816355b06d46ceb885312a0d6a490ee58e4"}],"notes":[]},{"id":"chapter:b3b809b4bc64361192cf81135792681993d9bab365d362ee2e70774464613a8e","title":"Tests and fixtures","rationale":"Groups source-backed verification changes.","impact":null,"kind":"test","items":[{"kind":"hunk","id":"hunk:d705bbc6457917968814af5e974f75f655dfe80729098f8bb053b875d5e592f1"},{"kind":"hunk","id":"hunk:c855fd07febccc2cbb0f4906da63ce65eb12e0d6f02a5c32f83772a54b55ec93"},{"kind":"hunk","id":"hunk:977a47effe55c31ff5c4f37494f889baca9640c1a383399dabaa48e707730486"}],"notes":[]},{"id":"chapter:25e5e3ea69fe74055ba6c40eac782b3a27f2c4cd4fedb718f79d9b5d086de6da","title":"Supporting changes","rationale":"Groups source-backed documentation, configuration, or other supporting changes.","impact":null,"kind":"supporting","items":[{"kind":"hunk","id":"hunk:8c166d70899616124dd65020d6b364adeaab1e6b9c06f712d8c5ab193fcfab67"},{"kind":"hunk","id":"hunk:d1203ebf52b3b4a830f6b7958f1e5da7425500882969d41d1801a0b620be53b6"},{"kind":"hunk","id":"hunk:fd5441f86e56882a58860d9fd4b6726049b01e9f7446bcb779952c372cad95ee"}],"notes":[]}],"checks":{"checks":[]},"stats":{"files":75,"hunks":314,"additions":7368,"deletions":2971,"binary_files":0,"non_text_files":0,"excluded_files":0},"generated_at_ms":1791417606577,"insight":null,"provenance":null,"seen":null,"brief":null},"reading":[{"chapter_id":"chapter:89136a98be06d45add90a01041fc5a70160b5d3b52458d8ad501f0ae09b3d196","needs_review":251},{"chapter_id":"chapter:b3b809b4bc64361192cf81135792681993d9bab365d362ee2e70774464613a8e","needs_review":38},{"chapter_id":"chapter:25e5e3ea69fe74055ba6c40eac782b3a27f2c4cd4fedb718f79d9b5d086de6da","needs_review":25}]} \ No newline at end of file diff --git a/crates/luxe-remote/src/render/review/tests.rs b/crates/luxe-remote/src/render/review/tests.rs new file mode 100644 index 0000000..de2a3a7 --- /dev/null +++ b/crates/luxe-remote/src/render/review/tests.rs @@ -0,0 +1,351 @@ +use super::{chapter, guide, Place}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; +use luxe_core::guided_review::{ + ChapterReading, GuidedReview, ItemNote, ReviewBrief, ReviewFile, TurnProvenance, +}; + +/// Prose marked so a test can tell it went through the markdown hook, and code by language. +struct Marked; + +impl Renderer for Marked { + fn markdown(&self, text: &str, _voice: Voice) -> String { + format!("

    md:{}

    ", escape(text)) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn code_line(&self, text: &str, language: Option<&str>) -> String { + format!("[{}:{}]", language.unwrap_or("-"), escape(text)) + } +} + +/// A real `open_review_shown` (PR #230's review on this repository), cut to three items a +/// chapter with hunks of four lines, and with the planning notes and PR body blanked. +fn captured() -> (GuidedReview, Vec) { + #[derive(serde::Deserialize)] + struct Shown { + review: GuidedReview, + reading: Vec, + } + let shown: Shown = + serde_json::from_str(include_str!("pr-230.json")).expect("the captured review parses"); + (shown.review, shown.reading) +} + +fn guide_of(review: &GuidedReview, reading: &[ChapterReading]) -> String { + guide(&Marked, review, reading, &[]) +} + +/// The section `guide` drew for chapter `index`. +fn section(html: &str, review: &GuidedReview, index: usize) -> String { + let id = review.chapters[index].id.as_str(); + let start = html.find(&format!("data-chapter=\"{id}\"")).expect("the chapter is drawn"); + let end = html[start..].find("").expect("its section closes") + start; + html[start..end].to_owned() +} + +/// Every chapter, in order, numbered against the whole and labeled by kind. +/// +/// The break this catches: numbering from zero or against the wrong total, or a kind mislabeled, +/// which is how a reader tells the core of a change from its tests. +#[test] +fn chapters_are_numbered_and_labeled_in_order() { + let (review, reading) = captured(); + let html = guide_of(&review, &reading); + let places = ["01 / 03CORE", "02 / 03TESTS", "03 / 03"]; + let at: Vec = places.iter().map(|it| html.find(it).expect(it)).collect(); + assert!(at.windows(2).all(|pair| pair[0] < pair[1]), "in the review's order"); + assert!(html.contains("SUPPORTING")); +} + +/// A walked chapter says so; the others don't. +/// +/// The break this catches: every chapter or none reading as reviewed, so the list can't say where +/// the reader got to. +#[test] +fn only_walked_chapters_say_reviewed() { + let (review, reading) = captured(); + let html = guide(&Marked, &review, &reading, &[review.chapters[1].id.clone()]); + assert!(!section(&html, &review, 0).contains("reviewed")); + assert!(section(&html, &review, 1).contains("reviewed")); +} + +/// A chapter to read shows its rationale through the markdown hook and its files, each once, in +/// the order it names them. +/// +/// The break this catches: a file listed per hunk (a chapter touching `cli.rs` twice lists it +/// twice), or the rationale skipping the TUI's markdown. +#[test] +fn a_chapter_to_read_shows_its_rationale_and_files_once() { + let (review, reading) = captured(); + let core = section(&guide_of(&review, &reading), &review, 0); + assert!(core.contains(&format!("md:{}", escape(&review.chapters[0].rationale)))); + assert_eq!(core.matches("crates/luxe-cli/src/cli.rs").count(), 1, "{core}"); + let (first, second) = (core.find("cli.rs").expect("cli.rs"), core.find("args.rs")); + assert!(second.is_some_and(|second| first < second), "the chapter's order"); + assert!(core.contains("M")); +} + +/// An impact sits under the rationale, marked as one. +/// +/// The break this catches: the impact dropped, which is the line saying what the change does to +/// everything else. +#[test] +fn an_impact_follows_the_rationale() { + let (mut review, reading) = captured(); + review.chapters[0].impact = Some("Clients see a new frame".into()); + let core = section(&guide_of(&review, &reading), &review, 0); + assert!(core.contains("

    md:Clients see a new frame

    ")); +} + +/// The reading for one chapter, overriding what the capture said. +fn reading_with( + review: &GuidedReview, + needs_review: usize, + reason: Option<&str>, +) -> ChapterReading { + let chapter_id = review.chapters[2].id.clone(); + ChapterReading { chapter_id, needs_review, reason: reason.map(str::to_owned) } +} + +/// A chapter nothing in needs the reader is one quiet line saying why, without its files. +/// +/// The break this catches: a lockfile chapter spending the page like the core change, or saying +/// nothing about why it's safe to skip. +#[test] +fn a_chapter_needing_nothing_says_why_in_one_line() { + let (review, _) = captured(); + let reading = [reading_with(&review, 0, Some("formatting only"))]; + let quiet = section(&guide_of(&review, &reading), &review, 2); + assert!(quiet.contains("formatting only \u{2014} nothing here needs you"), "{quiet}"); + assert!(quiet.contains("rv-title quiet")); + assert!(!quiet.contains("rv-files") && !quiet.contains("md:")); +} + +/// With no one reason, it still says there's nothing to read. +/// +/// The break this catches: an empty line where the reason would go. +#[test] +fn a_chapter_needing_nothing_for_mixed_reasons_says_only_that() { + let (review, _) = captured(); + let reading = [reading_with(&review, 0, None)]; + let quiet = section(&guide_of(&review, &reading), &review, 2); + assert!(quiet.contains("

    nothing here needs you

    "), "{quiet}"); +} + +/// A chapter the host said nothing about is one to read. +/// +/// The break this catches: a missing reading folding the chapter away, so a stale or partial +/// frame hides work. +#[test] +fn a_chapter_without_a_reading_is_one_to_read() { + let (review, _) = captured(); + let open = section(&guide_of(&review, &[]), &review, 2); + assert!(open.contains("rv-files") && !open.contains("rv-reason")); +} + +/// The summary leads: its intent, then its claims as a list. +/// +/// The break this catches: the brief left out, or its claims run together as one paragraph. +#[test] +fn the_summary_leads_the_guide() { + let (mut review, reading) = captured(); + let account = vec!["Adds a frame".into(), "Pins it".into()]; + review.brief = Some(ReviewBrief { intent: "Let a phone join".into(), account }); + let html = guide_of(&review, &reading); + let brief = "

    md:Let a phone join

    • md:Adds a \ + frame

    • md:Pins it

    "; + assert!(html.starts_with(&format!("
    {brief}")), "{html}"); +} + +/// Without a summary, the agent's own words lead, said to be just that. +/// +/// The break this catches: the turn's account passed off as a reviewed summary. +#[test] +fn without_a_summary_the_agents_words_lead_and_say_so() { + let (mut review, reading) = captured(); + let provenance = TurnProvenance { + requests: vec!["make it join".into()], + account: Some("I added show_open_review".into()), + ..TurnProvenance::default() + }; + review.provenance = Some(provenance); + let html = guide_of(&review, &reading); + let words = html.find("md:make it join").zip(html.find("md:I added show_open_review")); + assert!(words.is_some_and(|(asked, said)| asked < said), "{html}"); + assert!(html.contains("no summary was written for this review")); +} + +/// With neither, the guide opens on the chapters. +/// +/// The break this catches: an empty brief box above the first chapter. +#[test] +fn with_nothing_to_say_there_is_no_brief() { + let (review, reading) = captured(); + assert!(!guide_of(&review, &reading).contains("rv-brief")); +} + +/// Past eight files, the rest are counted. +/// +/// The break this catches: a forty-file chapter listing every path, or the count off by one. +#[test] +fn files_past_eight_are_counted() { + let (mut review, _) = captured(); + let template = review.files[0].clone(); + review.chapters[2].items = (0..11).map(|n| copy_of(&mut review, &template, n)).collect(); + let html = guide_of(&review, &[]); + assert_eq!(section(&html, &review, 2).matches("
  • \u{2026} 3 more
  • ")); +} + +/// A file numbered `n`, added to the review, named by the item returned. +fn copy_of( + review: &mut GuidedReview, + template: &ReviewFile, + n: usize, +) -> luxe_core::guided_review::ReviewItemRef { + let mut file = template.clone(); + file.id = serde_json::from_value(serde_json::json!(format!("file:{n}"))).expect("an id"); + file.new_path = Some(format!("docs/{n}.md").into()); + review.files.push(file.clone()); + luxe_core::guided_review::ReviewItemRef::File(file.id) +} + +/// Titles and paths are text, never markup. +/// +/// The break this catches: a branch's chapter title running script in the page. +#[test] +fn titles_are_escaped() { + let (mut review, reading) = captured(); + review.chapters[0].title = "".into(); + let html = guide_of(&review, &reading); + assert!(html.contains("<img src=x onerror=alert(1)>") && !html.contains(" &str { + match item { + luxe_core::guided_review::ReviewItemRef::File(id) => id.as_str(), + luxe_core::guided_review::ReviewItemRef::Hunk(id) => id.as_str(), + } +} + +/// The opened chapter's files with only its hunks, as the app sends them. +fn opened(review: &GuidedReview, index: usize) -> Vec { + let items = &review.chapters[index].items; + let named = |id: &str| items.iter().any(|item| item_id(item) == id); + let mut files: Vec = review.files.clone(); + files.retain_mut(|file| { + file.hunks.retain(|hunk| named(hunk.id.as_str())); + named(file.id.as_str()) || !file.hunks.is_empty() + }); + files +} + +fn open(review: &GuidedReview, index: usize) -> String { + let place = Place { number: index + 1, total: review.chapters.len(), walked: false }; + chapter(&Marked, &review.chapters[index], &opened(review, index), &place, None, &[]) +} + +/// An opened chapter names each file once above its run of hunks, in the chapter's order. +/// +/// The break this catches: the path repeated above every hunk, or a hunk drawn under the wrong +/// file. +#[test] +fn an_opened_chapter_names_each_file_once_above_its_hunks() { + let (review, _) = captured(); + let html = open(&review, 0); + assert_eq!(html.matches("

    crates/luxe-cli/src/cli.rs

    ").count(), 1); + let path = html.find("rv-file\">crates/luxe-cli/src/cli.rs").expect("the path"); + let hunks: Vec = html.match_indices("
    ").map(|(at, _)| at).collect(); + assert_eq!(hunks.len(), 3, "the chapter's three hunks"); + assert!(path < hunks[1], "cli.rs heads its hunks: {html}"); +} + +/// The guide's sentence for a hunk sits above that hunk's lines. +/// +/// The break this catches: notes dropped, or put under the wrong hunk, which narrates code the +/// reader isn't looking at. +#[test] +fn a_note_sits_above_its_hunk() { + let (mut review, _) = captured(); + let second = item_id(&review.chapters[0].items[1]).to_owned(); + review.chapters[0].notes = vec![ItemNote { item: second, note: "Reads the flag".into() }]; + let html = open(&review, 0); + let note = html.find("

    Reads the flag

    ").expect("the note"); + let hunks: Vec = html.match_indices("
    ").map(|(at, _)| at).collect(); + assert!(hunks[0] < note && note < hunks[1], "{html}"); +} + +/// The symbol a hunk sits in heads it, as the TUI's narration names it. +/// +/// The break this catches: the function name dropped, leaving only line numbers to say where the +/// change is. +#[test] +fn a_hunks_symbol_heads_it() { + let (mut review, _) = captured(); + let symbol = luxe_core::guided_review::SymbolContext { + kind: "function".into(), + name: Some("run_rpc".into()), + }; + let first = item_id(&review.chapters[0].items[0]).to_owned(); + let hunk = review.files.iter_mut().flat_map(|file| file.hunks.iter_mut()); + hunk.filter(|hunk| hunk.id.as_str() == first) + .for_each(|hunk| hunk.symbol = Some(symbol.clone())); + let html = open(&review, 0); + let named = html.find("

    run_rpc

    ").expect("the symbol"); + assert!(named < html.find("
    ").expect("a hunk"), "{html}"); +} + +/// The capture with chapter 2 naming one binary file as a whole, noted by the guide. +fn with_a_binary_file() -> GuidedReview { + let (mut review, _) = captured(); + let template = review.files[0].clone(); + let item = copy_of(&mut review, &template, 1); + let file = review.files.last_mut().expect("the copy"); + file.hunks.clear(); + file.non_text = Some(luxe_core::guided_review::NonTextChange { + kind: luxe_core::guided_review::NonTextChangeKind::Binary, + summary: "binary, 4 KiB".into(), + }); + let note = ItemNote { item: item_id(&item).to_owned(), note: "The new icon".into() }; + review.chapters[2].items = vec![item]; + review.chapters[2].notes = vec![note]; + review +} + +/// A file named as a whole shows its note and says why there are no lines. +/// +/// The break this catches: a binary or mode-only change drawn as nothing at all, so the reader +/// can't tell it was part of the chapter. +#[test] +fn a_whole_file_item_shows_its_note_and_why_there_are_no_lines() { + let review = with_a_binary_file(); + let html = open(&review, 2); + let note = html.find("

    The new icon

    ").expect("the note"); + let why = html.find("isn't text").or_else(|| html.find("isn't text")); + assert!(why.is_some_and(|why| note < why), "{html}"); +} + +/// A file with no lines to count says what changed in the guide's row instead. +/// +/// The break this catches: a binary file's row with no figures and no words. +#[test] +fn a_file_without_lines_says_what_changed() { + let review = with_a_binary_file(); + let row = section(&guide_of(&review, &[]), &review, 2); + assert!(row.contains("binary, 4 KiB"), "{row}"); +} + +/// An item whose file the app didn't send is left out rather than failing the chapter. +/// +/// The break this catches: one missing file blanking the whole chapter. +#[test] +fn an_item_without_its_file_is_left_out() { + let (review, _) = captured(); + let place = Place { number: 1, total: 3, walked: false }; + let html = chapter(&Marked, &review.chapters[0], &[], &place, None, &[]); + assert!(html.contains(&escape(&review.chapters[0].title)) && !html.contains("hunk")); +} diff --git a/crates/luxe-remote/src/render/tests.rs b/crates/luxe-remote/src/render/tests.rs new file mode 100644 index 0000000..7ce9656 --- /dev/null +++ b/crates/luxe-remote/src/render/tests.rs @@ -0,0 +1,256 @@ +use super::*; + +fn user(content: serde_json::Value) -> String { + let piece: Piece = + serde_json::from_value(serde_json::json!({ "kind": "user", "content": content })) + .expect("a user piece as the app sends it"); + render(&PlainText, &piece) +} + +/// A user message shows what the reader wrote, escaped, and not what rode along for the model. +/// +/// The break this catches: hook context shown as the reader's words, or their words written into +/// the page unescaped. +#[test] +fn a_user_message_shows_only_the_readers_words() { + let html = user(serde_json::json!([ + { "type": "text", "content": "why this?" }, + { "type": "text", "content": "[hook] Plan check: 10 tool calls" }, + ])); + assert_eq!(html, "

    why <b>this</b>?

    "); +} + +/// An image sent first keeps its place, so hook context after it is still hidden. +/// +/// The break this catches: skipping the blocks that aren't text instead of keeping them as +/// placeholders, which moves the hook's note to block 0, where it reads as the reader's own. +#[test] +fn an_image_keeps_its_place_in_a_user_message() { + let html = user(serde_json::json!([ + { "type": "image" }, + { "type": "text", "content": "[hook] Plan check: 10 tool calls" }, + ])); + assert_eq!(html, "

    1 image(s) attached

    "); +} + +/// The break this catches: images left without a trace, so a photo sent from the phone vanishes +/// from the conversation, or counted wrong, or their glyph written into the page unescaped. +#[test] +fn images_show_as_the_tuis_attached_line() { + let piece: Piece = serde_json::from_value(serde_json::json!({ + "kind": "user", + "content": [{ "type": "text", "content": "what's this?" }, { "type": "image" }, { "type": "image" }], + })) + .expect("a user piece as the app sends it"); + assert_eq!( + render(&Loud, &piece), + "

    what's this?

    & 2 image(s) attached

    " + ); +} + +/// The break this catches: a file or tree piece renamed, sent to another piece's renderer, or the +/// tree refusing the `null` changes the app sends before anything changed, so the Files tab's +/// request is refused or drawn as something else. +#[test] +fn the_file_pieces_arrive_by_their_kinds() { + let pieces = serde_json::json!([ + { "kind": "file", "file": { "path": "a.rs", "text": "x\n", "bytes": 2 } }, + { "kind": "file_failed", "error": "wrong_kind" }, + { "kind": "tree", "rows": [{ "kind": "note", "depth": 0, "text": "Loading" }], + "changes": null }, + ]); + let pieces: Vec = serde_json::from_value(pieces).expect("the pieces the app sends"); + let html: Vec = pieces.iter().map(|piece| render(&PlainText, piece)).collect(); + assert!(html[0].starts_with("
    "), "{html:?}"); +} + +/// The break this catches: a GitHub piece renamed or sent to another's renderer, or the +/// conversation refusing a request without `opened_by_you`, so the GitHub tab's request is refused. +#[test] +fn the_github_pieces_arrive_by_their_kinds() { + let issue = serde_json::json!({ "kind": "issue", "overview": { "number": 41, "title": "Crash", + "body": "", "url": "https://github.com/o/r/issues/41", "repository": "o/r", + "author": { "login": "mara", "bot": false }, "state": "open", "updated_at": 0, + "labels": [], "assignees": [], "milestone": null, "linked": [], "conversation_count": 0 } }); + let pieces = serde_json::json!([ + { "kind": "github_list", "repository": null, "now": 0, + "section": { "name": "Mine", "items": [], "error": null, "total": 0 } }, + { "kind": "github_header", "overview": issue, "now": 0 }, + { "kind": "github_overview", "overview": issue, "now": 0 }, + { "kind": "github_conversation", "entries": [], "now": 0 }, + ]); + let pieces: Vec = serde_json::from_value(pieces).expect("the pieces the app sends"); + let html: Vec = pieces.iter().map(|piece| render(&PlainText, piece)).collect(); + assert!(html[0].contains("Nothing matches this search"), "{html:?}"); + assert!(html[1].starts_with("
    "), "{html:?}"); + assert!(html[2].starts_with("

    Status"), "{html:?}"); + assert_eq!(html[3], "
    "); +} + +/// The break this catches: a review piece renamed, or one refusing a request that leaves out what +/// the app may not have (the walked chapters, a chapter's reading or whether it was walked). +#[test] +fn the_review_pieces_arrive_by_their_kinds() { + let shown: serde_json::Value = + serde_json::from_str(include_str!("review/pr-230.json")).expect("the captured review"); + let chapter = &shown["review"]["chapters"][0]; + let pieces = serde_json::json!([ + { "kind": "review_guide", "review": shown["review"], "reading": shown["reading"] }, + { "kind": "review_chapter", "chapter": chapter, "files": [], + "place": { "number": 1, "total": 3 }, "reading": null }, + ]); + let pieces: Vec = serde_json::from_value(pieces).expect("the pieces the app sends"); + let html: Vec = pieces.iter().map(|piece| render(&PlainText, piece)).collect(); + assert!(html[0].starts_with("
    "), "{html:?}"); + assert!(html[1].starts_with("
    "), "{html:?}"); +} + +/// The break this catches: a dock or diff piece renamed, so the app's request for it is refused +/// as a whole and nothing on the screen renders. +#[test] +fn the_dock_and_diff_pieces_arrive_by_their_kinds() { + let pieces = serde_json::json!([ + { "kind": "plan", "todos": { "current": null, "items": [], "pending": 0, "in_progress": 0, + "completed": 0, "blocked": 0, "total": 0, "truncated": false } }, + { "kind": "changes", "changes": { "files": [], "total_files": 0, "additions": 0, + "deletions": 0, "truncated": false } }, + { "kind": "diff", "diff": { "path": "a", "file": null, "untracked": false } }, + { "kind": "diff_failed", "error": "too_large" }, + ]); + let pieces: Vec = serde_json::from_value(pieces).expect("the pieces the app sends"); + let html: Vec = pieces.iter().map(|piece| render(&PlainText, piece)).collect(); + assert!(html[0].contains(">PLAN"), "{html:?}"); + assert!(html[1].contains(">FILES"), "{html:?}"); + assert!(html[2].contains("matches the last commit"), "{html:?}"); + assert!(html[3].contains("too large"), "{html:?}"); +} + +/// The break this catches: a message with no images given an "attached" line anyway. +#[test] +fn words_alone_say_nothing_is_attached() { + let html = + user(serde_json::json!([{ "type": "text", "content": "hi" }, { "type": "tool_result" }])); + assert_eq!(html, "

    hi

    "); +} + +/// The break this catches: a brief Luxe wrote shown whole, as a page of instructions in the +/// reader's colors. +#[test] +fn a_brief_shows_as_one_line() { + let html = user(serde_json::json!([ + { "type": "text", "content": "Draft a reply to @jon on PR 12.\n\nKeep it short." }, + ])); + assert_eq!(html, "

    Drafted a reply

    "); +} + +/// A question from a review is the reader's, so it shows, under where it was asked. +/// +/// The break this catches: the brief labeled as one line instead, losing the question the answer +/// below it is answering. +#[test] +fn a_review_question_shows_what_was_asked() { + let brief = "Guided review feedback\nSubmission: submission:1\nReview: review:2\n\ + Source revision: revision:3\nMode: Question\n\n\ + - Question · Why two passes?\n\ + \x20 Finding ID: finding:2\n\ + \x20 Evidence: src/a.rs:3 (new)\n\ + \x20 Why two passes?\n\ + Do not rewrite unrelated code."; + let html = user(serde_json::json!([{ "type": "text", "content": brief }])); + assert_eq!( + html, + "

    Asked in review \u{b7} src/a.rs:3 (new)\n\ + Why two passes?

    " + ); +} + +/// A renderer that words every status the same, with a mark and words that need escaping. +struct Loud; + +impl Renderer for Loud { + fn markdown(&self, _text: &str, _voice: Voice) -> String { + String::new() + } + + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + + fn status(&self, _facts: &StatusFacts) -> Vec { + let segment = |kind, glyph: Option<&str>, tone| StatusSegment { + kind, + glyph: glyph.map(str::to_string), + label: "<9%>".into(), + tone, + }; + vec![ + segment("context", Some("&"), StatusTone::Error), + segment("cost", None, StatusTone::Plain), + segment("model", None, StatusTone::Warning), + ] + } + + fn image_glyph(&self) -> String { + "&".into() + } + + fn mode_mark(&self, mode: &str) -> String { + if mode == "plan" { "P&" } else { "B" }.into() + } +} + +/// The break this catches: the mode button showing build's mark in plan mode (or none at all), +/// its mark or name written unescaped, or a renderer without marks leaving an empty mark behind. +#[test] +fn a_mode_wears_its_own_mark() { + let mode = |mode: &str| Piece::ModeName { mode: mode.into() }; + assert_eq!( + render(&Loud, &mode("plan")), + "P& plan" + ); + assert!(render(&Loud, &mode("")).ends_with(">B <b>")); + assert_eq!(render(&PlainText, &mode("build")), "build"); +} + +/// The break this catches: a status segment's words or mark written into the page unescaped, a +/// tone lost so a full window reads as a roomy one, or the app's facts not parsing as sent. +#[test] +fn a_status_renders_each_segment_escaped_with_its_tone() { + let piece: Piece = serde_json::from_value(serde_json::json!({ + "kind": "status", + "model": {"provider": "anthropic", "model": "claude-x"}, + "thinking": "high", + "context": {"used_tokens": 1, "context_window": 2}, + })) + .expect("a status piece as the app sends it"); + assert_eq!( + render(&Loud, &piece), + "\ + & <9%>\ + <9%>\ + <9%>" + ); +} + +/// The break this catches: the plain renderer, which a bridge has before the TUI's, showing no +/// model, so a phone can't tell what's answering. +#[test] +fn the_plain_renderer_names_the_model() { + let facts = StatusFacts { + model: Some(luxe_core::ModelRef::new("anthropic", "claude-x")), + ..StatusFacts::default() + }; + let labels: Vec<_> = PlainText.status(&facts).into_iter().map(|s| s.label).collect(); + assert_eq!(labels, ["claude-x"]); +} + +/// The break this catches: an answer rendered as sent, so a draft meant for its card shows in +/// the conversation too. +#[test] +fn an_answer_leaves_out_what_was_written_for_luxe() { + let piece = Piece::Answer { text: "```luxe-draft\nThanks, merged.\n```".into() }; + let html = render(&PlainText, &piece); + assert!(!html.contains("merged"), "{html}"); +} diff --git a/crates/luxe-remote/src/render/tree.rs b/crates/luxe-remote/src/render/tree.rs new file mode 100644 index 0000000..90c6e8a --- /dev/null +++ b/crates/luxe-remote/src/render/tree.rs @@ -0,0 +1,193 @@ +//! The Files tab's tree, drawn as the TUI's dock draws FILES. +//! +//! One row a line: a `│` guide for each level down, a chevron on a folder, the folder or language +//! mark in its hue, then the name, with a changed file's counts and letter at the right edge and a +//! dot on a closed folder that holds a change. The app decides which folders are open and sends +//! the rows it can see, so this draws and keeps nothing. + +use super::workspace::{change_status, counts}; +use super::{escape, Renderer}; +use luxe_core::workspace::{FileChangeSummary, WorkspaceChangesSummary}; + +/// The mark a file wears in the tree, and the theme role it's colored by. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FileMark { + /// The glyph, as plain text; empty for none + pub glyph: String, + /// What colors it + pub hue: MarkHue, +} + +/// The theme roles a language's mark is colored by, each a variable in the app's stylesheet. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum MarkHue { + /// The theme's warning hue + Warning, + /// The theme's info hue + Info, + /// The theme's success hue + Success, + /// The theme's error hue + Error, + /// The deepest thinking level's hue + ThinkingUltra, + /// Body text + Text, + /// Muted text, for a mark with no known hue + #[default] + Muted, +} + +impl MarkHue { + fn class(self) -> &'static str { + match self { + Self::Warning => "hue-warning", + Self::Info => "hue-info", + Self::Success => "hue-success", + Self::Error => "hue-error", + Self::ThinkingUltra => "hue-thinking-ultra", + Self::Text => "hue-text", + Self::Muted => "hue-muted", + } + } +} + +/// One row the app can see, as it sends it. +#[derive(Debug, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(crate) enum TreeRow { + /// A folder, open or closed + Folder(Entry), + /// A file + File(Entry), + /// Words where entries would be: loading, empty, or why not + Note { depth: usize, text: String }, +} + +/// A folder or file in the tree. +#[derive(Debug, serde::Deserialize)] +pub(crate) struct Entry { + /// From the project's root, `/` between folders + path: String, + name: String, + /// Folders above it, below the root + depth: usize, + /// Whether a folder shows what's in it + #[serde(default)] + open: bool, +} + +/// Every row, marked from `changes` where a file in it changed. +pub(super) fn tree( + renderer: &dyn Renderer, + rows: &[TreeRow], + changes: Option<&WorkspaceChangesSummary>, +) -> String { + let changed = changes.map_or(&[][..], |changes| changes.files.as_slice()); + let rows: String = rows.iter().map(|row| tree_row(renderer, row, changed)).collect(); + format!("
    {rows}
    ") +} + +/// The project's name behind the folder mark, then its branch, as the TUI's project section has +/// them: the branch quieter, with ` *` when the tree has changes. +pub(super) fn project_name( + renderer: &dyn Renderer, + name: &str, + branch: Option<&str>, + dirty: bool, +) -> String { + let folder = escape(&renderer.folder_mark()); + let mut out = format!("{folder}{}", escape(name)); + if let Some(branch) = branch { + let dirty = if dirty { " *" } else { "" }; + out.push_str(&format!( + "{}{}{dirty}", + escape(&renderer.branch_mark()), + escape(branch) + )); + } + out +} + +fn tree_row(renderer: &dyn Renderer, row: &TreeRow, changed: &[FileChangeSummary]) -> String { + match row { + TreeRow::Folder(folder) => { + folder_row(renderer, folder, holds_change(changed, &folder.path)) + } + TreeRow::File(file) => { + file_row(renderer, file, changed.iter().find(|change| display(change) == file.path)) + } + TreeRow::Note { depth, text } => { + format!("

    {}{}

    ", guides(*depth), escape(text)) + } + } +} + +fn folder_row(renderer: &dyn Renderer, folder: &Entry, holds_change: bool) -> String { + let chevron = if folder.open { "\u{25be}" } else { "\u{25b8}" }; + // only a closed folder hides the change, so only a closed one says it's there + let dot = match holds_change && !folder.open { + true => "\u{2022}", + false => "", + }; + format!( + "", + escape(&folder.path), + folder.open, + guides(folder.depth), + mark(&renderer.folder_mark(), "hue-secondary"), + escape(&folder.name) + ) +} + +fn file_row(renderer: &dyn Renderer, file: &Entry, change: Option<&FileChangeSummary>) -> String { + let file_mark = renderer.file_mark(&file.name); + let (name_class, right) = match change { + Some(change) => { + (format!(" change-{}", change_status(change.status)), change_cells(renderer, change)) + } + None => (String::new(), String::new()), + }; + format!( + "", + escape(&file.path), + guides(file.depth), + mark(&file_mark.glyph, file_mark.hue.class()), + escape(&file.name) + ) +} + +/// ` +6 −0 M`, as the dock's change rows end. +fn change_cells(renderer: &dyn Renderer, change: &FileChangeSummary) -> String { + format!( + "{} {}", + counts(change.additions, change.deletions), + change_status(change.status), + escape(&renderer.change_mark(change.status)) + ) +} + +fn guides(depth: usize) -> String { + "".repeat(depth) +} + +/// The mark's cells, kept even when there's no glyph so names line up with their neighbors'. +fn mark(glyph: &str, hue: &str) -> String { + format!("{}", escape(glyph)) +} + +fn holds_change(changed: &[FileChangeSummary], folder: &str) -> bool { + changed + .iter() + .any(|file| display(file).strip_prefix(folder).is_some_and(|rest| rest.starts_with('/'))) +} + +fn display(file: &FileChangeSummary) -> String { + luxe_core::paths::display(&file.path) +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/tree/tests.rs b/crates/luxe-remote/src/render/tree/tests.rs new file mode 100644 index 0000000..ba20249 --- /dev/null +++ b/crates/luxe-remote/src/render/tree/tests.rs @@ -0,0 +1,140 @@ +use super::{project_name, tree, FileMark, MarkHue, TreeRow}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; +use luxe_core::workspace::{FileChangeStatus, WorkspaceChangesSummary}; + +/// Marks that say what they are: `F` for a file, warm for Rust, `D` for a folder, a status's name. +struct Marked; + +impl Renderer for Marked { + fn markdown(&self, text: &str, _voice: Voice) -> String { + escape(text) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn change_mark(&self, status: FileChangeStatus) -> String { + format!("{status:?}") + } + fn file_mark(&self, name: &str) -> FileMark { + let hue = if name.ends_with(".rs") { MarkHue::Warning } else { MarkHue::Muted }; + FileMark { glyph: "F".into(), hue } + } + fn folder_mark(&self) -> String { + "D".into() + } + fn branch_mark(&self) -> String { + "B".into() + } +} + +/// A `workspace_updated` frame's `changes`, copied from a live session, with its file moved into +/// `src/` so a folder holds it. +const CHANGES: &str = r#"{"files": [{"path": "src/notes.txt", "status": "added", "additions": 1, "deletions": 0, "binary": false}], "total_files": 1, "additions": 1, "deletions": 0, "truncated": false}"#; + +/// The panel's bar names the project behind the tree's folder mark, and the name stays text. +/// +/// The break this catches: a drawn icon standing in for the TUI's glyph, so the bar and the tree +/// disagree at every tier, or a folder named like markup running as markup. +#[test] +fn the_project_name_wears_the_folder_mark() { + assert_eq!( + project_name(&Marked, "luxe", None, true), + "Dluxe", + "no branch, nothing after the name, dirty or not" + ); + assert!(project_name(&Marked, "x", None, false).ends_with("<b>x")); +} + +/// The branch follows the name behind its own mark, starred only when the tree has changes. +/// +/// The break this catches: the dirty star shown on a clean tree or lost on a dirty one, the branch +/// drawn without the TUI's mark, or a branch name running as markup. +#[test] +fn the_branch_follows_the_name_starred_when_dirty() { + let branch = |dirty| project_name(&Marked, "luxe", Some("remote-access"), dirty); + let lead = "Dluxe\ + Bremote-access"; + assert_eq!(branch(true), format!("{lead} *")); + assert_eq!(branch(false), format!("{lead}")); + assert!(project_name(&Marked, "x", Some(""), false).contains("<i>")); +} + +fn rows(json: serde_json::Value) -> Vec { + serde_json::from_value(json).expect("rows as the app sends them") +} + +fn changes() -> WorkspaceChangesSummary { + serde_json::from_str(CHANGES).expect("a changes summary as core sends it") +} + +/// The break this catches: a guide too many or too few, an open folder drawn closed, a mark in the +/// wrong hue, or the attribute the app's tap reads missing or crossed between folder and file. +#[test] +fn rows_read_as_the_tuis_tree() { + let rows = rows(serde_json::json!([ + { "kind": "folder", "path": "src", "name": "src", "depth": 0, "open": true }, + { "kind": "file", "path": "src/main.rs", "name": "main.rs", "depth": 1 }, + ])); + let expected = "
    \ + \ +
    "; + assert_eq!(tree(&Marked, &rows, None), expected); +} + +/// The break this catches: a changed file's counts or letter dropped, or its name not colored by +/// its status, as the TUI's tree colors it. +#[test] +fn a_changed_file_ends_with_its_counts_and_letter() { + let rows = rows(serde_json::json!([ + { "kind": "file", "path": "src/notes.txt", "name": "notes.txt", "depth": 1 }, + { "kind": "file", "path": "notes.txt", "name": "notes.txt", "depth": 0 }, + ])); + let html = tree(&Marked, &rows, Some(&changes())); + let changed = + "notes.txt \ + +1 −0 \ + Added"; + assert_eq!(html.matches(changed).count(), 1, "only the file at that path is marked: {html}"); +} + +/// The break this catches: the dot on an open folder, whose change is in plain sight, missing from +/// a closed one, or shown for a folder whose name only starts the changed file's (`sr` for `src`). +#[test] +fn a_closed_folder_holding_a_change_wears_a_dot() { + let folder = |path: &str, open: bool| serde_json::json!({ "kind": "folder", "path": path, "name": path, "depth": 0, "open": open }); + let html = |row| tree(&Marked, &rows(serde_json::json!([row])), Some(&changes())); + let dot = "•"; + assert!(html(folder("src", false)).contains(dot)); + assert!(!html(folder("src", true)).contains(dot)); + assert!(!html(folder("sr", false)).contains(dot)); +} + +/// The break this catches: a note drawn at the wrong depth, or written into the page unescaped. +#[test] +fn a_note_stands_where_entries_would() { + let rows = rows(serde_json::json!([{ "kind": "note", "depth": 2, "text": "" }])); + let expected = "

    \ + \ + <empty>

    "; + assert_eq!(tree(&Marked, &rows, None), expected); +} + +/// The break this catches: a path or name written into the attribute the app reads, or the page, +/// unescaped, so a file named with a quote breaks out of it. +#[test] +fn paths_and_names_are_escaped() { + let rows = rows(serde_json::json!([ + { "kind": "file", "path": "a\"", "name": "a\"", "depth": 0 }, + ])); + let html = tree(&Marked, &rows, None); + assert!(html.contains("data-file=\"a"<b>\""), "{html}"); + assert!(html.contains(">a"<b>"), "{html}"); +} diff --git a/crates/luxe-remote/src/render/workspace.rs b/crates/luxe-remote/src/render/workspace.rs new file mode 100644 index 0000000..fda13bb --- /dev/null +++ b/crates/luxe-remote/src/render/workspace.rs @@ -0,0 +1,108 @@ +//! The dock's sections, as the app shows them beside the transcript: the plan and the changes. +//! +//! The TUI's words and marks, laid out for a touch screen: every row of the plan wraps rather than +//! scrolling in a window of its own, and each changed file is a button that opens its diff. + +use super::{escape, Renderer}; +use luxe_core::workspace::{ + FileChangeStatus, FileChangeSummary, TodoSummary, TodoSummaryItem, WorkspaceChangesSummary, +}; +use luxe_core::TodoSummaryStatus; + +/// `PLAN 2/5`, the counts, and the checklist in the order it was written. +pub(super) fn plan(renderer: &dyn Renderer, todos: &TodoSummary) -> String { + let mut out = heading("PLAN", &format!("{}/{}", todos.completed, todos.total)); + out.push_str(&format!( + "

    {} pending \u{b7} {} active \u{b7} {} done

      ", + todos.pending, todos.in_progress, todos.completed + )); + for item in &todos.items { + out.push_str(&todo_row(renderer, item)); + } + out.push_str("
    "); + out + &more(todos.total, todos.items.len()) +} + +fn todo_row(renderer: &dyn Renderer, item: &TodoSummaryItem) -> String { + let (status, words) = todo_status(item.status); + format!( + "
  • {} {}
  • ", + escape(&renderer.todo_mark(item.status)), + escape(&item.subject) + ) +} + +/// The status as the class the stylesheet colors by, and as words for a screen reader. +fn todo_status(status: TodoSummaryStatus) -> (&'static str, &'static str) { + match status { + TodoSummaryStatus::Pending => ("pending", "to do"), + TodoSummaryStatus::InProgress => ("in-progress", "in progress"), + TodoSummaryStatus::Completed => ("completed", "done"), + TodoSummaryStatus::Blocked => ("blocked", "blocked"), + } +} + +/// `FILES 3 changed +7 −0`, and a row for each file. +pub(super) fn changes(renderer: &dyn Renderer, changes: &WorkspaceChangesSummary) -> String { + let counts = counts(changes.additions, changes.deletions); + let mut out = heading("FILES", &format!("{} changed{counts}", changes.total_files)); + if changes.files.is_empty() { + return out + "

    nothing has changed

    "; + } + out.push_str("
      "); + for file in &changes.files { + out.push_str(&change_row(renderer, file)); + } + out.push_str("
    "); + out + &more(changes.total_files, changes.files.len()) +} + +fn change_row(renderer: &dyn Renderer, file: &FileChangeSummary) -> String { + let path = escape(&luxe_core::paths::display(&file.path)); + format!( + "
  • ", + change_status(file.status), + counts(file.additions, file.deletions), + escape(&renderer.change_mark(file.status)), + ) +} + +pub(super) fn change_status(status: FileChangeStatus) -> &'static str { + match status { + FileChangeStatus::Added => "added", + FileChangeStatus::Modified => "modified", + FileChangeStatus::Deleted => "deleted", + FileChangeStatus::Renamed => "renamed", + FileChangeStatus::Untracked => "untracked", + } +} + +/// ` +6 −0`, or nothing when Git couldn't count, since `+0 −0` would claim nothing changed. +pub(super) fn counts(additions: Option, deletions: Option) -> String { + let (Some(additions), Some(deletions)) = (additions, deletions) else { + return String::new(); + }; + format!( + " +{additions} \u{2212}{deletions}" + ) +} + +/// The TUI's heading: the word cut into a badge at the depth both of these sections sit at, with +/// what it sums up riding bare beside it. +fn heading(title: &str, rest: &str) -> String { + format!("

    {title} {rest}

    ") +} + +/// `and 3 more`, for rows the snapshot left out. +fn more(total: usize, shown: usize) -> String { + match total.saturating_sub(shown) { + 0 => String::new(), + left => format!("

    and {left} more

    "), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/render/workspace/tests.rs b/crates/luxe-remote/src/render/workspace/tests.rs new file mode 100644 index 0000000..4cc42fa --- /dev/null +++ b/crates/luxe-remote/src/render/workspace/tests.rs @@ -0,0 +1,122 @@ +use super::{changes, plan}; +use crate::render::{escape, Renderer, StatusFacts, StatusSegment, Voice}; +use luxe_core::workspace::{FileChangeStatus, TodoSummary, WorkspaceChangesSummary}; +use luxe_core::TodoSummaryStatus; + +/// Marks that name their status, with markup in them so escaping shows. +struct Named; + +impl Renderer for Named { + fn markdown(&self, text: &str, _voice: Voice) -> String { + escape(text) + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn todo_mark(&self, status: TodoSummaryStatus) -> String { + format!("<{status:?}>") + } + fn change_mark(&self, status: FileChangeStatus) -> String { + format!("{status:?}") + } +} + +/// A `workspace_updated` frame's `todos`, copied from a live session. +const TODOS: &str = r#"{"current": {"id": "2", "subject": "Write the summary", "status": "in_progress", "blocked_by": []}, "items": [{"id": "1", "subject": "Read the notes", "status": "completed", "blocked_by": []}, {"id": "2", "subject": "Write the summary", "status": "in_progress", "blocked_by": []}, {"id": "3", "subject": "Check the summary", "status": "pending", "blocked_by": []}], "pending": 1, "in_progress": 1, "completed": 1, "blocked": 0, "total": 3, "truncated": false}"#; + +/// A `workspace_updated` frame's `changes`, copied from a live session. +const CHANGES: &str = r#"{"files": [{"path": "notes.txt", "status": "added", "additions": 1, "deletions": 0, "binary": false}, {"path": "README.md", "status": "untracked", "additions": 3, "deletions": 0, "binary": false}], "total_files": 2, "additions": 4, "deletions": 0, "truncated": false}"#; + +fn todos(json: &str) -> TodoSummary { + serde_json::from_str(json).expect("a todos summary as core sends it") +} + +fn changed(json: &str) -> WorkspaceChangesSummary { + serde_json::from_str(json).expect("a changes summary as core sends it") +} + +/// The break this catches: the dock's heading, counts or marks crossed or dropped, rows reordered +/// (the TUI keeps the order they were written in), a status class misspelled so the stylesheet +/// can't color it, or a mark written into the page unescaped. +#[test] +fn the_plan_reads_as_the_docks_checklist() { + let row = |status: &str, words: &str, mark: &str, subject: &str| { + format!( + "
  • <{mark}> {subject}\ +
  • " + ) + }; + let expected = format!( + "

    PLAN 1/3

    \ +

    1 pending · 1 active · 1 done

      {}{}{}
    ", + row("completed", "done", "Completed", "Read the notes"), + row("in-progress", "in progress", "InProgress", "Write the summary"), + row("pending", "to do", "Pending", "Check the summary"), + ); + assert_eq!(plan(&Named, &todos(TODOS)), expected); +} + +/// The break this catches: a trimmed plan shown as if it were all of it, or its counts crossed +/// (the live plan above has as many pending as active, so it can't tell them apart). +#[test] +fn a_trimmed_plan_says_how_much_more_there_is() { + let trimmed = TODOS + .replace("\"pending\": 1,", "\"pending\": 3,") + .replace("\"total\": 3, \"truncated\": false", "\"total\": 5, \"truncated\": true"); + let html = plan(&Named, &todos(&trimmed)); + assert!(html.contains(">3 pending · 1 active · 1 done<"), "{html}"); + assert!(html.ends_with("

    and 2 more

    "), "{html}"); +} + +/// The break this catches: a file's path, counts or mark crossed or dropped, the button without the +/// path the app opens the diff by, or the heading's totals wrong. +#[test] +fn each_change_is_a_way_into_its_diff() { + let expected = "

    FILES 2 changed \ + +4 −0

      \ +
    • \ +
    "; + assert_eq!(changes(&Named, &changed(CHANGES)), expected); +} + +/// The break this catches: counts Git couldn't make printed as `+0 −0`, which says the file +/// didn't change, when a binary file plainly did. +#[test] +fn counts_git_couldnt_make_are_left_out() { + let binary = r#"{"files": [{"path": "logo.png", "status": "modified", "additions": null, "deletions": null, "binary": true}], "total_files": 1, "additions": null, "deletions": null, "truncated": false}"#; + let html = changes(&Named, &changed(binary)); + assert!(html.starts_with( + "

    FILES 1 changed

    " + )); + assert!(html.contains(""), "{html}"); +} + +/// The break this catches: a path written into the page, or into the attribute the app reads, +/// unescaped, so a file named with a quote breaks out of it. +#[test] +fn a_path_is_escaped_everywhere_it_goes() { + let odd = CHANGES.replace("notes.txt", "a\\\".txt"); + let html = changes(&Named, &changed(&odd)); + assert!(html.contains("data-path=\"a"<b>.txt\""), "{html}"); + assert!(html.contains("a"<b>.txt"), "{html}"); +} + +/// The break this catches: an empty change list drawn as an empty box, or the trimmed tail said +/// when nothing was trimmed. +#[test] +fn nothing_changed_says_so() { + let none = + r#"{"files": [], "total_files": 0, "additions": 0, "deletions": 0, "truncated": false}"#; + assert!(changes(&Named, &changed(none)) + .ends_with("

    nothing has changed

    ")); +} diff --git a/crates/luxe-remote/src/routes.rs b/crates/luxe-remote/src/routes.rs new file mode 100644 index 0000000..f9102f6 --- /dev/null +++ b/crates/luxe-remote/src/routes.rs @@ -0,0 +1,269 @@ +//! Routes — what the bridge answers, and the one place a request is turned into a session. + +use std::path::PathBuf; +use std::sync::Arc; + +use axum::extract::{DefaultBodyLimit, Path, State, WebSocketUpgrade}; +use axum::http::StatusCode; +use axum::middleware::from_fn_with_state; +use axum::response::{Html, IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Extension, Json, Router}; + +use crate::access::{require_device, require_login}; +use crate::devices::{Device, DeviceBook}; +use crate::folders::Folder; +use crate::launch::{self, LaunchError, Launcher, Place}; +use crate::push::api as push; +use crate::sessions::{self, SessionSummary}; +use crate::REVOCATION_CHECK; + +/// What every route reads. +pub(crate) struct Bridged { + /// Where running Luxes record their sessions + pub(crate) runtime_dir: PathBuf, + /// Tailnet logins allowed in + pub(crate) logins: Vec, + /// The paired devices, read fresh on each request + pub(crate) devices: DeviceBook, + /// What starts sessions, when this bridge may + pub(crate) launcher: Option, + /// What turns messages into the app's HTML + pub(crate) renderer: Arc, + /// Which devices have which sessions open, so neither is notified about what it's showing + pub(crate) presence: crate::push::Presence, + /// The computer's tailnet name, when Tailscale gave one, which names the phone's app for it + pub(crate) machine: Option, +} + +/// Where an invitation link lands. +const PAIR_PAGE: &str = include_str!("pair.html"); + +/// The most a render request may carry. A diff or a file comes back to be rendered, and core caps +/// each at 2 MiB of text, which as a diff's JSON (an object per line, with its numbers) is several +/// times that. +const RENDER_BODY_LIMIT: usize = 16 * 1024 * 1024; + +pub(crate) fn router(bridged: Bridged) -> Router { + let bridged = Arc::new(bridged); + Router::new() + .route("/", get(crate::app::index)) + .route("/app/{*path}", get(crate::app::file)) + .route("/service-worker.js", get(crate::app::service_worker)) + .route("/theme.css", get(crate::app::theme)) + .route("/manifest.webmanifest", get(crate::home_screen::manifest)) + .route("/icons/{file}", get(crate::home_screen::icon)) + .route("/pair", get(|| async { Html(PAIR_PAGE) })) + .route("/api/pair", post(crate::pairing::pair)) + .merge(paired_only(&bridged)) + .layer(from_fn_with_state(bridged.clone(), require_login)) + .with_state(bridged) +} + +/// What only a paired device reaches: its sessions and everything about them. +fn paired_only(bridged: &Arc) -> Router> { + Router::new() + .route("/api/sessions", get(list_sessions).post(start_session)) + .route("/api/folders", get(list_folders)) + .route("/api/render", post(render).layer(DefaultBodyLimit::max(RENDER_BODY_LIMIT))) + .route("/api/sessions/{session_id}/socket", get(join_session)) + .route("/api/push", get(push::status).put(push::subscribe).delete(push::unsubscribe)) + .route_layer(from_fn_with_state(bridged.clone(), require_device)) +} + +async fn list_sessions(State(bridged): State>) -> Json> { + let runtime_dir = bridged.runtime_dir.clone(); + // reads a folder and, on Windows, asks `tasklist` about each pid + let running = tokio::task::spawn_blocking(move || sessions::running(&runtime_dir)).await; + let running = running.unwrap_or_default(); + if let Some(launcher) = &bridged.launcher { + launcher.saw(running.iter().map(|session| session.cwd.clone()).collect()).await; + } + Json(running) +} + +/// Renders what the app asks for, off the async threads: highlighting a long block is real work. +async fn render( + State(bridged): State>, + Json(request): Json, +) -> Response { + let renderer = bridged.renderer.clone(); + let pieces = request.pieces; + let html = tokio::task::spawn_blocking(move || { + pieces.iter().map(|piece| crate::render::render(&*renderer, piece)).collect() + }); + match html.await { + Ok(html) => Json(crate::render::Rendered { html }).into_response(), + Err(error) => { + tracing::error!(%error, "rendering failed"); + (StatusCode::INTERNAL_SERVER_ERROR, "rendering failed").into_response() + } + } +} + +#[derive(serde::Serialize)] +struct Folders { + folders: Vec, + /// Whether a session started now opens in herdr + herdr: bool, +} + +async fn list_folders(State(bridged): State>) -> Response { + let Some(launcher) = &bridged.launcher else { + return (StatusCode::NOT_IMPLEMENTED, "this bridge doesn't start sessions").into_response(); + }; + let (folders, herdr) = launcher.folders(&bridged.runtime_dir).await; + Json(Folders { folders, herdr }).into_response() +} + +#[derive(serde::Deserialize)] +struct StartRequest { + folder: String, +} + +#[derive(serde::Serialize)] +struct Started { + session: SessionSummary, + place: Place, +} + +/// Starts a session in the folder the device names, answering once it can be joined. +async fn start_session( + State(bridged): State>, + Extension(device): Extension, + Json(request): Json, +) -> Response { + let Some(launcher) = &bridged.launcher else { + return (StatusCode::NOT_IMPLEMENTED, "this bridge doesn't start sessions").into_response(); + }; + match start_in(launcher, &request.folder, &bridged.runtime_dir).await { + Ok((session, place)) => { + tracing::info!(session = %session.session_id, ?place, device = %device.name, "a device started a session"); + let started = Started { session: SessionSummary::from(&session), place }; + (StatusCode::CREATED, Json(started)).into_response() + } + Err(error) => { + tracing::warn!(%error, device = %device.name, "could not start a session"); + (start_failure_status(&error), error.to_string()).into_response() + } + } +} + +async fn start_in( + launcher: &Launcher, + asked: &str, + runtime_dir: &std::path::Path, +) -> Result<(luxe_core::local_endpoint::LiveSession, Place), LaunchError> { + let folder = launch::resolve_folder(asked, luxe_core::user_dirs::home_dir().as_deref())?; + launcher.start(&folder, runtime_dir).await +} + +fn start_failure_status(error: &LaunchError) -> StatusCode { + match error { + LaunchError::NotAFolder(_) => StatusCode::BAD_REQUEST, + LaunchError::Herdr(_) | LaunchError::Spawn(_) => StatusCode::BAD_GATEWAY, + LaunchError::NeverAppeared(_) => StatusCode::GATEWAY_TIMEOUT, + } +} + +/// Joins the session for the device, connecting before the upgrade so a session that has gone is +/// an HTTP error the app can show, not a socket that opens and closes. +async fn join_session( + State(bridged): State>, + Extension(device): Extension, + Path(session_id): Path, + upgrade: WebSocketUpgrade, +) -> Response { + let introduction = introduction(&bridged, &device); + match connect(bridged.runtime_dir.clone(), &session_id, &introduction).await { + Ok(stream) => { + tracing::info!(session = %session_id, device = %device.name, "a device joined"); + let here = bridged.presence.arrive(&device.id, &session_id); + let revoked = revoked(bridged.devices.clone(), device.id); + upgrade.on_upgrade(move |socket| async move { + crate::relay::relay(socket, stream, revoked).await; + drop(here); + }) + } + Err(refusal) => refusal.into_response(), + } +} + +/// Resolves once device `id` is no longer paired, checking every [`REVOCATION_CHECK`]. +/// +/// Polled because the file is changed by another process (`luxe remote devices revoke`), and a +/// revoked device's open sockets have to close, not just its next request fail. +async fn revoked(devices: DeviceBook, id: String) { + loop { + tokio::time::sleep(REVOCATION_CHECK).await; + let reader = devices.clone(); + let paired = tokio::task::spawn_blocking(move || reader.devices()).await; + let Ok(paired) = paired else { continue }; + if !paired.iter().any(|device| device.id == id) { + tracing::info!(device = %id, "closing a revoked device's socket"); + return; + } + } +} + +/// Who the bridge joins as for `device`: its name, and whether the computer's owner paired it, +/// judged by the first allowed login, where `luxe remote` puts the one Tailscale names as the +/// machine's. +fn introduction<'a>(bridged: &Bridged, device: &'a Device) -> crate::relay::Introduction<'a> { + let yours = owned_by(&bridged.logins, &device.login); + crate::relay::Introduction { name: &device.name, watch_only: false, yours } +} + +/// Whether `login` is the owner's, the first of the allowed `logins`. +fn owned_by(logins: &[String], login: &str) -> bool { + logins.first().is_some_and(|owner| owner == login) +} + +/// Connects to `session_id` and introduces the device to it as `device`. +/// +/// A refusal is the status and reason to answer with. +async fn connect( + runtime_dir: PathBuf, + session_id: &str, + device: &crate::relay::Introduction<'_>, +) -> Result { + let wanted = session_id.to_string(); + let found = tokio::task::spawn_blocking(move || sessions::find(&runtime_dir, &wanted)).await; + let Some(session) = found.ok().flatten() else { + return Err((StatusCode::NOT_FOUND, format!("no running session {session_id}"))); + }; + open(&session.address, device).await.map_err(|error| { + tracing::warn!(%error, session = %session_id, "could not join the session"); + let reason = format!("could not join session {session_id}: {error}"); + (StatusCode::BAD_GATEWAY, reason) + }) +} + +/// Connects to the endpoint at `address` and introduces the bridge there as `introduction`. +pub(crate) async fn open( + address: &str, + introduction: &crate::relay::Introduction<'_>, +) -> Result { + let connected = luxe_core::local_endpoint::connect(address).await; + let mut stream = connected.map_err(|error| error.to_string())?; + let introduced = crate::relay::introduce(&mut stream, introduction).await; + introduced.map_err(|error| error.to_string())?; + Ok(stream) +} + +#[cfg(test)] +mod tests { + use super::owned_by; + + /// A device is the owner's when the login that paired it is the first allowed, and only then. + /// + /// The break this catches: a guest let in with `--allow` treated as the owner, so their phone + /// joins the owner's session without a line, or the owner's own phone announced every time. + #[test] + fn only_the_first_allowed_login_is_the_owners() { + let logins = ["alex@github".to_string(), "sam@github".to_string()]; + assert!(owned_by(&logins, "alex@github")); + assert!(!owned_by(&logins, "sam@github")); + assert!(!owned_by(&[], "alex@github")); + } +} diff --git a/crates/luxe-remote/src/secrets.rs b/crates/luxe-remote/src/secrets.rs new file mode 100644 index 0000000..dbdf904 --- /dev/null +++ b/crates/luxe-remote/src/secrets.rs @@ -0,0 +1,25 @@ +//! Secrets — the random strings pairing hands out, and the digests the host keeps instead. + +use base64::Engine as _; +use sha2::{Digest, Sha256}; + +/// A fresh secret: 32 random bytes, URL-safe, so it fits in a link and a cookie as it is. +pub(crate) fn random_secret() -> String { + let mut bytes = [0u8; 32]; + // a guessable credential would be a hole, not an inconvenience + getrandom::fill(&mut bytes).expect("OS randomness unavailable"); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) +} + +/// A short random id to name a device by in a list. +pub(crate) fn random_id() -> String { + let mut bytes = [0u8; 4]; + getrandom::fill(&mut bytes).expect("OS randomness unavailable"); + base16ct::lower::encode_string(&bytes) +} + +/// What the host stores in place of `secret`. A plain hash is enough: the secret is 256 random +/// bits, so there is nothing to guess that a slow hash would protect. +pub(crate) fn digest(secret: &str) -> String { + base16ct::lower::encode_string(&Sha256::digest(secret.as_bytes())) +} diff --git a/crates/luxe-remote/src/service.rs b/crates/luxe-remote/src/service.rs new file mode 100644 index 0000000..996738e --- /dev/null +++ b/crates/luxe-remote/src/service.rs @@ -0,0 +1,123 @@ +//! Service — running the bridge at login, as the platform's own per-user service. +//! +//! systemd on Linux, launchd on macOS, and the `HKCU` Run key on Windows: each one is per user and +//! needs no admin rights. What runs is written down at install ([`Launch`]), with the owner's login +//! as an `--allow`, so a service started before the network (or without `tailscale` on its `PATH`, +//! as launchd's is) still knows who to let in. + +use std::path::PathBuf; + +#[cfg(any(test, target_os = "macos"))] +mod launchd; +#[cfg(any(test, windows))] +mod run_key; +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +mod systemd; + +/// What the service runs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Launch { + /// The `luxe` binary + pub program: PathBuf, + /// Its arguments: `remote` and the bridge's flags + pub args: Vec, +} + +/// Why the service couldn't be installed or removed. +#[derive(Debug, thiserror::Error)] +pub enum ServiceError { + /// A file couldn't be written or removed + #[error("could not {action} {path}: {source}")] + Io { + /// What was being done + action: &'static str, + /// To which file + path: PathBuf, + /// The operating system's reason + #[source] + source: std::io::Error, + }, + /// The platform's service manager refused + #[error("`{command}` failed: {detail}")] + Command { + /// The command line that failed + command: String, + /// What it said + detail: String, + }, + /// Nowhere to put a service: no home folder, or a platform without a per-user service manager + #[error("this system has no per-user service manager Luxe knows how to use")] + Unsupported, +} + +/// Installs and starts the service, replacing one already there. Returns where it was recorded. +pub fn install(launch: &Launch) -> Result { + #[cfg(target_os = "macos")] + return launchd::install(launch); + #[cfg(all(unix, not(target_os = "macos")))] + return systemd::install(launch); + #[cfg(windows)] + return run_key::install(launch); + #[cfg(not(any(unix, windows)))] + { + let _ = launch; + Err(ServiceError::Unsupported) + } +} + +/// Stops and removes the service. `false` when there was none. +pub fn remove() -> Result { + #[cfg(target_os = "macos")] + return launchd::remove(); + #[cfg(all(unix, not(target_os = "macos")))] + return systemd::remove(); + #[cfg(windows)] + return run_key::remove(); + #[cfg(not(any(unix, windows)))] + Err(ServiceError::Unsupported) +} + +/// Whether the service is installed. +pub fn installed() -> bool { + #[cfg(target_os = "macos")] + return launchd::installed(); + #[cfg(all(unix, not(target_os = "macos")))] + return systemd::installed(); + #[cfg(windows)] + return run_key::installed(); + #[cfg(not(any(unix, windows)))] + false +} + +/// Runs a service manager's command, turning a failure into what it said. +#[cfg(any(unix, windows))] +fn run(program: &str, args: &[&str]) -> Result<(), ServiceError> { + let command = || format!("{program} {}", args.join(" ")); + let output = std::process::Command::new(program).args(args).output(); + let output = output + .map_err(|error| ServiceError::Command { command: command(), detail: error.to_string() })?; + if output.status.success() { + return Ok(()); + } + let detail = String::from_utf8_lossy(&output.stderr).trim().to_string(); + Err(ServiceError::Command { command: command(), detail }) +} + +#[cfg(unix)] +fn write_file(path: &std::path::Path, contents: &str) -> Result<(), ServiceError> { + let io = |action| move |source| ServiceError::Io { action, path: path.to_path_buf(), source }; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(io("create the folder for"))?; + } + luxe_core::fs_atomic::replace(path, contents.as_bytes()).map_err(io("write")) +} + +/// Removes `path`, `false` when it wasn't there. +#[cfg(unix)] +fn remove_file(path: &std::path::Path) -> Result { + match std::fs::remove_file(path) { + Ok(()) => Ok(true), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(source) => Err(ServiceError::Io { action: "remove", path: path.to_path_buf(), source }), + } +} diff --git a/crates/luxe-remote/src/service/launchd.rs b/crates/luxe-remote/src/service/launchd.rs new file mode 100644 index 0000000..f9c35e5 --- /dev/null +++ b/crates/luxe-remote/src/service/launchd.rs @@ -0,0 +1,105 @@ +//! launchd — the bridge as a launch agent, `~/Library/LaunchAgents/dev.luxe.remote.plist`. + +use super::Launch; + +const LABEL: &str = "dev.luxe.remote"; + +/// Started at login, and again if it stops. +const TEMPLATE: &str = r#" + + + + Label + {label} + ProgramArguments + +{arguments} + RunAtLoad + + KeepAlive + + + +"#; + +/// The property list for `launch`. +fn plist(launch: &Launch) -> String { + let program = launch.program.to_string_lossy(); + let arguments: String = std::iter::once(program.as_ref()) + .chain(launch.args.iter().map(String::as_str)) + .map(|word| format!(" {}\n", escape(word))) + .collect(); + TEMPLATE.replace("{label}", LABEL).replace("{arguments}", &arguments) +} + +fn escape(text: &str) -> String { + text.replace('&', "&").replace('<', "<").replace('>', ">") +} + +#[cfg(target_os = "macos")] +mod manage { + use std::path::PathBuf; + + use super::super::{remove_file, run, write_file, Launch, ServiceError}; + use super::{plist, LABEL}; + + fn plist_path() -> Result { + let home = luxe_core::user_dirs::home_dir().ok_or(ServiceError::Unsupported)?; + Ok(home.join("Library").join("LaunchAgents").join(format!("{LABEL}.plist"))) + } + + /// `gui/`, the signed-in user's launchd domain. Asked of `id` because reading the uid + /// directly needs `unsafe`. + fn domain() -> Result { + let output = std::process::Command::new("id").arg("-u").output(); + let output = output.map_err(|error| ServiceError::Command { + command: "id -u".into(), + detail: error.to_string(), + })?; + Ok(format!("gui/{}", String::from_utf8_lossy(&output.stdout).trim())) + } + + pub(crate) fn install(launch: &Launch) -> Result { + let path = plist_path()?; + let domain = domain()?; + // a loaded agent keeps its old command until it is booted out + let _ = run("launchctl", &["bootout", &format!("{domain}/{LABEL}")]); + write_file(&path, &plist(launch))?; + run("launchctl", &["bootstrap", &domain, &path.to_string_lossy()])?; + Ok(path.display().to_string()) + } + + pub(crate) fn remove() -> Result { + let path = plist_path()?; + if !path.exists() { + return Ok(false); + } + let _ = run("launchctl", &["bootout", &format!("{}/{LABEL}", domain()?)]); + remove_file(&path) + } + + pub(crate) fn installed() -> bool { + plist_path().is_ok_and(|path| path.exists()) + } +} + +#[cfg(target_os = "macos")] +pub(crate) use manage::{install, installed, remove}; + +#[cfg(test)] +mod tests { + use super::*; + + /// Each word is its own argument, escaped for XML. + /// + /// The break this catches: an unescaped `&` or `<` in a path or login, which makes the plist + /// unreadable and launchd refuses it with no reason a user would find. + #[test] + fn each_word_is_an_escaped_argument() { + let launch = Launch { program: "/Users/a&b/luxe".into(), args: vec!["remote".into()] }; + let plist = plist(&launch); + assert!(plist + .contains(" /Users/a&b/luxe\n remote\n")); + assert!(plist.contains("RunAtLoad\n "), "{plist}"); + } +} diff --git a/crates/luxe-remote/src/service/run_key.rs b/crates/luxe-remote/src/service/run_key.rs new file mode 100644 index 0000000..1e90db6 --- /dev/null +++ b/crates/luxe-remote/src/service/run_key.rs @@ -0,0 +1,82 @@ +//! Run key — the bridge started at sign-in from `HKCU\...\CurrentVersion\Run`, which needs no admin. +//! +//! `luxe.exe` is a console program, so started bare it would open a console window at every +//! sign-in. PowerShell's hidden window style starts it with none showing, beyond a brief flash. + +use super::Launch; + +#[cfg(windows)] +const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; +#[cfg(windows)] +const VALUE: &str = "Luxe remote"; + +/// The command line the Run key holds for `launch`. +fn command_line(launch: &Launch) -> String { + let program = launch.program.to_string_lossy(); + let words: Vec = std::iter::once(program.as_ref()) + .chain(launch.args.iter().map(String::as_str)) + .map(|word| format!("'{}'", word.replace('\'', "''"))) + .collect(); + format!("powershell.exe -NoProfile -WindowStyle Hidden -Command \"& {}\"", words.join(" ")) +} + +#[cfg(windows)] +mod manage { + use super::super::{run, Launch, ServiceError}; + use super::{command_line, RUN_KEY, VALUE}; + + pub(crate) fn install(launch: &Launch) -> Result { + let command = command_line(launch); + run("reg", &["add", RUN_KEY, "/v", VALUE, "/t", "REG_SZ", "/d", &command, "/f"])?; + start_now(launch)?; + Ok(format!(r"{RUN_KEY}\{VALUE}")) + } + + /// The Run key only acts at the next sign-in; this one starts now, with no window. + fn start_now(launch: &Launch) -> Result<(), ServiceError> { + let mut command = tokio::process::Command::new(&launch.program); + command.args(&launch.args).stdin(std::process::Stdio::null()); + command.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); + luxe_core::program::detach_from_terminal(&mut command); + command.spawn().map(drop).map_err(|error| ServiceError::Command { + command: launch.program.display().to_string(), + detail: error.to_string(), + }) + } + + pub(crate) fn remove() -> Result { + if !installed() { + return Ok(false); + } + run("reg", &["delete", RUN_KEY, "/v", VALUE, "/f"])?; + Ok(true) + } + + pub(crate) fn installed() -> bool { + run("reg", &["query", RUN_KEY, "/v", VALUE]).is_ok() + } +} + +#[cfg(windows)] +pub(crate) use manage::{install, installed, remove}; + +#[cfg(test)] +mod tests { + use super::*; + + /// Each word reaches PowerShell as one literal string. + /// + /// The break this catches: words left bare or double-quoted, so a path with a space splits, or + /// PowerShell expands a `$` in it, or an apostrophe ends the string early. + #[test] + fn each_word_is_one_literal_string() { + let launch = Launch { + program: r"C:\Users\Alex O'Neil\luxe.exe".into(), + args: vec!["remote".into(), "--allow".into(), "$alex@github".into()], + }; + assert_eq!( + command_line(&launch), + r#"powershell.exe -NoProfile -WindowStyle Hidden -Command "& 'C:\Users\Alex O''Neil\luxe.exe' 'remote' '--allow' '$alex@github'""# + ); + } +} diff --git a/crates/luxe-remote/src/service/systemd.rs b/crates/luxe-remote/src/service/systemd.rs new file mode 100644 index 0000000..c70a15d --- /dev/null +++ b/crates/luxe-remote/src/service/systemd.rs @@ -0,0 +1,109 @@ +//! systemd — the bridge as a user unit, `~/.config/systemd/user/luxe-remote.service`. +//! +//! A user unit runs while you're signed in; with lingering on (`loginctl enable-linger`) it also +//! runs from boot. Setup doesn't turn lingering on: that is a machine-wide choice. + +use super::Launch; + +const TEMPLATE: &str = "[Unit] +Description=Luxe remote: your sessions on your own devices +After=network-online.target + +[Service] +ExecStart={command} +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=default.target +"; + +/// The unit file for `launch`. +fn unit(launch: &Launch) -> String { + let program = launch.program.to_string_lossy(); + let command: Vec = std::iter::once(program.as_ref()) + .chain(launch.args.iter().map(String::as_str)) + .map(quote) + .collect(); + TEMPLATE.replace("{command}", &command.join(" ")) +} + +/// One word of `ExecStart`, quoted the way systemd reads it: `%` and `$` would otherwise expand. +fn quote(word: &str) -> String { + let escaped = + word.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%").replace('$', "$$"); + format!("\"{escaped}\"") +} + +#[cfg(all(unix, not(target_os = "macos")))] +mod manage { + use std::path::PathBuf; + + use super::super::{remove_file, run, write_file, Launch, ServiceError}; + use super::unit; + + const UNIT: &str = "luxe-remote.service"; + + fn unit_path() -> Result { + let config = luxe_core::user_dirs::config_home().ok_or(ServiceError::Unsupported)?; + Ok(config.join("systemd").join("user").join(UNIT)) + } + + fn systemctl(args: &[&str]) -> Result<(), ServiceError> { + let mut all = vec!["--user"]; + all.extend_from_slice(args); + run("systemctl", &all) + } + + pub(crate) fn install(launch: &Launch) -> Result { + let path = unit_path()?; + write_file(&path, &unit(launch))?; + systemctl(&["daemon-reload"])?; + systemctl(&["enable", UNIT])?; + // restart, not start, so a reinstall runs the new command + systemctl(&["restart", UNIT])?; + Ok(path.display().to_string()) + } + + pub(crate) fn remove() -> Result { + let path = unit_path()?; + if !path.exists() { + return Ok(false); + } + systemctl(&["disable", "--now", UNIT])?; + let removed = remove_file(&path)?; + systemctl(&["daemon-reload"])?; + Ok(removed) + } + + pub(crate) fn installed() -> bool { + unit_path().is_ok_and(|path| path.exists()) + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +pub(crate) use manage::{install, installed, remove}; + +#[cfg(test)] +mod tests { + use super::*; + + /// The unit runs exactly the command it was given, whatever its path holds. + /// + /// The break this catches: writing words bare, so a path with a space splits in two, or a `%` + /// or `$` in it is expanded by systemd into something else. + #[test] + fn the_unit_runs_the_command_as_given() { + let launch = Launch { + program: "/home/a b/.local/bin/luxe".into(), + args: vec!["remote".into(), "--allow".into(), "50%$off@github".into()], + }; + let unit = unit(&launch); + let exec = unit.lines().find(|line| line.starts_with("ExecStart=")).unwrap(); + assert_eq!( + exec, + r#"ExecStart="/home/a b/.local/bin/luxe" "remote" "--allow" "50%%$$off@github""# + ); + assert!(unit.contains("WantedBy=default.target"), "it starts at login"); + } +} diff --git a/crates/luxe-remote/src/sessions.rs b/crates/luxe-remote/src/sessions.rs new file mode 100644 index 0000000..694f6b2 --- /dev/null +++ b/crates/luxe-remote/src/sessions.rs @@ -0,0 +1,42 @@ +//! Sessions — what a device is told about the sessions it can join. + +use std::path::Path; + +use luxe_core::local_endpoint::{self, LiveSession}; +use serde::Serialize; + +/// One joinable session, as a device sees it. +/// +/// The endpoint's address stays on this machine: a device joins through the bridge by id, and a +/// socket path or pipe name is of no use anywhere else. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub(crate) struct SessionSummary { + pub(crate) session_id: String, + pub(crate) pid: u32, + pub(crate) cwd: String, + pub(crate) luxe_version: String, +} + +impl From<&LiveSession> for SessionSummary { + fn from(session: &LiveSession) -> Self { + Self { + session_id: session.session_id.clone(), + pid: session.pid, + cwd: session.cwd.clone(), + luxe_version: session.luxe_version.clone(), + } + } +} + +/// Every session running on this machine that can be joined. +pub(crate) fn running(runtime_dir: &Path) -> Vec { + local_endpoint::running_sessions(runtime_dir).iter().map(SessionSummary::from).collect() +} + +/// The running session with exactly this id. Exact, unlike `luxe join`: a device picks from the +/// list, so a prefix would only ever be a guess. +pub(crate) fn find(runtime_dir: &Path, session_id: &str) -> Option { + local_endpoint::running_sessions(runtime_dir) + .into_iter() + .find(|session| session.session_id == session_id) +} diff --git a/crates/luxe-remote/src/tailnet.rs b/crates/luxe-remote/src/tailnet.rs new file mode 100644 index 0000000..2644f7c --- /dev/null +++ b/crates/luxe-remote/src/tailnet.rs @@ -0,0 +1,116 @@ +//! Tailnet — what Tailscale says about this machine: who owns it, and its name on the tailnet. +//! +//! Read from `tailscale status --json`, the CLI's stable machine-readable output, rather than the +//! local API's socket, whose path and permissions differ on every platform. + +use std::collections::HashMap; +use std::time::Duration; + +use serde::Deserialize; + +/// How long `tailscale status` gets; it answers from the running daemon in milliseconds. +const STATUS_TIMEOUT: Duration = Duration::from_secs(10); + +/// This machine on its tailnet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tailnet { + /// The login of the machine's owner, as Serve names it in `Tailscale-User-Login` + pub login: String, + /// The machine's name on the tailnet, such as `desk.tail1234.ts.net` + pub dns_name: String, +} + +impl Tailnet { + /// The machine's own name, the first label of [`Tailnet::dns_name`]: `desk` for + /// `desk.tail1234.ts.net`, as the tailnet's admin console and its addresses name it. + pub fn machine(&self) -> &str { + self.dns_name.split('.').next().unwrap_or(&self.dns_name) + } +} + +/// Why Tailscale couldn't say. +#[derive(Debug, thiserror::Error)] +pub enum TailnetError { + /// No `tailscale` on `PATH` + #[error("the `tailscale` command isn't installed or isn't on PATH")] + NotInstalled, + /// It ran but failed + #[error("`tailscale` failed: {0}")] + Failed(String), + /// It answered, but not with what this reads + #[error("`tailscale` said something this can't read: {0}")] + Unreadable(String), + /// Tailscale is installed but not connected + #[error("Tailscale isn't connected (it reports {0}); run `tailscale up`")] + NotRunning(String), +} + +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct Status { + backend_state: String, + #[serde(rename = "Self")] + this_machine: Option, + #[serde(default)] + user: HashMap, +} + +#[derive(Deserialize)] +struct Node { + #[serde(rename = "UserID")] + user_id: u64, + #[serde(rename = "DNSName")] + dns_name: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct User { + login_name: String, +} + +/// Asks Tailscale who owns this machine and what it is called. +pub async fn this_machine() -> Result { + parse_status(&ask_tailscale(&["status", "--json"]).await?) +} + +/// What `tailscale ` prints, for a query that answers at once. +async fn ask_tailscale(args: &[&str]) -> Result { + let program = luxe_core::program::resolve("tailscale").ok_or(TailnetError::NotInstalled)?; + let asked = tokio::process::Command::new(program).args(args).kill_on_drop(true).output(); + let output = tokio::time::timeout(STATUS_TIMEOUT, asked) + .await + .map_err(|_| TailnetError::Failed("it didn't answer within 10 seconds".into()))? + .map_err(|error| TailnetError::Failed(error.to_string()))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + return Err(TailnetError::Failed(format!("{} ({stderr})", output.status))); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) +} + +fn parse_status(json: &str) -> Result { + let status: Status = + serde_json::from_str(json).map_err(|error| TailnetError::Unreadable(error.to_string()))?; + if status.backend_state != "Running" { + return Err(TailnetError::NotRunning(status.backend_state)); + } + let node = status + .this_machine + .ok_or_else(|| TailnetError::Unreadable("it names no machine as this one".into()))?; + let owner = status.user.get(&node.user_id.to_string()).ok_or_else(|| { + TailnetError::Unreadable(format!( + "this machine's owner, user {}, isn't listed", + node.user_id + )) + })?; + let dns_name = node.dns_name.trim_end_matches('.').to_string(); + Ok(Tailnet { login: owner.login_name.clone(), dns_name }) +} + +mod serve; + +pub use serve::{publish, published, Published}; + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/tailnet/serve.rs b/crates/luxe-remote/src/tailnet/serve.rs new file mode 100644 index 0000000..86301e8 --- /dev/null +++ b/crates/luxe-remote/src/tailnet/serve.rs @@ -0,0 +1,98 @@ +//! Serve — whether Tailscale Serve already carries the bridge to the tailnet, and asking it to. +//! +//! Read from `tailscale serve status --json`, which prints Tailscale's `ServeConfig`: a `Web` map +//! from `host:port` to the handlers on each path, and a `Foreground` map holding the same shape for +//! each `tailscale serve` running in a terminal rather than in the background. + +use serde_json::Value; + +use super::{ask_tailscale, TailnetError}; + +/// What `https:///` leads to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Published { + /// The bridge on this port + Here, + /// Something else, which setup leaves alone + Elsewhere(String), + /// Nothing yet + Nowhere, +} + +/// What Serve does with `https:///`, judged against the bridge's `port`. +pub async fn published(port: u16) -> Result { + let status = ask_tailscale(&["serve", "status", "--json"]).await?; + let config: Value = serde_json::from_str(&status) + .map_err(|error| TailnetError::Unreadable(error.to_string()))?; + Ok(judge(&config, port)) +} + +/// Asks Serve to carry `https:///` to the bridge, in the background so it outlasts +/// the terminal. The output is the user's: Tailscale may print a link to turn HTTPS on for the +/// tailnet and wait while they do, so there is no timeout. +pub async fn publish(port: u16) -> Result<(), TailnetError> { + let program = luxe_core::program::resolve("tailscale").ok_or(TailnetError::NotInstalled)?; + let status = tokio::process::Command::new(program) + .args(["serve", "--bg", &target(port)]) + .kill_on_drop(true) + .status() + .await + .map_err(|error| TailnetError::Failed(error.to_string()))?; + if !status.success() { + return Err(TailnetError::Failed(format!("serve ended with {status}"))); + } + Ok(()) +} + +/// The address Serve proxies to. IPv4 because the bridge binds `127.0.0.1`, where `localhost` +/// could resolve to `::1` first. +fn target(port: u16) -> String { + format!("http://127.0.0.1:{port}") +} + +fn judge(config: &Value, port: u16) -> Published { + let roots = root_handlers(config); + if roots.iter().any(|handler| proxies_to(handler, port)) { + return Published::Here; + } + match roots.first() { + Some(handler) => Published::Elsewhere(describe(handler)), + None => Published::Nowhere, + } +} + +/// The handlers for `/` on port 443, in the background config and every foreground one. +fn root_handlers(config: &Value) -> Vec<&Value> { + let foreground = config.get("Foreground").and_then(Value::as_object); + let configs = + std::iter::once(config).chain(foreground.into_iter().flat_map(|map| map.values())); + configs + .filter_map(|config| config.get("Web")?.as_object()) + .flat_map(|web| web.iter()) + .filter(|(host_port, _)| host_port.ends_with(":443")) + .filter_map(|(_, site)| site.get("Handlers")?.get("/")) + .collect() +} + +fn proxies_to(handler: &Value, port: u16) -> bool { + let Some(proxy) = handler.get("Proxy").and_then(Value::as_str) else { + return false; + }; + let authority = proxy.strip_prefix("http://").unwrap_or(proxy).trim_end_matches('/'); + let Some((host, listening)) = authority.rsplit_once(':') else { + return false; + }; + let loopback = matches!(host, "127.0.0.1" | "localhost" | "[::1]"); + loopback && listening.parse::().is_ok_and(|listening| listening == port) +} + +fn describe(handler: &Value) -> String { + ["Proxy", "Path", "Text"] + .iter() + .find_map(|kind| handler.get(*kind).and_then(Value::as_str)) + .unwrap_or("another handler") + .to_string() +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-remote/src/tailnet/serve/tests.rs b/crates/luxe-remote/src/tailnet/serve/tests.rs new file mode 100644 index 0000000..d20fb78 --- /dev/null +++ b/crates/luxe-remote/src/tailnet/serve/tests.rs @@ -0,0 +1,56 @@ +use super::*; + +fn config(json: &str) -> Value { + serde_json::from_str(json).unwrap() +} + +/// What `tailscale serve --bg http://127.0.0.1:4519` left in `serve status --json` (1.102.3), +/// with the machine's name changed. +const OURS: &str = r#"{"TCP":{"443":{"HTTPS":true}},"Web":{"desk.tail1234.ts.net:443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:4519"}}}}}"#; + +/// A root that already proxies to the bridge's port counts as published, however the address is +/// written. +/// +/// The break this catches: matching the proxy as an exact string, so `tailscale serve 4519` +/// (which writes `localhost`) is offered again and setup tries to change a working config. +#[test] +fn a_root_proxying_to_the_bridge_is_published() { + assert_eq!(judge(&config(OURS), 4519), Published::Here); + let spelled = OURS.replace("http://127.0.0.1:4519", "http://localhost:4519/"); + assert_eq!(judge(&config(&spelled), 4519), Published::Here); +} + +/// A root that leads anywhere else is someone's, and setup leaves it alone. +/// +/// The break this catches: taking any root handler as the bridge, so setup reports a working +/// setup that serves another app (or the bridge on another port) to the phone. +#[test] +fn a_root_leading_elsewhere_is_not_the_bridge() { + let other_port = judge(&config(OURS), 4600); + assert_eq!(other_port, Published::Elsewhere("http://127.0.0.1:4519".into())); + let lan = OURS.replace("127.0.0.1", "192.168.1.9"); + assert!(matches!(judge(&config(&lan), 4519), Published::Elsewhere(_))); +} + +/// Only the HTTPS root counts: a handler on another path or port isn't what the phone opens. +/// +/// The break this catches: reading any handler, so `/files` or port 8443 reads as published and +/// the phone gets a 404 at the address setup printed. +#[test] +fn only_the_https_root_counts() { + assert_eq!(judge(&config("{}"), 4519), Published::Nowhere); + let other_path = OURS.replace(r#""/":"#, r#""/luxe":"#); + assert_eq!(judge(&config(&other_path), 4519), Published::Nowhere); + let other_port = OURS.replace(":443\"", ":8443\""); + assert_eq!(judge(&config(&other_port), 4519), Published::Nowhere); +} + +/// A `tailscale serve` running in a terminal counts too: its config sits under `Foreground`. +/// +/// The break this catches: reading only the background config, so setup offers to publish over a +/// foreground serve that already does it. +#[test] +fn a_foreground_serve_counts() { + let foreground = format!(r#"{{"Foreground":{{"a1b2":{OURS}}}}}"#); + assert_eq!(judge(&config(&foreground), 4519), Published::Here); +} diff --git a/crates/luxe-remote/src/tailnet/tests.rs b/crates/luxe-remote/src/tailnet/tests.rs new file mode 100644 index 0000000..1e961fd --- /dev/null +++ b/crates/luxe-remote/src/tailnet/tests.rs @@ -0,0 +1,36 @@ +use super::*; + +/// Trimmed from a real `tailscale status --json` (1.102.3), with the names changed. +const RUNNING: &str = r#"{"Version":"1.102.3","BackendState":"Running","Self":{"ID":"nZN73L4Wtr11CNTRL","HostName":"desk","DNSName":"desk.tail1234.ts.net.","OS":"linux","UserID":1618724369016884,"Online":true},"MagicDNSSuffix":"tail1234.ts.net","CurrentTailnet":{"Name":"alex.github","MagicDNSSuffix":"tail1234.ts.net","MagicDNSEnabled":true},"User":{"1618724369016884":{"ID":1618724369016884,"LoginName":"alex@github","DisplayName":"Alex"},"7":{"ID":7,"LoginName":"sam@github","DisplayName":"Sam"}}}"#; + +/// The owner is the user behind this machine, picked out of every user the tailnet lists. +/// +/// The break this catches: a renamed field read as missing, or taking the first user listed, so +/// the allowlist holds someone else's login and the owner is refused (or a sharer let in). +#[test] +fn the_owner_is_the_user_behind_this_machine() { + let tailnet = parse_status(RUNNING).unwrap(); + assert_eq!(tailnet.login, "alex@github"); + assert_eq!(tailnet.dns_name, "desk.tail1234.ts.net", "the trailing dot is a DNS detail"); +} + +/// The machine's name is the first label of its tailnet name, as its address leads with it. +/// +/// The break this catches: the phone's apps for two computers named by the tailnet (both +/// `tail1234`) or by the whole address, too long for a home screen label. +#[test] +fn the_machine_is_named_by_its_first_label() { + assert_eq!(parse_status(RUNNING).unwrap().machine(), "desk"); + let bare = Tailnet { login: String::new(), dns_name: "desk".into() }; + assert_eq!(bare.machine(), "desk"); +} + +/// A Tailscale that isn't connected says so, rather than handing back a stale login. +/// +/// The break this catches: ignoring the state, so a logged-out daemon's leftover user is trusted. +#[test] +fn a_disconnected_tailscale_is_not_an_owner() { + let stopped = RUNNING.replace(r#""BackendState":"Running""#, r#""BackendState":"NeedsLogin""#); + let refused = parse_status(&stopped).unwrap_err(); + assert!(matches!(refused, TailnetError::NotRunning(state) if state == "NeedsLogin")); +} diff --git a/crates/luxe-remote/src/tests.rs b/crates/luxe-remote/src/tests.rs new file mode 100644 index 0000000..7e1180a --- /dev/null +++ b/crates/luxe-remote/src/tests.rs @@ -0,0 +1,327 @@ +use std::net::SocketAddr; + +use futures::{SinkExt, StreamExt}; +use luxe_core::local_endpoint::{EndpointListener, LiveSession, Publication}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::Message; + +use super::*; + +mod access; +mod app; +mod closing; +mod home_screen; +mod push; +mod render; + +/// The device's end of a joined session socket. +type DeviceSocket = + tokio_tungstenite::WebSocketStream>; + +const SESSION: &str = "5898d57b-0000-4000-8000-000000000001"; +const OWNER: &str = "alex@github"; + +/// A session as a running Luxe shares it: an endpoint, and its record beside it. +struct FakeSession { + listener: EndpointListener, + _record: Publication, +} + +fn fake_session(runtime: &std::path::Path) -> FakeSession { + let listener = EndpointListener::bind(runtime).expect("bind the endpoint"); + let record = LiveSession { + pid: std::process::id(), + session_id: SESSION.into(), + cwd: "/work/app".into(), + address: listener.address().to_string(), + luxe_version: "0.1.3".into(), + }; + let _record = record.publish(runtime).expect("publish the record"); + FakeSession { listener, _record } +} + +/// A stand-in for `luxe --rpc`: it publishes a record for itself, then runs until stdin closes. +#[cfg(unix)] +pub(crate) fn fake_luxe(runtime: &std::path::Path) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let script = runtime.join("fake-luxe"); + let record = r#"{"pid":%s,"session_id":"started","cwd":"%s","address":"","luxe_version":"0"}"#; + let body = format!( + "#!/bin/sh\nprintf '{record}' $$ \"$PWD\" > \"{dir}/$$.json\"\ncat > /dev/null\n", + dir = runtime.display() + ); + std::fs::write(&script, body).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + script +} + +/// No stand-in on Windows, where only the tests that never start one run. +#[cfg(not(unix))] +pub(crate) fn fake_luxe(runtime: &std::path::Path) -> std::path::PathBuf { + runtime.join("no-luxe-here") +} + +/// A bridge on a free port, and the folders it reads. +struct Harness { + address: SocketAddr, + runtime: tempfile::TempDir, + devices: DeviceBook, + presence: crate::push::Presence, + _config: tempfile::TempDir, +} + +async fn harness() -> Harness { + harness_with(|bridge| bridge).await +} + +/// [`harness`], drawing through `renderer`. +async fn harness_rendering(renderer: std::sync::Arc) -> Harness { + harness_with(move |bridge| bridge.rendering_with(renderer)).await +} + +/// [`harness`], with the bridge set up by `configure` before it serves. +async fn harness_with(configure: impl FnOnce(Bridge) -> Bridge) -> Harness { + let runtime = tempfile::tempdir().unwrap(); + let config = tempfile::tempdir().unwrap(); + let devices = DeviceBook::at(config.path().join("remote.json")); + let access = Access { logins: vec![OWNER.into()], devices: devices.clone() }; + let bridge = Bridge::bind(([127, 0, 0, 1], 0).into(), runtime.path().into(), access); + let book = folders::FolderBook::at(config.path().join("remote-folders.json")); + let launcher = launch::Launcher::new(fake_luxe(runtime.path()), launch::Herdr::Off, book); + let bridge = configure(bridge.await.unwrap().with_launcher(launcher)); + let (address, presence) = (bridge.address(), bridge.presence()); + tokio::spawn(bridge.serve(std::future::pending())); + Harness { address, runtime, devices, presence, _config: config } +} + +impl Harness { + fn url(&self, path: &str) -> String { + format!("http://{}{path}", self.address) + } + + /// A request as Tailscale Serve forwards one from the owner. + fn get(&self, path: &str) -> reqwest::RequestBuilder { + reqwest::Client::new().get(self.url(path)).header("Tailscale-User-Login", OWNER) + } + + /// A paired device asking for a session in `folder`. + async fn start_in(&self, folder: &str) -> reqwest::Response { + let cookie = self.pair().await; + let request = reqwest::Client::new().post(self.url("/api/sessions")); + let request = request.header("Tailscale-User-Login", OWNER).header("cookie", cookie); + request.json(&serde_json::json!({ "folder": folder })).send().await.unwrap() + } + + /// Pairs a device through the pairing endpoint, returning its cookie. + async fn pair(&self) -> String { + let invitation = self.devices.invite().unwrap(); + let response = reqwest::Client::new() + .post(self.url("/api/pair")) + .header("Tailscale-User-Login", OWNER) + .json(&serde_json::json!({ "invitation": invitation, "name": "iPhone" })) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200, "pairing failed: {:?}", response.text().await); + let cookie = response.headers()["set-cookie"].to_str().unwrap(); + cookie.split(';').next().unwrap().to_string() + } + + /// A socket request for `session`, as the paired device sends it. + fn socket_request( + &self, + session: &str, + cookie: &str, + ) -> tokio_tungstenite::tungstenite::handshake::client::Request { + let url = format!("ws://{}/api/sessions/{session}/socket", self.address); + let mut request = url.into_client_request().unwrap(); + request.headers_mut().insert("tailscale-user-login", OWNER.parse().unwrap()); + request.headers_mut().insert("cookie", cookie.parse().unwrap()); + request + } + + /// Pairs a device and joins `session` with it: the device's socket, and the session's end. + async fn join( + &self, + session: &mut FakeSession, + ) -> (DeviceSocket, luxe_core::local_endpoint::Joined) { + let cookie = self.pair().await; + let request = self.socket_request(SESSION, &cookie); + let (device, _) = tokio_tungstenite::connect_async(request).await.expect("joined"); + let joined = session.listener.accept().await.expect("the bridge connected"); + (device, joined) + } +} + +/// The bridge will not listen beyond this machine, whatever it is asked. +/// +/// The break this catches: binding what it is given, so `--port` with a wider address, or a +/// changed default, puts every session on the local network with only the device check in front. +#[tokio::test] +async fn the_bridge_listens_on_loopback_only() { + let dir = tempfile::tempdir().unwrap(); + let access = || Access { logins: vec![], devices: DeviceBook::at(dir.path().join("r.json")) }; + let wide = Bridge::bind(([0, 0, 0, 0], 0).into(), dir.path().into(), access()).await; + assert!(matches!(wide, Err(RemoteError::NotLoopback(_)))); + let narrow = Bridge::bind(([127, 0, 0, 1], 0).into(), dir.path().into(), access()).await; + assert!(narrow.is_ok()); +} + +/// The list names running sessions and keeps their local address on this machine. +/// +/// The break this catches: listing a record whose Luxe has died, which the app shows as a session +/// that fails to open; or sending the endpoint's path, which means nothing off this machine. +#[tokio::test] +async fn the_list_shows_running_sessions_without_their_address() { + let bridge = harness().await; + let _live = fake_session(bridge.runtime.path()); + let dead = LiveSession { + pid: dead_pid(), + session_id: "dead".into(), + cwd: "/work/old".into(), + address: "nowhere".into(), + luxe_version: "0.1.2".into(), + }; + let _dead = dead.publish(bridge.runtime.path()).unwrap(); + + let cookie = bridge.pair().await; + let listed = bridge.get("/api/sessions").header("cookie", cookie).send().await.unwrap(); + let listed: serde_json::Value = listed.json().await.unwrap(); + let pid = std::process::id(); + let expected = serde_json::json!([ + { "session_id": SESSION, "pid": pid, "cwd": "/work/app", "luxe_version": "0.1.3" } + ]); + assert_eq!(listed, expected); +} + +/// The pid of a process that has exited: this test binary, asked only to list its tests. +fn dead_pid() -> u32 { + let mut gone = std::process::Command::new(std::env::current_exe().unwrap()) + .arg("--list") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + gone.wait().unwrap(); + gone.id() +} + +/// A device's socket and the session's endpoint carry each other's lines, after the bridge has +/// introduced the device by the name it paired with. +/// +/// The break this catches: either direction dropped or reframed, so the app sees nothing or the +/// session reads a frame as several broken actions; or no introduction, so the terminal names +/// the bridge's process instead of the phone; or the owner's own phone not said to be theirs, so +/// its every reconnect is announced. +#[tokio::test] +async fn a_device_socket_relays_the_protocol_both_ways() { + let bridge = harness().await; + let mut session = fake_session(bridge.runtime.path()); + let cookie = bridge.pair().await; + let request = bridge.socket_request(SESSION, &cookie); + let (mut device, _) = tokio_tungstenite::connect_async(request).await.expect("joined"); + let joined = session.listener.accept().await.expect("the bridge connected"); + let (from_device, mut to_device) = tokio::io::split(joined.stream); + + to_device.write_all(b"{\"kind\":\"ready\"}\n").await.unwrap(); + let frame = device.next().await.expect("a frame").expect("readable"); + assert_eq!(frame, Message::Text("{\"kind\":\"ready\"}".into())); + + device.send(Message::Text("{\n\"kind\": \"cancel\"\n}".into())).await.unwrap(); + let mut lines = BufReader::new(from_device).lines(); + let introduction = r#"{"kind":"introduce","content":{"name":"iPhone","yours":true}}"#; + assert_eq!(lines.next_line().await.unwrap().as_deref(), Some(introduction)); + assert_eq!(lines.next_line().await.unwrap().as_deref(), Some("{ \"kind\": \"cancel\" }")); + + device.close(None).await.unwrap(); + assert_eq!(lines.next_line().await.unwrap(), None, "the device left, so the bridge did"); +} + +/// A session older than `introduce` refuses it, and the device never sees that refusal, only what +/// follows. +/// +/// The break this catches: joining a session started before an update shows "Refused: no such +/// action `introduce`" in the phone's transcript, for a frame the bridge sent, not the phone. +#[tokio::test] +async fn an_older_sessions_refusal_of_the_introduction_stays_off_the_device() { + let bridge = harness().await; + let mut session = fake_session(bridge.runtime.path()); + let cookie = bridge.pair().await; + let request = bridge.socket_request(SESSION, &cookie); + let (mut device, _) = tokio_tungstenite::connect_async(request).await.expect("joined"); + let joined = session.listener.accept().await.expect("the bridge connected"); + let (_, mut to_device) = tokio::io::split(joined.stream); + let refusal = r#"{"kind":"action_rejected","content":{"kind":"introduce","reason":"no such action `introduce`"}}"#; + to_device.write_all(format!("{refusal}\n{{\"kind\":\"ready\"}}\n").as_bytes()).await.unwrap(); + let frame = device.next().await.expect("a frame").expect("readable"); + assert_eq!(frame, Message::Text("{\"kind\":\"ready\"}".into()), "the refusal was held back"); +} + +/// A paired device starts a session in a folder, and is told which one it can join. +/// +/// The break this catches: answering before the session is listed, or with another session, so +/// the app's join that follows finds nothing to join. +#[cfg(unix)] +#[tokio::test] +async fn a_device_starts_a_session_in_a_folder() { + let bridge = harness().await; + let folder = tempfile::tempdir().unwrap(); + let started = bridge.start_in(&folder.path().to_string_lossy()).await; + assert_eq!(started.status(), 201); + let started: serde_json::Value = started.json().await.unwrap(); + assert_eq!(started["session"]["session_id"], "started"); + assert_eq!(started["place"], "bridge"); +} + +/// A folder that isn't there is the device's mistake, said in words it can show. +/// +/// The break this catches: launching anyway and waiting out the timeout, or answering with a +/// server error the app would offer to retry. +#[tokio::test] +async fn starting_in_a_folder_that_isnt_there_is_refused() { + let bridge = harness().await; + let missing = bridge.runtime.path().join("missing"); + let refused = bridge.start_in(&missing.to_string_lossy()).await; + assert_eq!(refused.status(), 400); + assert!(refused.text().await.unwrap().contains("isn't a folder")); +} + +/// The folders a device can start in include the ones Luxe is running in, counted. +/// +/// The break this catches: listing only remembered folders, so a project open at the desk right +/// now is missing from the phone's list until it's been seen once before. +#[tokio::test] +async fn the_folder_list_names_where_luxe_is_running() { + let bridge = harness().await; + let project = tempfile::tempdir().unwrap(); + let running = LiveSession { + pid: std::process::id(), + session_id: SESSION.into(), + cwd: project.path().to_string_lossy().into_owned(), + address: String::new(), + luxe_version: "0.1.3".into(), + }; + let _record = running.publish(bridge.runtime.path()).unwrap(); + let cookie = bridge.pair().await; + let listed = bridge.get("/api/folders").header("cookie", cookie).send().await.unwrap(); + let listed: serde_json::Value = listed.json().await.unwrap(); + assert_eq!(listed["herdr"], false); + assert_eq!(listed["folders"][0]["path"], running.cwd.as_str()); + assert_eq!(listed["folders"][0]["sessions"], 1); +} + +/// A session that isn't running is a plain HTTP error, before any socket opens. +/// +/// The break this catches: upgrading first and closing at once, which the app can't tell apart +/// from a dropped connection worth retrying. +#[tokio::test] +async fn joining_a_session_that_is_not_running_is_not_found() { + let bridge = harness().await; + let cookie = bridge.pair().await; + let request = bridge.socket_request(SESSION, &cookie); + let refused = tokio_tungstenite::connect_async(request).await.expect_err("nothing to join"); + let tokio_tungstenite::tungstenite::Error::Http(response) = refused else { + panic!("expected an HTTP refusal, got {refused:?}"); + }; + assert_eq!(response.status(), 404); +} diff --git a/crates/luxe-remote/src/tests/access.rs b/crates/luxe-remote/src/tests/access.rs new file mode 100644 index 0000000..a15a852 --- /dev/null +++ b/crates/luxe-remote/src/tests/access.rs @@ -0,0 +1,138 @@ +use super::*; + +/// Nothing answers a request that didn't come through Tailscale Serve, not even the start page. +/// +/// The break this catches: checking the login only on session routes, so the bridge answers +/// anything on this machine that finds the port, and tells it what it is. +#[tokio::test] +async fn a_request_without_a_tailnet_login_is_refused() { + let bridge = harness().await; + for path in ["/", "/pair", "/api/sessions"] { + let response = reqwest::get(bridge.url(path)).await.unwrap(); + assert_eq!(response.status(), 401, "{path} answered"); + } +} + +/// A tailnet login that isn't on the allowlist is refused, though Serve vouched for it. +/// +/// The break this catches: taking any login as enough, so someone you share a node or a tailnet +/// with reaches your sessions. +#[tokio::test] +async fn a_login_not_on_the_allowlist_is_refused() { + let bridge = harness().await; + let response = reqwest::Client::new() + .get(bridge.url("/")) + .header("Tailscale-User-Login", "sam@github") + .send() + .await + .unwrap(); + assert_eq!(response.status(), 403); +} + +/// A login matches in any case: Tailscale has reported the same account with its name capitalized +/// and in lowercase. +/// +/// The break this catches: an exact comparison, which locks the owner out of their own bridge +/// when the header and `tailscale status` disagree on case. +#[tokio::test] +async fn a_login_matches_in_any_case() { + let bridge = harness().await; + let response = reqwest::Client::new() + .get(bridge.url("/")) + .header("Tailscale-User-Login", "Alex@GitHub") + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); +} + +/// The owner's login opens the start page, and sessions only from a paired device. +/// +/// The break this catches: letting the login alone reach sessions, when any process on this +/// machine can send the header straight to the loopback port. +#[tokio::test] +async fn sessions_need_a_paired_device() { + let bridge = harness().await; + assert_eq!(bridge.get("/").send().await.unwrap().status(), 200); + let unpaired = bridge.get("/api/sessions").send().await.unwrap(); + assert_eq!(unpaired.status(), 401); + let forged = bridge.get("/api/sessions").header("cookie", "luxe_device=guess").send().await; + assert_eq!(forged.unwrap().status(), 401); + let cookie = bridge.pair().await; + let paired = bridge.get("/api/sessions").header("cookie", cookie).send().await.unwrap(); + assert_eq!(paired.status(), 200); +} + +/// Pairing hands over a cookie no script can read, sent only over HTTPS and only by this site, +/// and the invitation it used is spent. +/// +/// The break this catches: a cookie a page script can read or another site can send, or an +/// invitation that pairs again. +#[tokio::test] +async fn pairing_sets_a_guarded_cookie_and_spends_the_invitation() { + let bridge = harness().await; + let invitation = bridge.devices.invite().unwrap(); + let pair = || { + reqwest::Client::new() + .post(bridge.url("/api/pair")) + .header("Tailscale-User-Login", OWNER) + .json(&serde_json::json!({ "invitation": invitation, "name": "iPad" })) + .send() + }; + let first = pair().await.unwrap(); + let cookie = first.headers()["set-cookie"].to_str().unwrap(); + for attribute in ["HttpOnly", "Secure", "SameSite=Strict"] { + assert!(cookie.contains(attribute), "{attribute} missing from {cookie}"); + } + assert_eq!(pair().await.unwrap().status(), 400, "the invitation paired twice"); + let paired = bridge.devices.devices(); + assert_eq!((paired.len(), paired[0].login.as_str()), (1, OWNER)); +} + +/// A page on another site can't open a session socket with the device's cookie. +/// +/// The break this catches: skipping the origin check on the upgrade, since a WebSocket isn't +/// held to the same-origin rule and the cookie rides along with it. +#[tokio::test] +async fn a_socket_from_another_site_is_refused() { + let bridge = harness().await; + let _session = fake_session(bridge.runtime.path()); + let cookie = bridge.pair().await; + let mut request = bridge.socket_request(SESSION, &cookie); + request.headers_mut().insert("origin", "https://evil.example".parse().unwrap()); + let refused = tokio_tungstenite::connect_async(request).await.expect_err("cross-site"); + let tokio_tungstenite::tungstenite::Error::Http(response) = refused else { + panic!("expected an HTTP refusal, got {refused:?}"); + }; + assert_eq!(response.status(), 403); + + let mut request = bridge.socket_request(SESSION, &cookie); + let own_site = format!("https://{}", bridge.address); + request.headers_mut().insert("origin", own_site.parse().unwrap()); + assert!(tokio_tungstenite::connect_async(request).await.is_ok(), "its own page is refused"); +} + +/// Only Serve's own host passes for a page's origin; a missing one is not a page at all. +/// +/// The break this catches: comparing against the wrong header, which refuses the app's own page +/// once Serve forwards the original host as `X-Forwarded-Host`. +#[test] +fn a_page_must_come_from_the_host_it_asked() { + let headers = |pairs: &[(&'static str, &str)]| { + let mut headers = axum::http::HeaderMap::new(); + for (name, value) in pairs { + headers.insert(*name, value.parse().unwrap()); + } + headers + }; + let ours = "https://home.tail0.ts.net"; + assert!(crate::access::same_site(&headers(&[])).is_ok()); + assert!(crate::access::same_site(&headers(&[("origin", ours), ("host", "home.tail0.ts.net")])) + .is_ok()); + let forwarded = + [("origin", ours), ("host", "127.0.0.1:4519"), ("x-forwarded-host", "home.tail0.ts.net")]; + assert!(crate::access::same_site(&headers(&forwarded)).is_ok()); + let elsewhere = [("origin", "https://evil.example"), ("host", "home.tail0.ts.net")]; + assert!(crate::access::same_site(&headers(&elsewhere)).is_err()); + assert!(crate::access::same_site(&headers(&[("origin", ours)])).is_err()); +} diff --git a/crates/luxe-remote/src/tests/app.rs b/crates/luxe-remote/src/tests/app.rs new file mode 100644 index 0000000..b99373c --- /dev/null +++ b/crates/luxe-remote/src/tests/app.rs @@ -0,0 +1,90 @@ +//! The app's files as a phone fetches them through the bridge. + +use super::*; + +/// The page comes with its policy, and a module with its type. +/// +/// The break this catches: serving the page without the policy, or a module as plain text, which +/// a browser refuses to run, so the app is a blank page. +#[tokio::test] +async fn the_app_is_served_with_its_policy_and_types() { + let bridge = harness().await; + let page = bridge.get("/").send().await.unwrap(); + assert_eq!(page.status(), 200); + let policy = page.headers()["content-security-policy"].to_str().unwrap().to_string(); + assert!(policy.contains("'sha256-"), "the import map isn't allowed: {policy}"); + assert!(page.text().await.unwrap().contains("type=\"importmap\"")); + + let module = bridge.get("/app/vendor/preact.mjs").send().await.unwrap(); + assert_eq!(module.status(), 200); + assert_eq!(module.headers()["content-type"], "text/javascript; charset=utf-8"); +} + +/// The break this catches: the worker served only under `/app/`, where it would cover nothing but +/// that folder and never see a notification tapped on the app's page, or served as plain text, +/// which a browser refuses to register. +#[tokio::test] +async fn the_service_worker_is_served_from_the_top() { + let bridge = harness().await; + let worker = bridge.get("/service-worker.js").send().await.unwrap(); + assert_eq!(worker.status(), 200); + assert_eq!(worker.headers()["content-type"], "text/javascript; charset=utf-8"); + assert!(worker.text().await.unwrap().contains("notificationclick")); +} + +/// A file the phone already has is answered with 304, and a changed one in full. +/// +/// The break this catches: ignoring `If-None-Match`, so every launch downloads the whole app over +/// the phone's connection; or answering 304 to any tag, so a phone keeps an old app. +#[tokio::test] +async fn a_file_the_phone_has_is_not_sent_again() { + let bridge = harness().await; + let first = bridge.get("/app/main.js").send().await.unwrap(); + let tag = first.headers()["etag"].to_str().unwrap().to_string(); + + let again = bridge.get("/app/main.js").header("if-none-match", &tag).send().await.unwrap(); + assert_eq!(again.status(), 304); + let stale = bridge.get("/app/main.js").header("if-none-match", "\"old\"").send().await.unwrap(); + assert_eq!(stale.status(), 200); +} + +/// A path that climbs out of the app's folder finds nothing. +/// +/// The break this catches: a debug build reading `app/` from disk resolving `..`, so a phone can +/// read the bridge's source or anything beside it. +#[tokio::test] +async fn app_paths_stay_in_the_app() { + let bridge = harness().await; + for path in + ["/app/..%2Fsrc%2Flib.rs", "/app/%2e%2e/Cargo.toml", "/app/vendor/..%2F..%2FCargo.toml"] + { + let response = bridge.get(path).send().await.unwrap(); + assert_eq!(response.status(), 404, "{path} answered {}", response.status()); + } +} + +/// The app's files need the owner's tailnet login like everything else. +/// +/// The break this catches: routing the files outside the login check, which shows the app to +/// anyone who can reach the port. +#[tokio::test] +async fn the_app_needs_the_owners_login() { + let bridge = harness().await; + let response = reqwest::get(bridge.url("/app/main.js")).await.unwrap(); + assert_eq!(response.status(), 401); +} + +/// The theme is a stylesheet of the active theme's properties, never cached as it stands. +/// +/// The break this catches: a missing route or the wrong type, which the browser drops, so the app +/// draws in its fallbacks whatever theme you picked; or a cached copy, so a new theme never shows. +#[tokio::test] +async fn the_theme_is_served_as_a_stylesheet() { + let bridge = harness().await; + let response = bridge.get("/theme.css").send().await.unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.headers()["content-type"], "text/css; charset=utf-8"); + assert_eq!(response.headers()["cache-control"], "no-cache"); + let css = response.text().await.unwrap(); + assert!(css.starts_with(":root {") && css.contains("color-scheme:"), "{css}"); +} diff --git a/crates/luxe-remote/src/tests/closing.rs b/crates/luxe-remote/src/tests/closing.rs new file mode 100644 index 0000000..12ef249 --- /dev/null +++ b/crates/luxe-remote/src/tests/closing.rs @@ -0,0 +1,69 @@ +//! How the bridge closes a device's socket, which is how the app tells leaving, an ended session +//! and being unpaired apart from a dropped connection. + +use super::*; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; +use tokio_tungstenite::tungstenite::protocol::CloseFrame; + +/// The close frame the device reads next, skipping any protocol frames before it. +async fn close_frame(device: &mut DeviceSocket) -> Option { + let wait = async { + loop { + match device.next().await { + Some(Ok(Message::Close(frame))) => return frame, + Some(Ok(_)) => continue, + other => panic!("the socket ended without a close frame: {other:?}"), + } + } + }; + tokio::time::timeout(REVOCATION_CHECK * 3, wait).await.expect("the socket stayed open") +} + +/// A device that closes its socket gets the close answered, not a dropped connection. +/// +/// The break this catches: dropping the socket as soon as the device's close arrives, so every +/// time the app leaves it sees code 1006 and can't tell that from losing the network. +#[tokio::test] +async fn a_device_that_closes_is_answered() { + let bridge = harness().await; + let mut session = fake_session(bridge.runtime.path()); + let (mut device, _joined) = bridge.join(&mut session).await; + + device.close(None).await.unwrap(); + let answer = tokio::time::timeout(REVOCATION_CHECK, device.next()).await.expect("no answer"); + assert!(matches!(answer, Some(Ok(Message::Close(_)))), "answered with {answer:?}"); +} + +/// A session that ends closes the device's socket normally, saying why. +/// +/// The break this catches: dropping the socket when the session goes, so the app retries a +/// session that is gone instead of saying it ended. +#[tokio::test] +async fn a_session_that_ends_closes_the_socket_normally() { + let bridge = harness().await; + let mut session = fake_session(bridge.runtime.path()); + let (mut device, joined) = bridge.join(&mut session).await; + + drop(joined); + let frame = close_frame(&mut device).await.expect("a close code"); + assert_eq!(frame.code, CloseCode::Normal); + assert_eq!(frame.reason, "the session ended"); +} + +/// Unpairing a connected device closes its open socket, with the code that says so. +/// +/// The break this catches: checking the device only at the upgrade, so a lost phone keeps +/// steering a session it already joined; or closing it like any other ending, so the app keeps +/// retrying with a credential that will never work again instead of asking to be paired. +#[tokio::test] +async fn an_unpaired_device_is_told_so() { + let bridge = harness().await; + let mut session = fake_session(bridge.runtime.path()); + let (mut device, _joined) = bridge.join(&mut session).await; + + let id = bridge.devices.devices()[0].id.clone(); + bridge.devices.revoke(&id).unwrap(); + let frame = close_frame(&mut device).await.expect("a close code"); + assert_eq!(u16::from(frame.code), relay::UNPAIRED); + assert_eq!(frame.reason, "this device was unpaired"); +} diff --git a/crates/luxe-remote/src/tests/home_screen.rs b/crates/luxe-remote/src/tests/home_screen.rs new file mode 100644 index 0000000..5334e8e --- /dev/null +++ b/crates/luxe-remote/src/tests/home_screen.rs @@ -0,0 +1,98 @@ +//! What a phone fetches to keep the app on its home screen. + +use std::sync::{Arc, Mutex}; + +use super::*; + +/// A renderer that draws a stand-in icon and remembers the sides it was asked for. +#[derive(Default)] +struct Sketch { + asked: Mutex>, +} + +impl Renderer for Sketch { + fn markdown(&self, text: &str, _voice: Voice) -> String { + text.into() + } + fn tool_glyph(&self, _tool: &str) -> String { + String::new() + } + fn status(&self, _facts: &StatusFacts) -> Vec { + Vec::new() + } + fn home_icon(&self, side: u32, _colors: TileColors) -> Option> { + self.asked.lock().unwrap().push(side); + Some(b"\x89PNG stand-in".to_vec()) + } +} + +/// A bridge named for its computer serves the page and the manifest named for it, so a phone +/// paired with two computers keeps two apps it can tell apart. +/// +/// The break this catches: the name set on the bridge but never reaching the routes that read it, +/// so both computers' apps are added as "Luxe". +#[tokio::test] +async fn a_named_bridge_serves_an_app_named_for_its_computer() { + let bridge = harness_with(|bridge| bridge.named("desk")).await; + let page = bridge.get("/").send().await.unwrap().text().await.unwrap(); + assert!(page.contains(r#""#), "{page}"); + let manifest = bridge.get("/manifest.webmanifest").send().await.unwrap(); + let manifest: serde_json::Value = manifest.json().await.unwrap(); + assert_eq!(manifest["short_name"], "desk"); +} + +/// The page links the manifest and the icon, and the manifest asks to open on its own. +/// +/// The break this catches: the links or the manifest's `display` dropped, so the home screen +/// keeps a bookmark that opens in Safari with its bars, under a screenshot for an icon. +#[tokio::test] +async fn the_page_and_manifest_make_a_home_screen_app() { + let bridge = harness().await; + let page = bridge.get("/").send().await.unwrap().text().await.unwrap(); + assert!(page.contains(""), "{page}"); + assert!(page.contains(""), "{page}"); + + let manifest = bridge.get("/manifest.webmanifest").send().await.unwrap(); + assert_eq!(manifest.headers()["content-type"], "application/manifest+json"); + let manifest: serde_json::Value = manifest.json().await.unwrap(); + assert_eq!(manifest["display"], "standalone"); +} + +/// The manifest and icon come to the tailnet login alone, without the paired-device cookie. +/// +/// The break this catches: the two routed behind the device check, where a manifest fetched +/// without credentials (as browsers fetch one) is turned away and the app installs bare. +#[tokio::test] +async fn the_manifest_and_icon_need_no_paired_device() { + let sketch = Arc::new(Sketch::default()); + let bridge = harness_rendering(sketch.clone()).await; + assert_eq!(bridge.get("/manifest.webmanifest").send().await.unwrap().status(), 200); + let icon = bridge.get("/icons/180.png").send().await.unwrap(); + assert_eq!(icon.status(), 200); + assert_eq!(icon.headers()["content-type"], "image/png"); + assert_eq!(*sketch.asked.lock().unwrap(), [180]); +} + +/// Only the sizes the page and manifest name are drawn. +/// +/// The break this catches: any size drawn on request, so one URL asks the bridge for a bitmap of +/// gigabytes. +#[tokio::test] +async fn an_icon_is_drawn_only_at_the_sizes_offered() { + let sketch = Arc::new(Sketch::default()); + let bridge = harness_rendering(sketch.clone()).await; + for file in ["100000.png", "181.png", "180.svg", "180"] { + let response = bridge.get(&format!("/icons/{file}")).send().await.unwrap(); + assert_eq!(response.status(), 404, "{file}"); + } + assert!(sketch.asked.lock().unwrap().is_empty()); +} + +/// A renderer with no art answers no icon, rather than an empty image. +/// +/// The break this catches: a 200 with no bytes, which iOS keeps as a blank icon. +#[tokio::test] +async fn a_renderer_without_art_has_no_icon() { + let bridge = harness().await; + assert_eq!(bridge.get("/icons/180.png").send().await.unwrap().status(), 404); +} diff --git a/crates/luxe-remote/src/tests/push.rs b/crates/luxe-remote/src/tests/push.rs new file mode 100644 index 0000000..ee81a36 --- /dev/null +++ b/crates/luxe-remote/src/tests/push.rs @@ -0,0 +1,117 @@ +//! A device turning its notifications on and off, and what reaches it once they're on. + +use super::*; +use crate::push::Recording; + +fn from_safari() -> serde_json::Value { + serde_json::from_str(crate::push::FROM_SAFARI).unwrap() +} + +/// A request to `/api/push` from the device with `cookie`. +fn push(bridge: &Harness, method: reqwest::Method, cookie: &str) -> reqwest::RequestBuilder { + let request = reqwest::Client::new().request(method, bridge.url("/api/push")); + request.header("Tailscale-User-Login", OWNER).header("cookie", cookie) +} + +async fn status(bridge: &Harness, cookie: &str) -> serde_json::Value { + let response = push(bridge, reqwest::Method::GET, cookie).send().await.unwrap(); + assert_eq!(response.status(), 200); + response.json().await.unwrap() +} + +/// The break this catches: the push routes outside the paired-device check, so anything on this +/// machine that sets the login header can point the bridge's notifications somewhere. +#[tokio::test] +async fn only_a_paired_device_reaches_its_notifications() { + let bridge = harness().await; + for method in [reqwest::Method::GET, reqwest::Method::PUT, reqwest::Method::DELETE] { + let response = push(&bridge, method.clone(), "luxe_device=nope").send().await.unwrap(); + assert_eq!(response.status(), 401, "{method}"); + } +} + +/// A device gets the key, subscribes, is told it has, and turns it off again. +/// +/// The break this catches: any of the three routes not reaching the device book, or the status +/// reporting another device's subscription or none at all. +#[tokio::test] +async fn a_device_turns_its_notifications_on_and_off() { + let bridge = harness().await; + let cookie = bridge.pair().await; + let before = status(&bridge, &cookie).await; + assert_eq!(before["subscribed"], false); + let key = before["key"].as_str().unwrap(); + assert_eq!(key.len(), 87, "65 bytes, base64url without padding: {key}"); + + let on = push(&bridge, reqwest::Method::PUT, &cookie).json(&from_safari()).send().await; + assert_eq!(on.unwrap().status(), 204); + let on = serde_json::json!({ "key": key, "subscribed": true }); + assert_eq!(status(&bridge, &cookie).await, on); + assert_eq!(status(&bridge, &bridge.pair().await).await["subscribed"], false, "another's"); + + let off = push(&bridge, reqwest::Method::DELETE, &cookie).send().await.unwrap(); + assert_eq!(off.status(), 204); + assert_eq!(status(&bridge, &cookie).await["subscribed"], false); +} + +/// The break this catches: a subscription kept without the check, so a paired device can have +/// the bridge post to a machine on the local network. +#[tokio::test] +async fn a_subscription_to_somewhere_else_is_refused() { + let bridge = harness().await; + let cookie = bridge.pair().await; + let mut elsewhere = from_safari(); + elsewhere["endpoint"] = "https://192.168.1.1/push".into(); + let response = push(&bridge, reqwest::Method::PUT, &cookie).json(&elsewhere).send().await; + let response = response.unwrap(); + assert_eq!(response.status(), 400); + assert!(response.text().await.unwrap().contains("192.168.1.1")); + assert_eq!(status(&bridge, &cookie).await["subscribed"], false); +} + +/// Waits up to a minute (of a paused clock, where one is) for `done`. +async fn eventually(mut done: impl FnMut() -> bool) -> bool { + let waited = tokio::time::timeout(std::time::Duration::from_secs(60), async { + while !done() { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + }); + waited.await.is_ok() +} + +/// The break this catches: presence not taken on join, so a phone showing a session is buzzed +/// about it, or never let go, so it's never notified about that session again. +#[tokio::test] +async fn a_device_counts_as_looking_while_its_socket_is_open() { + let bridge = harness().await; + let mut session = fake_session(bridge.runtime.path()); + let (socket, _joined) = bridge.join(&mut session).await; + let id = bridge.devices.devices()[0].id.clone(); + assert!(bridge.presence.is_here(&id, SESSION)); + drop(socket); + assert!(eventually(|| !bridge.presence.is_here(&id, SESSION)).await, "still looking"); +} + +const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#; + +/// The bridge joins the session once a device subscribes, and posts to that device when a +/// prompt is left waiting, titled with the computer the bridge is named for. +/// +/// The break this catches: the notifications never started with the bridge, or started without +/// the device book, the courier or the computer's name it was given. +#[tokio::test(start_paused = true)] +async fn a_prompt_left_waiting_reaches_a_subscribed_device() { + let courier = std::sync::Arc::new(Recording::taking()); + let posting = courier.clone(); + let bridge = harness_with(move |bridge| bridge.notifying_through(posting).named("desk")).await; + let mut session = fake_session(bridge.runtime.path()); + let cookie = bridge.pair().await; + let on = push(&bridge, reqwest::Method::PUT, &cookie).json(&from_safari()).send().await; + assert_eq!(on.unwrap().status(), 204); + + let mut watcher = session.listener.accept().await.expect("the bridge joined to watch"); + watcher.stream.write_all(format!("{PERMISSION}\n").as_bytes()).await.unwrap(); + assert!(eventually(|| !courier.sent().is_empty()).await, "nothing was posted"); + assert_eq!(courier.sent(), [from_safari()["endpoint"].as_str().unwrap()]); + assert!(courier.titles()[0].ends_with(" \u{00b7} desk"), "{:?}", courier.titles()); +} diff --git a/crates/luxe-remote/src/tests/render.rs b/crates/luxe-remote/src/tests/render.rs new file mode 100644 index 0000000..ba36903 --- /dev/null +++ b/crates/luxe-remote/src/tests/render.rs @@ -0,0 +1,68 @@ +//! `/api/render` as the app calls it. + +use super::*; + +fn render_request(bridge: &Harness, cookie: Option<&str>) -> reqwest::RequestBuilder { + let request = reqwest::Client::new().post(bridge.url("/api/render")); + let request = request.header("Tailscale-User-Login", OWNER); + match cookie { + Some(cookie) => request.header("cookie", cookie), + None => request, + } +} + +/// The break this catches: the route left outside the device check, so the owner's tailnet login +/// alone gets the host to do work for an unpaired browser. +#[tokio::test] +async fn rendering_needs_a_paired_device() { + let bridge = harness().await; + let pieces = serde_json::json!({ "pieces": [{ "kind": "answer", "text": "hi" }] }); + let response = render_request(&bridge, None).json(&pieces).send().await.unwrap(); + assert_eq!(response.status(), 401); +} + +/// Each piece comes back in the order it was asked for, by the bridge's renderer. +/// +/// The break this catches: answers out of order, so the app puts one message's HTML under +/// another; or a renderer that doesn't escape, which the plain one a bridge starts with must. +#[tokio::test] +async fn pieces_come_back_in_order() { + let bridge = harness().await; + let cookie = bridge.pair().await; + let pieces = serde_json::json!({ "pieces": [ + { "kind": "answer", "text": "**one** " }, + { "kind": "tool", "name": "bash" }, + { "kind": "user", "content": [{ "type": "text", "content": "three" }] }, + ]}); + let response = render_request(&bridge, Some(&cookie)).json(&pieces).send().await.unwrap(); + assert_eq!(response.status(), 200); + let rendered: serde_json::Value = response.json().await.unwrap(); + assert_eq!( + rendered, + serde_json::json!({ "html": [ + "

    **one** <i>

    ", + "", + "

    three

    ", + ]}) + ); +} + +/// The break this catches: the route left at axum's 2 MiB default, so a large diff, which comes +/// back to be rendered as JSON several times its text's size, is refused and never shows. +#[tokio::test] +async fn a_large_diff_can_be_rendered() { + let bridge = harness().await; + let cookie = bridge.pair().await; + let line = serde_json::json!({ "old_line": null, "new_line": 1, "kind": "addition", "text": "x".repeat(80) }); + let hunk = serde_json::json!({ "id": "hunk:a", "old_range": { "start": 0, "count": 0 }, + "new_range": { "start": 1, "count": 30000 }, "heading": null, "symbol": null, + "lines": vec![line; 30_000], "noise": "semantic" }); + let file = serde_json::json!({ "id": "file:a", "old_path": null, "new_path": "big.txt", + "status": "added", "language": null, "additions": 30000, "deletions": 0, "hunks": [hunk], + "binary": false, "generated": false, "non_text": null }); + let piece = serde_json::json!({ "kind": "diff", "diff": { "path": "big.txt", "file": file, "untracked": false } }); + let body = serde_json::json!({ "pieces": [piece] }); + assert!(body.to_string().len() > 3 * 1024 * 1024, "the request outgrows the default"); + let response = render_request(&bridge, Some(&cookie)).json(&body).send().await.unwrap(); + assert_eq!(response.status(), 200); +} diff --git a/crates/luxe-tools/Cargo.toml b/crates/luxe-tools/Cargo.toml index c3e4548..05129f2 100644 --- a/crates/luxe-tools/Cargo.toml +++ b/crates/luxe-tools/Cargo.toml @@ -11,12 +11,14 @@ homepage.workspace = true # Provides tool implementations (read, write, edit, bash, grep, glob, etc.). [dependencies] -luxe-core = { path = "../luxe-core", version = "0.1.2" } +luxe-core = { path = "../luxe-core", version = "0.1.3" } thiserror = { workspace = true } tracing = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } +# Running a search's phrasings at once +futures = { workspace = true } async-trait = "0.1" anyhow = "1" reqwest = { workspace = true } diff --git a/crates/luxe-tools/src/exa_mcp.rs b/crates/luxe-tools/src/exa_mcp.rs index 378552b..84f67d4 100644 --- a/crates/luxe-tools/src/exa_mcp.rs +++ b/crates/luxe-tools/src/exa_mcp.rs @@ -6,11 +6,10 @@ //! `EXA_API_KEY` still wins, since an explicit choice outranks the fallback, but having none does //! not mean having no web search. //! -//! The endpoint also carries the whole feature set worth having: several query variations in one -//! call, domain include/exclude, a published-after date, and extracted highlights. That last one is -//! the point. Returning titles and snippets forces the model into one `web_fetch` per result — a -//! research question becomes six round-trips. Returning the passages *with* the results answers it -//! in one. +//! The endpoint also carries the whole feature set worth having: domain include/exclude, a +//! published-after date, and extracted highlights. That last one is the point. Returning titles +//! and snippets forces the model into one `web_fetch` per result — a research question becomes six +//! round-trips. Returning the passages *with* the results answers it in one. use serde::Deserialize; @@ -98,9 +97,8 @@ impl SearchBackend for ExaMcpBackend { self.search_with(query, n, options).await } - /// Exa's advanced tool takes every phrasing as one call, which is the whole reason it is the - /// default: one round-trip covers the angles a caller would otherwise pay for separately. - fn batches_queries(&self) -> bool { + /// The keyless endpoint turns away even two searches at once. + fn one_phrasing_at_a_time(&self) -> bool { true } } @@ -113,9 +111,6 @@ fn build_arguments(query: &str, n: usize, options: &SearchOptions) -> serde_json "type": "auto", }); let map = arguments.as_object_mut().expect("object literal"); - if !options.also.is_empty() { - map.insert("additionalQueries".into(), serde_json::json!(options.also)); - } if !options.include_domains.is_empty() { map.insert("includeDomains".into(), serde_json::json!(options.include_domains)); } @@ -147,6 +142,16 @@ struct RpcResult { content: Vec, #[serde(default, rename = "isError")] is_error: bool, + #[serde(default, rename = "_meta")] + meta: RpcMeta, +} + +/// Flags the endpoint sets beside a result. +#[derive(Debug, Default, Deserialize)] +struct RpcMeta { + /// Set on the reply to a search over the keyless limit, which carries a notice, not results + #[serde(default, rename = "ai.exa/rateLimited")] + rate_limited: bool, } #[derive(Debug, Deserialize)] @@ -173,6 +178,11 @@ fn parse_response(body: &str, n: usize) -> Result, WebError> { let result = envelope .result .ok_or_else(|| WebError::Backend("exa mcp returned no result".to_string()))?; + if result.meta.rate_limited { + return Err(WebError::Backend( + "exa's free search is rate limited; try again shortly, or set EXA_API_KEY".to_string(), + )); + } if result.is_error { let detail = result.content.first().map(|c| c.text.as_str()).unwrap_or("unknown error"); return Err(WebError::Backend(format!("exa mcp: {detail}"))); @@ -291,150 +301,4 @@ fn flush(hits: &mut [SearchHit], snippet: &mut String) { } #[cfg(test)] -mod tests { - use super::*; - - /// The exact shape the live endpoint returned during development. - const SAMPLE: &str = "event: message\n\ - data: {\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"Title: select in tokio - Rust\\nURL: https://docs.rs/tokio/latest/tokio/macro.select.html\\nPublished: N/A\\nAuthor: N/A\\nHighlights:\\n## Cancellation safety\\n...\\nCancellation safety describes what happens when a future is dropped.\\nTitle: Second Result\\nURL: https://example.com/two\\nHighlights:\\nSomething else entirely.\"}]}}\n"; - - #[test] - fn an_sse_framed_response_parses_into_hits_with_content() { - let hits = parse_response(SAMPLE, 10).expect("parses"); - assert_eq!(hits.len(), 2); - assert_eq!(hits[0].title, "select in tokio - Rust"); - assert_eq!(hits[0].url, "https://docs.rs/tokio/latest/tokio/macro.select.html"); - assert!( - hits[0].snippet.contains("Cancellation safety describes"), - "the extracted passage rides along, so no follow-up fetch is needed: {:?}", - hits[0].snippet - ); - assert!(!hits[0].snippet.contains("N/A"), "metadata noise is dropped"); - assert_eq!(hits[1].url, "https://example.com/two"); - } - - #[test] - fn the_result_count_is_honored() { - assert_eq!(parse_response(SAMPLE, 1).expect("parses").len(), 1); - } - - #[test] - fn a_bare_json_body_parses_too() { - let bare = - r#"{"result":{"content":[{"type":"text","text":"Title: A\nURL: https://a.test"}]}}"#; - assert_eq!(parse_response(bare, 5).expect("parses")[0].url, "https://a.test"); - } - - #[test] - fn an_rpc_error_surfaces_instead_of_an_empty_result() { - let body = r#"{"error":{"code":-32602,"message":"bad arguments"}}"#; - let error = parse_response(body, 5).expect_err("must not look like zero results"); - assert!(error.to_string().contains("bad arguments"), "{error}"); - } - - #[test] - fn a_tool_level_error_surfaces_too() { - let body = - r#"{"result":{"isError":true,"content":[{"type":"text","text":"rate limited"}]}}"#; - let error = parse_response(body, 5).expect_err("isError must not be silently empty"); - assert!(error.to_string().contains("rate limited"), "{error}"); - } - - #[test] - fn garbage_is_an_error_not_a_panic() { - assert!(parse_response("not json at all", 5).is_err()); - assert!(parse_response("", 5).is_err()); - } - - #[test] - fn options_map_onto_exas_argument_names() { - let options = SearchOptions { - also: vec!["second phrasing".into()], - include_domains: vec!["arxiv.org".into()], - exclude_domains: vec!["spam.example".into()], - recency: Some(crate::web::Recency::Month), - include_content: true, - }; - let args = build_arguments("tokio cancellation", 7, &options); - - assert_eq!(args["query"], "tokio cancellation"); - assert_eq!(args["numResults"], 7); - assert_eq!(args["additionalQueries"][0], "second phrasing"); - assert_eq!(args["includeDomains"][0], "arxiv.org"); - assert_eq!(args["excludeDomains"][0], "spam.example"); - assert_eq!(args["startPublishedDate"].as_str().expect("a date").len(), 10); - assert_eq!(args["enableHighlights"], true); - } - - #[test] - fn defaults_stay_off_the_wire_and_the_count_is_clamped() { - let args = build_arguments("q", 999, &SearchOptions::default()); - assert_eq!(args["numResults"], 25, "clamped to Exa's practical ceiling"); - for absent in [ - "additionalQueries", - "includeDomains", - "excludeDomains", - "startPublishedDate", - "enableHighlights", - ] { - assert!(args.get(absent).is_none(), "{absent} must not be sent by default"); - } - } - - /// The advanced tool answers with a JSON envelope, not the basic tool's prose. Parsing only the - /// prose form meant every advanced search reported "No results" while the endpoint was - /// returning perfectly good ones. - #[test] - fn the_advanced_tools_json_envelope_parses() { - let inner = serde_json::json!({ - "requestId": "abc", - "results": [ - { - "id": "https://tokio.rs/x", - "url": "https://tokio.rs/x", - "title": "Select | Tokio", - "text": "Select | Tokio\n\n# Select\n\nSo far...", - "highlights": ["Futures can implement Drop to clean up.", "oneshot is cancel safe."], - "publishedDate": "2026-03-18T00:00:00.000Z" - }, - { "url": "", "title": "dropped: no url" } - ] - }) - .to_string(); - let body = serde_json::json!({ - "result": { "content": [{ "type": "text", "text": inner }] } - }) - .to_string(); - - let hits = parse_response(&body, 10).expect("parses"); - assert_eq!(hits.len(), 1, "a result with no url is not a result"); - assert_eq!(hits[0].title, "Select | Tokio"); - assert_eq!(hits[0].url, "https://tokio.rs/x"); - assert!(hits[0].snippet.contains("cancel safe"), "highlights lead: {:?}", hits[0].snippet); - assert!(!hits[0].snippet.contains('\n'), "whitespace is collapsed"); - } - - #[test] - fn a_result_without_highlights_falls_back_to_its_text() { - let inner = serde_json::json!({ - "results": [{ "url": "https://a.test", "title": "A", "text": " body text here " }] - }) - .to_string(); - let body = serde_json::json!({ "result": { "content": [{ "text": inner }] } }).to_string(); - let hits = parse_response(&body, 5).expect("parses"); - assert_eq!(hits[0].snippet, "body text here"); - } - - #[test] - fn a_long_snippet_is_clipped() { - let long = "word ".repeat(400); - let inner = serde_json::json!({ - "results": [{ "url": "https://a.test", "title": "A", "text": long }] - }) - .to_string(); - let body = serde_json::json!({ "result": { "content": [{ "text": inner }] } }).to_string(); - let hits = parse_response(&body, 5).expect("parses"); - assert!(hits[0].snippet.chars().count() <= SNIPPET_CHARS + 1, "clipped"); - assert!(hits[0].snippet.ends_with('…')); - } -} +mod tests; diff --git a/crates/luxe-tools/src/exa_mcp/tests.rs b/crates/luxe-tools/src/exa_mcp/tests.rs new file mode 100644 index 0000000..ff88650 --- /dev/null +++ b/crates/luxe-tools/src/exa_mcp/tests.rs @@ -0,0 +1,152 @@ +use super::*; + +/// The exact shape the live endpoint returned during development. +const SAMPLE: &str = "event: message\n\ + data: {\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"Title: select in tokio - Rust\\nURL: https://docs.rs/tokio/latest/tokio/macro.select.html\\nPublished: N/A\\nAuthor: N/A\\nHighlights:\\n## Cancellation safety\\n...\\nCancellation safety describes what happens when a future is dropped.\\nTitle: Second Result\\nURL: https://example.com/two\\nHighlights:\\nSomething else entirely.\"}]}}\n"; + +/// A burst of searches crossed the keyless limit; this is the reply, copied from the endpoint. +const RATE_LIMITED: &str = "event: message\ndata: {\"result\":{\"_meta\":{\"ai.exa/rateLimited\":true},\"content\":[{\"type\":\"text\",\"text\":\"You've hit Exa's free MCP rate limit. To continue using without limits, create your own Exa API key.\\n\\nFix: Create API key at https://dashboard.exa.ai/api-keys , and then update Exa MCP URL to this https://mcp.exa.ai/mcp?exaApiKey=YOUR_EXA_API_KEY\"}]},\"jsonrpc\":\"2.0\",\"id\":1}\n"; + +#[test] +fn an_sse_framed_response_parses_into_hits_with_content() { + let hits = parse_response(SAMPLE, 10).expect("parses"); + assert_eq!(hits.len(), 2); + assert_eq!(hits[0].title, "select in tokio - Rust"); + assert_eq!(hits[0].url, "https://docs.rs/tokio/latest/tokio/macro.select.html"); + assert!( + hits[0].snippet.contains("Cancellation safety describes"), + "the extracted passage rides along, so no follow-up fetch is needed: {:?}", + hits[0].snippet + ); + assert!(!hits[0].snippet.contains("N/A"), "metadata noise is dropped"); + assert_eq!(hits[1].url, "https://example.com/two"); +} + +#[test] +fn the_result_count_is_honored() { + assert_eq!(parse_response(SAMPLE, 1).expect("parses").len(), 1); +} + +#[test] +fn a_bare_json_body_parses_too() { + let bare = r#"{"result":{"content":[{"type":"text","text":"Title: A\nURL: https://a.test"}]}}"#; + assert_eq!(parse_response(bare, 5).expect("parses")[0].url, "https://a.test"); +} + +#[test] +fn an_rpc_error_surfaces_instead_of_an_empty_result() { + let body = r#"{"error":{"code":-32602,"message":"bad arguments"}}"#; + let error = parse_response(body, 5).expect_err("must not look like zero results"); + assert!(error.to_string().contains("bad arguments"), "{error}"); +} + +#[test] +fn a_tool_level_error_surfaces_too() { + let body = r#"{"result":{"isError":true,"content":[{"type":"text","text":"rate limited"}]}}"#; + let error = parse_response(body, 5).expect_err("isError must not be silently empty"); + assert!(error.to_string().contains("rate limited"), "{error}"); +} + +/// The break this catches: a rate-limited reply, which isn't flagged as an error, reading as a +/// search that found nothing, so the model gave up on a question the web could answer. +#[test] +fn a_rate_limited_reply_is_an_error_not_zero_results() { + let error = parse_response(RATE_LIMITED, 5).expect_err("rate limited is not empty"); + assert!(error.to_string().contains("rate limit"), "{error}"); + assert!(error.to_string().contains("EXA_API_KEY"), "says how to lift it: {error}"); +} + +/// The break this catches: the keyless endpoint getting a search's phrasings all at once, which +/// crosses its limit and turns all but one of them away. +#[test] +fn the_keyless_endpoint_gets_one_phrasing_at_a_time() { + assert!(ExaMcpBackend::new().one_phrasing_at_a_time()); +} + +#[test] +fn garbage_is_an_error_not_a_panic() { + assert!(parse_response("not json at all", 5).is_err()); + assert!(parse_response("", 5).is_err()); +} + +#[test] +fn options_map_onto_exas_argument_names() { + let options = SearchOptions { + include_domains: vec!["arxiv.org".into()], + exclude_domains: vec!["spam.example".into()], + recency: Some(crate::web::Recency::Month), + include_content: true, + }; + let args = build_arguments("tokio cancellation", 7, &options); + + assert_eq!(args["query"], "tokio cancellation"); + assert_eq!(args["numResults"], 7); + assert_eq!(args["highlightsQuery"], "tokio cancellation", "passages for this phrasing"); + assert_eq!(args["includeDomains"][0], "arxiv.org"); + assert_eq!(args["excludeDomains"][0], "spam.example"); + assert_eq!(args["startPublishedDate"].as_str().expect("a date").len(), 10); + assert_eq!(args["enableHighlights"], true); +} + +#[test] +fn defaults_stay_off_the_wire_and_the_count_is_clamped() { + let args = build_arguments("q", 999, &SearchOptions::default()); + assert_eq!(args["numResults"], 25, "clamped to Exa's practical ceiling"); + for absent in ["includeDomains", "excludeDomains", "startPublishedDate", "enableHighlights"] { + assert!(args.get(absent).is_none(), "{absent} must not be sent by default"); + } +} + +/// The advanced tool answers with a JSON envelope, not the basic tool's prose. Parsing only the +/// prose form meant every advanced search reported "No results" while the endpoint was returning +/// perfectly good ones. +#[test] +fn the_advanced_tools_json_envelope_parses() { + let inner = serde_json::json!({ + "requestId": "abc", + "results": [ + { + "id": "https://tokio.rs/x", + "url": "https://tokio.rs/x", + "title": "Select | Tokio", + "text": "Select | Tokio\n\n# Select\n\nSo far...", + "highlights": ["Futures can implement Drop to clean up.", "oneshot is cancel safe."], + "publishedDate": "2026-03-18T00:00:00.000Z" + }, + { "url": "", "title": "dropped: no url" } + ] + }) + .to_string(); + let body = serde_json::json!({ "result": { "content": [{ "type": "text", "text": inner }] } }) + .to_string(); + + let hits = parse_response(&body, 10).expect("parses"); + assert_eq!(hits.len(), 1, "a result with no url is not a result"); + assert_eq!(hits[0].title, "Select | Tokio"); + assert_eq!(hits[0].url, "https://tokio.rs/x"); + assert!(hits[0].snippet.contains("cancel safe"), "highlights lead: {:?}", hits[0].snippet); + assert!(!hits[0].snippet.contains('\n'), "whitespace is collapsed"); +} + +#[test] +fn a_result_without_highlights_falls_back_to_its_text() { + let inner = serde_json::json!({ + "results": [{ "url": "https://a.test", "title": "A", "text": " body text here " }] + }) + .to_string(); + let body = serde_json::json!({ "result": { "content": [{ "text": inner }] } }).to_string(); + let hits = parse_response(&body, 5).expect("parses"); + assert_eq!(hits[0].snippet, "body text here"); +} + +#[test] +fn a_long_snippet_is_clipped() { + let long = "word ".repeat(400); + let inner = + serde_json::json!({ "results": [{ "url": "https://a.test", "title": "A", "text": long }] }) + .to_string(); + let body = serde_json::json!({ "result": { "content": [{ "text": inner }] } }).to_string(); + let hits = parse_response(&body, 5).expect("parses"); + assert!(hits[0].snippet.chars().count() <= SNIPPET_CHARS + 1, "clipped"); + assert!(hits[0].snippet.ends_with('…')); +} diff --git a/crates/luxe-tools/src/grep.rs b/crates/luxe-tools/src/grep.rs index ad613bc..d95f092 100644 --- a/crates/luxe-tools/src/grep.rs +++ b/crates/luxe-tools/src/grep.rs @@ -52,7 +52,7 @@ fn grep_schema() -> ToolSchema { }, "glob": { "type": "string", - "description": "Glob pattern to filter files (e.g., '*.rs')" + "description": "Glob pattern to filter files (e.g., '*.rs'); a leading '!' excludes (e.g., '!tests/**')" }, "outputMode": { "type": "string", diff --git a/crates/luxe-tools/src/grep/tests.rs b/crates/luxe-tools/src/grep/tests.rs index 866c2bd..3f29609 100644 --- a/crates/luxe-tools/src/grep/tests.rs +++ b/crates/luxe-tools/src/grep/tests.rs @@ -76,6 +76,18 @@ fn the_native_search_honors_ignores_and_reports_ripgrep_shaped_rows() { assert!(native_search(cwd, &search("no_such_text")).expect("valid").is_empty()); } +/// A glob that starts with `!` leaves out what it names and searches the rest. +/// +/// The break this catches: `!` taken literally, so an exclude glob matched no file and the +/// search came back empty. +#[test] +fn an_exclude_glob_searches_everything_else() { + let dir = repo_with_build_output(); + let excluding = Search { glob: Some("!target/**"), all: true, ..search("needle") }; + let rows = native_search(dir.path(), &excluding).expect("a valid regex"); + assert_eq!(rows, vec!["src/main.rs:1:let needle = 1;"]); +} + /// Context lines use `-` where a match uses `:`, the way ripgrep prints them, so a reader (and /// the model) can tell the answer from its surroundings. #[test] diff --git a/crates/luxe-tools/src/question.rs b/crates/luxe-tools/src/question.rs index 129ac18..3cf21b8 100644 --- a/crates/luxe-tools/src/question.rs +++ b/crates/luxe-tools/src/question.rs @@ -174,6 +174,7 @@ impl Tool for QuestionTool { QuestionReply::Cancelled } }; + let _ = cx.event_tx.send(Event::PromptClosed { id: id.as_str().to_string() }).await; let outcome = match reply { QuestionReply::Answered(answers) => QuestionOutcome::Answered(answers), diff --git a/crates/luxe-tools/src/question/tests.rs b/crates/luxe-tools/src/question/tests.rs index e459936..20c8b22 100644 --- a/crates/luxe-tools/src/question/tests.rs +++ b/crates/luxe-tools/src/question/tests.rs @@ -89,6 +89,9 @@ async fn interactive_question_emits_event_and_awaits_the_brokered_answer() { assert!(!result.is_error); let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") }; assert!(text.contains("The user answered: Rust"), "got: {text}"); + // Any other front-end showing the question is told to take it down + let closed = event_rx.recv().await; + assert_eq!(closed, Some(Event::PromptClosed { id: id.as_str().to_string() })); } /// A multi-select answer reaches the model as a list, and comes back off the text as the same diff --git a/crates/luxe-tools/src/tavily.rs b/crates/luxe-tools/src/tavily.rs index 80511e2..a16f8e9 100644 --- a/crates/luxe-tools/src/tavily.rs +++ b/crates/luxe-tools/src/tavily.rs @@ -129,7 +129,6 @@ mod tests { exclude_domains: vec!["reddit.com".to_string()], recency: Some(crate::web::Recency::Year), include_content: true, - ..Default::default() }); assert_eq!(body["query"], "tokio"); assert_eq!(body["max_results"], 3); diff --git a/crates/luxe-tools/src/web/search.rs b/crates/luxe-tools/src/web/search.rs index 8da3683..98974b6 100644 --- a/crates/luxe-tools/src/web/search.rs +++ b/crates/luxe-tools/src/web/search.rs @@ -26,9 +26,9 @@ pub trait SearchBackend: Send + Sync { Vec::new() } - /// Whether one call covers every phrasing in [`SearchOptions::also`]. A plain search API does - /// not, so the caller runs them itself and merges. - fn batches_queries(&self) -> bool { + /// Whether a search's phrasings must run one after another. A rate-limited endpoint turns a + /// burst away, so its phrasings wait their turn instead of failing together. + fn one_phrasing_at_a_time(&self) -> bool { false } } @@ -112,8 +112,6 @@ impl Recency { /// exposed all of them would cost more context than the answers it fetches. #[derive(Debug, Clone, Default)] pub struct SearchOptions { - /// Extra query phrasings run alongside the main one, widening coverage in a single call. - pub also: Vec, /// Only these domains. pub include_domains: Vec, /// Never these domains. @@ -170,48 +168,82 @@ pub async fn create_backend(config: &WebConfig) -> Result } } +/// What a search found, and a note for each phrasing that failed. +#[derive(Debug)] +pub(super) struct Searched { + pub(super) hits: Vec, + pub(super) skipped: Vec, +} + /// Run every phrasing the caller asked for and merge the results. /// -/// One call per query for a backend that takes one query, first-seen order preserved and duplicate -/// URLs dropped — the same page found by two phrasings is one result, and the earlier phrasing is -/// the one that ranked it. A phrasing that errors is skipped rather than sinking the whole search; -/// the error only surfaces when *nothing* answered. +/// Each phrasing is its own search, so each gets its own ranking and its own passages; one call +/// carrying the extras ranks everything against the first. A phrasing that errors is skipped and +/// named rather than sinking the whole search; the error only fails it when *nothing* answered. pub(super) async fn run_search( backend: &dyn SearchBackend, queries: &[String], n: usize, options: &SearchOptions, -) -> Result, WebError> { - let Some((query, also)) = queries.split_first() else { - return Ok(Vec::new()); - }; - if backend.batches_queries() || also.is_empty() { - return backend.search(query, n, options).await; - } - - // The extras are already in `queries`; passing them again would double a backend that reads - // both. One phrasing at a time, and the option set minus the fan-out it has already served. - let single = SearchOptions { also: Vec::new(), ..options.clone() }; - let mut merged: Vec = Vec::new(); +) -> Result { + let mut lists = Vec::new(); + let mut skipped = Vec::new(); let mut last_error = None; - for query in queries { - match backend.search(query, n, &single).await { - Ok(hits) => { - for hit in hits { - if !merged.iter().any(|seen| seen.url == hit.url) { - merged.push(hit); - } - } + for (query, answer) in queries.iter().zip(search_each(backend, queries, n, options).await) { + match answer { + Ok(hits) => lists.push(hits), + Err(error) => { + skipped.push(format!("\"{query}\" wasn't searched: {error}")); + last_error = Some(error); } - Err(error) => last_error = Some(error), } } - match (merged.is_empty(), last_error) { + let hits = interleave(lists, n); + match (hits.is_empty(), last_error) { (true, Some(error)) => Err(error), - _ => Ok(merged), + _ => Ok(Searched { hits, skipped }), } } +/// Each phrasing's answer, in order: all at once, or in turn where the backend needs that. +async fn search_each( + backend: &dyn SearchBackend, + queries: &[String], + n: usize, + options: &SearchOptions, +) -> Vec, WebError>> { + if !backend.one_phrasing_at_a_time() { + let searches = queries.iter().map(|query| backend.search(query, n, options)); + return futures::future::join_all(searches).await; + } + let mut answers = Vec::with_capacity(queries.len()); + for query in queries { + answers.push(backend.search(query, n, options).await); + } + answers +} + +/// Up to `n` hits, rank by rank: the top of each list, then the next of each. +/// +/// So every phrasing is represented. A page two phrasings found is one result, at its first +/// position, and its second slot goes to the next page. +fn interleave(lists: Vec>, n: usize) -> Vec { + let mut lists: Vec<_> = lists.into_iter().map(Vec::into_iter).collect(); + let mut merged: Vec = Vec::new(); + while merged.len() < n { + let rank: Vec = lists.iter_mut().filter_map(Iterator::next).collect(); + if rank.is_empty() { + break; + } + for hit in rank { + if merged.len() < n && !merged.iter().any(|seen| seen.url == hit.url) { + merged.push(hit); + } + } + } + merged +} + /// web_search tool — pluggable search backend. pub struct WebSearchTool { pub(super) config: Arc>, @@ -272,14 +304,13 @@ impl Tool for WebSearchTool { async fn run(&self, args: serde_json::Value, _cx: &ToolContext) -> ToolResultData { let queries = search_queries(&args); - let Some((_, also)) = queries.split_first() else { + if queries.is_empty() { return ToolResultData::error("Error: 'query' (or 'queries') is required"); - }; + } let n = (args.get("n").and_then(serde_json::Value::as_u64).unwrap_or(5) as usize) .clamp(1, MAX_RESULTS); let options = SearchOptions { - also: also.to_vec(), include_content: args .get("content") .and_then(serde_json::Value::as_bool) @@ -297,8 +328,10 @@ impl Tool for WebSearchTool { Err(e) => return ToolResultData::error(format!("Backend error: {e}")), }; match run_search(backend.as_ref(), &queries, n, &options).await { - Ok(hits) => { - ToolResultData::text(render_hits(&queries, &hits, &backend.honors(&options))) + Ok(searched) => { + let mut caveats = backend.honors(&options); + caveats.extend(searched.skipped); + ToolResultData::text(render_hits(&queries, &searched.hits, &caveats)) } Err(e) => ToolResultData::error(format!("Search failed: {e}")), } @@ -336,3 +369,6 @@ pub(super) fn domain_filters(args: &serde_json::Value) -> SearchOptions { } options } + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-tools/src/web/search/tests.rs b/crates/luxe-tools/src/web/search/tests.rs new file mode 100644 index 0000000..19c56d6 --- /dev/null +++ b/crates/luxe-tools/src/web/search/tests.rs @@ -0,0 +1,142 @@ +use super::*; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +/// A backend with a result list per phrasing, which fails the phrasings it has no list for and +/// keeps what it was asked and how many searches it ran at once. +struct ByPhrasing { + lists: HashMap<&'static str, Vec<&'static str>>, + asked: Mutex>, + in_turn: bool, + running: AtomicUsize, + most_at_once: AtomicUsize, +} + +impl ByPhrasing { + fn new(lists: &[(&'static str, &[&'static str])]) -> Self { + let lists = lists.iter().map(|(query, urls)| (*query, urls.to_vec())).collect(); + let (running, most_at_once) = (AtomicUsize::new(0), AtomicUsize::new(0)); + Self { lists, asked: Mutex::new(Vec::new()), in_turn: false, running, most_at_once } + } + + fn in_turn(self) -> Self { + Self { in_turn: true, ..self } + } + + /// Holds a search open long enough for another to start beside it, if one is going to. + async fn overlap(&self) { + let now = self.running.fetch_add(1, Ordering::SeqCst) + 1; + self.most_at_once.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + self.running.fetch_sub(1, Ordering::SeqCst); + } +} + +#[async_trait] +impl SearchBackend for ByPhrasing { + async fn search( + &self, + query: &str, + n: usize, + _options: &SearchOptions, + ) -> Result, WebError> { + self.asked.lock().expect("no panic holds this lock").push((query.to_string(), n)); + self.overlap().await; + let Some(urls) = self.lists.get(query) else { + return Err(WebError::Backend(format!("no answer for {query}"))); + }; + Ok(urls.iter().take(n).map(|url| hit(url)).collect()) + } + + fn one_phrasing_at_a_time(&self) -> bool { + self.in_turn + } +} + +fn hit(url: &str) -> SearchHit { + SearchHit { title: url.to_string(), url: url.to_string(), snippet: String::new() } +} + +fn queries(list: &[&str]) -> Vec { + list.iter().map(|query| query.to_string()).collect() +} + +async fn searched(backend: &ByPhrasing, asked: &[&str], n: usize) -> Searched { + let answer = run_search(backend, &queries(asked), n, &SearchOptions::default()).await; + answer.expect("a phrasing answered") +} + +async fn urls(backend: &ByPhrasing, asked: &[&str], n: usize) -> Vec { + searched(backend, asked, n).await.hits.into_iter().map(|hit| hit.url).collect() +} + +/// Every phrasing gets its share of the results: the top of each, then the next of each. +/// +/// The break this catches: the first phrasing's results filling every slot, so the other +/// phrasings were searched and then thrown away. +#[tokio::test] +async fn each_phrasing_gets_its_share_of_the_results() { + let backend = ByPhrasing::new(&[("one", &["a1", "a2", "a3"]), ("two", &["b1", "b2", "b3"])]); + assert_eq!(urls(&backend, &["one", "two"], 4).await, ["a1", "b1", "a2", "b2"]); + // An odd count stops partway through a rank + assert_eq!(urls(&backend, &["one", "two"], 3).await, ["a1", "b1", "a2"]); +} + +/// Each phrasing is searched on its own and asked for the full count, so its own ranking and +/// passages come back. +/// +/// The break this catches: the extra phrasings riding along on the first one's search, which +/// ranks and extracts passages against the first phrasing alone. +#[tokio::test] +async fn each_phrasing_is_searched_on_its_own() { + let backend = ByPhrasing::new(&[("one", &["a1"]), ("two", &["b1"])]); + urls(&backend, &["one", "two"], 5).await; + let mut asked = backend.asked.lock().expect("no panic holds this lock").clone(); + asked.sort(); + assert_eq!(asked, [("one".to_string(), 5), ("two".to_string(), 5)]); +} + +/// Phrasings run together unless the backend needs them in turn, and then never overlap. +/// +/// The break this catches: a burst at a rate-limited endpoint, which turned all but one phrasing +/// away; or phrasings waiting on each other where nothing needed them to. +#[tokio::test] +async fn phrasings_wait_their_turn_only_where_the_backend_needs_it() { + let lists: &[(&str, &[&str])] = &[("one", &["a1"]), ("two", &["b1"]), ("three", &["c1"])]; + let together = ByPhrasing::new(lists); + urls(&together, &["one", "two", "three"], 5).await; + assert_eq!(together.most_at_once.load(Ordering::SeqCst), 3, "all at once"); + let in_turn = ByPhrasing::new(lists).in_turn(); + assert_eq!(urls(&in_turn, &["one", "two", "three"], 5).await, ["a1", "b1", "c1"]); + assert_eq!(in_turn.most_at_once.load(Ordering::SeqCst), 1, "one at a time"); +} + +/// A page two phrasings found is one result, and its slot goes to the next page. +/// +/// The break this catches: the same URL listed twice, spending a result on a repeat. +#[tokio::test] +async fn a_page_found_twice_is_one_result() { + let backend = ByPhrasing::new(&[("one", &["same", "a2"]), ("two", &["same", "b2"])]); + assert_eq!(urls(&backend, &["one", "two"], 3).await, ["same", "a2", "b2"]); +} + +/// A phrasing that fails is skipped and named while another answers; the error only fails the +/// search when none did. +/// +/// The break this catches: one failed phrasing sinking a search the others answered, a failure +/// the model is never told about, or every phrasing failing and the reply reading as no results. +#[tokio::test] +async fn a_failed_phrasing_is_named_and_skipped_until_none_answer() { + let backend = ByPhrasing::new(&[("works", &["a1"])]); + let partial = searched(&backend, &["broken", "works"], 5).await; + assert_eq!(partial.hits.len(), 1); + assert_eq!( + partial.skipped, + ["\"broken\" wasn't searched: backend error: no answer for broken"] + ); + let broken = queries(&["broken"]); + let all_failed = run_search(&backend, &broken, 5, &SearchOptions::default()).await; + let error = all_failed.expect_err("nothing answered"); + assert!(error.to_string().contains("no answer for broken"), "{error}"); +} diff --git a/crates/luxe-tools/tests/live_exa_mcp.rs b/crates/luxe-tools/tests/live_exa_mcp.rs index 90f2db5..0d1653b 100644 --- a/crates/luxe-tools/tests/live_exa_mcp.rs +++ b/crates/luxe-tools/tests/live_exa_mcp.rs @@ -46,7 +46,7 @@ async fn the_keyless_endpoint_returns_usable_results_with_content() { } #[tokio::test] -async fn domain_and_multi_query_filters_reach_the_endpoint() { +async fn the_domain_filter_reaches_the_endpoint() { if !enabled() { eprintln!("skipped: set LUXE_TEST_LIVE_WEB=1 to run"); return; @@ -57,7 +57,6 @@ async fn domain_and_multi_query_filters_reach_the_endpoint() { "async runtime", 5, &SearchOptions { - also: vec!["tokio runtime internals".to_string()], include_domains: vec!["docs.rs".to_string()], include_content: true, ..Default::default() diff --git a/crates/luxe-tui/Cargo.toml b/crates/luxe-tui/Cargo.toml index 448952d..d17cc62 100644 --- a/crates/luxe-tui/Cargo.toml +++ b/crates/luxe-tui/Cargo.toml @@ -8,7 +8,7 @@ repository.workspace = true homepage.workspace = true [dependencies] -luxe-core = { path = "../luxe-core", version = "0.1.2" } +luxe-core = { path = "../luxe-core", version = "0.1.3" } # `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). @@ -90,6 +90,10 @@ test = true name = "shiki_theme" test = true +[[example]] +name = "glyph_codepoints" +test = true + [[example]] name = "render_perf" required-features = ["fixture"] diff --git a/crates/luxe-tui/examples/glyph_codepoints.rs b/crates/luxe-tui/examples/glyph_codepoints.rs new file mode 100644 index 0000000..adc7621 --- /dev/null +++ b/crates/luxe-tui/examples/glyph_codepoints.rs @@ -0,0 +1,47 @@ +//! Glyph codepoints — every character the TUI's glyph table can draw, one `U+XXXX` per line. +//! +//! `scripts/remote-fonts.sh` reads this to subset the phone app's font, so a glyph added to the +//! table reaches the app without a capture having to show it first. Every tier is listed: which +//! one a reader sees depends on their terminal, and the app draws the same glyphs. +//! +//! Run with `cargo run -q -p luxe-tui --example glyph_codepoints`. + +use luxe_tui::glyphs::{GlyphTier, Icon, Mark, EVERY_ICON, EVERY_MARK}; +use std::collections::BTreeSet; + +const TIERS: [GlyphTier; 4] = + [GlyphTier::Nerd, GlyphTier::NerdWide, GlyphTier::Unicode, GlyphTier::Ascii]; + +fn main() { + for codepoint in codepoints() { + println!("U+{codepoint:04X}"); + } +} + +/// Every codepoint past ASCII that any icon or mark is drawn with, at any tier, in order. +fn codepoints() -> BTreeSet { + let icons = EVERY_ICON.iter().flat_map(|icon: &Icon| TIERS.map(|tier| icon.at(tier))); + let marks = EVERY_MARK.iter().flat_map(|mark: &Mark| TIERS.map(|tier| mark.at(tier))); + icons.chain(marks).flat_map(str::chars).map(u32::from).filter(|&c| c > 0x7e).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A glyph from each tier is listed, not just the default one. + /// + /// The break this catches: listing only the Nerd tier, so a phone whose session draws the + /// Unicode tier gets those shapes from a fallback font, in a different width. + #[test] + fn every_tier_is_listed() { + let listed = codepoints(); + for tier in [GlyphTier::Nerd, GlyphTier::Unicode] { + let glyphs = EVERY_ICON.iter().map(|icon| icon.at(tier)).flat_map(str::chars); + let missing: Vec = glyphs + .filter(|&c| u32::from(c) > 0x7e && !listed.contains(&u32::from(c))) + .collect(); + assert!(missing.is_empty(), "{tier:?} glyphs missing: {missing:?}"); + } + } +} diff --git a/crates/luxe-tui/examples/theme_css.rs b/crates/luxe-tui/examples/theme_css.rs index d98a3ed..280fda8 100644 --- a/crates/luxe-tui/examples/theme_css.rs +++ b/crates/luxe-tui/examples/theme_css.rs @@ -19,6 +19,7 @@ //! cargo run -p luxe-tui --example theme_css -- --json > web/src/assets/generated/themes.json //! ``` +use luxe_core::theme::css::{css_name, custom_properties}; use luxe_core::theme::{ColorValue, ThemeRegistry}; use luxe_tui::widgets::Wordmark; use std::collections::HashMap; @@ -73,7 +74,7 @@ fn catalog(registry: &ThemeRegistry) -> String { for token in EXPORTED { if let Some(hex) = hex(theme.get(*token)) { let separator = if first { "" } else { "," }; - let _ = write!(out, "{separator}\n \"{}\": \"{hex}\"", kebab(token)); + let _ = write!(out, "{separator}\n \"{}\": \"{hex}\"", css_name(token)); first = false; } } @@ -109,12 +110,7 @@ fn stylesheet(dark: &HashMap) -> String { /// One theme's custom properties, wordmark ramp included. fn block(theme: &HashMap, dark: bool) -> String { - let mut out = String::new(); - for token in EXPORTED { - if let Some(hex) = hex(theme.get(*token)) { - let _ = writeln!(out, " --luxe-{}: {hex};", kebab(token)); - } - } + let mut out = custom_properties(theme, EXPORTED.iter().copied()); // The wordmark's steps, taken from the renderer rather than a table copied out of it — a second // copy of a rule is a rule that drifts. A still is the frame at `STILL_TICK`, which is exactly @@ -157,22 +153,6 @@ fn blend(base: (u8, u8, u8), target: (u8, u8, u8), amount: f32) -> (u8, u8, u8) (mix(base.0, target.0), mix(base.1, target.1), mix(base.2, target.2)) } -/// `accentSecondary` reads as `--luxe-accent-secondary` on the web side. -fn kebab(token: &str) -> String { - let mut out = String::new(); - for (index, character) in token.char_indices() { - if character.is_ascii_uppercase() { - if index > 0 { - out.push('-'); - } - out.push(character.to_ascii_lowercase()); - } else { - out.push(character); - } - } - out -} - fn rgb(value: Option<&ColorValue>) -> Option<(u8, u8, u8)> { match value? { ColorValue::Rgb(red, green, blue) => Some((*red, *green, *blue)), @@ -181,7 +161,7 @@ fn rgb(value: Option<&ColorValue>) -> Option<(u8, u8, u8)> { } fn hex(value: Option<&ColorValue>) -> Option { - rgb(value).map(to_hex) + value.and_then(luxe_core::theme::css::hex) } fn to_hex((red, green, blue): (u8, u8, u8)) -> String { @@ -243,14 +223,6 @@ mod tests { ); } - /// Token names arrive in the shape a stylesheet expects. - #[test] - fn token_names_become_kebab_case() { - assert_eq!(kebab("accentSecondary"), "accent-secondary"); - assert_eq!(kebab("background"), "background"); - assert_eq!(kebab("borderMuted"), "border-muted"); - } - /// The document has the one theme and says it is generated, so nobody edits it by hand. #[test] fn the_stylesheet_carries_its_theme_and_its_own_warning() { diff --git a/crates/luxe-tui/examples/wordmark_svg.rs b/crates/luxe-tui/examples/wordmark_svg.rs index db014c4..364e5f3 100644 --- a/crates/luxe-tui/examples/wordmark_svg.rs +++ b/crates/luxe-tui/examples/wordmark_svg.rs @@ -31,9 +31,10 @@ fn main() { match target.as_str() { "wordmark" => print!("{}", svg(rows, 0..Wordmark::Full.group_count())), "mark" => print!("{}", svg(rows, 0..1)), + "app" => print!("{}", app_svg(rows)), "tile" => print!("{}", tile(rows, tile_colors())), other => { - eprintln!("usage: wordmark_svg [wordmark|mark|tile] (got {other:?})"); + eprintln!("usage: wordmark_svg [wordmark|mark|app|tile] (got {other:?})"); std::process::exit(2); } } @@ -72,11 +73,14 @@ fn tile(rows: &[&str], (plate_color, ink): (String, String)) -> String { let side = TILE; let plate = format!("M0 0H{side}V{side}H0z"); - // Fit the L by height, then center it: it is the taller axis, so height sets the scale. - let letter_w = ink_right(rows, 0..1) * CELL_W; + // Fit the L by height, then center its ink: it is the taller axis, so height sets the scale. + // The letter's first column is blank, so the ink, not the column span, is what gets centered. + let ink_left = first_inked_column(rows, 0) * CELL_W; + let letter_w = ink_right(rows, 0..1) * CELL_W - ink_left; let letter_h = rows.len() as u32 * CELL_H; let scale = f64::from(side - TILE_PAD * 2) / f64::from(letter_h); - let offset_x = (f64::from(side) - f64::from(letter_w) * scale) / 2.0; + let offset_x = + (f64::from(side) - f64::from(letter_w) * scale) / 2.0 - f64::from(ink_left) * scale; format!( ") -> String { out } +/// The phone app's copy: the wordmark, plus how deep the drift swings. +/// +/// The app's colors come from core's theme CSS, and the depth is the terminal's, so the file is +/// the one way it reaches the app without a second copy of the number. +fn app_svg(rows: &[&str]) -> String { + let depth = format!(" data-drift-depth=\"{}\" role=", luxe_tui::widgets::DRIFT_DEPTH); + svg(rows, 0..Wordmark::Full.group_count()).replacen(" role=", &depth, 1) +} + /// The first column of ink group `group`. fn first_column(group: usize) -> u32 { let groups = Wordmark::Full.groups(); @@ -134,6 +147,20 @@ fn group_span(group: usize) -> std::ops::Range { first..last + 1 } +/// The leftmost inked column of ink group `group`. +fn first_inked_column(rows: &[&str], group: usize) -> u32 { + let span = group_span(group); + rows.iter() + .flat_map(|row| { + row.chars() + .enumerate() + .filter(|(column, glyph)| *glyph != ' ' && span.contains(column)) + .map(|(column, _)| column as u32) + }) + .min() + .unwrap_or(0) +} + /// One column past the rightmost inked cell in `letters`. fn ink_right(rows: &[&str], letters: std::ops::Range) -> u32 { let span = group_span(letters.start).start..group_span(letters.end - 1).end; @@ -270,6 +297,21 @@ mod tests { assert!(svg.contains("data-cell=\"10 22\""), "the grid the highlight is drawn in"); } + /// The app's copy is the wordmark with the drift's depth on its root. + /// + /// The break this catches: the attribute left off, or put somewhere other than the `` tag, + /// which leaves the app swinging by a guess. + #[test] + fn the_app_copy_carries_the_drift_depth() { + let rows = Wordmark::Full.rows(); + let app = app_svg(rows); + let root = app.lines().next().expect("a root tag"); + let depth = luxe_tui::widgets::DRIFT_DEPTH; + assert!(root.contains(&format!("data-drift-depth=\"{depth}\"")), "{root}"); + let paths = |doc: &str| doc.lines().skip(1).collect::>().join("\n"); + assert_eq!(paths(&app), paths(&svg(rows, 0..Wordmark::Full.group_count()))); + } + /// The tile is a plain square and keeps the letter inside its own padding, which is what decides /// whether it survives a 16px tab strip. #[test] @@ -308,6 +350,24 @@ mod tests { ); } + /// The break this catches: the blank column the L's group starts with counted as part of the + /// letter, which sets the ink half a column right of center. + #[test] + fn the_tile_centers_the_ink() { + let rows = Wordmark::Full.rows(); + let svg = tile(rows, tile_colors()); + let offset: f64 = svg + .split("translate(") + .nth(1) + .and_then(|rest| rest.split(' ').next()) + .and_then(|raw| raw.parse().ok()) + .expect("an offset"); + let scale = f64::from(TILE - TILE_PAD * 2) / f64::from(rows.len() as u32 * CELL_H); + let left = offset + f64::from(first_inked_column(rows, 0) * CELL_W) * scale; + let right = f64::from(TILE) - (offset + f64::from(ink_right(rows, 0..1) * CELL_W) * scale); + assert!((left - right).abs() < 0.1, "margins {left} and {right}"); + } + /// The single-letter mark crops to its own ink instead of carrying three empty letters of /// padding. #[test] diff --git a/crates/luxe-tui/src/app.rs b/crates/luxe-tui/src/app.rs index d426adc..a5bb917 100644 --- a/crates/luxe-tui/src/app.rs +++ b/crates/luxe-tui/src/app.rs @@ -213,6 +213,11 @@ pub struct App { pub headless: bool, /// Whether submit sends `Action::EditResend` instead of `SubmitUserMessage` edit_resend_mode: bool, + /// Whether this front-end started a turn whose user message the engine hasn't committed yet. + /// + /// That message is already on screen, so its commit adopts the copy rather than adding one; + /// a commit with this unset came from a client joined to the session. + own_commit_pending: bool, /// When an interrupt was sent that the engine has not yet confirmed by ending the turn. pub(crate) interrupt_sent_at: Option, /// Whether this session has already been told that nothing is selected. diff --git a/crates/luxe-tui/src/app/commands.rs b/crates/luxe-tui/src/app/commands.rs index 634fd29..a610c06 100644 --- a/crates/luxe-tui/src/app/commands.rs +++ b/crates/luxe-tui/src/app/commands.rs @@ -4,7 +4,7 @@ //! command behavior stays separate from key precedence. use super::conversation::first_code_block; -use super::{App, AppState, ConvoBlock}; +use super::{App, ConvoBlock}; #[cfg(test)] use luxe_core::config::Config; use luxe_core::engine::Action; @@ -336,8 +336,7 @@ pub(super) fn dispatch_action(app: &mut App, action: UiAction) -> bool { let question = app.convo[index].block().clone(); app.push_convo(question); } - app.status.state = AppState::Streaming; - app.status.on_turn_start(); + app.begin_own_turn(); true } UiAction::Regenerate => { @@ -349,8 +348,7 @@ pub(super) fn dispatch_action(app: &mut App, action: UiAction) -> bool { return true; } app.drop_transcript_from(index + 1); - app.status.state = AppState::Streaming; - app.status.on_turn_start(); + app.begin_own_turn(); true } UiAction::EditResend => { diff --git a/crates/luxe-tui/src/app/construct.rs b/crates/luxe-tui/src/app/construct.rs index 66e348b..81ed2ed 100644 --- a/crates/luxe-tui/src/app/construct.rs +++ b/crates/luxe-tui/src/app/construct.rs @@ -1,6 +1,7 @@ //! App construction — building an app from its config and the machine it runs on. use super::*; +use crate::statusline_state::StatuslineState; impl App { /// Create a new app with the given engine channel, keymap, and UI config. @@ -47,8 +48,6 @@ impl App { let mouse_enabled = config.mouse.unwrap_or(true); let mut dock = DockState::new(config.dock.mode()); dock.position = config.dock.position(); - let statusline_state = - crate::statusline_state::StatuslineState::new(config.statusline.visibility()); // Seed the review's diff presentation from config; `w` and `Ctrl+B` move it at runtime. let mut guided_review_workspace = GuidedReviewWorkspace::default(); guided_review_workspace.word_wrap = config.diff.word_wrap(); @@ -70,6 +69,7 @@ impl App { review: ReviewMirror::default(), streaming: false, keymap, + statusline_state: StatuslineState::new(config.statusline.visibility()), config, mouse_enabled, hit: std::cell::RefCell::default(), @@ -82,7 +82,6 @@ impl App { files: crate::files::FilesTree::default(), external_seen: std::collections::HashMap::new(), external_folds: std::collections::HashMap::new(), - statusline_state, workspace_layout: WorkspaceLayout::Standard, theme_styles, themes, @@ -125,6 +124,7 @@ impl App { terminal_focused: None, headless: false, // Will be set by main_loop based on CLI args. edit_resend_mode: false, + own_commit_pending: false, interrupt_sent_at: None, said_to_choose_a_model: false, never_sent: HashSet::new(), diff --git a/crates/luxe-tui/src/app/events.rs b/crates/luxe-tui/src/app/events.rs index fe7640a..c48f291 100644 --- a/crates/luxe-tui/src/app/events.rs +++ b/crates/luxe-tui/src/app/events.rs @@ -5,11 +5,11 @@ //! off to the module that owns its domain. use super::{App, ConvoBlock}; -use luxe_core::config::NotificationEvent; use luxe_core::event::Event; mod compaction; mod github; +mod prompts; mod review; mod transcript; mod turn; @@ -65,38 +65,34 @@ pub(super) fn reduce(app: &mut App, event: Event) { Event::LastTurnAvailable { session_id, turn_id } => { app.review.last_turn = Some((session_id, turn_id)); } + Event::TurnStarted => turn::turn_started(app), Event::TurnEnded { .. } => turn::turn_ended(app), Event::PlanWritten { path } => app.plan_written = Some(path), - Event::ReviewStarted { model } => app.push_convo(ConvoBlock::System(format!( - "A reviewer on {model} is reading the uncommitted changes in a fresh context. Its \ - findings will show here." - ))), + Event::ReviewStarted { model } => { + app.push_convo(ConvoBlock::System(turn::review_started(&model))); + } Event::ReviewFinished { verdict, findings } => { app.push_convo(ConvoBlock::System(turn::review_summary(verdict, &findings))); } // The running turn took it in: retire the tray row. The transcript copy arrives (or has // already arrived) as the committed user entry the engine appended for it. Event::SteeringDelivered { .. } => app.retire_steering(), - // A notice is informational and the turn keeps running, so it lands in the transcript - // without touching streaming/turn state. - // On the dashboard there is no conversation to put it in — and whichever row the reader - // picks loads a session, which replaces the transcript. So it waits. + // A notice leaves the turn running, so it lands in the transcript without touching turn + // state. The dashboard has no conversation to put it in, and whichever row the reader + // picks loads a session that replaces the transcript, so there it waits. Event::Notice(msg) => match app.dashboard.is_some() { true => app.startup_notices.push(msg), false => app.push_convo(ConvoBlock::System(msg)), }, + Event::GuestsChanged(guests) => app.status.guests = guests, Event::Error(msg) => turn::failed(app, msg), Event::ToolStarted { name, .. } => turn::tool_started(app, name), Event::ToolProgress { .. } => {} // Over before its batch commits, so the clock beside it stops now rather than when the // last call of the message does - Event::ToolCompleted { .. } => { - app.status.active_tool = None; - app.status.tool_started = None; - } + Event::ToolCompleted { .. } => app.status.tool_finished(), Event::ToolEnded { call_id, .. } => { - app.status.active_tool = None; - app.status.tool_started = None; + app.status.tool_finished(); if app.pull_request_pushes.remove(&call_id) { app.pull_request_link_pending = true; } @@ -105,7 +101,7 @@ pub(super) fn reduce(app: &mut App, event: Event) { Event::ContextUsage { used_tokens, context_window } if context_window > 0 => { app.status.context_window = context_window; app.status.context_pct = - (used_tokens as f32 / context_window as f32 * 100.0).min(100.0); + crate::statusline::context_percent(used_tokens, context_window); } Event::TurnUsage { prompt_tokens, completion_tokens, cost_usd, cache_read_tokens, .. @@ -117,35 +113,20 @@ pub(super) fn reduce(app: &mut App, event: Event) { Event::ContextComposition(report) => app.push_convo(ConvoBlock::Context(report)), // Compaction rewrites what the model can see and spends a provider call doing it. Saying // so is the difference between "the agent forgot" and "the conversation was summarized". - Event::CompactionStarted { .. } => compaction::started(app), + Event::CompactionStarted { tokens_before } => compaction::started(app, tokens_before), Event::CompactionDone { tokens_before, tokens_after } => { compaction::done(app, tokens_before, tokens_after); } - Event::CompactionStopped => compaction::ended(app), + Event::CompactionStopped => compaction::stopped(app), Event::WorkspaceUpdated(snapshot) => workspace_updated(app, *snapshot), Event::ToolActivityUpdated(activity) => app.apply_tool_activity(*activity), Event::PermissionRequested { id, tool, summary, always_patterns, .. } => { - // The prompt is a question to the user; nothing above it should still be arriving. - app.reveal_catch_up(); - // The turn stops until someone answers, which is the moment most worth hearing about - let body = turn::permission_body(&tool, &summary); - turn::alert(app, NotificationEvent::Permission, &body); - app.overlays.permission = Some( - crate::permission_prompt::PermissionPromptState::new( - id, - tool, - summary, - always_patterns, - ) - .opened(app.frame_now()), - ); + prompts::permission_requested(app, id, tool, summary, always_patterns); } Event::QuestionAsked { id, prompt, options, multi, .. } => { - app.reveal_catch_up(); - turn::alert(app, NotificationEvent::Question, &format!("Question: {prompt}")); - app.overlays.question = - Some(crate::question_prompt::QuestionPromptState::new(id, prompt, options, multi)); + prompts::question_asked(app, id, prompt, options, multi); } + Event::PromptClosed { id } => prompts::prompt_closed(app, &id), Event::GuidedReviewLoading { request_id, .. } if app.active_guided_review_request.as_ref() != Some(&request_id) => { diff --git a/crates/luxe-tui/src/app/events/compaction.rs b/crates/luxe-tui/src/app/events/compaction.rs index 9a38dd7..0c77ea3 100644 --- a/crates/luxe-tui/src/app/events/compaction.rs +++ b/crates/luxe-tui/src/app/events/compaction.rs @@ -3,18 +3,26 @@ //! A summary is one provider call that can take a minute, on request or mid-turn. Without a state //! of its own the dock showed nothing for `/compact` and the turn's label for an automatic one, and //! the context reading kept the full figure until the next provider call reported a new one. +//! +//! The transcript says so as it starts, not only once it's done: the row above the composer shows +//! no label, and the statusline that does is hidden while the dock is open, so a minute of summary +//! otherwise looks like a turn that stalled. The line is settled in place when the summary ends. use super::super::{App, AppState, ConvoBlock}; +use luxe_core::usage::format_tokens; -/// The engine began writing a summary. -pub(super) fn started(app: &mut App) { +/// The engine began writing a summary of `tokens_before` of context. +pub(super) fn started(app: &mut App, tokens_before: u64) { app.status.compacting_mid_turn = matches!(app.status.state, AppState::Streaming); app.status.state = AppState::Compacting; + let note = + format!("Compacting the conversation — {} of context…", format_tokens(tokens_before)); + app.push_convo(ConvoBlock::System(note)); + app.status.compaction_note = app.convo.last().map(|item| item.id.clone()); } /// The summary stands: the dock reads what it left, and the transcript says what happened. pub(super) fn done(app: &mut App, tokens_before: u64, tokens_after: u64) { - use luxe_core::usage::format_tokens; ended(app); if app.status.context_window > 0 { let used = tokens_after as f32 / app.status.context_window as f32 * 100.0; @@ -22,19 +30,34 @@ pub(super) fn done(app: &mut App, tokens_before: u64, tokens_after: u64) { } // The summary may not have kept a server's tool names, so the next reference sends them app.mcp_listed.clear(); - app.push_convo(ConvoBlock::System(format!( - "Compacted the conversation — {} → {} of context.", - format_tokens(tokens_before), - format_tokens(tokens_after) - ))); + let before = format_tokens(tokens_before); + let after = format_tokens(tokens_after); + settle_note(app, format!("Compacted the conversation — {before} → {after} of context.")); +} + +/// The summary was cancelled or failed; a failure's reason follows as a notice of its own. +pub(super) fn stopped(app: &mut App) { + ended(app); + settle_note(app, "Compaction stopped.".to_string()); } /// The compaction under way is over, with or without a summary; the turn it interrupted, if any, /// carries on. -pub(super) fn ended(app: &mut App) { +fn ended(app: &mut App) { if !matches!(app.status.state, AppState::Compacting) { return; } app.status.state = if app.status.compacting_mid_turn { AppState::Streaming } else { AppState::Idle }; } + +/// Rewrites the line `started` left with how it ended, or adds one when it's gone (a session +/// switched mid-summary, or a host that never said it started). +fn settle_note(app: &mut App, text: String) { + let note = app.status.compaction_note.take(); + let item = note.and_then(|id| app.convo.iter_mut().rev().find(|item| item.id == id)); + match item { + Some(item) => item.set_block(ConvoBlock::System(text)), + None => app.push_convo(ConvoBlock::System(text)), + } +} diff --git a/crates/luxe-tui/src/app/events/prompts.rs b/crates/luxe-tui/src/app/events/prompts.rs new file mode 100644 index 0000000..9a3791a --- /dev/null +++ b/crates/luxe-tui/src/app/events/prompts.rs @@ -0,0 +1,54 @@ +//! Prompts — the permission and question modals a turn waits on, opened and taken down. +//! +//! A prompt can be answered somewhere else: a phone joined to the session, or any other front-end +//! on the same engine. The engine says when one stops waiting, and the modal goes with it. + +use super::super::App; +use luxe_core::config::NotificationEvent; +use luxe_core::permission::PermissionRequestId; +use luxe_core::question::{QuestionOption, QuestionRequestId}; + +/// Opens the permission prompt the turn is waiting on, and tells the reader. +pub(super) fn permission_requested( + app: &mut App, + id: PermissionRequestId, + tool: String, + summary: String, + always_patterns: Vec, +) { + // The prompt is a question to the user; nothing above it should still be arriving. + app.reveal_catch_up(); + // The turn stops until someone answers, which is the moment most worth hearing about + let body = super::turn::permission_body(&tool, &summary); + super::turn::alert(app, NotificationEvent::Permission, &body); + let prompt = + crate::permission_prompt::PermissionPromptState::new(id, tool, summary, always_patterns); + app.overlays.permission = Some(prompt.opened(app.frame_now())); +} + +/// Opens the question the turn is waiting on, and tells the reader. +pub(super) fn question_asked( + app: &mut App, + id: QuestionRequestId, + prompt: String, + options: Vec, + multi: bool, +) { + app.reveal_catch_up(); + super::turn::alert(app, NotificationEvent::Question, &format!("Question: {prompt}")); + app.overlays.question = + Some(crate::question_prompt::QuestionPromptState::new(id, prompt, options, multi)); +} + +/// Takes down the prompt `id` names, once nothing is waiting on it. +/// +/// Only that one: the reader may already be looking at the next prompt, and a question the TUI +/// asks itself (the plan handoff) has an id the engine never closes. +pub(super) fn prompt_closed(app: &mut App, id: &str) { + if app.overlays.permission.as_ref().is_some_and(|prompt| prompt.id.as_str() == id) { + app.overlays.permission = None; + } + if app.overlays.question.as_ref().is_some_and(|prompt| prompt.id.as_str() == id) { + app.overlays.question = None; + } +} diff --git a/crates/luxe-tui/src/app/events/transcript.rs b/crates/luxe-tui/src/app/events/transcript.rs index 27a966a..f2390a2 100644 --- a/crates/luxe-tui/src/app/events/transcript.rs +++ b/crates/luxe-tui/src/app/events/transcript.rs @@ -27,7 +27,14 @@ pub(super) fn message_committed(app: &mut App, session_id: String, entry_id: Str // The user's own words are never held back — a steer that lands mid-turn has to be // visible the moment it lands, not when the prose above it finishes arriving. app.reveal_catch_up(); - for (block_index, text) in luxe_core::briefs::readers_words(&msg.content) { + let words = luxe_core::briefs::readers_words(&msg.content); + if std::mem::take(&mut app.own_commit_pending) { + let block_index = words.first().map_or(0, |(index, _)| *index); + if adopt_own_message(app, &session_id, &entry_id, block_index) { + return; + } + } + for (block_index, text) in words { app.convo.push(ConversationItem::new( persisted_id(&session_id, &entry_id, block_index), user_block(text), @@ -49,7 +56,19 @@ pub(super) fn message_committed(app: &mut App, session_id: String, entry_id: Str } } +/// This front-end's own message, on screen since it was sent, takes the id the engine gave it. +/// +/// The copy on screen keeps its chips and images, which the committed text doesn't carry. +fn adopt_own_message(app: &mut App, session_id: &str, entry_id: &str, block_index: usize) -> bool { + let Some(index) = app.last_user_message_index() else { + return false; + }; + app.convo[index].id = persisted_id(session_id, entry_id, block_index); + true +} + pub(super) fn session_loaded(app: &mut App, session_id: String, messages: Vec) { + app.own_commit_pending = false; app.review.last_turn = None; app.mcp_listed.clear(); app.worktree_emptied = false; diff --git a/crates/luxe-tui/src/app/events/turn.rs b/crates/luxe-tui/src/app/events/turn.rs index fc25934..70c5da0 100644 --- a/crates/luxe-tui/src/app/events/turn.rs +++ b/crates/luxe-tui/src/app/events/turn.rs @@ -62,6 +62,15 @@ pub(super) fn token_delta(app: &mut App, delta: String) { app.status.state = AppState::Streaming; } +/// A turn began, maybe one a joined client asked for. One sent from here has been running since +/// Enter, so its clock is left alone. +pub(super) fn turn_started(app: &mut App) { + app.status.state = AppState::Streaming; + if app.status.turn_started.is_none() { + app.status.on_turn_start(); + } +} + pub(super) fn turn_ended(app: &mut App) { end_turn(app, "The turn ended before this call ran"); // Steering the turn ended before taking in stays held. That window is now narrow — the @@ -111,6 +120,8 @@ pub(super) fn failed(app: &mut App, msg: String) { fn end_turn(app: &mut App, reason: &str) { // A load that failed sends no snapshot, and one that never comes must not mute the next real one app.arrival.owes_snapshot = false; + // A prompt a hook refused never commits, and must not claim the next client's message + app.own_commit_pending = false; app.interrupt_sent_at = None; app.streaming = false; app.streamed_thinking = false; @@ -281,6 +292,14 @@ pub(super) fn mark_unfinished_tools(app: &mut App, state: ToolActivityState, sum } } +/// The transcript line saying a requested review began. +pub(super) fn review_started(model: &str) -> String { + format!( + "A reviewer on {model} is reading the uncommitted changes in a fresh context. Its \ + findings will show here." + ) +} + /// What a requested review found, as one line of the transcript and the list under it. pub(super) fn review_summary( verdict: luxe_core::event::RequestedReviewVerdict, diff --git a/crates/luxe-tui/src/app/input/submit.rs b/crates/luxe-tui/src/app/input/submit.rs index 4977d96..26487d7 100644 --- a/crates/luxe-tui/src/app/input/submit.rs +++ b/crates/luxe-tui/src/app/input/submit.rs @@ -233,7 +233,10 @@ fn send_user_turn( app.never_sent.extend(message); app.push_convo(ConvoBlock::System("[engine unavailable — channel closed]".to_string())); app.status.state = AppState::Idle; - } else if starts_new_turn { + return; + } + app.own_commit_pending = true; + if starts_new_turn { app.review.last_turn = None; } } @@ -241,7 +244,13 @@ fn send_user_turn( /// Routes a submission made while a turn is running: steer it into the turn, or hold it for one /// of its own. Either way it is pinned above the composer rather than dropped into the /// transcript, so the UI never claims a message started work it hasn't started. -fn deliver_mid_turn(app: &mut App, submission: PendingSubmission) { +/// +/// A message with images always waits: steering carries text alone, so steering one would deliver +/// its words and drop its images. +fn deliver_mid_turn(app: &mut App, mut submission: PendingSubmission) { + if !submission.images.is_empty() { + submission.delivery = MidTurnDelivery::Queue; + } if submission.delivery == MidTurnDelivery::Steer { let content = submission.content.clone(); if !app.send_action(Action::SteerTurn { content }, "steer the turn") { diff --git a/crates/luxe-tui/src/app/input/submit/tests.rs b/crates/luxe-tui/src/app/input/submit/tests.rs index 3f13e31..18bf4f6 100644 --- a/crates/luxe-tui/src/app/input/submit/tests.rs +++ b/crates/luxe-tui/src/app/input/submit/tests.rs @@ -65,6 +65,51 @@ async fn a_message_the_engine_never_took_is_marked_never_sent() { assert!(!marked(|block| matches!(block, ConvoBlock::Image { .. })), "its image is not"); } +/// An app with a turn running, and the actions it sends. +fn mid_turn() -> (App, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(8); + let config = luxe_core::config::Config::default(); + let mut app = App::new(tx, luxe_core::keymap::KeyMap::defaults(), config); + app.status.model = "gpt-5.6".into(); + app.status.state = AppState::Streaming; + (app, rx) +} + +fn trace_png() -> AttachedImage { + let (data, mime) = ("aW1hZ2U=".into(), "image/png".into()); + AttachedImage { data, mime, filename: "trace.png".into(), width: 4, height: 4 } +} + +/// A message with an image, sent mid-turn, waits for a turn of its own: steering carries text +/// alone, so steering it would deliver the words and drop the image. +/// +/// The break this catches: Enter mid-turn steering a message with a pasted screenshot, which the +/// model never sees, and which leaves the tray when the words are delivered. +#[tokio::test] +async fn a_message_with_an_image_waits_for_its_own_turn() { + let (mut app, mut sent) = mid_turn(); + app.editor.prepend_messages([("why does it stall here?".to_string(), vec![trace_png()])]); + + submit_prompt(&mut app); + + assert!(sent.try_recv().is_err(), "nothing steered the turn"); + assert_eq!(app.queued_count(), 1); + assert_eq!(app.pending_submissions[0].images.len(), 1); +} + +/// The break this catches: the image check catching every mid-turn message, so plain text no +/// longer steers the running turn. +#[tokio::test] +async fn a_message_without_one_still_steers() { + let (mut app, mut sent) = mid_turn(); + app.editor.prepend_messages([("also check the backoff".to_string(), vec![])]); + + submit_prompt(&mut app); + + assert!(matches!(sent.try_recv(), Ok(Action::SteerTurn { .. }))); + assert_eq!(app.queued_count(), 0); +} + /// A draft whose mentions nest still places its chips instead of crashing on submit. #[test] fn nested_mention_text_places_chips() { diff --git a/crates/luxe-tui/src/app/status.rs b/crates/luxe-tui/src/app/status.rs index ebd221e..4e0bdaf 100644 --- a/crates/luxe-tui/src/app/status.rs +++ b/crates/luxe-tui/src/app/status.rs @@ -16,6 +16,8 @@ pub struct StatusModel { pub mode: String, pub git_branch: Option, pub git_dirty: bool, + /// Who's joined this session from elsewhere, by name, for the dock's SESSION block + pub guests: Vec, /// Project name, for the bar's left anchor. pub project: Option, /// Compact working-directory path (e.g. `~/projects/luxe`) for the optional cwd module. @@ -26,6 +28,8 @@ pub struct StatusModel { /// Whether the compaction under way started inside a turn, which carries on once it ends; one /// asked for with `/compact` returns to idle pub(crate) compacting_mid_turn: bool, + /// The transcript line saying a summary is being written, rewritten with how it ended + pub(crate) compaction_note: Option, /// Animation frame counter, advanced on every tick while streaming/compacting. /// /// Monotonic within a turn: every consumer takes it modulo its own frame count, and the @@ -100,11 +104,13 @@ impl Default for StatusModel { mode: luxe_core::mode::BUILD.into(), git_branch: None, git_dirty: false, + guests: Vec::new(), project: None, cwd: None, active_tool: None, state: AppState::Idle, compacting_mid_turn: false, + compaction_note: None, spinner_frame: 0, animating: false, turn_started: None, @@ -126,6 +132,12 @@ impl Default for StatusModel { } impl StatusModel { + /// The tool call in flight is over: no name beside the spinner, no clock on its card. + pub(crate) fn tool_finished(&mut self) { + self.active_tool = None; + self.tool_started = None; + } + /// Advance the animation frame. /// /// Streaming and compacting are the states with something running, plus whatever a surface has @@ -296,19 +308,6 @@ impl StatusModel { .map_or(std::time::Duration::ZERO, |since| now.saturating_duration_since(since)) } - /// Format elapsed time as a string (e.g. "31s", "1m 23s"). - /// - /// Whole seconds: this counts up while a turn runs, and a tenth of a second is not a figure - /// anyone reads — it is one they notice moving. - pub fn format_elapsed(dur: std::time::Duration) -> String { - let secs = dur.as_secs(); - if secs < 60 { - format!("{secs}s") - } else { - format!("{}m {:02}s", secs / 60, secs % 60) - } - } - /// Format token counts as a string (e.g. "↑1.2k ↓340"). pub fn format_tokens(prompt: u64, completion: u64) -> String { let fmt = |n: u64| -> String { @@ -357,7 +356,7 @@ impl StatusModel { spans.push(Span::raw(state)); if let Some(dur) = self.elapsed(now) { spans.push(Span::raw(" ")); - spans.push(Span::raw(Self::format_elapsed(dur))); + spans.push(Span::raw(crate::statusline::format_elapsed_compact(dur))); } if self.prompt_tokens > 0 || self.completion_tokens > 0 { spans.push(Span::raw(" ")); diff --git a/crates/luxe-tui/src/app/submissions.rs b/crates/luxe-tui/src/app/submissions.rs index 47d335b..0e7c9bf 100644 --- a/crates/luxe-tui/src/app/submissions.rs +++ b/crates/luxe-tui/src/app/submissions.rs @@ -18,6 +18,14 @@ impl App { .count() } + /// A turn this front-end asked for is under way, re-sending a message already on screen, so + /// its commit adopts that copy rather than adding a second. + pub(crate) fn begin_own_turn(&mut self) { + self.own_commit_pending = true; + self.status.state = AppState::Streaming; + self.status.on_turn_start(); + } + /// Records a submission that could not be delivered at all, so it still shows up in the /// transcript instead of vanishing along with the failure. pub fn record_unsent_submission(&mut self, submission: PendingSubmission) { @@ -132,6 +140,7 @@ impl App { // It is a real turn now, so it reads as one: the message joins the transcript ahead of // the output it is about to produce. self.land_submission(message, false); + self.own_commit_pending = true; self.review.last_turn = None; true } diff --git a/crates/luxe-tui/src/app/tests.rs b/crates/luxe-tui/src/app/tests.rs index 68ade7d..51474b1 100644 --- a/crates/luxe-tui/src/app/tests.rs +++ b/crates/luxe-tui/src/app/tests.rs @@ -4,10 +4,12 @@ use luxe_core::engine::ReviewEdit; mod composer; mod dashboard; mod github; +mod joined; mod mentions; mod modes; mod notify; mod pickers; +mod prompts; mod replay; mod review; mod review_send; diff --git a/crates/luxe-tui/src/app/tests/joined.rs b/crates/luxe-tui/src/app/tests/joined.rs new file mode 100644 index 0000000..0774116 --- /dev/null +++ b/crates/luxe-tui/src/app/tests/joined.rs @@ -0,0 +1,121 @@ +//! Joined clients: messages sent here and from a client joined to the same session. + +use super::*; +use luxe_core::message::Message; +use luxe_core::session::EntryId; + +/// Who's joined, as the shared session reports it, is what the status holds, replaced whole each +/// time, and it adds nothing to the transcript. +/// +/// The break this catches: the dock's list never updated, kept growing as phones reconnect, or a +/// join written into the transcript after all. +#[test] +fn whos_joined_is_held_for_the_dock_and_not_written_down() { + let (mut app, _rx) = app_in_session(); + let before = app.convo.len(); + app.update(Msg::Engine(Event::GuestsChanged(vec!["iPhone".into()]))); + app.update(Msg::Engine(Event::GuestsChanged(vec!["iPad".into()]))); + assert_eq!(app.status.guests, ["iPad"]); + assert_eq!(app.convo.len(), before); +} + +fn app_in_session() -> (App, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(8); + let config = luxe_core::config::Config::default(); + let mut app = App::new(tx, luxe_core::keymap::KeyMap::defaults(), config); + app.status.model = "gpt-5.6".into(); + app.update(Msg::Engine(Event::SessionLoaded { session_id: "s".into(), messages: Vec::new() })); + (app, rx) +} + +fn send(app: &mut App, text: &str) { + app.editor.insert_text(text); + app.submit_prompt(); +} + +fn committed(app: &mut App, entry: &str, text: &str) { + let message = Message::user(text); + let entry_id = EntryId(entry.into()); + app.update(Msg::Engine(Event::MessageCommitted { session_id: "s".into(), entry_id, message })); +} + +fn user_messages(app: &App) -> Vec<(&ConversationItemId, &str)> { + app.convo.iter().filter_map(user_message).collect() +} + +fn user_message(item: &ConversationItem) -> Option<(&ConversationItemId, &str)> { + match item.block() { + ConvoBlock::User { text, .. } => Some((&item.id, text.as_str())), + _ => None, + } +} + +/// A message sent here is on screen once, and takes the id of the entry the engine saved. +/// +/// The break this catches: landing every committed user message, so each one you type shows +/// twice; or leaving the copy's id provisional, so copy and expand can't find it in the session. +#[test] +fn a_message_sent_here_is_adopted_not_repeated() { + let (mut app, _engine) = app_in_session(); + send(&mut app, "explain the stall"); + committed(&mut app, "entry-1", "explain the stall"); + let saved = ConversationItemId::Persisted { + session_id: "s".into(), + entry_id: "entry-1".into(), + block_index: 0, + }; + assert_eq!(user_messages(&app), [(&saved, "explain the stall")]); +} + +/// A message a joined client sent is shown, after one sent here has already been adopted. +/// +/// The break this catches: adopting whatever user message commits next, so the phone's message +/// replaces the id of the last one typed here and never appears. +#[test] +fn a_joined_clients_message_is_shown() { + let (mut app, _engine) = app_in_session(); + send(&mut app, "mine"); + committed(&mut app, "entry-1", "mine"); + committed(&mut app, "entry-2", "from the phone"); + let texts: Vec<&str> = user_messages(&app).into_iter().map(|(_, text)| text).collect(); + assert_eq!(texts, ["mine", "from the phone"]); +} + +/// A turn a joined client started shows as running from its start, not its first token. +/// +/// The break this catches: ignoring `turn_started`, so the bar reads idle (and Enter starts a turn +/// instead of steering) while the phone's turn waits on the model. +#[test] +fn a_turn_another_client_started_shows_as_running() { + let (mut app, _engine) = app_in_session(); + app.update(Msg::Engine(Event::TurnStarted)); + assert!(app.turn_in_flight()); + assert!(app.status.turn_started.is_some(), "the turn clock runs"); +} + +/// The break this catches: `turn_started` restarting the clock of a turn sent here, which began +/// counting when Enter was pressed. +#[test] +fn the_start_of_a_turn_sent_here_keeps_its_clock() { + let (mut app, _engine) = app_in_session(); + send(&mut app, "explain the stall"); + let pressed = app.status.turn_started; + std::thread::sleep(std::time::Duration::from_millis(2)); + app.update(Msg::Engine(Event::TurnStarted)); + assert_eq!(app.status.turn_started, pressed); +} + +/// A prompt a hook refused never commits, so the turn's end lets go of it. +/// +/// The break this catches: still waiting on the refused prompt's commit, so the next message a +/// joined client sends is taken for it and never shows. +#[test] +fn a_refused_prompt_does_not_claim_the_next_message() { + let (mut app, _engine) = app_in_session(); + send(&mut app, "refused"); + let reason = luxe_core::StopReason::EndTurn; + app.update(Msg::Engine(Event::TurnEnded { reason })); + committed(&mut app, "entry-2", "from the phone"); + let texts: Vec<&str> = user_messages(&app).into_iter().map(|(_, text)| text).collect(); + assert_eq!(texts, ["refused", "from the phone"]); +} diff --git a/crates/luxe-tui/src/app/tests/prompts.rs b/crates/luxe-tui/src/app/tests/prompts.rs new file mode 100644 index 0000000..5e2147e --- /dev/null +++ b/crates/luxe-tui/src/app/tests/prompts.rs @@ -0,0 +1,40 @@ +//! Prompts — a modal answered on another front-end comes down here too. + +use super::notify::{permission_asked, question_asked}; +use super::*; + +fn closed(id: &str) -> Msg { + Msg::Engine(Event::PromptClosed { id: id.into() }) +} + +fn quiet_app() -> App { + let (tx, _rx) = mpsc::channel(8); + App::new(tx, KeyMap::defaults(), Config::default()) +} + +/// A permission prompt answered on another front-end comes down, and only that one. +/// +/// The break this catches: ignoring `PromptClosed`, which leaves the terminal holding a prompt a +/// phone already answered; or closing on any id, which takes down the next prompt because of a +/// late close of the last one. +#[tokio::test] +async fn a_permission_answered_elsewhere_comes_down_here() { + let mut app = quiet_app(); + app.update(permission_asked("bash", "Run: ls")); + app.update(closed("perm:another")); + assert!(app.overlays.permission.is_some(), "another prompt's close leaves this one"); + app.update(closed("perm:1")); + assert!(app.overlays.permission.is_none()); +} + +/// The same for a question, which has its own modal. +#[tokio::test] +async fn a_question_answered_elsewhere_comes_down_here() { + let mut app = quiet_app(); + app.update(question_asked("Which database?")); + let id = app.overlays.question.as_ref().expect("asked").id.as_str().to_string(); + app.update(closed("ask:another")); + assert!(app.overlays.question.is_some(), "another question's close leaves this one"); + app.update(closed(&id)); + assert!(app.overlays.question.is_none()); +} diff --git a/crates/luxe-tui/src/app/tests/status.rs b/crates/luxe-tui/src/app/tests/status.rs index 2e36a59..c0c51f7 100644 --- a/crates/luxe-tui/src/app/tests/status.rs +++ b/crates/luxe-tui/src/app/tests/status.rs @@ -326,16 +326,23 @@ fn test_status_model_cost_none_when_price_unknown() { assert_eq!(status.cost_usd, None); } +/// The turn timer reads at every scale a turn reaches, the way a tool card does. +/// +/// The break this catches: minutes as a clock (`1:23`) with no hours, so a two-hour turn read +/// `125:03` above the composer while the tool card beside it said `2h 05m`. #[test] -fn test_status_model_format_elapsed() { - // Zero duration. - let formatted = StatusModel::format_elapsed(std::time::Duration::ZERO); - assert!(formatted.contains("0s"), "zero elapsed should show 0s"); - - // Whole seconds. This counts up on a running turn, so a tenths digit is a number moving ten - // times a second beside a spinner already saying the same thing. - assert_eq!(StatusModel::format_elapsed(std::time::Duration::from_millis(3_140)), "3s"); - assert_eq!(StatusModel::format_elapsed(std::time::Duration::from_secs(83)), "1m 23s"); +fn the_turn_timer_reads_at_every_scale() { + use crate::statusline::format_elapsed_compact as timer; + use std::time::Duration; + assert_eq!(timer(Duration::ZERO), "0s"); + // Whole seconds: a tenths digit moves ten times a second beside a bar already moving + assert_eq!(timer(Duration::from_millis(3_140)), "3s"); + assert_eq!(timer(Duration::from_secs(59)), "59s"); + assert_eq!(timer(Duration::from_secs(60)), "1m 00s"); + assert_eq!(timer(Duration::from_secs(83)), "1m 23s"); + assert_eq!(timer(Duration::from_secs(3_599)), "59m 59s"); + assert_eq!(timer(Duration::from_secs(3_600)), "1h 00m"); + assert_eq!(timer(Duration::from_secs(7_503)), "2h 05m"); } #[test] @@ -396,6 +403,42 @@ async fn turn_reports_keep_a_compaction_on_show_until_the_turn_ends() { assert!(matches!(app.status.state, AppState::Idle), "{:?}", app.status.state); } +/// The transcript's notices, in order. +fn system_lines(app: &App) -> Vec { + let notices = app.convo.iter().filter_map(|item| match item.block() { + ConvoBlock::System(text) => Some(text.clone()), + _ => None, + }); + notices.collect() +} + +/// A compaction is in the transcript from the moment it starts, and its line becomes the result. +/// +/// The break this catches: a minute of summary with nothing in the conversation to say so (the +/// row above the composer has no label), or a second line added beside the first when it's done. +#[tokio::test] +async fn a_compaction_is_written_down_as_it_starts_and_settled_when_done() { + let mut app = idle_app(); + app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 579_400 })); + assert_eq!(system_lines(&app), ["Compacting the conversation — 579.4k of context…"]); + app.update(Msg::Engine(Event::CompactionDone { tokens_before: 579_400, tokens_after: 28_700 })); + let done = "Compacted the conversation — 579.4k → 28.7k of context."; + assert_eq!(system_lines(&app), [done]); +} + +/// A compaction that ends without a summary says so on the line that announced it. +/// +/// The break this catches: "Compacting the conversation…" left standing after a cancel or a +/// failure, reading as a summary still under way. +#[tokio::test] +async fn a_stopped_compaction_settles_its_line() { + let mut app = idle_app(); + app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 190_000 })); + app.update(Msg::Engine(Event::Notice("between".into()))); + app.update(Msg::Engine(Event::CompactionStopped)); + assert_eq!(system_lines(&app), ["Compaction stopped.", "between"]); +} + pub(super) fn type_into(app: &mut App, text: &str) { for character in text.chars() { app.update(Msg::Key(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE))); diff --git a/crates/luxe-tui/src/github_detail.rs b/crates/luxe-tui/src/github_detail.rs index 97eeebc..ad32421 100644 --- a/crates/luxe-tui/src/github_detail.rs +++ b/crates/luxe-tui/src/github_detail.rs @@ -35,6 +35,7 @@ pub use card::{render_card, CardState, PullRequestCard}; pub(crate) use draft::note_lines as draft_note_lines; pub use draft::{DraftCard, DraftKey}; pub use header::{ago, author_spans, diff_counts, state_word}; +pub use html::readable; pub use merge::MergeDialog; pub use parts::action_hint; pub(crate) use parts::lift_dim; diff --git a/crates/luxe-tui/src/github_detail/html.rs b/crates/luxe-tui/src/github_detail/html.rs index 881e072..0a1dc61 100644 --- a/crates/luxe-tui/src/github_detail/html.rs +++ b/crates/luxe-tui/src/github_detail/html.rs @@ -7,7 +7,7 @@ //! entities. Code is left alone: a fenced block or an inline span that shows HTML means to show it. /// `body` with its HTML reduced to markdown, outside code. -pub(super) fn readable(body: &str) -> String { +pub fn readable(body: &str) -> String { if !body.contains('<') && !body.contains('&') { return body.to_string(); } diff --git a/crates/luxe-tui/src/graphics/store.rs b/crates/luxe-tui/src/graphics/store.rs index aed9786..8943af6 100644 --- a/crates/luxe-tui/src/graphics/store.rs +++ b/crates/luxe-tui/src/graphics/store.rs @@ -62,6 +62,8 @@ pub struct ImageStore { clock: u64, next_id: u32, total_source_bytes: usize, + /// Bumped whenever something a layout reads changes: see [`Self::layout_revision`] + layout_revision: u64, } impl Default for ImageStore { @@ -84,9 +86,20 @@ impl ImageStore { // drawing images in the same window — and a collision silently replaces *their* image. next_id: seed_id(), total_source_bytes: 0, + layout_revision: 0, } } + /// Counts the changes to what laying an image out reads: the sources, the tier and the cell + /// size. + /// + /// The transcript keys an image's laid-out rows on it, so they are reused until one of those + /// changes rather than rebuilt every frame. What is prepared for painting isn't counted: + /// painting prepares on sight. + pub fn layout_revision(&self) -> u64 { + self.layout_revision + } + /// The fidelity this store is drawing at. pub fn tier(&self) -> ImageTier { self.tier @@ -98,6 +111,7 @@ impl ImageStore { return; } self.tier = tier; + self.layout_revision += 1; self.release_prepared(); } @@ -107,6 +121,7 @@ impl ImageStore { return; } self.cell = cell; + self.layout_revision += 1; self.release_prepared(); } @@ -132,6 +147,7 @@ impl ImageStore { return false; } self.clock += 1; + self.layout_revision += 1; self.total_source_bytes += bytes.len(); self.sources.insert( key, @@ -258,6 +274,7 @@ impl ImageStore { self.release_all(); self.sources.clear(); self.total_source_bytes = 0; + self.layout_revision += 1; } /// Ensures `key` is prepared at `fit`, re-preparing when the size changed. @@ -318,6 +335,7 @@ impl ImageStore { fn drop_source(&mut self, key: &ImageKey) { if let Some(source) = self.sources.remove(key) { self.total_source_bytes = self.total_source_bytes.saturating_sub(source.bytes.len()); + self.layout_revision += 1; } } diff --git a/crates/luxe-tui/src/graphics/store/tests.rs b/crates/luxe-tui/src/graphics/store/tests.rs index 0c27d49..b53adbb 100644 --- a/crates/luxe-tui/src/graphics/store/tests.rs +++ b/crates/luxe-tui/src/graphics/store/tests.rs @@ -239,3 +239,58 @@ fn image_ids_stay_inside_the_protocols_range() { assert_eq!(store.allocate_id(), kitty::MAX_ID); assert_eq!(store.allocate_id(), 1, "and wraps rather than overflowing"); } + +/// The break this catches: an image arriving without moving the layout revision, so a card laid +/// out before it landed keeps its old rows. +#[test] +fn a_new_image_moves_the_layout_revision_and_a_known_one_does_not() { + let mut store = store(ImageTier::Blocks); + let empty = store.layout_revision(); + let key = ImageKey::new("k"); + assert!(store.insert(key.clone(), png(32, 16), origin("shot.png"))); + let landed = store.layout_revision(); + assert_ne!(landed, empty, "a new source moves it"); + + assert!(store.insert(key, png(32, 16), origin("shot.png"))); + assert_eq!(store.layout_revision(), landed, "a known one changes nothing a layout reads"); +} + +/// The break this catches: a new cell size or tier leaving image rows sized for the old one, or +/// a repeated report of the same geometry throwing every image card's layout away. +#[test] +fn only_a_real_change_of_geometry_or_tier_moves_the_layout_revision() { + let mut store = store(ImageTier::Blocks); + let start = store.layout_revision(); + store.set_cell_size(CellSize { width: 10, height: 20 }); + store.set_tier(ImageTier::Blocks); + assert_eq!(store.layout_revision(), start, "the same geometry and tier change nothing"); + + store.set_cell_size(CellSize { width: 8, height: 16 }); + let resized = store.layout_revision(); + assert_ne!(resized, start, "a new cell size moves it"); + store.set_tier(ImageTier::Text); + assert_ne!(store.layout_revision(), resized, "a new tier moves it"); +} + +/// The break this catches: a source that is gone (cleared for another session, or dropped for not +/// decoding) leaving its card laid out as though it could still be drawn. +#[test] +fn losing_a_source_moves_the_layout_revision() { + let (mut store, _) = seeded(ImageTier::Blocks, 32, 16); + let seeded_at = store.layout_revision(); + store.clear(); + assert_ne!(store.layout_revision(), seeded_at, "clearing moves it"); + + // A header that parses ahead of pixels that don't: the source is dropped on first paint + let mut broken = png(32, 16); + let pixels = broken.len() - 20; + broken[pixels] ^= 0xff; + let key = ImageKey::new("broken"); + assert!(store.insert(key.clone(), broken, origin("broken.png"))); + let inserted = store.layout_revision(); + let fit = store.fit(&key, 6, 24).expect("the header gives a size"); + let mut buf = Buffer::empty(Rect::new(0, 0, 10, 2)); + assert!(!store.paint_row(&mut buf, (0, 0), &key, fit, 0, Color::Reset)); + assert!(!store.contains(&key), "the source is gone"); + assert_ne!(store.layout_revision(), inserted, "and the layout revision says so"); +} diff --git a/crates/luxe-tui/src/highlight.rs b/crates/luxe-tui/src/highlight.rs index e15acf4..e855b60 100644 --- a/crates/luxe-tui/src/highlight.rs +++ b/crates/luxe-tui/src/highlight.rs @@ -234,7 +234,7 @@ fn role_theme() -> &'static syntect::highlighting::Theme { } /// One highlighted line, as roles: what the memo keeps, since it holds for every theme. -type RoleLine = Vec<(Role, String)>; +pub type RoleLine = Vec<(Role, String)>; /// Highlights `code` as `lang`, in `styles`' colors. /// @@ -243,7 +243,9 @@ pub fn highlight_code(code: &str, lang: Option<&str>, styles: &ThemeStyles) -> V paint(&highlight_roles(code, lang), styles) } -fn highlight_roles(code: &str, lang: Option<&str>) -> Arc> { +/// Highlights `code` as `lang` into roles, for a surface that colors roles itself: the phone app's +/// HTML names each role's theme token as a class. Memoized, like [`highlight_code`]. +pub fn highlight_roles(code: &str, lang: Option<&str>) -> Arc> { let key = fingerprint(code, lang); if let Some(hit) = cache().get(key, code, lang) { return hit; diff --git a/crates/luxe-tui/src/lib.rs b/crates/luxe-tui/src/lib.rs index fc0d722..e1bb9ae 100644 --- a/crates/luxe-tui/src/lib.rs +++ b/crates/luxe-tui/src/lib.rs @@ -33,10 +33,11 @@ pub(crate) mod keys_card; pub mod launcher; pub mod main_loop; pub mod markdown; +pub mod marks; pub mod mention_flyout; pub mod mentions; pub mod model_picker; -pub(crate) mod modes; +pub mod modes; pub mod mouse; pub mod notify; pub(crate) mod option_layer; diff --git a/crates/luxe-tui/src/main_loop/overlay_matrix.rs b/crates/luxe-tui/src/main_loop/overlay_matrix.rs index 7b6b249..b424fb9 100644 --- a/crates/luxe-tui/src/main_loop/overlay_matrix.rs +++ b/crates/luxe-tui/src/main_loop/overlay_matrix.rs @@ -243,8 +243,13 @@ fn matrix() -> String { /// /// The break this catches: grouping or reordering the overlays changing which one an input /// reaches. Set `LUXE_OVERLAY_MATRIX` to a path to write the current table there. +/// +/// A click can choose a theme, which is written to the global config, so the test has a config +/// home of its own; without one it rewrites the developer's real theme. #[tokio::test] async fn every_pair_of_overlays_answers_as_recorded() { + let home = tempfile::tempdir().expect("temp dir"); + let _config_home = crate::test_env::TempConfigHome::at(home.path()); let actual = matrix(); if let Ok(path) = std::env::var("LUXE_OVERLAY_MATRIX") { std::fs::write(path, &actual).expect("write the matrix"); diff --git a/crates/luxe-tui/src/markdown.rs b/crates/luxe-tui/src/markdown.rs index f8911e4..b5e1348 100644 --- a/crates/luxe-tui/src/markdown.rs +++ b/crates/luxe-tui/src/markdown.rs @@ -11,6 +11,7 @@ //! `MarkdownVoice`. mod fence; +pub mod html; mod layout; mod line; mod table; diff --git a/crates/luxe-tui/src/markdown/html.rs b/crates/luxe-tui/src/markdown/html.rs new file mode 100644 index 0000000..fb1e3a6 --- /dev/null +++ b/crates/luxe-tui/src/markdown/html.rs @@ -0,0 +1,352 @@ +//! Markdown as HTML — model text for the phone app, drawn the way the transcript draws it. +//! +//! The line renderer lays text out in cells at a width it knows; a browser reflows on every turn of +//! the phone, so this walks the same events, in the same dialect, into elements instead, and keeps +//! the TUI's choices: the alert's word and mark, a fence's language and copy affordance on its +//! rule, a link's address after its words. How those look (bullets, `> `, the rules) is the app's +//! stylesheet. Code is highlighted into the same roles the terminal paints, each a class naming +//! its theme token (`t-accent-secondary`), never an inline style: the app's CSP forbids those, and +//! the token's color comes from the user's theme as it is now. +//! +//! What the model wrote is data: every character of it is escaped, raw HTML shows as its source +//! the way the TUI shows it, and a link only gets an `href` when it leaves for the web or mail. + +use pulldown_cmark::{Alignment, BlockQuoteKind, CodeBlockKind, Event, Parser, Tag, TagEnd}; + +use super::fence::fence_language; +use super::layout::parser_options; +use super::voice::{alert_icon, alert_label}; +use crate::glyphs::{GlyphTier, Icon}; +use crate::highlight::{highlight_roles, Role}; + +/// Which reader a block is rendered for, as in the transcript. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Voice { + /// Assistant prose, fences highlighted + #[default] + Answer, + /// Model reasoning: line breaks kept, fences left plain so the block stays muted + Reasoning, +} + +/// The app's font ships with the Nerd Font marks, so every glyph is drawn at that tier. +const TIER: GlyphTier = GlyphTier::Nerd; + +/// `src` as HTML for `voice`, with no wrapping element: the app supplies that and its class. +/// +/// Partial input is fine. A reply is rendered as it streams, and pulldown-cmark closes whatever is +/// still open at the end, so an unterminated fence is a fence. +pub fn render(src: &str, voice: Voice) -> String { + let mut writer = HtmlWriter { voice, ..HtmlWriter::default() }; + for event in Parser::new_ext(src, parser_options()) { + writer.event(event); + } + writer.out +} + +/// One source line highlighted as HTML, the way a diff row's code is: on its own, as the TUI's +/// diff views highlight it. Everything in `text` comes back escaped. +pub fn code_line(text: &str, lang: Option<&str>) -> String { + let mut out = String::new(); + // the highlighter keeps every character of a line, so only empty text has no first line + for (role, part) in highlight_roles(text, lang).first().into_iter().flatten() { + role_span_into(&mut out, *role, part); + } + out +} + +/// `text` in the span for its highlight role, or bare when the role is body text. +fn role_span_into(out: &mut String, role: Role, text: &str) { + let Some(class) = role_class(role) else { return escape_into(out, text) }; + out.push_str(&format!("")); + escape_into(out, text); + out.push_str(""); +} + +/// One walk's state: the HTML so far, and the open things whose end changes what is written. +#[derive(Default)] +struct HtmlWriter { + out: String, + voice: Voice, + link: Option, + fence: Option, + table: Option, +} + +/// A link being written: where it goes, what it says so far, and whether it got an `href`. +struct Link { + url: String, + words: String, + live: bool, +} + +/// A code block being collected, since it is highlighted whole. +struct Fence { + lang: Option, + code: String, +} + +/// A table being written: how each column aligns, and which cell is next. +struct Table { + alignments: Vec, + cell: usize, + head: bool, +} + +impl HtmlWriter { + fn event(&mut self, event: Event<'_>) { + match event { + Event::Start(tag) => self.start(tag), + Event::End(tag) => self.end(tag), + // block HTML shows as the source the model wrote, as it does in the terminal + Event::Text(text) | Event::Html(text) => self.text(&text), + Event::Code(code) => self.code(&code), + Event::SoftBreak if self.voice == Voice::Reasoning => self.out.push_str("
    "), + Event::SoftBreak => self.out.push(' '), + Event::HardBreak => self.out.push_str("
    "), + Event::Rule => self.out.push_str("
    "), + // inline HTML, footnotes and the rest: the terminal leaves them out too + _ => {} + } + } + + fn start(&mut self, tag: Tag<'_>) { + match tag { + Tag::Paragraph => self.out.push_str("

    "), + Tag::Heading { level, .. } => self.out.push_str(&format!("<{level}>")), + Tag::BlockQuote(kind) => self.open_quote(kind), + Tag::CodeBlock(kind) => { + self.fence = Some(Fence { lang: fence_lang(kind), code: "".into() }) + } + Tag::List(Some(1)) => self.out.push_str("

      "), + Tag::List(Some(start)) => self.out.push_str(&format!("
        ")), + Tag::List(None) => self.out.push_str("
          "), + Tag::Item => self.out.push_str("
        • "), + Tag::Table(alignments) => self.open_table(alignments), + Tag::TableHead | Tag::TableRow => self.open_row(), + Tag::TableCell => self.open_cell(), + Tag::Emphasis => self.out.push_str(""), + Tag::Strong => self.out.push_str(""), + Tag::Strikethrough => self.out.push_str(""), + Tag::Link { dest_url, .. } => self.open_link(&dest_url), + // an image's words are its alt text, which follows as text + _ => {} + } + } + + fn end(&mut self, tag: TagEnd) { + let close = match tag { + TagEnd::Paragraph => "

          ", + TagEnd::Heading(level) => return self.out.push_str(&format!("")), + TagEnd::BlockQuote(_) => "", + TagEnd::CodeBlock => return self.close_fence(), + TagEnd::List(true) => "
      ", + TagEnd::List(false) => "", + TagEnd::Item => "", + TagEnd::Table => return self.close_table(), + TagEnd::TableHead => return self.close_head(), + TagEnd::TableRow => "", + TagEnd::TableCell => return self.close_cell(), + TagEnd::Emphasis => "", + TagEnd::Strong => "", + TagEnd::Strikethrough => "", + TagEnd::Link => return self.close_link(), + _ => "", + }; + self.out.push_str(close); + } + + fn text(&mut self, text: &str) { + if let Some(fence) = &mut self.fence { + return fence.code.push_str(text); + } + if let Some(link) = &mut self.link { + link.words.push_str(text); + } + escape_into(&mut self.out, text); + } + + fn code(&mut self, code: &str) { + if let Some(link) = &mut self.link { + link.words.push_str(code); + } + self.out.push_str(""); + escape_into(&mut self.out, code); + self.out.push_str(""); + } + + /// Opens a quote; an alert writes its word out first, since its severity is in the tag rather + /// than in its prose, and the color is only polish. + fn open_quote(&mut self, kind: Option) { + let Some(kind) = kind else { return self.out.push_str("
      ") }; + let label = alert_label(kind); + self.out.push_str(&format!("
      ", label.to_lowercase())); + self.out.push_str("

      "); + escape_into(&mut self.out, &icon_label(alert_icon(kind), label)); + self.out.push_str("

      "); + } + + fn open_link(&mut self, url: &str) { + let live = leaves_for_the_web(url); + if live { + self.out.push_str(""); + } else { + self.out.push_str(""); + } + self.link = Some(Link { url: url.to_string(), words: String::new(), live }); + } + + /// Closes a link and writes its address after it, once, unless the words already are the + /// address or a table cell holds it, as the terminal does. + fn close_link(&mut self) { + let Some(link) = self.link.take() else { return }; + self.out.push_str(if link.live { "" } else { "" }); + let repeats = link.url.trim_start_matches("mailto:") == link.words.trim(); + if link.url.is_empty() || repeats || self.table.is_some() { + return; + } + self.out.push_str(" ("); + escape_into(&mut self.out, &link.url); + self.out.push_str(")"); + } +} + +impl HtmlWriter { + /// Writes a code block between its rules: the language and copy on the top one. An empty + /// block draws nothing, as in the terminal. + fn close_fence(&mut self) { + let Some(fence) = self.fence.take() else { return }; + if fence.code.is_empty() { + return; + } + self.out.push_str("
      "); + if let Some(language) = fence_language(fence.lang.as_deref()) { + self.out.push_str(""); + let icon = crate::widgets::language_icon(&language); + escape_into(&mut self.out, &icon_label(icon, &language)); + self.out.push_str(""); + } + self.out.push_str("
      ");
      +        self.fence_body(&fence);
      +        self.out.push_str("
      "); + } + + /// The code, highlighted for an answer and plain for reasoning, which a palette would pull out + /// of its muted voice. + fn fence_body(&mut self, fence: &Fence) { + if self.voice == Voice::Reasoning { + return escape_into(&mut self.out, fence.code.trim_end_matches('\n')); + } + let lines = highlight_roles(&fence.code, fence.lang.as_deref()); + for (index, line) in lines.iter().enumerate() { + if index > 0 { + self.out.push('\n'); + } + for (role, text) in line { + role_span_into(&mut self.out, *role, text); + } + } + } + + fn open_table(&mut self, alignments: Vec) { + self.table = Some(Table { alignments, cell: 0, head: true }); + self.out.push_str("
    "); + } + + fn open_row(&mut self) { + if let Some(table) = &mut self.table { + table.cell = 0; + } + self.out.push_str(""); + } + + fn open_cell(&mut self) { + let Some(table) = &mut self.table else { return }; + let tag = if table.head { "th" } else { "td" }; + let align = match table.alignments.get(table.cell) { + Some(Alignment::Right) => " class=\"right\"", + Some(Alignment::Center) => " class=\"center\"", + _ => "", + }; + self.out.push_str(&format!("<{tag}{align}>")); + } + + fn close_cell(&mut self) { + let Some(table) = &mut self.table else { return }; + self.out.push_str(if table.head { "" } else { "" }); + table.cell += 1; + } + + /// pulldown-cmark puts the header cells straight under the head, with no row of their own. + fn close_head(&mut self) { + if let Some(table) = &mut self.table { + table.head = false; + } + self.out.push_str(""); + } + + fn close_table(&mut self) { + self.table = None; + self.out.push_str("
    "); + } +} + +/// The language a code block declared: an indented one declares none. +fn fence_lang(kind: CodeBlockKind<'_>) -> Option { + match kind { + CodeBlockKind::Fenced(lang) => Some(lang.to_string()), + CodeBlockKind::Indented => None, + } +} + +/// `{glyph} {label}`, the shape the terminal's labels take at the Nerd tier. +fn icon_label(icon: Icon, label: &str) -> String { + format!("{} {label}", icon.at(TIER)) +} + +/// The classes a role is drawn with: its theme token, then its weight or slant. Plain text takes +/// none, which keeps a highlighted block about half the size. +fn role_class(role: Role) -> Option { + use ratatui::style::Modifier; + if role == Role::Text { + return None; + } + let (token, modifier) = role.token(); + let mut class = format!("t-{}", luxe_core::theme::css::css_name(token)); + if modifier.contains(Modifier::BOLD) { + class.push_str(" b"); + } + if modifier.contains(Modifier::ITALIC) { + class.push_str(" i"); + } + Some(class) +} + +/// Whether a link may be followed from the app: to the web or to mail, never `javascript:`, a +/// `data:` page, or a path on the bridge itself. +fn leaves_for_the_web(url: &str) -> bool { + let lower = url.trim_start().to_ascii_lowercase(); + ["https://", "http://", "mailto:"].iter().any(|scheme| lower.starts_with(scheme)) +} + +/// Appends `text` with every character that means something in HTML escaped, quotes included, +/// since some of it lands in attributes. +fn escape_into(out: &mut String, text: &str) { + for character in text.chars() { + match character { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(character), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/luxe-tui/src/markdown/html/tests.rs b/crates/luxe-tui/src/markdown/html/tests.rs new file mode 100644 index 0000000..651e983 --- /dev/null +++ b/crates/luxe-tui/src/markdown/html/tests.rs @@ -0,0 +1,135 @@ +use super::{code_line, render, Voice}; + +fn answer(src: &str) -> String { + render(src, Voice::Answer) +} + +/// What a model writes is shown, never run: block HTML is escaped and inline HTML left out. +/// +/// The break this catches: text written into the page unescaped, which would let a reply run +/// script in the app. +#[test] +fn model_html_is_shown_not_run() { + let html = answer("\n\nhi & bye"); + assert!(!html.contains("tap"), "{unsafe_link}"); + let page = answer("[docs](https://example.com/a)"); + assert!(page.contains(")"); + assert!(!html.contains("\" onclick"), "{html}"); + assert!(html.contains("" onclick="steal()"), "{html}"); +} + +/// The address follows the words, as in the terminal, but not when the words are the address. +/// +/// The break this catches: the repeat check dropped, doubling every bare link. +#[test] +fn a_link_names_its_address_unless_its_words_are_it() { + let named = answer("[docs](https://example.com)"); + assert!(named.contains(" (https://example.com)"), "{named}"); + let bare = answer(""); + assert!(!bare.contains("class=\"url\""), "{bare}"); +} + +/// The break this catches: a fence losing its language label, copy control or highlighting +/// classes, which are what make it read like the terminal's. +#[test] +fn a_fence_is_framed_with_its_language_and_copy() { + let html = answer("```Rust\nfn main() {}\n```"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(" rust"), "{html}"); + assert!(html.contains("

    - Built to help you do the work. -
    - Refined to help you enjoy it. + A better way to build.

    @@ -808,8 +797,8 @@ const NARROW = { mobileCols: 72, mobileRows: 24 }; } } - /* "Built to help you do the work." is about 9.7em wide, so 10cqi keeps each line on one line in - any column, a hair under the type's cap at a laptop's width */ + /* "A better way to build." is about 7.5em wide, so 10cqi keeps it on one line in any column, and + the type's cap sets it at a laptop's width */ .hero__line { font-size: min(var(--step-4), 10cqi); margin-bottom: var(--space-4); @@ -845,15 +834,15 @@ const NARROW = { mobileCols: 72, mobileRows: 24 }; * * A background behind the text cannot invert it, and light text on the accent is unreadable — so * the highlight is the same word again, drawn in the selection's own colors, clipped to whatever - * has been "selected" so far. `steps(7)` for seven characters: the selection arrives a letter at a + * has been "selected" so far. `steps(6)` for six characters: the selection arrives a letter at a * time, the way a drag does, rather than the whole word blinking on at once. * * Right to left because that is how the gesture reads as deliberate — the cursor lands past the * end of the word and pulls back across it. * * A real element rather than `::after`, because several screen readers announce generated - * content and this one sits inside the `h1`: the page's own heading would have read "Built for - * agents. Refined Refined for humans." */ + * content and this one sits inside the `h1`: the page's own heading would have read "A better + * better way to build." */ .hero__refine span { position: absolute; inset: 0; @@ -862,10 +851,10 @@ const NARROW = { mobileCols: 72, mobileRows: 24 }; color: var(--luxe-background); clip-path: inset(0 0 0 100%); /* Not selectable and not clickable: it is a picture of a selection sitting on top of the real - word, and letting a reader drag through it would hand them "RefinedRefined". */ + word, and letting a reader drag through it would hand them "betterbetter". */ user-select: none; pointer-events: none; - animation: select 3100ms steps(7, end) 3500ms both; + animation: select 3100ms steps(6, end) 3500ms both; } /* The swap happens *under* the highlight, on purpose. diff --git a/web/src/pages/press-shots.astro b/web/src/pages/press-shots.astro new file mode 100644 index 0000000..f14beb9 --- /dev/null +++ b/web/src/pages/press-shots.astro @@ -0,0 +1,43 @@ +--- +/** + * The press kit's screenshots, laid out to be photographed by `scripts/press-shots.mjs`. + * + * Drawn by the same `Still` the home page uses, so a downloaded PNG is the picture on the site. + * Kept out of the sitemap and the navigation, like the social card. + */ +import "../assets/generated/tokens.css"; +import "../styles/grain.css"; +import "../styles/base.css"; +import Still from "../components/Still.astro"; +import { screenshots } from "../lib/press"; +--- + + + + + Luxe — press screenshots + + + + { + screenshots.map((shot) => ( +

    + +
    + )) + } + + + + diff --git a/web/src/pages/press/[file].ts b/web/src/pages/press/[file].ts new file mode 100644 index 0000000..db54035 --- /dev/null +++ b/web/src/pages/press/[file].ts @@ -0,0 +1,9 @@ +import type { APIRoute, GetStaticPaths } from "astro"; +import { logos, type Logo } from "../../lib/press"; + +/** One press logo per file, its colors written in at build time. */ +export const getStaticPaths = (() => + logos.map((logo) => ({ params: { file: logo.file }, props: { logo } }))) satisfies GetStaticPaths; + +export const GET: APIRoute<{ logo: Logo }> = ({ props }) => + new Response(props.logo.svg(), { headers: { "Content-Type": "image/svg+xml" } }); diff --git a/web/src/pages/social-card.astro b/web/src/pages/social-card.astro index 4531679..d3eaf5d 100644 --- a/web/src/pages/social-card.astro +++ b/web/src/pages/social-card.astro @@ -26,9 +26,9 @@ import Wordmark from "../components/Wordmark.astro";
    -

    Built for agents.
    Refined for humans.

    +

    A better way to build.

    - Rust · terminal · plan → build → review · luxe.dev + plan → build → review · luxe.dev

    diff --git a/web/src/pages/tools.astro b/web/src/pages/tools.astro index 39ac3b9..f2c43ee 100644 --- a/web/src/pages/tools.astro +++ b/web/src/pages/tools.astro @@ -352,7 +352,11 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100,
    -

    Whole tasks

    +

    What a task costs

    +
    + {/* The words, the table and its note are one column, so the chart starts beside the words + and the note sits under what it qualifies */} +

    Luxe, Claude Code, Codex and OpenCode each ran the first twelve Django tasks of @@ -361,10 +365,6 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100, spent on the same task, as a multiple of what Luxe spent: above 1× costs more than Luxe.

    -
    - {/* The table and its note are one column, so the note sits under what it qualifies rather - than below whichever of table and chart runs longer */} -
    @@ -620,24 +620,25 @@ const share = (shell: number, tool: number) => `${Math.max((tool / shell) * 100, margin-bottom: var(--space-2) !important; } - /* The words, and beside them what they claim, drawn; one column once there is no room. Shares - rather than a fixed text column: the prose keeps its own measure, and the drawing gets room for - its longest command just above the breakpoint */ + /* The words, and beside them what they claim, drawn; one column once there is no room. The text + column is the prose's own measure, so the drawing starts one gap from the words rather than + after a column wider than they are */ .split { display: grid; - grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); + grid-template-columns: minmax(0, var(--measure)) minmax(0, 1fr); gap: var(--space-5) var(--space-6); align-items: center; } .split--tasks { - grid-template-columns: auto minmax(0, 1fr); align-items: start; - margin-top: var(--space-5); + } + + .tasks__data .prose { + margin-top: 0; } .split--tasks .costs { - margin-top: 0; width: 100%; }