diff --git a/.claude/agents/implementer.md b/.claude/agents/implementer.md index 942ca40b..d0744630 100644 --- a/.claude/agents/implementer.md +++ b/.claude/agents/implementer.md @@ -24,4 +24,4 @@ under the input-based Definition of done. Do not launch an independent full pipeline at every handoff. Report changed files, commands/results, meaningful deviations and anything left -undone. Commit, push or open a PR only when the user explicitly requests it. +undone. Commit verified task changes locally by default; push or open a PR only when the user explicitly requests it. diff --git a/.claude/skills/crate-split/SKILL.md b/.claude/skills/crate-split/SKILL.md index 8d5ba09c..fee0f4df 100644 --- a/.claude/skills/crate-split/SKILL.md +++ b/.claude/skills/crate-split/SKILL.md @@ -29,4 +29,4 @@ when helpful. A crate-boundary change requires an ADR. combined dependency changes settle. Use `gate` for both sides and consumers. 6. Review with `design-review`, fix findings and finish the applicable completion checks. Report ownership/metric changes, checks/results and limitations. - Vendor and app changes require separate commits; commit/push/PR only on request. + Vendor and app changes require separate commits; commit verified task changes locally by default. Push/PR only on request. diff --git a/.claude/skills/design-review/SKILL.md b/.claude/skills/design-review/SKILL.md index f6e62309..6bd26969 100644 --- a/.claude/skills/design-review/SKILL.md +++ b/.claude/skills/design-review/SKILL.md @@ -20,6 +20,11 @@ and check the code against the authorized task. ## Ownership and cost +For every runtime-code change, apply the mandatory post-change +[performance review](../performance/SKILL.md) before approving the change. +Record its verdict and resolve blocking performance findings in this review; +routine bounded low-cost changes do not need separate benchmarks. + For changed state or boundaries, trace one actual use case through its owners: - Who owns the authoritative state, its invariant and all transitions? Does the diff --git a/.claude/skills/feature/SKILL.md b/.claude/skills/feature/SKILL.md index 844ab5e2..52dd610f 100644 --- a/.claude/skills/feature/SKILL.md +++ b/.claude/skills/feature/SKILL.md @@ -39,4 +39,4 @@ branch/base, plan/evidence location, scope and relevant prior findings. input-based Definition of done after review fixes; preserve valid evidence. 6. Report what changed, commands/results, scope and remaining limitations. Propose commit/PR text only when useful. Vendor and app changes belong in - separate commits; commit, push and PR actions require the user's request. + separate commits; commit verified task changes locally by default. Push and PR actions require the user's request. diff --git a/.claude/skills/gate/SKILL.md b/.claude/skills/gate/SKILL.md index 8cf4d3f2..2ba00821 100644 --- a/.claude/skills/gate/SKILL.md +++ b/.claude/skills/gate/SKILL.md @@ -33,7 +33,9 @@ queuing the same pending check twice. ## Completion and failures -At integrated completion, choose the applicable AGENTS.md scope after review +At integrated completion, confirm the mandatory post-change +[performance review](../performance/SKILL.md) for runtime code has passed as +part of design review. Choose the applicable AGENTS.md scope after review fixes. Broad shared changes, uncertain workspace impact or an explicit full-verification request need the full workspace suite below. A small change does not inherit that suite merely because a stage or worktree ended. Apply @@ -96,7 +98,7 @@ Additional checks follow actual changed inputs: - Hook changes run `python3 scripts/test-claude-hooks.py`; configuration-validator changes run `python3 scripts/test-claude-config.py` as well. -Commit, push and PR creation still require the user's request. +Commit verified task changes locally without asking. Push and PR creation still require the user's request. ## Commands diff --git a/.claude/skills/performance/SKILL.md b/.claude/skills/performance/SKILL.md index 87b3281f..78b21e2b 100644 --- a/.claude/skills/performance/SKILL.md +++ b/.claude/skills/performance/SKILL.md @@ -1,13 +1,75 @@ --- name: performance -description: Evaluate changed hot paths, rendering, repeated I/O or caches using representative costs and behavior. Use for optimization work or changes that affect input latency, redraws, large collections, background jobs or retained memory; not as a benchmark gate for every edit. +description: Review performance of every coherent runtime-code change before commit. Trace execution frequency, CPU/GPU work, allocations, memory, latency, I/O and resource lifetime; prevent measured Nocterm regressions. Use relevant profiling and behavior evidence for hot paths; routine edits do not require a benchmark suite. user-invocable: false --- # Runtime cost and rendering -AGENTS.md's Performance rule applies. Keep notes and results in the existing -compact plan; this procedure creates no extra approval or completion stage. +AGENTS.md's Performance rule applies. Use this procedure both when designing +runtime code and after writing it: the post-change review is mandatory before +a local commit. Keep findings in the existing design review/compact plan; do +not create a parallel approval stage or run a full benchmark suite for routine +edits. + +## Post-change review (always for runtime code) + +1. Inspect task-related committed, staged, unstaged and relevant untracked + changes, not just the last edited file. Trace new/changed calls through real + producers, consumers, observers, lifetime and platform boundaries. +2. For every changed runtime path identify its trigger (one-shot, per item, + per event, per frame, periodic), maximum relevant size, multiplicative + fan-out and owner. Compare old and new work: algorithmic passes, allocations + and copied bytes, CPU/GPU operations, I/O, latency and retained resources. + Include no-change, idle, cancellation and large-input cases when applicable. +3. Apply the checklist below and read matching sections of + [review patterns](review-patterns.md) for concrete examples. A newly added + avoidable heavy operation in a frequent path, unbounded queue/cache/work, + or demonstrated regression is blocking; name the triggering workload and + smallest correction. Do not label a cheap bounded operation a blocker merely + because it has a theoretical alternative. +4. Fix blocking findings within the task, re-review the changed paths, and + obtain relevant behavior/cost evidence using the existing gate. For ordinary + low-cost paths a reasoned inspection is enough; for claimed speedups or + consequential changed hot paths use a representative measurement or report + precisely why it is unavailable. Never claim a measured improvement from + code inspection, a green test suite or FPS alone. + +Record the outcome in the design review: inspected paths/triggers, workload +and expected or measured cost change, blocking findings/fixes, remaining +evidence limitations, and verdict (pass / changes required). If a change has +no runtime effect, state that briefly and stop this review. + +## Checklist + +- **Algorithm and allocation:** avoid repeated full collection traversals, + nested linear lookup, repeated normalization/serialization, large clones + before filtering, unnecessary intermediate strings/Vec/JSON values, and + allocating per item when existing borrowed slices, shared immutable data or + bounded scratch storage suffice. Preserve order, Unicode semantics, payload + bounds and checked mutations. +- **Rendering/GPU:** work proportional to the visible/changed region, not the + full catalog or history; avoid rebuilding unchanged view identities, text + shaping, image decode/upload, scene/buffer allocation or paint. Distinguish + layout, paint, submissions, actual GPU work and presentation. Do not cap + refresh or suppress valid frames to make a performance number look better. +- **Events and background work:** no unchanged-state notify, broad observer + fan-out, duplicate polling/subscriptions or timer wakeups in idle, hidden + or closed views. Scope updates to interested owners; coalesce only when + observable order, final state, feedback and cancellation remain correct. +- **I/O and concurrency:** no blocking I/O or heavy parsing on foreground + callbacks; avoid per-byte/row RPC, metadata query or process spawn. Batch + where semantics permit; bound queue count and bytes, worker concurrency, + retries, timeouts, and in-flight data. Do not trade responsiveness for + starvation or weaken durable write/admission/security contracts. +- **Memory/lifetime:** assess cumulative requested bytes separately from + retained memory and peak RSS/PSS; account for decoded pixels, GPU + VRAM/GTT, shared buffers, retained callbacks, clones and per-window/session + multiplication. Reclaim unused objects on close/cancel and handle late + results; avoid speculative caching or unbounded reuse buffers. +- **Evidence:** compare representative work across small/large, unchanged/ + changed, warm/cold and loaded/idle conditions as appropriate. Verify exact + output, UI behavior, and other observable contracts before accepting wins. ## Find the cost diff --git a/.claude/skills/performance/review-patterns.md b/.claude/skills/performance/review-patterns.md new file mode 100644 index 00000000..07244cd2 --- /dev/null +++ b/.claude/skills/performance/review-patterns.md @@ -0,0 +1,161 @@ +# Nocterm performance review patterns + +Read the sections relevant to changed execution paths. These are lessons from +measured Nocterm optimization work, not rules that every code path must use +the same implementation. Prefer the simplest adequate change; preserve +behavior, layer ownership and lifetime. Reuse existing benchmark fixtures +rather than inventing duplicate harnesses. + +## CPU, algorithms and allocation + +**Trace cost multiplication.** A linear scan in a once-per-frame function +becomes expensive when repeated for every row, window, session or event. +Partition/group once, index repeated lookup at the existing owner when useful, +reuse prepared results on unchanged inputs, and check the worst supported +size. Preserve ordering, duplicates, identity, matching semantics and empty +results. Do not trade a small linear scan for an unnecessarily persistent +index. Connections/catalog reconciliation and workspace list projection +benefited from eliminating quadratic/repeated full scans. The cold Hub +mirror and detach fixtures in +[replication tests](../../../crates/connections-store/src/replication/tests/performance.rs) +exercise bulk and steady cases. + +**Borrow or move before cloning.** Check what actually needs ownership. +Use slices/iterators/borrowed views, move already-owned values, share immutable +payloads where lifetimes justify it. Filter/select before cloning, format only +what is displayed or copied, avoid decoding/encoding the same JSON/text/image +for each consumer. Count calls and requested bytes, including deep nested +payloads; a cheap Arc clone is not a deep String/Vec clone. Avoid retaining a +huge source buffer just to save a tiny copy. If a payload can be locally +reused, bound the scratch capacity and lifecycle. Do not cache secrets. + +**Skip work proven unnecessary, not merely unlikely.** Use an exact no-op +test or a necessary condition that cannot exclude a legitimate result. +Maintain Unicode, segmentation, error, boundary and ordering semantics. +The [redaction fixture](../../../crates/ai/src/redact.rs) measures ordinary, +sparse and dense matches and verifies the complete output. Reusing capture +storage and skipping provably irrelevant text reduced work without changing +the policy. This is not permission to weaken validation or security checks. +For specialized fast paths, characterize the fallback as well as the fast +case and compare against the actual previous behavior. + +## Rendering and GPU + +- Prepare stable model projections on source/query changes, consume them + during render; virtualize large lists using existing ListState/viewport + facilities. Render visible rows and bounded overscan, not every row. + Check variable heights, scroll anchors, focus/keyboard traversal, + accessibility, selection, filtering and action identity. The + [workspace fixture](../../../crates/projects/src/tests/library.rs) measures + large scroll and search with behavior assertions. +- Keep semantic state changes separate from focus, hover, animation and + geometry. A cursor blink or unchanged status must not rebuild a whole + transcript/catalog; an actual change must still invalidate the view. + Reuse stable identities rather than creating replacement entities and + subscriptions on redraw. Disable invisible animation only when its + lifecycle and visible behavior allow it. Do not reduce the refresh rate + or change animation duration merely to improve CPU numbers. +- Check for repeated text shaping/parsing, unused decoration geometry, + unnecessary image decode/resizing, texture uploads, buffers, layout + passes, hitboxes or scene copies. Preserve font/theme/scale, wrapping, + clipping, bidi, scroll and input behavior. Bound any reused buffer or + GPU resource by actual cost and dispose when its owner ends. +- Measure process/main-thread CPU, draw/submission work, actual device + graphics work and memory (including VRAM/GTT), plus operation-to-next + buffer latency. Samples from GPU timestamp queries describe the measured + encoder interval, not every GPU operation or input-to-photon. + A faster FPS counter with higher unnecessary work is not an optimization; + a lower FPS cap is not evidence of fewer operations for equivalent work. + +## State, notifications and idle work + +- Compare the relevant immutable snapshot/section or revision, not a full + unrelated document. Reuse unchanged results and suppress only equivalent + observable publications. Avoid rebuilding every consumer for one changed + row; retain identities and notify the exact affected owner. The + [settings tests](../../../crates/settings/src/store/tests.rs) measure + registered/snapshot costs; [layout publications](../../../crates/workspace/src/workspace/layout_switch_tests.rs) + exercise multi-window composition. +- Review callbacks for captured large data and stale references. Use narrow + IDs or shared immutable snapshots when safe; retain checked expected + records or revisions where needed for mutations. Freshness/authorization + remains with its original authoritative owner. +- One source can feed multiple active subscribers when semantics permit. + Stop polling, refresh timers and detached work when interest disappears; + bound necessary independent services. Verify both hidden/idle and active + states, and behavior after cancel/reopen. The Linux + [vault idle test](../../../crates/vault-store/tests/worker_idle.rs) + samples the worker's CPU time and context switches, not elapsed sleep + time. The [plugin-view handoff fixture](../../../crates/plugin-view/src/tests/performance.rs) + compares changed and equal views. + +## I/O, transport and background work + +- Count actual syscalls/metadata reads, RPCs, started processes, full-file + writes and user-visible round trips. Request only needed metadata/payload + and use existing projection/streaming ports. Prefer batching/pipelining + where ordering and error semantics permit, with bounded byte and request + budgets, backpressure and fair admission. Large transfers should not + starve terminal echo, input or discovery. +- Preserve durability and mutation semantics. A memory-only mirror is not + equivalent to a durable store; do not batch away required acknowledgements, + fsync or checked revisions to make a synthetic benchmark faster. +- Do not hold foreground/shared-state locks while doing expensive encoding, + filesystem, network or process I/O. Stage data through existing owners, + cancel obsolete work, validate the current scope before publication and + dispose of late results. Moving work to a background task does not remove + CPU, memory or scheduling cost. +- Test latency with real isolated local services where feasible, with + controlled delay and exact payload/operation outcomes. Measure both bulk + throughput and interactive latency under concurrent load. The + [SSH performance fixtures](../../../crates/ssh/tests/cases/performance.rs) + include controlled-latency SFTP and terminal echo. Never target real + accounts or servers without authorization. + +## Memory and lifetime + +Distinguish requested allocation traffic, successful allocation calls, +peak RSS, PSS/anonymous PSS, retained heap, mapped/shared pages and GPU +residency. They answer different questions. Account for data growth across +windows, sessions, history, scrollback, plugin instances, observers and +decoded images. An optimization can reduce allocation traffic while keeping +resident memory unchanged or increasing retained buffers; measure the +tradeoff. Check teardown and repeated open/close and large-to-small changes. +The [VT selection fixtures](../../../crates/vt/tests/selection_cost.rs) +check history sizes/widths and exact copied content rather than assuming +that shorter retained text implies lower memory. + +## Choose defensible measurements + +1. Name the operation, owner, input shape and exact completion boundary; + measure frequency × work and the caller-visible output. A producer + finishing does not prove its consumer, rendering or durable write finished. +2. Use optimized/release builds with comparable settings, workload, input + count, size, display cadence, device/backend and initial state. Compare + old/new in repeated alternating runs (ABBA when appropriate), separate + cold/warm/unchanged/changed paths. Report p50/p95 or distributions for + latency, and absolute work per operation/interval. Short microbenchmarks + need enough repetitions and realistic controls to reveal regressions. +3. Pick counters for the cost under investigation: CPU scheduled time, + instructions/cycles, allocation count/requested bytes, memory residency, + GPU work, calls/bytes/I/O or latency. Use separate profiling lanes where + tracing, sampling, allocation interception or GPU queries perturb timing. + Identify scope: app, thread, whole process tree or server. Single-core + pinning is a stress/control for concurrent workloads, not multicore + latency; do not confuse wrapper or child measurements with app-only cost. +4. Verify the same complete output and visible behavior (exact buffers, + render/crop comparisons excluding only explained dynamic regions, + selection/focus and cancellation). Check that the intended fixture + actually executed and did not skip due to an unavailable service. +5. Reuse the repository's [performance harness](../../../scripts/perf/README.md) + and existing manual fixtures. Isolate user data, processes, profiles and + compositor; do not alter the installed application or user's display. + If only a virtual compositor or partial platform is available, identify + that limitation. Do not claim physical scanout, other OS/device, or + real-world WAN results from the isolated test. + +For automated regression gates, prefer deterministic assertions about +observable operation counts, byte/queue budgets, unchanged publications, +exact output and lifecycle. Manual performance fixtures may report timing +and counters; avoid fragile wall-clock thresholds in ordinary CI. Record +actual evidence and regression tradeoffs, not a universal speedup. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2b8489e8..601ee2b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -314,12 +314,20 @@ jobs: workspaces: | vendor/alacritty_terminal -> target vendor/gpui-component -> target + vendor/gpui-base -> target - name: Test the vendored terminal emulator if: ${{ !cancelled() }} run: cargo test --manifest-path vendor/alacritty_terminal/Cargo.toml --lib - name: Verify native menu patch if: ${{ !cancelled() }} run: cargo test --manifest-path vendor/gpui-component/Cargo.toml --locked --features test-support --lib menu::app_menu_bar + - name: Verify calendar and time controls + if: ${{ !cancelled() }} + run: | + cargo test --manifest-path vendor/gpui-base/Cargo.toml --locked --features test-support --lib calendar + cargo test --manifest-path vendor/gpui-base/Cargo.toml --locked --features test-support --lib time_field + cargo test --manifest-path vendor/gpui-component/Cargo.toml --locked --features test-support --lib time:: + cargo test --locked -p gpui-pre-scheduler --lib clock::tests # Installers ship for Windows, so a pull request also checks that the whole application # builds there; release validation would otherwise be the first to compile it. @@ -364,15 +372,17 @@ jobs: - name: Test authenticated MCP bridge after idle and refresh on Windows if: runner.os == 'Windows' run: cargo test --locked -p nocterm-acp --lib bridge::tests + - name: Check the application builds for Windows + if: runner.os == 'Windows' + run: cargo check --locked -p nocterm + # Held directories, chat history and agent launch have Windows-only code paths: + # run them against the real filesystem and process APIs there. - name: Lint Windows history adapters and test agent environment if: runner.os == 'Windows' run: | cargo clippy --locked -p nocterm-localfs -p nocterm-agent-storage -p nocterm-agent-runtime --all-targets -- -D warnings cargo test --locked -p nocterm-ai -p nocterm-agent-storage cargo test --locked -p nocterm --test native_chat_history - - name: Check the application builds for Windows - if: runner.os == 'Windows' - run: cargo check --locked -p nocterm # The one check to require in branch protection: it passes only when every # job above passed or was skipped by design, so adding a job never needs a diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ada7355e..3d3c5268 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "3.1.0" + ".": "4.2.1" } diff --git a/AGENTS.md b/AGENTS.md index e1f4b657..b3715828 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Follow [CONTRIBUTING.md](CONTRIBUTING.md) for Git, PR and vendor rules. - Record the target (`master` release / `dev` integration); branch from it using `/`. Never commit directly to `master` or `dev`. -- Commit, push and open PRs only when the user asks; use Conventional Commits. +- Create local Conventional Commits autonomously after coherent changes pass the applicable checks. Keep commits focused; do not include unrelated user changes. Push and open PRs only when the user asks. - Never edit `CHANGELOG.md`, `version.txt`, `.release-please-manifest.json` or create tags: releases are automated. Never bypass hooks or weaken checks. - Rust files stay at or under 800 lines, tests included. This is a ceiling, not @@ -82,14 +82,17 @@ Use [port-design](.claude/skills/port-design/SKILL.md) for contracts and ## Performance -For changed hot paths, assess frequency × work per event and retained memory. +Before committing every coherent runtime-code change, apply the post-change +review in [performance](.claude/skills/performance/SKILL.md) as part of design +review. Fix blocking performance findings and recheck affected behavior. For +changed hot paths, assess frequency × work per event and retained memory. Keep blocking I/O and expensive computation off render/input callbacks. Remove redundant work, repeated parsing/scans and unchanged-state notifications; use bounded, coalesced background work with cancellation. Check the affected visible behavior. Cache worthwhile repeated work with an explicit owner, complete key, invalidation, memory bound and teardown; never use a cache as authorization or a second source -of truth. Follow [performance](.claude/skills/performance/SKILL.md) for rendering, -cache and cost evidence. Measure representative before/after cases for optimization +of truth. Use the performance procedure for rendering, cache and cost +evidence. Measure representative before/after cases for optimization claims; describe unmeasured expectations honestly. Routine edits need no benchmark suite. ## Tests @@ -134,4 +137,4 @@ After review fixes, finish the [completion matrix and applicable fixtures](.clau Broad shared changes, uncertain workspace impact or an explicit full-verification request require the full suite there. Required CI and limits remain unchanged. Report actual commands/results, scope and omitted checks with reasons; a scoped -pass is not a workspace pass. Commit, push and PR still require the user's request. +pass is not a workspace pass. Commit verified task changes locally without asking; push and PR still require the user's request. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f484ec5..af56283f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,688 @@ # Changelog +## [4.2.1](https://github.com/cu-e/nocterm/compare/v4.2.0...v4.2.1) (2026-12-03) + + +### Bug Fixes + +* **deps:** replace chrono in application time paths ([8affb09](https://github.com/cu-e/nocterm/commit/8affb09b44c14c9bab0b75efe6ac011e053c45fd)) +* **deps:** update url and curve25519-dalek ([aa13694](https://github.com/cu-e/nocterm/commit/aa1369477679a4630d97e7fb9f1f6a31ecaf2680)) + + +### Performance + +* **agent:** streamline chat streaming and attachments ([2e6908f](https://github.com/cu-e/nocterm/commit/2e6908f63d031dafa00e609537dd93e34b96dcf0)) +* **connections:** streamline catalog and hub synchronization ([3d6e392](https://github.com/cu-e/nocterm/commit/3d6e3927f2744b5a0f2410cfac0e2bbd3b570177)) +* **files:** bound explorer and container presentation ([74ac8ad](https://github.com/cu-e/nocterm/commit/74ac8addc0d8f43784948b2a470fd20b663578f3)) +* **gpui:** drive selection scrolling with window frames ([714a14e](https://github.com/cu-e/nocterm/commit/714a14e693c218b23b6b5110c08e3eb15919aafe)) +* **monitor-ui:** reduce collection and graph work ([963fceb](https://github.com/cu-e/nocterm/commit/963fceb83576cdb6f62269addb0aaec0813cd5e6)) +* **plugin-host:** reduce guest execution and render overhead ([fe998ce](https://github.com/cu-e/nocterm/commit/fe998ce1f7f99ea27460c46bddd5c197bec4f085)) +* **settings-ui:** avoid repeated settings and theme projections ([2fafcc1](https://github.com/cu-e/nocterm/commit/2fafcc1a37b0244f797e78a00e7cc3e5da1e49a2)) +* **ssh:** streamline transport and native process work ([0d24efc](https://github.com/cu-e/nocterm/commit/0d24efce1e3ab5a9850d5a0a20c498b062241b69)) +* **terminal:** reduce input and scrollback processing ([f2f01eb](https://github.com/cu-e/nocterm/commit/f2f01eb59cfb187baff0dce0ecf70411667f60d6)) +* **ui:** virtualize chat history and reuse terminal render work ([74d043f](https://github.com/cu-e/nocterm/commit/74d043faec2d8170bb8e480da4366b93c3c4beee)) +* **vault-ui:** reduce credential and device unlock overhead ([f19ef1c](https://github.com/cu-e/nocterm/commit/f19ef1c602ff549ee9f591932593eddf2e89af0d)) +* **vendor:** optimize rendering and terminal primitives ([c19ffef](https://github.com/cu-e/nocterm/commit/c19ffef33c0116b7f444f3adcda83e64a5482cad)) +* **workspace:** streamline layout and tab publications ([f4066e4](https://github.com/cu-e/nocterm/commit/f4066e448449c85b4ed98dbb69a04242e838fd6a)) + + +### Documentation + +* **agents:** commit verified task changes autonomously ([c5cf3a7](https://github.com/cu-e/nocterm/commit/c5cf3a77dc6f095d9985565753a65ee1fff4b6cd)) +* **agents:** enforce post-change performance review ([f605a74](https://github.com/cu-e/nocterm/commit/f605a74810ffe29369164bc8fa1afa4ef4e5a828)) +* **architecture:** record optimized ownership contracts ([d1fa21e](https://github.com/cu-e/nocterm/commit/d1fa21e87a6cdac6ee1073dc25f315b08aed077f)) +* **plugin-sdk:** fix context documentation link ([2d210f6](https://github.com/cu-e/nocterm/commit/2d210f6537474cdfaecce499218d4fc8b522f903)) + +## [4.2.0](https://github.com/cu-e/nocterm/compare/v4.1.1...v4.2.0) (2026-11-15) + + +### Features + +* **agent:** copy conversations from the chat title menu ([ee01c68](https://github.com/cu-e/nocterm/commit/ee01c686d0834a810ac2590359d39d6d09e7b018)) + + +### Bug Fixes + +* **acp:** clear authentication timeout on the retained reader ([c4f298c](https://github.com/cu-e/nocterm/commit/c4f298c9f0f1dab6f7cf75baa54ddd717f465d9a)) +* **agent-runtime:** retain larger conversation histories ([3b000e9](https://github.com/cu-e/nocterm/commit/3b000e9f261031306969fe98065d5b936ea3be6a)) +* **agent:** contain nested transcript scrolling ([547598d](https://github.com/cu-e/nocterm/commit/547598dd5d050491bd4361f3293fb237a0fb9b7b)) +* **agent:** keep attachment choices stable across session updates ([70e5c23](https://github.com/cu-e/nocterm/commit/70e5c2373307e45f7d931727fe650678f7c179eb)) +* **deps:** use patched native transport dependencies ([#65](https://github.com/cu-e/nocterm/issues/65)) ([98e48bf](https://github.com/cu-e/nocterm/commit/98e48bf4c834d03b64f5a89e7ab5b83aff84b263)) +* **gpui:** preserve relative wheel geometry in virtual lists ([9faa00b](https://github.com/cu-e/nocterm/commit/9faa00bf513b03e408d133617bed57b9f8daba1b)) +* **localfs:** retain native Windows directory capabilities ([55074a8](https://github.com/cu-e/nocterm/commit/55074a84655a14dc57483901af7d3a476afbe5af)) +* stabilize agent chats across native sessions ([765be46](https://github.com/cu-e/nocterm/commit/765be46d57011f1e2e645ec0eaf378643591cc30)) + +## [4.1.1](https://github.com/cu-e/nocterm/compare/v4.1.0...v4.1.1) (2026-11-10) + + +### Bug Fixes + +* save new chats, find npx and hide agent consoles on Windows ([#59](https://github.com/cu-e/nocterm/issues/59)) ([a1d4e62](https://github.com/cu-e/nocterm/commit/a1d4e62ef2f314ef61c02755fd9e2613a95120c6)) + +## [4.1.0](https://github.com/cu-e/nocterm/compare/v4.0.0...v4.1.0) (2026-11-10) + + +### Features + +* ship user plugins in every build ([#54](https://github.com/cu-e/nocterm/issues/54)) ([83ec876](https://github.com/cu-e/nocterm/commit/83ec876bc7c7cc07634ac8a9e2c319f3751e19f5)) + + +### Documentation + +* **plugins-ui:** stop linking public docs to the private describe ([#57](https://github.com/cu-e/nocterm/issues/57)) ([067e067](https://github.com/cu-e/nocterm/commit/067e067944a7aa5d16e80d183f1bbdb3bd3064b4)) + +## [4.0.0](https://github.com/cu-e/nocterm/compare/v3.3.0...v4.0.0) (2026-11-10) + + +### ⚠ BREAKING CHANGES + +* hub chats run on the hub and use the agent chat UI; the device-side Cloud code, the node session transport, the session lists and the sessions panel are removed, as is the account server choice. The chat journal format is version 8. workspace::SwapSides is replaced by the Window → Layouts → Swapped sides layout, and Ctrl+E / Cmd+E reach the terminal instead of swapping the side panels. + +### Features + +* agent access connects with saved credentials; profiles have one space ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-chat:** refuse file transfer calls until execution is wired ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-chat:** run agent file transfers with paired approvals ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-engine:** install runner-bound provider credentials ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-engine:** offer the model only an allowed set of tools ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-engine:** renew provider leases and add the broker endpoint ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-runtime:** supply transfer requests to chats ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-tools:** publish admitted initial sessions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-tools:** reuse connected terminals for allowlisted servers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-tools:** run file transfers for headless runs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** a Servers control for Cloud chats and bound servers in history rows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** add the Cloud tab to the new-agent menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** attach a hub chat's servers from the attach menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** attach files of any kind with the paperclip ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** describe file transfer approvals and tool inputs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** draw one composer and footer for Local and Cloud chats ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** every window lists every chat; a resting chat moves to the window that opens it ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** file tools for attached terminals that run no programs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** list a hub's Cloud chats in the history column ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** open Cloud chats from the Cloud menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** open the chat of an online-only agent on the own runner ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** present captured conversations in the shared panel ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** separate local and server chats in a hub window's history ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** stop and remove a seat from its agent row ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ai:** add file transfer tools to the terminal catalog ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** add Layouts and Panels submenus and the plugins reference ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** add Noct brand mark and default themes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** add nocterm plugin dev ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** add the Servers page and Hub commands ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** compose the Cloud chat launcher ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** compose the layout editor into Appearance ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** compose the Plugins page and plugin settings ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** compose the wasm runtime for user plugins and plugin check ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** compose user plugins into windows, menus and check command ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** dial hub routes through the hub links ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** follow the hub account for the vault and profiles ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** give a hub window the account's connections and vault ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** hold user plugins in safe mode and until the user allows them ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** inject the system clock ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** list plugin settings in the plugins reference ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** open and switch hub windows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** open windows in a local or hub environment ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** reattach hub sessions of restored windows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** remove the swap-sides shortcut ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** restore window environments after restart ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** share the transfer runtime with agents ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** show the account's spaces and announce a refused change ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** store plugin records and data ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** wire the agent hosts observer and agent access ports ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-agents-model:** add the Cloud chat launcher port ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-agents:** add the Cloud agents model and catalog service ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-agents:** answer bound Cloud chats' certificate requests while unlocked ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-agents:** route offline-off personal agents to the own runner ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-agents:** stop and remove seats, state the web panel url ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-chat:** allow a queued run to use the model ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-chat:** handle captured tool approval answers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-chat:** show a Cloud tool row with the core's title and typed outcome ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-chat:** show sent prompts as pending until the runner accepts them ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-conversation-model:** add the neutral Cloud conversation model and port ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-conversation-model:** bind a Cloud chat to servers and run prompts on one ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-conversation-model:** say a chat is Opening before its first round ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-model:** admit chat SSH bindings and certificates ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-model:** derive runner chat summaries from journaled facts ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-model:** grant transfers through the execution bit ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-model:** open a chat when its key is admitted ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** announce deleted chats to the hub for retirement ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** broker original-run sessions on the native runner ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** claim a chat's writer on key admission ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** journal v7 summary rows and coordinator summary publication ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** keep chat SSH keys in journal v8 and run their transitions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** let the runner relax approval for contained targets ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** list a bound chat's servers in its summary ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** persist the outbox retry horizon (journal v6) ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** seal the chat SSH row under its own journal class (journal v9) ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** supply native timer and captured identity IDs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-runner:** wake runs parked for provider access ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud:** persist captured account conversations ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-io:** keep the replica state in a private file ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-model:** place profiles in a space and move them ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-model:** reconcile profiles with a replica ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-model:** report a locked replica ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** move a profile's secrets with it between spaces ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** place profiles in a space, roll back a refusal ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** replicate profiles ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** show a locked account ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** a group's button opens every connection of the group ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** announce connected sessions to an observer ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** choose, create and import vault keys in the editor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** install connections kept only in memory ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** keep a typed password in the window's vault and drop the unsaved agent servers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** offer the agent servers this window has not saved ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** show organization sections and choose a space ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** show the account state above the list ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **core:** add a one-line error cause chain for log records ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **core:** define the wall-clock contract ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **core:** read bounded regular files without following links ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **design:** let the sidebar widen as far as the agent panel ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **files:** offer transfer counts to plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **files:** show relayed copies in transfer activity ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* hub chats run on the hub and use the agent chat UI ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* hub chats, managed agents and user plugin toolbars ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-agents:** follow agent and server changes of a hub ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** adapt the Cloud agents ports over the hub contract ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** admit persistent runner inbox commands ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** answer fresh runner head probes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** attach terminal tabs to hub sessions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** confirm administrator keys before opening groups ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** confirm administrator keys through a narrow port ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** create and list Cloud chats ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** give each trusted server its own CA principal with the contract CA ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** import bounded public runner setup documents ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** journal file transfer tool calls ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** keep own-runner agent keys and carry provider grants ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** keep the account keyset and an encrypted cache ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** lease a personal agent's key to the own runner ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** list and revoke account devices ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** map chat SSH grants, events and certificates for the runner ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** move credentials between the personal vault and a group ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** offer a new recovery key while one is unconfirmed ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** open relay streams ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** open the account keys at sign-in and recovery ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** persist and republish chat key grants ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** reach hubs through the contract with device credentials ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** read failure codes and provider kinds from the contract ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** report closed account keys as locked ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** restore account Cloud trust and runner catalogs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** resume a Cloud command kept across a restart ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** retain runner authority across token rotation ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** run Cloud chats on the contract device core ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** seal a provider lease to a verified runner boot ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** send a provider lease to a chat without a window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** send publication retry horizons and retire deleted chats ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** serve group profiles and credentials of organizations ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** show the organization name the hub sends in Cloud ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** sign, seal and publish runner chat summaries ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** store the agent SSH CA and trust registry as E2E data ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** wake a chat's seat with the core's WakeSeat ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** add an optional colour to a known server ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** add hub addresses, trust rules and access ports ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** add the account devices port and its fake ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** add the account server and the account key states ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** add the agent host trust and chat grant ports ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** name the environment a window shows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** remember the organization and sessions of a hub window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** report the id of a session that a terminal starts ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** add environment menu, sign-in dialog and sessions panel ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** add the agent access tab to the Servers page ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** add the Cloud agents tab to the Servers page ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** ask for the instructions of a personal agent again ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** confirm administrator keys on the Servers page ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** keep the recovery key step open until it is saved ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** list and forget pinned pool keys ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** lock and unlock the account keys in Agent access ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** manage known servers in settings ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** open the selected session with Enter ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** remember and reattach the sessions of a hub window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** show per-model usage in the Cloud agents tab ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** sign in again to a known server from its window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** sign-in steps for account keys and the account server ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** split the Servers page into a list and tabs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** switch a window between this computer and a hub ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** add the hub registry, connection status and sign-in service ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** choose the server that keeps the account ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** list and confirm the pending administrator keys of a hub ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** offer account devices through the registry ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** prefer a remembered organization in a hub window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** reach the agent SSH CA through the hub service ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** redraw the Servers page when account keys open or close ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** rename, recolour and safely remove known servers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* integrate cloud chat execution and desktop foundations ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **layout-ui:** edit the bar in its preview by drag and menus ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **layout-ui:** edit the status bar and panels in Appearance ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **layout-ui:** show the host's facts for user plugin items ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **local:** contain cloud tool child processes on Linux ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **local:** integrate contained interactive shell sessions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **local:** read the local wall clock ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **monitor-ui:** anchor the host monitor popover to its zone ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **monitor-ui:** declare the status bar metrics as plugin settings ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **monitor-ui:** offer the monitor reading to plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-abi:** add the guest call ABI and its wire types ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-api:** add the user plugin contract and declarative runtime ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-api:** declare the wasm runtime and the code package format ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-api:** type the manifest keys of the surface ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-enablement:** add the plugins settings section ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-enablement:** add the user plugins switch to [plugins] ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-enablement:** keep user plugin ids out of the plugins section ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-host:** add session-only records and data ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-host:** add the plugin host, broker and per-plugin data ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-host:** count code runtime faults toward the disable limit ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-host:** expose installed plugins to the shell ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-host:** remove a plugin's data on its own ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-model:** add the plugin set of both tiers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-model:** add user plugin tiers, ids and the clamp ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-model:** declare plugin settings schemas ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-model:** mark a plugin set as held or as a developer's ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-packages:** add the session package store ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-packages:** read a package directory for the check command ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-packages:** read, hash, store and remove user plugin packages ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-packages:** read, store and check wasm packages ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-ports:** add observation and effect ports for user plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-ports:** say which capabilities a provider record provides ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-sdk:** add testing::Host over the real ABI ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-sdk:** add the example code plugin, its guest test and guide ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-sdk:** add the guest SDK, view builder and export macro ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-sdk:** re-export Effect, so a plugin's tests can read its effects ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-sdk:** re-export what guests need for requests and views ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-view:** draw validated plugin views in a host frame ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-view:** mark developer plugin frames ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-wasm:** run code plugins on wasmi within resource limits ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** a compact plugin detail with folded lists and removal in a dialog ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** add the Plugins settings page ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** add the User section behind the user feature ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** confirm before removing a plugin or its data ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** install plugins from a button or the plugins folder ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** link a plugin to the status bar editor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** list external plugins with the built-in ones, with one switch ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** offer the development plugin with a DEV consent ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** show the allow switch and why user plugins are held ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** a plugin's terminal tab can serve files to the explorer and AI chats ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** a plugin's terminal tab carries the plugin's bar along one edge ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** a plugin's toolbar keeps to its own tabs and the user places it ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** arrow-left and chevron-left glyphs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** build plugin views from the application's own components ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** charts in plugin views, toolbars that know their axis, and toolbar moves that apply ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **projects:** add folder workspaces with scoped chat history ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **projects:** support container-backed workspaces ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** add the managed mode with a bounded stdin boot document ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** approval never trusts the runner's contained targets ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** bind chats to reachable servers and sign in with their certificates ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** compose the execution runtime for the daemon ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** narrow tools, limits and spend by the boot policy ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** publish chat summaries from the delivery sweep ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** read chat access frames from the host ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** read the agent policy from boot v2 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** relay agent transfers through a remote-only runtime ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** run managed tools through the host broker ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** run prompts on bound servers and read boot v3 with the contract ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** send the agent's instructions as the managed system prompt ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** supervise persistent Cloud control-plane sessions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **session:** add Event::Restore for the screen of an attached session ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **session:** add pipelined remote read batches ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **session:** route the first hop through a hub relay ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **session:** sign in with a key kept in the vault ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **settings-ui:** open a settings page at an anchor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **settings-ui:** scroll to a section of a settings page ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh-keys:** derive the raw Ed25519 public key of a seed ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh-keys:** issue agent certificates from a personal user CA ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh-keys:** parse, normalize and fingerprint SSH keys ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** authenticate with a key kept in the vault ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** dial the first hop through a relay stream ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** edit authorized_keys through the user's session ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** sign a runner in with a chat's in-memory key and certificate ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** sign in with a vault key and its user certificate ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** answer vault key requests from the vault only ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** derive an installation with other credentials ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** expose the connection filesystem to consumers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** open tabs on an attached session ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** restore the screen of an attached session ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* toolbars for plugins, and requests, timers and terminals for user plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfer-runtime:** relay between remote hosts and run remote only ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfers:** add relay requests, endpoints and owned transfer books ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** anchor status bar popovers to a zone ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** compose settings pages from owner sections ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** find the settings of user plugins through the directory ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** let plugins post and read their own notices ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** let settings pages reveal an anchor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** offer a Nocterm hub as a proxy ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** render plugin settings forms from schemas ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault-ui, connections:** search saved passwords and add one in a dialog ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault-ui:** answer vault key requests and list keys by fingerprint ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault-ui:** install a vault for the windows that use it ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault:** bind a credential to an SSH public key ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault:** mark group credentials and refuse writes to read-only ones ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault:** report offline and unsupported operations ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault:** saved passwords sign in to the servers they list and are managed by name ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vendor:** expose native input document revisions ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **vt:** reset an emulator in place and keep its generation counting ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-layout:** edit layout presets on the current settings ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-layout:** keep disabled plugins out of resolved layouts ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-layout:** let panels stand alone and users make groups ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-layout:** read layout presets from settings ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-set:** remember the environments of open windows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-set:** save what a hub window keeps of its server ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace-ports:** add the terminal files port ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** add a title-bar slot for the environment menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** add the clock plugin ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** add the status bar context menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** anchor widget popovers to their zone ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** apply plugin enablement live in every window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** centre the status bar and order shrinking ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** collapse overflowing status bar items into a menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** give the title bar an environment slot ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** lay out panel columns in the order of the bar ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** list the placed panels for the window menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** name a developer session's panels with DEV ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** offer the workspace kind to plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** read plugins through a source of both tiers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** replace the swap-sides action with a layout ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** switch layout presets from the window menu ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** ban the wasmi auto-dispatch feature in every member ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** check plugin crate isolation ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** check the plugin ABI golden file and document the ABI ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** generate the manifest schema and check the plugin guide ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** generate the plugin API reference for authors ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** generate the plugin API surface ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** keep guest-only crates out of the app closure ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** let the plugin host notify its observers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** limit the hub contract and protocol SDK to hub-io ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) + + +### Bug Fixes + +* **agent-chat:** approve a transfer card for its terminal pair ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-chat:** box the rejected transfer call ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-chat:** count snapshot capacity like the retained snapshot ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-runtime:** gate the test-only work bytes export ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent-runtime:** read provider usage only through ACP ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** enforce bounded conversation work ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** make the Cloud tab a plain list of agents ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** offer Cloud agents only in the window of their hub ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** show a locked hub account as an actionable notice ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ai:** grant transfers per terminal pair ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ai:** refuse control characters in transfer paths ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** fence background SSH host preparation by source ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** keep remembered servers that are unavailable for one run ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* apply plugin effects after the host's update and refresh after the workspace's ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** publish held and developer sets and test a safe-mode edit ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** report the current revision when the vault is switched ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** retain asynchronous plugin publication workflows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** satisfy clippy after merging the hub branches ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** show the sessions panel first in a hub window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** stop polling user widgets the bar does not draw ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **app:** word a personal refusal as the event docs describe it ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-agents:** one start per agent, retry a failed start ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-chat:** keep a chat live when its runner does not answer ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **cloud-model:** name the kind of record a projection refusal rejected ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-io:** isolate DNS work and reuse HTTP connections ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-model:** read a move between scopes as a move ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** copy a secret other profiles still use ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** keep a requested move through interruptions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** keep every profile when an account is stopped ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** keep the cursor behind a refused remote change ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** reject unbounded replica feeds ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** retry transient flag acquisition failures ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** share secrets with a group only on request ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-store:** take an account's profiles off on detach ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** act on a folder only within the clicked scope ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** apply the chosen space as part of the save ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** keep the debt ratchets and the actions reference green ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** keep vault key state in its owner and Import in view ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** list a lost organization's connections read-only ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** move a saved connection only after its save ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** offer unsaved agent servers once the account's list arrived ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** say a saved secret is shared with an organization ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** share a secret when saved with the note shown ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** warn beside the save before sharing a secret ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **containers-service:** subscribe before acquiring snapshots ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **core:** reject serialization before publication side effects ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **core:** reject stale settings and profile publications ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **deps:** take the security fixes of rustls, tokio and webpki-roots ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-agents:** list a hub's agents and servers again after a failure ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** bound account publication and retire removed sources ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** coalesce lossy agent catalog hints ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** copy a shared secret under a new id ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** decode transfer arguments in their own function ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** erase the account cache and keys of a revoked device ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** fit the inference grant in the prompt's window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** hub chats no longer freeze the app and start on their first message ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** keep one client per hub and lock off the worker ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** keep one retry horizon per publication ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** never provision a seat when opening a chat ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** preserve bounded monotonic vault snapshots ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** refuse a too short password as wrong credentials ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** retry a start while the seat is still being deleted ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** serialize source clock observations ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** sign in through the derived login value ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** skip a deleted record when reading a group's secret ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hub-io:** wake a managed chat's seat before it delivers a prompt ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** forget the account server when the server is removed ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-model:** read window records one by one and keep unopened ones ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** ask to update an outdated server, not Nocterm ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** build the test workspace with the hub's change feed ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** keep the window ports private behind a constructor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** make the Servers page findable by the tests of the app ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** read the workspace after it created the sessions panel ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** reattach remembered sessions in their own organization ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** report a server that cannot be removed ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs-ui:** save a server name through the shared settings field ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** keep the organization chosen while a read runs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** refuse a sign-in to a server that is listed already ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* keep the plugins folder apart from the plugin host's files ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **keymap:** offer the hub commands in the palette ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **keymap:** publish bindings through retained persistence ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **layout-ui:** drops land where the pointer aims and never freeze the editor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* let a window's plugin terminals go with the window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **local:** build local commands on Windows and macOS again ([#52](https://github.com/cu-e/nocterm/issues/52)) ([11b5265](https://github.com/cu-e/nocterm/commit/11b526587458ee81063277499a9fa981ad9ab8dd)) +* **local:** finish PTY sessions when the leader exits ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **local:** prepare workspace shells on bounded native workers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* make agent workflows portable and proportional ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-enablement:** keep a switched-off plugin when the list is full ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-host:** retain prepared instances through publication ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugin-packages:** retain immutable consented versions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** await admitted management operations ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins-ui:** keep the detail's fold state private and its tests under the line limit ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** a plugin terminal reports a clean prompt to AI chats ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* preserve virtual list height estimates across layout changes ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **projects:** remove flex_1 from server label ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* resolve clippy findings in cloud-chat crates ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** an unknown session target stays unsupported with or without consent ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** create the inbox cursor when a runner is initialized ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** create the tool workspace on first start ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** drain transfers and sessions under one deadline ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** read the control channel without the stdin buffer ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** renew expired access before the boot announcement ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** report the cause chain of a failed start ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **runner:** size the ingress pool for one inbox read ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* satisfy test-support policy and view-field ratchets ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **snippets-ui:** every snippet row reaches the panel's right edge ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** preserve terminal admission and retry SFTP setup ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** serialize cooperating authorized keys edits ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* tell user plugin panels and toolbars when they are shown ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **themes-registry:** bound scans and recover interrupted installs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **themes-registry:** open discovered files without following links ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfer-runtime:** finish a pending write before cancelling ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfer-runtime:** name the failing side of a relay ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfer-runtime:** share capacity across independent batches ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfers:** refuse empty remote path components ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **transfers:** refuse relative local transfer paths ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** coalesce theme browser background requests ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ui:** publish plugin availability transitions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vault-ui:** sign in again when a hub's keys are not on this device ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vendor:** draw the window content uncached again ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **window-layout:** keep the user entries a held run cannot show ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **window-set:** keep unopened windows and a newer document ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** keep focus when hiding a group that does not hold it ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) + + +### Performance + +* **agent-storage:** read catalog metadata from transcripts ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** cache the chat footer to its content ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** draw the transcript and history as cached regions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** keep each message's parsed markdown per row ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** show queued messages on the first frame ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **agent:** skip redundant notifies and resolve agents once per render ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections-model:** index profiles during reconciliation ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **connections:** prepare visible rows on semantic changes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **containers:** share host watches and filter listing refreshes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **files:** publish transfer projections on native changes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **layout-ui:** bound retained layout edit history ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **monitor-service:** share collection by captured executor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **project-container-fs:** batch acknowledged upload writes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **project-model:** validate decoded catalogs once ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **projects:** redraw panels on search text changes only ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **ssh:** pipeline SFTP download reads ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **store:** notify once for an optimistic write ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** pause inactive cursor timers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **terminal:** reuse bounded search navigation work ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **vendor:** cache gpui views and keep list estimates ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **vendor:** cache views to their content and cache dock tab groups ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **vendor:** draw the window content as a cached view ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **vendor:** reuse cached views nested in a redrawn cached view ([2cbede6](https://github.com/cu-e/nocterm/commit/2cbede657ec5ef60d14c1567f5dbf62a4aa2964b)) +* **workspace:** cache status bar widgets and keep tab groups current ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** cache the tab surface so sidebar redraws reuse it ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **xtask:** reuse parsed architecture inventories ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) + + +### Documentation + +* add the hubs user guide and link it from the README ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** keep SSH keys in the vault and record the boundary ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** lease a personal agent's key to the own runner ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record agent file transfer through the shared runtime ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record Cloud chat creation protocol ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record desktop binding, answering and bound-server prompts as ADR 0139 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record profile replication ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record the hub as a route step ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record the hub client's device transport and resumable commands as ADR 0138 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** record the managed runner agent policy ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** show one environment in a window ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **adr:** supersede window environments with ADR 0099 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **architecture:** regenerate the dependency reference ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* centralize integrated verification policy ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* correct ADR 0098 on skipped entries and the Booted field count ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **deps:** regenerate third-party notices ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe agent file transfers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe bounded publication and work ownership ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe Cloud agents and managed pools (ADR 0120, 0121) ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe container filesystem ownership ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe hub environments in the layer notes and the overview ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe hub windows ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe managing servers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe the status bar and panels editor ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* describe the status bar overflow menu and zone anchors ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* fix ADR 0097 references ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* fix the links that failed rustdoc in CI ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** describe account keys, recovery and the account server ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** describe confirming administrator keys ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** describe group connections and passwords ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** describe remembered hub windows and their reattach ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** describe sessions remembered with their organization ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **hubs:** say where unsent connections go when switching accounts ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* match the hub docs to the labels of the interface ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** add example declarative plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** add the preview plugin guide and feature DoD lines ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** record the code runtime decision (ADR 0091) ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **plugins:** record the start gate and the compatibility promise ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **project-providers:** clarify adapter contract invariants ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record attached sessions in ADR 0095 and the layer notes ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record built-in panels and widgets as system plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record layout presets as app-wide settings ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record one plugin model with separate trust tiers ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record panel groups as the owner of side panels ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record per-server CA principals and runner certificate sessions in ADR 0137 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record plugin enablement and the Plugins page ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record project adapter ownership ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record project terminal contract ownership ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record runner chat summaries and journal v7 in ADR 0135 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record shared bounded contract ownership ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record standalone panels and the preview editor in ADR 0094 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the device side on the contract core in ADR 0136 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the gated hub test in AGENTS.md and the README ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the hub contract boundary in ADR 0096 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the plugin host ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the plugin SDK and developer sessions ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the user plugin contract ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the wall-clock contract ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record the zoned status bar ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record window environments in ADR 0097 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* record window restore in ADR 0098 ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **reference:** regenerate the plugins reference ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* regenerate the action and dependency references for hubs ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* regenerate the plugins reference for the sessions panel ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* toolbars, and requests, timers and terminals for user plugins ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) +* **workspace:** drop the environment menu slot from the UI note ([8135943](https://github.com/cu-e/nocterm/commit/8135943856605b1dd19803f94411210feb9451da)) + +## [3.3.0](https://github.com/cu-e/nocterm/compare/v3.2.0...v3.3.0) (2026-10-20) + + +### Features + +* **agent:** add animated thinking indicator ([4943824](https://github.com/cu-e/nocterm/commit/49438242f28c3022d2f28928b31dcb97f36bddfb)) +* **agent:** copy and highlight fenced code in chat replies ([2308f88](https://github.com/cu-e/nocterm/commit/2308f889131bf26797059a26c71a38576c736b0d)) +* **connections-model:** store and resolve profile jump hosts ([fe21b82](https://github.com/cu-e/nocterm/commit/fe21b8218e72b4c2185d6597ccd26fc4a6748983)) +* **connections:** edit jump hosts and resolve them when opening ([1d0689e](https://github.com/cu-e/nocterm/commit/1d0689e483a5cf2959d570cb7e1fb2b9d6cff955)) +* **session:** add jump host route values to the session contract ([7ecaf50](https://github.com/cu-e/nocterm/commit/7ecaf506f8083d0ac6e755f3447c2726d6a5c079)) +* **ssh:** establish sessions through jump hosts ([19670e0](https://github.com/cu-e/nocterm/commit/19670e09bc29c3a4ed02b041469a09b085cdc4aa)) +* **terminal:** label jump host prompts and use hop credentials ([3c80948](https://github.com/cu-e/nocterm/commit/3c80948878395fe880fe8351cfa345b8a36a9cfd)) +* **workspace:** carry resolved jump hosts in session specs ([6337f67](https://github.com/cu-e/nocterm/commit/6337f67eae7605448043e0cbf40ab2352554bfc3)) + + +### Bug Fixes + +* **agent-usage:** read Claude plan limits from the account ([bba1b18](https://github.com/cu-e/nocterm/commit/bba1b188c7cbce63ba86febe5cd9248c7b85d979)) +* **agent:** end a removed chat's queue edit before it leaves the roster ([e6aa903](https://github.com/cu-e/nocterm/commit/e6aa90358e6f2fe07c7b6e1392a5a887d45e3738)) + + +### Documentation + +* **agent-chat:** record chats below the panel in ADR 0063 ([b1151b5](https://github.com/cu-e/nocterm/commit/b1151b5d8c6397411f6473c9be59fc24ea6da2d2)) +* record procedure skills and early structural signals ([f8d0b2c](https://github.com/cu-e/nocterm/commit/f8d0b2c786be6b563efca95f6bb95498423db672)) +* record SSH jump host routes ([5d96600](https://github.com/cu-e/nocterm/commit/5d96600fa40ab701fa41228321fa6d70a1c6a0e0)) +* trim agent instructions and drop stale checks ([b88a65e](https://github.com/cu-e/nocterm/commit/b88a65eec70d940d4aaaba7bd566cd7d5e4c03e9)) +* **vault-broker:** add the crate ownership card ([955c36d](https://github.com/cu-e/nocterm/commit/955c36d131c7b927ab5f32886e0824b595dbf000)) + +## [3.2.0](https://github.com/cu-e/nocterm/compare/v3.1.0...v3.2.0) (2026-10-19) + + +### Features + +* **agent:** reconnect dropped server terminals on demand ([af5d3c5](https://github.com/cu-e/nocterm/commit/af5d3c5203a4e86b5e70172f5d05da6a551551a7)) +* **agent:** remove queued messages ([117a7b4](https://github.com/cu-e/nocterm/commit/117a7b43bd292ca896e89b568aefd30638817082)) +* **xtask:** limit the agent protocol SDK to its adapters ([8d51c29](https://github.com/cu-e/nocterm/commit/8d51c29b569553cd3ea4349cc941af4bd717c9da)) + + +### Bug Fixes + +* **acp:** gate Unix-only managed launch helpers for other targets ([8eb0b7f](https://github.com/cu-e/nocterm/commit/8eb0b7f6dc18378ec16eaf21cfc2fc0c82d8adda)) +* **acp:** preserve taskkill error sources ([5d10726](https://github.com/cu-e/nocterm/commit/5d1072680e15644ccf22e64c0f897c3a7399c7b9)) +* **agent-runtime:** ignore events of a released connection ([f18c221](https://github.com/cu-e/nocterm/commit/f18c2214895254d3ab54b00d841bf02087e4343d)) +* **agent-storage:** gate Linux-only replay failures for other targets ([f48c0b3](https://github.com/cu-e/nocterm/commit/f48c0b3f76936dd730f5fdf5ff388e236e7ff60b)) +* **agent-storage:** keep original faults of managed replay creation ([4fde2fc](https://github.com/cu-e/nocterm/commit/4fde2fcabb8fab36c89fcef54089c0050ad8d5ca)) +* **agent:** connect saved chats when they are shown ([714d3c3](https://github.com/cu-e/nocterm/commit/714d3c356b5bc508b510f395aacc633bc24a771b)) +* **agent:** fit the open button in the attach menu ([bb5df39](https://github.com/cu-e/nocterm/commit/bb5df397aecd7a44a5af8fa735db957e0c2afd65)) +* **agent:** keep each chat's configuration across sessions ([5d2b7d2](https://github.com/cu-e/nocterm/commit/5d2b7d2fddebdab008ef54cb012df1ac56d1e522)) +* **agent:** preserve accepted reconnect dispatch order ([e6a9e66](https://github.com/cu-e/nocterm/commit/e6a9e66f976e7bc9e3a8b0af0a3ce814d2bb9dbb)) +* **ai:** preserve workspace and sandbox native causes ([48ef259](https://github.com/cu-e/nocterm/commit/48ef259ed821cece1f0addee8c69ee102107d869)) +* **core:** prepay the ancestor list of cold private directories ([1a329d3](https://github.com/cu-e/nocterm/commit/1a329d3272233aba57445aae798a09d812f986a7)) +* **core:** retain concrete owned codec error sources ([4e4cfc4](https://github.com/cu-e/nocterm/commit/4e4cfc45fde4eaceb0cba465349de21104fcc6a5)) +* **files:** preserve directory transfers through native ports ([765d7a8](https://github.com/cu-e/nocterm/commit/765d7a8315e288f943c78c42b0dbad8ae0b95213)) +* **store:** publish append status through public handles ([b8b21df](https://github.com/cu-e/nocterm/commit/b8b21df6469f2f845e759071445b74eed02f1820)) +* **store:** retain bounded wake across recording idle periods ([d6a88e5](https://github.com/cu-e/nocterm/commit/d6a88e53952e48a9e46fbe7c5562ae7c29030f0c)) +* **terminal:** retain credential association error sources ([a54d23f](https://github.com/cu-e/nocterm/commit/a54d23fb7cea595cf19a129c1acc12710d3de5b5)) +* **ui:** preserve checked settings text submissions ([9068d7a](https://github.com/cu-e/nocterm/commit/9068d7ae94d51fb17acec13e32cc8d034df3cbcf)) +* **xtask:** resolve implicit prelude types in symbol ratchets ([43063e6](https://github.com/cu-e/nocterm/commit/43063e674b4cb847a91e97c8640579ba44bdca10)) +* **xtask:** resolve implicit prelude types in symbol ratchets ([256a821](https://github.com/cu-e/nocterm/commit/256a82179368411ff11165e4309b4a8a7033c15b)) + + +### Documentation + +* align agent guardrails with the integration workflow ([5db9f64](https://github.com/cu-e/nocterm/commit/5db9f646a011b9f5112fc342992b61c077721885)) +* **architecture:** describe crate ownership and invariants ([3f0ab91](https://github.com/cu-e/nocterm/commit/3f0ab91958d74413bc8d8d6e5803fe38350ad2ed)) + ## [3.1.0](https://github.com/cu-e/nocterm/compare/v3.0.0...v3.1.0) (2026-10-09) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f590776..71bec162 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,8 +10,7 @@ confirm that you have the right to license it under these terms. Contributions to the third-party forks under `vendor/`, including local patches, are instead submitted under the license declared by the corresponding vendored -package: Apache-2.0 for `alacritty_terminal`, `gpui-base` and `gpui-component`, and MIT for -`tid-rs`. Preserve upstream copyright notices and license files, and mark changed +package, recorded in [vendor sources](vendor/patches/sources.json). Preserve upstream copyright notices and license files, and mark changed Apache-2.0 files prominently. This policy applies to new contributions; it does not change the license of code submitted by others under different terms. diff --git a/Cargo.lock b/Cargo.lock index 57a45269..a9ccbb06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -160,7 +160,7 @@ dependencies = [ "futures", "futures-concurrency", "rustc-hash 2.1.3", - "rustix 1.1.5", + "rustix 1.1.6", "schemars 1.2.2", "serde", "serde_json", @@ -232,7 +232,7 @@ dependencies = [ "piper", "polling", "regex-automata", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-openpty", "serde", "signal-hook", @@ -482,7 +482,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -524,7 +524,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -550,7 +550,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -1007,7 +1007,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "tracing", ] @@ -1018,7 +1018,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-client", ] @@ -1035,7 +1035,7 @@ dependencies = [ "io-lifetimes 3.0.1", "ipnet", "maybe-owned", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-linux-procfs", "windows-sys 0.61.2", "winx", @@ -1158,10 +1158,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", "serde", - "wasm-bindgen", "windows-link 0.2.1", ] @@ -1694,9 +1692,9 @@ checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" [[package]] name = "curve25519-dalek" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -2536,9 +2534,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -2561,7 +2559,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.59.0", ] @@ -2738,7 +2736,6 @@ version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "337d46834ee672ab3e48caca2cb0c78cc174fb12b3a68d0d88f99a0519a5e36e" dependencies = [ - "generic-array 0.14.7", "rustversion", "typenum", ] @@ -2749,7 +2746,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link 0.2.1", ] @@ -2873,9 +2870,9 @@ dependencies = [ [[package]] name = "gloo-timers" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "482ce8a491a501da4cd806bd190275363d674f2845005c6ddbd5d3e1dd54495d" +checksum = "a4460540da666acdb5722b2a62ac47d18f627fcfc0c728d04dc7226b3f6d40a7" dependencies = [ "futures-channel", "futures-core", @@ -2946,7 +2943,6 @@ dependencies = [ "anyhow", "ashpd", "async-channel", - "chrono", "data-url", "futures", "gpui-pre", @@ -2955,6 +2951,7 @@ dependencies = [ "html5ever", "instant", "itertools 0.13.0", + "jiff 1.1.0", "lsp-types", "markdown", "markup5ever_rcdom", @@ -2981,7 +2978,6 @@ name = "gpui-component" version = "0.7.0" dependencies = [ "anyhow", - "chrono", "core-text", "enum-iterator", "gpui-base", @@ -2992,6 +2988,7 @@ dependencies = [ "gpui-pre-sum-tree", "instant", "itertools 0.13.0", + "jiff 1.1.0", "log", "lsp-types", "markdown", @@ -3086,7 +3083,6 @@ dependencies = [ "backtrace", "bindgen", "bitflags 2.13.2", - "chrono", "core-video", "ctor", "derive_more", @@ -3108,6 +3104,7 @@ dependencies = [ "image", "inventory", "itertools 0.14.0", + "jiff 1.1.0", "log", "lyon", "num_cpus", @@ -3215,8 +3212,6 @@ dependencies = [ [[package]] name = "gpui-pre-linux" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aac7022e347409454777701082201742710052813964a1e25160f7e22c965ad" dependencies = [ "accesskit", "accesskit_unix", @@ -3410,14 +3405,12 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8049963b716df01b67b58f86000597f222d5b31b15b35069b23a3b07f3c68352" dependencies = [ "async-task", "backtrace", - "chrono", "flume", "futures", + "jiff 1.1.0", "parking_lot", "rand 0.9.5", "wasm_thread", @@ -3555,12 +3548,10 @@ dependencies = [ [[package]] name = "gpui-pre-zlog" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7506302091e66d7fb5e04a5b3480e90cff0bbe3157458d7df91a41c59238c48" dependencies = [ "anyhow", - "chrono", "gpui-pre-collections", + "jiff 1.1.0", "log", ] @@ -4324,13 +4315,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" dependencies = [ "defmt", - "jiff-core", - "jiff-static", - "jiff-tzdb-platform", + "jiff-core 0.1.1", + "jiff-static 0.2.37", + "jiff-tzdb-platform 0.1.3", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" +dependencies = [ + "jiff-core 1.1.0", + "jiff-static 1.1.0", + "jiff-tzdb-platform 1.0.0", + "js-sys", "log", "portable-atomic", "portable-atomic-util", "serde_core", + "wasm-bindgen", "windows-link 0.2.1", ] @@ -4344,31 +4353,67 @@ dependencies = [ "log", ] +[[package]] +name = "jiff-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" dependencies = [ - "jiff-core", + "jiff-core 0.1.1", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "jiff-static" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" +dependencies = [ + "jiff-core 1.1.0", + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "jiff-tzdb" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + [[package]] name = "jiff-tzdb-platform" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" dependencies = [ - "jiff-tzdb", + "jiff-tzdb 0.1.8", +] + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb 1.0.0", ] [[package]] @@ -4411,9 +4456,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -4633,9 +4678,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" dependencies = [ "serde_core", "value-bag", @@ -4794,8 +4839,6 @@ dependencies = [ [[package]] name = "markdown" version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5cab8f2cadc416a82d2e783a1946388b31654d391d1c7d92cc1f03e295b1deb" dependencies = [ "serde", "unicode-id", @@ -5127,7 +5170,7 @@ dependencies = [ [[package]] name = "nocterm" -version = "3.1.0" +version = "4.2.1" dependencies = [ "anyhow", "async-io", @@ -5232,12 +5275,14 @@ dependencies = [ "dunce", "futures", "getrandom 0.4.3", + "memchr", "nix 0.28.0", "nocterm-agent-providers", "nocterm-ai", "nocterm-core", "nocterm-settings", - "rustix 1.1.5", + "rustix 1.1.6", + "serde", "serde_json", "subtle", "tempfile", @@ -5251,9 +5296,10 @@ version = "0.0.0" dependencies = [ "async-channel", "base64 0.22.1", - "chrono", "futures", "gpui-kit", + "image", + "jiff 1.1.0", "nocterm-agent-chat", "nocterm-agent-directory", "nocterm-agent-providers", @@ -5536,6 +5582,7 @@ name = "nocterm-device-unlock" version = "0.0.0" dependencies = [ "chacha20poly1305", + "futures", "getrandom 0.4.3", "hkdf 0.12.4", "nix 0.31.3", @@ -5578,9 +5625,9 @@ dependencies = [ name = "nocterm-files" version = "0.0.0" dependencies = [ - "chrono", "futures", "gpui-kit", + "jiff 1.1.0", "nocterm-explorer", "nocterm-plugin-api", "nocterm-plugin-model", @@ -5770,6 +5817,7 @@ version = "0.0.0" dependencies = [ "image", "nocterm-ai", + "png 0.18.1", ] [[package]] @@ -5834,15 +5882,16 @@ name = "nocterm-local" version = "0.0.0" dependencies = [ "async-channel", - "chrono", + "async-io", "filedescriptor", "futures", + "jiff 1.1.0", "nix 0.28.0", "nocterm-core", "nocterm-session", "portable-pty", "process-wrap", - "rustix 1.1.5", + "rustix 1.1.6", "tempfile", "thiserror 2.0.21", "tracing", @@ -5862,7 +5911,7 @@ dependencies = [ "nocterm-session", "ouroboros", "prikk-ffi", - "rustix 1.1.5", + "rustix 1.1.6", "tempfile", "tracing", "windows-sys 0.61.2", @@ -6141,7 +6190,7 @@ dependencies = [ "getrandom 0.4.3", "nocterm-core", "nocterm-project-model", - "rustix 1.1.5", + "rustix 1.1.6", "serde_json", "tempfile", ] @@ -6199,6 +6248,7 @@ name = "nocterm-settings-ui" version = "0.0.0" dependencies = [ "gpui-kit", + "nocterm-settings", "nocterm-store", "nocterm-ui", "nocterm-workspace", @@ -6209,6 +6259,7 @@ dependencies = [ name = "nocterm-snippets" version = "0.0.0" dependencies = [ + "memchr", "serde", "thiserror 2.0.21", "uuid", @@ -6264,7 +6315,7 @@ dependencies = [ "nocterm-ssh-keys", "russh", "russh-sftp", - "rustix 1.1.5", + "rustix 1.1.6", "sha1", "tempfile", "thiserror 2.0.21", @@ -6493,6 +6544,7 @@ version = "0.0.0" dependencies = [ "alacritty_terminal", "encoding_rs", + "memchr", "nocterm-session", "regex", "regex-syntax", @@ -7671,7 +7723,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -8635,9 +8687,9 @@ dependencies = [ [[package]] name = "russh" -version = "0.63.3" +version = "0.65.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "036204edbd199552a5b3832f63c60dcdf395dc44c7f06b4af1c0e8139cc11bce" +checksum = "94be3d86c71b9ed220a675c405e35c7a02565a009bf8da2e9cc13a700320a5c5" dependencies = [ "aes 0.9.3", "bitflags 2.13.2", @@ -8718,15 +8770,15 @@ dependencies = [ [[package]] name = "russh-sftp" -version = "3.0.1" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb17f72aba4314656b359ffba72c68dcbd70ed9e97497898b75498fe7198042" +checksum = "5b8067d56cde438de09db20be974be92118b85d671c7f50ea3b37cf9011760f0" dependencies = [ "bitflags 2.13.2", "bytes", - "chrono", "dashmap", "gloo-timers", + "jiff 1.1.0", "log", "serde", "serde_bytes", @@ -8739,10 +8791,8 @@ dependencies = [ [[package]] name = "russh-util" version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668424a5dde0bcb45b55ba7de8476b93831b4aa2fa6947e145f3b053e22c60b6" dependencies = [ - "chrono", + "jiff 1.1.0", "tokio", "wasm-bindgen", "wasm-bindgen-futures", @@ -8875,9 +8925,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -8893,7 +8943,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -8904,7 +8954,7 @@ checksum = "1de16c7c59892b870a6336f185dc10943517f1327447096bbb7bb32cd85e2393" dependencies = [ "errno", "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -9343,7 +9393,7 @@ dependencies = [ "hex", "indexmap 1.9.3", "indexmap 2.14.2", - "jiff", + "jiff 0.2.37", "schemars 0.9.0", "schemars 1.2.2", "serde_core", @@ -10106,7 +10156,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -10351,9 +10401,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -10439,8 +10489,6 @@ dependencies = [ [[package]] name = "toml_parser" version = "1.1.3+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" dependencies = [ "winnow 1.0.4", ] @@ -10951,9 +10999,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -11184,12 +11232,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -11197,9 +11244,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", "tokio", @@ -11208,9 +11255,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11218,9 +11265,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", @@ -11231,9 +11278,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -11365,7 +11412,7 @@ dependencies = [ "cc", "downcast-rs", "log", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -11378,7 +11425,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -11389,7 +11436,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -11457,9 +11504,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -12427,7 +12474,7 @@ dependencies = [ "as-raw-xcb-connection", "gethostname", "libc", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", "xcursor", ] @@ -12445,7 +12492,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -12628,7 +12675,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tokio", diff --git a/Cargo.toml b/Cargo.toml index c82a7af9..ca54abbd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nocterm" description = "A fast, extensible SSH client." -version = "3.1.0" +version = "4.2.1" edition.workspace = true license-file.workspace = true publish = false @@ -156,6 +156,7 @@ openssh-clients = "*" winresource = "0.1" [dev-dependencies] +nocterm-plugin-host = { workspace = true, features = ["test-support"] } nocterm-plugin-ports = { workspace = true, features = ["test-support"] } nocterm-connections-store = { workspace = true, features = ["test-support"] } async-io.workspace = true @@ -185,17 +186,23 @@ gpui-kit = { workspace = true, features = ["test-support"] } [workspace] members = ["crates/*", "xtask"] -exclude = ["vendor/alacritty_terminal", "vendor/gpui-component", "vendor/gpui-base", "vendor/gpui-pre", "vendor/gpui-pre-windows", "vendor/gpui-pre-wgpu", "vendor/tid-rs", "examples/plugins/focus-timer"] +exclude = ["vendor/alacritty_terminal", "vendor/gpui-component", "vendor/gpui-base", "vendor/gpui-pre", "vendor/gpui-pre-scheduler", "vendor/gpui-pre-zlog", "vendor/gpui-pre-linux", "vendor/gpui-pre-windows", "vendor/gpui-pre-wgpu", "vendor/markdown", "vendor/tid-rs", "vendor/toml_parser", "vendor/russh-util", "examples/plugins/focus-timer"] resolver = "3" [patch.crates-io] +markdown = { path = "vendor/markdown" } alacritty_terminal = { path = "vendor/alacritty_terminal" } gpui-component = { path = "vendor/gpui-component" } gpui-base = { path = "vendor/gpui-base" } gpui-pre = { path = "vendor/gpui-pre" } +gpui-pre-scheduler = { path = "vendor/gpui-pre-scheduler" } +gpui-pre-zlog = { path = "vendor/gpui-pre-zlog" } +gpui-pre-linux = { path = "vendor/gpui-pre-linux" } gpui-pre-windows = { path = "vendor/gpui-pre-windows" } gpui-pre-wgpu = { path = "vendor/gpui-pre-wgpu" } tid-rs = { path = "vendor/tid-rs" } +toml_parser = { path = "vendor/toml_parser" } +russh-util = { path = "vendor/russh-util" } [workspace.package] edition = "2024" @@ -314,6 +321,7 @@ anyhow = "1" async-channel = "2" directories = "6" futures = "0.3" +memchr = "2" sha2 = "0.10.9" gpui-kit = "0.7" # GPUI alone, for crates that must not reach the component library. @@ -325,8 +333,8 @@ regex = "1" # Zed's reqwest fork, already in the tree through GPUI. reqwest = { package = "gpui-pre-reqwest", version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] } regex-syntax = "0.8" -russh = { version = "0.63", default-features = false, features = ["ring", "flate2", "rsa"] } -russh-sftp = "3" +russh = { version = "0.65.1", default-features = false, features = ["ring", "flate2", "rsa"] } +russh-sftp = "4" # Pinned to the version `russh` resolves, so key text round-trips between the two (ADR 0102). ssh-key = { version = "=0.7.0-rc.11", default-features = false, features = ["ed25519", "p256", "p384", "p521", "rsa", "encryption"] } schemars = "1" diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt index 562e0c7f..cd0007aa 100644 --- a/THIRD_PARTY_NOTICES.txt +++ b/THIRD_PARTY_NOTICES.txt @@ -2,9 +2,9 @@ Nocterm third-party licenses and notices ======================================== Generated by scripts/generate-license-notices.py using cargo-about 0.9.2. -Content SHA-256: 4536e416d08a476065d40732bd53803885df66157f1241e698c4a44f95a08940 -Input fingerprint: d41268d9912392fcbb1660baaf43a364f1134c4c9ea22d56895995475b4a400e -Cargo.lock SHA-256 (release version masked): efe961a6a4b84e2fbff7e2afb64c5f4dd94c9cf43cb33860cf52881a5469d189 +Content SHA-256: 23f38964a59e4349ce78c3623d881bd996f343a217ad640e1f91906a7ef379de +Input fingerprint: 76076c89e8bd371a415fe064f1b773b52fb9e84437c9c85598cceb5abbb3f1e2 +Cargo.lock SHA-256 (release version masked): b33eec8e734dbb668401cb696d4cc21b59b8aeed795c149ed508e484bf5c34a7 Scope: runtime and build dependencies of Nocterm and its optional vault broker for Linux x86_64, Windows x86_64, macOS x86_64 and macOS arm64. @@ -503,10 +503,6 @@ Authors: RustCrypto Developers Source: https://crates.io/api/v1/crates/chacha20poly1305/0.11.0/download Repository: https://github.com/RustCrypto/AEADs -chrono 0.4.45: MIT OR Apache-2.0 -Source: https://crates.io/api/v1/crates/chrono/0.4.45/download -Repository: https://github.com/chronotope/chrono - cipher 0.4.4: MIT OR Apache-2.0 Authors: RustCrypto Developers Source: https://crates.io/api/v1/crates/cipher/0.4.4/download @@ -717,9 +713,9 @@ Authors: Kirill Chibisov Source: https://crates.io/api/v1/crates/cursor-icon/1.2.0/download Repository: https://github.com/rust-windowing/cursor-icon -curve25519-dalek 5.0.0: BSD-3-Clause +curve25519-dalek 5.1.0: BSD-3-Clause Authors: Isis Lovecruft ; Henry de Valence -Source: https://crates.io/api/v1/crates/curve25519-dalek/5.0.0/download +Source: https://crates.io/api/v1/crates/curve25519-dalek/5.1.0/download Repository: https://github.com/dalek-cryptography/curve25519-dalek/tree/main/curve25519-dalek curve25519-dalek-derive 0.1.1: MIT OR Apache-2.0 @@ -1089,9 +1085,9 @@ Authors: Steven Fackler Source: https://crates.io/api/v1/crates/foreign-types-shared/0.3.1/download Repository: https://github.com/sfackler/foreign-types -form_urlencoded 1.2.2: MIT OR Apache-2.0 +form_urlencoded 1.2.3: MIT OR Apache-2.0 Authors: The rust-url developers -Source: https://crates.io/api/v1/crates/form_urlencoded/1.2.2/download +Source: https://crates.io/api/v1/crates/form_urlencoded/1.2.3/download Repository: https://github.com/servo/rust-url freetype-sys 0.20.1: MIT @@ -1305,7 +1301,7 @@ Source: https://crates.io/api/v1/crates/gpui-pre-http-client/0.3.7/download Repository: https://github.com/zed-industries/zed gpui-pre-linux 0.3.7: Apache-2.0 -Source: https://crates.io/api/v1/crates/gpui-pre-linux/0.3.7/download +Source: vendor/gpui-pre-linux Repository: https://github.com/zed-industries/zed gpui-pre-macos 0.3.7: Apache-2.0 @@ -1334,7 +1330,7 @@ Source: https://crates.io/api/v1/crates/gpui-pre-reqwest/0.12.15/download Repository: https://github.com/seanmonstar/reqwest gpui-pre-scheduler 0.3.7: Apache-2.0 -Source: https://crates.io/api/v1/crates/gpui-pre-scheduler/0.3.7/download +Source: vendor/gpui-pre-scheduler Repository: https://github.com/zed-industries/zed gpui-pre-shared-string 0.3.7: Apache-2.0 @@ -1362,7 +1358,7 @@ Source: vendor/gpui-pre-windows Repository: https://github.com/zed-industries/zed gpui-pre-zlog 0.3.7: Apache-2.0 -Source: https://crates.io/api/v1/crates/gpui-pre-zlog/0.3.7/download +Source: vendor/gpui-pre-zlog Repository: https://github.com/zed-industries/zed gpui-pre-ztracing 0.3.7: Apache-2.0 @@ -1529,11 +1525,6 @@ Authors: Sean McArthur Source: https://crates.io/api/v1/crates/hyper-util/0.1.21/download Repository: https://github.com/hyperium/hyper-util -iana-time-zone 0.1.65: MIT OR Apache-2.0 -Authors: Andrew Straw ; René Kijewski ; Ryan Lopopolo -Source: https://crates.io/api/v1/crates/iana-time-zone/0.1.65/download -Repository: https://github.com/strawlab/iana-time-zone - icu_collections 2.3.0: Unicode-3.0 Authors: The ICU4X Project Developers Source: https://crates.io/api/v1/crates/icu_collections/2.3.0/download @@ -1697,6 +1688,26 @@ Authors: David Tolnay Source: https://crates.io/api/v1/crates/itoa/1.0.18/download Repository: https://github.com/dtolnay/itoa +jiff 1.1.0: Unlicense OR MIT +Authors: Andrew Gallant +Source: https://crates.io/api/v1/crates/jiff/1.1.0/download +Repository: https://github.com/BurntSushi/jiff + +jiff-core 1.1.0: Unlicense OR MIT +Authors: Andrew Gallant +Source: https://crates.io/api/v1/crates/jiff-core/1.1.0/download +Repository: https://github.com/BurntSushi/jiff + +jiff-tzdb 1.0.0: Unlicense OR MIT +Authors: Andrew Gallant +Source: https://crates.io/api/v1/crates/jiff-tzdb/1.0.0/download +Repository: https://github.com/BurntSushi/jiff + +jiff-tzdb-platform 1.0.0: Unlicense OR MIT +Authors: Andrew Gallant +Source: https://crates.io/api/v1/crates/jiff-tzdb-platform/1.0.0/download +Repository: https://github.com/BurntSushi/jiff + keccak 0.2.2: Apache-2.0 OR MIT Authors: RustCrypto Developers Source: https://crates.io/api/v1/crates/keccak/0.2.2/download @@ -1803,9 +1814,9 @@ Authors: Amanieu d'Antras Source: https://crates.io/api/v1/crates/lock_api/0.4.14/download Repository: https://github.com/Amanieu/parking_lot -log 0.4.34: MIT OR Apache-2.0 +log 0.4.35: MIT OR Apache-2.0 Authors: The Rust Project Developers -Source: https://crates.io/api/v1/crates/log/0.4.34/download +Source: https://crates.io/api/v1/crates/log/0.4.35/download Repository: https://github.com/rust-lang/log logos 0.16.1: MIT OR Apache-2.0 @@ -1874,7 +1885,7 @@ Repository: https://github.com/SSheldon/malloc_buf markdown 1.0.0: MIT Authors: Titus Wormer -Source: https://crates.io/api/v1/crates/markdown/1.0.0/download +Source: vendor/markdown Repository: https://github.com/wooorm/markdown-rs markup5ever 0.12.1: MIT OR Apache-2.0 @@ -2777,9 +2788,9 @@ Authors: RustCrypto Developers; dignifiedquire Source: https://crates.io/api/v1/crates/rsa/0.10.0-rc.18/download Repository: https://github.com/RustCrypto/RSA -russh 0.63.3: Apache-2.0 +russh 0.65.1: Apache-2.0 Authors: Pierre-Étienne Meunier -Source: https://crates.io/api/v1/crates/russh/0.63.3/download +Source: https://crates.io/api/v1/crates/russh/0.65.1/download Repository: https://github.com/warp-tech/russh russh-cryptovec 0.62.0: Apache-2.0 @@ -2787,12 +2798,12 @@ Authors: Pierre-Étienne Meunier ; Eugeny ; Jakub Konka ; Jakub Konka -Source: https://crates.io/api/v1/crates/rustix/1.1.5/download +Source: https://crates.io/api/v1/crates/rustix/1.1.6/download Repository: https://github.com/bytecodealliance/rustix rustix-linux-procfs 0.1.1: Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT @@ -3432,9 +3443,9 @@ Authors: Tokio Contributors Source: https://crates.io/api/v1/crates/tokio-stream/0.1.19/download Repository: https://github.com/tokio-rs/tokio -tokio-util 0.7.19: MIT +tokio-util 0.7.20: MIT Authors: Tokio Contributors -Source: https://crates.io/api/v1/crates/tokio-util/0.7.19/download +Source: https://crates.io/api/v1/crates/tokio-util/0.7.20/download Repository: https://github.com/tokio-rs/tokio toml 0.8.23: MIT OR Apache-2.0 @@ -3462,7 +3473,7 @@ Source: https://crates.io/api/v1/crates/toml_edit/0.25.15+spec-1.1.0/download Repository: https://github.com/toml-rs/toml toml_parser 1.1.3+spec-1.1.0: MIT OR Apache-2.0 -Source: https://crates.io/api/v1/crates/toml_parser/1.1.3+spec-1.1.0/download +Source: vendor/toml_parser Repository: https://github.com/toml-rs/toml toml_write 0.1.2: MIT OR Apache-2.0 @@ -3732,9 +3743,9 @@ Authors: Brian Smith Source: https://crates.io/api/v1/crates/untrusted/0.9.0/download Repository: https://github.com/briansmith/untrusted -url 2.5.8: MIT OR Apache-2.0 +url 2.5.9: MIT OR Apache-2.0 Authors: The rust-url developers -Source: https://crates.io/api/v1/crates/url/2.5.8/download +Source: https://crates.io/api/v1/crates/url/2.5.9/download Repository: https://github.com/servo/rust-url usvg 0.45.1: Apache-2.0 OR MIT @@ -10038,9 +10049,9 @@ Apache License ======================================================================== License: Apache-2.0 -Used by: clang-sys 1.9.1, codespan-reporting 0.13.1, cvt 0.1.2, miette 7.6.0, self_cell 1.3.0, unicode-linebreak 0.1.5 +Used by: clang-sys 1.9.1, codespan-reporting 0.13.1, cvt 0.1.2, miette 7.6.0, russh-util 0.52.0, self_cell 1.3.0, unicode-linebreak 0.1.5 License: Apache-2.0 -Used by: russh-sftp 3.0.1 +Used by: russh-sftp 4.0.0 Original notice: as-raw-xcb-connection 1.0.1 / LICENSE-APACHE Original notice: atspi 0.29.0 / LICENSE-APACHE2.txt Original notice: atspi-common 0.13.0 / LICENSE-APACHE2.txt @@ -10068,11 +10079,12 @@ Original notice: polycool 0.4.0 / LICENSE-APACHE Original notice: raw-window-metal 1.1.0 / LICENSE-APACHE Original notice: russh-cryptovec@0.62.0 / upstream/brendanzab-gl-rs-license-cfc7749b96f6.txt Source: https://raw.githubusercontent.com/warp-tech/russh/907c732562c5732aad6c140dba958eafddc41ba0/LICENSE.txt -Original notice: russh-sftp 3.0.1 / LICENSE +Original notice: russh-sftp 4.0.0 / LICENSE +Original notice: russh-util 0.52.0 / LICENSE-2.0.txt Original notice: russh-util@0.52.0 / upstream/russh-apache-cfc7749b96f6.txt Source: https://raw.githubusercontent.com/warp-tech/russh/3d09c20c52a542ffa327723d3a44cb1edd9b0ca4/LICENSE-2.0.txt -Original notice: russh@0.63.3 / upstream/brendanzab-gl-rs-license-cfc7749b96f6.txt -Source: https://raw.githubusercontent.com/warp-tech/russh/f33baf439be8c59c49cb6cb2ae5976c579495bdf/LICENSE.txt +Original notice: russh@0.65.1 / upstream/brendanzab-gl-rs-license-cfc7749b96f6.txt +Source: https://raw.githubusercontent.com/warp-tech/russh/b33092aad1e51c66258a12e8b83fc473a68d9d34/LICENSE.txt Original notice: secrecy 0.10.3 / LICENSE-APACHE Original notice: self_cell 1.3.0 / LICENSE-APACHE Original notice: siphasher 1.0.4 / LICENSE-APACHE @@ -10304,7 +10316,7 @@ Original notice: io-lifetimes 3.0.1 / LICENSE-Apache-2.0_WITH_LLVM-exception Original notice: linux-raw-sys 0.12.1 / LICENSE-Apache-2.0_WITH_LLVM-exception Original notice: linux-raw-sys 0.4.15 / LICENSE-Apache-2.0_WITH_LLVM-exception Original notice: rustix 0.38.44 / LICENSE-Apache-2.0_WITH_LLVM-exception -Original notice: rustix 1.1.5 / LICENSE-Apache-2.0_WITH_LLVM-exception +Original notice: rustix 1.1.6 / LICENSE-Apache-2.0_WITH_LLVM-exception Original notice: rustix-linux-procfs 0.1.1 / LICENSE-Apache-2.0_WITH_LLVM-exception Original notice: rustix-openpty 0.2.0 / LICENSE-Apache-2.0_WITH_LLVM-exception Original notice: wasmparser@0.228.0 / upstream/bytecodealliance-wasm-tools-license-apache-llvm-exception-268872b9816f.txt @@ -15130,211 +15142,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -======================================================================== -Original notice: iana-time-zone 0.1.65 / LICENSE-APACHE - -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2020 Andrew Straw - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - ======================================================================== License: Apache-2.0 Used by: alacritty_terminal 0.26.0 @@ -16641,7 +16448,7 @@ Original notice: find-msvc-tools 0.1.14 / LICENSE-APACHE Original notice: fixedbitset 0.5.7 / LICENSE-APACHE Original notice: flate2 1.1.10 / LICENSE-APACHE Original notice: fnv 1.0.7 / LICENSE-APACHE -Original notice: form_urlencoded 1.2.2 / LICENSE-APACHE +Original notice: form_urlencoded 1.2.3 / LICENSE-APACHE Original notice: fs-set-times 0.20.3 / LICENSE-APACHE Original notice: fs2 0.4.3 / LICENSE-APACHE Original notice: futf 0.1.5 / LICENSE-APACHE @@ -16680,7 +16487,7 @@ Original notice: lazy_static 1.5.1 / LICENSE-APACHE Original notice: linux-raw-sys 0.12.1 / LICENSE-APACHE Original notice: linux-raw-sys 0.4.15 / LICENSE-APACHE Original notice: lock_api 0.4.14 / LICENSE-APACHE -Original notice: log 0.4.34 / LICENSE-APACHE +Original notice: log 0.4.35 / LICENSE-APACHE Original notice: markup5ever 0.12.1 / LICENSE-APACHE Original notice: markup5ever_rcdom 0.3.0 / LICENSE-APACHE Original notice: metal 0.33.0 / LICENSE-APACHE @@ -16739,7 +16546,7 @@ Original notice: rustc-demangle 0.1.28 / LICENSE-APACHE Original notice: rustc-hash 1.1.0 / LICENSE-APACHE Original notice: rustc_version 0.4.1 / LICENSE-APACHE Original notice: rustix 0.38.44 / LICENSE-APACHE -Original notice: rustix 1.1.5 / LICENSE-APACHE +Original notice: rustix 1.1.6 / LICENSE-APACHE Original notice: rustix-linux-procfs 0.1.1 / LICENSE-APACHE Original notice: rustix-openpty 0.2.0 / LICENSE-APACHE Original notice: rustls 0.23.46 / LICENSE-APACHE @@ -16782,7 +16589,7 @@ Original notice: unicode-vo 0.1.0 / LICENSE-APACHE Original notice: unicode-width 0.1.14 / LICENSE-APACHE Original notice: unicode-width 0.2.2 / LICENSE-APACHE Original notice: unicode-xid 0.2.6 / LICENSE-APACHE -Original notice: url 2.5.8 / LICENSE-APACHE +Original notice: url 2.5.9 / LICENSE-APACHE Original notice: uuid 1.26.1 / LICENSE-APACHE Original notice: value-bag 1.14.1 / LICENSE-APACHE Original notice: value-bag-serde1 1.14.1 / LICENSE-APACHE @@ -18964,7 +18771,7 @@ limitations under the License. ======================================================================== Original notice: document-features 0.2.12 / LICENSE-APACHE SPDX reference license terms: Apache-2.0 -Used by: agent-client-protocol 2.2.0, agent-client-protocol-derive 2.2.0, agent-client-protocol-schema 1.9.1, dunce 1.0.5, fs_at 0.2.1, gl_generator 0.14.0, gpui-kit 0.7.0, gpui-kit-assets 0.7.0, khronos_api 3.1.0, pageant 0.2.3, prikk-ffi 0.56.0, russh 0.63.3, russh-cryptovec 0.62.0, russh-util 0.52.0, ryu 1.0.23, serial2 0.2.38, spirv 0.4.0+sdk-1.4.341.0, sync_wrapper 1.0.2 +Used by: agent-client-protocol 2.2.0, agent-client-protocol-derive 2.2.0, agent-client-protocol-schema 1.9.1, dunce 1.0.5, fs_at 0.2.1, gl_generator 0.14.0, gpui-kit 0.7.0, gpui-kit-assets 0.7.0, khronos_api 3.1.0, pageant 0.2.3, prikk-ffi 0.56.0, russh 0.65.1, russh-cryptovec 0.62.0, ryu 1.0.23, serial2 0.2.38, spirv 0.4.0+sdk-1.4.341.0, sync_wrapper 1.0.2 Apache License Version 2.0, January 2004 @@ -19915,8 +19722,8 @@ SOFTWARE. ======================================================================== License: MIT -Used by: form_urlencoded 1.2.2 -Original notice: form_urlencoded 1.2.2 / LICENSE-MIT +Used by: form_urlencoded 1.2.3 +Original notice: form_urlencoded 1.2.3 / LICENSE-MIT Copyright (c) 2013-2016 The rust-url developers @@ -19946,11 +19753,11 @@ DEALINGS IN THE SOFTWARE. ======================================================================== License: MIT -Used by: data-url 0.3.2, idna 1.1.0, percent-encoding 2.3.2, url 2.5.8 +Used by: data-url 0.3.2, idna 1.1.0, percent-encoding 2.3.2, url 2.5.9 Original notice: data-url 0.3.2 / LICENSE-MIT Original notice: idna 1.1.0 / LICENSE-MIT Original notice: percent-encoding 2.3.2 / LICENSE-MIT -Original notice: url 2.5.8 / LICENSE-MIT +Original notice: url 2.5.9 / LICENSE-MIT Copyright (c) 2013-2025 The rust-url developers @@ -20167,11 +19974,11 @@ DEALINGS IN THE SOFTWARE. ======================================================================== License: MIT -Used by: bitflags 1.3.2, bitflags 2.13.2, glob 0.3.4, log 0.4.34, num 0.4.3, num-bigint 0.4.8, num-bigint 0.5.1, num-bigint-dig 0.9.1, num-complex 0.4.6, num-derive 0.3.3, num-integer 0.1.47, num-iter 0.1.46, num-rational 0.4.2, num-traits 0.2.19, regex 1.13.1, regex-automata 0.4.18, regex-syntax 0.8.11 +Used by: bitflags 1.3.2, bitflags 2.13.2, glob 0.3.4, log 0.4.35, num 0.4.3, num-bigint 0.4.8, num-bigint 0.5.1, num-bigint-dig 0.9.1, num-complex 0.4.6, num-derive 0.3.3, num-integer 0.1.47, num-iter 0.1.46, num-rational 0.4.2, num-traits 0.2.19, regex 1.13.1, regex-automata 0.4.18, regex-syntax 0.8.11 Original notice: bitflags 1.3.2 / LICENSE-MIT Original notice: bitflags 2.13.2 / LICENSE-MIT Original notice: glob 0.3.4 / LICENSE-MIT -Original notice: log 0.4.34 / LICENSE-MIT +Original notice: log 0.4.35 / LICENSE-MIT Original notice: num 0.4.3 / LICENSE-MIT Original notice: num-bigint 0.4.8 / LICENSE-MIT Original notice: num-bigint 0.5.1 / LICENSE-MIT @@ -21889,11 +21696,12 @@ DEALINGS IN THE SOFTWARE. ======================================================================== License: BSD-3-Clause -Used by: curve25519-dalek 5.0.0 -Original notice: curve25519-dalek 5.0.0 / LICENSE +Used by: curve25519-dalek 5.1.0 +Original notice: curve25519-dalek 5.1.0 / LICENSE Copyright (c) 2016-2021 isis agora lovecruft. All rights reserved. Copyright (c) 2016-2021 Henry de Valence. All rights reserved. +Copyright (c) 2025-2026 The Beneficial AI Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -24092,37 +23900,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -======================================================================== -License: MIT -Used by: iana-time-zone 0.1.65 -Original notice: iana-time-zone 0.1.65 / LICENSE-MIT - -Copyright (c) 2020 Andrew D. Straw - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - ======================================================================== License: MIT Used by: downcast-rs 1.2.1 @@ -31319,7 +31096,7 @@ SOFTWARE. ======================================================================== SPDX reference license terms: MIT -Used by: accesskit 0.24.1, accesskit_atspi_common 0.19.1, accesskit_consumer 0.38.0, accesskit_macos 0.26.3, accesskit_unix 0.22.1, accesskit_windows 0.34.0, block 0.1.6, block2 0.6.2, chrono 0.4.45, delegate 0.13.5, dispatch2 0.3.1, gpu-descriptor 0.3.2, gpu-descriptor-types 0.2.0, granit-parser 1.3.0, harfrust 0.5.2, leak 0.1.2, leaky-cow 0.1.1, libm 0.2.16, lyon 1.0.19, lyon_algorithms 1.0.21, lyon_geom 1.0.19, lyon_path 1.0.19, lyon_tessellation 1.0.22, mac 0.1.1, mac-notification-sys 0.6.15, malloc_buf 0.0.6, md5 0.8.1, objc-sys 0.3.5, objc2 0.5.2, objc2 0.6.4, objc2-app-kit 0.2.2, objc2-app-kit 0.3.2, objc2-cloud-kit 0.3.2, objc2-core-data 0.3.2, objc2-core-foundation 0.3.2, objc2-core-graphics 0.3.2, objc2-core-image 0.3.2, objc2-core-location 0.3.2, objc2-core-media 0.3.2, objc2-core-text 0.3.2, objc2-core-video 0.3.2, objc2-encode 4.1.0, objc2-foundation 0.2.2, objc2-foundation 0.3.2, objc2-metal 0.3.2, objc2-quartz-core 0.3.2, objc2-screen-capture-kit 0.3.2, objc2-user-notifications 0.3.2, ouroboros 0.18.5, ouroboros_macro 0.18.5, pathfinder_geometry 0.5.1, pathfinder_simd 0.5.6, profiling 1.0.18, profiling-procmacros 1.0.18, pulp-wasm-simd-flag 0.1.1, rust-i18n-macro 4.2.4, rust-i18n-support 4.2.4, seahash 4.1.0, svg_fmt 0.4.5, taffy 0.13.0, tauri-winrt-notification 0.8.1, tonic-prost-build 0.14.7, tree-sitter-bash 0.23.3, tree-sitter-cpp 0.23.4, tree-sitter-css 0.23.2, tree-sitter-diff 0.1.0, tree-sitter-go 0.23.4, tree-sitter-html 0.23.2, tree-sitter-java 0.23.5, tree-sitter-javascript 0.23.1, tree-sitter-json 0.24.8, tree-sitter-python 0.23.6, tree-sitter-toml-ng 0.7.0, tree-sitter-typescript 0.23.2, wasmi 2.0.0, wasmi_collections 2.0.0, wasmi_core 2.0.0, wasmi_ir 2.0.0, wasmparser 0.228.0, windows 0.58.0, windows 0.62.2, windows-collections 0.3.2, windows-core 0.58.0, windows-core 0.62.2, windows-future 0.3.2, windows-implement 0.58.0, windows-implement 0.60.2, windows-interface 0.58.0, windows-interface 0.59.3, windows-link 0.1.3, windows-link 0.2.1, windows-numerics 0.3.1, windows-registry 0.4.0, windows-registry 0.6.1, windows-result 0.2.0, windows-result 0.3.4, windows-result 0.4.1, windows-strings 0.1.0, windows-strings 0.3.1, windows-strings 0.5.1, windows-sys 0.48.0, windows-sys 0.52.0, windows-sys 0.59.0, windows-sys 0.61.2, windows-targets 0.48.5, windows-targets 0.52.6, windows-targets 0.53.5, windows-threading 0.2.1, windows-version 0.1.7, windows_x86_64_gnu 0.48.5, windows_x86_64_gnu 0.52.6, windows_x86_64_gnu 0.53.1, windows_x86_64_msvc 0.48.5, windows_x86_64_msvc 0.52.6, windows_x86_64_msvc 0.53.1, xim-ctext 0.3.0, xim-parser 0.2.2, zune-core 0.4.12, zune-inflate 0.2.54, zune-jpeg 0.4.21 +Used by: accesskit 0.24.1, accesskit_atspi_common 0.19.1, accesskit_consumer 0.38.0, accesskit_macos 0.26.3, accesskit_unix 0.22.1, accesskit_windows 0.34.0, block 0.1.6, block2 0.6.2, delegate 0.13.5, dispatch2 0.3.1, gpu-descriptor 0.3.2, gpu-descriptor-types 0.2.0, granit-parser 1.3.0, harfrust 0.5.2, leak 0.1.2, leaky-cow 0.1.1, libm 0.2.16, lyon 1.0.19, lyon_algorithms 1.0.21, lyon_geom 1.0.19, lyon_path 1.0.19, lyon_tessellation 1.0.22, mac 0.1.1, mac-notification-sys 0.6.15, malloc_buf 0.0.6, md5 0.8.1, objc-sys 0.3.5, objc2 0.5.2, objc2 0.6.4, objc2-app-kit 0.2.2, objc2-app-kit 0.3.2, objc2-cloud-kit 0.3.2, objc2-core-data 0.3.2, objc2-core-foundation 0.3.2, objc2-core-graphics 0.3.2, objc2-core-image 0.3.2, objc2-core-location 0.3.2, objc2-core-media 0.3.2, objc2-core-text 0.3.2, objc2-core-video 0.3.2, objc2-encode 4.1.0, objc2-foundation 0.2.2, objc2-foundation 0.3.2, objc2-metal 0.3.2, objc2-quartz-core 0.3.2, objc2-screen-capture-kit 0.3.2, objc2-user-notifications 0.3.2, ouroboros 0.18.5, ouroboros_macro 0.18.5, pathfinder_geometry 0.5.1, pathfinder_simd 0.5.6, profiling 1.0.18, profiling-procmacros 1.0.18, pulp-wasm-simd-flag 0.1.1, rust-i18n-macro 4.2.4, rust-i18n-support 4.2.4, seahash 4.1.0, svg_fmt 0.4.5, taffy 0.13.0, tauri-winrt-notification 0.8.1, tonic-prost-build 0.14.7, tree-sitter-bash 0.23.3, tree-sitter-cpp 0.23.4, tree-sitter-css 0.23.2, tree-sitter-diff 0.1.0, tree-sitter-go 0.23.4, tree-sitter-html 0.23.2, tree-sitter-java 0.23.5, tree-sitter-javascript 0.23.1, tree-sitter-json 0.24.8, tree-sitter-python 0.23.6, tree-sitter-toml-ng 0.7.0, tree-sitter-typescript 0.23.2, wasmi 2.0.0, wasmi_collections 2.0.0, wasmi_core 2.0.0, wasmi_ir 2.0.0, wasmparser 0.228.0, windows 0.58.0, windows 0.62.2, windows-collections 0.3.2, windows-core 0.58.0, windows-core 0.62.2, windows-future 0.3.2, windows-implement 0.58.0, windows-implement 0.60.2, windows-interface 0.58.0, windows-interface 0.59.3, windows-link 0.1.3, windows-link 0.2.1, windows-numerics 0.3.1, windows-registry 0.4.0, windows-registry 0.6.1, windows-result 0.2.0, windows-result 0.3.4, windows-result 0.4.1, windows-strings 0.1.0, windows-strings 0.3.1, windows-strings 0.5.1, windows-sys 0.48.0, windows-sys 0.52.0, windows-sys 0.59.0, windows-sys 0.61.2, windows-targets 0.48.5, windows-targets 0.52.6, windows-targets 0.53.5, windows-threading 0.2.1, windows-version 0.1.7, windows_x86_64_gnu 0.48.5, windows_x86_64_gnu 0.52.6, windows_x86_64_gnu 0.53.1, windows_x86_64_msvc 0.48.5, windows_x86_64_msvc 0.52.6, windows_x86_64_msvc 0.53.1, xim-ctext 0.3.0, xim-parser 0.2.2, zune-core 0.4.12, zune-inflate 0.2.54, zune-jpeg 0.4.21 MIT License @@ -31373,10 +31150,10 @@ SOFTWARE. ======================================================================== License: MIT -Used by: tokio 1.54.1, tokio-stream 0.1.19, tokio-util 0.7.19 +Used by: tokio 1.54.1, tokio-stream 0.1.19, tokio-util 0.7.20 Original notice: tokio 1.54.1 / LICENSE Original notice: tokio-stream 0.1.19 / LICENSE -Original notice: tokio-util 0.7.19 / LICENSE +Original notice: tokio-util 0.7.20 / LICENSE MIT License @@ -32968,7 +32745,7 @@ DEALINGS IN THE SOFTWARE. ======================================================================== License: MIT -Used by: adler2 2.0.1, ambient-authority 0.0.2, anyhow 1.0.104, async-channel 2.5.0, async-executor 1.14.1, async-fs 2.2.0, async-io 2.6.0, async-lock 3.4.2, async-net 2.0.0, async-process 2.5.0, async-recursion 1.1.1, async-signal 0.2.14, async-task 4.7.1, async-trait 0.1.92, atomic-waker 1.1.2, blocking 1.7.0, cap-primitives 4.0.3, concurrent-queue 2.5.0, curve25519-dalek-derive 0.1.1, displaydoc 0.2.7, dyn-clone 1.0.20, endi 1.1.1, enumn 0.1.14, erased-serde 0.4.10, event-listener 5.4.2, event-listener-strategy 0.5.4, fastrand 2.5.0, flume 0.12.0, fs-set-times 0.20.3, futures-lite 2.6.1, group 0.14.0, home 0.5.12, inventory 0.3.24, io-extras 0.19.0, io-lifetimes 2.0.4, io-lifetimes 3.0.1, itoa 1.0.18, khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys 0.4.15, minimal-lexical 0.2.1, once_cell 1.21.4, ordered-stream 0.2.0, parking 2.2.1, paste 1.0.15, pin-project 1.1.13, pin-project-internal 1.1.13, pin-project-lite 0.2.17, piper 0.2.5, polling 3.11.0, prettyplease 0.2.37, proc-macro-crate 3.5.0, proc-macro2 1.0.107, process-wrap 9.1.1, prost-reflect 0.16.5, protox 0.10.0, protox-parse 0.10.0, quote 1.0.47, ref-cast 1.0.27, ref-cast-impl 1.0.27, rsa 0.10.0-rc.18, rustc-hash 1.1.0, rustc-hash 2.1.3, rustix 0.38.44, rustix 1.1.5, rustix-linux-procfs 0.1.1, rustix-openpty 0.2.0, rustversion 1.0.23, semver 1.0.28, serde 1.0.229, serde-saphyr 1.3.0, serde_bytes 0.11.19, serde_core 1.0.229, serde_derive 1.0.229, serde_derive_internals 0.30.0, serde_json 1.0.151, serde_json_lenient 0.2.4, serde_repr 0.1.21, smol 2.0.2, smol_str 0.3.6, syn 1.0.109, syn 2.0.119, syn 3.0.6, thiserror 1.0.69, thiserror 2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typeid 1.0.3, unicode-ident 1.0.26, utf-8 0.7.6, waker-fn 1.2.0, zbus-lockstep 0.5.2, zbus-lockstep-macros 0.5.2, zed-font-kit 0.14.1-zed, zmij 1.0.23, zvariant_utils 4.2.0 +Used by: adler2 2.0.1, ambient-authority 0.0.2, anyhow 1.0.104, async-channel 2.5.0, async-executor 1.14.1, async-fs 2.2.0, async-io 2.6.0, async-lock 3.4.2, async-net 2.0.0, async-process 2.5.0, async-recursion 1.1.1, async-signal 0.2.14, async-task 4.7.1, async-trait 0.1.92, atomic-waker 1.1.2, blocking 1.7.0, cap-primitives 4.0.3, concurrent-queue 2.5.0, curve25519-dalek-derive 0.1.1, displaydoc 0.2.7, dyn-clone 1.0.20, endi 1.1.1, enumn 0.1.14, erased-serde 0.4.10, event-listener 5.4.2, event-listener-strategy 0.5.4, fastrand 2.5.0, flume 0.12.0, fs-set-times 0.20.3, futures-lite 2.6.1, group 0.14.0, home 0.5.12, inventory 0.3.24, io-extras 0.19.0, io-lifetimes 2.0.4, io-lifetimes 3.0.1, itoa 1.0.18, khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys 0.4.15, minimal-lexical 0.2.1, once_cell 1.21.4, ordered-stream 0.2.0, parking 2.2.1, paste 1.0.15, pin-project 1.1.13, pin-project-internal 1.1.13, pin-project-lite 0.2.17, piper 0.2.5, polling 3.11.0, prettyplease 0.2.37, proc-macro-crate 3.5.0, proc-macro2 1.0.107, process-wrap 9.1.1, prost-reflect 0.16.5, protox 0.10.0, protox-parse 0.10.0, quote 1.0.47, ref-cast 1.0.27, ref-cast-impl 1.0.27, rsa 0.10.0-rc.18, rustc-hash 1.1.0, rustc-hash 2.1.3, rustix 0.38.44, rustix 1.1.6, rustix-linux-procfs 0.1.1, rustix-openpty 0.2.0, rustversion 1.0.23, semver 1.0.28, serde 1.0.229, serde-saphyr 1.3.0, serde_bytes 0.11.19, serde_core 1.0.229, serde_derive 1.0.229, serde_derive_internals 0.30.0, serde_json 1.0.151, serde_json_lenient 0.2.4, serde_repr 0.1.21, smol 2.0.2, smol_str 0.3.6, syn 1.0.109, syn 2.0.119, syn 3.0.6, thiserror 1.0.69, thiserror 2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typeid 1.0.3, unicode-ident 1.0.26, utf-8 0.7.6, waker-fn 1.2.0, zbus-lockstep 0.5.2, zbus-lockstep-macros 0.5.2, zed-font-kit 0.14.1-zed, zmij 1.0.23, zvariant_utils 4.2.0 License: MIT Used by: allocator-api2 0.2.21, glow 0.17.0 Original notice: accesskit@0.24.1 / upstream/AccessKit-accesskit-license-mit-23f18e03dc49.txt @@ -33042,7 +32819,7 @@ Original notice: rsa 0.10.0-rc.18 / LICENSE-MIT Original notice: rustc-hash 1.1.0 / LICENSE-MIT Original notice: rustc-hash 2.1.3 / LICENSE-MIT Original notice: rustix 0.38.44 / LICENSE-MIT -Original notice: rustix 1.1.5 / LICENSE-MIT +Original notice: rustix 1.1.6 / LICENSE-MIT Original notice: rustix-linux-procfs 0.1.1 / LICENSE-MIT Original notice: rustix-openpty 0.2.0 / LICENSE-MIT Original notice: rustversion 1.0.23 / LICENSE-MIT @@ -61453,249 +61230,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -======================================================================== -Original notice: chrono 0.4.45 / LICENSE.txt - -Rust-chrono is dual-licensed under The MIT License [1] and -Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and -contributors. - -Nota Bene: This is same as the Rust Project's own license. - - -[1]: , which is reproduced below: - -~~~~ -The MIT License (MIT) - -Copyright (c) 2014, Kang Seonghoon. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -~~~~ - - -[2]: , which is reproduced below: - -~~~~ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -~~~~ - ======================================================================== Original notice: tauri-winrt-notification 0.8.1 / LICENSE.spdx @@ -62020,7 +61554,7 @@ at your option. ======================================================================== Original notice: rustix 0.38.44 / COPYRIGHT -Original notice: rustix 1.1.5 / COPYRIGHT +Original notice: rustix 1.1.6 / COPYRIGHT Short version for non-lawyers: @@ -62540,13 +62074,17 @@ THE SOFTWARE. ======================================================================== License: MIT -Used by: aho-corasick 1.1.5, byteorder 1.5.0, byteorder-lite 0.1.0, encoding_rs_io 0.1.8, globset 0.4.20, ignore 0.4.33, memchr 2.8.3, walkdir 2.5.0 +Used by: aho-corasick 1.1.5, byteorder 1.5.0, byteorder-lite 0.1.0, encoding_rs_io 0.1.8, globset 0.4.20, ignore 0.4.33, jiff 1.1.0, jiff-core 1.1.0, jiff-tzdb 1.0.0, jiff-tzdb-platform 1.0.0, memchr 2.8.3, walkdir 2.5.0 Original notice: aho-corasick 1.1.5 / LICENSE-MIT Original notice: byteorder 1.5.0 / LICENSE-MIT Original notice: byteorder-lite 0.1.0 / LICENSE-MIT Original notice: encoding_rs_io 0.1.8 / LICENSE-MIT Original notice: globset 0.4.20 / LICENSE-MIT Original notice: ignore 0.4.33 / LICENSE-MIT +Original notice: jiff 1.1.0 / LICENSE-MIT +Original notice: jiff-core 1.1.0 / LICENSE-MIT +Original notice: jiff-tzdb 1.0.0 / LICENSE-MIT +Original notice: jiff-tzdb-platform 1.0.0 / LICENSE-MIT Original notice: memchr 2.8.3 / LICENSE-MIT Original notice: walkdir 2.5.0 / LICENSE-MIT @@ -64053,6 +63591,10 @@ Original notice: aho-corasick 1.1.5 / COPYING Original notice: byteorder 1.5.0 / COPYING Original notice: globset 0.4.20 / COPYING Original notice: ignore 0.4.33 / COPYING +Original notice: jiff 1.1.0 / COPYING +Original notice: jiff-core 1.1.0 / COPYING +Original notice: jiff-tzdb 1.0.0 / COPYING +Original notice: jiff-tzdb-platform 1.0.0 / COPYING Original notice: memchr 2.8.3 / COPYING Original notice: same-file 1.0.6 / COPYING Original notice: walkdir 2.5.0 / COPYING diff --git a/crates/acp/Cargo.toml b/crates/acp/Cargo.toml index 231f5377..aa17e3f0 100644 --- a/crates/acp/Cargo.toml +++ b/crates/acp/Cargo.toml @@ -18,6 +18,8 @@ async-process.workspace = true async-io.workspace = true async-channel.workspace = true futures.workspace = true +memchr.workspace = true +serde.workspace = true serde_json.workspace = true getrandom.workspace = true thiserror.workspace = true diff --git a/crates/acp/src/bridge.rs b/crates/acp/src/bridge.rs index 96a0ddf3..724777d6 100644 --- a/crates/acp/src/bridge.rs +++ b/crates/acp/src/bridge.rs @@ -417,18 +417,17 @@ pub(crate) fn bounded_line(reader: &mut R, limit: usize) -> io::Resu )) }; } - let end = available.iter().position(|&b| b == b'\n'); - let count = end.map_or(available.len(), |end| end + 1); - if bytes.len() + count > limit + 1 { + let end = memchr::memchr(b'\n', available); + let payload_len = end.unwrap_or(available.len()); + if payload_len > limit - bytes.len() { return Err(io::Error::new( io::ErrorKind::InvalidData, "Protocol line too large", )); } - bytes.extend_from_slice(&available[..count]); - reader.consume(count); + bytes.extend_from_slice(&available[..payload_len]); + reader.consume(payload_len + usize::from(end.is_some())); if end.is_some() { - bytes.pop(); if bytes.last() == Some(&b'\r') { bytes.pop(); } diff --git a/crates/acp/src/bridge/tests.rs b/crates/acp/src/bridge/tests.rs index d9509ff2..fe5f88e3 100644 --- a/crates/acp/src/bridge/tests.rs +++ b/crates/acp/src/bridge/tests.rs @@ -488,3 +488,27 @@ fn unauthenticated_connections_still_expire() { let mut reader = BufReader::new(socket); assert!(bounded_line(&mut reader, 4096).unwrap().is_none()); } + +#[test] +fn fragmented_crlf_at_the_limit_keeps_the_next_relay_message() { + let mut reader = BufReader::with_capacity(2, io::Cursor::new(b"abc\r\nnext\n")); + assert_eq!( + bounded_line(&mut reader, 4).unwrap().as_deref(), + Some("abc") + ); + assert_eq!( + bounded_line(&mut reader, 4).unwrap().as_deref(), + Some("next") + ); + + let mut reader = BufReader::with_capacity(2, io::Cursor::new(b"abcd\r\n")); + let error = bounded_line(&mut reader, 4).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); +} + +#[test] +fn over_limit_relay_message_fails_even_without_a_newline() { + let mut reader = io::Cursor::new(b"abcde"); + let error = bounded_line(&mut reader, 4).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); +} diff --git a/crates/acp/src/client/commands.rs b/crates/acp/src/client/commands.rs index a1dd84db..cf0d2cb1 100644 --- a/crates/acp/src/client/commands.rs +++ b/crates/acp/src/client/commands.rs @@ -27,7 +27,7 @@ use super::{ handshake::SessionSupport, remote_errors::{map_error_with, restore_error}, }; -use crate::{mapping, models::Models, process}; +use crate::{lines::PromptHandoff, mapping, models::Models, process}; /// How the agent reopens earlier sessions, if it can. #[derive(Clone, Copy)] @@ -47,6 +47,7 @@ pub(super) struct Commands { fork_supported: bool, models: Arc>, events: async_channel::Sender, + prompts: PromptHandoff, } impl Commands { pub(super) fn new( @@ -57,6 +58,7 @@ impl Commands { support: SessionSupport, models: Arc>, events: async_channel::Sender, + prompts: PromptHandoff, ) -> Self { let restore = if support.resume { Restore::Resume @@ -75,6 +77,7 @@ impl Commands { fork_supported: support.fork, models, events, + prompts, } } } @@ -180,12 +183,17 @@ impl AgentCommands for Commands { ) -> BoxFuture<'static, Result> { let connection = self.connection.clone(); let secrets = self.secrets.clone(); + let prompts = self.prompts.clone(); async move { - let response = connection - .send_request(mapping::prompt(request)) - .block_task() - .await - .map_err(|error| map_error_with(error, &secrets))?; + let result = match prompts.stage(mapping::prompt(request)) { + Ok(ticket) => { + let result = connection.send_request(ticket).block_task().await; + prompts.finish(ticket); + result + } + Err(prompt) => connection.send_request(prompt).block_task().await, + }; + let response = result.map_err(|error| map_error_with(error, &secrets))?; Ok(mapping::prompt_outcome(response)?) } .boxed() diff --git a/crates/acp/src/client/driver.rs b/crates/acp/src/client/driver.rs index a1cf6e2e..1594e92e 100644 --- a/crates/acp/src/client/driver.rs +++ b/crates/acp/src/client/driver.rs @@ -77,6 +77,7 @@ impl Driver { } = self; let models = Arc::new(Mutex::new(Models::default())); let (stop, stopped) = async_channel::bounded(1); + let (prompts, prompt_writer) = lines::PromptHandoff::channel(); let session = Session { handshake, ready, @@ -86,10 +87,11 @@ impl Driver { secrets: process.secrets.clone(), models: models.clone(), events: events.clone(), + prompts, }; let protocol = client_builder_with_models(events.sender(), models).connect_with( Lines::new( - Box::pin(lines::outgoing(stdin)), + Box::pin(lines::outgoing(stdin, prompt_writer)), Box::pin(lines::incoming(stdout)), ), async move |connection: ConnectionTo| session.serve(connection).await, @@ -128,6 +130,7 @@ struct Session { secrets: Arc>, models: Arc>, events: EventQueue, + prompts: lines::PromptHandoff, } impl Session { async fn serve(self, connection: ConnectionTo) -> Result<(), acp::Error> { @@ -146,6 +149,7 @@ impl Session { support, self.models, self.events.sender(), + self.prompts, )); let connected = AgentConnection { info, diff --git a/crates/acp/src/client/lifecycle_tests.rs b/crates/acp/src/client/lifecycle_tests.rs index 61ba1b45..8b5570b5 100644 --- a/crates/acp/src/client/lifecycle_tests.rs +++ b/crates/acp/src/client/lifecycle_tests.rs @@ -2,34 +2,86 @@ use super::*; use nocterm_ai::{AgentLaunch, CloseSessionOutcome}; -async fn connection(mode: &str, directory: &std::path::Path) -> AgentConnection { - let script = r#" -import json, sys +const SUBPROCESS_FIXTURE: &str = r#" +import json, sys, time +from pathlib import Path mode = sys.argv[1] -for line in sys.stdin: +def update(text): + return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':text}}}} +def activity(state): + return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'session_info_update','_meta':{'codex':{'threadStatus':{'type':state}}}}}} +pause_next_read = False +prompts = [] +while True: + prefix = b'' + if pause_next_read: + pause_next_read = False + prefix = sys.stdin.buffer.read1(16) + print(json.dumps(update('reading request')), flush=True) + deadline = time.monotonic() + 10 + while not Path('resume-read').exists(): + assert time.monotonic() < deadline, 'client did not deliver the update during the write' + time.sleep(0.005) + line = prefix + sys.stdin.buffer.readline() + if not line: break request = json.loads(line) - if 'id' not in request: continue method = request['method'] + if 'id' not in request: + if mode == 'queued-cancel' and method == '$/cancel_request': + assert len(prompts) == 2 and request['params']['requestId'] == prompts[1], request + print(json.dumps(update('cancel matched the queued prompt')), flush=True) + continue if method == 'initialize': result = {'protocolVersion':1,'agentCapabilities': {} if mode == 'unsupported' else {'sessionCapabilities':{'close':{}}}} - elif method == 'session/new': result = {'sessionId':'s1'} + elif method == 'session/new': + result = {'sessionId':'s1'} + pause_next_read = mode in ('backpressure', 'queued-cancel') + elif method == 'session/prompt' and mode == 'batch': + calls = [{'jsonrpc':'2.0','method':'test/missing','id':token} for token in ('first','second')] + print(json.dumps([update('one'), calls[0], update('two'), calls[1]]), flush=True) + replies = json.loads(sys.stdin.buffer.readline()) + assert isinstance(replies, list) and len(replies) == 2, replies + assert {reply['id']: reply['error']['code'] for reply in replies} == {'first':-32601,'second':-32601}, replies + result = {'stopReason':'end_turn'} + elif method == 'session/prompt' and mode == 'autonomous': + print(json.dumps(activity('active')), flush=True) + print(json.dumps(activity('idle')), flush=True) + print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':{'stopReason':'end_turn'}}),flush=True) + print(json.dumps(activity('active')), flush=True) + print(json.dumps(update('continuation')), flush=True) + print(json.dumps(activity('idle')), flush=True) + continue + elif method == 'session/prompt' and mode == 'bench-text': + assert request['params']['prompt'] == [{'type':'text','text':'latency fixture'}] + result = {'stopReason':'end_turn'} + elif method == 'session/prompt': + blocks = request['params']['prompt'] + assert blocks[0]['text'] == 'keep the original images' + assert len(blocks) == 5 + expected = 'A' * 6990507 + '=' + assert all(block['type'] == 'image' and block['mimeType'] == 'image/png' + and block['data'] == expected for block in blocks[1:]) + prompts.append(request['id']) + result = {'stopReason':'end_turn'} elif method == 'session/close': if mode == 'hang': continue if mode == 'error': print(json.dumps({'jsonrpc':'2.0','id':request['id'],'error':{'code':-32603,'message':'close rejected'}}),flush=True) continue - print(json.dumps({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'final chunk'}}}}),flush=True) + print(json.dumps(update('final chunk')),flush=True) result = {} else: raise Exception(method) print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':result}),flush=True) "#; + +async fn connection(mode: &str, directory: &std::path::Path) -> AgentConnection { AcpConnector::unmanaged() .connect(ConnectRequest { launch: AgentLaunch { id: "close-test".into(), name: "Close".into(), command: "/usr/bin/python3".into(), - args: vec!["-c".into(), script.into(), mode.into()], + args: vec!["-c".into(), SUBPROCESS_FIXTURE.into(), mode.into()], env: Default::default(), inherit_env: Vec::new(), hub: None, @@ -43,6 +95,297 @@ for line in sys.stdin: .await .unwrap() } +#[test] +fn subprocess_batches_keep_update_order_and_group_replies() { + use nocterm_ai::model::{content::Content, session::StopReason}; + + let exercise = async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("batch", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let result = connection + .commands + .prompt(PromptRequest { + session: session.session, + content: vec![Content::text("batch")], + }) + .await + .unwrap(); + assert_eq!(result.stop_reason, StopReason::EndTurn); + for expected in [Content::text("one"), Content::text("two")] { + let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else { + panic!("expected an ACP session update"); + }; + assert_eq!(event.update, SessionUpdate::AgentMessageChunk(expected)); + } + connection.commands.shutdown_gracefully().await.unwrap(); + }; + futures::executor::block_on(async { + assert!(matches!( + select( + Box::pin(exercise), + Box::pin(async_io::Timer::after(Duration::from_secs(5))), + ) + .await, + Either::Left(_) + )); + }); +} + +#[test] +fn subprocess_activity_arrives_even_after_the_prompt_response() { + use nocterm_ai::model::session::{SessionActivity, StopReason}; + + let exercise = async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("autonomous", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let result = connection + .commands + .prompt(PromptRequest { + session: session.session.clone(), + content: vec![nocterm_ai::model::content::Content::text("work")], + }) + .await + .unwrap(); + assert_eq!(result.stop_reason, StopReason::EndTurn); + for expected in [ + Some(SessionActivity::Active), + Some(SessionActivity::Idle), + Some(SessionActivity::Active), + None, + Some(SessionActivity::Idle), + ] { + let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else { + panic!("expected an ACP session update"); + }; + assert_eq!(event.session, session.session); + match (expected, event.update) { + (Some(activity), SessionUpdate::SessionInfoUpdate(info)) => { + assert_eq!(info.activity, Some(activity)) + } + (None, SessionUpdate::AgentMessageChunk(content)) => assert_eq!( + content, + nocterm_ai::model::content::Content::text("continuation") + ), + _ => panic!("unexpected update"), + } + } + connection.commands.shutdown_gracefully().await.unwrap(); + }; + futures::executor::block_on(async { + assert!(matches!( + select( + Box::pin(exercise), + Box::pin(async_io::Timer::after(Duration::from_secs(5))) + ) + .await, + Either::Left(_) + )); + }); +} + +#[test] +fn sends_a_full_composer_image_budget_to_the_agent() { + use nocterm_ai::model::session::StopReason; + + futures::executor::block_on(async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("ok", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let result = connection + .commands + .prompt(PromptRequest { + session: session.session, + content: full_budget_content(), + }) + .await; + connection.commands.shutdown_gracefully().await.unwrap(); + assert_eq!(result.unwrap().stop_reason, StopReason::EndTurn); + }); +} + +#[test] +fn delivers_agent_updates_while_a_large_prompt_waits_for_the_peer_to_read() { + use nocterm_ai::model::{content::Content, session::StopReason}; + + let exercise = async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("backpressure", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let prompt = connection.commands.prompt(PromptRequest { + session: session.session, + content: full_budget_content(), + }); + let unblock_agent = async { + let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else { + panic!("expected a session update while the write was waiting"); + }; + assert_eq!( + event.update, + SessionUpdate::AgentMessageChunk(Content::text("reading request")) + ); + std::fs::write(directory.path().join("resume-read"), []).unwrap(); + }; + let (response, ()) = futures::join!(prompt, unblock_agent); + assert_eq!(response.unwrap().stop_reason, StopReason::EndTurn); + connection.commands.shutdown_gracefully().await.unwrap(); + }; + futures::executor::block_on(async { + assert!(matches!( + select( + Box::pin(exercise), + Box::pin(async_io::Timer::after(Duration::from_secs(10))), + ) + .await, + Either::Left(_) + )); + }); +} + +#[test] +fn dropping_a_queued_large_prompt_cancels_the_matching_request() { + use nocterm_ai::model::{content::Content, session::StopReason}; + + let exercise = async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("queued-cancel", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let content = full_budget_content(); + let mut first = connection.commands.prompt(PromptRequest { + session: session.session.clone(), + content: content.clone(), + }); + assert!(futures::poll!(&mut first).is_pending()); + assert!(matches!( + connection.events.recv().await.unwrap(), + AgentEvent::Session(_) + )); + let mut second = connection.commands.prompt(PromptRequest { + session: session.session, + content, + }); + assert!(futures::poll!(&mut second).is_pending()); + drop(second); + std::fs::write(directory.path().join("resume-read"), []).unwrap(); + + assert_eq!(first.await.unwrap().stop_reason, StopReason::EndTurn); + let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else { + panic!("expected the agent's acknowledgement of cancellation"); + }; + assert_eq!( + event.update, + SessionUpdate::AgentMessageChunk(Content::text("cancel matched the queued prompt")) + ); + connection.commands.shutdown_gracefully().await.unwrap(); + }; + futures::executor::block_on(async { + assert!(matches!( + select( + Box::pin(exercise), + Box::pin(async_io::Timer::after(Duration::from_secs(10))) + ) + .await, + Either::Left(_) + )); + }); +} + +fn full_budget_content() -> Vec { + use nocterm_ai::{ + images::{MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES}, + model::content::{Content, Image}, + }; + let encoded_size = MAX_IMAGE_BYTES.div_ceil(3) * 4; + let image = Content::Image(Image::new("A".repeat(encoded_size - 1) + "=", "image/png")); + let mut content = vec![Content::text("keep the original images")]; + content.extend(std::iter::repeat_n( + image, + MAX_TOTAL_IMAGE_BYTES / MAX_IMAGE_BYTES, + )); + content +} + +#[test] +#[ignore = "release performance fixture for a native ACP subprocess request and reply"] +fn measure_subprocess_prompt_roundtrip() { + use nocterm_ai::model::{content::Content, session::StopReason}; + use std::{io::Write as _, time::Instant}; + + futures::executor::block_on(async { + for (mode, content, repetitions) in [ + ("bench-text", vec![Content::text("latency fixture")], 50), + ("ok", full_budget_content(), 12), + ] { + let directory = tempfile::tempdir().unwrap(); + let connection = connection(mode, directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let mut timings = Vec::with_capacity(repetitions); + for _ in 0..repetitions { + let prompt = PromptRequest { + session: session.session.clone(), + content: content.clone(), + }; + let start = Instant::now(); + let reply = connection.commands.prompt(prompt).await.unwrap(); + timings.push(start.elapsed()); + assert_eq!(reply.stop_reason, StopReason::EndTurn); + } + connection.commands.shutdown_gracefully().await.unwrap(); + timings.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{mode}: {repetitions} requests, median {:?}, max {:?}", + timings[repetitions / 2], + timings[repetitions - 1], + ) + .unwrap(); + } + }); +} + #[cfg(unix)] #[test] fn acknowledged_close_waits_for_the_foreground_event_barrier() { diff --git a/crates/acp/src/lines.rs b/crates/acp/src/lines.rs index 0f5ccce8..bcfee8cd 100644 --- a/crates/acp/src/lines.rs +++ b/crates/acp/src/lines.rs @@ -5,7 +5,17 @@ use futures::{ io::{AsyncRead, AsyncWrite, BufReader}, }; -pub(crate) const ACP_LINE_LIMIT: usize = 16 * 1024 * 1024; +mod prompt_handoff; +mod prompt_segments; + +pub(crate) use prompt_handoff::PromptHandoff; +use prompt_handoff::PromptWriter; + +const MAX_INCOMING_LINE_BYTES: usize = 16 * 1024 * 1024; +// Each admitted image is encoded separately, so allow rounding at every block. +const MAX_ENCODED_ATTACHMENTS: usize = 4 + * (nocterm_ai::images::MAX_TOTAL_IMAGE_BYTES.div_ceil(3) + nocterm_ai::images::MAX_IMAGES - 1); +const MAX_OUTGOING_LINE_BYTES: usize = MAX_INCOMING_LINE_BYTES + MAX_ENCODED_ATTACHMENTS; /// Reads without letting a malicious peer allocate an unbounded line. pub(crate) async fn read_line( @@ -25,18 +35,17 @@ pub(crate) async fn read_line( )) }; } - let end = available.iter().position(|&b| b == b'\n'); - let count = end.map_or(available.len(), |end| end + 1); - if bytes.len().saturating_add(count) > limit + 1 { + let end = memchr::memchr(b'\n', available); + let payload_len = end.unwrap_or(available.len()); + if payload_len > limit - bytes.len() { return Err(io::Error::new( io::ErrorKind::InvalidData, "Protocol line exceeds its limit", )); } - bytes.extend_from_slice(&available[..count]); - reader.consume_unpin(count); + bytes.extend_from_slice(&available[..payload_len]); + reader.consume_unpin(payload_len + usize::from(end.is_some())); if end.is_some() { - bytes.pop(); if bytes.last() == Some(&b'\r') { bytes.pop(); } @@ -52,7 +61,7 @@ pub(crate) fn incoming( ) -> impl Stream> + Send { futures::stream::unfold(Some(BufReader::new(reader)), async |reader| { let mut reader = reader?; - match read_line(&mut reader, ACP_LINE_LIMIT).await { + match read_line(&mut reader, MAX_INCOMING_LINE_BYTES).await { Ok(Some(line)) => Some((Ok(line), Some(reader))), Ok(None) => None, Err(error) => Some((Err(error), None)), @@ -62,24 +71,209 @@ pub(crate) fn incoming( pub(crate) fn outgoing( writer: W, + prompts: PromptWriter, ) -> impl Sink + Send { - futures::sink::unfold(writer, async |mut writer, line: String| { - if line.len() > ACP_LINE_LIMIT || line.contains('\n') { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Invalid outgoing protocol line", - )); - } - writer.write_all(line.as_bytes()).await?; - writer.write_all(b"\n").await?; - writer.flush().await?; - Ok(writer) - }) + futures::sink::unfold( + (writer, prompts), + async |(mut writer, prompts), line: String| { + if line.len() > MAX_OUTGOING_LINE_BYTES || line.contains('\n') { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid outgoing protocol line", + )); + } + if let Some((id, prompt)) = prompts.take(&line)? { + for part in prompt_segments::encode(id, &prompt, MAX_OUTGOING_LINE_BYTES)? { + writer.write_all(part.bytes()).await?; + } + } else { + writer.write_all(line.as_bytes()).await?; + } + writer.write_all(b"\n").await?; + writer.flush().await?; + Ok((writer, prompts)) + }, + ) } #[cfg(test)] mod tests { use super::*; + use futures::{AsyncReadExt as _, SinkExt as _, StreamExt as _, pin_mut}; + + #[test] + fn fragmented_crlf_at_the_limit_keeps_the_next_message() { + futures::executor::block_on(async { + let mut reader = + BufReader::with_capacity(2, futures::io::Cursor::new(b"abc\r\nnext\n")); + assert_eq!( + read_line(&mut reader, 4).await.unwrap().as_deref(), + Some("abc") + ); + assert_eq!( + read_line(&mut reader, 4).await.unwrap().as_deref(), + Some("next") + ); + + let mut reader = BufReader::with_capacity(2, futures::io::Cursor::new(b"abcd\r\n")); + let error = read_line(&mut reader, 4).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + }); + } + + #[test] + #[ignore = "release performance fixture for bounded ACP and MCP line reads"] + fn line_read_cost() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + for (size, count) in [(96, 65_536), (MAX_INCOMING_LINE_BYTES, 16)] { + let input = framed_payload(size); + let mut reader = BufReader::new(futures::io::Cursor::new(input.as_slice())); + let start = Instant::now(); + let mut capacity = 0; + futures::executor::block_on(async { + for _ in 0..count { + let line = read_line(&mut reader, size).await.unwrap().unwrap(); + assert_eq!(black_box(line.as_bytes()).len(), size); + capacity = line.capacity(); + reader.get_mut().set_position(0); + } + }); + writeln!( + io::stdout().lock(), + "ACP {size} bytes × {count}, {:?}, returned buffer {capacity} bytes", + start.elapsed() + ) + .unwrap(); + } + + for (size, count) in [(96, 65_536), (nocterm_ai::MAX_MCP_LINE, 256)] { + let input = framed_payload(size); + let mut reader = std::io::BufReader::new(io::Cursor::new(input.as_slice())); + let start = Instant::now(); + let mut capacity = 0; + for _ in 0..count { + let line = crate::bridge::bounded_line(&mut reader, size) + .unwrap() + .unwrap(); + assert_eq!(black_box(line.as_bytes()).len(), size); + capacity = line.capacity(); + reader.get_mut().set_position(0); + } + writeln!( + io::stdout().lock(), + "MCP {size} bytes × {count}, {:?}, returned buffer {capacity} bytes", + start.elapsed() + ) + .unwrap(); + } + } + + fn framed_payload(size: usize) -> Vec { + let mut input = Vec::with_capacity(size + 1); + input.extend_from_slice(b"{\"text\":\""); + input.resize(size - 2, b'x'); + input.extend_from_slice(b"\"}\n"); + input + } + + #[test] + fn incoming_agent_lines_keep_the_original_budget() { + futures::executor::block_on(async { + let input = futures::io::repeat(b'a').take((16 * 1024 * 1024 + 2) as u64); + let lines = incoming(input); + pin_mut!(lines); + let error = lines.next().await.unwrap().unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!(lines.next().await.is_none()); + }); + } + + #[test] + fn outgoing_lines_reject_over_budget_and_literal_line_breaks() { + futures::executor::block_on(async { + for line in ["a".repeat(MAX_OUTGOING_LINE_BYTES + 1), "{}\n{}".into()] { + let (_, prompts) = PromptHandoff::channel(); + let writer = outgoing(futures::io::sink(), prompts); + pin_mut!(writer); + let error = writer.send(line).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + } + }); + } + + #[test] + fn a_staged_prompt_writes_one_complete_line_with_the_sdk_request_id() { + use nocterm_ai::model::content::{Content, Image}; + + futures::executor::block_on(async { + let data = "A".repeat(prompt_segments::MIN_SOURCE_BYTES) + "\n\"🖥"; + let image = Content::Image(Image::new(data, "image/png")); + let text = Content::text("send\n\""); + let content = vec![text, image]; + let (handoff, writer) = PromptHandoff::channel(); + let line = stage_line(&handoff, content.clone()); + let mut output = Vec::new(); + Box::pin(outgoing(&mut output, writer)) + .send(line) + .await + .unwrap(); + + assert_eq!(output.last(), Some(&b'\n')); + assert_eq!(output.iter().filter(|byte| **byte == b'\n').count(), 1); + assert_eq!( + serde_json::from_slice::(&output).unwrap(), + serde_json::json!({"jsonrpc":"2.0", "id":7, "method":"session/prompt", + "params":{"sessionId":"test", "prompt":content}}), + ); + }); + } + + #[test] + fn an_oversized_staged_prompt_writes_no_prefix() { + use nocterm_ai::model::content::{Content, Image}; + + futures::executor::block_on(async { + let text = Content::text("x".repeat(MAX_OUTGOING_LINE_BYTES)); + let data = "A".repeat(prompt_segments::MIN_SOURCE_BYTES); + let image = Content::Image(Image::new(data, "image/png")); + let (handoff, writer) = PromptHandoff::channel(); + let line = stage_line(&handoff, vec![text, image]); + let mut output = Vec::new(); + let error = Box::pin(outgoing(&mut output, writer)) + .send(line) + .await + .unwrap_err(); + + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!(output.is_empty()); + }); + } + + fn stage_line( + handoff: &PromptHandoff, + content: Vec, + ) -> String { + use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage}; + use agent_client_protocol_schema::v1::RequestId; + use nocterm_ai::model::{ids::SessionId, session::PromptRequest}; + + let request = crate::mapping::prompt(PromptRequest { + session: SessionId::new("test"), + content, + }); + let message = handoff + .stage(request) + .unwrap() + .to_untyped_message() + .unwrap(); + let (method, params) = message.into_parts(); + serde_json::to_string( + &RawJsonRpcMessage::request(method, params, RequestId::Number(7)).unwrap(), + ) + .unwrap() + } + #[test] fn bounds_lines_and_rejects_partial_or_invalid_utf8() { futures::executor::block_on(async { @@ -94,6 +288,9 @@ mod tests { assert_eq!(read_line(&mut reader, 4).await.unwrap().unwrap(), "abcd"); assert_eq!(read_line(&mut reader, 4).await.unwrap().unwrap(), "next"); assert!(read_line(&mut reader, 4).await.unwrap().is_none()); + let mut reader = futures::io::Cursor::new(b"abcde"); + let error = read_line(&mut reader, 4).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); }); } } diff --git a/crates/acp/src/lines/prompt_handoff.rs b/crates/acp/src/lines/prompt_handoff.rs new file mode 100644 index 00000000..e2c23fb3 --- /dev/null +++ b/crates/acp/src/lines/prompt_handoff.rs @@ -0,0 +1,131 @@ +use std::{ + io, + sync::{Arc, Mutex}, +}; + +use agent_client_protocol_schema::v1 as wire; +use serde::{Deserialize, Serialize}; + +use crate::mapping::OutgoingPrompt; + +use super::{MAX_OUTGOING_LINE_BYTES, prompt_segments::MIN_SOURCE_BYTES}; + +pub(super) const PROMPT_METHOD: &str = "session/prompt"; +const MAX_TICKET_LINE_BYTES: usize = 256; + +/// A private request parameter, consumed by the line writer before subprocess I/O. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, agent_client_protocol::JsonRpcRequest)] +#[request(method = "session/prompt", response = wire::PromptResponse)] +#[serde(deny_unknown_fields)] +pub(crate) struct PromptTicket { + #[serde(rename = "noctermPrompt")] + generation: u64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TicketLine<'a> { + jsonrpc: &'a str, + id: wire::RequestId, + method: &'a str, + params: PromptTicket, +} + +struct State { + open: bool, + generation: u64, + pending: Option, +} + +impl State { + fn remove(&mut self, ticket: PromptTicket) -> Option { + if self.generation == ticket.generation { + self.pending.take() + } else { + None + } + } +} + +/// The command side can stage at most one prompt per connection. +#[derive(Clone)] +pub(crate) struct PromptHandoff(Arc>); + +impl PromptHandoff { + pub(crate) fn channel() -> (Self, PromptWriter) { + let state = Arc::new(Mutex::new(State { + open: true, + generation: 0, + pending: None, + })); + (Self(state.clone()), PromptWriter(state)) + } + + pub(crate) fn stage(&self, prompt: OutgoingPrompt) -> Result { + let mut bytes = 0usize; + let mut large = false; + for data in prompt.images() { + bytes = bytes.saturating_add(data.len()); + large |= data.len() >= MIN_SOURCE_BYTES; + } + if !large || bytes > MAX_OUTGOING_LINE_BYTES { + return Err(prompt); + } + let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner()); + if !state.open || state.pending.is_some() { + return Err(prompt); + } + let Some(generation) = state.generation.checked_add(1) else { + return Err(prompt); + }; + state.generation = generation; + state.pending = Some(prompt); + Ok(PromptTicket { generation }) + } + + pub(crate) fn finish(&self, ticket: PromptTicket) { + let remaining = self + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(ticket); + drop(remaining); + } +} + +/// On transport loss, releases unsent payloads even while command handles remain. +pub(crate) struct PromptWriter(Arc>); + +impl PromptWriter { + pub(super) fn take(&self, line: &str) -> io::Result> { + if line.len() > MAX_TICKET_LINE_BYTES || !line.contains("\"noctermPrompt\":") { + return Ok(None); + } + let Ok(line) = serde_json::from_str::>(line) else { + return Ok(None); + }; + if line.method != PROMPT_METHOD || line.jsonrpc != "2.0" { + return Ok(None); + } + let prompt = self + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(line.params); + let prompt = prompt.ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "Missing outgoing ACP prompt") + })?; + Ok(Some((line.id, prompt))) + } +} + +impl Drop for PromptWriter { + fn drop(&mut self) { + let remaining = { + let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner()); + state.open = false; + state.pending.take() + }; + drop(remaining); + } +} diff --git a/crates/acp/src/lines/prompt_segments.rs b/crates/acp/src/lines/prompt_segments.rs new file mode 100644 index 00000000..e44e4945 --- /dev/null +++ b/crates/acp/src/lines/prompt_segments.rs @@ -0,0 +1,100 @@ +use std::io::{self, Write}; + +use agent_client_protocol_schema::v1::{JsonRpcMessage, Request, RequestId}; + +use crate::mapping::OutgoingPrompt; + +use super::prompt_handoff::PROMPT_METHOD; + +const MIN_FRAGMENT_BYTES: usize = 4096; +pub(super) const MIN_SOURCE_BYTES: usize = 1024 * 1024; + +pub(super) fn encode( + id: RequestId, + prompt: &OutgoingPrompt, + limit: usize, +) -> io::Result>> { + let mut line = Collector { + sources: prompt + .images() + .filter(|data| data.len() >= MIN_SOURCE_BYTES) + .map(str::as_bytes) + .collect(), + parts: Vec::new(), + inline: Vec::new(), + remaining: limit, + }; + let request = Request { + id, + method: PROMPT_METHOD.into(), + params: Some(prompt), + }; + serde_json::to_writer(&mut line, &JsonRpcMessage::wrap(request)) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + line.finish_inline(); + Ok(line.parts.into_iter()) +} + +pub(super) enum Part<'a> { + Inline(Vec), + Borrowed(&'a [u8]), +} + +impl Part<'_> { + pub(super) fn bytes(&self) -> &[u8] { + match self { + Self::Inline(bytes) => bytes, + Self::Borrowed(bytes) => bytes, + } + } +} + +struct Collector<'a> { + sources: Vec<&'a [u8]>, + parts: Vec>, + inline: Vec, + remaining: usize, +} + +impl<'a> Collector<'a> { + fn fragment(&self, bytes: &[u8]) -> Option<&'a [u8]> { + // The JSON writer forwards fragments from string values. Recover a + // slice only from a known live source; other bytes remain owned. + let address = bytes.as_ptr().addr(); + self.sources.iter().find_map(|source| { + let start = address.checked_sub(source.as_ptr().addr())?; + let end = start.checked_add(bytes.len())?; + source.get(start..end) + }) + } + + fn finish_inline(&mut self) { + if !self.inline.is_empty() { + self.parts + .push(Part::Inline(std::mem::take(&mut self.inline))); + } + } +} + +impl Write for Collector<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.remaining = self + .remaining + .checked_sub(bytes.len()) + .ok_or(io::ErrorKind::FileTooLarge)?; + if bytes.len() >= MIN_FRAGMENT_BYTES + && let Some(fragment) = self.fragment(bytes) + { + self.finish_inline(); + self.parts.push(Part::Borrowed(fragment)); + } else { + self.inline.extend_from_slice(bytes); + } + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.finish_inline(); + Ok(()) + } +} diff --git a/crates/acp/src/mapping/content.rs b/crates/acp/src/mapping/content.rs index fedc62a8..4b65636c 100644 --- a/crates/acp/src/mapping/content.rs +++ b/crates/acp/src/mapping/content.rs @@ -4,9 +4,6 @@ use nocterm_ai::model::{content::*, diagnostic::ModelError, extensions::Extensio pub(super) fn extensions(meta: Option) -> Option { meta.map(Extensions::from) } -fn meta(value: Option) -> Option { - value.map(Extensions::into_map) -} fn annotations(value: Option) -> Result, ModelError> { value .map(|value| { @@ -87,68 +84,3 @@ pub(super) fn content(value: wire::ContentBlock) -> Result _ => return Err(ModelError::Unsupported("content")), }) } -fn wire_annotations(value: Option) -> Option { - value.map(|value| { - wire::Annotations::new() - .audience(value.audience.map(|values| { - values - .into_iter() - .map(|value| match value { - Audience::User => wire::Role::User, - Audience::Assistant => wire::Role::Assistant, - }) - .collect::>() - })) - .last_modified(value.last_modified) - .priority(value.priority) - .meta(meta(value.meta)) - }) -} -pub(super) fn wire_content(value: Content) -> wire::ContentBlock { - match value { - Content::Text(value) => wire::ContentBlock::Text( - wire::TextContent::new(value.text) - .annotations(wire_annotations(value.annotations)) - .meta(meta(value.meta)), - ), - Content::Image(value) => wire::ContentBlock::Image( - wire::ImageContent::new(String::from(value.data), value.mime_type) - .uri(value.uri) - .annotations(wire_annotations(value.annotations)) - .meta(meta(value.meta)), - ), - Content::Audio(value) => wire::ContentBlock::Audio( - wire::AudioContent::new(value.data, value.mime_type) - .annotations(wire_annotations(value.annotations)) - .meta(meta(value.meta)), - ), - Content::ResourceReference(value) => wire::ContentBlock::ResourceLink( - wire::ResourceLink::new(value.name, value.uri) - .title(value.title) - .description(value.description) - .mime_type(value.mime_type) - .size(value.size) - .annotations(wire_annotations(value.annotations)) - .meta(meta(value.meta)), - ), - Content::EmbeddedResource(value) => { - let resource = match value.resource { - ResourceBody::Text(body) => wire::EmbeddedResourceResource::TextResourceContents( - wire::TextResourceContents::new(body.text, body.uri) - .mime_type(body.mime_type) - .meta(meta(body.meta)), - ), - ResourceBody::Blob(body) => wire::EmbeddedResourceResource::BlobResourceContents( - wire::BlobResourceContents::new(body.blob, body.uri) - .mime_type(body.mime_type) - .meta(meta(body.meta)), - ), - }; - wire::ContentBlock::Resource( - wire::EmbeddedResource::new(resource) - .annotations(wire_annotations(value.annotations)) - .meta(meta(value.meta)), - ) - } - } -} diff --git a/crates/acp/src/mapping/equivalence_tests.rs b/crates/acp/src/mapping/equivalence_tests.rs index 12f2b27e..e0387149 100644 --- a/crates/acp/src/mapping/equivalence_tests.rs +++ b/crates/acp/src/mapping/equivalence_tests.rs @@ -1,13 +1,16 @@ //! The neutral records read and write exactly the JSON the protocol records do. use super::{ - content::{content, wire_content}, + content::content, controls::option, + prompt, tools::{patch, record}, }; use agent_client_protocol_schema::v1 as wire; use nocterm_ai::model::{ content::Content, controls::{ConfigChoices, ConfigKind}, + ids::SessionId, + session::PromptRequest, tools::{ToolKind, ToolRecord, ToolStatus}, }; use serde_json::{Value, json}; @@ -76,10 +79,34 @@ fn content_writes_the_same_bytes_as_the_protocol_record() { let sdk: wire::ContentBlock = serde_json::from_value(json).unwrap(); let neutral = content(sdk.clone()).unwrap(); assert_eq!(bytes!(neutral), bytes!(sdk)); - assert_eq!(wire_content(neutral), sdk); } } #[test] +fn outgoing_prompt_has_the_sdk_request_shape_for_every_content_kind() { + use agent_client_protocol::JsonRpcMessage as _; + + let sdk: Vec = content_corpus() + .into_iter() + .map(|block| serde_json::from_value(block).unwrap()) + .collect(); + let neutral = sdk + .iter() + .cloned() + .map(content) + .collect::>() + .unwrap(); + let session = "session\n\"🖥"; + let expected = wire::PromptRequest::new(session, sdk); + let actual = prompt(PromptRequest { + session: SessionId::new(session), + content: neutral, + }); + assert_eq!( + actual.to_untyped_message().unwrap(), + expected.to_untyped_message().unwrap(), + ); +} +#[test] fn content_reads_the_same_records_as_the_protocol() { for json in content_corpus().into_iter().chain(malformed_content()) { let sdk = serde_json::from_value::(json.clone()); diff --git a/crates/acp/src/mapping/mod.rs b/crates/acp/src/mapping/mod.rs index 0c838694..468f3bae 100644 --- a/crates/acp/src/mapping/mod.rs +++ b/crates/acp/src/mapping/mod.rs @@ -9,8 +9,8 @@ mod tools; pub(crate) use controls::options; pub(crate) use info::{auth_methods, capabilities, remote_error}; pub(crate) use requests::{ - new_session, opened, permission, prompt, prompt_outcome, servers, set_config, set_mode, - wire_outcome, wire_session, + OutgoingPrompt, new_session, opened, permission, prompt, prompt_outcome, servers, set_config, + set_mode, wire_outcome, wire_session, }; pub(crate) use session::notice; diff --git a/crates/acp/src/mapping/requests.rs b/crates/acp/src/mapping/requests.rs index e0f849d3..92ad8e2d 100644 --- a/crates/acp/src/mapping/requests.rs +++ b/crates/acp/src/mapping/requests.rs @@ -1,11 +1,11 @@ use super::{ - content::wire_content, controls::{modes, options, wire_setting}, tools::patch, }; use agent_client_protocol_schema::v1 as wire; use nocterm_ai::model::{ auth::{PermissionChoice, PermissionEffect, PermissionOutcome, ProviderPermission}, + content::Content, diagnostic::ModelError, ids::{PermissionOptionId, SessionId}, session::*, @@ -35,11 +35,31 @@ pub(crate) fn servers(values: Vec) -> Vec pub(crate) fn new_session(value: SessionOpen) -> wire::NewSessionRequest { wire::NewSessionRequest::new(value.working_directory).mcp_servers(servers(value.endpoints)) } -pub(crate) fn prompt(value: PromptRequest) -> wire::PromptRequest { - wire::PromptRequest::new( - wire_session(&value.session), - value.content.into_iter().map(wire_content).collect(), - ) +// Neutral blocks serialize to the ACP shape while retaining their shared image bytes. +#[derive( + Clone, Debug, serde::Serialize, serde::Deserialize, agent_client_protocol::JsonRpcRequest, +)] +#[request(method = "session/prompt", response = wire::PromptResponse)] +#[serde(rename_all = "camelCase")] +pub(crate) struct OutgoingPrompt { + session_id: wire::SessionId, + prompt: Vec, +} + +impl OutgoingPrompt { + pub(crate) fn images(&self) -> impl Iterator { + self.prompt.iter().filter_map(|block| match block { + Content::Image(image) => Some(&*image.data), + _ => None, + }) + } +} + +pub(crate) fn prompt(value: PromptRequest) -> OutgoingPrompt { + OutgoingPrompt { + session_id: wire_session(&value.session), + prompt: value.content, + } } pub(crate) fn set_mode(value: SetMode) -> wire::SetSessionModeRequest { wire::SetSessionModeRequest::new(wire_session(&value.session), value.mode.to_string()) diff --git a/crates/acp/src/mapping/session.rs b/crates/acp/src/mapping/session.rs index 6270e226..e885ab4f 100644 --- a/crates/acp/src/mapping/session.rs +++ b/crates/acp/src/mapping/session.rs @@ -10,7 +10,7 @@ use nocterm_ai::model::{ diagnostic::ModelError, ids::{ModeId, SessionId}, plan::{Plan, PlanEntry, PlanPriority, PlanStatus}, - session::{SessionInfo, SessionNotice, SessionUpdate}, + session::{SessionActivity, SessionInfo, SessionNotice, SessionUpdate}, usage::{ContextUsage, Cost}, }; @@ -55,6 +55,21 @@ fn title(value: MaybeUndefined) -> Change { _ => Change::Keep, } } +// codex-acp reports autonomous app-server turns through this session-info extension. +// Other provider metadata remains inert; unknown or malformed statuses do not change liveness. +fn session_activity(meta: Option<&wire::Meta>) -> Option { + match meta? + .get("codex")? + .get("threadStatus")? + .get("type")? + .as_str()? + { + "active" => Some(SessionActivity::Active), + "idle" => Some(SessionActivity::Idle), + _ => None, + } +} + fn update(value: wire::SessionUpdate) -> Result { Ok(match value { wire::SessionUpdate::UserMessageChunk(chunk) => { @@ -85,6 +100,7 @@ fn update(value: wire::SessionUpdate) -> Result { wire::SessionUpdate::SessionInfoUpdate(value) => { SessionUpdate::SessionInfoUpdate(SessionInfo { title: title(value.title), + activity: session_activity(value.meta.as_ref()), meta: extensions(value.meta), }) } diff --git a/crates/acp/src/mapping/session_tests.rs b/crates/acp/src/mapping/session_tests.rs index 8e6618d8..a6a5f507 100644 --- a/crates/acp/src/mapping/session_tests.rs +++ b/crates/acp/src/mapping/session_tests.rs @@ -3,7 +3,7 @@ use super::{ info::{auth_methods, capabilities, remote_error}, requests::{ new_session, opened, permission, prompt, prompt_outcome, servers, set_config, set_mode, - wire_outcome, wire_session, + wire_outcome, }, session::notice, }; @@ -124,8 +124,10 @@ fn requests_carry_neutral_facts_to_the_protocol_unchanged() { session: SessionId::new("s"), content: vec![Content::text("go")], }); - assert_eq!(request.session_id, wire_session(&SessionId::new("s"))); - assert_eq!(request.prompt.len(), 1); + assert_eq!( + serde_json::to_value(request).unwrap(), + json!({"sessionId":"s","prompt":[{"type":"text","text":"go"}]}), + ); let request = set_mode(SetMode { session: SessionId::new("s"), mode: ModeId::new("plan"), @@ -234,3 +236,30 @@ fn agent_introductions_keep_images_and_sign_in_methods() { assert_eq!(setup.args, ["login"]); assert_eq!(methods[1].label, "Setup"); } + +#[test] +fn codex_thread_status_is_a_typed_activity_without_losing_the_title() { + for (status, expected) in [ + ( + json!({"type":"active","activeFlags":[]}), + Some(SessionActivity::Active), + ), + (json!({"type":"idle"}), Some(SessionActivity::Idle)), + (json!({"type":"notLoaded"}), None), + (json!({"type":"future"}), None), + (json!("active"), None), + (json!(null), None), + ] { + let notice = notice(update(json!({"update":{ + "sessionUpdate":"session_info_update", + "title":"Still my chat", + "_meta":{"codex":{"threadStatus":status}} + }}))) + .unwrap(); + let SessionUpdate::SessionInfoUpdate(info) = notice.update else { + panic!("session info expected"); + }; + assert_eq!(info.title, Change::Set("Still my chat".into())); + assert_eq!(info.activity, expected); + } +} diff --git a/crates/agent-chat/src/thread.rs b/crates/agent-chat/src/thread.rs index c54e67c6..287deebf 100644 --- a/crates/agent-chat/src/thread.rs +++ b/crates/agent-chat/src/thread.rs @@ -46,6 +46,7 @@ mod tool_runtime; pub use restart::RestartData; mod document; pub(crate) mod local_payloads; +mod save_failure; mod saved; mod sign_in_wait; mod title; diff --git a/crates/agent-chat/src/thread/client.rs b/crates/agent-chat/src/thread/client.rs index e191952f..e4658aae 100644 --- a/crates/agent-chat/src/thread/client.rs +++ b/crates/agent-chat/src/thread/client.rs @@ -15,7 +15,7 @@ use nocterm_ai::model::ids::{PermissionOptionId, SessionId}; use nocterm_ai::model::session::{PromptOutcome, SessionNotice, SessionUpdate, StopReason}; use nocterm_ai::{ AgentCommands, AgentInfo, BridgeCall, BridgeRejection, TerminalCall, ToolFailure, - thread::{Entry, ThreadChange}, + thread::ThreadChange, tool_display::{self, ToolDisplay}, }; @@ -267,8 +267,16 @@ impl AgentThread { pub fn apply_presented_update( &mut self, - mut update: SessionUpdate, + update: SessionUpdate, ) -> Result { + self.apply_presented_update_with_row(update) + .map(|(change, _)| change) + } + + fn apply_presented_update_with_row( + &mut self, + mut update: SessionUpdate, + ) -> Result<(ThreadChange, Option), nocterm_ai::history::HistoryCodecError> { self.tools .prepare_displays(self.session.turn(), self.state.entries().len()); tool_display::strip_provider_meta(&mut update); @@ -277,7 +285,7 @@ impl AgentThread { SessionUpdate::ToolCall(_) | SessionUpdate::ToolCallUpdate(_) ); let change = if self.config.report_control(&update) { - ThreadChange::Controls + (ThreadChange::Controls, None) } else { self.state.apply_transcript(update, self.deps.timestamp())? }; @@ -323,6 +331,7 @@ impl AgentThread { self.state.set_pending_history(false, self.deps.timestamp()); self.persist(cx); } + self.resume_observed_turn(); self.dispatch_next(cx); cx.notify(); } @@ -341,13 +350,6 @@ impl AgentThread { } } - pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) { - if !self.deps.enabled(cx) && self.state.release_disabled() { - self.config.disabled(); - self.composer.reset_after_disable(); - } - } - /// The chat's connection stopped. With AI turned off, the chat also /// forgets its transcript and what was attached. pub fn connection_stopped(&mut self, message: &str, cx: &mut Context) { @@ -362,37 +364,38 @@ impl AgentThread { self.config .keep_control(self.session.ticket(), notification); } + if self.session().as_ref() != Some(¬ification.session) { + return; + } if let SessionUpdate::Turn(activity) = ¬ification.update { - if self.session().as_ref() == Some(¬ification.session) { - self.external_turn(activity, cx); - } + self.external_turn(activity, cx); return; } - if self.session().as_ref() != Some(¬ification.session) - || !self.session.accepts_updates() + if let SessionUpdate::SessionInfoUpdate(info) = ¬ification.update + && let Some(activity) = info.activity + { + self.observe_session_activity(activity, cx); + if matches!(info.title, nocterm_ai::model::controls::Change::Keep) { + return; + } + } + if !self.session.accepts_updates() || matches!(notification.update, SessionUpdate::UserMessageChunk(_)) { return; } - let index = match ¬ification.update { - SessionUpdate::ToolCallUpdate(update) => self - .state - .entries() - .iter() - .position(|entry| matches!(entry, Entry::Tool(call) if call.id == update.id)), - _ => self.state.entries().len().checked_sub(1), - }; let configuration = matches!( notification.update, SessionUpdate::ConfigOptionUpdate(_) | SessionUpdate::CurrentModeUpdate(_) ); - let change = match self.apply_presented_update(notification.update.clone()) { - Ok(change) => change, - Err(error) => { - self.fail(&error.to_string(), cx); - return; - } - }; + let (change, index) = + match self.apply_presented_update_with_row(notification.update.clone()) { + Ok(change) => change, + Err(error) => { + self.fail(&error.to_string(), cx); + return; + } + }; match change { ThreadChange::Transcript => { if let Some(index) = index { @@ -701,7 +704,7 @@ impl AgentThread { error: crate::runtime::AgentPersistenceError, cx: &mut Context, ) { - let message = super::notice::persistence_failure(&error); + let message = super::save_failure::message(&error); let diagnostic = nocterm_ai::redact::redact(&format!("{error:?}")); if !self.state.failed(revision, error) { return; diff --git a/crates/agent-chat/src/thread/document.rs b/crates/agent-chat/src/thread/document.rs index b0e02985..50230381 100644 --- a/crates/agent-chat/src/thread/document.rs +++ b/crates/agent-chat/src/thread/document.rs @@ -24,6 +24,7 @@ pub struct ChatDocument { identity: Identity, metadata: Metadata, transcript: Transcript, + transcript_generation: u64, persistence: PersistenceState, budget: BudgetState, changed_rows: HashSet, @@ -53,6 +54,7 @@ impl ChatDocument { ), metadata: Metadata::new(updated), transcript: Transcript::default(), + transcript_generation: 0, persistence: PersistenceState::default(), budget: BudgetState::default(), changed_rows: HashSet::new(), @@ -95,6 +97,14 @@ impl ChatDocument { pub fn transcript(&self) -> &ThreadState { self.transcript.state() } + /// Within one generation, existing agent and thought text and user parts only grow by appending. + pub fn transcript_generation(&self) -> u64 { + self.transcript_generation + } + fn install_transcript(&mut self, transcript: Transcript) { + self.transcript = transcript; + self.transcript_generation = self.transcript_generation.wrapping_add(1); + } pub fn entries(&self) -> &[Entry] { &self.transcript().entries } @@ -133,11 +143,11 @@ impl ChatDocument { pending, ); self.budget = BudgetState::restored(chat.prepared_budget()); - self.transcript = Transcript::restored( + self.install_transcript(Transcript::restored( std::mem::take(&mut chat.entries), std::mem::take(&mut chat.times), chat.header.title.take(), - ); + )); self.persistence.imported_clean(); self.persistence.begin_hydration(); self.draft_debounce = None; @@ -214,12 +224,12 @@ impl ChatDocument { &mut self, update: SessionUpdate, now: u64, - ) -> Result { - let (change, semantic) = self.transcript.apply(update, now)?; + ) -> Result<(ThreadChange, Option), HistoryCodecError> { + let (change, semantic, row) = self.transcript.apply(update, now)?; if semantic { self.changed(now, false); } - Ok(change) + Ok((change, row)) } /// Adds a prompt another device sent as user rows, marked for redraw. pub(super) fn append_prompt( @@ -244,7 +254,7 @@ impl ChatDocument { ) -> Result<(), HistoryCodecError> { let next = self.transcript.replaced(updates, now)?; let rows = self.entries().len().max(next.state().entries.len()); - self.transcript = next; + self.install_transcript(next); for row in 0..rows { self.mark_row(row); } @@ -484,7 +494,7 @@ impl ChatDocument { if !self.clean() || self.draft_changed() { return false; } - self.transcript = Transcript::default(); + self.install_transcript(Transcript::default()); self.budget = BudgetState::default(); self.changed_rows.clear(); true @@ -493,7 +503,7 @@ impl ChatDocument { if !self.clean() && !self.persistence.writer_owns_current() { return false; } - self.transcript = Transcript::default(); + self.install_transcript(Transcript::default()); self.budget = BudgetState::default(); self.changed_rows.clear(); true @@ -509,7 +519,7 @@ impl ChatDocument { pub(super) fn hydrate_restart(&mut self, data: DocumentRestart) { self.identity = data.identity; self.metadata = data.metadata; - self.transcript = data.transcript; + self.install_transcript(data.transcript); self.persistence = data.persistence; self.budget = BudgetState::default(); self.draft_debounce = None; diff --git a/crates/agent-chat/src/thread/document/tests.rs b/crates/agent-chat/src/thread/document/tests.rs index 97956b4d..b5b15353 100644 --- a/crates/agent-chat/src/thread/document/tests.rs +++ b/crates/agent-chat/src/thread/document/tests.rs @@ -55,6 +55,7 @@ fn update(value: serde_json::Value) -> SessionUpdate { }), "session_info_update" => SessionUpdate::SessionInfoUpdate(SessionInfo { title: Change::Set(value["title"].as_str().unwrap().into()), + activity: None, meta: None, }), "usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new( @@ -400,3 +401,158 @@ fn snapshot_capacity_covers_a_hub_account_header_and_draft() { let snapshot = document.snapshot(&inputs).expect("non-empty chat"); assert!(document.snapshot_capacity(&inputs).unwrap() >= snapshot.retained_bytes().unwrap()); } + +fn tool_title_patch(id: &str, title: &str) -> SessionUpdate { + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + id, + ToolChanges::default().title(title), + ))) +} + +fn assert_replaced_tool_rows(mut document: ChatDocument, padding: usize) { + let mut replacement = (0..padding) + .map(|i| { + SessionUpdate::ToolCall(Box::new(ToolRecord::new(format!("fresh-{i}"), "unrelated"))) + }) + .collect::>(); + replacement.push(SessionUpdate::ToolCall(Box::new(ToolRecord::new( + "new", + "replacement", + )))); + replacement.push(SessionUpdate::ToolCall(Box::new(ToolRecord::new( + "new", + "duplicate", + )))); + document.replace_history(replacement, 86).unwrap(); + assert_eq!( + document + .apply_transcript(tool_title_patch("same", "ignored"), 87) + .unwrap(), + (ThreadChange::Transcript, None) + ); + assert_eq!( + document + .apply_transcript(tool_title_patch("new", "last"), 88) + .unwrap(), + (ThreadChange::Transcript, Some(padding)) + ); + assert_eq!(document.entries().len(), padding + 2); + assert_eq!(document.desired_revision(), 6); + assert!(matches!(&document.entries()[padding], Entry::Tool(call) if call.title == "last")); + assert!( + matches!(&document.entries()[padding + 1], Entry::Tool(call) if call.title == "duplicate") + ); +} + +#[test] +fn tool_patches_select_the_first_duplicate_after_restore_append_and_history_replacement() { + for padding in [0, 128] { + let mut entries = vec![Entry::Tool(ToolRecord::new("same", "first"))]; + entries.extend( + (0..padding).map(|i| Entry::Tool(ToolRecord::new(format!("other-{i}"), "unrelated"))), + ); + entries.push(Entry::Tool(ToolRecord::new("same", "second"))); + let duplicate = entries.len() - 1; + let mut document = imported(entries); + assert_eq!( + document + .apply_transcript(tool_title_patch("same", "changed"), 81) + .unwrap(), + (ThreadChange::Transcript, Some(0)) + ); + assert_eq!( + document + .apply_transcript(tool_title_patch("missing", "ignored"), 82) + .unwrap(), + (ThreadChange::Transcript, None) + ); + assert_eq!(document.desired_revision(), 1); + assert!(matches!(&document.entries()[0], Entry::Tool(call) if call.title == "changed")); + assert!( + matches!(&document.entries()[duplicate], Entry::Tool(call) if call.title == "second") + ); + document + .apply_transcript( + SessionUpdate::ToolCall(Box::new(ToolRecord::new("new", "appended"))), + 83, + ) + .unwrap(); + assert_eq!( + document + .apply_transcript(tool_title_patch("new", "updated"), 84) + .unwrap(), + (ThreadChange::Transcript, Some(duplicate + 1)) + ); + assert!( + matches!(&document.entries()[duplicate + 1], Entry::Tool(call) if call.title == "updated") + ); + let mut document = ChatDocument::restarted(document.restart_snapshot()); + assert_eq!( + document + .apply_transcript(tool_title_patch("new", "restarted"), 85) + .unwrap(), + (ThreadChange::Transcript, Some(duplicate + 1)) + ); + assert_replaced_tool_rows(document, padding); + } +} + +#[test] +fn a_matched_patch_in_an_oversized_transcript_does_not_mutate_the_document() { + let mut rows = vec![Entry::Agent(String::new()); nocterm_ai::history::MAX_SAVED_ENTRIES]; + rows.push(Entry::Tool(ToolRecord::new("last", "original"))); + let mut document = imported(rows); + let result = document.apply_transcript( + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + "last", + ToolChanges::default().title("rejected"), + ))), + 81, + ); + assert!(matches!(result, Err(HistoryCodecError::CollectionLimit))); + assert_eq!(document.desired_revision(), 0); + assert_eq!(document.updated(), 40); + assert!( + matches!(document.entries().last(), Some(Entry::Tool(call)) if call.title == "original") + ); +} + +#[test] +#[ignore = "manual dense transcript patch workload"] +fn measure_dense_tool_row_updates() { + use std::{io::Write as _, time::Instant}; + let rows = std::env::var("NOCTERM_PROFILE_TOOL_ROWS") + .unwrap_or_else(|_| "16000".into()) + .parse::() + .unwrap(); + let mut document = imported( + (0..rows) + .map(|index| Entry::Tool(ToolRecord::new(format!("call-{index:05}"), "initial"))) + .collect(), + ); + let target = format!("call-{:05}", rows - 1); + let repeats = 5_000; + let start = Instant::now(); + for i in 0..repeats { + let title = if i % 2 == 0 { "one" } else { "two" }; + document + .apply_transcript( + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + target.as_str(), + ToolChanges::default().title(title), + ))), + 100 + i, + ) + .unwrap(); + } + let elapsed = start.elapsed(); + assert_eq!(document.desired_revision(), repeats); + assert!(matches!(document.entries().last(), Some(Entry::Tool(call)) if call.title == "two")); + writeln!( + std::io::stdout().lock(), + "rows={rows} repeats={repeats} elapsed_ns={} revision={}", + elapsed.as_nanos(), + document.desired_revision() + ) + .unwrap(); +} diff --git a/crates/agent-chat/src/thread/document/transcript.rs b/crates/agent-chat/src/thread/document/transcript.rs index 386367d0..68f53e38 100644 --- a/crates/agent-chat/src/thread/document/transcript.rs +++ b/crates/agent-chat/src/thread/document/transcript.rs @@ -2,14 +2,16 @@ use nocterm_ai::model::content::Content; use nocterm_ai::model::controls::Change; use nocterm_ai::model::session::SessionUpdate; -use nocterm_ai::model::tools::{ToolChanges, ToolRecord, ToolStatus}; +use nocterm_ai::model::tools::{ToolChanges, ToolPatch, ToolRecord, ToolStatus}; use nocterm_ai::model::usage::TokenTotals; +use nocterm_ai::thread::live::ToolRows; use nocterm_ai::thread::{Entry, ThreadChange, ThreadState}; #[derive(Clone)] pub(super) struct Transcript { state: ThreadState, live_bytes: usize, + tool_rows: ToolRows, } impl Default for Transcript { fn default() -> Self { @@ -37,7 +39,11 @@ impl Transcript { ..Default::default() }; let live_bytes = nocterm_ai::thread::live::resident_bytes(&state).unwrap_or(usize::MAX); - Self { state, live_bytes } + Self { + state, + live_bytes, + tool_rows: ToolRows::default(), + } } pub(super) fn state(&self) -> &ThreadState { &self.state @@ -46,12 +52,43 @@ impl Transcript { &mut self, update: SessionUpdate, now: u64, - ) -> Result<(ThreadChange, bool), nocterm_ai::history::HistoryCodecError> { + ) -> Result<(ThreadChange, bool, Option), nocterm_ai::history::HistoryCodecError> { + if let SessionUpdate::ToolCallUpdate(patch) = update { + return self.apply_tool_patch(*patch); + } + let old_len = self.state.entries.len(); let next = nocterm_ai::thread::live::admit_update(&self.state, self.live_bytes, &update)?; let semantic = self.changes_saved(&update); let change = self.state.apply(update, now); + if let Some(Entry::Tool(call)) = self.state.entries.get(old_len) { + self.tool_rows.appended(&call.id, old_len); + } + self.live_bytes = next; + Ok((change, semantic, old_len.checked_sub(1))) + } + + fn apply_tool_patch( + &mut self, + patch: ToolPatch, + ) -> Result<(ThreadChange, bool, Option), nocterm_ai::history::HistoryCodecError> { + let Some(row) = self.tool_rows.find(&self.state.entries, &patch.id) else { + return Ok((ThreadChange::Transcript, false, None)); + }; + let rows = self.state.entries.len(); + let Entry::Tool(call) = &mut self.state.entries[row] else { + unreachable!("tool row lookup returns a matching tool"); + }; + let next = nocterm_ai::thread::live::admit_tool_change( + call, + &patch.changes, + self.live_bytes, + rows, + )?; + let semantic = row >= nocterm_ai::history::SavedChat::saved_entry_start(rows) + && changed_tool(call, &patch.changes); + call.apply(patch.changes); self.live_bytes = next; - Ok((change, semantic)) + Ok((ThreadChange::Transcript, semantic, Some(row))) } fn changes_saved(&self, update: &SessionUpdate) -> bool { match update { @@ -62,20 +99,6 @@ impl Transcript { !matches!((chunk, self.state.entries.last()), (Content::Text(text), Some(Entry::Thought(_))) if text.text.is_empty()) } SessionUpdate::UserMessageChunk(_) | SessionUpdate::ToolCall(_) => true, - SessionUpdate::ToolCallUpdate(update) => self - .state - .entries - .iter() - .enumerate() - .find(|(_, entry)| matches!(entry, Entry::Tool(call) if call.id == update.id)) - .is_some_and(|(row, entry)| { - row >= nocterm_ai::history::SavedChat::saved_entry_start( - self.state.entries.len(), - ) && match entry { - Entry::Tool(call) => changed_tool(call, &update.changes), - _ => false, - } - }), SessionUpdate::SessionInfoUpdate(update) => { matches!(&update.title, Change::Set(title) if Some(title) != self.state.title.as_ref()) } @@ -88,11 +111,13 @@ impl Transcript { updates: Vec, now: u64, ) -> Result { - let mut next = Self::restored(Vec::new(), Vec::new(), self.state.title.clone()); - for update in updates { - next.apply(update, now)?; - } - Ok(next) + let (state, live_bytes) = + nocterm_ai::thread::live::replay_history(self.state.title.clone(), updates, now)?; + Ok(Self { + state, + live_bytes, + tool_rows: ToolRows::default(), + }) } pub(super) fn append_user( &mut self, diff --git a/crates/agent-chat/src/thread/notice.rs b/crates/agent-chat/src/thread/notice.rs index c1822b4a..ead36e77 100644 --- a/crates/agent-chat/src/thread/notice.rs +++ b/crates/agent-chat/src/thread/notice.rs @@ -1,7 +1,4 @@ //! Status text and its error emphasis have one presentation owner. -use crate::runtime::{AgentPersistenceError, PersistenceFailure}; -use nocterm_ai::storage::AgentStorageError; - pub(super) struct ThreadNotice { text: String, error: bool, @@ -35,46 +32,3 @@ impl ThreadNotice { self.error = false; } } - -pub(super) fn persistence_failure(error: &AgentPersistenceError) -> String { - let failure = PersistenceFailure::of(error); - if let Some(guidance) = history_guidance(failure) { - return format!("Could not save chat: {guidance} Queued messages are retained."); - } - let recovery = match failure { - PersistenceFailure::Unsupported => { - "this build lacks the native storage support needed for this chat. Update Nocterm before retrying." - } - PersistenceFailure::StorageFull => "free disk space before retrying.", - PersistenceFailure::AccessDenied => { - "allow access to the chat storage directory before retrying." - } - _ => "resolve the storage error before retrying.", - }; - format!("Could not save chat: {error}. Queued messages are retained; {recovery}") -} - -pub(super) fn load_failure(error: &AgentStorageError) -> String { - if let Some(guidance) = history_guidance(PersistenceFailure::of_storage(error)) { - return format!("Could not open saved chat: {guidance}"); - } - format!("Could not open saved chat: {error}") -} - -fn history_guidance(failure: PersistenceFailure) -> Option<&'static str> { - match failure { - PersistenceFailure::HistoryMemory => { - Some("history needs more memory. Close an unused chat and try again.") - } - PersistenceFailure::HistoryBusy => { - Some("history is busy. Close an unused chat or try again shortly.") - } - PersistenceFailure::ChatLimit => { - Some("this conversation is too large. Start a new chat to continue.") - } - _ => None, - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/agent-chat/src/thread/queue.rs b/crates/agent-chat/src/thread/queue.rs index 6069351a..2706eab8 100644 --- a/crates/agent-chat/src/thread/queue.rs +++ b/crates/agent-chat/src/thread/queue.rs @@ -8,8 +8,8 @@ use super::{ execution::WaitSubject, }; use gpui::{App, Context, EntityId, Task}; -use nocterm_ai::history::{SavedAttachment, SavedPrompt}; -use nocterm_ai::model::content::Content; +use nocterm_ai::history::SavedAttachment; +use nocterm_ai::model::{content::Content, session::SessionActivity}; use nocterm_ai::{BridgeCall, TerminalCall, ToolFailure}; use nocterm_workspace_ports::{ExpectedSession, TerminalEntry, TerminalStatus}; @@ -20,48 +20,8 @@ use super::{AgentThread, Attachment}; mod submit_error; pub(super) use submit_error::SubmitError; -#[derive(Clone)] -pub struct QueuedPrompt { - saved: Arc, - attachments: Vec, - encoded_len: usize, - memory_len: usize, -} - -impl QueuedPrompt { - #[cfg(any(test, feature = "test-support"))] - pub fn new(saved: SavedPrompt, attachments: Vec) -> Self { - Self::prepared(saved, attachments, None) - } - pub fn prepared( - saved: SavedPrompt, - attachments: Vec, - encoded_len: Option, - ) -> Self { - let encoded_len = encoded_len - .unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX)); - let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX); - Self { - memory_len, - saved: Arc::new(saved), - attachments, - encoded_len, - } - } - pub fn saved(&self) -> &Arc { - &self.saved - } - /// What the prompt was written about, captured when it was queued. - pub fn attachments(&self) -> &[Attachment] { - &self.attachments - } - pub fn encoded_len(&self) -> usize { - self.encoded_len - } - pub fn memory_len(&self) -> usize { - self.memory_len - } -} +mod prompt; +pub use prompt::QueuedPrompt; impl AgentThread { pub(super) fn start_execution_watch(&mut self, cx: &mut Context) { @@ -681,8 +641,8 @@ impl AgentThread { } self.state.validate_candidate( &metadata, - queue.iter().map(|prompt| prompt.encoded_len), - queue.iter().map(|prompt| prompt.memory_len), + queue.iter().map(QueuedPrompt::encoded_len), + queue.iter().map(QueuedPrompt::memory_len), )?; self.composer.commit_prompt_change(candidate); self.accept_document_inputs(cx, false); @@ -719,15 +679,46 @@ impl AgentThread { if !self.session.finish_external_turn() { return; } - self.finalize_tool_displays(); - self.notice.present("Ready".into()); - self.persist(cx); - self.dispatch_next(cx); + self.settle_external_turn(cx); } } cx.notify(); } + /// Provider status is an observation, not a new user prompt or a tool grant. + pub(super) fn observe_session_activity( + &mut self, + activity: SessionActivity, + cx: &mut Context, + ) { + if !self.session.observe_activity(activity) { + return; + } + if self.session.generating() { + self.notice.present("Working…".into()); + } else { + self.settle_external_turn(cx); + } + cx.notify(); + } + + pub(super) fn resume_observed_turn(&mut self) { + if self.session.resume_observed_turn() { + self.notice.present("Working…".into()); + } + } + + fn settle_external_turn(&mut self, cx: &mut Context) { + self.finalize_tool_displays(); + self.notice.present(if self.session.stopped() { + "Stopped".into() + } else { + "Ready".into() + }); + self.persist(cx); + self.dispatch_next(cx); + } + pub fn dispatch_next(&mut self, cx: &mut Context) { if !self.queue_dispatchable() || self.session.generating() @@ -751,8 +742,9 @@ impl AgentThread { return; }; // Context is fixed for this turn, including terminal tool access. - self.tools.capture_scope(prompt.attachments); - let saved = Arc::unwrap_or_clone(prompt.saved); + let (attachments, saved) = prompt.into_parts(); + self.tools.capture_scope(attachments); + let saved = Arc::unwrap_or_clone(saved); self.start_prompt(saved.text, saved.images, cx); } } @@ -767,33 +759,3 @@ pub(super) fn restore_attachments(values: &[SavedAttachment]) -> Vec }) .collect() } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn rendering_snapshot_shares_immutable_image_payload() { - let prompt = QueuedPrompt::new( - SavedPrompt { - id: 1, - text: "image".into(), - images: vec![Content::Image(nocterm_ai::model::content::Image::new( - "a".repeat(2 * 1024 * 1024), - "image/png", - ))], - attachments: Vec::new(), - }, - Vec::new(), - ); - let copy = prompt.clone(); - assert!(Arc::ptr_eq(prompt.saved(), copy.saved())); - let Content::Image(original) = &prompt.saved().images[0] else { - panic!("image"); - }; - let Content::Image(cloned) = ©.saved().images[0] else { - panic!("image"); - }; - assert_eq!(original.data.as_ptr(), cloned.data.as_ptr()); - assert_eq!(cloned.data.len(), 2 * 1024 * 1024); - } -} diff --git a/crates/agent-chat/src/thread/queue/prompt.rs b/crates/agent-chat/src/thread/queue/prompt.rs new file mode 100644 index 00000000..e5213dbb --- /dev/null +++ b/crates/agent-chat/src/thread/queue/prompt.rs @@ -0,0 +1,81 @@ +//! Immutable queued prompt and its accounted snapshot; clones share the encoded payload. +use super::Attachment; +use nocterm_ai::history::SavedPrompt; +use std::sync::Arc; + +#[derive(Clone)] +pub struct QueuedPrompt { + saved: Arc, + attachments: Vec, + encoded_len: usize, + memory_len: usize, +} + +impl QueuedPrompt { + #[cfg(any(test, feature = "test-support"))] + pub fn new(saved: SavedPrompt, attachments: Vec) -> Self { + Self::prepared(saved, attachments, None) + } + pub fn prepared( + saved: SavedPrompt, + attachments: Vec, + encoded_len: Option, + ) -> Self { + let encoded_len = encoded_len + .unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX)); + let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX); + Self { + memory_len, + saved: Arc::new(saved), + attachments, + encoded_len, + } + } + pub(super) fn into_parts(self) -> (Vec, Arc) { + (self.attachments, self.saved) + } + pub fn saved(&self) -> &Arc { + &self.saved + } + /// What the prompt was written about, captured when it was queued. + pub fn attachments(&self) -> &[Attachment] { + &self.attachments + } + pub fn encoded_len(&self) -> usize { + self.encoded_len + } + pub fn memory_len(&self) -> usize { + self.memory_len + } +} + +#[cfg(test)] +mod tests { + use super::*; + use nocterm_ai::model::content::Content; + #[test] + fn rendering_snapshot_shares_immutable_image_payload() { + let prompt = QueuedPrompt::new( + SavedPrompt { + id: 1, + text: "image".into(), + images: vec![Content::Image(nocterm_ai::model::content::Image::new( + "a".repeat(2 * 1024 * 1024), + "image/png", + ))], + attachments: Vec::new(), + }, + Vec::new(), + ); + let copy = prompt.clone(); + assert!(Arc::ptr_eq(prompt.saved(), copy.saved())); + let Content::Image(original) = &prompt.saved().images[0] else { + panic!("image"); + }; + let Content::Image(cloned) = ©.saved().images[0] else { + panic!("image"); + }; + assert_eq!(original.data.as_ptr(), cloned.data.as_ptr()); + assert_eq!(cloned.data.len(), 2 * 1024 * 1024); + } +} diff --git a/crates/agent-chat/src/thread/save_failure.rs b/crates/agent-chat/src/thread/save_failure.rs new file mode 100644 index 00000000..f5cb447a --- /dev/null +++ b/crates/agent-chat/src/thread/save_failure.rs @@ -0,0 +1,75 @@ +//! Recovery guidance for typed chat-save and history-load failures. +use crate::runtime::{AgentPersistenceError, PersistenceFailure}; +use nocterm_ai::storage::AgentStorageError; + +pub(super) fn message(error: &AgentPersistenceError) -> String { + let failure = PersistenceFailure::of(error); + if let Some(guidance) = history_guidance(failure) { + return format!("Could not save chat: {guidance} Queued messages are retained."); + } + let recovery = match failure { + PersistenceFailure::Unsupported => { + "this is a limitation of the history storage: this build lacks the native storage support needed for this chat. Update Nocterm before retrying." + } + PersistenceFailure::StorageFull => "free disk space before retrying.", + PersistenceFailure::AccessDenied => { + "allow access to the chat storage directory before retrying." + } + _ => "resolve the storage error before retrying.", + }; + format!("Could not save chat: {error}. Queued messages are retained; {recovery}") +} + +pub(super) fn load_failure(error: &AgentStorageError) -> String { + if let Some(guidance) = history_guidance(PersistenceFailure::of_storage(error)) { + return format!("Could not open saved chat: {guidance}"); + } + format!("Could not open saved chat: {error}") +} + +fn history_guidance(failure: PersistenceFailure) -> Option<&'static str> { + match failure { + PersistenceFailure::HistoryMemory => { + Some("history needs more memory. Close an unused chat and try again.") + } + PersistenceFailure::HistoryBusy => { + Some("history is busy. Close an unused chat or try again shortly.") + } + PersistenceFailure::ChatLimit => { + Some("this conversation is too large. Start a new chat to continue.") + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::message; + use nocterm_ai::storage::AgentStorageError; + use nocterm_session::local_fs::LocalFsError; + use std::{io, sync::Arc}; + + #[test] + fn only_a_full_disk_suggests_freeing_space() { + let unsupported: crate::runtime::AgentPersistenceError = + AgentStorageError::EnvironmentUnsupported(Arc::new(Default::default())).into(); + let full: crate::runtime::AgentPersistenceError = AgentStorageError::from( + LocalFsError::from_io("history", io::Error::from(io::ErrorKind::StorageFull)), + ) + .into(); + let failed: crate::runtime::AgentPersistenceError = AgentStorageError::from( + LocalFsError::from_io("history", io::Error::other("device error")), + ) + .into(); + assert!(message(&unsupported).contains("limitation of the history storage")); + assert!(!message(&unsupported).contains("disk space")); + assert!(message(&full).contains("free disk space")); + assert!(!message(&failed).contains("disk space")); + for text in [message(&unsupported), message(&full), message(&failed)] { + assert!(text.contains("Queued messages are retained")); + } + } +} + +#[cfg(test)] +mod guidance_tests; diff --git a/crates/agent-chat/src/thread/notice/tests.rs b/crates/agent-chat/src/thread/save_failure/guidance_tests.rs similarity index 98% rename from crates/agent-chat/src/thread/notice/tests.rs rename to crates/agent-chat/src/thread/save_failure/guidance_tests.rs index 1fa65c5c..cd14428d 100644 --- a/crates/agent-chat/src/thread/notice/tests.rs +++ b/crates/agent-chat/src/thread/save_failure/guidance_tests.rs @@ -1,3 +1,4 @@ +use super::message as persistence_failure; use super::*; use nocterm_ai::{history::ContextId, local_environment::LocalEnvironment}; use nocterm_session::local_fs::LocalFsError; diff --git a/crates/agent-chat/src/thread/saved.rs b/crates/agent-chat/src/thread/saved.rs index b57ce3b6..b3595691 100644 --- a/crates/agent-chat/src/thread/saved.rs +++ b/crates/agent-chat/src/thread/saved.rs @@ -126,10 +126,18 @@ impl AgentThread { cx.notify(); } + pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) { + if !self.deps.enabled(cx) && self.state.release_disabled() { + self.config.disabled(); + self.composer.reset_after_disable(); + } + } + pub(super) fn configured(&mut self, cx: &mut Context) { self.session.opened(); self.sync_config(true, cx); self.remember_options(cx); + self.resume_observed_turn(); self.dispatch_next(cx); cx.notify(); } @@ -441,7 +449,7 @@ impl AgentThread { archive::LoadOutcome::Stale => return, archive::LoadOutcome::Failed(error) => { tracing::warn!(error = %nocterm_ai::redact::redact(&format!("{error:?}")), "could not load saved chat"); - self.notice.present(super::notice::load_failure(&error)); + self.notice.present(super::save_failure::load_failure(&error)); self.notice.mark_error(); } archive::LoadOutcome::Hydrate { diff --git a/crates/agent-chat/src/thread/session_driver.rs b/crates/agent-chat/src/thread/session_driver.rs index dc7558b0..3fe3bf8a 100644 --- a/crates/agent-chat/src/thread/session_driver.rs +++ b/crates/agent-chat/src/thread/session_driver.rs @@ -1,7 +1,7 @@ //! Session and lease transitions retain their original connection and operation identity. use super::Restore; use crate::runtime::SessionLease; -use nocterm_ai::model::ids::SessionId; +use nocterm_ai::model::{ids::SessionId, session::SessionActivity}; use nocterm_ai::{ AgentCommands, AgentInfo, BridgeRegistration, session::{SessionPhase, SessionState, Ticket}, @@ -228,6 +228,12 @@ impl SessionDriver { pub(super) fn finish_external_turn(&mut self) -> bool { self.phase.finish_external_turn() } + pub(super) fn observe_activity(&mut self, activity: SessionActivity) -> bool { + self.phase.observe_activity(activity) + } + pub(super) fn resume_observed_turn(&mut self) -> bool { + self.phase.resume_observed_turn() + } pub(super) fn opened(&mut self) { self.phase.opened() } diff --git a/crates/agent-chat/src/thread/tool_display.rs b/crates/agent-chat/src/thread/tool_display.rs index 196128af..4d7cc008 100644 --- a/crates/agent-chat/src/thread/tool_display.rs +++ b/crates/agent-chat/src/thread/tool_display.rs @@ -7,9 +7,11 @@ use nocterm_ai::model::tools::ToolRecord; use nocterm_ai::{ ToolFailure, thread::Entry, - tool_display::{self, ToolDisplay}, + tool_display::{self, RawEnvelope, ToolDisplay}, }; +const MAX_RECORDS: usize = 128; + #[derive(Default)] pub(super) struct ToolDisplays { turn: Option, @@ -28,10 +30,12 @@ struct Record { } impl Record { - fn matches(&self, call: &ToolRecord) -> bool { - self.row.as_ref() == Some(&call.id) - || tool_display::raw_envelope(call, &self.server) - .is_some_and(|request| request == self.request) + fn matches(&self, call: &ToolRecord, envelope: Option<&RawEnvelope<'_>>) -> bool { + self.row.as_ref() == Some(&call.id) || self.request_matches(envelope) + } + + fn request_matches(&self, envelope: Option<&RawEnvelope<'_>>) -> bool { + envelope.is_some_and(|envelope| envelope.matches(&self.server, &self.request)) } fn revoke_destination(&mut self) { @@ -87,10 +91,17 @@ impl ToolDisplays { &mut self, entries: &[Entry], ) -> Vec { + if self.records.is_empty() { + return Vec::new(); + } self.revoke_ambiguous_destinations(entries); + let has_unbound = self + .records + .iter() + .any(|record| !record.ambiguous && record.row.is_none()); let mut changed = Vec::new(); - for index in self.start..entries.len() { - let Entry::Tool(call) = &entries[index] else { + for (index, entry) in entries.iter().enumerate().skip(self.start) { + let Entry::Tool(call) = entry else { continue; }; let bound = self @@ -98,43 +109,29 @@ impl ToolDisplays { .iter() .position(|record| record.row.as_ref() == Some(&call.id)); let candidate = bound.or_else(|| { - let matches: Vec<_> = self - .records - .iter() - .enumerate() - .filter(|(_, record)| { - !record.ambiguous - && record.row.is_none() - && tool_display::raw_envelope(call, &record.server) - .is_some_and(|request| request == record.request) - }) - .map(|(index, _)| index) - .collect(); - if matches.len() != 1 { + if !has_unbound { return None; } - let record = &self.records[matches[0]]; - let rows = entries[self.start..] - .iter() - .filter(|entry| { - let Entry::Tool(other) = entry else { - return false; - }; - ToolDisplay::from_call(other).is_none() - && tool_display::raw_envelope(other, &record.server) - .is_some_and(|request| request == record.request) - }) - .count(); - (rows == 1).then_some(matches[0]) + let envelope = RawEnvelope::from_call(call)?; + let candidate = unique(self.records.iter().enumerate().filter_map( + |(index, record)| { + (!record.ambiguous + && record.row.is_none() + && record.request_matches(Some(&envelope))) + .then_some(index) + }, + ))?; + // The preceding ambiguity pass already proved there is at + // most one matching row for every unbound, non-ambiguous record. + (!ToolDisplay::has_valid_metadata(call)).then_some(candidate) }); let Some(candidate) = candidate else { continue; }; let record = &mut self.records[candidate]; - let Entry::Tool(call) = &entries[index] else { - continue; - }; - record.row = Some(call.id.clone()); + if record.row.is_none() { + record.row = Some(call.id.clone()); + } if let Ok(value) = serde_json::to_value(&record.display) && call .meta @@ -149,30 +146,45 @@ impl ToolDisplays { } fn revoke_ambiguous_destinations(&mut self, entries: &[Entry]) { - let ambiguous: Vec<_> = self - .records - .iter() - .enumerate() - .filter(|(_, record)| { - record.ambiguous - || self - .records - .iter() - .filter(|other| { - other.server == record.server && other.request == record.request - }) - .count() - > 1 - || entries[self.start..] - .iter() - .filter(|entry| matches!(entry, Entry::Tool(call) if record.matches(call))) - .count() - > 1 - }) - .map(|(index, _)| index) - .collect(); - for index in ambiguous { - self.records[index].revoke_destination(); + for index in 0..self.records.len() { + let record = &self.records[index]; + let ambiguous = record.ambiguous + || self + .records + .iter() + .filter(|other| { + other.server == record.server && other.request == record.request + }) + .take(2) + .count() + > 1; + if ambiguous { + self.records[index].revoke_destination(); + } + } + if self.records.iter().any(|record| !record.ambiguous) { + self.revoke_duplicate_rows(&entries[self.start..]); + } + } + + fn revoke_duplicate_rows(&mut self, entries: &[Entry]) { + // Each record only needs to distinguish zero, one, or multiple rows. + // Parse a row's envelope once, irrespective of the number of bridge records. + let mut seen = [false; MAX_RECORDS]; + for entry in entries { + let Entry::Tool(call) = entry else { + continue; + }; + let envelope = RawEnvelope::from_call(call); + for (record, seen) in self.records.iter_mut().zip(&mut seen) { + if !record.ambiguous && record.matches(call, envelope.as_ref()) { + if *seen { + record.revoke_destination(); + } else { + *seen = true; + } + } + } } } @@ -182,7 +194,7 @@ impl ToolDisplays { request: (String, serde_json::Value), display: ToolDisplay, ) -> Option { - if self.records.len() >= 128 { + if self.records.len() >= MAX_RECORDS { for record in &mut self.records { if record.server == server && record.request == request { record.revoke_destination(); @@ -210,5 +222,10 @@ impl ToolDisplays { } } +fn unique(mut matches: impl Iterator) -> Option { + let first = matches.next()?; + matches.next().is_none().then_some(first) +} + #[cfg(test)] mod tests; diff --git a/crates/agent-chat/src/thread/tool_display/tests.rs b/crates/agent-chat/src/thread/tool_display/tests.rs index 2930835c..057bbada 100644 --- a/crates/agent-chat/src/thread/tool_display/tests.rs +++ b/crates/agent-chat/src/thread/tool_display/tests.rs @@ -382,3 +382,152 @@ fn an_execution_completed_before_its_provider_row_binds_the_saved_outcome() { }; assert_eq!(value, json!({"text":"completed before row"})); } + +#[test] +fn provider_only_rows_are_not_annotated_and_late_bridge_records_still_bind() { + let mut displays = ToolDisplays::default(); + displays.prepare(1, 0); + let mut entries = vec![ + Entry::Tool(ToolRecord::new("provider", "Provider activity")), + row("c1"), + ]; + assert!(normalize(&mut displays, &mut entries).is_empty()); + assert!( + entries.iter().all( + |entry| matches!(entry, Entry::Tool(call) if ToolDisplay::from_call(call).is_none()) + ) + ); + displays.records.push(record()); + assert_eq!(normalize(&mut displays, &mut entries), vec![1]); + assert!(matches!(&entries[0], Entry::Tool(call) if ToolDisplay::from_call(call).is_none())); + assert!(matches!(&entries[1], Entry::Tool(call) if ToolDisplay::from_call(call).is_some())); +} + +#[test] +#[ignore = "manual provider-only and bridge reconciliation workload"] +fn measure_dense_tool_display_reconciliation() { + use std::{hint::black_box, io::Write as _, time::Instant}; + let rows = std::env::var("NOCTERM_PROFILE_TOOL_ROWS") + .unwrap_or_else(|_| "16000".into()) + .parse::() + .unwrap(); + let bridge = std::env::var("NOCTERM_PROFILE_TOOL_BRIDGE").as_deref() == Ok("1"); + let mut displays = ToolDisplays::default(); + displays.prepare(1, 0); + let mut entries = (0..rows) + .map(|index| { + Entry::Tool(ToolRecord::new( + format!("provider-{index:05}"), + "Provider activity", + )) + }) + .collect::>(); + if bridge { + displays.records.push(record()); + entries.push(row("local")); + assert_eq!(normalize(&mut displays, &mut entries), vec![rows]); + } + let repeats = if bridge { 200 } else { 5_000 }; + let start = Instant::now(); + for _ in 0..repeats { + assert!(black_box(displays.normalize(black_box(&entries))).is_empty()); + } + let elapsed = start.elapsed(); + writeln!( + std::io::stdout().lock(), + "rows={rows} bridge={bridge} repeats={repeats} elapsed_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} + +#[test] +#[ignore = "manual bridge envelope comparison workload"] +fn measure_bridge_envelope_comparisons() { + use std::{hint::black_box, io::Write as _, time::Instant}; + let rows = std::env::var("NOCTERM_PROFILE_BRIDGE_ROWS") + .unwrap_or_else(|_| "2000".into()) + .parse::() + .unwrap(); + let payload = std::env::var("NOCTERM_PROFILE_BRIDGE_BYTES") + .unwrap_or_else(|_| "1024".into()) + .parse::() + .unwrap(); + let records = std::env::var("NOCTERM_PROFILE_BRIDGE_RECORDS") + .unwrap_or_else(|_| "1".into()) + .parse::() + .unwrap(); + let mut displays = ToolDisplays::default(); + displays.prepare(1, 0); + let mut entries = (0..rows) + .map(|i| { + let arguments = json!({"index":i,"fixture":"x".repeat(payload)}); + if i < records { + displays.record_raw( + "nocterm-3".into(), + ("fixture".into(), arguments.clone()), + ToolDisplay::requested("fixture".into(), arguments.clone()), + ); + } + Entry::Tool( + ToolRecord::new(format!("row-{i:05}"), "mcp.nocterm-3.fixture") + .raw_input(arguments), + ) + }) + .collect::>(); + assert_eq!( + normalize(&mut displays, &mut entries), + (0..records).collect::>() + ); + let repeats = 100; + let start = Instant::now(); + for _ in 0..repeats { + assert!(black_box(displays.normalize(black_box(&entries))).is_empty()); + } + let elapsed = start.elapsed(); + writeln!( + std::io::stdout().lock(), + "rows={rows} bytes={payload} records={records} repeats={repeats} elapsed_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} + +#[test] +fn an_already_annotated_matching_row_still_makes_an_unbound_request_ambiguous() { + let mut displays = ToolDisplays::default(); + displays.prepare(1, 0); + let mut entries = vec![row("annotated"), row("new")]; + let Entry::Tool(call) = &mut entries[0] else { + unreachable!() + }; + let bridge = record(); + bridge.display.attach(call); + displays.records.push(bridge); + assert!(normalize(&mut displays, &mut entries).is_empty()); + let Entry::Tool(new) = &entries[1] else { + unreachable!() + }; + assert!(ToolDisplay::from_call(new).is_none()); +} + +#[test] +fn a_bound_id_and_a_different_matching_row_revoke_the_destination_even_after_input_changes() { + let mut displays = ToolDisplays::default(); + displays.prepare(1, 0); + displays.records.push(record()); + let mut entries = vec![row("bound")]; + assert_eq!(normalize(&mut displays, &mut entries), vec![0]); + let Entry::Tool(call) = &mut entries[0] else { + unreachable!() + }; + call.raw_input = Some(json!({"unrelated":true})); + entries.push(row("other")); + assert_eq!(normalize(&mut displays, &mut entries), vec![0]); + let Entry::Tool(call) = &entries[0] else { + unreachable!() + }; + let display = ToolDisplay::from_call(call).unwrap(); + assert!(display.destination.is_none()); + assert_eq!(display.arguments["command"], "echo hello"); +} diff --git a/crates/agent-directory/src/lib.rs b/crates/agent-directory/src/lib.rs index 72a72a29..eb325d13 100644 --- a/crates/agent-directory/src/lib.rs +++ b/crates/agent-directory/src/lib.rs @@ -61,12 +61,28 @@ impl AgentsHandle { } pub fn get(&self, id: &str, cx: &App) -> Option { - self.available(cx).get(id).cloned() + let settings = self.settings.setting::(cx); + if !settings.enabled { + return None; + } + AvailableAgents::resolve_one(&self.catalog, settings, id).or_else(|| { + let hubs = self.hubs.as_ref()?; + let launch = hubs(cx) + .into_iter() + .find(|launch| launch.id == id && launch.hub.is_some())?; + AvailableAgents::default() + .with_hub_agents([launch]) + .get(id) + .cloned() + }) } /// The profile of agent `id`: its own when available, else the catalog's. pub fn profile(&self, id: &str, cx: &App) -> Option { - self.profile_in(&self.available(cx), id) + match self.get(id, cx) { + Some(agent) => agent.profile().copied(), + None => self.catalog.get(id).copied(), + } } /// The profile of agent `id` among agents already resolved by [`Self::available`], diff --git a/crates/agent-directory/src/tests.rs b/crates/agent-directory/src/tests.rs index c8eb4e06..74eb64a3 100644 --- a/crates/agent-directory/src/tests.rs +++ b/crates/agent-directory/src/tests.rs @@ -71,3 +71,129 @@ async fn the_agents_of_signed_in_hubs_are_available_beside_the_local_ones(cx: &m assert!(agents.get("alpha", cx).is_some()); }); } + +#[gpui::test] +#[ignore = "release profile of one-agent lookup through AgentsHandle"] +async fn measure_agent_directory_lookup(cx: &mut TestAppContext) { + use std::{hint::black_box, io::Write as _, time::Instant}; + let count = std::env::var("NOCTERM_PROFILE_AGENT_COUNT") + .map_or(Ok(512), |count| count.parse::()) + .unwrap(); + assert!(count <= 4096); + let hub_count = std::env::var("NOCTERM_PROFILE_HUB_AGENT_COUNT") + .map_or(Ok(0), |count| count.parse::()) + .unwrap(); + assert!(hub_count <= 4096); + let hub = nocterm_hubs_model::HubId::from( + nocterm_hubs_model::HubAddress::parse("hub.example:7443").unwrap(), + ); + let agents = handle(cx).with_hub_agents(Rc::new(move |_| { + (0..hub_count) + .map(|index| { + AgentLaunch::hub_agent(hub.clone(), index.to_string(), format!("Hub agent {index}")) + }) + .collect() + })); + cx.update(|cx| { + agents.settings.update::(cx, move |ai| { + for index in 0..count { + let id = format!("custom-{index}"); + ai.agents.insert( + id, + AgentServerSettings { + command: Some("/opt/alpha/run".into()), + name: Some(format!("Agent {index}")), + args: Some(vec!["acp".into()]), + ..Default::default() + }, + ); + } + }) + }) + .await + .unwrap(); + let mut samples = cx.update(|cx| { + std::array::from_fn::<_, 25, _>(|_| { + let started = Instant::now(); + for _ in 0..64 { + let profile = black_box(agents.profile(black_box("alpha"), cx)); + assert_eq!(profile, Some(ALPHA)); + let agent = black_box(agents.get(black_box("alpha"), cx)).unwrap(); + assert_eq!(agent.id(), "alpha"); + assert_eq!(agent.source(), AgentSource::Builtin); + } + started.elapsed() + }) + }); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "agents={count} hubs={hub_count} lookup_p50={:?} lookup_max={:?}", + samples[12], + samples[24] + ) + .unwrap(); +} + +#[gpui::test] +async fn direct_lookup_follows_local_precedence_and_live_hub_changes(cx: &mut TestAppContext) { + use nocterm_hubs_model::{HubAddress, HubId}; + use std::cell::RefCell; + let hub = HubId::from(HubAddress::parse("hub.example:7443").unwrap()); + let launch = AgentLaunch::hub_agent(hub, "a1".into(), "Ops".into()); + let id = launch.id.clone(); + let launches = Rc::new(RefCell::new(vec![launch.clone()])); + let current = launches.clone(); + let agents = handle(cx).with_hub_agents(Rc::new(move |_| current.borrow().clone())); + cx.update(|cx| { + assert_eq!(agents.get(&id, cx), agents.available(cx).get(&id).cloned()); + assert_eq!(agents.profile("alpha", cx), Some(ALPHA)); + assert_eq!(agents.profile(&id, cx), None); + }); + let override_id = id.clone(); + cx.update(|cx| { + agents.settings.update::(cx, move |settings| { + settings.agents.insert( + override_id, + AgentServerSettings { + command: Some("/opt/alpha/run".into()), + ..Default::default() + }, + ); + }) + }) + .await + .unwrap(); + cx.update(|cx| { + assert_eq!(agents.get(&id, cx).unwrap().source(), AgentSource::Custom); + assert_eq!(agents.get(&id, cx), agents.available(cx).get(&id).cloned()); + assert_eq!(agents.profile(&id, cx), Some(ALPHA)); + }); + let override_id = id.clone(); + cx.update(|cx| { + agents.settings.update::(cx, move |settings| { + settings.agents.remove(&override_id); + }) + }) + .await + .unwrap(); + cx.update(|cx| { + assert_eq!(agents.get(&id, cx).unwrap().source(), AgentSource::Hub); + launches.borrow_mut().clear(); + assert!(agents.get(&id, cx).is_none()); + assert_eq!(agents.profile("alpha", cx), Some(ALPHA)); + }); + cx.update(|cx| { + agents + .settings + .update::(cx, |settings| settings.enabled = false) + }) + .await + .unwrap(); + launches.borrow_mut().push(launch); + cx.update(|cx| { + assert!(agents.get(&id, cx).is_none()); + assert!(agents.get("alpha", cx).is_none()); + assert_eq!(agents.profile("alpha", cx), Some(ALPHA)); + }); +} diff --git a/crates/agent-runtime/src/catalog.rs b/crates/agent-runtime/src/catalog.rs index 42f71c64..fb67426f 100644 --- a/crates/agent-runtime/src/catalog.rs +++ b/crates/agent-runtime/src/catalog.rs @@ -5,7 +5,7 @@ use gpui::{Context, Task}; use nocterm_ai::{ execution_origin::ChatKey, history::{ChatSummary, ContextId, HistoryGate, SavedChat}, - local_environment::ChatScope, + local_environment::{ChatScope, LocalEnvironmentAccess}, storage::{AgentStorageError, ChatRepository, require_local_scope}, }; use std::sync::Arc; @@ -133,7 +133,15 @@ struct ScopeCatalog { snapshot: Option, generation: u64, loading: Option>, + hinted_reload: Option<(LocalEnvironmentAccess, CatalogRead)>, } + +#[derive(Clone, Copy)] +pub(super) enum CatalogRead { + Cached, + Refresh, +} + pub(super) struct Catalog { saved: PreparedRecords, scopes: std::collections::HashMap, @@ -277,7 +285,7 @@ impl Catalog { ScopeCatalog { snapshot: Some(CatalogSnapshot { payload }), generation, - loading: None, + ..ScopeCatalog::default() }, ); Ok(()) @@ -302,16 +310,30 @@ impl Catalog { &mut self, scope: ChatScope, cx: &mut Context, + ) -> Result<(), CatalogLoadError> { + self.read(scope, CatalogRead::Refresh, cx) + } + + fn read( + &mut self, + scope: ChatScope, + read: CatalogRead, + cx: &mut Context, ) -> Result<(), CatalogLoadError> { let (generation, allocation) = self.reserve(scope.clone(), allocation::WORK_BYTES, cx)?; let entry = self.scopes.entry(scope.clone()).or_default(); entry.generation = generation; + entry.hinted_reload = None; let repository = self.repository.clone(); let captured = scope.clone(); let (complete, loading) = futures::channel::oneshot::channel(); cx.background_executor() .spawn(async move { - let rows = CatalogAllocation::check(repository.catalog_in(captured).await); + let rows = match read { + CatalogRead::Cached => repository.catalog_cached_in(captured), + CatalogRead::Refresh => repository.catalog_in(captured), + }; + let rows = CatalogAllocation::check(rows.await); // The detached bounded read owns its allocation independently of a // cancelled viewer. An abandoned result drops bytes and proof together. let _ = complete.send((rows, allocation)); @@ -322,18 +344,45 @@ impl Catalog { return; }; let _ = runtime.update(cx, |runtime, cx| { - runtime.chats.loaded(scope, generation, rows, allocation); + runtime + .chats + .loaded(scope, generation, rows, allocation, cx); cx.notify(); }); })); Ok(()) } + pub(super) fn history_changed( + &mut self, + scope: ChatScope, + source: LocalEnvironmentAccess, + read: CatalogRead, + cx: &mut Context, + ) -> Result<(), CatalogLoadError> { + if self.closing { + return Err(CatalogLoadError::Closed); + } + if let Some(entry) = self.scopes.get_mut(&scope) + && entry.loading.is_some() + { + if matches!(read, CatalogRead::Cached) + && let Some((pending_source, CatalogRead::Refresh)) = &entry.hinted_reload + && pending_source.check_current().is_ok() + { + return Ok(()); + } + entry.hinted_reload = Some((source, read)); + return Ok(()); + } + self.read(scope, read, cx) + } pub(super) fn complete( &mut self, scope: ChatScope, generation: u64, rows: Result, AgentStorageError>, allocation: CatalogAllocation, + cx: &mut Context, ) { if self.closing { return; @@ -344,46 +393,28 @@ impl Catalog { if entry.generation != generation { return; } - let (mut rows, error): (Vec, _) = match rows { - Ok(mut rows) => { - rows.retain(|row| { - require_local_scope(&scope, &row.chat_scope()).is_ok() && row.validate().is_ok() + entry.loading.take(); + let hinted_reload = entry.hinted_reload.take(); + let (rows, error) = checked_catalog_rows(&scope, rows, &self.saved); + match allocation.finish(&self.admission, &rows, rows.capacity()) { + Ok(allocation) => { + let payload = Arc::new(CatalogPayload { + scope: scope.clone(), + generation, + rows, + error, + allocation, }); - rows.truncate(nocterm_ai::history::MAX_RESTORED); - (rows, None) - } - Err(error) => { - tracing::warn!(%error, "could not load agent catalog"); - (Vec::new(), Some(error)) + entry.snapshot = Some(CatalogSnapshot { payload }); } - }; - if scope == ContextId::General.into() - && let Some(prepared) = self.saved.rows() + Err(error) => tracing::warn!(%error, "could not retain catalog metadata"), + } + if let Some((source, read)) = hinted_reload + && source.check_current().is_ok() + && let Err(error) = self.read(scope, read, cx) { - for row in prepared { - rows.retain(|known| known.id != row.id); - rows.push(row); - } - rows.sort_by_key(|row| std::cmp::Reverse((row.pinned, row.updated))); - rows.truncate(nocterm_ai::history::MAX_RESTORED); + tracing::warn!(%error, "could not refresh changed agent history"); } - let allocation = match allocation.finish(&self.admission, &rows, rows.capacity()) { - Ok(allocation) => allocation, - Err(error) => { - entry.loading.take(); - tracing::warn!(%error, "could not retain catalog metadata"); - return; - } - }; - let payload = Arc::new(CatalogPayload { - scope, - generation, - rows, - error, - allocation, - }); - entry.snapshot = Some(CatalogSnapshot { payload }); - entry.loading.take(); } pub(super) fn invalidate(&mut self, scope: ChatScope) { self.scopes.remove(&scope); @@ -431,8 +462,40 @@ impl Catalog { self.closing = true; for entry in self.scopes.values_mut() { entry.loading.take(); + entry.hinted_reload.take(); + } + } +} + +fn checked_catalog_rows( + scope: &ChatScope, + rows: Result, AgentStorageError>, + saved: &PreparedRecords, +) -> (Vec, Option) { + let (mut rows, error): (Vec, _) = match rows { + Ok(mut rows) => { + rows.retain(|row| { + require_local_scope(scope, &row.chat_scope()).is_ok() && row.validate().is_ok() + }); + rows.truncate(nocterm_ai::history::MAX_RESTORED); + (rows, None) + } + Err(error) => { + tracing::warn!(%error, "could not load agent catalog"); + (Vec::new(), Some(error)) + } + }; + if *scope == ContextId::General.into() + && let Some(prepared) = saved.rows() + { + for row in prepared { + rows.retain(|known| known.id != row.id); + rows.push(row); } + rows.sort_by_key(|row| std::cmp::Reverse((row.pinned, row.updated))); + rows.truncate(nocterm_ai::history::MAX_RESTORED); } + (rows, error) } fn catalog_admission_error(error: HistoryAdmissionError) -> CatalogLoadError { diff --git a/crates/agent-runtime/src/documents.rs b/crates/agent-runtime/src/documents.rs index 1886fc58..78722b57 100644 --- a/crates/agent-runtime/src/documents.rs +++ b/crates/agent-runtime/src/documents.rs @@ -5,7 +5,7 @@ use gpui::AppContext as _; use nocterm_ai::{ execution_origin::ChatKey, history::{ChatSummary, ContextId, SavedChat, SharedChat}, - local_environment::ChatScope, + local_environment::{ChatScope, LocalEnvironmentAccess}, storage::AgentStorageError, }; use nocterm_store::{KeyedPersisted, KeyedRetention, StoreError}; @@ -381,6 +381,7 @@ impl ChatStore { generation: u64, rows: Result, AgentStorageError>, allocation: crate::catalog::CatalogAllocation, + cx: &mut Context, ) { let rows = rows.map(|mut rows| { rows.retain(|row| { @@ -391,7 +392,8 @@ impl ChatStore { }); rows }); - self.catalog.complete(scope, generation, rows, allocation) + self.catalog + .complete(scope, generation, rows, allocation, cx) } pub(super) fn ensure( &mut self, @@ -407,6 +409,15 @@ impl ChatStore { ) -> Result<(), crate::CatalogLoadError> { self.catalog.reload(scope, cx) } + pub(super) fn history_changed( + &mut self, + scope: ChatScope, + source: LocalEnvironmentAccess, + read: crate::catalog::CatalogRead, + cx: &mut Context, + ) -> Result<(), CatalogLoadError> { + self.catalog.history_changed(scope, source, read, cx) + } pub(super) fn claim_residency( &self, claim: &DocumentClaim, diff --git a/crates/agent-runtime/src/documents/history_tests/contexts/catalog_capacity.rs b/crates/agent-runtime/src/documents/history_tests/contexts/catalog_capacity.rs index dea9bcbe..cd28ce86 100644 --- a/crates/agent-runtime/src/documents/history_tests/contexts/catalog_capacity.rs +++ b/crates/agent-runtime/src/documents/history_tests/contexts/catalog_capacity.rs @@ -2,6 +2,66 @@ use super::*; use crate::history_admission::{HistoryAdmissionError, MAX_NORMAL_HISTORY_BYTES}; +#[gpui::test] +fn chat_change_bursts_share_a_pending_catalog_read(cx: &mut TestAppContext) { + let (general, _directory, repository, _, _) = scoped_fixture(cx); + let project = general.for_scope(project_chat().header.scope); + let second_view = project.clone(); + let mut chat = project_chat(); + chat.header.title = Some("Initial".into()); + repository.seed_chat(&chat).unwrap(); + cx.update(|cx| project.try_reload_history(cx).unwrap()); + cx.run_until_parked(); + let before = repository.operations().len(); + let release = repository.block_next(StorageOperation::Catalog); + cx.update(|cx| project.try_reload_history(cx).unwrap()); + cx.run_until_parked(); + let mut refused = 0; + cx.update(|cx| { + for _ in 0..50 { + for view in [&project, &second_view] { + refused += usize::from(view.history_changed(cx).is_err()); + } + } + }); + cx.run_until_parked(); + let while_blocked = repository.operations().len() - before; + chat.header.title = Some("Latest".into()); + repository.seed_chat(&chat).unwrap(); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + + let total = repository.operations().len() - before; + assert_eq!((while_blocked, total, refused), (1, 2, 0)); + assert_eq!( + cx.update(|cx| project.catalog_snapshot(cx).unwrap().rows()[0] + .title() + .to_owned()), + "Latest" + ); +} + +#[gpui::test] +fn explicit_reload_covers_a_change_waiting_on_the_older_read(cx: &mut TestAppContext) { + let (general, _directory, repository, _, _) = scoped_fixture(cx); + let project = general.for_scope(project_chat().header.scope); + cx.run_until_parked(); + let before = repository.operations().len(); + let release = repository.block_next(StorageOperation::Catalog); + cx.update(|cx| project.history_changed(cx).unwrap()); + cx.run_until_parked(); + cx.update(|cx| { + project.history_changed(cx).unwrap(); + project.try_reload_history(cx).unwrap(); + }); + cx.run_until_parked(); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + + assert_eq!(repository.operations().len() - before, 2); + assert!(cx.update(|cx| project.catalog_snapshot(cx)).is_some()); +} + #[gpui::test] fn catalogs_and_saved_chats_remain_available_with_a_busy_installation(cx: &mut TestAppContext) { let (general, _directory, _, _, _) = scoped_fixture(cx); diff --git a/crates/agent-runtime/src/documents/history_tests/environments.rs b/crates/agent-runtime/src/documents/history_tests/environments.rs index 428eca36..a608bc09 100644 --- a/crates/agent-runtime/src/documents/history_tests/environments.rs +++ b/crates/agent-runtime/src/documents/history_tests/environments.rs @@ -157,6 +157,119 @@ fn stale_claims_and_native_startup_cannot_acquire_the_replacement_account(cx: &m assert_eq!(claim.key().environment(), current.environment().unwrap()); }); } +#[gpui::test] +fn a_pending_history_hint_does_not_reload_a_replaced_account_lease(cx: &mut TestAppContext) { + let (base, _directory, repository, _, _) = contexts::scoped_fixture(cx); + let factory = ScriptedLocalAccountFactory::default(); + let partition = partition(1, "alice"); + factory.sign_in(partition.clone()); + let original = bind(&base, &factory); + cx.run_until_parked(); + let before = repository.operations().len(); + let release = repository.block_next(StorageOperation::Catalog); + cx.update(|cx| original.history_changed(cx).unwrap()); + cx.run_until_parked(); + cx.update(|cx| original.history_changed(cx).unwrap()); + factory.sign_in(partition); + let replacement = bind(&base, &factory); + assert!(original.check_current().is_err()); + assert!(replacement.check_current().is_ok()); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + assert_eq!(repository.operations().len() - before, 1); + + cx.update(|cx| replacement.history_changed(cx).unwrap()); + cx.run_until_parked(); + assert_eq!(repository.operations().len() - before, 2); + assert!(cx.update(|cx| replacement.catalog_snapshot(cx)).is_some()); +} + +#[gpui::test] +fn cache_publication_history_hints_coalesce_and_show_the_latest_rows(cx: &mut TestAppContext) { + let (base, _directory, repository, _, _) = contexts::scoped_fixture(cx); + let factory = ScriptedLocalAccountFactory::default(); + factory.sign_in(partition(1, "alice")); + let handle = bind(&base, &factory); + cx.run_until_parked(); + let before = repository.operations().len(); + let release = repository.block_next(StorageOperation::CachedCatalog); + cx.update(|cx| handle.history_cache_changed(cx).unwrap()); + cx.run_until_parked(); + repository + .seed_chat(&chat(&handle, "Published").metadata) + .unwrap(); + cx.update(|cx| { + handle.history_cache_changed(cx).unwrap(); + handle.history_cache_changed(cx).unwrap(); + }); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + assert_eq!( + &repository.operations()[before..], + &[ + StorageOperation::CachedCatalog, + StorageOperation::CachedCatalog + ], + ); + cx.update(|cx| { + assert_eq!( + handle.catalog_snapshot(cx).unwrap().rows()[0].title(), + "Published" + ); + }); +} + +#[gpui::test] +fn cache_publication_history_hints_preserve_a_pending_remote_refresh(cx: &mut TestAppContext) { + let (base, _directory, repository, _, _) = contexts::scoped_fixture(cx); + let factory = ScriptedLocalAccountFactory::default(); + factory.sign_in(partition(1, "alice")); + let handle = bind(&base, &factory); + cx.run_until_parked(); + let before = repository.operations().len(); + let release = repository.block_next(StorageOperation::CachedCatalog); + cx.update(|cx| handle.history_cache_changed(cx).unwrap()); + cx.run_until_parked(); + cx.update(|cx| { + handle.history_cache_changed(cx).unwrap(); + handle.history_changed(cx).unwrap(); + handle.history_cache_changed(cx).unwrap(); + }); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + assert_eq!( + &repository.operations()[before..], + &[StorageOperation::CachedCatalog, StorageOperation::Catalog], + ); +} + +#[gpui::test] +fn a_cache_publication_does_not_inherit_a_replaced_accounts_refresh(cx: &mut TestAppContext) { + let (base, _directory, repository, _, _) = contexts::scoped_fixture(cx); + let factory = ScriptedLocalAccountFactory::default(); + let partition = partition(1, "alice"); + factory.sign_in(partition.clone()); + let original = bind(&base, &factory); + cx.run_until_parked(); + let before = repository.operations().len(); + let release = repository.block_next(StorageOperation::CachedCatalog); + cx.update(|cx| original.history_cache_changed(cx).unwrap()); + cx.run_until_parked(); + cx.update(|cx| original.history_changed(cx).unwrap()); + factory.sign_in(partition); + let replacement = bind(&base, &factory); + cx.update(|cx| replacement.history_cache_changed(cx).unwrap()); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + assert_eq!( + &repository.operations()[before..], + &[ + StorageOperation::CachedCatalog, + StorageOperation::CachedCatalog + ], + ); +} + #[gpui::test] fn all_account_context_views_consume_one_installation_catalog_budget(cx: &mut TestAppContext) { let (base, _directory, repository, _, _) = contexts::scoped_fixture(cx); diff --git a/crates/agent-runtime/src/handle.rs b/crates/agent-runtime/src/handle.rs index 358329db..2123dfbb 100644 --- a/crates/agent-runtime/src/handle.rs +++ b/crates/agent-runtime/src/handle.rs @@ -442,6 +442,25 @@ impl RuntimeHandle { runtime.try_scoped_reload_history(self.chat_scope()?, cx) }) } + /// Refresh after an external change. A running read retains one follow-up for this scope. + pub fn history_changed(&self, cx: &mut App) -> Result<(), crate::CatalogLoadError> { + self.history_hint(crate::catalog::CatalogRead::Refresh, cx) + } + /// Read history after a cache publication without requesting another network refresh. + pub fn history_cache_changed(&self, cx: &mut App) -> Result<(), crate::CatalogLoadError> { + self.history_hint(crate::catalog::CatalogRead::Cached, cx) + } + fn history_hint( + &self, + read: crate::catalog::CatalogRead, + cx: &mut App, + ) -> Result<(), crate::CatalogLoadError> { + let source = self.captured_source()?; + let scope = ChatScope::new(source.environment().clone(), self.scope); + self.runtime.update(cx, |runtime, cx| { + runtime.chats.history_changed(scope, source, read, cx) + }) + } pub fn reload_history(&self, cx: &mut App) { if self.check_current().is_err() { return; diff --git a/crates/agent-settings-ui/src/agents.rs b/crates/agent-settings-ui/src/agents.rs index 8bb2fd9d..f69914cb 100644 --- a/crates/agent-settings-ui/src/agents.rs +++ b/crates/agent-settings-ui/src/agents.rs @@ -10,11 +10,12 @@ use nocterm_ai::{ }; use std::collections::BTreeSet; impl AiPage { - pub(super) fn new(probe: std::sync::Arc) -> Self { + pub(super) fn new(probe: std::sync::Arc, cx: &mut gpui_kit::App) -> Self { Self { probe, expanded: BTreeSet::new(), agents: Vec::new(), + list: super::listing::AgentList::new(cx), new_id: None, new_command: None, add_error: None, @@ -24,19 +25,20 @@ impl AiPage { } } -fn agent_ids(catalog: &AgentCatalog, settings: &AiSettings) -> Vec { - let mut ids: Vec = catalog +fn agent_ids<'a>( + catalog: &'a AgentCatalog, + settings: &'a AiSettings, +) -> impl Iterator { + catalog .iter() - .map(|profile| profile.id().to_owned()) - .collect(); - ids.extend( - settings - .agents - .keys() - .filter(|id| !catalog.is_builtin(id)) - .cloned(), - ); - ids + .map(|profile| -> &'a str { profile.id() }) + .chain( + settings + .agents + .keys() + .map(String::as_str) + .filter(move |id| !catalog.is_builtin(id)), + ) } pub(super) fn add_fields( @@ -68,30 +70,58 @@ pub(super) fn add_fields( sync(view, window, cx); } -/// Adds fields for agents that appeared and drops those of removed ones. +/// Updates the ordered list and retires fields of removed agents. Only opened +/// details own input fields, including a newly added agent opened on admission. pub(super) fn sync( view: &mut AgentSettingsPage, window: &mut Window, cx: &mut Context, ) { - let ids = agent_ids( - view.agents().catalog(), - view.settings().setting::(cx), - ); - for id in view.ai.agents.clone() { - if !ids.contains(&id) { - view.remove_fields(&format!("agent.{id}.")); - view.ai.expanded.remove(&id); + let ids: Vec<_> = { + let catalog = view.agents().catalog(); + let settings = view.settings().setting::(cx); + if agent_ids(catalog, settings).eq(view.ai.agents.iter().map(String::as_str)) { + return; } + agent_ids(catalog, settings).map(str::to_owned).collect() + }; + let present: BTreeSet<_> = ids.iter().map(String::as_str).collect(); + let removed: Vec<_> = view + .ai + .agents + .iter() + .filter(|id| !present.contains(id.as_str())) + .cloned() + .collect(); + for id in removed { + view.remove_fields(&format!("agent.{id}.")); + view.ai.expanded.remove(&id); } for id in &ids { - if !view.ai.agents.contains(id) { - agent_fields(view, id.clone(), window, cx); + if view.ai.expanded.contains(id) { + ensure_agent_fields(view, id, window, cx); } } + view.ai.list.replace(&view.ai.agents, &ids, &present, cx); view.ai.agents = ids; } +/// First expansion creates the original receipt owners. Collapse retains +/// them so a pending save or invalid literal survives reopening. +pub(super) fn ensure_agent_fields( + view: &mut AgentSettingsPage, + id: &str, + window: &mut Window, + cx: &mut Context, +) { + if !view + .fields + .contains_key(format!("agent.{id}.name").as_str()) + { + agent_fields(view, id.to_owned(), window, cx); + } +} + fn agent_fields( view: &mut AgentSettingsPage, id: String, @@ -153,7 +183,10 @@ fn agent_fields( let catalog = view.agents().catalog().clone(); view.add_field( format!("agent.{id}.{name}"), - move |s: &AiSettings| get(&s.agents.get(&read_id).cloned().unwrap_or_default()), + move |s: &AiSettings| match s.agents.get(&read_id) { + Some(agent) => get(agent), + None => get(&AgentServerSettings::default()), + }, move |s, text| edit_agent(&catalog, s, &write_id, |agent| set(agent, text)), window, cx, diff --git a/crates/agent-settings-ui/src/controls.rs b/crates/agent-settings-ui/src/controls.rs index 4a54a884..b00b21ee 100644 --- a/crates/agent-settings-ui/src/controls.rs +++ b/crates/agent-settings-ui/src/controls.rs @@ -10,7 +10,7 @@ pub(crate) fn toggle( checked: bool, disabled: bool, set: fn(&mut S, bool), - cx: &mut Context, + cx: &Context, ) -> Switch { Switch::new(id) .checked(checked) diff --git a/crates/agent-settings-ui/src/lib.rs b/crates/agent-settings-ui/src/lib.rs index b89afc4d..81042e84 100644 --- a/crates/agent-settings-ui/src/lib.rs +++ b/crates/agent-settings-ui/src/lib.rs @@ -16,6 +16,7 @@ mod agents; mod controls; mod field; +mod listing; mod render; use gpui_kit::Entity; use gpui_kit::component::input::InputState; @@ -28,6 +29,7 @@ struct AiPage { expanded: BTreeSet, /// Agents with fields, in display order. agents: Vec, + list: listing::AgentList, new_id: Option>, new_command: Option>, add_error: Option, @@ -60,6 +62,7 @@ pub fn settings_page( cx.new(|cx| AgentSettingsPage::new(settings, agents, probe, context, window, cx)) }) .with_icon(nocterm_ui::IconName::Bot) + .with_viewport() } struct AgentSettingsPage { settings: SettingsHandle, @@ -91,12 +94,13 @@ impl AgentSettingsPage { let _ = original_window.update(cx, |_, window, cx| { let _ = weak.update(cx, |this, cx| { agents::sync(this, window, cx); + this.ai.list.remeasure(); cx.notify(); }); }); }); let mut this = Self { - ai: AiPage::new(probe), + ai: AiPage::new(probe, cx), settings, agents, fields: BTreeMap::new(), diff --git a/crates/agent-settings-ui/src/listing.rs b/crates/agent-settings-ui/src/listing.rs new file mode 100644 index 00000000..989da450 --- /dev/null +++ b/crates/agent-settings-ui/src/listing.rs @@ -0,0 +1,100 @@ +//! The settings page's variable-height scroll and stable row focus identities. +use gpui_kit::{App, FocusHandle, ListAlignment, ListOffset, ListState, prelude::*, px}; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) struct AgentList { + scroll: ListState, + header: FocusHandle, + footer: FocusHandle, + rows: BTreeMap, +} + +impl AgentList { + pub(super) fn new(cx: &mut App) -> Self { + let header = cx.focus_handle(); + let footer = cx.focus_handle(); + let scroll = ListState::new(0, ListAlignment::Top, px(96.)); + scroll.splice_focusable(0..0, [Some(header.clone()), Some(footer.clone())]); + Self { + scroll, + header, + footer, + rows: BTreeMap::new(), + } + } + + pub(super) fn scroll(&self) -> ListState { + self.scroll.clone() + } + + /// Match the original overflow container's line height and horizontal-wheel fallback. + pub(super) fn wheel_scroll(&self) -> impl IntoElement + use<> { + nocterm_ui::form::list_wheel_overlay(self.scroll.clone()) + } + + pub(super) fn focus(&self, index: usize, ids: &[String]) -> &FocusHandle { + match index { + 0 => &self.header, + i if i == ids.len() + 1 => &self.footer, + i => &self.rows[&ids[i - 1]], + } + } + + /// Preserve stable focus handles and measured prefix/suffix rows on membership changes. + pub(super) fn replace( + &mut self, + old: &[String], + new: &[String], + present: &BTreeSet<&str>, + cx: &mut App, + ) { + let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count(); + let suffix = old[prefix..] + .iter() + .rev() + .zip(new[prefix..].iter().rev()) + .take_while(|(a, b)| a == b) + .count(); + let old_end = old.len() - suffix; + let new_end = new.len() - suffix; + for id in &new[prefix..new_end] { + if !self.rows.contains_key(id) { + self.rows.insert(id.clone(), cx.focus_handle()); + } + } + let changed = prefix + 1..old_end + 1; + let anchor = self.scroll.logical_scroll_top(); + let retained_anchor = if changed.contains(&anchor.item_ix) { + let id = &old[anchor.item_ix - 1]; + new.iter().position(|current| current == id) + } else { + None + }; + self.scroll.splice_focusable( + changed, + new[prefix..new_end] + .iter() + .map(|id| Some(self.rows[id].clone())), + ); + // The hint is only an estimate. The list replaces it with actual sizes + // as rows are measured, including expanded fields and diagnostics. + self.scroll.clone().with_uniform_item_height(px(48.)); + if let Some(index) = retained_anchor { + self.scroll.scroll_to(ListOffset { + item_ix: index + 1, + offset_in_item: anchor.offset_in_item, + }); + } + self.rows.retain(|id, _| present.contains(id.as_str())); + } + + pub(super) fn remeasure_agent(&self, id: &str, ids: &[String]) { + if let Some(index) = ids.iter().position(|current| current == id) { + self.scroll.remeasure_items(index + 1..index + 2); + } + } + + pub(super) fn remeasure(&self) { + self.scroll.remeasure_items(0..self.scroll.item_count()); + } +} diff --git a/crates/agent-settings-ui/src/render.rs b/crates/agent-settings-ui/src/render.rs index 88f197b8..feb249c4 100644 --- a/crates/agent-settings-ui/src/render.rs +++ b/crates/agent-settings-ui/src/render.rs @@ -2,7 +2,7 @@ //! agents themselves. use super::{ AgentSettingsPage, - agents::{edit_agent, save_checked}, + agents::{edit_agent, ensure_agent_fields, save_checked}, controls::{text_row, toggle}, field::{FieldError, optional}, }; @@ -15,46 +15,84 @@ use gpui_kit::{ input::Input, v_flex, }, - div, + div, list, prelude::*, + px, }; use nocterm_ai::{ AgentCatalog, AgentServerSettings, AiSettings, ApprovalPolicy, SandboxMode, agents::AgentProfile, sandbox::Availability, validate_agent, }; -use nocterm_ui::{IconName, form}; -pub(super) fn render( - view: &mut AgentSettingsPage, - cx: &mut Context, +use nocterm_ui::{IconName, PickerOption, form, open_choice_picker}; +pub(super) fn render(view: &AgentSettingsPage, cx: &Context) -> AnyElement { + div() + .id("ai-settings-list") + .test_support() + .size_full() + .min_h_0() + .relative() + .child( + list( + view.ai.list.scroll(), + cx.processor(|this, index, _, cx| render_item(this, index, cx)), + ) + .size_full(), + ) + .child(view.ai.list.wheel_scroll()) + .into_any_element() +} + +fn render_item( + view: &AgentSettingsPage, + index: usize, + cx: &Context, ) -> AnyElement { - let ai = view.settings().setting::(cx).clone(); + let ai = view.settings().setting::(cx); let off = !ai.enabled; + let content = match index { + 0 => general(view, ai, off, cx), + i if i == view.ai.agents.len() + 1 => add_agent(view, off, cx), + i => agent(view, &view.ai.agents[i - 1], ai, off, cx), + }; + div() + .w_full() + .track_focus(view.ai.list.focus(index, &view.ai.agents)) + .when(index > 1, |row| { + row.border_t_1() + .border_color(cx.theme().border.opacity(0.5)) + }) + .child(content) + .into_any_element() +} + +fn general( + view: &AgentSettingsPage, + ai: &AiSettings, + off: bool, + cx: &Context, +) -> AnyElement { let available = view.agents().available(cx); - let mut page = v_flex() + v_flex() .w_full() .child(form::page_header( "AI agents", Some("Chat with coding agents about your terminals. Agents run on this computer as your user.".into()), cx, )) - .child(general_section(view, &ai, off, cx)) - .child(permissions_section(&ai, off, cx)) - .child(terminal_access_section(&ai, off, cx)) - .child(form::section("Isolation", [isolation(view, &ai, off, cx)], cx)) - .when_some(view.ai.error.clone(), |page, error| page.child(form::error_text(error, cx))); - let mut agents: Vec = Vec::new(); - for id in view.ai.agents.clone() { - agents.push(agent(view, &id, &ai, &available, off, cx)); - } - agents.push(add_agent(view, off, cx)); - page = page.child(form::section("Agents", agents, cx)); - page.into_any_element() + .child(general_section(view, ai, &available, off, cx)) + .child(permissions_section(ai, off, cx)) + .child(terminal_access_section(ai, off, cx)) + .child(form::section("Isolation", [isolation(view, ai, off, cx)], cx)) + .when_some(view.ai.error.clone(), |page, error| page.child(form::error_text(error, cx))) + .child(form::section("Agents", [], cx)) + .into_any_element() } fn general_section( view: &AgentSettingsPage, ai: &AiSettings, + available: &nocterm_ai::AvailableAgents, off: bool, - cx: &mut Context, + cx: &Context, ) -> AnyElement { form::section( "General", @@ -74,7 +112,7 @@ fn general_section( form::row( "Default agent", "The agent a new chat starts with.", - default_agent(view, ai, off, cx), + default_agent(ai, available, off, cx), cx, ), text_row( @@ -88,11 +126,7 @@ fn general_section( cx, ) } -fn permissions_section( - ai: &AiSettings, - off: bool, - cx: &mut Context, -) -> AnyElement { +fn permissions_section(ai: &AiSettings, off: bool, cx: &Context) -> AnyElement { form::section( "Agent permissions", [form::row( @@ -113,7 +147,7 @@ fn permissions_section( fn terminal_access_section( ai: &AiSettings, off: bool, - cx: &mut Context, + cx: &Context, ) -> AnyElement { form::section( "Terminal access", @@ -168,16 +202,19 @@ fn policy(ask: bool) -> ApprovalPolicy { } fn default_agent( - view: &AgentSettingsPage, ai: &AiSettings, + agents: &nocterm_ai::AvailableAgents, disabled: bool, - cx: &mut Context, + cx: &Context, ) -> AnyElement { - let agents = view.agents().available(cx); let current = ai .default_agent .clone() .filter(|id| agents.get(id).is_some()); + // Match the shared settings convention: at most four inline choices. + if agents.iter().nth(3).is_some() { + return default_agent_picker(agents, current.as_deref(), disabled, cx); + } let options = std::iter::once((None, SharedString::from("Ask"), None)) .chain(agents.iter().map(|agent| { ( @@ -212,11 +249,66 @@ fn default_agent( .into_any_element() } +fn default_agent_picker( + agents: &nocterm_ai::AvailableAgents, + current: Option<&str>, + disabled: bool, + cx: &Context, +) -> AnyElement { + let selected = current.and_then(|id| agents.get(id)); + Button::new("ai-default-agent-choose") + .small() + .outline() + .max_w(px(220.)) + .label(selected.map_or("Ask", |agent| agent.name()).to_owned()) + .dropdown_caret(true) + .disabled(disabled) + .on_click(cx.listener(|this, _, window, cx| { + let ai = this.settings().setting::(cx); + if !ai.enabled { + return; + } + let agents = this.agents().available(cx); + let current = ai + .default_agent + .as_deref() + .filter(|id| agents.get(id).is_some()); + let options = std::iter::once(PickerOption::new("Ask", current.is_none(), None)) + .chain(agents.iter().map(|agent| { + PickerOption::new( + agent.name(), + current == Some(agent.id()), + Some(agent.id().to_owned()), + ) + })) + .collect(); + let page = cx.weak_entity(); + open_choice_picker( + "Choose an agent…", + options, + move |id, _, cx| { + let _ = page.update(cx, |this, cx| { + if this.settings().setting::(cx).enabled + && id + .as_deref() + .is_none_or(|id| this.agents().get(id, cx).is_some()) + { + this.save(move |s: &mut AiSettings| s.default_agent = id, cx); + } + }); + }, + window, + cx, + ); + })) + .into_any_element() +} + fn isolation( view: &AgentSettingsPage, ai: &AiSettings, off: bool, - cx: &mut Context, + cx: &Context, ) -> AnyElement { let on = ai.sandbox == SandboxMode::Workspace; let (available, status) = match view.ai.sandbox.clone().unwrap_or(Availability::Unsupported) { @@ -253,39 +345,42 @@ fn agent( view: &AgentSettingsPage, id: &str, ai: &AiSettings, - available: &nocterm_ai::AvailableAgents, off: bool, - cx: &mut Context, + cx: &Context, ) -> AnyElement { let mut block = v_flex() .w_full() - .child(agent_heading(view, id, ai, available, off, cx)); + .child(agent_heading(view, id, ai, off, cx)); if view.ai.expanded.contains(id) { block = block.child(agent_details(view, id, cx)); } block.into_any_element() } fn agent_label(catalog: &AgentCatalog, id: &str, ai: &AiSettings) -> (String, String, bool) { - let setting = ai.agents.get(id).cloned().unwrap_or_default(); + let setting = ai.agents.get(id); let default = catalog.get(id); let name = setting - .name - .clone() + .and_then(|setting| setting.name.clone()) .or_else(|| default.map(|profile| profile.name().to_owned())) .unwrap_or_else(|| id.to_owned()); let description = match default.map(AgentProfile::launch_defaults) { Some(launch) => format!("{} {}", launch.command(), launch.args().join(" ")), - None => setting.command.clone().unwrap_or_default(), + None => setting + .and_then(|setting| setting.command.clone()) + .unwrap_or_default(), }; - (name, description, setting.enabled) + ( + name, + description, + setting.is_none_or(|setting| setting.enabled), + ) } fn agent_heading( view: &AgentSettingsPage, id: &str, ai: &AiSettings, - available: &nocterm_ai::AvailableAgents, off: bool, - cx: &mut Context, + cx: &Context, ) -> AnyElement { let (name, description, enabled) = agent_label(view.agents().catalog(), id, ai); let expanded = view.ai.expanded.contains(id); @@ -312,7 +407,7 @@ fn agent_heading( .small() .text_color(cx.theme().muted_foreground), ) - .child(agent_icon(view.agents().profile_in(available, id)).small()) + .child(agent_icon(view.agents().profile(id, cx)).small()) .child(div().text_sm().font_medium().child(name)) .child( div() @@ -321,10 +416,12 @@ fn agent_heading( .truncate() .child(description), ) - .on_click(cx.listener(move |this, _, _, cx| { + .on_click(cx.listener(move |this, _, window, cx| { if !this.ai.expanded.remove(&toggle_id) { + ensure_agent_fields(this, &toggle_id, window, cx); this.ai.expanded.insert(toggle_id.clone()); } + this.ai.list.remeasure_agent(&toggle_id, &this.ai.agents); cx.notify(); })), ) @@ -355,7 +452,7 @@ fn agent_heading( fn agent_details( view: &AgentSettingsPage, id: &str, - cx: &mut Context, + cx: &Context, ) -> AnyElement { let default = view.agents().catalog().get(id); let key = |name: &str| format!("agent.{id}.{name}"); @@ -402,11 +499,7 @@ fn agent_details( details.into_any_element() } -fn add_agent( - view: &AgentSettingsPage, - off: bool, - cx: &mut Context, -) -> AnyElement { +fn add_agent(view: &AgentSettingsPage, off: bool, cx: &Context) -> AnyElement { let (Some(id), Some(command)) = (view.ai.new_id.clone(), view.ai.new_command.clone()) else { return div().into_any_element(); }; diff --git a/crates/agent-storage/src/catalog.rs b/crates/agent-storage/src/catalog.rs index 4778973a..ecdea19b 100644 --- a/crates/agent-storage/src/catalog.rs +++ b/crates/agent-storage/src/catalog.rs @@ -70,9 +70,16 @@ fn scan( let Ok(Some(row)) = summary(partition, id) else { continue; }; - rows.push(row); - rows.sort_by_key(|row| std::cmp::Reverse((row.pinned, row.updated))); - rows.truncate(MAX_RESTORED); + let rank = (row.pinned, row.updated); + // Insert after equal ranks to preserve discovery order at the cutoff. + let position = rows.partition_point(|row| (row.pinned, row.updated) >= rank); + if position == MAX_RESTORED { + continue; + } + if rows.len() == MAX_RESTORED { + rows.pop(); + } + rows.insert(position, row); } Ok(()) } diff --git a/crates/agent-storage/tests/catalog.rs b/crates/agent-storage/tests/catalog.rs new file mode 100644 index 00000000..57d2e1b6 --- /dev/null +++ b/crates/agent-storage/tests/catalog.rs @@ -0,0 +1,161 @@ +use futures::executor::block_on; +use nocterm_agent_storage::FileChatRepository; +use nocterm_ai::{ + history::{self, ChatSummary, ContextId, SavedChat, TranscriptVersion}, + local_environment::LocalEnvironment, + storage::ChatRepository as _, +}; +use nocterm_session::testing::InMemoryFs; +use std::{ + io::Write as _, + path::{Path, PathBuf}, + sync::Arc, + time::Instant, +}; + +struct CatalogFixture { + _root: tempfile::TempDir, + partitions: [PathBuf; 3], + fs: Arc, + repository: FileChatRepository, +} + +impl CatalogFixture { + fn new() -> Self { + let root = tempfile::tempdir().unwrap(); + let path = root.path().canonicalize().unwrap(); + let partitions = [ + path.clone(), + path.join("scoped-v2/general"), + path.join("scoped-v3") + .join(LocalEnvironment::ThisComputer.storage_key()) + .join("general"), + ]; + let fs = Arc::new(InMemoryFs::default()); + for partition in &partitions { + seed_parents(&fs, partition); + } + let repository = FileChatRepository::new(path, fs.clone()); + Self { + _root: root, + partitions, + fs, + repository, + } + } + + fn seed(&self, version: u32, index: usize, pinned: bool, updated: u64) { + let mut chat = SavedChat::for_identity("agent".into(), chat_id(index), updated); + chat.version = version; + chat.header.name = Some("Catalog test chat".into()); + chat.header.pinned = pinned; + self.seed_bytes(version, index, history::encode(&chat).unwrap()); + } + + fn seed_bytes(&self, version: u32, index: usize, bytes: Vec) { + self.fs + .seed_native_file( + &self.partitions[version as usize - 1].join(format!("{}.json", chat_id(index))), + bytes, + ) + .unwrap(); + } + + fn seed_current_chats(&self, count: usize) { + for index in 0..count { + let (pinned, updated) = rank(index); + self.seed( + TranscriptVersion::ENVIRONMENT.wire(), + index, + pinned, + updated, + ); + } + } + + fn catalog(&self) -> Vec { + block_on(self.repository.catalog(ContextId::General)).unwrap() + } +} + +fn seed_parents(fs: &InMemoryFs, path: &Path) { + let parents: Vec<_> = path.ancestors().collect(); + for parent in parents.into_iter().rev() { + fs.seed_native_directory(parent).unwrap(); + } +} + +fn chat_id(index: usize) -> String { + format!("00000000-0000-4000-8000-{index:012x}") +} + +fn rank(index: usize) -> (bool, u64) { + (index.is_multiple_of(17), (index * 97 % 113) as u64) +} + +#[test] +fn catalog_keeps_the_best_rows_and_leaves_equal_ranks_in_discovery_order() { + let fixture = CatalogFixture::new(); + let limit = history::MAX_RESTORED; + let count = 3 * limit + 2; + fixture.seed_current_chats(count); + let mut expected: Vec<_> = (0..count).collect(); + // InMemoryFs lists child names in lexical order, which matches the numeric + // fixture IDs. Stable sorting retains the order of those names on rank ties. + expected.sort_by_key(|index| std::cmp::Reverse(rank(*index))); + assert_eq!(rank(expected[limit - 1]), rank(expected[limit])); + let rows = fixture.catalog(); + assert_eq!(rows.len(), limit); + for (row, index) in rows.iter().zip(expected) { + assert_eq!(row.id, chat_id(index)); + assert_eq!((row.pinned, row.updated), rank(index)); + } +} + +#[test] +fn catalog_retains_preferred_partition_order_and_damaged_records_still_shadow() { + let fixture = CatalogFixture::new(); + fixture.seed(1, 1, true, 100); + fixture.seed(2, 2, true, 100); + fixture.seed(3, 3, true, 100); + fixture.seed(1, 4, true, 150); + fixture.seed(2, 4, true, 200); + fixture.seed_bytes(3, 4, b"invalid transcript".to_vec()); + fixture.seed(2, 5, true, 300); + fixture.seed(3, 5, false, 0); + + assert_eq!( + fixture + .catalog() + .into_iter() + .map(|row| row.id) + .collect::>(), + [3, 2, 1, 5].map(chat_id) + ); +} + +#[test] +#[ignore = "manual release benchmark; compare samples on the same host and profile"] +fn catalog_scan_benchmark() { + let mut output = std::io::stdout().lock(); + for count in [200, 2_000, 10_000] { + let fixture = CatalogFixture::new(); + fixture.seed_current_chats(count); + let expected = fixture.catalog(); + assert_eq!(expected.len(), history::MAX_RESTORED.min(count)); + let mut timings = [0.0; 9]; + for sample in &mut timings { + let started = Instant::now(); + let catalog = fixture.catalog(); + *sample = started.elapsed().as_secs_f64() * 1_000.0; + assert_eq!(catalog, expected); + } + timings.sort_by(f64::total_cmp); + writeln!( + output, + "{count} transcripts: median {:.3} ms, range {:.3}–{:.3} ms", + timings[4], timings[0], timings[8] + ) + .unwrap(); + } +} diff --git a/crates/agent-tools/src/jobs.rs b/crates/agent-tools/src/jobs.rs index f36d627e..63a5a90f 100644 --- a/crates/agent-tools/src/jobs.rs +++ b/crates/agent-tools/src/jobs.rs @@ -28,6 +28,13 @@ struct Job { cancel: async_channel::Sender<()>, } impl Job { + fn is_active(&self) -> bool { + self.snapshot + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .active() + } + fn snapshot(&self) -> Snapshot { self.snapshot .lock() @@ -75,20 +82,14 @@ impl Jobs { terminal_id: String, executor: Arc, ) -> Result<(String, Arc>, async_channel::Receiver<()>), JobError> { - if self - .jobs - .values() - .filter(|job| job.snapshot().active()) - .count() - >= MAX_ACTIVE - { + if self.jobs.values().filter(|job| job.is_active()).count() >= MAX_ACTIVE { return Err(JobError::Busy); } while self.jobs.len() >= MAX_RETAINED { let oldest = self .jobs .iter() - .find(|(_, job)| !job.snapshot().active()) + .find(|(_, job)| !job.is_active()) .map(|(id, _)| *id); if let Some(oldest) = oldest { self.jobs.remove(&oldest); @@ -130,7 +131,7 @@ impl Jobs { fn active(&self) -> impl Iterator)> { self.jobs .values() - .filter(|job| job.snapshot().active()) + .filter(|job| job.is_active()) .map(|job| (job.terminal_id.as_str(), &job.executor)) } } diff --git a/crates/agent-tools/tests/command_lifecycle.rs b/crates/agent-tools/tests/command_lifecycle.rs index ec989532..df031c56 100644 --- a/crates/agent-tools/tests/command_lifecycle.rs +++ b/crates/agent-tools/tests/command_lifecycle.rs @@ -329,3 +329,57 @@ fn dropping_the_registry_cancels_a_runner_even_when_its_read_waiter_is_gone() { assert!(sink.is_closed()); }); } + +#[test] +#[ignore = "manual release timing of command status with retained output"] +fn measure_command_activity_with_retained_output() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + futures::executor::block_on(async { + for size in [0, 4096, 65536] { + let stdout = "x".repeat(size); + let stderr = "e".repeat(size / 16); + let executor: Arc = Arc::new(FakeExec::new(vec![( + "program", + Ok((stdout.as_str(), 0, stderr.as_str())), + )])); + let mut jobs = JobsFactory.create(); + let mut oldest_id = None; + for _ in 0..15 { + let (id, run) = start(&mut *jobs, executor.clone(), "t"); + run.await; + oldest_id.get_or_insert(id); + } + let (last_id, run) = start(&mut *jobs, executor.clone(), "t"); + run.await; + let (active_id, active) = start(&mut *jobs, executor.clone(), "t"); + let current = [("t".to_string(), Some(executor.clone()))]; + assert!(matches!( + jobs.snapshot(&oldest_id.unwrap(), "t"), + Err(JobError::Unknown) + )); + + let start = Instant::now(); + let repetitions = 4_000; + for _ in 0..repetitions { + assert!(black_box(&jobs).has_active()); + jobs.revoke_replaced(black_box(¤t)); + } + let ns = start.elapsed().as_nanos() / repetitions; + writeln!( + std::io::stdout().lock(), + "{size} stdout bytes per command, {ns} ns per activity and revocation pair" + ) + .unwrap(); + + let retained = jobs.snapshot(&last_id, "t").unwrap(); + assert_eq!(retained.state(), CommandState::Exited); + assert_eq!(retained.stdout(), stdout.as_bytes()); + assert_eq!(retained.exit().unwrap().stderr.as_str(), stderr); + assert!(jobs.snapshot(&active_id, "t").unwrap().active()); + jobs.cancel(&active_id, "t").unwrap(); + active.await; + assert!(!jobs.has_active()); + } + }); +} diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml index 16629604..2096a3d9 100644 --- a/crates/agent/Cargo.toml +++ b/crates/agent/Cargo.toml @@ -42,14 +42,15 @@ gpui-kit = { workspace = true, features = [ "tree-sitter-yaml", ] } futures.workspace = true -async-channel.workspace = true serde_json.workspace = true base64.workspace = true -chrono = { version = "0.4", default-features = false, features = ["clock"] } +image = { version = "0.25", default-features = false } +jiff = "1.1" thiserror.workspace = true tracing.workspace = true [dev-dependencies] +async-channel.workspace = true nocterm-hubs-model = { workspace = true, features = ["test-support"] } nocterm-workspace-ports.workspace = true nocterm-workspace = { workspace = true, features = ["test-support"] } diff --git a/crates/agent/src/image_deps.rs b/crates/agent/src/image_deps.rs index ddb44c3f..8af9b064 100644 --- a/crates/agent/src/image_deps.rs +++ b/crates/agent/src/image_deps.rs @@ -1,31 +1,24 @@ //! Explicit codec dependencies supplied by application composition. use nocterm_ai::images::{ImageInspector, ImageThumbnailer}; use std::sync::Arc; +mod work_budget; + +use work_budget::{ImageWorkBudget, Work}; +pub(crate) use work_budget::{ImageWorkPermit, ImageWorkReservation}; + #[derive(Clone)] pub struct ImageDeps { inspector: Arc, thumbnailer: Arc, - available: async_channel::Receiver<()>, - returned: async_channel::Sender<()>, -} -/// Retained by the actual background work, including after a panel disappears. -pub(crate) struct ImageWorkPermit(async_channel::Sender<()>); -impl Drop for ImageWorkPermit { - fn drop(&mut self) { - let _ = self.0.try_send(()); - } + work: Arc, } + impl ImageDeps { pub fn new(inspector: Arc, thumbnailer: Arc) -> Self { - let (returned, available) = async_channel::bounded(4); - for _ in 0..4 { - returned.try_send(()).expect("new image work slots"); - } Self { inspector, thumbnailer, - available, - returned, + work: Arc::new(ImageWorkBudget::default()), } } pub(crate) fn inspector(&self) -> Arc { @@ -34,16 +27,22 @@ impl ImageDeps { pub(crate) fn thumbnailer(&self) -> Arc { self.thumbnailer.clone() } + #[cfg(test)] pub(crate) fn admit_work(&self) -> Option { - self.available.try_recv().ok()?; - Some(ImageWorkPermit(self.returned.clone())) + self.work.try_start() + } + pub(crate) fn reserve_attachment(&self) -> Option { + self.work.reserve(Work::Attachment) + } + pub(crate) fn reserve_edit(&self) -> ImageWorkReservation { + self.work + .reserve(Work::QueueEdit) + .expect("queue edits retain shared prompts") } - pub(crate) fn work(&self) -> futures::future::BoxFuture<'static, ImageWorkPermit> { - let (available, returned) = (self.available.clone(), self.returned.clone()); - Box::pin(async move { - available.recv().await.expect("retained image work slots"); - ImageWorkPermit(returned) - }) + pub(crate) fn reserve_preview(&self) -> ImageWorkReservation { + self.work + .reserve(Work::Preview) + .expect("preview jobs are bounded by the preview cache") } } @@ -70,10 +69,10 @@ mod tests { .map(|_| deps.admit_work().unwrap()) .collect::>(); futures::executor::block_on(async { - let mut cancelled = deps.work(); + let mut cancelled = Box::pin(deps.reserve_preview().acquire()); assert!(futures::poll!(&mut cancelled).is_pending()); drop(cancelled); - let mut waiting = deps.work(); + let mut waiting = std::pin::pin!(deps.reserve_preview().acquire()); assert!(futures::poll!(&mut waiting).is_pending()); permits.pop(); let released = waiting.await; @@ -82,4 +81,56 @@ mod tests { assert!(deps.admit_work().is_some()); }); } + + #[test] + fn attachments_and_queue_edits_receive_slots_before_queued_previews() { + let codec = Arc::new(nocterm_ai::testing::ScriptedImageCodec::default()); + let deps = ImageDeps::new(codec.clone(), codec); + let mut active = (0..4) + .map(|_| deps.admit_work().unwrap()) + .collect::>(); + let mut preview = std::pin::pin!(deps.reserve_preview().acquire()); + let attachment = deps.reserve_attachment().unwrap(); + let edit = deps.reserve_edit(); + + futures::executor::block_on(async { + let mut attached = std::pin::pin!(attachment.acquire()); + let mut edited = std::pin::pin!(edit.acquire()); + assert!(futures::poll!(&mut attached).is_pending()); + drop(active.pop()); + assert!(futures::poll!(&mut edited).is_pending()); + assert!(futures::poll!(&mut preview).is_pending()); + drop(attached.await); + assert!(futures::poll!(&mut preview).is_pending()); + drop(edited.await); + let _preview = preview.await; + assert!(deps.admit_work().is_none()); + }); + } + + #[test] + fn cancelled_attachments_release_backlog_space_and_unclaimed_grants() { + let codec = Arc::new(nocterm_ai::testing::ScriptedImageCodec::default()); + let deps = ImageDeps::new(codec.clone(), codec); + let mut active = (0..4) + .map(|_| deps.admit_work().unwrap()) + .collect::>(); + let mut waiting = (0..4) + .map(|_| deps.reserve_attachment().unwrap()) + .collect::>(); + assert!(deps.reserve_attachment().is_none()); + drop(waiting.pop_front()); + waiting.push_back(deps.reserve_attachment().unwrap()); + assert!(deps.reserve_attachment().is_none()); + + drop(active.pop()); + assert!(deps.admit_work().is_none()); + drop(waiting.pop_front()); + futures::executor::block_on(async { + let mut next = std::pin::pin!(waiting.pop_front().unwrap().acquire()); + assert!(futures::poll!(&mut next).is_ready()); + }); + drop(waiting); + assert!(deps.admit_work().is_some()); + } } diff --git a/crates/agent/src/image_deps/work_budget.rs b/crates/agent/src/image_deps/work_budget.rs new file mode 100644 index 00000000..7d614ba2 --- /dev/null +++ b/crates/agent/src/image_deps/work_budget.rs @@ -0,0 +1,163 @@ +//! Shared admission for physical image work across an Agent installation. +use futures::channel::oneshot; +use std::{ + collections::VecDeque, + sync::{Arc, Mutex}, +}; + +const ACTIVE_LIMIT: usize = 4; +const WAITING_ATTACHMENTS: usize = 4; + +type WaitQueue = VecDeque>; + +#[derive(Default)] +pub(super) struct ImageWorkBudget(Mutex); + +#[derive(Default)] +struct Slots { + active: usize, + attachments: usize, + interactive: WaitQueue, + previews: WaitQueue, +} + +#[derive(Clone, Copy)] +pub(super) enum Work { + Attachment, + QueueEdit, + Preview, +} + +impl Work { + fn queue(self, slots: &mut Slots) -> &mut WaitQueue { + match self { + Self::Attachment | Self::QueueEdit => &mut slots.interactive, + Self::Preview => &mut slots.previews, + } + } +} + +/// A granted slot is counted even when its receiver has yet to resume. +pub(crate) struct ImageWorkPermit(Option>); + +pub(crate) struct ImageWorkReservation(Reservation); + +enum Reservation { + Ready(ImageWorkPermit), + Waiting(Waiting), +} + +struct Waiting { + budget: Arc, + work: Work, + receiver: Option>, +} + +impl ImageWorkBudget { + fn lock(&self) -> std::sync::MutexGuard<'_, Slots> { + self.0.lock().unwrap_or_else(|error| error.into_inner()) + } + + pub(super) fn reserve(self: &Arc, work: Work) -> Option { + let mut slots = self.lock(); + if let Some(permit) = self.start(&mut slots) { + return Some(ImageWorkReservation(Reservation::Ready(permit))); + } + // Only direct attachments can retain a new owned picker or paste payload. + // Queue edits already hold a shared saved prompt in a cancellable view task. + if matches!(work, Work::Attachment) { + if slots.attachments >= WAITING_ATTACHMENTS { + return None; + } + slots.attachments += 1; + } + let (sender, receiver) = oneshot::channel(); + work.queue(&mut slots).push_back(sender); + Some(ImageWorkReservation(Reservation::Waiting(Waiting { + budget: Arc::clone(self), + work, + receiver: Some(receiver), + }))) + } + + fn start(self: &Arc, slots: &mut Slots) -> Option { + if slots.active == ACTIVE_LIMIT { + return None; + } + slots.active += 1; + Some(ImageWorkPermit(Some(Arc::clone(self)))) + } + + #[cfg(test)] + pub(super) fn try_start(self: &Arc) -> Option { + self.start(&mut self.lock()) + } + + fn next_waiter(&self) -> Option> { + let mut slots = self.lock(); + let next = slots + .interactive + .pop_front() + .or_else(|| slots.previews.pop_front()); + if next.is_none() { + slots.active -= 1; + } + next + } +} + +impl ImageWorkReservation { + pub(crate) async fn acquire(self) -> ImageWorkPermit { + match self.0 { + Reservation::Ready(permit) => permit, + Reservation::Waiting(mut waiting) => { + let permit = waiting + .receiver + .as_mut() + .expect("waiting reservation owns its receiver") + .await + .expect("a reservation retains the image work budget"); + waiting.receiver = None; + permit + } + } + } +} + +impl Drop for Waiting { + fn drop(&mut self) { + let cancelled = self.receiver.is_some(); + let attachment = matches!(self.work, Work::Attachment); + if !cancelled && !attachment { + return; + } + // A dropped receiver can own an already dispatched permit. Release it before + // locking so it can hand the same slot to the next waiter. + drop(self.receiver.take()); + let mut slots = self.budget.lock(); + if attachment { + slots.attachments -= 1; + } + if cancelled { + self.work + .queue(&mut slots) + .retain(|sender| !sender.is_canceled()); + } + } +} + +impl Drop for ImageWorkPermit { + fn drop(&mut self) { + let Some(budget) = self.0.take() else { + return; + }; + while let Some(sender) = budget.next_waiter() { + // Transfer the active slot even if it is not picked up immediately. + if let Err(mut returned) = sender.send(Self(Some(Arc::clone(&budget)))) { + returned.0.take(); + } else { + return; + } + } + } +} diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs index c20afd05..620cfcd5 100644 --- a/crates/agent/src/lib.rs +++ b/crates/agent/src/lib.rs @@ -17,7 +17,9 @@ //! Owns: panel views and presentation state, the panel's ChatRoster, WorkspaceSeat (the //! ChatWorkspace over an original surface and exact ChatKey) and WorkspaceSignIn (the SignInTerminal over the //! host's TerminalAuthOpener). -//! Image previews retain immutable source identity with a 64 MiB source/PNG/RGBA budget and at most 32 cached entries. +//! Image previews reserve source identities without holding their encoded bytes after decoding. +//! The 64 MiB working and residency budget and 32-entry limit apply to the preview cache. +//! It releases rendered images on eviction. //! Preparation and preview decoding share four physical work permits across windows, retained through actual background work. //! Does not own: chats, sessions and tools (nocterm-agent-chat), ACP transport, connection //! admission, filesystem storage or image decoding. diff --git a/crates/agent/src/panel.rs b/crates/agent/src/panel.rs index ca9bbace..3860def9 100644 --- a/crates/agent/src/panel.rs +++ b/crates/agent/src/panel.rs @@ -102,6 +102,8 @@ impl AgentPanel { // and typing redraw only their regions instead of notifying the panel. cx.observe_self(|panel, cx| panel.layout.parts().invalidate(cx)) .detach(); + cx.on_release(|panel, cx| panel.messages.clear_previews(cx)) + .detach(); let panel = cx.weak_entity(); window.defer(cx, move |window, cx| { let _ = panel.update(cx, |panel, cx| panel.on_runtime_changed(window, cx)); @@ -375,12 +377,21 @@ impl AgentPanel { cx: &mut Context, ) { use nocterm_hub_agents::HubAgentsEvent; - match event { + let result = match event { HubAgentsEvent::ChatsChanged(hub) if Some(hub) == window_hub => { - self.host.runtime().reload_history(cx); + self.host.runtime().history_changed(cx) + } + HubAgentsEvent::ChatCatalogPublished(hub) if Some(hub) == window_hub => { + self.host.runtime().history_cache_changed(cx) + } + HubAgentsEvent::Changed(hub) if Some(hub) == window_hub => { + cx.notify(); + return; } - HubAgentsEvent::Changed(hub) if Some(hub) == window_hub => cx.notify(), - _ => {} + _ => return, + }; + if let Err(error) = result { + tracing::debug!(%error, "could not update hub history"); } } #[cfg(test)] @@ -421,6 +432,9 @@ impl AgentPanel { if let Some(width) = self.layout.set_history(open, chat, cx) { cx.emit(PanelRequest::Widen(width)); } + if !open && chat { + self.notices.cancel_redraw(); + } cx.notify(); } pub(super) fn render_split( @@ -441,30 +455,43 @@ impl AgentPanel { ) -> AnyElement { match kind { parts::PartKind::Transcript => self.render_transcript_part(cx), - parts::PartKind::History => { - let stamp = history::HistoryProjection::stamp(&self.chats, &self.history, cx); - self.layout.parts_mut().drew_history(stamp); - let hub_window = self - .host - .hub_agents() - .is_some_and(|access| access.hub().is_some()); - let history = history::HistoryProjection::render( - &self.chats, - &self.history, - (self.host.agents(), hub_window), - self.host.timestamp(), - cx, - ); - div() - .size_full() - .flex() - .flex_col() - .child(history) - .into_any_element() - } parts::PartKind::Footer => self.render_footer(window, cx), + parts::PartKind::Queue => self.render_queue_part(cx), } } + fn render_history( + &mut self, + viewport: &mut history::HistoryViewport, + cx: &mut Context, + ) -> AnyElement { + let hub_window = self + .host + .hub_agents() + .is_some_and(|access| access.hub().is_some()); + if viewport.needs_prepare(self.history.query_revision(cx)) { + let stamp = history::HistoryProjection::stamp(&self.chats, &self.history, cx); + self.layout.parts_mut().drew_history(stamp); + viewport.prepare( + &self.chats, + &self.history, + self.host.agents(), + hub_window, + cx, + ); + } + div() + .size_full() + .flex() + .flex_col() + .child(history::HistoryProjection::render( + viewport, + &self.history, + hub_window, + self.host.timestamp(), + cx, + )) + .into_any_element() + } fn toggle_history(&mut self, cx: &mut Context) { self.set_history(!self.layout.history(), cx); } diff --git a/crates/agent/src/panel/chat.rs b/crates/agent/src/panel/chat.rs index d0863e5f..7c06c137 100644 --- a/crates/agent/src/panel/chat.rs +++ b/crates/agent/src/panel/chat.rs @@ -7,6 +7,7 @@ use super::{ }; use gpui_kit::AnyElement; use nocterm_ai::usage::{Breakdown, RateLimit}; +use std::time::Duration; impl AgentPanel { /// The open chat's footer: approvals, status, queue, commands and the composer. @@ -22,7 +23,8 @@ impl AgentPanel { let approvals = self.render_approvals(&thread, window, cx); let status = self.chat_status(&thread, cx); let labels = attachments::AttachmentLabels::new(thread.read(cx).workspace_seat(), cx); - let queue = self.render_queue(&thread, &labels, cx); + let queue = + (!thread.read(cx).composer().queue().is_empty()).then(|| self.layout.parts().queue()); let commands = self.render_commands(window, cx); let composer = self.render_composer(&frame, &thread, &labels, cx); v_flex() @@ -35,6 +37,16 @@ impl AgentPanel { .child(composer) .into_any_element() } + pub(super) fn render_queue_part(&mut self, cx: &mut Context) -> AnyElement { + let Some(thread) = self.current() else { + return div().into_any_element(); + }; + let labels = attachments::AttachmentLabels::new(thread.read(cx).workspace_seat(), cx); + v_flex() + .w_full() + .children(self.render_queue(&thread, &labels, cx)) + .into_any_element() + } pub(super) fn sync_approval_attention(&mut self, window: &mut Window, cx: &mut Context) { let attention = self .chats @@ -169,15 +181,19 @@ impl AgentPanel { pub(super) fn on_reveal_tick( &mut self, binding: message_list::ActiveListBinding, + elapsed: Duration, cx: &mut Context, ) { let Some(thread) = self.messages.thread() else { return; }; let reduced = cx.reduce_motion(); - let changed = - self.messages - .advance_reveal(&binding, &thread.read(cx).transcript().entries, reduced); + let changed = self.messages.advance_reveal( + &binding, + &thread.read(cx).transcript().entries, + reduced, + elapsed, + ); if let Some(changed) = changed { self.messages.apply_reveal(changed, cx); // The reveal animates the transcript's rows only. @@ -188,15 +204,17 @@ impl AgentPanel { &mut self, binding: message_list::ActiveListBinding, ticket: image_pipeline::PreviewTicket, - row: Option, image: Option, cx: &mut Context, ) { - if self - .messages - .accept_preview(&binding, ticket, row, image, cx) - { - cx.notify(); + if let Some(regions) = self.messages.accept_preview(&binding, ticket, image, cx) { + let parts = self.layout.parts(); + if regions.transcript() { + parts.notify(parts::PartKind::Transcript, cx); + } + if regions.footer() { + parts.notify(parts::PartKind::Footer, cx); + } } } pub(super) fn on_message_expanded( @@ -282,8 +300,8 @@ impl AgentPanel { .and_then(|entry| { super::message_markdown::MessageMarkdown::text(entry, index, &self.messages) }); - if let Some((text, source_len)) = markdown { - self.messages.prepare_markdown(index, text, source_len, cx); + if let Some(update) = markdown { + self.messages.prepare_markdown(index, update, cx); } let state = thread.read(cx); let transcript = state.transcript(); @@ -294,6 +312,7 @@ impl AgentPanel { let frame = RowPresentation::new( identity, self.messages.binding(), + state.document().transcript_generation(), index, self.messages.expanded(index), entry_is_live( @@ -333,6 +352,7 @@ impl AgentPanel { let state = thread.read(cx); let rows = self.messages.observe_rows( thread.entity_id(), + state.document().transcript_generation(), &state.transcript().entries, dirty, state.session_generating(), diff --git a/crates/agent/src/panel/composer.rs b/crates/agent/src/panel/composer.rs index 3aee82bb..13043f36 100644 --- a/crates/agent/src/panel/composer.rs +++ b/crates/agent/src/panel/composer.rs @@ -1,7 +1,7 @@ use super::*; use super::{ commands::CommandOrigin, - images::ImageAttachError, + images::{ImageAttachError, PreparedImages}, menu::{ConfigurationSelection, FavoriteSelection, ModeSelection}, }; use crate::thread::Attachment; @@ -226,13 +226,12 @@ impl AgentPanel { } else { Vec::new() }; - let previews = - preview_operation::PreviewOperation::queued_previews(&mut self.messages, &prompts, cx); + let previews = preview_operation::PreviewOperation::queued_previews(&prompts, cx); queue::QueueRenderer::render_queue(&self.composer, prompts, previews, thread, labels, cx) } pub(super) fn prepare_images( &mut self, - work: impl std::future::Future, ImageAttachError>> + work: impl std::future::Future> + Send + 'static, cx: &mut Context, @@ -248,25 +247,32 @@ impl AgentPanel { { return; } - let Some(permit) = self.messages.admit_image_work() else { + let Some(reservation) = self.messages.image_deps().reserve_attachment() else { self.notices .set_error(Some(ImageAttachError::Busy.to_string())); cx.notify(); return; }; let binding = self.composer.prepare_images(thread.entity_id()); - cx.notify(); let ticket = thread.read(cx).session_ticket(); let owner = thread.downgrade(); - image_preparation::ImagePreparation::new(binding, owner, ticket, Box::pin(work), permit) - .launch(cx); + let task = image_preparation::ImagePreparation::new( + binding, + owner, + ticket, + Box::pin(work), + reservation, + ) + .launch(cx); + self.composer.install_image_preparation(task); + self.layout.parts().notify(parts::PartKind::Footer, cx); } pub(super) fn on_composer_images_prepared( &mut self, binding: composer_view::ComposerBinding, owner: gpui_kit::WeakEntity, ticket: nocterm_ai::session::Ticket, - result: Result, ImageAttachError>, + work: image_preparation::PreparedImageWork, cx: &mut Context, ) { let Some(thread) = owner.upgrade() else { @@ -280,38 +286,42 @@ impl AgentPanel { { return; } - thread.update(cx, |thread, cx| { + let preview = thread.update(cx, |thread, cx| { if !thread.session_request_current(ticket) { - return; - } - match result { - Ok(images) => { - let mut collection = thread.composer().images().to_vec(); - collection.extend(images); - if let Err(error) = thread.accept_composer_images(collection, cx) { - self.notices.set_error(Some(error.to_string())); - } - } - Err(error) => self.notices.set_error(Some(error.to_string())), + return Ok(None); } - cx.notify(); + let (result, permit) = work; + let (images, preview) = result.map_err(|error| error.to_string())?.into_parts(); + let mut collection = thread.composer().images().to_vec(); + collection.extend(images); + thread + .accept_composer_images(collection, cx) + .map_err(|error| error.to_string())?; + Ok(preview.map(|(source, preview)| (source, preview, permit))) }); - cx.notify(); + if let Ok(Some((source, preview, permit))) = preview { + preview_operation::PreviewOperation::from_decoded( + &mut self.messages, + &source, + preview, + permit, + cx, + ); + } else if let Err(error) = preview { + self.notices.set_error(Some(error)); + cx.notify(); + return; + } + self.layout.parts().notify(parts::PartKind::Footer, cx); } pub(super) fn add_image_bytes(&mut self, bytes: Vec, cx: &mut Context) { let Some(thread) = self.current() else { return; }; - let budget = nocterm_ai::images::ImageCollectionBudget::remaining( - thread.read(cx).composer().images(), - ); + let admitted = images::admit_paste(bytes, thread.read(cx).composer().images()); let inspector = self.messages.inspector(); self.prepare_images( - async move { - let mut budget = budget?; - budget.admit(bytes.len())?; - Ok(vec![PromptImage::validate(bytes, inspector.as_ref())?]) - }, + async move { PreparedImages::single(admitted?, inspector.as_ref()) }, cx, ); } @@ -319,12 +329,13 @@ impl AgentPanel { let Some(thread) = self.current() else { return; }; - let budget = nocterm_ai::images::ImageCollectionBudget::remaining( - thread.read(cx).composer().images(), - ); + let admitted = images::admit_paths(paths, thread.read(cx).composer().images()); let inspector = self.messages.inspector(); self.prepare_images( - async move { images::read_images(paths, inspector.as_ref(), budget?) }, + async move { + let (paths, budget) = admitted?; + images::read_images(paths, inspector.as_ref(), budget) + }, cx, ); } diff --git a/crates/agent/src/panel/composer_view.rs b/crates/agent/src/panel/composer_view.rs index 9caf03ec..f85549a8 100644 --- a/crates/agent/src/panel/composer_view.rs +++ b/crates/agent/src/panel/composer_view.rs @@ -69,7 +69,7 @@ struct ComposerState { edit: Option, loading: Option<(EntityId, String)>, revision: u64, - pending_images: usize, + image_preparation: Option>, } struct QueueEdit { chat: EntityId, @@ -168,7 +168,7 @@ impl ComposerView { .map(|edit| edit.id) } pub(super) fn preparing(&self) -> bool { - self.state.pending_images > 0 || self.preparing_edit() + self.state.image_preparation.is_some() || self.preparing_edit() } pub(super) fn preparing_edit(&self) -> bool { self.state.edit.as_ref().is_some_and(|edit| !edit.ready) @@ -184,7 +184,7 @@ impl ComposerView { } fn invalidate(&mut self) { self.state.revision = self.state.revision.wrapping_add(1); - self.state.pending_images = 0; + self.state.image_preparation = None; if let Some(binding) = &mut self.binding { binding.identity = Arc::new(()); } @@ -302,7 +302,7 @@ impl ComposerView { } } pub(super) fn prepare_images(&mut self, chat: EntityId) -> ComposerBinding { - let binding = match self.binding.as_ref().filter(|binding| binding.chat == chat) { + match self.binding.as_ref().filter(|binding| binding.chat == chat) { Some(binding) => binding.clone(), None => { let binding = ComposerBinding { @@ -312,16 +312,16 @@ impl ComposerView { self.binding = Some(binding.clone()); binding } - }; - self.state.pending_images += 1; - binding + } + } + pub(super) fn install_image_preparation(&mut self, task: Task<()>) { + self.state.image_preparation = Some(task); } pub(super) fn images_completed(&mut self, binding: &ComposerBinding) -> bool { if !self.current(binding) { return false; } - self.state.pending_images = self.state.pending_images.saturating_sub(1); - true + self.state.image_preparation.take().is_some() } pub(super) fn queue_open(&self) -> bool { self.queue_open diff --git a/crates/agent/src/panel/entries.rs b/crates/agent/src/panel/entries.rs index 79987f41..4bcc6d71 100644 --- a/crates/agent/src/panel/entries.rs +++ b/crates/agent/src/panel/entries.rs @@ -15,7 +15,7 @@ use nocterm_ui::IconName; use super::{ AgentPanel, image_pipeline::PreviewState, - message_actions::{MESSAGE_GROUP, escape_markdown, message_text}, + message_actions::{CopyExtent, MESSAGE_GROUP, MessageCopy, MessageRowActions, escape_markdown}, widgets::{chat_markdown, chat_markdown_in, disclosure_header, safe_markdown}, }; @@ -25,6 +25,8 @@ pub(super) enum PreviewError { Base64(#[from] base64::DecodeError), #[error("{0}")] Codec(#[from] nocterm_ai::images::ImageCodecError), + #[error("Could not decode the preview for rendering")] + Render(#[source] Box), } mod literal_viewport; pub(super) mod tool_input; @@ -33,6 +35,7 @@ pub(super) mod tool_output; pub(super) struct RowPresentation { chat: gpui_kit::EntityId, binding: Option, + generation: u64, index: usize, expanded: bool, live: bool, @@ -45,7 +48,7 @@ pub(super) struct EntryRenderer; impl EntryRenderer { pub(super) fn image(state: Option<&PreviewState>) -> gpui_kit::AnyElement { match state { - Some(PreviewState::Ready(image)) => img(image.clone()) + Some(PreviewState::Ready(image)) => img(image.rendered().clone()) .max_w_full() .h(rems(10.)) .into_any_element(), @@ -74,21 +77,12 @@ impl EntryRenderer { .text_sm(); let mut pending = Vec::new(); let row = match entry { - Entry::User(parts) => Self::user( - row, - &frame, - parts, - messages, - &mut pending, - message_text(entry).unwrap_or_default(), - cx, - ), + Entry::User(parts) => Self::user(row, &frame, parts, messages, &mut pending, cx), Entry::Agent(text) => Self::agent(row, &frame, text, messages, cx), Entry::Thought(text) => Self::thought(row, &frame, text, messages, cx), Entry::Tool(call) => Self::tool(row, &frame, call, cx), Entry::Content(Content::Image(image)) => { - let key = Self::pending_image(image, messages, &mut pending); - row.child(Self::image(messages.preview_state(&key))) + row.child(Self::pending_image(image, messages, &mut pending)) } Entry::Content(_) => row.child("Agent supplied additional content."), }; @@ -98,13 +92,13 @@ impl EntryRenderer { image: &nocterm_ai::model::content::Image, messages: &super::message_list::MessageList, pending: &mut Vec, - ) -> super::image_pipeline::ImageKey { + ) -> gpui_kit::AnyElement { let source = super::image_pipeline::PreviewSource::Encoded(image.data.clone()); - let key = source.key(); - if !messages.has_preview(&key) { + let state = messages.preview_state(&source.key()); + if matches!(state, None | Some(PreviewState::Loading(_))) { pending.push(source); } - key + Self::image(state) } fn user( mut row: gpui_kit::Stateful, @@ -112,7 +106,6 @@ impl EntryRenderer { parts: &[Content], messages: &super::message_list::MessageList, pending: &mut Vec, - text: String, cx: &Context, ) -> gpui_kit::Stateful { row = row.items_end().group(MESSAGE_GROUP); @@ -142,9 +135,8 @@ impl EntryRenderer { )); } Content::Image(image) => { - let key = Self::pending_image(image, messages, pending); has_images = true; - images = images.child(Self::image(messages.preview_state(&key))); + images = images.child(Self::pending_image(image, messages, pending)); } Content::ResourceReference(link) => { has_files = true; @@ -159,16 +151,8 @@ impl EntryRenderer { if has_files { bubble = bubble.child(files); } - row.child(bubble).child( - super::message_actions::MessageRowActions::new( - frame.can_fork.then_some(frame.chat), - frame.index, - text, - frame.time, - true, - ) - .render(cx), - ) + row.child(bubble) + .child(frame.actions(CopyExtent::UserParts(parts.len()), true, cx)) } /// A file the message carried: its name beside a paperclip. fn file(name: &str, cx: &Context) -> gpui_kit::Div { @@ -205,16 +189,7 @@ impl EntryRenderer { .group(MESSAGE_GROUP) .child(markdown.stream_fade(frame.generating || messages.revealing())); if !frame.live { - row = row.child( - super::message_actions::MessageRowActions::new( - frame.can_fork.then_some(frame.chat), - frame.index, - text.to_owned(), - frame.time, - false, - ) - .render(cx), - ); + row = row.child(frame.actions(CopyExtent::AgentBytes(text.len()), false, cx)); } row } @@ -324,6 +299,7 @@ impl RowPresentation { pub(super) fn new( chat: gpui_kit::EntityId, binding: Option, + generation: u64, index: usize, expanded: bool, live: bool, @@ -334,6 +310,7 @@ impl RowPresentation { Self { chat, binding, + generation, index, expanded, live, @@ -347,4 +324,18 @@ impl RowPresentation { self.can_fork = available; self } + fn actions( + &self, + extent: CopyExtent, + user: bool, + cx: &Context, + ) -> gpui_kit::AnyElement { + MessageRowActions::new( + self.can_fork.then_some(self.chat), + MessageCopy::new(self.binding.clone(), self.generation, self.index, extent), + self.time, + user, + ) + .render(cx) + } } diff --git a/crates/agent/src/panel/entries/tool_input.rs b/crates/agent/src/panel/entries/tool_input.rs index f3c21dca..b3da501c 100644 --- a/crates/agent/src/panel/entries/tool_input.rs +++ b/crates/agent/src/panel/entries/tool_input.rs @@ -1,11 +1,12 @@ //! Literal tool input, separate from the tool's result. use gpui_kit::{ - App, ClipboardItem, IntoElement, SharedString, StyledText, TestSupportExt as _, + App, ClipboardItem, HighlightStyle, IntoElement, RenderOnce, SharedString, StyledText, + TestSupportExt as _, Window, component::{ ActiveTheme as _, Rope, Sizable as _, button::{Button, ButtonVariants as _}, h_flex, - highlighter::SyntaxHighlighter, + highlighter::{HighlightTheme, SyntaxHighlighter}, v_flex, }, div, @@ -19,6 +20,7 @@ use nocterm_ai::{ }; use nocterm_ui::IconName; use serde_json::Value; +use std::{ops::Range, sync::Arc}; pub(in crate::panel) struct Source { pub label: &'static str, @@ -87,7 +89,7 @@ fn parameters_source(arguments: &Value) -> Source { } pub(in crate::panel) fn source(call: &ToolRecord) -> Option { - if let Some(display) = ToolDisplay::from_call(call) { + if let Some(display) = ToolDisplay::view(call) { let mut source = if let Some(request) = display.display_request() { let mut source = request_source(request); if matches!( @@ -98,7 +100,7 @@ pub(in crate::panel) fn source(call: &ToolRecord) -> Option { } source } else { - parameters_source(&display.arguments) + parameters_source(display.arguments.as_ref()) }; if display.redacted { source.parameters.push("Secrets hidden".into()); @@ -323,7 +325,6 @@ pub(super) fn render(index: usize, source: Source, cx: &App) -> impl IntoElement source.label, source.text, source.language, - cx, )); if !source.parameters.is_empty() { container = container.child( @@ -342,7 +343,6 @@ pub(super) fn render(index: usize, source: Source, cx: &App) -> impl IntoElement extra.label, extra.text, extra.language, - cx, )); } container @@ -354,7 +354,6 @@ fn section( label: &'static str, text: String, language: Option<&'static str>, - cx: &App, ) -> impl IntoElement { let copy_label = match label { "Command" | "Requested command" => "Copy command", @@ -375,7 +374,6 @@ fn section( }, copy_label, None, - cx, ) } @@ -386,7 +384,6 @@ pub(super) fn literal_section( section: Section, copy_label: &'static str, limit: Option, - cx: &App, ) -> impl IntoElement { let key = |name: String| -> (SharedString, usize) { ( @@ -404,23 +401,12 @@ pub(super) fn literal_section( text, language, } = section; - let copied = text.clone(); let mut end = limit.unwrap_or(text.len()).min(text.len()); while !text.is_char_boundary(end) { end -= 1; } let truncated = end < text.len(); - let text = text[..end].to_owned(); - let mut highlighter = language - .filter(|_| text.len() <= 64 * 1024) - .map(SyntaxHighlighter::new); - let highlights = highlighter - .as_mut() - .map(|highlighter| { - highlighter.update(None, &Rope::from(text.as_str()), None); - highlighter.styles(&(0..text.len()), cx.theme().highlight_theme.as_ref()) - }) - .unwrap_or_default(); + let preview = SharedString::from(&text[..end]); v_flex() .w_full() .min_w_0() @@ -439,23 +425,78 @@ pub(super) fn literal_section( .label("Copy") .accessibility_label(copy_label) .on_click(move |_, _, cx| { - cx.write_to_clipboard(ClipboardItem::new_string(copied.clone())); + cx.write_to_clipboard(ClipboardItem::new_string(text.clone())); }), ), ) .child(super::literal_viewport::LiteralViewport::new( scroll_id, - div() - .id(code_id) - .test_support() - .flex_shrink_0() - .font_family(cx.theme().mono_font_family.clone()) - .text_color(cx.theme().foreground) - .text_xs() - .whitespace_nowrap() - .child(StyledText::new(text).with_highlights(highlights)), + LiteralCode { + id: code_id, + text: preview, + language, + }, )) .when(truncated, |section| { section.child("Preview limited to 200 KiB. Copy includes the full text.") }) } + +#[derive(IntoElement)] +struct LiteralCode { + id: (SharedString, usize), + text: SharedString, + language: Option<&'static str>, +} + +struct LiteralHighlights { + text: SharedString, + language: &'static str, + theme: Arc, + styles: Vec<(Range, HighlightStyle)>, +} + +impl LiteralCode { + fn highlights(&self, window: &mut Window, cx: &mut App) -> Vec<(Range, HighlightStyle)> { + let Some(language) = self.language.filter(|_| self.text.len() <= 64 * 1024) else { + return Vec::new(); + }; + let theme = cx.theme().highlight_theme.clone(); + // This belongs to the rendered section and expires with it. + let cache = window.use_keyed_state(self.id.clone(), cx, |_, _| None::); + cache.update(cx, |cached, _| { + if let Some(hit) = cached.as_ref() + && hit.language == language + && hit.text == self.text + && Arc::ptr_eq(&hit.theme, &theme) + { + return hit.styles.clone(); + } + let mut highlighter = SyntaxHighlighter::new(language); + highlighter.update(None, &Rope::from(self.text.as_ref()), None); + let styles = highlighter.styles(&(0..self.text.len()), theme.as_ref()); + *cached = (styles.len() <= 4096).then(|| LiteralHighlights { + text: self.text.clone(), + language, + theme, + styles: styles.clone(), + }); + styles + }) + } +} + +impl RenderOnce for LiteralCode { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let highlights = self.highlights(window, cx); + div() + .id(self.id) + .test_support() + .flex_shrink_0() + .font_family(cx.theme().mono_font_family.clone()) + .text_color(cx.theme().foreground) + .text_xs() + .whitespace_nowrap() + .child(StyledText::new(self.text).with_highlights(highlights)) + } +} diff --git a/crates/agent/src/panel/entries/tool_output.rs b/crates/agent/src/panel/entries/tool_output.rs index c123e000..4f7e3dd4 100644 --- a/crates/agent/src/panel/entries/tool_output.rs +++ b/crates/agent/src/panel/entries/tool_output.rs @@ -72,14 +72,14 @@ fn content_value(item: &ToolContent) -> Value { } pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option { - let display = ToolDisplay::from_call(call); + let display = ToolDisplay::view(call); if let Some(display) = &display && let Some(outcome) = &display.outcome { let mut output = match outcome { ToolOutcome::Pending => return None, - ToolOutcome::Ok(value) => decode::bridge(&display.tool, value), - ToolOutcome::Err(error) => Output::plain("Error", error.clone()), + ToolOutcome::Ok(value) => decode::bridge(&display.tool, value.as_ref()), + ToolOutcome::Err(error) => Output::plain("Error", error.to_string()), }; if redact { output.redact(); @@ -88,8 +88,19 @@ pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option) -> Output { let mut output = Output { sections: Vec::new(), parameters: Vec::new(), @@ -107,14 +118,23 @@ pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option Option false, - [value] => decode::equivalent(tool, value, raw), + [_] => single_duplicate, values => decode::equivalent(tool, &Value::Array(values.to_vec()), raw), }; if !duplicate { - let decoded = tool.and_then(|tool| decode::known(tool, raw, 0)); + let decoded = tool.and_then(|tool| decode::known(tool, raw)); output.append(decoded.unwrap_or_else(|| Output::plain("Tool output", text(raw)))); } } - if output.sections.is_empty() { - return None; - } - if redact { - output.redact(); - } - Some(output) + output } pub(super) fn render(index: usize, output: Output, cx: &App) -> impl IntoElement { @@ -194,7 +208,6 @@ pub(super) fn render(index: usize, output: Output, cx: &App) -> impl IntoElement section, copy_label, Some(limit), - cx, )); } container diff --git a/crates/agent/src/panel/entries/tool_output/decode.rs b/crates/agent/src/panel/entries/tool_output/decode.rs index dab519b9..fcd22652 100644 --- a/crates/agent/src/panel/entries/tool_output/decode.rs +++ b/crates/agent/src/panel/entries/tool_output/decode.rs @@ -1,6 +1,7 @@ //! Historical provider wrappers are presentation hints, independent of execution validation. use super::Output; use serde_json::Value; +use std::fmt::Write as _; mod payload; mod unwrap; pub(super) use unwrap::truncated_preview; @@ -12,16 +13,35 @@ pub(super) fn equivalent(tool: Option<&str>, content: &Value, raw: &Value) -> bo .is_some_and(|content| Some(content) == unwrap::normalized(tool, raw, 0))) } -pub(super) fn known(tool: &str, value: &Value, depth: usize) -> Option { +pub(super) fn known(tool: &str, value: &Value) -> Option { + known_with_duplicate(tool, value, None).0 +} + +/// Reuse the content's normalized parts for the duplicate check, rather than +/// parsing the same provider envelope again after producing its output. +pub(super) fn known_with_duplicate( + tool: &str, + value: &Value, + raw: Option<&Value>, +) -> (Option, bool) { if let Some(output) = payload::known(tool, value) { - return Some(output); + return ( + Some(output), + raw.is_some_and(|raw| equivalent(Some(tool), value, raw)), + ); } - let Some(parts) = unwrap::normalized(Some(tool), value, depth) else { - return Some(Output::plain( - "Tool output", - "Tool result exceeds display limits".into(), - )); + let exact = raw.is_some_and(|raw| value == raw); + let Some(parts) = unwrap::normalized(Some(tool), value, 0) else { + return ( + Some(Output::plain( + "Tool output", + "Tool result exceeds display limits".into(), + )), + exact, + ); }; + let duplicate = exact + || raw.is_some_and(|raw| unwrap::normalized(Some(tool), raw, 0).as_ref() == Some(&parts)); let mut output = Output { sections: Vec::new(), parameters: Vec::new(), @@ -32,7 +52,7 @@ pub(super) fn known(tool: &str, value: &Value, depth: usize) -> Option { unwrap::Part::Error(error) => Output::plain("Error", error), }); } - (!output.sections.is_empty()).then_some(output) + ((!output.sections.is_empty()).then_some(output), duplicate) } pub(super) fn bridge(tool: &str, value: &Value) -> Output { @@ -41,26 +61,41 @@ pub(super) fn bridge(tool: &str, value: &Value) -> Output { /// Key/value text also handles future payloads without exposing provider JSON. pub(in crate::panel::entries) fn readable(value: &Value) -> String { - readable_at(value, 0) + let mut text = String::new(); + readable_into(value, 0, &mut text); + text } -fn readable_at(value: &Value, depth: usize) -> String { +fn readable_into(value: &Value, depth: usize, text: &mut String) { if depth >= 16 { - return "…".into(); + text.push('…'); + return; } match value { - Value::String(text) => text.clone(), - Value::Object(values) => values - .iter() - .map(|(key, value)| format!("{key}: {}", readable_at(value, depth + 1))) - .collect::>() - .join("\n"), - Value::Array(values) => values - .iter() - .map(|value| readable_at(value, depth + 1)) - .collect::>() - .join("\n\n"), - Value::Null => "None".into(), - value => value.to_string(), + Value::String(value) => text.push_str(value), + Value::Object(values) => { + for (index, (key, value)) in values.iter().enumerate() { + if index != 0 { + text.push('\n'); + } + text.push_str(key); + text.push_str(": "); + readable_into(value, depth + 1, text); + } + } + Value::Array(values) => { + for (index, value) in values.iter().enumerate() { + if index != 0 { + text.push_str("\n\n"); + } + readable_into(value, depth + 1, text); + } + } + Value::Null => text.push_str("None"), + Value::Bool(value) => text.push_str(if *value { "true" } else { "false" }), + Value::Number(value) => { + // Writing to String cannot fail. + let _ = write!(text, "{value}"); + } } } diff --git a/crates/agent/src/panel/entries/tool_output/decode/payload.rs b/crates/agent/src/panel/entries/tool_output/decode/payload.rs index 896060d4..ce4928a0 100644 --- a/crates/agent/src/panel/entries/tool_output/decode/payload.rs +++ b/crates/agent/src/panel/entries/tool_output/decode/payload.rs @@ -10,10 +10,10 @@ use serde_json::Value; pub(super) fn recognizes(tool: &str, value: &Value) -> bool { match tool { "exec_command" | "read_command" | "cancel_command" => { - serde_json::from_value::(value.clone()).is_ok() + Command::<&str>::decode(value).is_ok() } - "run_command" => serde_json::from_value::(value.clone()).is_ok(), - "read_terminal" => serde_json::from_value::(value.clone()).is_ok(), + "run_command" => Observation::<&str>::decode(value).is_ok(), + "read_terminal" => Terminal::<&str>::decode(value).is_ok(), "list_terminals" => value.get("context").is_some_and(Value::is_string), "send_input" => value.get("accepted").is_some_and(Value::is_boolean), "open_terminal" => value.get("terminal").is_some_and(Value::is_object), @@ -73,7 +73,7 @@ pub(super) fn known(tool: &str, value: &Value) -> Option { "open_terminal" => ( Output::plain( "Terminal", - super::readable(&Value::Object(object.get("terminal")?.as_object()?.clone())), + super::readable(object.get("terminal").filter(|value| value.is_object())?), ), &["terminal"][..], ), @@ -90,7 +90,7 @@ pub(super) fn known(tool: &str, value: &Value) -> Option { } pub(super) fn command(value: &Value) -> Option { - let value: Command = serde_json::from_value(value.clone()).ok()?; + let value: Command = Command::decode(value).ok()?; let state = match value.state.as_str() { "starting" => "Starting", "running" => "Running", @@ -149,11 +149,11 @@ fn terminal_output(value: Terminal) -> Option { Some(output) } pub(super) fn terminal(value: &Value) -> Option { - terminal_output(serde_json::from_value(value.clone()).ok()?) + terminal_output(Terminal::decode(value).ok()?) } pub(super) fn observation(value: &Value) -> Option { - let value: Observation = serde_json::from_value(value.clone()).ok()?; + let value: Observation = Observation::decode(value).ok()?; let status = match (value.completion.as_str(), value.completed) { ("prompt_returned", true) => "Prompt returned", ("output_idle", false) => "Observation ended: output idle; process completion unknown", diff --git a/crates/agent/src/panel/entries/tool_output/decode/unwrap.rs b/crates/agent/src/panel/entries/tool_output/decode/unwrap.rs index a77b4f58..cda6a56b 100644 --- a/crates/agent/src/panel/entries/tool_output/decode/unwrap.rs +++ b/crates/agent/src/panel/entries/tool_output/decode/unwrap.rs @@ -1,78 +1,83 @@ //! Bounded provider envelope removal; the entire Hermes fence must be complete. use serde_json::Value; +use std::borrow::Cow; const MAX_DECODE_BYTES: usize = 512 * 1024; const MAX_WRAPPER_DEPTH: usize = 8; #[derive(PartialEq)] -pub(super) enum Part { - Payload(Value), +pub(super) enum Part<'a> { + Payload(Cow<'a, Value>), Error(String), } -pub(super) fn normalized(tool: Option<&str>, value: &Value, depth: usize) -> Option> { +pub(super) fn normalized<'a>( + tool: Option<&str>, + value: &'a Value, + depth: usize, +) -> Option>> { if nocterm_ai::history::json_size(value).ok()? > MAX_DECODE_BYTES { return None; } let mut parts = Vec::new(); - descend(tool, value, depth, false, &mut parts)?; + descend(tool, Cow::Borrowed(value), depth, false, &mut parts)?; Some(parts) } -fn descend( +fn descend<'a>( tool: Option<&str>, - value: &Value, + value: Cow<'a, Value>, depth: usize, error: bool, - parts: &mut Vec, + parts: &mut Vec>, ) -> Option<()> { if depth >= MAX_WRAPPER_DEPTH { return None; } if let Some(text) = value.as_str() { if let Some(result) = fenced(text) { - return descend(tool, &Value::String(result.into()), depth + 1, error, parts); + return descend( + tool, + Cow::Owned(Value::String(result.into())), + depth + 1, + error, + parts, + ); } if text.len() <= MAX_DECODE_BYTES && let Ok(next) = serde_json::from_str::(text) { - return descend(tool, &next, depth + 1, error, parts); + return descend(tool, Cow::Owned(next), depth + 1, error, parts); } } - if let Some(values) = value.as_array() { - for value in values { - descend(tool, value, depth + 1, error, parts)?; - } - return Some(()); + if value.is_array() { + return descend_array(tool, value, depth + 1, error, parts); } if let Some(object) = value.as_object() - && !tool.is_some_and(|tool| super::payload::recognizes(tool, value)) + && !tool.is_some_and(|tool| super::payload::recognizes(tool, value.as_ref())) { let error = error || object .get("isError") .and_then(Value::as_bool) .unwrap_or(false); - if let Some(message) = provider_error(value) { + if let Some(message) = provider_error(value.as_ref()) { parts.push(Part::Error(message)); return Some(()); } - if let Some(result) = object.get("result") { - return descend(tool, result, depth + 1, error, parts); + if object.contains_key("result") { + return descend(tool, child(value, "result")?, depth + 1, error, parts); } if let Some(content) = object.get("content").and_then(Value::as_array) { if content.is_empty() && error { parts.push(Part::Error("Tool request failed".into())); } - for block in content { - descend(tool, block, depth + 1, error, parts)?; - } - return Some(()); + return descend_array(tool, child(value, "content")?, depth + 1, error, parts); } if object.get("type").and_then(Value::as_str) == Some("text") - && let Some(text) = object.get("text").and_then(Value::as_str) + && object.get("text").is_some_and(Value::is_string) { - return descend(tool, &Value::String(text.into()), depth + 1, error, parts); + return descend(tool, child(value, "text")?, depth + 1, error, parts); } if object.get("isError").and_then(Value::as_bool) == Some(true) { parts.push(Part::Error("Tool request failed".into())); @@ -80,13 +85,45 @@ fn descend( } } parts.push(if error { - Part::Error(super::readable(value)) + Part::Error(super::readable(value.as_ref())) } else { - Part::Payload(value.clone()) + Part::Payload(value) }); Some(()) } +/// Preserve ownership while traversing a wrapper: retained children are +/// borrowed and children of newly parsed objects are moved out. +fn child<'a>(value: Cow<'a, Value>, key: &str) -> Option> { + match value { + Cow::Borrowed(value) => value.get(key).map(Cow::Borrowed), + Cow::Owned(mut value) => value.as_object_mut()?.remove(key).map(Cow::Owned), + } +} + +fn descend_array<'a>( + tool: Option<&str>, + value: Cow<'a, Value>, + depth: usize, + error: bool, + parts: &mut Vec>, +) -> Option<()> { + match value { + Cow::Borrowed(value) => { + for value in value.as_array()? { + descend(tool, Cow::Borrowed(value), depth, error, parts)?; + } + } + Cow::Owned(Value::Array(values)) => { + for value in values { + descend(tool, Cow::Owned(value), depth, error, parts)?; + } + } + _ => return None, + } + Some(()) +} + fn provider_error(value: &Value) -> Option { let error = value .get("error")? diff --git a/crates/agent/src/panel/history.rs b/crates/agent/src/panel/history.rs index 94bf78d3..2a090dd1 100644 --- a/crates/agent/src/panel/history.rs +++ b/crates/agent/src/panel/history.rs @@ -5,7 +5,8 @@ //! no actions: opening one moves it here or brings its window forward. use gpui_kit::{ - Anchor, App, Context, Entity, TestSupportExt as _, + Anchor, App, Context, Entity, FocusHandle, ListAlignment, ListState, TestSupportExt as _, + WeakEntity, component::{ ActiveTheme as _, Selectable as _, Sizable as _, button::{Button, ButtonVariants as _}, @@ -13,18 +14,18 @@ use gpui_kit::{ input::Input, v_flex, }, - div, + div, list, prelude::*, px, }; use nocterm_agent_directory::AgentsHandle; use nocterm_ai::agents::{AgentProfile, AvailableAgents}; use nocterm_ui::IconName; -use std::time::Duration; +use std::{rc::Rc, time::Duration}; use super::{ AgentPanel, - history_column::HistorySide, + history_column::{HistoryColumn, HistorySide}, widgets::{relative_prompt_time, single_line_label}, }; use crate::thread::AgentThread; @@ -87,15 +88,22 @@ impl HistoryRowRenderer { } } fn details(row: &HistoryRow, name: gpui_kit::AnyElement, cx: &gpui_kit::App) -> gpui_kit::Div { - let icon = if row.generating { - gpui_kit::component::spinner::Spinner::new() + let icon = match (row.generating, row.elsewhere) { + // The status is visible without driving frames in the window that only lists it. + (true, true) => div() + .child( + gpui_kit::component::Icon::new(IconName::Loader) + .small() + .text_color(cx.theme().muted_foreground), + ) + .into_any_element(), + (true, false) => gpui_kit::component::spinner::Spinner::new() .small() .color(cx.theme().muted_foreground) - .into_any_element() - } else { - crate::agent_icon::agent_icon(row.agent) + .into_any_element(), + (false, _) => crate::agent_icon::agent_icon(row.agent) .small() - .into_any_element() + .into_any_element(), }; v_flex() .flex_1() @@ -279,6 +287,16 @@ impl HistoryRowRenderer { } pub(super) struct HistoryProjection; + +fn history_chat<'a>(thread: &Entity, elsewhere: bool, cx: &'a App) -> &'a AgentThread { + if elsewhere { + // Cross-window history is updated by its own coalesced observation of the thread. + thread.read_untracked(cx) + } else { + thread.read(cx) + } +} + impl HistoryProjection { /// The chats to list, in order, matching the search, each with whether another window /// holds it; in a hub window only those of the side shown. @@ -303,24 +321,21 @@ impl HistoryProjection { .collect(); let keys: Vec<(bool, u64)> = threads .iter() - .map(|(thread, _)| { - let document = thread.read(cx).document(); + .map(|(thread, elsewhere)| { + let document = history_chat(thread, *elsewhere, cx).document(); (document.pinned(), document.updated()) }) .collect(); order(&keys) .into_iter() .map(|index| threads[index].clone()) - .filter(|(thread, _)| { - let thread = thread.read(cx); - !hub_window || HistorySide::of(thread.document().agent_id()) == side - }) - .filter(|(thread, _)| { - let thread = thread.read(cx); - query.is_empty() - || thread.title().to_lowercase().contains(&query) - || thread.transcript().mentions(&query) - || history.matches(thread.document().chat_id()) + .filter(|(thread, elsewhere)| { + let thread = history_chat(thread, *elsewhere, cx); + (!hub_window || HistorySide::of(thread.document().agent_id()) == side) + && (query.is_empty() + || thread.title().to_lowercase().contains(&query) + || thread.transcript().mentions(&query) + || history.matches(thread.document().chat_id())) }) .collect() } @@ -343,8 +358,12 @@ impl HistoryProjection { .map(|current| current.entity_id()) .hash(&mut hasher); let others = history.others().listed(cx); - for thread in chats.iter().chain(&others) { - let chat = thread.read(cx); + for (thread, elsewhere) in chats + .iter() + .map(|thread| (thread, false)) + .chain(others.iter().map(|thread| (thread, true))) + { + let chat = history_chat(thread, elsewhere, cx); ( thread.entity_id(), chat.title(), @@ -384,10 +403,118 @@ impl HistoryProjection { )) .into_any_element() } - pub(super) fn render( +} + +struct HistoryEntry { + id: EntityId, + thread: WeakEntity, + elsewhere: bool, +} + +pub(super) struct HistoryViewport { + entries: Rc>, + scroll: ListState, + rename: Option<(EntityId, FocusHandle)>, + agents: Rc, + empty: bool, + dirty: bool, + query_revision: u64, +} + +impl Default for HistoryViewport { + fn default() -> Self { + Self { + entries: Rc::default(), + scroll: ListState::new(0, ListAlignment::Top, px(100.)), + rename: None, + agents: Rc::default(), + empty: true, + dirty: true, + query_revision: 0, + } + } +} + +impl HistoryViewport { + pub(super) fn invalidate(&mut self) { + self.dirty = true; + } + + pub(super) fn needs_prepare(&self, query_revision: u64) -> bool { + self.dirty || self.query_revision != query_revision + } + + pub(super) fn prepare( + &mut self, chats: &crate::roster::ChatRoster, - column: &super::history_column::HistoryColumn, - (agents, hub_window): (&AgentsHandle, bool), + column: &HistoryColumn, + agents: &AgentsHandle, + hub_window: bool, + cx: &App, + ) { + let listed = HistoryProjection::listed_threads(chats, column, hub_window, cx); + let entries: Vec<_> = listed + .into_iter() + .map(|(thread, elsewhere)| HistoryEntry { + id: thread.entity_id(), + thread: thread.downgrade(), + elsewhere, + }) + .collect(); + let rename = column.rename_focus(cx); + self.sync_scroll(&entries, &rename); + self.entries = Rc::new(entries); + self.rename = rename; + self.agents = Rc::new(agents.available(cx)); + self.empty = chats.is_empty() && column.others().listed(cx).is_empty(); + self.query_revision = column.query_revision(cx); + self.dirty = false; + } + + fn sync_scroll(&mut self, entries: &[HistoryEntry], rename: &Option<(EntityId, FocusHandle)>) { + if self.rename == *rename + && self + .entries + .iter() + .map(|entry| entry.id) + .eq(entries.iter().map(|entry| entry.id)) + { + return; + } + let mut offset = self.scroll.logical_scroll_top(); + let focus_handle = |entry: &HistoryEntry| { + rename + .as_ref() + .filter(|(id, _)| *id == entry.id) + .map(|(_, focus)| focus.clone()) + }; + self.scroll + .splice_focusable(0..self.entries.len(), entries.iter().map(focus_handle)); + // Let native wheel and scrollbar movements reach rows before they are measured. + self.scroll = self.scroll.clone().with_uniform_item_height(px(60.)); + if offset.item_ix > 0 || offset.offset_in_item > px(0.) { + if let Some(index) = self.entries.get(offset.item_ix).and_then(|entry| { + entries + .iter() + .position(|candidate| candidate.id == entry.id) + }) { + offset.item_ix = index; + } else { + offset = gpui_kit::ListOffset { + item_ix: 0, + offset_in_item: px(0.), + }; + } + } + self.scroll.scroll_to(offset); + } +} + +impl HistoryProjection { + pub(super) fn render( + viewport: &HistoryViewport, + column: &HistoryColumn, + hub_window: bool, now: u64, cx: &mut Context, ) -> gpui_kit::AnyElement { @@ -396,23 +523,18 @@ impl HistoryProjection { .test_support() .flex_1() .min_h_0() - .overflow_y_scroll() .p_2() .gap_1(); if hub_window { history = history.child(Self::sides(column.side(), cx)); } - if chats.is_empty() && column.others().listed(cx).is_empty() { + if viewport.empty { return history - .child( - div() - .id("agent-history-empty") - .test_support() - .px_1() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child("History is empty"), - ) + .child(Self::empty_label( + "agent-history-empty", + "History is empty", + cx, + )) .into_any_element(); } history = history.child( @@ -423,42 +545,65 @@ impl HistoryProjection { .cleanable(true), ), ); - let listed = Self::listed_threads(chats, column, hub_window, cx); - if listed.is_empty() { + if viewport.entries.is_empty() { let empty = match (column.query(cx).is_empty(), hub_window, column.side()) { (false, ..) | (true, false, _) => "No chats match", (true, true, HistorySide::Local) => "No chats with agents on this computer", (true, true, HistorySide::Server) => "No chats with the server's agents", }; - history = history.child( - div() - .id("agent-history-no-match") - .test_support() - .px_1() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(empty), - ); - } - // Resolved once: resolving builds the whole agent list from the catalog and settings. - let available = agents.available(cx); - // Pinned first, then the most recently changed. - let mut rows: Vec<((bool, u64), HistoryRow)> = Vec::with_capacity(listed.len()); - for (thread, elsewhere) in listed { - let document = thread.read(cx).document(); - let key = (document.pinned(), document.updated()); - let mut row = Self::local_row(&thread, chats, column, (agents, &available), now, cx); - row.elsewhere = elsewhere; - rows.push((key, row)); - } - rows.sort_by_key(|(key, _)| std::cmp::Reverse(*key)); - for (_, row) in rows { - history = history.child(HistoryRowRenderer::render(row, cx)); + return history + .child(Self::empty_label("agent-history-no-match", empty, cx)) + .into_any_element(); } - history.into_any_element() + let entries = viewport.entries.clone(); + let agents = viewport.agents.clone(); + history + .child( + div().relative().w_full().flex_1().min_h_0().child( + list( + viewport.scroll.clone(), + cx.processor(move |panel, index: usize, _, cx| { + let entry = &entries[index]; + let Some(thread) = entry.thread.upgrade() else { + return div().into_any_element(); + }; + let row = Self::row( + &thread, + entry.elsewhere, + &panel.chats, + &panel.history, + (panel.host.agents(), &agents), + now, + cx, + ); + div() + .w_full() + .pb_1() + .child(HistoryRowRenderer::render(row, cx)) + .into_any_element() + }), + ) + .absolute() + .inset_0(), + ), + ) + .into_any_element() + } + + fn empty_label(id: &'static str, label: &'static str, cx: &App) -> gpui_kit::AnyElement { + div() + .id(id) + .test_support() + .px_1() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(label) + .into_any_element() } - fn local_row( + + fn row( thread: &Entity, + elsewhere: bool, chats: &crate::roster::ChatRoster, history: &super::history_column::HistoryColumn, (agents, available): (&AgentsHandle, &AvailableAgents), @@ -466,7 +611,7 @@ impl HistoryProjection { cx: &App, ) -> HistoryRow { let id = thread.entity_id(); - let chat = thread.read(cx); + let chat = history_chat(thread, elsewhere, cx); let when = if chat.archive_summary().is_none_or(|row| !row.has_content) && chat.history_entries().is_empty() && chat.draft_text().is_none() @@ -489,7 +634,7 @@ impl HistoryProjection { generating: chat.session_generating(), agent: agents.profile_in(available, chat.document().agent_id()), rename: history.rename_input(id), - elsewhere: false, + elsewhere, } } } diff --git a/crates/agent/src/panel/history_column.rs b/crates/agent/src/panel/history_column.rs index ea9a2aa3..e9540650 100644 --- a/crates/agent/src/panel/history_column.rs +++ b/crates/agent/src/panel/history_column.rs @@ -182,6 +182,9 @@ impl HistoryColumn { pub(super) fn query(&self, cx: &App) -> String { self.input.read(cx).value().trim().to_lowercase() } + pub(super) fn query_revision(&self, cx: &App) -> u64 { + self.input.read(cx).document_revision() + } pub(super) fn query_input(&self) -> Input { Input::new(&self.input).id("agent-history-search").small() } @@ -297,6 +300,10 @@ impl HistoryColumn { pub(super) fn renaming(&self) -> bool { self.rename.is_some() } + pub(super) fn rename_focus(&self, cx: &App) -> Option<(EntityId, gpui_kit::FocusHandle)> { + let rename = self.rename.as_ref()?; + Some((rename.chat, rename.input.read(cx).focus_handle(cx))) + } pub(super) fn rename_input(&self, chat: EntityId) -> Option { self.rename .as_ref() diff --git a/crates/agent/src/panel/image_pipeline.rs b/crates/agent/src/panel/image_pipeline.rs index fc910f3e..c9da3bb0 100644 --- a/crates/agent/src/panel/image_pipeline.rs +++ b/crates/agent/src/panel/image_pipeline.rs @@ -1,40 +1,57 @@ -//! Bounded previews retain immutable sources, so pointer identities cannot be reused. +//! Bounded previews keep allocation identities separate from their encoded bytes. use crate::ImageDeps; -use gpui_kit::{Image, Task}; +use gpui_kit::{App, Image, RenderImage, SvgRenderer, Task}; use nocterm_ai::{ - images::{ImageInspector, MAX_PREVIEW_BYTES}, - model::content::ImageData, + images::{ + EncodedPreview, ImageCodecError, ImageInspector, MAX_PREVIEW_BYTES, PreviewImage, + PreviewPixels, + }, + model::content::{ImageData, ImageIdentity}, }; -use std::{cell::Cell, collections::HashMap, sync::Arc}; -pub(super) type ImageKey = (usize, usize, bool); +use std::{ + cell::Cell, + collections::{BTreeSet, HashMap}, + hash::{DefaultHasher, Hasher as _}, + sync::{Arc, Weak}, +}; +pub(super) type ImageKey = usize; const MAX_ENTRIES: usize = 32; const MAX_BYTES: usize = 64 * 1024 * 1024; const MAX_PREVIEW_RESIDENT: usize = MAX_PREVIEW_BYTES + 640 * 640 * 8; const MAX_LOADING: usize = 4; -#[derive(Clone)] pub(super) enum PreviewSource { Encoded(ImageData), - Original(Arc<[u8]>), + Original { data: ImageData, bytes: Arc<[u8]> }, } impl PreviewSource { - pub(super) fn retained_bytes(&self) -> usize { + pub(super) fn prompt(image: &nocterm_ai::images::PromptImage) -> Self { + Self::Original { + data: image.encoded_data().clone(), + bytes: image.shared_bytes(), + } + } + + fn encoded(&self) -> &ImageData { match self { - Self::Encoded(data) => data.retained_bytes(), - Self::Original(data) => data.len().saturating_add( + Self::Encoded(data) | Self::Original { data, .. } => data, + } + } + fn retained_bytes(&self) -> usize { + let encoded = self.encoded().retained_bytes(); + match self { + Self::Encoded(_) => encoded, + Self::Original { bytes, .. } => encoded.saturating_add(bytes.len()).saturating_add( 2 * std::mem::size_of::() + std::mem::align_of::() - 1, ), } } pub(super) fn key(&self) -> ImageKey { - match self { - Self::Encoded(data) => (data.as_ptr() as usize, data.len(), true), - Self::Original(data) => (data.as_ptr() as usize, data.len(), false), - } + self.encoded().allocation_key() } pub(super) fn decode(&self) -> Result, super::entries::PreviewError> { match self { - Self::Original(data) => Ok(data.clone()), + Self::Original { bytes, .. } => Ok(bytes.clone()), Self::Encoded(data) => { use base64::Engine as _; if data.len() > nocterm_ai::images::MAX_IMAGE_BYTES.div_ceil(3) * 4 { @@ -55,44 +72,163 @@ pub(super) struct PreviewTicket { } #[derive(Clone)] pub(super) struct CompletedPreview { - image: Arc, + image: Arc, +} + +pub(super) struct PreviewRender { + key: PreviewKey, + rendered: Arc, resident_bytes: usize, } + +#[derive(Clone, Copy, PartialEq, Eq)] +struct PreviewKey { + dimensions: (u32, u32), + fingerprint: u64, +} +impl PreviewKey { + fn new(dimensions: (u32, u32), pixels: &[u8]) -> Self { + let mut hasher = DefaultHasher::new(); + hasher.write(pixels); + Self { + dimensions, + fingerprint: hasher.finish(), + } + } +} + impl CompletedPreview { - pub(super) fn from_encoded(preview: nocterm_ai::images::EncodedPreview) -> Self { - let (width, height) = preview.dimensions(); - let resident_bytes = preview.bytes().len() + width as usize * height as usize * 8; + pub(super) fn from_preview( + preview: PreviewImage, + renderer: SvgRenderer, + reusable: &[Weak], + ) -> Result { + match preview { + PreviewImage::Png(preview) => Self::from_encoded(preview, renderer, reusable), + PreviewImage::Pixels(preview) => Self::from_pixels(preview, reusable), + } + } + + fn from_encoded( + preview: EncodedPreview, + renderer: SvgRenderer, + reusable: &[Weak], + ) -> Result { + let rendered = Image::from_bytes(gpui_kit::ImageFormat::Png, preview.bytes().to_vec()) + .to_image_data(renderer) + .map_err(|error| super::entries::PreviewError::Render(error.into_boxed_dyn_error()))?; + let pixels = rendered + .as_bytes(0) + .ok_or(ImageCodecError::InvalidEvidence)?; + let size = rendered.size(0); + let key = PreviewKey::new((size.width.into(), size.height.into()), pixels); + let resident_bytes = pixels.len() * 2; + Ok(Self::reuse(reusable, key, pixels) + .unwrap_or_else(|| Self::new(key, resident_bytes, rendered))) + } + + fn from_pixels( + preview: PreviewPixels, + reusable: &[Weak], + ) -> Result { + let dimensions = preview.dimensions(); + let mut pixels = preview.into_rgba(); + for pixel in pixels.as_chunks_mut::<4>().0 { + pixel.swap(0, 2); + } + let key = PreviewKey::new(dimensions, &pixels); + if let Some(preview) = Self::reuse(reusable, key, &pixels) { + return Ok(preview); + } + let resident_bytes = pixels.capacity() + pixels.len(); + let frame = image::RgbaImage::from_raw(dimensions.0, dimensions.1, pixels) + .ok_or(ImageCodecError::InvalidEvidence)?; + let rendered = Arc::new(RenderImage::new([image::Frame::new(frame)])); + Ok(Self::new(key, resident_bytes, rendered)) + } + + fn reuse(reusable: &[Weak], key: PreviewKey, pixels: &[u8]) -> Option { + reusable + .iter() + .filter_map(Weak::upgrade) + .find(|image| image.key == key && image.rendered.as_bytes(0) == Some(pixels)) + .map(|image| Self { image }) + } + + fn new(key: PreviewKey, resident_bytes: usize, rendered: Arc) -> Self { Self { - image: Arc::new(Image::from_bytes( - gpui_kit::ImageFormat::Png, - preview.bytes().to_vec(), - )), - resident_bytes, + image: Arc::new(PreviewRender { + key, + rendered, + resident_bytes, + }), } } - fn into_ready(self) -> (PreviewState, usize) { - (PreviewState::Ready(self.image), self.resident_bytes) + pub(super) fn rendered(&self) -> &Arc { + &self.image.rendered } } pub(super) enum PreviewState { - Loading, - Ready(Arc), + Loading(PreviewWaiters), + Ready(CompletedPreview), Failed, } +#[derive(Default)] +pub(super) struct PreviewWaiters { + rows: BTreeSet, + footer: bool, +} +impl PreviewWaiters { + fn add(&mut self, row: Option) { + if let Some(row) = row { + self.rows.insert(row); + } else { + self.footer = true; + } + } +} +#[derive(Default)] +pub(super) struct PreviewRegions { + transcript: bool, + footer: bool, +} +impl PreviewRegions { + pub(super) fn transcript(&self) -> bool { + self.transcript + } + + pub(super) fn footer(&self) -> bool { + self.footer + } + + fn retry(&mut self, row: Option) { + self.transcript |= row.is_some(); + self.footer |= row.is_none(); + } +} struct PreviewEntry { ticket: PreviewTicket, state: PreviewState, - source: PreviewSource, + _source_identity: ImageIdentity, last_used: Cell, task: Option>, charge: usize, } +impl PreviewEntry { + fn ready(&self) -> Option<&CompletedPreview> { + match &self.state { + PreviewState::Ready(preview) => Some(preview), + PreviewState::Loading(_) | PreviewState::Failed => None, + } + } +} struct PreviewCache { entries: HashMap, generation: u64, next_request: u64, clock: Cell, + redraw_on_completion: PreviewRegions, } pub(super) struct ImagePipeline { cache: PreviewCache, @@ -106,6 +242,7 @@ impl ImagePipeline { generation: 0, next_request: 0, clock: Cell::new(0), + redraw_on_completion: PreviewRegions::default(), }, deps, } @@ -116,48 +253,60 @@ impl ImagePipeline { pub(super) fn image_deps(&self) -> ImageDeps { self.deps.clone() } - pub(super) fn admit_work(&self) -> Option { - self.deps.admit_work() - } - pub(super) fn contains_key(&self, key: &ImageKey) -> bool { - self.state(key).is_some() - } pub(super) fn state(&self, key: &ImageKey) -> Option<&PreviewState> { let entry = self.cache.entries.get(key)?; - let next = self.cache.clock.get().saturating_add(1); - self.cache.clock.set(next); - entry.last_used.set(next); + Self::touch(&self.cache.clock, entry); Some(&entry.state) } - pub(super) fn request(&mut self, source: PreviewSource) -> Option { + + fn touch(clock: &Cell, entry: &PreviewEntry) { + let next = clock.get().saturating_add(1); + clock.set(next); + entry.last_used.set(next); + } + + pub(super) fn request( + &mut self, + source: &PreviewSource, + row: Option, + cx: &mut App, + ) -> Option { let key = source.key(); - if self.contains_key(&key) { + if let Some(entry) = self.cache.entries.get_mut(&key) { + Self::touch(&self.cache.clock, entry); + if let PreviewState::Loading(waiters) = &mut entry.state { + waiters.add(row); + } return None; } let loading = self .cache .entries .values() - .filter(|entry| matches!(entry.state, PreviewState::Loading)) + .filter(|entry| matches!(entry.state, PreviewState::Loading(_))) .count(); if loading >= MAX_LOADING { + self.cache.redraw_on_completion.retry(row); return None; } let charge = source.retained_bytes().saturating_add(MAX_PREVIEW_RESIDENT); if charge > MAX_BYTES { return None; } - while self.cache.entries.len() >= MAX_ENTRIES - || self.charged_bytes().saturating_add(charge) > MAX_BYTES - { + while !self.can_admit(charge) { + // Wait for reservations to shrink before displacing a ready image. + if loading > 0 { + self.cache.redraw_on_completion.retry(row); + return None; + } let oldest = self .cache .entries .iter() - .filter(|(_, entry)| !matches!(entry.state, PreviewState::Loading)) .min_by_key(|(_, entry)| entry.last_used.get()) - .map(|(key, _)| *key)?; - self.cache.entries.remove(&oldest); + .map(|(key, _)| *key) + .expect("a preview with a bounded charge fits an empty cache"); + self.evict(oldest, cx); } self.cache.next_request = self .cache @@ -171,12 +320,14 @@ impl ImagePipeline { }; let last_used = self.cache.clock.get().saturating_add(1); self.cache.clock.set(last_used); + let mut waiters = PreviewWaiters::default(); + waiters.add(row); self.cache.entries.insert( key, PreviewEntry { ticket, - state: PreviewState::Loading, - source, + state: PreviewState::Loading(waiters), + _source_identity: source.encoded().identity(), last_used: Cell::new(last_used), task: None, charge, @@ -184,8 +335,51 @@ impl ImagePipeline { ); Some(ticket) } - fn charged_bytes(&self) -> usize { - self.cache.entries.values().map(|entry| entry.charge).sum() + + fn evict(&mut self, key: ImageKey, cx: &mut App) { + let Some(entry) = self.cache.entries.remove(&key) else { + return; + }; + let Some(preview) = entry.ready() else { + return; + }; + // A cached region can still refer to the evicted source. + self.cache.redraw_on_completion = PreviewRegions { + transcript: true, + footer: true, + }; + if !self + .cache + .entries + .values() + .filter_map(PreviewEntry::ready) + .any(|remaining| Arc::ptr_eq(&preview.image, &remaining.image)) + { + // The updated window returns to App before deferred effects run. + let image = preview.rendered().clone(); + cx.defer(move |cx| cx.drop_image(image, None)); + } + } + + fn can_admit(&self, charge: usize) -> bool { + self.cache.entries.len() < MAX_ENTRIES + && self + .cache + .entries + .values() + .map(|entry| entry.charge) + .sum::() + + charge + <= MAX_BYTES + } + + pub(super) fn reusable_previews(&self) -> Vec> { + self.cache + .entries + .values() + .filter_map(PreviewEntry::ready) + .map(|preview| Arc::downgrade(&preview.image)) + .collect() } pub(super) fn install_task(&mut self, ticket: PreviewTicket, task: Task<()>) { if let Some(entry) = self @@ -201,31 +395,53 @@ impl ImagePipeline { &mut self, ticket: PreviewTicket, image: Option, - ) -> bool { - let Some(entry) = self + ) -> Option<(BTreeSet, PreviewRegions)> { + let entry = self .cache .entries .get_mut(&ticket.key) - .filter(|entry| entry.ticket == ticket) - else { - return false; + .filter(|entry| entry.ticket == ticket)?; + let PreviewState::Loading(waiters) = &mut entry.state else { + return None; }; - if !matches!(entry.state, PreviewState::Loading) { - return false; - } - let (state, bytes) = image.map_or((PreviewState::Failed, 0), CompletedPreview::into_ready); - entry.charge = entry.source.retained_bytes().saturating_add(bytes); + let waiters = std::mem::take(waiters); + let (state, bytes) = image.map_or((PreviewState::Failed, 0), |image| { + let bytes = image.image.resident_bytes; + (PreviewState::Ready(image), bytes) + }); + entry.charge = ImageIdentity::RETAINED_BYTES.saturating_add(bytes); entry.state = state; entry.task = None; - true + let mut regions = std::mem::take(&mut self.cache.redraw_on_completion); + regions.transcript |= !waiters.rows.is_empty(); + regions.footer |= waiters.footer; + Some((waiters.rows, regions)) } - pub(super) fn clear(&mut self) { + pub(super) fn clear(&mut self, cx: &mut App) { + self.cache.redraw_on_completion = PreviewRegions::default(); self.cache.generation = self .cache .generation .checked_add(1) .expect("preview generation space"); - self.cache.entries.clear(); + let mut images = self + .cache + .entries + .drain() + .filter_map(|(_, entry)| match entry.state { + PreviewState::Ready(image) => Some(image.rendered().clone()), + PreviewState::Loading(_) | PreviewState::Failed => None, + }) + .collect::>(); + if !images.is_empty() { + images.sort_unstable_by_key(|image| image.id); + images.dedup_by_key(|image| image.id); + cx.defer(move |cx| { + for image in images { + cx.drop_image(image, None); + } + }); + } } } #[cfg(test)] diff --git a/crates/agent/src/panel/image_pipeline/tests.rs b/crates/agent/src/panel/image_pipeline/tests.rs index a6d60a41..51a9607f 100644 --- a/crates/agent/src/panel/image_pipeline/tests.rs +++ b/crates/agent/src/panel/image_pipeline/tests.rs @@ -1,84 +1,127 @@ //! Request methods reject old delivery even when a new chat reuses its key. use super::*; +use base64::Engine as _; +use gpui_kit::TestAppContext; use nocterm_ai::testing::ScriptedImageCodec; fn pipeline() -> ImagePipeline { let codec = Arc::new(ScriptedImageCodec::default()); ImagePipeline::new(ImageDeps::new(codec.clone(), codec)) } -fn completed_preview() -> CompletedPreview { +fn original_source(byte: u8, length: usize) -> PreviewSource { + let bytes: Arc<[u8]> = vec![byte; length].into(); + let data = base64::engine::general_purpose::STANDARD + .encode(&bytes) + .into(); + PreviewSource::Original { data, bytes } +} + +fn completed_preview(reusable: &[Weak]) -> CompletedPreview { let bytes = include_bytes!("../tests/fixtures/prompt.png").to_vec(); let bounds = nocterm_ai::images::PreviewBounds::new(640, 640).unwrap(); let preview = nocterm_ai::images::EncodedPreview::new(bytes.into(), bounds).unwrap(); - CompletedPreview::from_encoded(preview) + CompletedPreview::from_encoded(preview, SvgRenderer::new(Arc::new(())), reusable).unwrap() } + #[test] -fn cleared_generation_cannot_install_old_success_or_failure_over_a_reused_key() { +fn direct_render_pixels_preserve_color_alpha_and_shape() { + let bounds = nocterm_ai::images::PreviewBounds::new(2, 2).unwrap(); + let rgba = vec![12, 34, 56, 77, 112, 121, 97, 0]; + let a = + CompletedPreview::from_pixels(PreviewPixels::new(2, 1, rgba.clone(), bounds).unwrap(), &[]) + .unwrap(); + assert_eq!( + a.rendered().size(0), + gpui_kit::size(2u32.into(), 1u32.into()) + ); + assert_eq!( + a.rendered().as_bytes(0), + Some([56, 34, 12, 77, 97, 121, 112, 0].as_slice()) + ); + let reusable = [Arc::downgrade(&a.image)]; + let b = + CompletedPreview::from_pixels(PreviewPixels::new(1, 2, rgba, bounds).unwrap(), &reusable) + .unwrap(); + assert_ne!(a.rendered().id, b.rendered().id); +} +#[gpui_kit::test] +fn cleared_generation_cannot_install_old_success_or_failure_over_a_reused_key( + cx: &mut TestAppContext, +) { let mut pipeline = pipeline(); - let source = PreviewSource::Original(vec![7].into()); + let source = original_source(7, 1); let key = source.key(); - let old = pipeline.request(source.clone()).unwrap(); - pipeline.clear(); - let current = pipeline.request(source.clone()).unwrap(); - let image = completed_preview(); - assert!(!pipeline.complete(old, Some(image.clone()))); - assert!(!pipeline.complete(old, None)); - assert!(matches!(pipeline.state(&key), Some(PreviewState::Loading))); - assert!(pipeline.complete(current, Some(image))); + let old = cx.update(|cx| pipeline.request(&source, None, cx)).unwrap(); + cx.update(|cx| pipeline.clear(cx)); + let current = cx.update(|cx| pipeline.request(&source, None, cx)).unwrap(); + let image = completed_preview(&[]); + assert!(pipeline.complete(old, Some(image.clone())).is_none()); + assert!(pipeline.complete(old, None).is_none()); + assert!(matches!( + pipeline.state(&key), + Some(PreviewState::Loading(_)) + )); + assert!(pipeline.complete(current, Some(image)).is_some()); assert!(matches!(pipeline.state(&key), Some(PreviewState::Ready(_)))); - assert!(pipeline.request(source.clone()).is_none()); - assert!(!pipeline.complete(current, None)); + assert!( + cx.update(|cx| pipeline.request(&source, None, cx)) + .is_none() + ); + assert!(pipeline.complete(current, None).is_none()); } -#[test] -fn retained_source_prevents_aliasing_and_cloned_image_reuses_its_preview() { +#[gpui_kit::test] +fn retained_source_prevents_aliasing_and_cloned_image_reuses_its_preview(cx: &mut TestAppContext) { let mut pipeline = pipeline(); let source = PreviewSource::Encoded("old image".to_owned().into()); let key = source.key(); - let ticket = pipeline.request(source.clone()).unwrap(); - assert!(pipeline.complete(ticket, None)); - assert!(pipeline.request(source).is_none()); + let ticket = cx.update(|cx| pipeline.request(&source, None, cx)).unwrap(); + assert!(pipeline.complete(ticket, None).is_some()); + assert!( + cx.update(|cx| pipeline.request(&source, None, cx)) + .is_none() + ); let other = PreviewSource::Encoded("new image".to_owned().into()); assert_ne!(key, other.key()); - assert!(pipeline.request(other).is_some()); + assert!(cx.update(|cx| pipeline.request(&other, None, cx)).is_some()); } -#[test] -fn preview_admission_bounds_concurrent_decodes_and_reclaims_finished_sources() { +#[gpui_kit::test] +fn preview_admission_bounds_concurrent_decodes_and_reclaims_finished_sources( + cx: &mut TestAppContext, +) { let mut pipeline = pipeline(); - let first = PreviewSource::Original(vec![0; 5 * 1024 * 1024].into()); + let first = original_source(0, 5 * 1024 * 1024); let key = first.key(); - let ticket = pipeline.request(first.clone()).unwrap(); - assert!(pipeline.complete(ticket, None)); - for value in 1..=16 { - let source = PreviewSource::Original(vec![value as u8; 5 * 1024 * 1024].into()); - if let Some(ticket) = pipeline.request(source) { - assert!(pipeline.complete(ticket, None)); + let ticket = cx.update(|cx| pipeline.request(&first, None, cx)).unwrap(); + assert!(pipeline.complete(ticket, None).is_some()); + for value in 1..=MAX_ENTRIES { + let source = original_source(value as u8, 1); + if let Some(ticket) = cx.update(|cx| pipeline.request(&source, None, cx)) { + assert!(pipeline.complete(ticket, None).is_some()); } } assert!(pipeline.state(&key).is_none()); - pipeline.clear(); + cx.update(|cx| pipeline.clear(cx)); for value in 0..MAX_LOADING { assert!( - pipeline - .request(PreviewSource::Original(vec![value as u8].into())) + cx.update(|cx| pipeline.request(&original_source(value as u8, 1), None, cx)) .is_some() ); } assert!( - pipeline - .request(PreviewSource::Original(vec![99].into())) + cx.update(|cx| pipeline.request(&original_source(99, 1), None, cx)) .is_none() ); } -#[test] -fn small_completed_previews_release_their_decode_reservation() { +#[gpui_kit::test] +fn small_completed_previews_release_their_decode_reservation(cx: &mut TestAppContext) { let mut pipeline = pipeline(); let mut sources = Vec::new(); for value in 0..16u8 { - let source = PreviewSource::Original(vec![value; 1024].into()); - let ticket = pipeline.request(source.clone()).unwrap(); - let image = completed_preview(); - assert!(pipeline.complete(ticket, Some(image))); + let source = original_source(value, 1024); + let ticket = cx.update(|cx| pipeline.request(&source, None, cx)).unwrap(); + let image = completed_preview(&[]); + assert!(pipeline.complete(ticket, Some(image)).is_some()); sources.push(source); } for source in sources { @@ -88,3 +131,162 @@ fn small_completed_previews_release_their_decode_reservation() { )); } } + +#[gpui_kit::test] +fn four_composer_previews_settle_beside_four_visible_transcript_previews(cx: &mut TestAppContext) { + let mut pipeline = pipeline(); + let bounds = nocterm_ai::images::PreviewBounds::new(640, 640).unwrap(); + let mut sources = Vec::new(); + for color in 0..8u8 { + let source = original_source(color, 5 * 1024 * 1024); + let row = (color < 4).then_some(0); + let ticket = cx.update(|cx| pipeline.request(&source, row, cx)).unwrap(); + let pixels = PreviewPixels::new(640, 640, vec![color; 640 * 640 * 4], bounds).unwrap(); + let preview = CompletedPreview::from_pixels(pixels, &[]).unwrap(); + assert!(pipeline.complete(ticket, Some(preview)).is_some()); + sources.push((source, row)); + } + for (color, (source, row)) in sources.iter().enumerate() { + let Some(PreviewState::Ready(preview)) = pipeline.state(&source.key()) else { + panic!("expected visible preview {color} to remain ready"); + }; + assert_eq!(preview.rendered().as_bytes(0).unwrap()[0], color as u8); + assert!(cx.update(|cx| pipeline.request(source, *row, cx)).is_none()); + } +} + +#[gpui_kit::test] +fn a_decode_waits_for_temporary_space_while_existing_previews_stay_ready(cx: &mut TestAppContext) { + let mut pipeline = pipeline(); + let bounds = nocterm_ai::images::PreviewBounds::new(640, 640).unwrap(); + let sources: Vec<_> = (0..7) + .map(|color| original_source(color, 5 * 1024 * 1024)) + .collect(); + for (color, source) in sources[..4].iter().enumerate() { + let ticket = cx + .update(|cx| pipeline.request(source, Some(0), cx)) + .unwrap(); + let pixels = + PreviewPixels::new(640, 640, vec![color as u8; 640 * 640 * 4], bounds).unwrap(); + let preview = CompletedPreview::from_pixels(pixels, &[]).unwrap(); + assert!(pipeline.complete(ticket, Some(preview)).is_some()); + } + let first = cx + .update(|cx| pipeline.request(&sources[4], None, cx)) + .unwrap(); + assert!( + cx.update(|cx| pipeline.request(&sources[5], None, cx)) + .is_some() + ); + assert!( + cx.update(|cx| pipeline.request(&sources[6], None, cx)) + .is_none() + ); + for source in &sources[..4] { + assert!(matches!( + pipeline.state(&source.key()), + Some(PreviewState::Ready(_)) + )); + } + let (_, redraw) = pipeline.complete(first, None).unwrap(); + assert!(redraw.footer()); + assert!( + cx.update(|cx| pipeline.request(&sources[6], None, cx)) + .is_some() + ); +} + +#[gpui_kit::test] +fn a_preview_completion_retries_backpressure_and_redraws_every_waiting_surface( + cx: &mut TestAppContext, +) { + let mut pipeline = pipeline(); + let mut tickets = Vec::new(); + for value in 0..MAX_LOADING { + let source = original_source(value as u8, 1); + tickets.push( + cx.update(|cx| pipeline.request(&source, Some(value), cx)) + .unwrap(), + ); + } + let waiting = original_source(99, 1); + assert!( + cx.update(|cx| pipeline.request(&waiting, None, cx)) + .is_none() + ); + + let (rows, first) = pipeline.complete(tickets[0], None).unwrap(); + assert_eq!(rows.into_iter().collect::>(), [0]); + assert!(first.transcript() && first.footer()); + let footer_ticket = cx + .update(|cx| pipeline.request(&waiting, None, cx)) + .unwrap(); + assert!( + cx.update(|cx| pipeline.request(&waiting, Some(99), cx)) + .is_none() + ); + let (rows, shared) = pipeline + .complete(footer_ticket, Some(completed_preview(&[]))) + .unwrap(); + assert_eq!(rows.into_iter().collect::>(), [99]); + assert!(shared.transcript() && shared.footer()); + let (_, next) = pipeline.complete(tickets[1], None).unwrap(); + assert!(next.transcript() && !next.footer()); +} + +#[gpui_kit::test] +fn identical_previews_share_one_atlas_entry_until_last_eviction(cx: &mut TestAppContext) { + let mut pipeline = pipeline(); + let source = original_source(0, 1); + let ticket = cx.update(|cx| pipeline.request(&source, None, cx)).unwrap(); + assert!( + pipeline + .complete(ticket, Some(completed_preview(&[]))) + .is_some() + ); + let duplicate = original_source(1, 1); + let ticket = cx + .update(|cx| pipeline.request(&duplicate, None, cx)) + .unwrap(); + let png = completed_preview(&[]); + let mut rgba = png.rendered().as_bytes(0).unwrap().to_vec(); + for pixel in rgba.as_chunks_mut::<4>().0 { + pixel.swap(0, 2); + } + let bounds = nocterm_ai::images::PreviewBounds::new(2, 2).unwrap(); + let raw = PreviewPixels::new(2, 2, rgba, bounds).unwrap(); + let reused = CompletedPreview::from_pixels(raw, &pipeline.reusable_previews()).unwrap(); + let image = reused.rendered().clone(); + assert!(pipeline.complete(ticket, Some(reused)).is_some()); + + let window = cx.add_empty_window(); + let state = pipeline.state(&source.key()); + let Some(PreviewState::Ready(first)) = state else { + panic!("preview was not ready"); + }; + assert_eq!(first.rendered().id, image.id); + window.draw( + gpui_kit::point(gpui_kit::px(0.), gpui_kit::px(0.)), + gpui_kit::size(gpui_kit::px(400.), gpui_kit::px(400.)), + |_, _| super::super::entries::EntryRenderer::image(state), + ); + assert_eq!(image.frame_count(), 1); + assert_eq!(image.size(0), gpui_kit::size(2u32.into(), 2u32.into())); + assert_eq!(image.as_bytes(0).unwrap().len(), 2 * 2 * 4); + assert!(window.update(|window, _| window.has_image_atlas_entry(&image))); + + for value in 2..=MAX_ENTRIES { + let next = original_source(value as u8, 1); + let ticket = window + .update(|_, cx| pipeline.request(&next, None, cx)) + .unwrap(); + assert!(pipeline.complete(ticket, None).is_some()); + } + assert!(window.update(|window, _| window.has_image_atlas_entry(&image))); + let next = original_source((MAX_ENTRIES + 1) as u8, 1); + let ticket = window + .update(|_, cx| pipeline.request(&next, None, cx)) + .unwrap(); + assert!(pipeline.complete(ticket, None).is_some()); + assert!(!window.update(|window, _| window.has_image_atlas_entry(&image))); +} diff --git a/crates/agent/src/panel/image_preparation.rs b/crates/agent/src/panel/image_preparation.rs index 0cb78ae1..8c689e7d 100644 --- a/crates/agent/src/panel/image_preparation.rs +++ b/crates/agent/src/panel/image_preparation.rs @@ -1,51 +1,60 @@ //! Finite result work owns its injected inspector and retains original completion authority. -use super::{AgentPanel, composer_view::ComposerBinding, images::ImageAttachError}; +use super::{ + AgentPanel, + composer_view::ComposerBinding, + images::{ImageAttachError, PreparedImages}, +}; use crate::thread::AgentThread; use futures::future::BoxFuture; -use gpui_kit::{Context, WeakEntity}; -use nocterm_ai::{images::PromptImage, session::Ticket}; +use gpui_kit::{Context, Task, WeakEntity}; +use nocterm_ai::session::Ticket; + +/// The result drops before its permit if the view never receives it. +pub(super) type PreparedImageWork = ( + Result, + crate::image_deps::ImageWorkPermit, +); pub(super) struct ImagePreparation { binding: ComposerBinding, thread: WeakEntity, ticket: Ticket, - work: BoxFuture<'static, Result, ImageAttachError>>, - permit: crate::image_deps::ImageWorkPermit, + work: BoxFuture<'static, Result>, + reservation: crate::image_deps::ImageWorkReservation, } impl ImagePreparation { pub(super) fn new( binding: ComposerBinding, thread: WeakEntity, ticket: Ticket, - work: BoxFuture<'static, Result, ImageAttachError>>, - permit: crate::image_deps::ImageWorkPermit, + work: BoxFuture<'static, Result>, + reservation: crate::image_deps::ImageWorkReservation, ) -> Self { Self { binding, thread, ticket, work, - permit, + reservation, } } - pub(super) fn launch(self, cx: &mut Context) { + pub(super) fn launch(self, cx: &mut Context) -> Task<()> { let Self { binding, thread, ticket, work, - permit, + reservation, } = self; let future = cx.background_executor().spawn(async move { - let _permit = permit; - work.await + let permit = reservation.acquire().await; + (work.await, permit) }); cx.spawn(async move |panel, cx| { - let result = future.await; + let work = future.await; let _ = panel.update(cx, |panel, cx| { - panel.on_composer_images_prepared(binding, thread, ticket, result, cx) + panel.on_composer_images_prepared(binding, thread, ticket, work, cx) }); }) - .detach(); } } diff --git a/crates/agent/src/panel/images.rs b/crates/agent/src/panel/images.rs index a9cda4ce..e82c50f3 100644 --- a/crates/agent/src/panel/images.rs +++ b/crates/agent/src/panel/images.rs @@ -1,9 +1,44 @@ //! Image preparation runs outside the UI and belongs to one composer revision. +use super::image_pipeline::PreviewSource; use nocterm_ai::images::{ - ImageCollectionBudget, ImageCollectionError, MAX_IMAGE_BYTES, PromptImage, PromptImageError, + DecodedPreviewSource, ImageCollectionBudget, ImageCollectionError, ImageInspector, PromptImage, + PromptImageError, }; use std::{io::Read as _, path::PathBuf}; +pub(super) struct PreparedImages { + images: Vec, + preview: Option, +} + +type PreparedPreview = (PreviewSource, Box); + +impl PreparedImages { + pub(super) fn single( + bytes: Vec, + inspector: &dyn ImageInspector, + ) -> Result { + let (image, preview) = inspect_for_preview(bytes, inspector)?; + Ok(Self { + images: vec![image], + preview, + }) + } + + pub(super) fn into_parts(self) -> (Vec, Option) { + (self.images, self.preview) + } +} + +impl From> for PreparedImages { + fn from(images: Vec) -> Self { + Self { + images, + preview: None, + } + } +} + /// Why attaching images to the composer failed. #[derive(Debug, thiserror::Error)] pub(super) enum ImageAttachError { @@ -19,28 +54,119 @@ pub(super) enum ImageAttachError { Busy, } +pub(super) fn admit_paste( + bytes: Vec, + images: &[PromptImage], +) -> Result, ImageAttachError> { + ImageCollectionBudget::remaining(images)?.admit(bytes.len())?; + nocterm_ai::images::check_source_size(bytes.len()).map_err(PromptImageError::from)?; + Ok(bytes) +} + +pub(super) fn admit_paths( + paths: Vec, + images: &[PromptImage], +) -> Result<(Vec, ImageCollectionBudget), ImageCollectionError> { + let budget = ImageCollectionBudget::remaining(images)?; + budget.check_count(paths.len())?; + Ok((paths, budget)) +} + pub(super) fn read_images( paths: Vec, - inspector: &dyn nocterm_ai::images::ImageInspector, + inspector: &dyn ImageInspector, mut budget: ImageCollectionBudget, -) -> Result, ImageAttachError> { +) -> Result { budget.check_count(paths.len())?; - paths - .into_iter() - .map(|path| { - let mut file = std::fs::File::open(path)?; - let mut bytes = Vec::new(); - std::io::Read::take(&mut file, (MAX_IMAGE_BYTES + 1) as u64).read_to_end(&mut bytes)?; - budget.admit(bytes.len())?; - Ok(PromptImage::validate(bytes, inspector)?) - }) - .collect() + let Some((last, preceding)) = paths.split_last() else { + return Ok(Vec::new().into()); + }; + let mut read = |path: &PathBuf| read_image(std::fs::File::open(path)?, &mut budget); + if preceding.is_empty() { + return PreparedImages::single(read(last)?, inspector); + } + let mut images = Vec::with_capacity(paths.len()); + for path in preceding { + images.push(PromptImage::validate(read(path)?, inspector)?); + } + let (image, preview) = inspect_for_preview(read(last)?, inspector)?; + images.push(image); + Ok(PreparedImages { images, preview }) +} + +fn inspect_for_preview( + bytes: Vec, + inspector: &dyn ImageInspector, +) -> Result<(PromptImage, Option), ImageAttachError> { + let (image, preview) = PromptImage::validate_for_preview(bytes, inspector)?; + let preview = preview.map(|preview| (PreviewSource::prompt(&image), preview)); + Ok((image, preview)) +} + +fn read_image( + source: impl std::io::Read, + budget: &mut ImageCollectionBudget, +) -> Result, ImageAttachError> { + let mut bytes = Vec::new(); + // Keep one byte of evidence for the existing collection and image-size checks. + source + .take((budget.max_source_bytes() + 1) as u64) + .read_to_end(&mut bytes)?; + budget.admit(bytes.len())?; + Ok(bytes) } #[cfg(test)] mod tests { use super::*; + use nocterm_ai::images::{MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES}; use nocterm_ai::testing::ScriptedImageCodec; + use std::io::Cursor; + + #[test] + fn collection_rejection_reads_only_one_byte_past_remaining_capacity() { + let remaining = 4096; + let mut budget = ImageCollectionBudget::remaining(&[]).unwrap(); + budget.admit(MAX_TOTAL_IMAGE_BYTES - remaining).unwrap(); + let mut source = Cursor::new(vec![19; remaining + 2]); + assert!(matches!( + read_image(&mut source, &mut budget), + Err(ImageAttachError::Collection(ImageCollectionError)) + )); + assert_eq!(source.position(), (remaining + 1) as u64); + + let original = vec![19; remaining]; + assert_eq!( + read_image(original.as_slice(), &mut budget).unwrap(), + original + ); + } + + #[test] + fn per_image_rejection_retains_its_error_when_the_collection_has_room() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("oversized.png"); + std::fs::File::create(&path) + .unwrap() + .set_len((MAX_IMAGE_BYTES + 2) as u64) + .unwrap(); + let codec = ScriptedImageCodec::default(); + let budget = ImageCollectionBudget::remaining(&[]).unwrap(); + assert!(matches!( + read_images(vec![path.clone()], &codec, budget), + Err(ImageAttachError::Invalid(PromptImageError::TooLarge)) + )); + + let mut budget = budget; + budget + .admit(MAX_TOTAL_IMAGE_BYTES - MAX_IMAGE_BYTES) + .unwrap(); + assert!(matches!( + read_images(vec![path], &codec, budget), + Err(ImageAttachError::Collection(ImageCollectionError)) + )); + assert!(codec.requests().is_empty()); + } #[test] fn excessive_selection_is_refused_before_opening_any_path() { let codec = ScriptedImageCodec::default(); diff --git a/crates/agent/src/panel/lifecycle.rs b/crates/agent/src/panel/lifecycle.rs index 88fa18f4..7946f9ed 100644 --- a/crates/agent/src/panel/lifecycle.rs +++ b/crates/agent/src/panel/lifecycle.rs @@ -68,6 +68,7 @@ impl AgentPanel { self.reset_chat_view(cx); } if !removed.is_empty() { + self.layout.parts().invalidate_history(cx); self.on_history_catalog_changed(cx); } } @@ -195,8 +196,11 @@ impl AgentPanel { } } pub(super) fn set_pinned(&mut self, id: EntityId, pinned: bool, cx: &mut Context) { - if let Some(thread) = self.chats.find(id).cloned() { + if let Some(thread) = self.chats.find(id).cloned() + && thread.read(cx).document().pinned() != pinned + { thread.update(cx, |thread, cx| thread.set_pinned(pinned, cx)); + self.layout.parts().invalidate_history(cx); } } pub(super) fn start_rename( @@ -210,6 +214,7 @@ impl AgentPanel { }; let title = thread.read(cx).title(); self.history.begin_rename(id, title.to_string(), window, cx); + self.layout.parts().invalidate_history(cx); cx.notify(); } pub(super) fn finish_rename( @@ -508,6 +513,10 @@ impl AgentPanel { } /// Redraws the history once the changes of the next frames have arrived. fn schedule_history_redraw(&mut self, cx: &mut Context) { + // Without an open chat, history is the whole panel regardless of the split setting. + if !self.layout.history() && self.current().is_some() { + return; + } let Some(ticket) = self.notices.request_redraw() else { return; }; @@ -548,7 +557,7 @@ impl AgentPanel { pub(super) fn refresh_other_windows(&mut self, cx: &mut Context) { let chats = self.chats.held_elsewhere(cx); if self.history.others_mut().set(chats, cx) { - self.schedule_history_redraw(cx); + self.layout.parts().invalidate_history(cx); } } /// A chat another window holds changed: its row follows on the coalesced redraw. diff --git a/crates/agent/src/panel/message_actions.rs b/crates/agent/src/panel/message_actions.rs index 1a21317b..afab4340 100644 --- a/crates/agent/src/panel/message_actions.rs +++ b/crates/agent/src/panel/message_actions.rs @@ -14,40 +14,103 @@ use nocterm_ai::model::content::Content; use nocterm_ai::thread::Entry; use nocterm_ui::IconName; -use super::AgentPanel; +use super::{AgentPanel, message_list::ActiveListBinding}; /// The group a message row joins, so its actions show on hover. pub(super) const MESSAGE_GROUP: &str = "agent-message-row"; -/// The text a message copies as. -pub(super) fn message_text(entry: &Entry) -> Option { - match entry { - Entry::User(parts) => Some( - parts - .iter() - .filter_map(|part| match part { - Content::Text(text) => Some(text.text.as_str()), - _ => None, - }) - .collect::>() - .join("\n"), - ), - Entry::Agent(text) => Some(text.clone()), - _ => None, +pub(super) enum CopyExtent { + UserParts(usize), + AgentBytes(usize), +} + +/// A row's copyable prefix, scoped to the transcript that drew its action. +pub(super) struct MessageCopy { + binding: Option, + generation: u64, + index: usize, + extent: CopyExtent, +} +impl MessageCopy { + pub(super) fn new( + binding: Option, + generation: u64, + index: usize, + extent: CopyExtent, + ) -> Self { + Self { + binding, + generation, + index, + extent, + } + } + + fn copy(&self, panel: &AgentPanel, cx: &mut Context) { + let Some(thread) = self + .binding + .as_ref() + .and_then(|binding| panel.messages.thread_for(binding)) + else { + return; + }; + let thread = thread.read(cx); + if thread.document().transcript_generation() != self.generation { + return; + } + let Some(entry) = thread.transcript().entries.get(self.index) else { + return; + }; + // Agent text and user parts can append within a generation. Keep + // the extent the button had when drawn, including unrevealed text. + let text = match (&self.extent, entry) { + (CopyExtent::UserParts(count), Entry::User(parts)) => { + let Some(parts) = parts.get(..*count) else { + return; + }; + parts + .iter() + .filter_map(|part| match part { + Content::Text(text) => Some(text.text.as_str()), + _ => None, + }) + .collect::>() + .join("\n") + } + (CopyExtent::AgentBytes(bytes), Entry::Agent(text)) => { + let Some(prefix) = text.get(..*bytes) else { + return; + }; + prefix.to_owned() + } + _ => return, + }; + cx.write_to_clipboard(ClipboardItem::new_string(text)); } } /// `seconds` since the epoch as local time: the clock time today, the date /// as well on other days. pub(super) fn sent_at(seconds: u64) -> String { - use chrono::{Local, TimeZone as _}; - let Some(time) = Local.timestamp_opt(seconds as i64, 0).single() else { + sent_at_in_zone( + seconds, + jiff::Timestamp::now(), + &jiff::tz::TimeZone::system(), + ) +} + +fn sent_at_in_zone(seconds: u64, now: jiff::Timestamp, zone: &jiff::tz::TimeZone) -> String { + let Some(time) = i64::try_from(seconds) + .ok() + .and_then(|seconds| jiff::Timestamp::from_second(seconds).ok()) + else { return String::new(); }; - if time.date_naive() == Local::now().date_naive() { - time.format("%H:%M").to_string() + let time = zone.to_datetime(time); + if time.date() == zone.to_datetime(now).date() { + time.strftime("%H:%M").to_string() } else { - time.format("%-d %b %Y, %H:%M").to_string() + time.strftime("%-d %b %Y, %H:%M").to_string() } } @@ -66,23 +129,20 @@ pub(super) fn escape_markdown(text: &str) -> String { pub(super) struct MessageRowActions { thread: Option, - index: usize, - text: String, + copy: MessageCopy, time: Option, user: bool, } impl MessageRowActions { pub(super) fn new( thread: Option, - index: usize, - text: String, + copy: MessageCopy, time: Option, user: bool, ) -> Self { Self { thread, - index, - text, + copy, time, user, } @@ -90,11 +150,11 @@ impl MessageRowActions { pub(super) fn render(self, cx: &Context) -> AnyElement { let Self { thread, - index, - text, + copy, time, user, } = self; + let index = copy.index; let muted = cx.theme().muted_foreground; h_flex() .id(("message-actions", index)) @@ -109,9 +169,7 @@ impl MessageRowActions { .xsmall() .icon(IconName::Copy) .tooltip("Copy") - .on_click(move |_, _, cx| { - cx.write_to_clipboard(ClipboardItem::new_string(text.clone())) - }), + .on_click(cx.listener(move |panel, _, _, cx| copy.copy(panel, cx))), ) .when_some(thread, |row, thread| { row.child( @@ -140,7 +198,42 @@ impl MessageRowActions { #[cfg(test)] mod tests { - use super::escape_markdown; + use super::{escape_markdown, sent_at_in_zone}; + + #[test] + fn message_dates_follow_the_local_day_and_historical_offset() { + let zone = jiff::tz::TimeZone::get("America/New_York").unwrap(); + let now = "2024-03-10T12:00:00Z".parse().unwrap(); + let before: jiff::Timestamp = "2024-03-10T06:59:00Z".parse().unwrap(); + let after: jiff::Timestamp = "2024-03-10T07:01:00Z".parse().unwrap(); + let yesterday: jiff::Timestamp = "2024-03-10T04:59:00Z".parse().unwrap(); + assert_eq!( + sent_at_in_zone(before.as_second() as u64, now, &zone), + "01:59" + ); + assert_eq!( + sent_at_in_zone(after.as_second() as u64, now, &zone), + "03:01" + ); + assert_eq!( + sent_at_in_zone(yesterday.as_second() as u64, now, &zone), + "9 Mar 2024, 23:59" + ); + assert_eq!(sent_at_in_zone(u64::MAX, now, &zone), ""); + } + + #[test] + fn message_dates_handle_repeated_local_time_after_dst() { + let zone = jiff::tz::TimeZone::get("America/New_York").unwrap(); + let now = "2024-11-03T12:00:00Z".parse().unwrap(); + for stamp in ["2024-11-03T05:30:00Z", "2024-11-03T06:30:00Z"] { + let stamp: jiff::Timestamp = stamp.parse().unwrap(); + assert_eq!( + sent_at_in_zone(stamp.as_second() as u64, now, &zone), + "01:30" + ); + } + } #[test] fn escaped_text_keeps_punctuation_and_lines() { diff --git a/crates/agent/src/panel/message_list.rs b/crates/agent/src/panel/message_list.rs index 79f5815a..c192b878 100644 --- a/crates/agent/src/panel/message_list.rs +++ b/crates/agent/src/panel/message_list.rs @@ -2,11 +2,12 @@ use super::{ AgentPanel, image_pipeline::{ - CompletedPreview, ImageKey, ImagePipeline, PreviewSource, PreviewState, PreviewTicket, + CompletedPreview, ImageKey, ImagePipeline, PreviewRegions, PreviewSource, PreviewState, + PreviewTicket, }, message_markdown::MessageMarkdown, navigation::MessageNavigation, - stream::StreamReveal, + stream::{REVEAL_INTERVAL, StreamReveal}, }; use gpui_kit::{ App, AppContext as _, Context, Entity, EntityId, Task, WeakEntity, @@ -98,6 +99,12 @@ impl MessageList { pub(super) fn thread(&self) -> Option> { self.thread.as_ref()?.upgrade() } + pub(super) fn thread_for( + &self, + binding: &ActiveListBinding, + ) -> Option> { + self.current(binding).then(|| self.thread()).flatten() + } fn current(&self, binding: &ActiveListBinding) -> bool { self.binding .as_ref() @@ -110,7 +117,7 @@ impl MessageList { self.row_count = 0; self.navigation.clear(); self.expanded.clear(); - self.pipeline.clear(); + self.clear_previews(cx); self.binding = None; self.thread = None; self.markdown.clear(); @@ -118,18 +125,28 @@ impl MessageList { pub(super) fn observe_rows( &mut self, chat: EntityId, + generation: u64, entries: &[Entry], dirty: &[usize], live: bool, reduced: bool, ) -> MessageRows { - self.markdown.invalidate(dirty); + let replaced = self.markdown.observe_transcript(generation); let previous = self.row_count; self.row_count = entries.len(); - self.navigation.observe(chat, entries, dirty); - let mut changed = dirty.to_vec(); - changed.extend(entries.len()..self.row_count.min(previous)); - changed.extend(self.reveal.observe(entries, dirty, live, reduced)); + let changed = if replaced { + self.navigation.clear(); + self.navigation.observe(chat, entries, &[]); + self.tick = None; + self.reveal = StreamReveal::default(); + self.reveal.observe(entries, &[], live, reduced); + (0..entries.len().min(previous)).collect() + } else { + self.navigation.observe(chat, entries, dirty); + let mut changed = dirty.to_vec(); + changed.extend(self.reveal.observe(entries, dirty, live, reduced)); + changed + }; MessageRows { previous, count: self.row_count, @@ -155,12 +172,14 @@ impl MessageList { binding: &ActiveListBinding, entries: &[Entry], reduced: bool, + elapsed: Duration, ) -> Option> { if !self.current(binding) { return None; } self.tick = None; - Some(self.reveal.advance(entries, reduced)) + let changed = self.reveal.advance(entries, reduced, elapsed); + (!changed.is_empty()).then_some(changed) } pub(super) fn apply_reveal(&mut self, changed: Vec, cx: &mut Context) { self.remeasure_rows(changed, cx); @@ -173,11 +192,13 @@ impl MessageList { let Some(binding) = self.binding() else { return; }; + let executor = cx.background_executor().clone(); + let scheduled = executor.now(); + let timer = executor.timer(REVEAL_INTERVAL); self.tick = Some(cx.spawn(async move |panel, cx| { - cx.background_executor() - .timer(Duration::from_millis(16)) - .await; - let _ = panel.update(cx, |panel, cx| panel.on_reveal_tick(binding, cx)); + timer.await; + let elapsed = executor.now().saturating_duration_since(scheduled); + let _ = panel.update(cx, |panel, cx| panel.on_reveal_tick(binding, elapsed, cx)); })); } fn remeasure_rows(&self, mut rows: Vec, cx: &mut Context) { @@ -225,8 +246,8 @@ impl MessageList { pub(super) fn revealed_slice<'a>(&self, row: usize, text: &'a str) -> &'a str { self.reveal.slice(row, text) } - pub(super) fn markdown_current(&self, row: usize, source_len: usize) -> bool { - self.markdown.current(row, source_len) + pub(super) fn markdown_source_len(&self, row: usize) -> Option { + self.markdown.source_len(row) } pub(super) fn revealing(&self) -> bool { self.reveal.pending() @@ -235,11 +256,10 @@ impl MessageList { pub(super) fn prepare_markdown( &mut self, row: usize, - text: String, - source_len: usize, + update: super::message_markdown::MarkdownUpdate, cx: &mut Context, ) { - self.markdown.prepare(row, text, source_len, cx); + self.markdown.prepare(row, update, cx); } pub(super) fn markdown(&self, row: usize) -> Option<&Entity> { self.markdown.state(row) @@ -247,11 +267,21 @@ impl MessageList { pub(super) fn preview_state(&self, key: &ImageKey) -> Option<&PreviewState> { self.pipeline.state(key) } - pub(super) fn has_preview(&self, key: &ImageKey) -> bool { - self.pipeline.contains_key(key) + pub(super) fn request_preview( + &mut self, + source: &PreviewSource, + row: Option, + cx: &mut App, + ) -> Option { + self.pipeline.request(source, row, cx) } - pub(super) fn request_preview(&mut self, source: PreviewSource) -> Option { - self.pipeline.request(source) + pub(super) fn clear_previews(&mut self, cx: &mut App) { + self.pipeline.clear(cx); + } + pub(super) fn reusable_previews( + &self, + ) -> Vec> { + self.pipeline.reusable_previews() } pub(super) fn install_preview_task(&mut self, ticket: PreviewTicket, task: Task<()>) { self.pipeline.install_task(ticket, task); @@ -260,17 +290,20 @@ impl MessageList { &mut self, binding: &ActiveListBinding, ticket: PreviewTicket, - row: Option, image: Option, cx: &mut Context, - ) -> bool { - if !self.current(binding) || !self.pipeline.complete(ticket, image) { - return false; - } - if let Some(row) = row { - self.remeasure_rows(vec![row], cx); + ) -> Option { + if !self.current(binding) { + return None; } - true + let (rows, regions) = self.pipeline.complete(ticket, image)?; + self.remeasure_rows( + rows.into_iter() + .filter(|&row| row < self.row_count) + .collect(), + cx, + ); + Some(regions) } pub(super) fn inspector(&self) -> Arc { self.pipeline.inspector() @@ -278,9 +311,6 @@ impl MessageList { pub(super) fn image_deps(&self) -> crate::ImageDeps { self.pipeline.image_deps() } - pub(super) fn admit_image_work(&self) -> Option { - self.pipeline.admit_work() - } pub(super) fn scroller(&self, cx: &mut Context) -> MessageScroller { MessageScroller::new( "agent-transcript", diff --git a/crates/agent/src/panel/message_markdown.rs b/crates/agent/src/panel/message_markdown.rs index 06ba0e8b..02376403 100644 --- a/crates/agent/src/panel/message_markdown.rs +++ b/crates/agent/src/panel/message_markdown.rs @@ -1,7 +1,12 @@ //! Parsed Markdown of the visible chat's agent messages and reasoning, kept per row: a //! row scrolled back into view keeps its parse, and text streamed into a row parses //! only what was appended instead of the whole message again. -use super::{AgentPanel, message_list::MessageList, parts::PartKind, widgets::safe_markdown}; +use super::{ + AgentPanel, + message_list::MessageList, + parts::PartKind, + widgets::{safe_markdown, safe_markdown_extension}, +}; use gpui_kit::{AppContext as _, Context, Entity, Subscription, component::text::TextViewState}; use nocterm_ai::thread::Entry; use std::collections::HashMap; @@ -13,9 +18,15 @@ struct RowMarkdown { _parsed: Subscription, } +pub(super) enum MarkdownUpdate { + Append(String, usize), + Full(String, usize), +} + #[derive(Default)] pub(super) struct MessageMarkdown { rows: HashMap, + generation: Option, } impl MessageMarkdown { /// The Markdown a row draws now: an agent message as revealed so far, or expanded @@ -24,37 +35,54 @@ impl MessageMarkdown { entry: &Entry, row: usize, messages: &MessageList, - ) -> Option<(String, usize)> { + ) -> Option { let source = match entry { Entry::Agent(text) => messages.revealed_slice(row, text), Entry::Thought(text) if messages.expanded(row) => text, _ => return None, }; - if messages.markdown_current(row, source.len()) { - return None; + if let Some(previous) = messages.markdown_source_len(row) { + if previous == source.len() { + return None; + } + if let Some(extension) = safe_markdown_extension(source, previous) { + return Some(MarkdownUpdate::Append(extension, source.len())); + } } - Some((safe_markdown(source), source.len())) + Some(MarkdownUpdate::Full(safe_markdown(source), source.len())) } - pub(super) fn current(&self, row: usize, source_len: usize) -> bool { - self.rows - .get(&row) - .is_some_and(|kept| kept.source_len == Some(source_len)) + pub(super) fn source_len(&self, row: usize) -> Option { + self.rows.get(&row)?.source_len } - pub(super) fn invalidate(&mut self, dirty: &[usize]) { - for row in dirty { - if let Some(kept) = self.rows.get_mut(row) { + pub(super) fn observe_transcript(&mut self, generation: u64) -> bool { + let previous = self.generation.replace(generation); + let replaced = previous.is_some_and(|previous| previous != generation); + if replaced { + for kept in self.rows.values_mut() { kept.source_len = None; } } + replaced } /// Shows `text` in the row's state, appending when it extends what the row showed. pub(super) fn prepare( &mut self, row: usize, - text: String, - source_len: usize, + update: MarkdownUpdate, cx: &mut Context, ) { + let (text, source_len) = match update { + MarkdownUpdate::Append(appended, source_len) => { + if let Some(kept) = self.rows.get_mut(&row) { + kept.source_len = Some(source_len); + kept.state + .update(cx, |state, cx| state.push_str(&appended, cx)); + kept.text.push_str(&appended); + } + return; + } + MarkdownUpdate::Full(text, source_len) => (text, source_len), + }; if let Some(kept) = self.rows.get_mut(&row) { kept.source_len = Some(source_len); if kept.text == text { @@ -93,5 +121,6 @@ impl MessageMarkdown { } pub(super) fn clear(&mut self) { self.rows.clear(); + self.generation = None; } } diff --git a/crates/agent/src/panel/notices.rs b/crates/agent/src/panel/notices.rs index 4ca52e02..6991c98b 100644 --- a/crates/agent/src/panel/notices.rs +++ b/crates/agent/src/panel/notices.rs @@ -81,9 +81,12 @@ impl PanelNotices { { return false; } - self.redraw = None; + self.cancel_redraw(); true } + pub(super) fn cancel_redraw(&mut self) { + self.redraw = None; + } } #[cfg(test)] @@ -95,7 +98,7 @@ mod tests { let mut notices = PanelNotices::default(); let original = notices.request_redraw().unwrap(); assert!(notices.request_redraw().is_none()); - assert!(notices.finish_redraw(&original)); + notices.cancel_redraw(); let replacement = notices.request_redraw().unwrap(); assert!(!notices.finish_redraw(&original)); assert!(notices.request_redraw().is_none()); diff --git a/crates/agent/src/panel/other_windows.rs b/crates/agent/src/panel/other_windows.rs index e298abbb..4ff53167 100644 --- a/crates/agent/src/panel/other_windows.rs +++ b/crates/agent/src/panel/other_windows.rs @@ -1,7 +1,7 @@ //! The chats other windows hold, which this window's history lists without holding them. //! -//! The runtime names them; each is observed so that its row follows it — its title, and the -//! spinner while its agent works. Only weak handles are kept: a chat lives as long as its own +//! The runtime names them; each is observed so that its row follows its title and working +//! status. Only weak handles are kept: a chat lives as long as its own //! window keeps it. A burst of changes (a window adopting its saved chats) refreshes the list //! once. use super::AgentPanel; @@ -47,7 +47,7 @@ impl OtherWindowChats { .iter() .filter_map(WeakEntity::upgrade) .filter(|chat| { - let chat = chat.read(cx); + let chat = chat.read_untracked(cx); !chat.history_entries().is_empty() || chat.archive_summary().is_some_and(|row| row.has_content) }) diff --git a/crates/agent/src/panel/parts.rs b/crates/agent/src/panel/parts.rs index ddb4066c..01cbf57c 100644 --- a/crates/agent/src/panel/parts.rs +++ b/crates/agent/src/panel/parts.rs @@ -6,7 +6,7 @@ //! The footer (approvals, status, queue, commands and composer) is cached to its //! content while its pickers are closed. Open pickers keep their interaction state //! live instead of reusing a content-sized cache's deferred popup. -use super::AgentPanel; +use super::{AgentPanel, history::HistoryViewport}; use gpui_kit::{ App, AppContext as _, Context, Entity, IntoElement, Render, StyleRefinement, Styled, WeakEntity, Window, div, @@ -16,8 +16,8 @@ use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PartKind { Transcript, - History, Footer, + Queue, } pub(super) struct PanelPart { @@ -33,10 +33,23 @@ impl Render for PanelPart { } } +struct HistoryPart { + panel: WeakEntity, + viewport: HistoryViewport, +} +impl Render for HistoryPart { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + self.panel + .update(cx, |panel, cx| panel.render_history(&mut self.viewport, cx)) + .unwrap_or_else(|_| div().into_any_element()) + } +} + pub(super) struct PanelParts { transcript: Entity, - history: Entity, + history: Entity, footer: Entity, + queue: Entity, transcript_seen: Option, history_seen: Option, } @@ -47,10 +60,18 @@ impl PanelParts { let panel = panel.clone(); cx.new(|_| PanelPart { panel, kind }) }; + let transcript = part(PartKind::Transcript); + let footer = part(PartKind::Footer); + let queue = part(PartKind::Queue); + let history = cx.new(|_| HistoryPart { + panel, + viewport: HistoryViewport::default(), + }); Self { - transcript: part(PartKind::Transcript), - history: part(PartKind::History), - footer: part(PartKind::Footer), + transcript, + history, + footer, + queue, transcript_seen: None, history_seen: None, } @@ -86,17 +107,26 @@ impl PanelParts { .into_any_element() } } + /// Keep a static queue available to the status animation's footer redraws. + pub(super) fn queue(&self) -> impl IntoElement + use<> { + self.queue + .clone() + .cached_to_content(StyleRefinement::default().w_full()) + } /// Redraws the cached regions: the panel's state changed in a way only it knows. pub(super) fn invalidate(&self, cx: &mut App) { self.transcript.update(cx, |_, cx| cx.notify()); - self.history.update(cx, |_, cx| cx.notify()); - self.footer.update(cx, |_, cx| cx.notify()); + self.invalidate_history(cx); + self.notify(PartKind::Footer, cx); } pub(super) fn notify(&self, kind: PartKind, cx: &mut App) { let part = match kind { PartKind::Transcript => &self.transcript, - PartKind::History => &self.history, - PartKind::Footer => &self.footer, + PartKind::Footer => { + self.queue.update(cx, |_, cx| cx.notify()); + &self.footer + } + PartKind::Queue => &self.queue, }; part.update(cx, |_, cx| cx.notify()); } @@ -114,9 +144,15 @@ impl PanelParts { /// a stamp (a search matches transcripts) it always redraws. pub(super) fn history_changed(&self, stamp: Option, cx: &mut App) { if stamp.is_none() || self.history_seen != stamp { - self.notify(PartKind::History, cx); + self.invalidate_history(cx); } } + pub(super) fn invalidate_history(&self, cx: &mut App) { + self.history.update(cx, |history, cx| { + history.viewport.invalidate(); + cx.notify(); + }); + } pub(super) fn drew_history(&mut self, stamp: Option) { self.history_seen = stamp; } @@ -128,6 +164,7 @@ pub(super) fn transcript_stamp(thread: &crate::thread::AgentThread) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); let transcript = thread.transcript(); ( + thread.document().transcript_generation(), transcript.entries.len(), thread.session_generating(), thread.session_accepts_updates(), diff --git a/crates/agent/src/panel/preview_operation.rs b/crates/agent/src/panel/preview_operation.rs index 7f49f972..4313feda 100644 --- a/crates/agent/src/panel/preview_operation.rs +++ b/crates/agent/src/panel/preview_operation.rs @@ -1,18 +1,22 @@ //! Finite thumbnail work retains original list/row generation and installs into MessageList. -use super::entries::PreviewError; use super::{ AgentPanel, image_pipeline::{CompletedPreview, PreviewSource, PreviewTicket}, message_list::{ActiveListBinding, MessageList}, }; use gpui_kit::{Context, Task}; -use nocterm_ai::model::content::Content; +use nocterm_ai::{images::DecodedPreviewSource, model::content::Content}; pub(super) struct PreviewOperation { binding: ActiveListBinding, ticket: PreviewTicket, - row: Option, - source: PreviewSource, - images: crate::ImageDeps, + work: PreviewWork, +} +enum PreviewWork { + Source(PreviewSource, crate::ImageDeps), + Decoded( + Box, + crate::image_deps::ImageWorkPermit, + ), } impl PreviewOperation { pub(super) fn cached( @@ -23,41 +27,67 @@ impl PreviewOperation { ) -> gpui_kit::AnyElement { let key = source.key(); if let Some(binding) = messages.binding() - && let Some(ticket) = messages.request_preview(source.clone()) + && let Some(ticket) = messages.request_preview(&source, row, cx) { let task = Self { binding, ticket, - row, - source, - images: messages.image_deps(), + work: PreviewWork::Source(source, messages.image_deps()), } - .launch(cx); + .launch(messages, cx); messages.install_preview_task(ticket, task); } super::entries::EntryRenderer::image(messages.preview_state(&key)) } - fn launch(self, cx: &mut Context) -> Task<()> { + pub(super) fn from_decoded( + messages: &mut MessageList, + source: &PreviewSource, + decoded: Box, + permit: crate::image_deps::ImageWorkPermit, + cx: &mut Context, + ) { + let work = PreviewWork::Decoded(decoded, permit); + if let Some(binding) = messages.binding() + && let Some(ticket) = messages.request_preview(source, None, cx) + { + let task = Self { + binding, + ticket, + work, + } + .launch(messages, cx); + messages.install_preview_task(ticket, task); + } + } + fn launch(self, messages: &MessageList, cx: &mut Context) -> Task<()> { let Self { binding, ticket, - row, - source, - images, + work, } = self; + let reusable = messages.reusable_previews(); + let renderer = cx.svg_renderer(); let future = cx.background_executor().spawn(async move { - let _permit = images.work().await; - let bytes = source.decode()?; let bounds = nocterm_ai::images::PreviewBounds::new(640, 640)?; - let preview = images.thumbnailer().thumbnail(bytes, bounds)?; - // Supplied previews retain the same pure size/format contract. - let preview = nocterm_ai::images::EncodedPreview::new(preview.bytes().clone(), bounds)?; - Ok::<_, PreviewError>(CompletedPreview::from_encoded(preview)) + let (preview, _permit) = match work { + PreviewWork::Source(source, images) => { + let permit = images.reserve_preview().acquire().await; + ( + images + .thumbnailer() + .render_preview(source.decode()?, bounds)?, + permit, + ) + } + PreviewWork::Decoded(image, permit) => (image.render_preview(bounds)?, permit), + }; + preview.check_bounds(bounds)?; + CompletedPreview::from_preview(preview, renderer, &reusable) }); cx.spawn(async move |panel, cx| { let result = future.await; let _ = panel.update(cx, |panel, cx| { - panel.on_preview_completed(binding, ticket, row, result.ok(), cx) + panel.on_preview_completed(binding, ticket, result.ok(), cx) }); }) } @@ -74,7 +104,7 @@ impl PreviewOperation { .composer() .images() .iter() - .map(|image| PreviewSource::Original(image.shared_bytes())) + .map(PreviewSource::prompt) .collect::>(); if previews.is_empty() { return Vec::new(); @@ -88,10 +118,10 @@ impl PreviewOperation { impl PreviewOperation { pub(super) fn queued_previews( - messages: &mut MessageList, prompts: &[crate::thread::QueuedPrompt], - cx: &mut Context, + cx: &Context, ) -> Vec> { + let panel = cx.weak_entity(); prompts .iter() .map(|prompt| { @@ -103,11 +133,9 @@ impl PreviewOperation { let Content::Image(image) = block else { return None; }; - Some(Self::cached( - messages, + Some(queue_image( PreviewSource::Encoded(image.data.clone()), - None, - cx, + panel.clone(), )) }) .collect() @@ -115,3 +143,40 @@ impl PreviewOperation { .collect() } } + +fn queue_image( + source: PreviewSource, + panel: gpui_kit::WeakEntity, +) -> gpui_kit::AnyElement { + use gpui_kit::{AvailableSpace, IntoElement as _, Styled as _, canvas, size}; + // The queue measures all rows. Decode only chips that reach its clipped viewport. + canvas( + move |bounds, window, cx| { + if !bounds.intersects(&window.content_mask().bounds) { + return None; + } + let mut element = panel + .update(cx, |panel, cx| { + PreviewOperation::cached(&mut panel.messages, source, None, cx) + }) + .ok()?; + element.layout_as_root( + size( + AvailableSpace::Definite(bounds.size.width), + AvailableSpace::Definite(bounds.size.height), + ), + window, + cx, + ); + element.prepaint_at(bounds.origin, window, cx); + Some(element) + }, + |_, element, window, cx| { + if let Some(mut element) = element { + element.paint(window, cx); + } + }, + ) + .size_full() + .into_any_element() +} diff --git a/crates/agent/src/panel/queue_image_preparation.rs b/crates/agent/src/panel/queue_image_preparation.rs index 162c4f94..1de565bf 100644 --- a/crates/agent/src/panel/queue_image_preparation.rs +++ b/crates/agent/src/panel/queue_image_preparation.rs @@ -40,8 +40,9 @@ impl QueueImagePreparation { saved, images, } = self; + let reservation = images.reserve_edit(); let future = cx.background_executor().spawn(async move { - let _permit = images.work().await; + let _permit = reservation.acquire().await; let inspector = images.inspector(); let mut budget = nocterm_ai::images::ImageCollectionBudget::remaining(&[])?; budget.check_count( diff --git a/crates/agent/src/panel/stream.rs b/crates/agent/src/panel/stream.rs index b132e65a..c3122143 100644 --- a/crates/agent/src/panel/stream.rs +++ b/crates/agent/src/panel/stream.rs @@ -1,6 +1,27 @@ //! Display-only reveal visits changed rows and the live backlog, never the whole history. use nocterm_ai::thread::Entry; -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + time::Duration, +}; + +pub(super) const REVEAL_INTERVAL: Duration = Duration::from_millis(16); + +fn advance_prefix(text: &str, mut end: usize, intervals: u128) -> usize { + // Only the newest prefix is published when several animation steps are due. + for _ in 0..intervals { + if end == text.len() { + break; + } + let remaining = text.len() - end; + end += remaining.div_ceil(6).max(12).min(remaining); + while !text.is_char_boundary(end) { + end += 1; + } + } + end +} + #[derive(Default)] pub(super) struct StreamReveal { bytes: HashMap, @@ -55,7 +76,13 @@ impl StreamReveal { } changed } - pub(super) fn advance(&mut self, entries: &[Entry], reduced: bool) -> Vec { + pub(super) fn advance( + &mut self, + entries: &[Entry], + reduced: bool, + elapsed: Duration, + ) -> Vec { + let intervals = (elapsed.as_nanos() / REVEAL_INTERVAL.as_nanos()).max(1); let mut changed = Vec::with_capacity(self.backlog.len()); self.backlog.retain(|&index| { let Some(Entry::Agent(text)) = entries.get(index) else { @@ -65,16 +92,15 @@ impl StreamReveal { .bytes .get_mut(&index) .expect("backlog owns reveal position"); - let mut end = if reduced { + let end = if reduced { text.len() } else { - (*shown + (text.len() - *shown).div_ceil(6).max(12)).min(text.len()) + advance_prefix(text, (*shown).min(text.len()), intervals) }; - while !text.is_char_boundary(end) { - end += 1; + if end != *shown { + *shown = end; + changed.push(index); } - *shown = end; - changed.push(index); end < text.len() }); changed @@ -124,14 +150,36 @@ mod tests { assert!(reveal.pending()); } assert_eq!(reveal.text(2000, full), initial); - reveal.advance(&entries, false); + reveal.advance(&entries, false, REVEAL_INTERVAL); assert!(!reveal.text(2000, full).is_empty()); assert!(reveal.text(2000, full).len() < full.len()); for _ in 0..100 { - reveal.advance(&entries, false); + reveal.advance(&entries, false, REVEAL_INTERVAL); } assert_eq!(reveal.text(2000, full), *full); } + + #[test] + fn a_late_tick_publishes_only_the_latest_due_unicode_prefix() { + let full = "Ответ 👨‍👩‍👧‍👦 世界!\n".repeat(160); + let entries = [Entry::Agent(full.clone())]; + let mut on_time = StreamReveal::default(); + let mut delayed = StreamReveal::default(); + for reveal in [&mut on_time, &mut delayed] { + reveal.observe(&[], &[], false, false); + reveal.observe(&entries, &[0], true, false); + } + + for _ in 0..7 { + assert_eq!(on_time.advance(&entries, false, REVEAL_INTERVAL), [0]); + } + assert_eq!(delayed.advance(&entries, false, REVEAL_INTERVAL * 7), [0]); + assert_eq!(delayed.slice(0, &full), on_time.slice(0, &full)); + assert!(delayed.slice(0, &full).len() < full.len()); + assert_eq!(delayed.advance(&entries, false, Duration::MAX), [0]); + assert_eq!(delayed.slice(0, &full), full); + assert!(delayed.advance(&entries, false, REVEAL_INTERVAL).is_empty()); + } #[test] fn historical_and_reduced_motion_text_is_immediate() { let mut reveal = StreamReveal::default(); diff --git a/crates/agent/src/panel/tests/authentication.rs b/crates/agent/src/panel/tests/authentication.rs index 20a92291..6900dfb1 100644 --- a/crates/agent/src/panel/tests/authentication.rs +++ b/crates/agent/src/panel/tests/authentication.rs @@ -236,3 +236,105 @@ fn terminal_authentication_uses_host_callback_and_retries_after_cancel_or_failur .ends_with(&["--setup".into(), "$(literal_argument)".into()]) ); } + +fn report_activity( + f: &Fixture, + session: SessionId, + activity: nocterm_ai::model::session::SessionActivity, + cx: &mut TestAppContext, +) { + f.events + .try_send(AgentEvent::Session(SessionNotice::new( + session, + SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { + activity: Some(activity), + ..Default::default() + }), + ))) + .unwrap(); + cx.run_until_parked(); +} + +#[gpui_kit::test] +fn autonomous_agent_activity_shows_stop_and_returns_to_idle(cx: &mut TestAppContext) { + use nocterm_ai::model::session::SessionActivity::{Active, Idle}; + let f = fixture(cx); + new_chat(&f, cx); + let session = cx.update(|cx| { + f.panel + .read(cx) + .current() + .unwrap() + .read(cx) + .session() + .clone() + .unwrap() + }); + report_activity(&f, SessionId::new("another-session"), Active, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_none()); + }) + .unwrap(); + report_activity(&f, session.clone(), Active, cx); + report_activity(&f, session.clone(), Active, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + window.click("agent-send", cx); + }) + .unwrap(); + assert_eq!(f.commands.cancels.load(Ordering::SeqCst), 1); + assert!(f.commands.prompts.lock().unwrap().is_empty()); + report_activity(&f, session, Idle, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + // Stopped remains a status notice, but the busy indicator and stop action are gone. + assert!(window.try_find("agent-thinking").is_none()); + let thread = f.panel.read(cx).current().unwrap(); + assert_eq!(thread.read(cx).status(), "Stopped"); + assert!(!thread.read(cx).session_generating()); + window.click("agent-send", cx); + }) + .unwrap(); + assert_eq!(f.commands.cancels.load(Ordering::SeqCst), 1); +} + +#[gpui_kit::test] +fn autonomous_continuation_keeps_the_composer_busy_and_queues_the_next_message( + cx: &mut TestAppContext, +) { + use nocterm_ai::model::session::{ + PromptOutcome, + SessionActivity::{Active, Idle}, + StopReason, + }; + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let session = thread.read_with(cx, |thread, _| thread.session().clone().unwrap()); + thread.update(cx, |thread, cx| thread.send("first".into(), cx)); + cx.run_until_parked(); + report_activity(&f, session.clone(), Active, cx); + report_activity(&f, session.clone(), Idle, cx); + report_activity(&f, session.clone(), Active, cx); + f.commands + .pending + .lock() + .unwrap() + .take() + .unwrap() + .send(PromptOutcome::new(StopReason::EndTurn)) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + }) + .unwrap(); + thread.update(cx, |thread, cx| thread.send("second".into(), cx)); + cx.run_until_parked(); + assert_eq!(f.commands.prompts.lock().unwrap().len(), 1); + report_activity(&f, session, Idle, cx); + assert_eq!(f.commands.prompts.lock().unwrap().len(), 2); +} diff --git a/crates/agent/src/panel/tests/bridge_outcomes.rs b/crates/agent/src/panel/tests/bridge_outcomes.rs index 27a58403..e0cee678 100644 --- a/crates/agent/src/panel/tests/bridge_outcomes.rs +++ b/crates/agent/src/panel/tests/bridge_outcomes.rs @@ -288,3 +288,99 @@ fn a_call_the_bridge_rejected_shows_the_command_and_the_error() { assert_eq!(output.sections[0].label, "Error"); assert!(output.sections[0].text.starts_with("tool call error")); } + +fn update_dense_bridge_rows( + rows: usize, + records: usize, + repeats: usize, + cx: &mut TestAppContext, +) -> std::time::Duration { + use nocterm_ai::model::tools::{ToolChanges, ToolPatch}; + let f = fixture(cx); + f.bridge.next.store(17, Ordering::SeqCst); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let session = cx.update(|cx| thread.read(cx).session().clone().unwrap()); + let arguments = |i| json!({"index":i,"fixture":"x".repeat(1024)}); + for i in 0..rows { + update( + &f, + &session, + SessionUpdate::ToolCall(Box::new( + ToolRecord::new(format!("row-{i}"), title("codex", "fixture")) + .raw_input(arguments(i)), + )), + cx, + ); + } + for i in 0..records { + f.rejections + .try_send(nocterm_ai::BridgeRejection { + registration_id: 17, + tool: "fixture".into(), + arguments: arguments(i), + error: "fixture rejection".into(), + }) + .unwrap(); + cx.run_until_parked(); + } + let started = std::time::Instant::now(); + for i in 0..repeats { + update( + &f, + &session, + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + format!("row-{}", rows - 1), + ToolChanges::default().status(if i % 2 == 0 { + ToolStatus::Running + } else { + ToolStatus::Succeeded + }), + ))), + cx, + ); + } + let elapsed = started.elapsed(); + cx.update(|cx| { + let transcript = thread.read(cx).transcript(); + assert_eq!(transcript.entries.len(), rows); + for (i, entry) in transcript.entries.iter().enumerate() { + let Entry::Tool(call) = entry else { + panic!("tool row"); + }; + assert_eq!(call.raw_input, Some(arguments(i))); + if i < records { + let display = tool_display::ToolDisplay::from_call(call).unwrap(); + assert_eq!(display.arguments, arguments(i)); + assert!(matches!(display.outcome, Some(tool_display::ToolOutcome::Err(_)))); + } else { + assert!(tool_display::ToolDisplay::from_call(call).is_none()); + } + } + assert!(matches!(transcript.entries.last(), Some(Entry::Tool(call)) if call.status == ToolStatus::Succeeded)); + }); + elapsed +} + +#[gpui_kit::test] +fn multiple_bridge_rejections_preserve_only_the_matching_provider_rows(cx: &mut TestAppContext) { + update_dense_bridge_rows(32, 4, 4, cx); +} + +#[gpui_kit::test] +#[ignore = "manual bridge reconciliation through provider and bridge events"] +fn measure_dense_bridge_event_reconciliation(cx: &mut TestAppContext) { + use std::io::Write as _; + let rows = std::env::var("NOCTERM_PROFILE_BRIDGE_ROWS") + .unwrap_or_else(|_| "2000".into()) + .parse() + .unwrap(); + let records = 16; + let elapsed = update_dense_bridge_rows(rows, records, 100, cx); + writeln!( + std::io::stdout().lock(), + "bridge_events rows={rows} records={records} wall_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/composer.rs b/crates/agent/src/panel/tests/composer.rs index 90db8739..1c2b1fff 100644 --- a/crates/agent/src/panel/tests/composer.rs +++ b/crates/agent/src/panel/tests/composer.rs @@ -5,6 +5,7 @@ use nocterm_ai::model::session::{PromptOutcome, SessionNotice, SessionUpdate, St use nocterm_ai::model::usage::{ContextUsage, TokenTotals}; mod context_usage; +mod image_selection; mod menu_stability; #[gpui_kit::test] @@ -75,6 +76,63 @@ fn implicit_markdown_images_are_disabled_and_config_labels_show_selection() { ); assert_eq!(crate::thread::config_label(&option), "First"); } + +#[test] +fn markdown_preserves_ordinary_text_and_neutralizes_each_image_syntax() { + use crate::panel::widgets::safe_markdown; + for (source, expected) in [ + ("λ! (x < y) ![", "λ! (x < y) ["), + ("普通! a < b ", "<img src='λ'><img>"), + ("\n", "<img src='x'>\n"), + ("mixed", "![λ](x)\n", "[λ](x)<img>\n"), + ] { + let repeats = 1024 * 1024 / unit.len(); + let input = unit.repeat(repeats); + assert_eq!(safe_markdown(&input), expected.repeat(repeats)); + let start = Instant::now(); + for _ in 0..32 { + black_box(safe_markdown(black_box(&input))); + } + writeln!(std::io::stdout().lock(), "{name}: {:?}", start.elapsed()).unwrap(); + } +} + +#[test] +fn streamed_markdown_disables_images_at_every_chunk_boundary() { + use crate::panel::widgets::{safe_markdown, safe_markdown_extension}; + let source = "текст ![secret](file:///hidden) end"; + for (boundary, _) in source.char_indices() { + let prefix = safe_markdown(&source[..boundary]); + let streamed = safe_markdown_extension(source, boundary) + .map(|extension| prefix + &extension) + .unwrap_or_else(|| safe_markdown(source)); + assert_eq!( + streamed, + "текст [secret](file:///hidden)<img src='x'> end" + ); + } + assert_eq!(safe_markdown_extension(source, 1), None); + assert_eq!( + safe_markdown_extension(source, source.len() - 4).as_deref(), + Some(" end") + ); +} #[gpui_kit::test] fn image_preparation_runs_once_and_renders_a_cached_small_static_preview(cx: &mut TestAppContext) { let codec = image_codec(); @@ -102,30 +160,117 @@ fn image_preparation_runs_once_and_renders_a_cached_small_static_preview(cx: &mu .unwrap(); cx.run_until_parked(); assert_eq!(codec.requests().len(), 1); - // Draw the real composer strip, then deliver its image asset completion. cx.update_window(f.handle, |_, window, cx| window.render_frame(cx)) .unwrap(); cx.run_until_parked(); - let rendered = cx - .update_window(f.handle, |_, window, cx| { - window.draw(cx).clear(cx); - assert!(expected.is_asset_cached(cx)); - expected - .clone() - .get_render_image(window, cx) - .expect("successful preview rendering must load its supplied PNG") + cx.update_window(f.handle, |_, window, cx| { + window.draw(cx).clear(cx); + assert!(window.find(("remove-image", 0usize)).bounds().size.height > gpui_kit::px(0.)); + assert!(!expected.is_asset_cached(cx)); + }) + .unwrap(); + assert_eq!(codec.requests().len(), 1); + thread.update(cx, |thread, cx| thread.send("send cached image".into(), cx)); + super::queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, _| { + assert!( + window.find(("agent-entry", 0usize)).bounds().size.height + > gpui_kit::rems(10.).to_pixels(window.rem_size()) + ); + }) + .unwrap(); + assert_eq!( + codec.requests().len(), + 1, + "the transcript reuses the composer preview" + ); +} + +#[gpui_kit::test] +fn pasting_an_image_previews_the_inspected_decode_and_sends_the_original(cx: &mut TestAppContext) { + let codec = image_codec(); + codec.reuse_inspected_decode(); + let f = fixture_with_width( + cx, + 26., + workspace_resolver(), + crate::ImageDeps::new(codec.clone(), codec.clone()), + ); + f.connector.support_images(); + new_chat(&f, cx); + super::queue_layout::settle(&f, cx); + let (notifications, _observer) = super::invalidation::count_panel_notifications(&f, cx); + let data = image_bytes(); + let preview = Arc::new(gpui_kit::Image::from_bytes( + gpui_kit::ImageFormat::Png, + data.clone(), + )); + f.panel + .update(cx, |panel, cx| panel.add_image_bytes(data, cx)); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + // The footer must update in the normal cached draw. + window.draw(cx).clear(cx); + assert!(window.find(("remove-image", 0usize)).bounds().size.height > gpui_kit::px(0.)); + assert!(!preview.is_asset_cached(cx)); + }) + .unwrap(); + assert_eq!(notifications.get(), 0, "pasting stays in the chat's footer"); + + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| thread.send("send pasted image".into(), cx)); + super::queue_layout::settle(&f, cx); + let requests = f.commands.prompts.lock().unwrap(); + assert!(requests[0].content.contains(&prompt_image().content())); + assert!(matches!( + codec.requests().as_slice(), + [nocterm_ai::testing::ImageRequest::Inspect(_)] + )); +} + +#[gpui_kit::test] +fn sending_while_the_attachment_preview_loads_remeasures_the_transcript_once( + cx: &mut TestAppContext, +) { + let codec = image_codec(); + let images = crate::ImageDeps::new(codec.clone(), codec.clone()); + let f = fixture_with_width(cx, 26., workspace_resolver(), images.clone()); + f.connector.support_images(); + new_chat(&f, cx); + let permits = (0..4) + .map(|_| images.admit_work().unwrap()) + .collect::>(); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let attachment = prompt_image(); + let payload = attachment.content(); + thread.update(cx, |thread, cx| { + thread.accept_composer_images(vec![attachment], cx).unwrap(); + }); + super::queue_layout::settle(&f, cx); + thread.update(cx, |thread, cx| { + thread.send("send loading image".into(), cx) + }); + super::queue_layout::settle(&f, cx); + assert!(codec.requests().is_empty()); + assert!( + f.commands.prompts.lock().unwrap()[0] + .content + .contains(&payload) + ); + let row_height = |cx: &mut TestAppContext| { + cx.update_window(f.handle, |_, window, _| { + window.find(("agent-entry", 0usize)).bounds().size.height }) - .unwrap(); - assert_eq!(rendered.frame_count(), 1); - assert_eq!(rendered.size(0), gpui_kit::size(2u32.into(), 2u32.into())); - assert_eq!(rendered.as_bytes(0).unwrap().len(), 2 * 2 * 4); + .unwrap() + }; + let loading_height = row_height(cx); + drop(permits); + cx.run_until_parked(); cx.update_window(f.handle, |_, window, cx| { window.draw(cx).clear(cx); - assert!(window.has_image_atlas_entry(&rendered)); - let reused = expected.clone().get_render_image(window, cx).unwrap(); - assert!(Arc::ptr_eq(&rendered, &reused)); }) .unwrap(); + assert!(row_height(cx) > loading_height); assert_eq!(codec.requests().len(), 1); } diff --git a/crates/agent/src/panel/tests/composer/image_selection.rs b/crates/agent/src/panel/tests/composer/image_selection.rs new file mode 100644 index 00000000..24a0888f --- /dev/null +++ b/crates/agent/src/panel/tests/composer/image_selection.rs @@ -0,0 +1,249 @@ +use super::super::*; + +#[gpui_kit::test] +fn selecting_four_large_files_again_reuses_transcript_previews(cx: &mut TestAppContext) { + use nocterm_ai::{ + images::{EncodedPreview, ImageFacts, ImageFormat, MAX_IMAGE_BYTES, PreviewBounds}, + testing::ImageRequest, + }; + + let codec = image_codec(); + let dir = tempfile::tempdir().unwrap(); + let preview = + EncodedPreview::new(image_bytes().into(), PreviewBounds::new(2, 2).unwrap()).unwrap(); + let paths = (0..4) + .map(|index| { + let path = dir.path().join(format!("image-{index}.png")); + let mut original = image_bytes(); + original.resize(MAX_IMAGE_BYTES, index); + codec.inspection( + &original, + Ok(ImageFacts::new(ImageFormat::Png, 2, 2).unwrap()), + ); + codec.preview(&original, Ok(preview.clone())); + std::fs::write(&path, original).unwrap(); + path + }) + .collect::>(); + let f = fixture_with_width( + cx, + 26., + workspace_resolver(), + crate::ImageDeps::new(codec.clone(), codec.clone()), + ); + f.connector.support_images(); + new_chat(&f, cx); + for selection in 0..2 { + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.click("agent-attach-files", cx) + }) + .unwrap(); + cx.simulate_path_prompt_response(|_| Some(paths.clone())); + for _ in 0..3 { + queue_layout::settle(&f, cx); + } + cx.update_window(f.handle, |_, window, _| { + for index in 0..4usize { + assert!(window.find(("remove-image", index)).visible()); + } + }) + .unwrap(); + if selection == 0 { + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| thread.send("send first batch".into(), cx)); + } + } + let thumbnails = codec + .requests() + .iter() + .filter(|request| matches!(request, ImageRequest::Thumbnail(..))) + .count(); + assert_eq!( + thumbnails, 8, + "one thumbnail decode per attachment across both batches" + ); +} + +#[gpui_kit::test] +fn selecting_images_reuses_the_last_decode_and_sends_every_original(cx: &mut TestAppContext) { + use nocterm_ai::{images::PromptImage, testing::ImageRequest}; + + let codec = image_codec(); + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first.png"); + let last = dir.path().join("last.png"); + let first_bytes = image_bytes(); + std::fs::write(&first, &first_bytes).unwrap(); + image::RgbaImage::from_pixel(2, 2, image::Rgba([90, 60, 180, 255])) + .save(&last) + .unwrap(); + let last_bytes = std::fs::read(&last).unwrap(); + image_fixtures::supply_small_png(&codec, &last_bytes); + let expected = PromptImage::validate(last_bytes.clone(), codec.as_ref()) + .unwrap() + .content(); + codec.reuse_inspected_decode(); + let f = fixture_with_width( + cx, + 26., + workspace_resolver(), + crate::ImageDeps::new(codec.clone(), codec.clone()), + ); + f.connector.support_images(); + new_chat(&f, cx); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.click("agent-attach-files", cx) + }) + .unwrap(); + cx.simulate_path_prompt_response(|options| { + assert!(options.multiple); + Some(vec![first, last]) + }); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, _| { + for index in 0..2usize { + assert!(window.find(("remove-image", index)).visible()); + } + }) + .unwrap(); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + thread.send("send selected images".into(), cx) + }); + queue_layout::settle(&f, cx); + let requests = f.commands.prompts.lock().unwrap(); + let originals = requests[0] + .content + .iter() + .filter(|block| matches!(block, Content::Image(_))) + .collect::>(); + assert_eq!(originals, [&prompt_image().content(), &expected]); + let thumbnail_requests = codec + .requests() + .into_iter() + .filter_map(|request| match request { + ImageRequest::Thumbnail(bytes, _) => Some(bytes), + ImageRequest::Inspect(_) => None, + }) + .collect::>(); + assert_eq!(thumbnail_requests, [Arc::<[u8]>::from(first_bytes)]); +} + +#[gpui_kit::test] +fn selecting_a_batch_with_a_bad_last_image_keeps_the_existing_draft(cx: &mut TestAppContext) { + let f = fixture(cx); + f.connector.support_images(); + new_chat(&f, cx); + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first.png"); + let last = dir.path().join("bad.png"); + std::fs::write(&first, image_bytes()).unwrap(); + std::fs::write(&last, b"not a PNG").unwrap(); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + thread + .accept_composer_images(vec![prompt_image()], cx) + .unwrap(); + }); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.click("agent-attach-files", cx) + }) + .unwrap(); + cx.simulate_path_prompt_response(|_| Some(vec![first, last])); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, _| { + assert!(window.find("agent-error").visible()); + assert!(window.find(("remove-image", 0usize)).visible()); + assert!(window.try_find(("remove-image", 1usize)).is_none()); + }) + .unwrap(); + thread.update(cx, |thread, cx| { + thread.send("send existing image".into(), cx) + }); + queue_layout::settle(&f, cx); + let requests = f.commands.prompts.lock().unwrap(); + let originals = requests[0] + .content + .iter() + .filter(|block| matches!(block, Content::Image(_))) + .collect::>(); + assert_eq!(originals, [&prompt_image().content()]); +} + +#[gpui_kit::test] +fn a_file_selection_waits_for_a_decoder_and_sends_the_original(cx: &mut TestAppContext) { + let codec = image_codec(); + let images = crate::ImageDeps::new(codec.clone(), codec.clone()); + let f = fixture_with_width(cx, 26., workspace_resolver(), images.clone()); + f.connector.support_images(); + new_chat(&f, cx); + let mut permits = (0..4) + .map(|_| images.admit_work().unwrap()) + .collect::>(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("waiting.png"); + std::fs::write(&path, image_bytes()).unwrap(); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.click("agent-attach-files", cx) + }) + .unwrap(); + cx.simulate_path_prompt_response(|_| Some(vec![path])); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, _| { + assert!(window.try_find("agent-error").is_none()); + assert!(window.try_find(("remove-image", 0usize)).is_none()); + }) + .unwrap(); + assert!(codec.requests().is_empty()); + drop(permits.pop()); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, _| { + assert!(window.find(("remove-image", 0usize)).visible()); + }) + .unwrap(); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + thread.send("send waiting image".into(), cx) + }); + queue_layout::settle(&f, cx); + assert!( + f.commands.prompts.lock().unwrap()[0] + .content + .contains(&prompt_image().content()) + ); +} + +#[gpui_kit::test] +fn switching_chat_cancels_a_selection_waiting_for_a_decoder(cx: &mut TestAppContext) { + let codec = image_codec(); + let images = crate::ImageDeps::new(codec.clone(), codec.clone()); + let f = fixture_with_width(cx, 26., workspace_resolver(), images.clone()); + f.connector.support_images(); + new_chat(&f, cx); + let permits = (0..4) + .map(|_| images.admit_work().unwrap()) + .collect::>(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("waiting.png"); + std::fs::write(&path, image_bytes()).unwrap(); + queue_layout::settle(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.click("agent-attach-files", cx) + }) + .unwrap(); + cx.simulate_path_prompt_response(|_| Some(vec![path])); + queue_layout::settle(&f, cx); + new_chat(&f, cx); + drop(permits); + queue_layout::settle(&f, cx); + assert!(codec.requests().is_empty()); + cx.update_window(f.handle, |_, window, _| { + assert!(window.try_find("agent-error").is_none()); + assert!(window.try_find(("remove-image", 0usize)).is_none()); + }) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/composer/menu_stability.rs b/crates/agent/src/panel/tests/composer/menu_stability.rs index 0e437976..4ae2e1b5 100644 --- a/crates/agent/src/panel/tests/composer/menu_stability.rs +++ b/crates/agent/src/panel/tests/composer/menu_stability.rs @@ -28,6 +28,52 @@ fn many_servers(f: &Fixture, cx: &mut TestAppContext) -> Rc { const ROW: &str = "attach-connection-server-10"; +#[gpui_kit::test] +fn attachment_picker_only_requests_images_for_visible_servers(cx: &mut TestAppContext) { + let f = fixture_with_width(cx, 18., workspace_resolver(), image_deps()); + let directory = many_servers(&f, cx); + let icons = Rc::new(std::cell::RefCell::new(Vec::new())); + let flags = Rc::new(std::cell::RefCell::new(Vec::new())); + for (index, server) in directory.0.borrow_mut().iter_mut().enumerate() { + for (image, requests) in [(&mut server.icon, &icons), (&mut server.flag, &flags)] { + let requests = requests.clone(); + *image = Some(gpui_kit::ImageSource::from( + move |_: &mut Window, _: &mut App| { + requests.borrow_mut().push(index); + None + }, + )); + } + } + + new_chat(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + window.click("agent-attach-context", cx); + window.render_frame(cx); + for initial in [icons.take(), flags.take()] { + assert!(initial.contains(&0)); + assert!(!initial.contains(&10)); + } + + window.scroll( + "agent-picker", + ScrollDelta::Pixels(point(px(0.), px(-240.))), + cx, + ); + icons.take(); + flags.take(); + window.refresh(); + window.render_frame(cx); + for scrolled in [icons.take(), flags.take()] { + assert!(scrolled.contains(&10)); + assert!(!scrolled.contains(&0)); + assert!(!scrolled.contains(&34)); + } + }) + .unwrap(); +} + fn scrolled_picker(f: &Fixture, cx: &mut TestAppContext) -> Bounds { cx.update_window(f.handle, |_, window, cx| { window.render_frame(cx); diff --git a/crates/agent/src/panel/tests/flow.rs b/crates/agent/src/panel/tests/flow.rs index 75af14af..4ba70eee 100644 --- a/crates/agent/src/panel/tests/flow.rs +++ b/crates/agent/src/panel/tests/flow.rs @@ -570,7 +570,8 @@ fn pending_image_preparation_blocks_early_submit_and_retains_prompt(cx: &mut Tes Ok(vec![nocterm_ai::images::PromptImage::validate( bytes, codec.as_ref(), - )?]) + )?] + .into()) }, cx, ); @@ -630,8 +631,8 @@ fn late_image_preparation_cannot_attach_to_a_different_chat(cx: &mut TestAppCont ) }); new_chat(&f, cx); - ready.send(()).unwrap(); cx.run_until_parked(); + assert!(ready.send(()).is_err()); cx.update_window(f.handle, |_, window, cx| { window.render_frame(cx); assert!(window.try_find("agent-error").is_none()); diff --git a/crates/agent/src/panel/tests/history.rs b/crates/agent/src/panel/tests/history.rs index 055ec91a..f5a79f1a 100644 --- a/crates/agent/src/panel/tests/history.rs +++ b/crates/agent/src/panel/tests/history.rs @@ -1,4 +1,5 @@ mod search; +mod viewport; use super::*; use crate::thread::AgentThread; use nocterm_ai::model::content::Content; @@ -310,6 +311,7 @@ fn history_records_only_accepted_prompts_and_keeps_model_snapshot(cx: &mut TestA thread, SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { title: nocterm_ai::model::controls::Change::Set("Updated title".into()), + activity: None, meta: None, }), cx, diff --git a/crates/agent/src/panel/tests/history/viewport.rs b/crates/agent/src/panel/tests/history/viewport.rs new file mode 100644 index 00000000..4d1b8dee --- /dev/null +++ b/crates/agent/src/panel/tests/history/viewport.rs @@ -0,0 +1,60 @@ +use super::*; +use gpui_kit::{InputEvent as _, MouseMoveEvent, ScrollDelta, ScrollWheelEvent, point, px}; +use nocterm_ai::{history::SavedChat, metadata::ChatMetadataSource as _}; + +#[gpui_kit::test] +fn history_scrolls_to_unbuilt_rows_and_keeps_search_visible(cx: &mut TestAppContext) { + let mut f = fixture(cx); + let chats = (0..120) + .map(|index| { + let identity = f._directory.metadata.new_identity(); + let mut chat = SavedChat::for_identity("codex".into(), identity.id, index); + chat.header.name = Some(format!("Chat {index:03}")); + chat + }) + .collect(); + reinstall_history(&mut f, chats, cx); + cx.run_until_parked(); + let (first, last) = cx.update(|cx| { + let panel = f.panel.read(cx); + let row = |title| { + let thread = panel + .chat_documents() + .find(|thread| thread.read(cx).title() == title) + .unwrap(); + ("history-thread", thread.entity_id().as_u64()) + }; + (row("Chat 119"), row("Chat 000")) + }); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.find(first).visible()); + assert!(window.try_find(last).is_none()); + let position = window.find("agent-history-list").bounds().center(); + window.dispatch_event( + MouseMoveEvent { + position, + ..Default::default() + } + .to_platform_input(), + cx, + ); + window.dispatch_event( + ScrollWheelEvent { + position, + delta: ScrollDelta::Pixels(point(px(0.), px(-12_000.))), + ..Default::default() + } + .to_platform_input(), + cx, + ); + window.render_frame(cx); + assert!(window.find(last).visible()); + assert!(window.try_find(first).is_none()); + replace_textbox("agent-history-search", "Chat 119", window, cx); + window.render_frame(cx); + assert!(window.find(first).visible()); + assert!(window.try_find(last).is_none()); + }) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/image_fixtures.rs b/crates/agent/src/panel/tests/image_fixtures.rs index 3c0ad16d..6b4ea9b0 100644 --- a/crates/agent/src/panel/tests/image_fixtures.rs +++ b/crates/agent/src/panel/tests/image_fixtures.rs @@ -7,16 +7,16 @@ pub(super) fn image_bytes() -> Vec { } pub(super) fn image_codec() -> Arc { let codec = Arc::new(ScriptedImageCodec::default()); - let bytes = image_bytes(); - codec.inspection(&bytes, Ok(ImageFacts::new(ImageFormat::Png, 2, 2).unwrap())); + supply_small_png(&codec, &image_bytes()); + codec +} + +pub(super) fn supply_small_png(codec: &ScriptedImageCodec, bytes: &[u8]) { + codec.inspection(bytes, Ok(ImageFacts::new(ImageFormat::Png, 2, 2).unwrap())); codec.preview( - &bytes, - Ok( - EncodedPreview::new(bytes.clone().into(), PreviewBounds::new(640, 640).unwrap()) - .unwrap(), - ), + bytes, + Ok(EncodedPreview::new(bytes.into(), PreviewBounds::new(640, 640).unwrap()).unwrap()), ); - codec } pub(super) fn image_deps() -> crate::ImageDeps { let codec = image_codec(); diff --git a/crates/agent/src/panel/tests/invalidation.rs b/crates/agent/src/panel/tests/invalidation.rs index ffe06393..1a067b00 100644 --- a/crates/agent/src/panel/tests/invalidation.rs +++ b/crates/agent/src/panel/tests/invalidation.rs @@ -266,7 +266,7 @@ fn late_image_preparation_cannot_cross_chat_or_overwrite_its_draft(cx: &mut Test panel.prepare_images( async move { receive.await.unwrap(); - Ok(vec![prompt_image()]) + Ok(vec![prompt_image()].into()) }, cx, ) @@ -275,8 +275,8 @@ fn late_image_preparation_cannot_cross_chat_or_overwrite_its_draft(cx: &mut Test cx.update(|cx| assert!(f.panel.read(cx).preparing_images())); new_chat(&f, cx); set_input(&f, "second chat draft", cx); - send.send(()).unwrap(); cx.run_until_parked(); + assert!(send.send(()).is_err()); cx.update(|cx| { let panel = f.panel.read(cx); assert!(!panel.preparing_images()); @@ -395,7 +395,7 @@ async fn ai_off_clears_edit_drafts_stream_and_queue_measurements(cx: &mut TestAp .unwrap(); } -fn count_panel_notifications( +pub(super) fn count_panel_notifications( f: &Fixture, cx: &mut TestAppContext, ) -> (Rc>, gpui_kit::Subscription) { @@ -449,6 +449,46 @@ fn a_streamed_chunk_draws_in_the_open_chat_without_redrawing_the_whole_panel( ); } +#[gpui_kit::test] +fn reopening_history_search_finds_text_streamed_while_closed(cx: &mut TestAppContext) { + let f = fixture(cx); + new_chat(&f, cx); + let source = cx.update(|cx| f.panel.read(cx).current().unwrap()); + source.update(cx, |thread, cx| thread.send("question".into(), cx)); + cx.run_until_parked(); + let id = source.entity_id().as_u64(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + replace_textbox("agent-history-search", "new fragment", window, cx); + window.render_frame(cx); + assert!(window.try_find(("history-thread", id)).is_none()); + window.click("agent-history", cx); + window.render_frame(cx); + assert!(window.try_find("agent-history-column").is_none()); + }) + .unwrap(); + + let session = cx.update(|cx| source.read(cx).session().clone().unwrap()); + f.events + .try_send(AgentEvent::Session(SessionNotice::new( + session, + SessionUpdate::AgentMessageChunk(Content::text("This is a new fragment.")), + ))) + .unwrap(); + cx.run_until_parked(); + cx.executor() + .advance_clock(std::time::Duration::from_millis(100)); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.draw(cx).clear(cx); + assert!(window.try_find("agent-history-column").is_none()); + window.click("agent-history", cx); + window.draw(cx).clear(cx); + assert!(window.find(("history-thread", id)).visible()); + }) + .unwrap(); +} + #[gpui_kit::test] fn typing_a_draft_saves_it_without_redrawing_the_whole_panel(cx: &mut TestAppContext) { let f = fixture(cx); diff --git a/crates/agent/src/panel/tests/labels.rs b/crates/agent/src/panel/tests/labels.rs index 5bd968a8..9a21f7cb 100644 --- a/crates/agent/src/panel/tests/labels.rs +++ b/crates/agent/src/panel/tests/labels.rs @@ -77,6 +77,7 @@ fn chat_header_and_history_keep_multiline_titles_on_one_line(cx: &mut TestAppCon session, SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { title: nocterm_ai::model::controls::Change::Set(agent_title.into()), + activity: None, meta: None, }), ))) diff --git a/crates/agent/src/panel/tests/message_copy.rs b/crates/agent/src/panel/tests/message_copy.rs new file mode 100644 index 00000000..15087ba5 --- /dev/null +++ b/crates/agent/src/panel/tests/message_copy.rs @@ -0,0 +1,122 @@ +use super::*; +use gpui_kit::{ClipboardItem, InputEvent as _, MouseButton, MouseDownEvent, MouseUpEvent}; +use nocterm_ai::thread::Entry; + +fn click_painted_copy( + f: &Fixture, + cx: &mut TestAppContext, + before_click: impl FnOnce(&mut App), +) -> String { + cx.update_window(f.handle, |_, window, cx| { + window.hover(("agent-entry", 0usize), cx); + window.render_frame(cx); + let position = window.find(("copy-message", 0usize)).bounds().center(); + window.simulate_mouse_move(position, cx); + before_click(cx); + window.dispatch_event( + MouseDownEvent { + button: MouseButton::Left, + position, + click_count: 1, + ..Default::default() + } + .to_platform_input(), + cx, + ); + window.dispatch_event( + MouseUpEvent { + button: MouseButton::Left, + position, + click_count: 1, + ..Default::default() + } + .to_platform_input(), + cx, + ); + cx.read_from_clipboard().unwrap().text().unwrap() + }) + .unwrap() +} + +#[gpui_kit::test] +fn copy_keeps_the_painted_agent_prefix_while_an_append_is_pending(cx: &mut TestAppContext) { + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let prefix = "Ответ 世界"; + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Agent(prefix.into())], cx); + }); + assert_eq!( + click_painted_copy(&f, cx, |cx| { + thread.update(cx, |thread, cx| { + report_control( + thread, + SessionUpdate::AgentMessageChunk(Content::text(" plus text")), + cx, + ); + }); + }), + prefix + ); + assert_eq!( + click_painted_copy(&f, cx, |_| {}), + format!("{prefix} plus text") + ); +} + +#[gpui_kit::test] +fn a_painted_copy_cannot_read_a_replacement_transcript(cx: &mut TestAppContext) { + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Agent("One".into())], cx); + }); + assert_eq!( + click_painted_copy(&f, cx, |cx| { + cx.write_to_clipboard(ClipboardItem::new_string("Clipboard before click".into())); + thread.update(cx, |thread, cx| { + let mut saved = restored_projection(thread, cx); + saved.entries = vec![Entry::Agent("Two".into())]; + thread.restore_content(saved, cx).unwrap(); + cx.notify(); + }); + }), + "Clipboard before click" + ); + assert_eq!(click_painted_copy(&f, cx, |_| {}), "Two"); +} + +#[gpui_kit::test] +fn copy_keeps_user_text_parts_in_order_and_omits_attachments(cx: &mut TestAppContext) { + use nocterm_ai::model::content::ResourceReference; + + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + let attachment = Content::ResourceReference(ResourceReference { + annotations: None, + description: None, + mime_type: None, + name: "notes.txt".into(), + size: None, + title: None, + uri: "file:///notes.txt".into(), + meta: None, + }); + restore_entries( + &f, + thread, + vec![Entry::User(vec![ + Content::text("*first*"), + attachment, + Content::text(""), + Content::text("二番目"), + ])], + cx, + ); + }); + assert_eq!(click_painted_copy(&f, cx, |_| {}), "*first*\n\n二番目"); +} diff --git a/crates/agent/src/panel/tests/mod.rs b/crates/agent/src/panel/tests/mod.rs index ee7b3010..f64affe1 100644 --- a/crates/agent/src/panel/tests/mod.rs +++ b/crates/agent/src/panel/tests/mod.rs @@ -53,6 +53,7 @@ fn shutdown_runtime(installed: &crate::Installed, cx: &mut TestAppContext) { mod builders; mod config_responses; mod process_commands; +mod provider_history; mod scripted_agent; use scripted_agent::{Bridge, Commands, Connector}; @@ -501,6 +502,7 @@ mod history; mod invalidation; mod labels; mod lifecycle; +mod message_copy; mod navigation; mod other_windows; mod persistence; @@ -515,6 +517,7 @@ mod routing; mod scroll_geometry; mod seat_binding; mod servers; +mod streamed_markdown; mod tool_corpus; mod tool_input; mod tool_output; diff --git a/crates/agent/src/panel/tests/navigation.rs b/crates/agent/src/panel/tests/navigation.rs index e443b7cc..4bc49069 100644 --- a/crates/agent/src/panel/tests/navigation.rs +++ b/crates/agent/src/panel/tests/navigation.rs @@ -457,8 +457,8 @@ fn copy_completed_message_uses_full_text_while_reveal_is_pending(cx: &mut TestAp cx.update_window(f.handle, |_, window, cx| window.render_frame(cx)) .unwrap(); complete_active(&f, cx); - let before = cx - .update_window(f.handle, |_, window, cx| { + let copy_and_measure = |cx: &mut TestAppContext| { + cx.update_window(f.handle, |_, window, cx| { window.render_frame(cx); let height = window.find(("agent-entry", 1usize)).bounds().size.height; window.hover(("agent-entry", 1usize), cx); @@ -466,21 +466,47 @@ fn copy_completed_message_uses_full_text_while_reveal_is_pending(cx: &mut TestAp assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), full); height }) - .unwrap(); + .unwrap() + }; + let before = copy_and_measure(cx); cx.executor() - .advance_clock(std::time::Duration::from_millis(500)); + .advance_clock(std::time::Duration::from_millis(16)); cx.run_until_parked(); - cx.update_window(f.handle, |_, window, cx| { - window.render_frame(cx); - assert!( - window.find(("agent-entry", 1usize)).bounds().size.height > before, - "visible streamed text must continue revealing after copy" - ); - window.hover(("agent-entry", 1usize), cx); - window.click(("copy-message", 1usize), cx); - assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), full); - }) - .unwrap(); + let first_step = copy_and_measure(cx); + assert!(first_step > before, "the reply starts revealing on time"); + + let displayed_height = |cx: &mut TestAppContext| { + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + window.find(("agent-entry", 1usize)).bounds().size.height + }) + .unwrap() + }; + // Move the clock without running each intervening timer, as when the UI thread stalls. + cx.executor() + .dispatcher() + .as_test() + .unwrap() + .scheduler() + .clock() + .advance(std::time::Duration::from_secs(2)); + let caught_up = displayed_height(cx); + assert!( + caught_up > first_step, + "the first step only shows part of the reply" + ); + cx.update(|cx| cx.set_reduce_motion(true)); + cx.executor() + .advance_clock(std::time::Duration::from_millis(16)); + assert_eq!( + caught_up, + displayed_height(cx), + "one delayed reveal callback should display the full reply" + ); } #[gpui_kit::test] diff --git a/crates/agent/src/panel/tests/other_windows.rs b/crates/agent/src/panel/tests/other_windows.rs index b4d1e24f..b3ebeeb6 100644 --- a/crates/agent/src/panel/tests/other_windows.rs +++ b/crates/agent/src/panel/tests/other_windows.rs @@ -98,6 +98,15 @@ fn a_chat_working_in_another_window_opens_in_that_window(cx: &mut TestAppContext ); }); complete_active(&f, cx); + cx.executor() + .advance_clock(std::time::Duration::from_millis(40)); + cx.run_until_parked(); + in_window(second, cx, |window, _| { + assert_eq!( + window.find(("history-elsewhere", row)).label(), + Some("Open in another window: opens here") + ); + }); } #[gpui_kit::test] @@ -135,3 +144,55 @@ fn a_saved_chat_the_first_window_has_not_opened_moves_with_its_transcript(cx: &m ); }); } + +#[gpui_kit::test] +fn listing_a_working_chat_preserves_its_window_for_stream_updates(cx: &mut TestAppContext) { + let f = fixture(cx); + new_chat(&f, cx); + let working = cx.update(|cx| f.panel.read(cx).current().unwrap()); + cx.update(|cx| working.update(cx, |thread, cx| thread.send("Rotate the logs".into(), cx))); + cx.run_until_parked(); + + let (other, _) = open_window_panel(&f, cx); + show_history_in(other, cx); + let id = working.entity_id(); + let rendered_owner = |cx: &mut TestAppContext| { + cx.update(|cx| cx.with_window(id, |window, _| window.window_handle())) + }; + in_window(f.handle, cx, |window, _| { + assert!(window.try_find("agent-composer").is_some()); + }); + assert_eq!(rendered_owner(cx), Some(f.handle)); + in_window(other, cx, |window, _| { + assert_eq!( + window.find(("history-elsewhere", id.as_u64())).label(), + Some("Working in another window: opens there") + ); + }); + assert_eq!(rendered_owner(cx), Some(f.handle)); + + in_window(other, cx, |window, cx| { + replace_textbox("agent-history-search", "rotation complete", window, cx); + window.render_frame(cx); + assert!(window.try_find("agent-history-no-match").is_some()); + }); + let session = cx.update(|cx| working.read(cx).session().clone().unwrap()); + f.events + .try_send(AgentEvent::Session(SessionNotice::new( + session, + SessionUpdate::AgentMessageChunk(Content::Text(nocterm_ai::model::content::Text::new( + "Rotation complete.", + ))), + ))) + .unwrap(); + cx.run_until_parked(); + cx.executor() + .advance_clock(std::time::Duration::from_millis(40)); + cx.run_until_parked(); + cx.update_window(other, |_, window, _| { + assert!(window.try_find(("history-thread", id.as_u64())).is_some()); + }) + .unwrap(); + assert_eq!(rendered_owner(cx), Some(f.handle)); + complete_active(&f, cx); +} diff --git a/crates/agent/src/panel/tests/provider_history.rs b/crates/agent/src/panel/tests/provider_history.rs new file mode 100644 index 00000000..318fffa3 --- /dev/null +++ b/crates/agent/src/panel/tests/provider_history.rs @@ -0,0 +1,134 @@ +//! Restoring a provider-owned transcript through the open-session route. +use super::*; +use nocterm_ai::thread::Entry; + +fn reopen_with_chunks( + parts: usize, + chunk_bytes: usize, + cx: &mut TestAppContext, +) -> std::time::Duration { + let f = fixture(cx); + f.connector.info.lock().unwrap().capabilities.keeps_history = true; + let mut saved = restoration::empty_chat(&f); + saved.header.title = Some("Saved title".into()); + saved.entries = vec![Entry::Agent("Saved placeholder".into())]; + let thread = restoration::restore_released(&f, saved, cx); + *f.commands.restore_history.lock().unwrap() = Some( + (0..parts) + .map(|index| { + let mut text = "x".repeat(chunk_bytes); + text.replace_range(..1, if index % 2 == 0 { "a" } else { "b" }); + SessionUpdate::AgentMessageChunk(Content::text(text)) + }) + .collect(), + ); + let started = std::time::Instant::now(); + cx.update(|cx| activate_thread(&thread, cx)); + cx.run_until_parked(); + let elapsed = started.elapsed(); + assert_eq!(f.commands.restores.lock().unwrap().len(), 1); + cx.update(|cx| { + let transcript = thread.read(cx).transcript(); + let [Entry::Agent(text)] = transcript.entries.as_slice() else { + panic!("provider history replaces the saved contents"); + }; + assert_eq!(transcript.title.as_deref(), Some("Saved title")); + assert_eq!(text.len(), parts * chunk_bytes); + for (index, chunk) in text.as_bytes().chunks_exact(chunk_bytes).enumerate() { + assert_eq!(chunk[0], if index % 2 == 0 { b'a' } else { b'b' }); + assert!(chunk[1..].iter().all(|&byte| byte == b'x')); + } + }); + elapsed +} + +#[gpui_kit::test] +fn the_provider_history_replaces_saved_rows_and_keeps_the_title(cx: &mut TestAppContext) { + reopen_with_chunks(3, 12, cx); +} + +#[gpui_kit::test] +#[ignore = "manual measurement of the provider history open-session path"] +fn measure_provider_history_restore(cx: &mut TestAppContext) { + use std::io::Write as _; + let size = std::env::var("NOCTERM_PROVIDER_HISTORY_PROFILE").unwrap(); + let (parts, chunk_bytes) = match size.as_str() { + "short" => (24, 1024), + "wide" => (621, 64_007), + "large" => (1500, 64_007), + _ => panic!("choose short, wide or large"), + }; + let elapsed = reopen_with_chunks(parts, chunk_bytes, cx); + writeln!( + std::io::stdout().lock(), + "provider_restore parts={parts} chunk_bytes={chunk_bytes} wall_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} + +fn reopen_with_tools(rows: usize, cx: &mut TestAppContext) -> std::time::Duration { + use nocterm_ai::model::tools::{ToolChanges, ToolPatch, ToolRecord, ToolStatus}; + let f = fixture(cx); + f.connector.info.lock().unwrap().capabilities.keeps_history = true; + let mut saved = restoration::empty_chat(&f); + saved.header.title = Some("Saved title".into()); + saved.entries = vec![Entry::Agent("Saved placeholder".into())]; + let thread = restoration::restore_released(&f, saved, cx); + let updates = (0..rows) + .flat_map(|index| { + let id = format!("tool-{index:05}"); + [ + SessionUpdate::ToolCall(Box::new(ToolRecord::new(id.as_str(), "pending"))), + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + id, + ToolChanges::default() + .title("restored result") + .status(ToolStatus::Succeeded), + ))), + ] + }) + .collect(); + *f.commands.restore_history.lock().unwrap() = Some(updates); + let started = std::time::Instant::now(); + cx.update(|cx| activate_thread(&thread, cx)); + cx.run_until_parked(); + let elapsed = started.elapsed(); + assert_eq!(f.commands.restores.lock().unwrap().len(), 1); + cx.update(|cx| { + let transcript = thread.read(cx).transcript(); + assert_eq!(transcript.title.as_deref(), Some("Saved title")); + assert_eq!(transcript.entries.len(), rows); + for (index, entry) in transcript.entries.iter().enumerate() { + let Entry::Tool(call) = entry else { + panic!("expected a restored tool row"); + }; + assert_eq!(call.id.as_str(), format!("tool-{index:05}")); + assert_eq!(call.title, "restored result"); + assert_eq!(call.status, ToolStatus::Succeeded); + } + }); + elapsed +} + +#[gpui_kit::test] +fn reopening_a_provider_session_restores_every_tool_patch(cx: &mut TestAppContext) { + reopen_with_tools(128, cx); +} + +#[gpui_kit::test] +#[ignore = "manual measurement of dense tool restoration through the open-session path"] +fn measure_dense_provider_history_restore(cx: &mut TestAppContext) { + use std::io::Write as _; + let rows = std::env::var("NOCTERM_PROFILE_REPLAY_ROWS") + .unwrap_or_else(|_| "16000".into()) + .parse() + .unwrap(); + let elapsed = reopen_with_tools(rows, cx); + writeln!( + std::io::stdout().lock(), + "tool_restore rows={rows} wall_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/queue_layout.rs b/crates/agent/src/panel/tests/queue_layout.rs index 90404ae4..fa4c6994 100644 --- a/crates/agent/src/panel/tests/queue_layout.rs +++ b/crates/agent/src/panel/tests/queue_layout.rs @@ -248,3 +248,117 @@ fn reopening_the_queue_keeps_its_thumbnail_and_needs_no_animation_ticks(cx: &mut "reopening must reuse the existing image preview" ); } + +fn enqueue_image_rows( + thread: &Entity, + codec: &nocterm_ai::testing::ScriptedImageCodec, + cx: &mut TestAppContext, +) -> Vec> { + use nocterm_ai::images::PromptImage; + + let mut last_images = Vec::new(); + thread.update(cx, |thread, cx| { + for row in 0..12u8 { + let images = (0..4) + .map(|column| { + let picture = + image::RgbaImage::from_pixel(2, 2, image::Rgba([row, column, 127, 255])); + let mut output = std::io::Cursor::new(Vec::new()); + picture + .write_to(&mut output, image::ImageFormat::Png) + .unwrap(); + let bytes = output.into_inner(); + if row == 11 { + last_images.push(bytes.clone()); + } + image_fixtures::supply_small_png(codec, &bytes); + PromptImage::validate(bytes, codec).unwrap() + }) + .collect(); + thread.accept_composer_images(images, cx).unwrap(); + thread.send(format!("queued row {row}"), cx); + } + assert_eq!(thread.composer().queue().len(), 12); + }); + last_images +} + +#[gpui_kit::test] +fn opening_a_long_queue_requests_previews_only_from_visible_rows(cx: &mut TestAppContext) { + use nocterm_ai::testing::ImageRequest; + + let codec = image_codec(); + let fixture = fixture_with_width( + cx, + 32., + workspace_resolver(), + crate::ImageDeps::new(codec.clone(), codec.clone()), + ); + fixture.connector.support_images(); + new_chat(&fixture, cx); + cx.update(|cx| cx.set_reduce_motion(true)); + let executor = cx.executor(); + let pump = || { + // A cache-miss loop must reach the assertion instead of hanging the test. + for _ in 0..256 { + if !executor.tick() { + break; + } + } + }; + let draw = |cx: &mut TestAppContext| { + cx.update_window(fixture.handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + pump(); + }; + let thread = cx.update(|cx| fixture.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + thread.clear_composer_context(cx); + thread.send("active".into(), cx); + }); + draw(cx); + assert_eq!(fixture.commands.prompts.lock().unwrap().len(), 1); + let last_images = enqueue_image_rows(&thread, &codec, cx); + let requests = || { + codec + .requests() + .into_iter() + .filter(|request| matches!(request, ImageRequest::Thumbnail(..))) + .count() + }; + draw(cx); + assert_eq!(requests(), 0); + cx.update_window(fixture.handle, |_, window, cx| { + window.click("queue-toggle", cx) + }) + .unwrap(); + pump(); + for _ in 0..8 { + draw(cx); + } + let initial = requests(); + assert!( + initial > 0 && initial <= 20, + "{initial} decode requests in the first viewport" + ); + draw(cx); + assert_eq!( + requests(), + initial, + "an unchanged viewport must stop decoding" + ); + cx.update_window(fixture.handle, |_, window, cx| { + window.scroll( + "agent-queue-scroll", + gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), px(-5000.))), + cx, + ); + }) + .unwrap(); + draw(cx); + let seen = codec.requests(); + for original in last_images { + assert!(seen.iter().any(|request| matches!(request, + ImageRequest::Thumbnail(bytes, _) if bytes.as_ref() == original.as_slice()))); + } +} diff --git a/crates/agent/src/panel/tests/scripted_agent.rs b/crates/agent/src/panel/tests/scripted_agent.rs index 76dd8054..5abb748d 100644 --- a/crates/agent/src/panel/tests/scripted_agent.rs +++ b/crates/agent/src/panel/tests/scripted_agent.rs @@ -20,6 +20,7 @@ pub(super) struct Commands { /// Each reopened session, and whether it was forked. pub(super) restores: Mutex>, pub(super) restore_errors: Mutex>, + pub(super) restore_history: Mutex>>, /// The MCP servers each new session was given. pub(super) servers: Mutex>>, /// The configuration options every session reports. @@ -74,7 +75,13 @@ impl AgentCommands for Commands { }; let config = self.config.options(); let modes = self.config.modes(); - async move { Ok(opened(session, config, modes)) }.boxed() + let history = self.restore_history.lock().unwrap().take(); + async move { + let mut response = opened(session, config, modes); + response.history = history; + Ok(response) + } + .boxed() } fn prompt(&self, r: PromptRequest) -> BoxFuture<'static, Result> { self.prompts.lock().unwrap().push(r); diff --git a/crates/agent/src/panel/tests/streamed_markdown.rs b/crates/agent/src/panel/tests/streamed_markdown.rs new file mode 100644 index 00000000..0ca386dd --- /dev/null +++ b/crates/agent/src/panel/tests/streamed_markdown.rs @@ -0,0 +1,217 @@ +use super::*; +use nocterm_ai::{model::content::Content, thread::Entry}; + +fn row_height(f: &Fixture, cx: &mut TestAppContext) -> gpui_kit::Pixels { + for _ in 0..3 { + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + cx.update_window(f.handle, |_, window, _| { + window.find(("agent-entry", 0usize)).bounds().size.height + }) + .unwrap() +} + +#[gpui_kit::test] +fn same_length_history_replacement_updates_the_rendered_message(cx: &mut TestAppContext) { + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let original = "one two three"; + let replacement = "one\n\ntwo\n\nend"; + assert_eq!(original.len(), replacement.len()); + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Agent(original.into())], cx); + }); + let before = row_height(&f, cx); + thread.update(cx, |thread, cx| { + let mut chat = restored_projection(thread, cx); + chat.entries = vec![Entry::Agent(replacement.into())]; + chat.times.clear(); + thread.restore_content(chat, cx).unwrap(); + // An authoritative replacement can arrive without any individual row notices. + cx.notify(); + }); + assert!(row_height(&f, cx) > before + gpui_kit::px(20.)); +} + +#[gpui_kit::test] +fn an_expanded_thought_renders_appended_paragraphs(cx: &mut TestAppContext) { + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Thought("First".into())], cx); + }); + row_height(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.click(("thought", 0usize), cx); + }) + .unwrap(); + let before = row_height(&f, cx); + thread.update(cx, |thread, cx| { + report_control( + thread, + SessionUpdate::AgentThoughtChunk(Content::text("\n\nNext\n\nLast")), + cx, + ); + }); + assert!(row_height(&f, cx) > before + gpui_kit::px(20.)); +} + +#[gpui_kit::test] +#[ignore = "streaming performance fixture; run in isolation"] +fn measure_visible_markdown_stream(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let f = fixture(cx); + cx.update(|cx| cx.set_reduce_motion(true)); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let start = "Initial paragraph. ".repeat(768); + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Agent(start.clone())], cx); + }); + row_height(&f, cx); + let fragments: Vec<_> = (0..120) + .map(|index| format!("\n\n**Paragraph {index:03}** with `code` and *emphasis*.")) + .collect(); + let clock = Instant::now(); + for fragment in &fragments { + thread.update(cx, |thread, cx| { + report_control( + thread, + SessionUpdate::AgentMessageChunk(Content::text(fragment)), + cx, + ); + }); + cx.update_window(f.handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + } + let elapsed = clock.elapsed(); + let expected: String = std::iter::once(start.as_str()) + .chain(fragments.iter().map(String::as_str)) + .collect(); + cx.update(|cx| { + assert!( + matches!(thread.read(cx).history_entries(), [Entry::Agent(text)] if *text == expected) + ); + }); + writeln!( + std::io::stdout().lock(), + "120 visible Markdown updates: {:.3} ms", + elapsed.as_secs_f64() * 1_000.0 + ) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "warm transcript row preparation fixture; run in isolation"] +fn measure_completed_message_row_preparation(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let f = fixture(cx); + cx.update(|cx| cx.set_reduce_motion(true)); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let text = format!( + "Completed answer.\n\n", + "Saved source with Unicode 世界. ".repeat(8_192) + ); + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Agent(text.clone())], cx); + }); + row_height(&f, cx); + + let mut output = std::io::stdout().lock(); + writeln!(output, "Preparing completed row of {} bytes", text.len()).unwrap(); + for _ in 0..7 { + let clock = Instant::now(); + for _ in 0..64 { + thread.update(cx, |thread, cx| { + thread.mark_dirty(0); + cx.notify(); + }); + cx.update_window(f.handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + writeln!( + output, + "64 warm transcript frames: {:.3} ms", + clock.elapsed().as_secs_f64() * 1_000.0 + ) + .unwrap(); + } + drop(output); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + window.hover(("agent-entry", 0usize), cx); + window.click(("copy-message", 0usize), cx); + assert_eq!( + cx.read_from_clipboard().unwrap().text().as_deref(), + Some(text.as_str()) + ); + }) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "focus-change performance fixture; run in isolation"] +fn measure_tab_repaint_with_restored_markdown(cx: &mut TestAppContext) { + use gpui_kit::{InputEvent as _, KeyDownEvent, KeyUpEvent, Keystroke}; + use std::{io::Write as _, time::Instant}; + + let f = fixture(cx); + cx.update(|cx| cx.set_reduce_motion(true)); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + for paragraph_count in [8, 4_096] { + let text = "A completed response with Unicode 世界.\n\n".repeat(paragraph_count); + thread.update(cx, |thread, cx| { + restore_entries(&f, thread, vec![Entry::Agent(text)], cx); + }); + let original_height = row_height(&f, cx); + let mut output = std::io::stdout().lock(); + for _ in 0..12 { + let elapsed = cx + .update_window(f.handle, |_, window, cx| { + let composer = f.panel.read(cx).composer_focus(cx); + window.focus(&composer, cx); + let position = window.find("agent-composer").bounds().center(); + window.simulate_mouse_move(position, cx); + window.draw(cx).clear(cx); + assert!(composer.is_focused(window)); + + let start = Instant::now(); + let tab = Keystroke::parse("tab").unwrap(); + window.dispatch_event( + KeyDownEvent { + keystroke: tab.clone(), + is_held: false, + prefer_character_input: false, + } + .to_platform_input(), + cx, + ); + window.dispatch_event(KeyUpEvent { keystroke: tab }.to_platform_input(), cx); + window.draw(cx).clear(cx); + let elapsed = start.elapsed(); + assert!(!composer.is_focused(window)); + assert_eq!( + window.find(("agent-entry", 0usize)).bounds().size.height, + original_height + ); + elapsed + }) + .unwrap(); + writeln!( + output, + "{paragraph_count} paragraphs, Tab + draw: {:.3} ms", + elapsed.as_secs_f64() * 1_000. + ) + .unwrap(); + } + } +} diff --git a/crates/agent/src/panel/tests/tool_input.rs b/crates/agent/src/panel/tests/tool_input.rs index caaf15b0..119d46f0 100644 --- a/crates/agent/src/panel/tests/tool_input.rs +++ b/crates/agent/src/panel/tests/tool_input.rs @@ -311,6 +311,60 @@ fn click_reveals_literal_source_copy_and_collapse_without_changing_result(cx: &m .unwrap(); } +#[gpui_kit::test] +#[ignore = "expanded ACP tool rendering performance fixture"] +fn measure_expanded_tool_during_output_updates(cx: &mut TestAppContext) { + let script = "printf '%s\\n' 'stable command'"; + let f = tool_fixture(cx, "Running a script", Some(json!({"command":script}))); + let session = cx.update(|cx| { + f.panel + .read(cx) + .current() + .unwrap() + .read(cx) + .session() + .clone() + .unwrap() + }); + cx.update_window(f.handle, |_, window, cx| { + window.click(("tool-call", 0usize), cx) + }) + .unwrap(); + settle(&f, cx); + let start = std::time::Instant::now(); + for index in 0..120 { + let output = format!("Line {index:04} ▸ output from a tool\n").repeat(750); + f.events + .try_send(AgentEvent::Session(SessionNotice::new( + session.clone(), + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + "script", + ToolChanges::default().raw_output(json!({"stdout":output})), + ))), + ))) + .unwrap(); + settle(&f, cx); + } + let elapsed = start.elapsed(); + cx.update_window(f.handle, |_, window, cx| { + window.click(("copy-tool-input", 0usize), cx); + assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), script); + window.click(("copy-tool-output-extra-0", 0usize), cx); + let output = cx.read_from_clipboard().unwrap().text().unwrap(); + assert_eq!( + serde_json::from_str::(&output).unwrap()["stdout"], + "Line 0119 ▸ output from a tool\n".repeat(750) + ); + }) + .unwrap(); + use std::io::Write as _; + writeln!( + std::io::stdout().lock(), + "120 visible tool output updates in {elapsed:?}" + ) + .unwrap(); +} + #[gpui_kit::test] fn actual_hover_tooltip_is_short_and_bounded(cx: &mut TestAppContext) { let f = tool_fixture(cx, &"very long tool title\n".repeat(400), None); diff --git a/crates/agent/src/panel/tests/tool_output.rs b/crates/agent/src/panel/tests/tool_output.rs index 8013e992..95dba282 100644 --- a/crates/agent/src/panel/tests/tool_output.rs +++ b/crates/agent/src/panel/tests/tool_output.rs @@ -464,3 +464,189 @@ fn unexpected_large_metadata_stays_inside_generic_bounded_output() { assert!(output.parameters.is_empty()); assert!(output.sections[0].text.contains("largelarge")); } + +#[test] +#[ignore = "manual expanded saved tool input/output projection workload"] +fn measure_expanded_bridge_projection() { + use crate::panel::entries::tool_input; + use std::{hint::black_box, io::Write as _, time::Instant}; + let bytes = std::env::var("NOCTERM_PROFILE_EXPANDED_BYTES") + .unwrap_or_else(|_| "65536".into()) + .parse::() + .unwrap(); + let mode = std::env::var("NOCTERM_PROFILE_EXPANDED_MODE").unwrap_or_else(|_| "both".into()); + let input = "x".repeat(bytes); + let stdout = "y".repeat(bytes); + let arguments = json!({"terminal_id":"t1","program":"sh","args":["-c",input]}); + let mut output = exec_result("exited"); + output["stdout"] = json!(stdout); + let mut display = ToolDisplay::requested("exec_command".into(), arguments.clone()); + display.finish(Ok(output)); + assert!(display.outcome.is_some()); + let mut call = ToolRecord::new("fixture", "mcp.nocterm-17.exec_command") + .status(ToolStatus::Succeeded) + .raw_input(arguments); + display.attach(&mut call); + let repeats = 1000; + let start = Instant::now(); + for _ in 0..repeats { + if mode != "output" { + let body = black_box(tool_input::source(black_box(&call))).unwrap(); + assert_eq!(body.text, input); + } + if mode != "input" { + let body = black_box(source(black_box(&call), false)).unwrap(); + assert_eq!(body.sections[0].text, stdout); + } + } + let elapsed = start.elapsed(); + writeln!( + std::io::stdout().lock(), + "mode={mode} bytes={bytes} repeats={repeats} elapsed_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} + +fn saved_generic_call(arguments: Value, outcome: Value) -> ToolRecord { + let mut display = ToolDisplay::requested("future_fixture".into(), arguments); + display.finish(Ok(outcome)); + assert!(display.outcome.is_some()); + let mut call = ToolRecord::new("fixture", "Nocterm future tool").status(ToolStatus::Succeeded); + display.attach(&mut call); + call +} + +#[test] +fn generic_literal_preserves_empty_values_separators_unicode_and_depth_limit() { + use crate::panel::entries::tool_input; + let mut deep = json!("not visible"); + for _ in 0..16 { + deep = json!([deep]); + } + let payload = json!({ + "a": [{}, "", [null, true, 12, "line\n界"]], + "b": {"empty": [], "nothing": null}, + "c": deep + }); + let expected = "a: \n\n\n\nNone\n\ntrue\n\n12\n\nline\n界\nb: empty: \nnothing: None\nc: …"; + let call = saved_generic_call(payload.clone(), payload); + let input = tool_input::source(&call).unwrap(); + let output = source(&call, false).unwrap(); + assert_eq!(input.label, "Requested parameters"); + assert_eq!(input.text, expected); + assert_eq!(output.sections[0].label, "Tool output"); + assert_eq!(output.sections[0].text, expected); +} + +#[test] +#[ignore = "manual nested generic tool formatting workload"] +fn measure_generic_tool_literal_projection() { + use crate::panel::entries::tool_input; + use std::{hint::black_box, io::Write as _, time::Instant}; + let bytes = std::env::var("NOCTERM_PROFILE_GENERIC_BYTES") + .unwrap_or_else(|_| "65536".into()) + .parse::() + .unwrap(); + let depth = std::env::var("NOCTERM_PROFILE_GENERIC_DEPTH") + .unwrap_or_else(|_| "6".into()) + .parse::() + .unwrap(); + assert!(depth <= 7); + let leaf = "界".repeat(bytes / 3); + let mut payload = json!({"leaf":leaf}); + for _ in 0..depth { + payload = json!({"layer":[payload]}); + } + let expected = format!("{}leaf: {leaf}", "layer: ".repeat(depth)); + let call = saved_generic_call(payload.clone(), payload); + let repeats = 1000; + let start = Instant::now(); + for _ in 0..repeats { + let input = black_box(tool_input::source(black_box(&call))).unwrap(); + assert_eq!(input.text, expected); + let output = black_box(source(black_box(&call), false)).unwrap(); + assert_eq!(output.sections[0].text, expected); + } + writeln!( + std::io::stdout().lock(), + "bytes={bytes} depth={depth} repeats={repeats} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); +} + +#[test] +#[ignore = "manual known command result projection workload"] +fn measure_known_tool_result_projection() { + use std::{hint::black_box, io::Write as _, time::Instant}; + let bytes = std::env::var("NOCTERM_PROFILE_KNOWN_BYTES") + .unwrap_or_else(|_| "65536".into()) + .parse::() + .unwrap(); + let mode = std::env::var("NOCTERM_PROFILE_KNOWN_MODE").unwrap_or_else(|_| "saved".into()); + let stdout = "x".repeat(bytes); + let mut payload = exec_result("exited"); + payload["stdout"] = json!(stdout); + let args = json!({"terminal_id":"t1","program":"true"}); + let mut fixture = call("exec_command", args.clone(), payload.clone(), false); + match mode.as_str() { + "saved" => { + let mut display = ToolDisplay::requested("exec_command".into(), args); + display.finish(Ok(payload)); + assert!(display.outcome.is_some()); + display.attach(&mut fixture); + } + "direct" => {} + "wrapped" => { + fixture.raw_output = + Some(json!({"result":{"content":[{"type":"text","text":payload.to_string()}]}})); + } + "duplicate" => { + fixture.content = serde_json::from_value(json!([ + {"type":"content","content":{"type":"text","text":payload.to_string()}} + ])) + .unwrap(); + } + _ => panic!("unknown workload"), + } + let repeats = 1000; + let start = Instant::now(); + for _ in 0..repeats { + let output = black_box(source(black_box(&fixture), false)).unwrap(); + assert_eq!(output.sections.len(), 2); + assert_eq!(output.sections[0].label, "Standard output"); + assert_eq!(output.sections[0].text, stdout); + assert!(output.parameters.contains(&"Process: Exited".into())); + } + writeln!( + std::io::stdout().lock(), + "mode={mode} bytes={bytes} repeats={repeats} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); +} + +#[test] +fn duplicate_check_preserves_an_independent_raw_result_when_content_exceeds_limits() { + let mut payload = exec_result("exited"); + let stdout = "x".repeat(512 * 1024); + payload["stdout"] = json!(stdout); + let mut call = call( + "exec_command", + json!({"terminal_id":"t1","program":"true"}), + payload.clone(), + false, + ); + call.content = serde_json::from_value(json!([ + {"type":"content","content":{"type":"text","text":payload.to_string()}} + ])) + .unwrap(); + let output = source(&call, false).unwrap(); + assert_eq!( + output.sections[0].text, + "Tool result exceeds display limits" + ); + assert_eq!(output.sections[1].label, "Standard output"); + assert_eq!(output.sections[1].text, stdout); +} diff --git a/crates/agent/src/panel/tests/tool_wrappers.rs b/crates/agent/src/panel/tests/tool_wrappers.rs index 15b02f40..1fcd1d42 100644 --- a/crates/agent/src/panel/tests/tool_wrappers.rs +++ b/crates/agent/src/panel/tests/tool_wrappers.rs @@ -281,3 +281,33 @@ fn truncated_preview_proof_requires_the_exact_count_and_one_successful_raw_text( ); } } + +#[test] +fn nested_owned_and_retained_provider_wrappers_have_identical_literal_parts() { + let payload = exec_result("exited"); + let args = json!({"terminal_id":"t1","program":"sh"}); + let nested = json!({"result":{"content":[ + {"type":"text","text":payload.to_string()}, + {"type":"text","text":"literal 界\n"}, + {"isError":true,"result":{"text":"denied"}}, + {"future":{"nested":[1,2]}} + ]}}); + for wrapper in [nested.clone(), json!(nested.to_string())] { + let output = source(&call("exec_command", args.clone(), wrapper, false), false).unwrap(); + let parts = output + .sections + .iter() + .map(|part| (part.label, part.text.as_str())) + .collect::>(); + assert_eq!( + parts, + vec![ + ("Standard output", payload["stdout"].as_str().unwrap()), + ("Standard error", payload["stderr"].as_str().unwrap()), + ("Tool output", "literal 界\n"), + ("Error", "text: denied"), + ("Tool output", "future: nested: 1\n\n2"), + ] + ); + } +} diff --git a/crates/agent/src/panel/widgets.rs b/crates/agent/src/panel/widgets.rs index 5045e9e7..abb0767e 100644 --- a/crates/agent/src/panel/widgets.rs +++ b/crates/agent/src/panel/widgets.rs @@ -4,7 +4,8 @@ use std::time::Duration; use gpui_kit::component::clipboard::Clipboard; use gpui_kit::{ - App, IntoElement, SharedString, TestSupportExt as _, + AnyElement, App, DefiniteLength, ImageSource, IntoElement, ObjectFit, SharedString, Size, + TestSupportExt as _, component::{ ActiveTheme as _, Sizable as _, button::{Button, ButtonCustomVariant, ButtonVariants as _}, @@ -15,7 +16,7 @@ use gpui_kit::{ }, div, prelude::*, - px, rems, + px, rems, size, }; use nocterm_ai::thread::Entry; use nocterm_ui::IconName; @@ -24,8 +25,32 @@ use crate::thread::Attachment; // Inline Markdown image URLs never trigger a resource request. Images travel // through explicit ACP image blocks and the same bounded validation as attachments. +const MARKDOWN_IMAGE: &str = "!["; +const HTML_IMAGE: &str = " String { - text.replace("![", "[").replace(" text.to_owned(), + (true, false) => text.replace(MARKDOWN_IMAGE, "["), + (false, true) => text.replace(HTML_IMAGE, "<img"), + (true, true) => text + .replace(MARKDOWN_IMAGE, "[") + .replace(HTML_IMAGE, "<img"), + } +} + +/// A marker completed by a new chunk may change the previously sanitized text. +pub(super) fn safe_markdown_extension(text: &str, previous: usize) -> Option { + let tail = text.get(previous..)?; + let prefix = &text[..previous]; + for marker in [MARKDOWN_IMAGE, HTML_IMAGE] { + if (1..marker.len()) + .any(|split| prefix.ends_with(&marker[..split]) && tail.starts_with(&marker[split..])) + { + return None; + } + } + Some(safe_markdown(tail)) } /// A compact visible label; the original text remains available in tooltips and data. @@ -114,19 +139,60 @@ pub(super) fn attachment_icon(attachment: &Attachment) -> IconName { } } /// A saved server's system icon, the size of a menu icon. -pub(super) fn server_image(icon: std::sync::Arc) -> gpui_kit::AnyElement { - gpui_kit::img(icon) - .size_4() +pub(super) fn server_image(icon: ImageSource) -> AnyElement { + visible_server_raster( + icon, + ObjectFit::Contain, + size(rems(1.).into(), rems(1.).into()), + ) +} + +pub(super) fn flag_image(flag: ImageSource) -> impl IntoElement { + div() .flex_shrink_0() - .into_any_element() + .rounded_xs() + .overflow_hidden() + .child(visible_server_raster( + flag, + ObjectFit::Cover, + size(px(16.).into(), px(11.).into()), + )) } -pub(super) fn flag_image(flag: std::sync::Arc) -> impl IntoElement { - div().flex_shrink_0().rounded_xs().overflow_hidden().child( - gpui_kit::img(flag) - .w(px(16.)) - .h(px(11.)) - .object_fit(gpui_kit::ObjectFit::Cover), + +fn visible_server_raster( + image: ImageSource, + fit: ObjectFit, + dimensions: Size, +) -> AnyElement { + let ImageSource::Custom(load) = image else { + return gpui_kit::img(image) + .w(dimensions.width) + .h(dimensions.height) + .flex_shrink_0() + .object_fit(fit) + .into_any_element(); + }; + // The menu lays out every server. Only visible artwork needs a raster. + gpui_kit::canvas( + |_, _, _| (), + move |bounds, (), window, cx| { + if bounds.intersects(&window.content_mask().bounds) + && let Some(Ok(image)) = load(window, cx) + && image.frame_count() > 0 + { + let image_bounds = fit.get_bounds(bounds, image.size(0)); + if let Err(error) = + window.paint_image(bounds, image_bounds, Default::default(), image, 0, false) + { + tracing::warn!(%error, "could not paint saved server image"); + } + } + }, ) + .w(dimensions.width) + .h(dimensions.height) + .flex_shrink_0() + .into_any_element() } pub(super) fn running_dot(cx: &App) -> impl IntoElement { div() diff --git a/crates/ai/src/agents/available.rs b/crates/ai/src/agents/available.rs index 0e33196e..fee9894c 100644 --- a/crates/ai/src/agents/available.rs +++ b/crates/ai/src/agents/available.rs @@ -63,20 +63,58 @@ pub struct AvailableAgents { impl AvailableAgents { /// Catalog agents, overridden, disabled or extended by `settings`. pub fn resolve(catalog: &AgentCatalog, settings: &AiSettings) -> Self { - let mut launches: BTreeMap = catalog - .iter() + Self::resolve_entries( + catalog, + catalog.iter(), + settings.agents.iter(), + settings.enabled, + ) + } + + /// One local agent under the same settings and rules as the complete + /// directory, without resolving unrelated entries or their warnings. + pub fn resolve_one( + catalog: &AgentCatalog, + settings: &AiSettings, + id: &str, + ) -> Option { + if !settings.enabled { + return None; + } + let Some(override_entry) = settings.agents.get_key_value(id) else { + let profile = catalog.get(id).copied()?; + return Some(AvailableAgent { + launch: profile.default_launch(), + source: AgentSource::Builtin, + profile: Some(profile), + }); + }; + Self::resolve_entries(catalog, catalog.get(id), [override_entry], true) + .agents + .into_values() + .next() + } + + fn resolve_entries<'a>( + catalog: &AgentCatalog, + profiles: impl IntoIterator, + overrides: impl IntoIterator, + enabled: bool, + ) -> Self { + let mut launches: BTreeMap = profiles + .into_iter() .map(|profile| { let launch = profile.default_launch(); (launch.id.clone(), (launch, AgentSource::Builtin)) }) .collect(); let mut warnings = Vec::new(); - for (id, setting) in &settings.agents { + for (id, setting) in overrides { if let Err(warning) = apply(&mut launches, id, setting) { warnings.push(warning); } } - if !settings.enabled { + if !enabled { launches.clear(); } let agents = launches diff --git a/crates/ai/src/agents/tests.rs b/crates/ai/src/agents/tests.rs index 30a66cf3..8779ece4 100644 --- a/crates/ai/src/agents/tests.rs +++ b/crates/ai/src/agents/tests.rs @@ -223,3 +223,55 @@ fn a_hub_window_offers_its_hub_agents_and_a_local_window_none() { AgentLaunch::hub_agent(home, "a1".into(), "x".into()).id ); } + +#[test] +fn single_agent_resolution_matches_complete_directory() { + let mut settings = AiSettings::default(); + let defaults = catalog(); + let default_agents = AvailableAgents::resolve(&defaults, &settings); + for id in ["alpha", "beta", "unknown"] { + assert_eq!( + AvailableAgents::resolve_one(&defaults, &settings, id), + default_agents.get(id).cloned() + ); + } + settings + .agents + .insert("alpha".into(), custom("/opt/alpha-acp")); + settings.agents.insert( + "beta".into(), + AgentServerSettings { + enabled: false, + ..Default::default() + }, + ); + settings + .agents + .insert("custom".into(), custom("/opt/alpha-acp")); + settings.agents.insert("other".into(), custom("/opt/other")); + settings + .agents + .insert("invalid/id".into(), custom("/opt/other")); + settings + .agents + .insert("missing-command".into(), Default::default()); + for enabled in [true, false] { + settings.enabled = enabled; + let catalog = catalog(); + let all = AvailableAgents::resolve(&catalog, &settings); + for id in [ + "alpha", + "beta", + "custom", + "other", + "invalid/id", + "missing-command", + "unknown", + ] { + assert_eq!( + AvailableAgents::resolve_one(&catalog, &settings, id), + all.get(id).cloned() + ); + } + } +} diff --git a/crates/ai/src/history/size.rs b/crates/ai/src/history/size.rs index e2d522c8..3c358e31 100644 --- a/crates/ai/src/history/size.rs +++ b/crates/ai/src/history/size.rs @@ -1,4 +1,4 @@ -//! Exact compact JSON byte count without allocating the encoded payload. +//! Exact compact JSON length and conservative retained size without encoding the payload. use serde::{ Serialize, ser::{self, SerializeMap, SerializeSeq, SerializeStruct}, @@ -6,14 +6,20 @@ use serde::{ use std::io; pub(super) fn encoded_len(value: &impl Serialize) -> Result { - let mut counter = Counter(0, 0); + let mut counter = Counter { + encoded: Some(0), + structural: 0, + }; value.serialize(&mut counter)?; - Ok(counter.0) + Ok(counter.encoded.expect("encoded counting is enabled")) } pub(super) fn structural_size(value: &impl Serialize) -> Result { - let mut counter = Counter(0, 0); + let mut counter = Counter { + encoded: None, + structural: 0, + }; value.serialize(&mut counter)?; - Ok(counter.1) + Ok(counter.structural) } /// Examine sixteen bytes at once; ordinary UTF-8 and base64 need no escaping. fn string_len(text: &str) -> usize { @@ -41,7 +47,23 @@ fn string_len(text: &str) -> usize { } length + remainder.iter().copied().map(extra).sum::() } -struct Counter(usize, usize); +struct Counter { + encoded: Option, + structural: usize, +} +impl Counter { + fn add_encoded(&mut self, bytes: usize) { + if let Some(encoded) = &mut self.encoded { + *encoded += bytes; + } + } + + fn add_encoded_string(&mut self, text: &str, framing: usize) { + if let Some(encoded) = &mut self.encoded { + *encoded += string_len(text) + framing; + } + } +} struct Compound<'a> { counter: &'a mut Counter, first: bool, @@ -52,19 +74,21 @@ impl Compound<'_> { if self.first { self.first = false; } else { - self.counter.0 += 1; + self.counter.add_encoded(1); } } fn finish(self) -> Result<(), serde_json::Error> { - self.counter.0 += self.close; + self.counter.add_encoded(self.close); Ok(()) } } macro_rules! number { ($name:ident, $ty:ty) => { fn $name(self, value: $ty) -> Result<(), Self::Error> { - self.1 += 512; - self.0 += serde_json::to_string(&value)?.len(); + self.structural += 512; + if let Some(encoded) = &mut self.encoded { + *encoded += serde_json::to_string(&value)?.len(); + } Ok(()) } }; @@ -80,8 +104,8 @@ impl<'a> ser::Serializer for &'a mut Counter { type SerializeStruct = Compound<'a>; type SerializeStructVariant = Compound<'a>; fn serialize_bool(self, value: bool) -> Result<(), Self::Error> { - self.1 += 512; - self.0 += if value { 4 } else { 5 }; + self.structural += 512; + self.add_encoded(if value { 4 } else { 5 }); Ok(()) } number!(serialize_i8, i8); @@ -100,8 +124,8 @@ impl<'a> ser::Serializer for &'a mut Counter { self.serialize_str(value.encode_utf8(&mut [0; 4])) } fn serialize_str(self, value: &str) -> Result<(), Self::Error> { - self.1 += 512 + value.len() * 2; - self.0 += string_len(value); + self.structural += 512 + value.len() * 2; + self.add_encoded_string(value, 0); Ok(()) } fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> { @@ -118,8 +142,8 @@ impl<'a> ser::Serializer for &'a mut Counter { value.serialize(self) } fn serialize_unit(self) -> Result<(), Self::Error> { - self.1 += 512; - self.0 += 4; + self.structural += 512; + self.add_encoded(4); Ok(()) } fn serialize_unit_struct(self, _: &'static str) -> Result<(), Self::Error> { @@ -147,13 +171,13 @@ impl<'a> ser::Serializer for &'a mut Counter { variant: &'static str, value: &T, ) -> Result<(), Self::Error> { - self.1 += 1536 + variant.len() * 2; - self.0 += string_len(variant) + 3; + self.structural += 1536 + variant.len() * 2; + self.add_encoded_string(variant, 3); value.serialize(self) } fn serialize_seq(self, _: Option) -> Result, Self::Error> { - self.1 += 512; - self.0 += 1; + self.structural += 512; + self.add_encoded(1); Ok(Compound { counter: self, first: true, @@ -177,8 +201,8 @@ impl<'a> ser::Serializer for &'a mut Counter { variant: &'static str, _: usize, ) -> Result, Self::Error> { - self.1 += 1536 + variant.len() * 2; - self.0 += string_len(variant) + 3; + self.structural += 1536 + variant.len() * 2; + self.add_encoded_string(variant, 3); Ok(Compound { counter: self, first: true, @@ -186,8 +210,8 @@ impl<'a> ser::Serializer for &'a mut Counter { }) } fn serialize_map(self, _: Option) -> Result, Self::Error> { - self.1 += 512; - self.0 += 1; + self.structural += 512; + self.add_encoded(1); Ok(Compound { counter: self, first: true, @@ -204,8 +228,8 @@ impl<'a> ser::Serializer for &'a mut Counter { variant: &'static str, _: usize, ) -> Result, Self::Error> { - self.1 += 1536 + variant.len() * 2; - self.0 += string_len(variant) + 3; + self.structural += 1536 + variant.len() * 2; + self.add_encoded_string(variant, 3); Ok(Compound { counter: self, first: true, @@ -240,8 +264,7 @@ impl SerializeMap for Compound<'_> { type Error = serde_json::Error; fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> { self.comma(); - let old = self.counter.0; - self.counter.0 += match serde_json::to_value(key)? { + let encoded_key = match serde_json::to_value(key)? { serde_json::Value::String(text) => string_len(&text), serde_json::Value::Number(number) => number.to_string().len() + 2, serde_json::Value::Bool(value) => { @@ -256,8 +279,10 @@ impl SerializeMap for Compound<'_> { "invalid JSON map key", ))); } - } + 1; - self.counter.1 += 512 + self.counter.0.saturating_sub(old + 3) * 2; + }; + // Map keys retain the existing conservative charge for the escaped spelling. + self.counter.structural += 512 + encoded_key.saturating_sub(2) * 2; + self.counter.add_encoded(encoded_key + 1); Ok(()) } fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> { @@ -276,8 +301,8 @@ impl SerializeStruct for Compound<'_> { value: &T, ) -> Result<(), Self::Error> { self.comma(); - self.counter.1 += 512 + key.len() * 2; - self.counter.0 += string_len(key) + 1; + self.counter.structural += 512 + key.len() * 2; + self.counter.add_encoded_string(key, 1); value.serialize(&mut *self.counter) } fn end(self) -> Result<(), Self::Error> { @@ -301,6 +326,26 @@ impl ser::SerializeStructVariant for Compound<'_> { #[cfg(test)] mod tests { use super::*; + #[test] + fn retained_size_charges_value_lengths_and_escaped_map_keys() { + use std::collections::BTreeMap; + let key = "界\u{0000}\n"; + let value = "x\u{0000}\n\\"; + assert_eq!(structural_size(&value).unwrap(), 512 + value.len() * 2); + + let record = BTreeMap::from([(key, value)]); + let escaped_key = "界\\u0000\\n"; + assert_eq!( + structural_size(&record).unwrap(), + 3 * 512 + (escaped_key.len() + value.len()) * 2 + ); + assert_eq!( + encoded_len(&record).unwrap(), + serde_json::to_vec(&record).unwrap().len() + ); + assert!(structural_size(&BTreeMap::from([([1, 2], false)])).is_err()); + } + #[test] fn unicode_control_bytes_and_every_chunk_boundary_match_json() { for length in 0..80 { diff --git a/crates/ai/src/images.rs b/crates/ai/src/images.rs index 6867f3c5..264a7bb8 100644 --- a/crates/ai/src/images.rs +++ b/crates/ai/src/images.rs @@ -49,16 +49,25 @@ impl ImageCollectionBudget { Ok(()) } } + /// Largest source that can fit both the individual and remaining collection limits. + pub fn max_source_bytes(self) -> usize { + MAX_IMAGE_BYTES.min(self.remaining_bytes()) + } + /// Refuses before decoding or encoding the incoming image. pub fn admit(&mut self, bytes: usize) -> Result<(), ImageCollectionError> { self.check_count(1)?; - if bytes > MAX_TOTAL_IMAGE_BYTES.saturating_sub(self.bytes) { + if bytes > self.remaining_bytes() { return Err(ImageCollectionError); } self.count += 1; self.bytes += bytes; Ok(()) } + + fn remaining_bytes(self) -> usize { + MAX_TOTAL_IMAGE_BYTES - self.bytes + } } #[derive(Clone, Debug)] pub struct PromptImage { @@ -74,33 +83,54 @@ impl PromptImage { data: Vec, inspector: &dyn ImageInspector, ) -> Result { + Self::validate_using(data, |bytes| { + inspector.inspect(bytes).map(|image| (image, ())) + }) + .map(|(image, ())| image) + } + pub fn validate_for_preview( + data: Vec, + inspector: &dyn ImageInspector, + ) -> Result<(Self, Option>), PromptImageError> { + Self::validate_using(data, |bytes| inspector.inspect_for_preview(bytes)) + } + fn validate_using( + data: Vec, + inspect: impl FnOnce(std::sync::Arc<[u8]>) -> Result<(InspectedImage, T), ImageCodecError>, + ) -> Result<(Self, T), PromptImageError> { let facts = preflight(&data).map_err(PromptImageError::from)?; let data: std::sync::Arc<[u8]> = data.into(); - let inspected = inspector - .inspect(data.clone()) - .map_err(PromptImageError::from)?; + let (inspected, extra) = inspect(data.clone()).map_err(PromptImageError::from)?; if !std::sync::Arc::ptr_eq(&data, inspected.bytes()) || inspected.facts() != facts { return Err(PromptImageError::Decode(ImageCodecError::InvalidEvidence)); } let mime = facts.format().mime(); let content = Content::Image(Image::new(STANDARD.encode(&data), mime)); let encoded_len = crate::history::content_size(&content)?; - Ok(Self { + let image = Self { mime_type: mime.into(), data, width: facts.width(), height: facts.height(), content: std::sync::Arc::new(content), encoded_len, - }) + }; + Ok((image, extra)) } pub fn content(&self) -> Content { (*self.content).clone() } + /// Encoded data shared by the prompt and its transcript projection. + pub fn encoded_data(&self) -> &crate::model::content::ImageData { + let Content::Image(image) = self.content.as_ref() else { + unreachable!("prompt image content invariant"); + }; + &image.data + } pub fn bytes(&self) -> &[u8] { &self.data } - /// Shared immutable source for retained background decoding and preview identity. + /// Shared immutable source for background decoding. pub fn shared_bytes(&self) -> std::sync::Arc<[u8]> { self.data.clone() } diff --git a/crates/ai/src/images/codec.rs b/crates/ai/src/images/codec.rs index aaf7954d..b886092e 100644 --- a/crates/ai/src/images/codec.rs +++ b/crates/ai/src/images/codec.rs @@ -91,10 +91,16 @@ impl ImageFacts { self.height } } -pub fn preflight(bytes: &[u8]) -> Result { - if bytes.is_empty() || bytes.len() > MAX_IMAGE_BYTES { +/// Checks the source length before it can be retained for later inspection. +pub fn check_source_size(len: usize) -> Result<(), ImageCodecError> { + if len == 0 || len > MAX_IMAGE_BYTES { return Err(ImageCodecError::SourceSize); } + Ok(()) +} + +pub fn preflight(bytes: &[u8]) -> Result { + check_source_size(bytes.len())?; let (format, width, height) = header::dimensions(bytes).ok_or(ImageCodecError::UnsupportedFormat)?; ImageFacts::new(format, width, height) @@ -120,6 +126,28 @@ impl InspectedImage { } pub trait ImageInspector: Send + Sync { fn inspect(&self, bytes: Arc<[u8]>) -> Result; + + /// Inspect the original and optionally return transient work for its first preview. + /// Retain the existing physical work permit until the preview work finishes or drops. + fn inspect_for_preview( + &self, + bytes: Arc<[u8]>, + ) -> Result<(InspectedImage, Option>), ImageCodecError> { + self.inspect(bytes).map(|image| (image, None)) + } +} +/// A validated native decode that can produce one preview without decoding the original again. +/// It can retain a full-size decoded image, so it belongs to in-flight work. +pub trait DecodedPreviewSource: Send { + fn thumbnail(self: Box, bounds: PreviewBounds) + -> Result; + + fn render_preview( + self: Box, + bounds: PreviewBounds, + ) -> Result { + self.thumbnail(bounds).map(PreviewImage::Png) + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct PreviewBounds { @@ -175,10 +203,75 @@ impl EncodedPreview { (self.width, self.height) } } + +/// A checked transport for a single preview frame. +pub enum PreviewImage { + Png(EncodedPreview), + Pixels(PreviewPixels), +} +impl PreviewImage { + /// Validate the returned frame against the bounds of this request. + pub fn check_bounds(&self, bounds: PreviewBounds) -> Result<(), ImageCodecError> { + let (width, height) = match self { + Self::Png(preview) => preview.dimensions(), + Self::Pixels(preview) => preview.dimensions(), + }; + if width > bounds.width() || height > bounds.height() { + return Err(ImageCodecError::InvalidEvidence); + } + Ok(()) + } +} + +/// Owned row-major RGBA8 pixels with nonzero dimensions and no stride padding. +#[derive(Debug)] +pub struct PreviewPixels { + rgba: Vec, + width: u32, + height: u32, +} +impl PreviewPixels { + pub fn new( + width: u32, + height: u32, + rgba: Vec, + bounds: PreviewBounds, + ) -> Result { + if width == 0 + || height == 0 + || width > bounds.width() + || height > bounds.height() + || rgba.len() != width as usize * height as usize * 4 + || rgba.capacity() > MAX_PREVIEW_BYTES + { + return Err(ImageCodecError::InvalidEvidence); + } + Ok(Self { + rgba, + width, + height, + }) + } + pub fn dimensions(&self) -> (u32, u32) { + (self.width, self.height) + } + pub fn into_rgba(self) -> Vec { + self.rgba + } +} + pub trait ImageThumbnailer: Send + Sync { fn thumbnail( &self, bytes: Arc<[u8]>, bounds: PreviewBounds, ) -> Result; + + fn render_preview( + &self, + bytes: Arc<[u8]>, + bounds: PreviewBounds, + ) -> Result { + self.thumbnail(bytes, bounds).map(PreviewImage::Png) + } } diff --git a/crates/ai/src/images/tests.rs b/crates/ai/src/images/tests.rs index a66bcf93..53b665d8 100644 --- a/crates/ai/src/images/tests.rs +++ b/crates/ai/src/images/tests.rs @@ -3,6 +3,27 @@ use super::*; use crate::model::content::Content; use crate::testing::{ScriptedImageCodec, images::png_header_fixture}; use std::sync::Arc; +#[test] +fn preview_pixels_require_bounded_dimensions_and_exact_owned_bytes() { + let bounds = PreviewBounds::new(4, 3).unwrap(); + assert!(PreviewPixels::new(0, 3, Vec::new(), bounds).is_err()); + assert!(PreviewPixels::new(5, 1, vec![0; 20], bounds).is_err()); + assert!(PreviewPixels::new(4, 3, vec![0; 47], bounds).is_err()); + assert!(PreviewPixels::new(4, 3, vec![0; 49], bounds).is_err()); + let mut overallocated = Vec::with_capacity(MAX_PREVIEW_BYTES + 1); + overallocated.extend_from_slice(&[0; 4]); + assert!(PreviewPixels::new(1, 1, overallocated, bounds).is_err()); + let frame = PreviewPixels::new(4, 3, vec![5; 48], bounds).unwrap(); + assert_eq!(frame.dimensions(), (4, 3)); + assert_eq!(frame.into_rgba(), vec![5; 48]); + let frame = PreviewImage::Pixels(PreviewPixels::new(4, 3, vec![5; 48], bounds).unwrap()); + assert!( + frame + .check_bounds(PreviewBounds::new(3, 3).unwrap()) + .is_err() + ); +} + fn codec(bytes: &[u8]) -> ScriptedImageCodec { let codec = ScriptedImageCodec::default(); codec.inspection(bytes, Ok(preflight(bytes).unwrap())); diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs index d19bee24..b6e63df0 100644 --- a/crates/ai/src/lib.rs +++ b/crates/ai/src/lib.rs @@ -16,7 +16,7 @@ //! AgentStateRepository, ChatRepository and bounded PreparedChatLoad, //! workspace::WorkdirResolver, sandbox::SandboxProbe and //! images::{ImageInspector, ImageThumbnailer}. -//! Image preflight and encoded admission are pure; native decoding is injected. +//! Image preflight, encoded admission and preview result bounds are pure; native decoding is injected. //! ImageCodecCause reuses core shared causes without exposing a native codec type. //! Workspace preparation and sandbox spawn diagnostics retain typed shared native I/O; //! adapter constructors preserve classification without changing policy or mount authority. diff --git a/crates/ai/src/model/content.rs b/crates/ai/src/model/content.rs index 1a171931..b29db087 100644 --- a/crates/ai/src/model/content.rs +++ b/crates/ai/src/model/content.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none}; #[path = "image_data.rs"] mod image_data; -pub use image_data::ImageData; +pub use image_data::{ImageData, ImageIdentity}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] diff --git a/crates/ai/src/model/image_data.rs b/crates/ai/src/model/image_data.rs index 11db7418..d04b3926 100644 --- a/crates/ai/src/model/image_data.rs +++ b/crates/ai/src/model/image_data.rs @@ -1,16 +1,40 @@ //! Immutable encoded image data: clones share their allocation and wire bytes stay a string. use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{ops::Deref, sync::Arc}; +use std::{ + ops::Deref, + sync::{Arc, Weak}, +}; + +/// Keeps an allocation key reserved without keeping the encoded bytes alive. +pub struct ImageIdentity { + _allocation: Weak, +} + +impl ImageIdentity { + /// The allocation framing retained by the weak identity after its bytes drop. + pub const RETAINED_BYTES: usize = + std::mem::size_of::() + 2 * std::mem::size_of::(); +} #[derive(Clone, Debug, PartialEq, Eq)] pub struct ImageData(Arc); impl ImageData { + /// Process-local allocation key, valid while a clone or identity is held. + pub fn allocation_key(&self) -> usize { + Arc::as_ptr(&self.0).addr() + } + + pub fn identity(&self) -> ImageIdentity { + ImageIdentity { + _allocation: Arc::downgrade(&self.0), + } + } + /// The normalized encoded allocation and its owned String/Arc framing. pub fn retained_bytes(&self) -> usize { self.0 .capacity() - .saturating_add(std::mem::size_of::()) - .saturating_add(2 * std::mem::size_of::()) + .saturating_add(ImageIdentity::RETAINED_BYTES) } } impl Deref for ImageData { @@ -77,4 +101,17 @@ mod tests { ); assert_eq!(String::from(copy), "encoded image"); } + + #[test] + fn preview_identity_reserves_the_key_without_sharing_the_bytes() { + let data = ImageData::from("encoded image".repeat(128)); + let key = data.allocation_key(); + assert_eq!(data.clone().allocation_key(), key); + let identity = data.identity(); + let bytes = data.as_ptr(); + let owned = String::from(data); + assert_eq!(owned.as_ptr(), bytes); + assert_ne!(ImageData::from(owned).allocation_key(), key); + drop(identity); + } } diff --git a/crates/ai/src/model/session.rs b/crates/ai/src/model/session.rs index 735c7a21..ad2d893a 100644 --- a/crates/ai/src/model/session.rs +++ b/crates/ai/src/model/session.rs @@ -155,9 +155,17 @@ pub enum TurnActivity { Ended, } +/// A provider's explicit observation of whether the session is running work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionActivity { + Active, + Idle, +} + #[derive(Clone, Debug, Default, PartialEq)] pub struct SessionInfo { pub title: Change, + pub activity: Option, pub meta: Option, } diff --git a/crates/ai/src/model/tools.rs b/crates/ai/src/model/tools.rs index 77a29b2b..e74d232c 100644 --- a/crates/ai/src/model/tools.rs +++ b/crates/ai/src/model/tools.rs @@ -45,8 +45,7 @@ fn is_default(value: &T) -> bool { } #[serde_as] -#[skip_serializing_none] -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolRecord { #[serde(rename = "toolCallId")] @@ -56,16 +55,16 @@ pub struct ToolRecord { #[serde(default)] pub name: Option, #[serde_as(deserialize_as = "DefaultOnError")] - #[serde(default, skip_serializing_if = "is_default")] + #[serde(default)] pub kind: ToolKind, #[serde_as(deserialize_as = "DefaultOnError")] - #[serde(default, skip_serializing_if = "is_default")] + #[serde(default)] pub status: ToolStatus, #[serde_as(deserialize_as = "DefaultOnError>")] - #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[serde(default)] pub content: Vec, #[serde_as(deserialize_as = "DefaultOnError>")] - #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[serde(default)] pub locations: Vec, #[serde_as(deserialize_as = "DefaultOnError")] #[serde(default)] @@ -77,7 +76,68 @@ pub struct ToolRecord { #[serde(default, rename = "_meta")] pub meta: Option, } +/// Canonical borrowed serialization of a tool row, including a projected +/// sparse patch. The owned row and pre-admission projection share this shape. +#[skip_serializing_none] +#[derive(Serialize)] +#[serde(rename = "ToolRecord", rename_all = "camelCase")] +struct ToolRecordView<'a> { + #[serde(rename = "toolCallId")] + id: &'a ToolId, + title: &'a str, + name: Option<&'a str>, + #[serde(skip_serializing_if = "is_default")] + kind: ToolKind, + #[serde(skip_serializing_if = "is_default")] + status: ToolStatus, + #[serde(skip_serializing_if = "<[ToolContent]>::is_empty")] + content: &'a [ToolContent], + #[serde(skip_serializing_if = "<[Location]>::is_empty")] + locations: &'a [Location], + raw_input: Option<&'a Value>, + raw_output: Option<&'a Value>, + #[serde(rename = "_meta")] + meta: Option<&'a Extensions>, +} + +impl Serialize for ToolRecord { + fn serialize(&self, serializer: S) -> Result { + self.view().serialize(serializer) + } +} impl ToolRecord { + fn view(&self) -> ToolRecordView<'_> { + ToolRecordView { + id: &self.id, + title: &self.title, + name: self.name.as_deref(), + kind: self.kind, + status: self.status, + content: &self.content, + locations: &self.locations, + raw_input: self.raw_input.as_ref(), + raw_output: self.raw_output.as_ref(), + meta: self.meta.as_ref(), + } + } + + /// Borrow the same canonical fields that would result from applying the + /// patch, without copying the accepted row or the incoming data. + pub(crate) fn projected<'a>(&'a self, changes: &'a ToolChanges) -> impl Serialize + 'a { + let view = self.view(); + ToolRecordView { + title: changes.title.as_deref().unwrap_or(view.title), + name: changes.name.as_deref().or(view.name), + kind: changes.kind.unwrap_or(view.kind), + status: changes.status.unwrap_or(view.status), + content: changes.content.as_deref().unwrap_or(view.content), + locations: changes.locations.as_deref().unwrap_or(view.locations), + raw_input: changes.raw_input.as_ref().or(view.raw_input), + raw_output: changes.raw_output.as_ref().or(view.raw_output), + ..view + } + } + pub fn new(id: impl Into, title: impl Into) -> Self { Self { id: id.into(), diff --git a/crates/ai/src/redact.rs b/crates/ai/src/redact.rs index 71e6a2a5..31630934 100644 --- a/crates/ai/src/redact.rs +++ b/crates/ai/src/redact.rs @@ -42,11 +42,16 @@ static AUTHORIZATION: LazyLock = LazyLock::new(|| { ) .expect("authorization pattern") }); +const SECRET_NAMES: &str = concat!( + "(?:password|passwd|passphrase|secret|api[_-]?key|access[_-]?key|", + "private[_-]?key|access[_-]?token|auth[_-]?token|refresh[_-]?token|client[_-]?secret|token)" +); +// A necessary substring of every assignment key, with the same Unicode case folding. +static SECRET_NAME: LazyLock = + LazyLock::new(|| Regex::new(&format!("(?i){SECRET_NAMES}")).expect("secret names")); static ASSIGNMENT: LazyLock = LazyLock::new(|| { - Regex::new(concat!( - r#"(?i)\b([a-z0-9_.-]*(?:password|passwd|passphrase|secret|api[_-]?key|access[_-]?key|"#, - r#"private[_-]?key|access[_-]?token|auth[_-]?token|refresh[_-]?token|client[_-]?secret|token)[a-z0-9_.-]*)"#, - r#"(["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|(?:bearer\s+)?[^\s,;"']+)"#, + Regex::new(&format!( + r#"(?i)\b([a-z0-9_.-]*{SECRET_NAMES}[a-z0-9_.-]*)(["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|(?:bearer\s+)?[^\s,;"']+)"#, )) .expect("secret pattern") }); @@ -57,9 +62,36 @@ pub fn redact(text: &str) -> String { let value = TOKEN.replace_all(&value, "[REDACTED TOKEN]"); let value = URL_CREDENTIALS.replace_all(&value, "${1}[REDACTED]@"); let value = AUTHORIZATION.replace_all(&value, "$1: [REDACTED]"); - ASSIGNMENT - .replace_all(&value, "$1$2[REDACTED]") - .into_owned() + let mut redacted = String::new(); + let mut copied = 0; + let mut locations = None; + while let Some(name) = SECRET_NAME.find_at(&value, copied) { + // A key cannot start before the line containing the next required + // name or before the end of the preceding assignment match. + let start = value[copied..name.start()] + .rfind('\n') + .map_or(copied, |line| copied + line + 1); + let locations = locations.get_or_insert_with(|| ASSIGNMENT.capture_locations()); + let Some(matched) = ASSIGNMENT.captures_read_at(locations, &value, start) else { + break; + }; + let (key_start, key_end) = locations.get(1).expect("assignment key"); + let (separator_start, separator_end) = locations.get(2).expect("assignment separator"); + if copied == 0 { + redacted.reserve(value.len()); + } + redacted.push_str(&value[copied..matched.start()]); + redacted.push_str(&value[key_start..key_end]); + redacted.push_str(&value[separator_start..separator_end]); + redacted.push_str("[REDACTED]"); + copied = matched.end(); + } + if copied == 0 { + value.into_owned() + } else { + redacted.push_str(&value[copied..]); + redacted + } } #[cfg(test)] @@ -128,4 +160,80 @@ mod tests { let text = "total 12\ndrwxr-xr-x 2 root root 4096 token_count.rs\nssh user@host -p 22"; assert_eq!(redact(text), text); } + + #[test] + fn masks_case_folded_assignment_names_after_long_unicode_output() { + let prefix = "Процесс ▸ fixture completed: no change\n".repeat(800); + let text = format!("{prefix}DATA_PAſſWORD=example API_KEY: \"dummy\""); + assert_eq!( + redact(&text), + format!("{prefix}DATA_PAſſWORD=[REDACTED] API_KEY: [REDACTED]") + ); + } + + #[test] + fn preserves_complete_lines_before_the_first_assignment() { + let prefix = "ordinary output: ready\r\nПроцесс ▸ completed\n".repeat(20); + let text = format!("{prefix}CLIENT_SECRET=fixture-only\napi_key: 'value'\nfinished"); + assert_eq!( + redact(&text), + format!("{prefix}CLIENT_SECRET=[REDACTED]\napi_key: [REDACTED]\nfinished") + ); + } + + #[test] + fn keeps_name_mentions_without_assignments_and_masks_later_fields() { + let text = "ordinary output\npassword info\nstatus completed\nsecret=fixture-only"; + assert_eq!( + redact(text), + "ordinary output\npassword info\nstatus completed\nsecret=[REDACTED]" + ); + assert_eq!( + redact("ordinary output\npassword info"), + "ordinary output\npassword info" + ); + } + + #[test] + fn masks_separated_assignments_and_preserves_long_plain_output() { + let middle = "Процесс ▸ fixture completed: no change\n".repeat(100); + let text = format!("CLIENT_SECRET=fixture-only\n{middle}api_key: 'value'\n{middle}"); + assert_eq!( + redact(&text), + format!("CLIENT_SECRET=[REDACTED]\n{middle}api_key: [REDACTED]\n{middle}") + ); + } + + #[test] + #[ignore = "manual large tool and terminal output fixture"] + fn measure_redacting_long_unicode_output() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let plain = "Процесс ▸ fixture completed: no change\n".repeat(800); + let with_secret = format!("{plain}CLIENT_SECRET=fixture-only"); + let masked = format!("{plain}CLIENT_SECRET=[REDACTED]"); + let early = format!("CLIENT_SECRET=fixture-only\n{plain}"); + let early_masked = format!("CLIENT_SECRET=[REDACTED]\n{plain}"); + let dense = "Status fixture CLIENT_SECRET=fixture-only\n".repeat(800); + let dense_masked = "Status fixture CLIENT_SECRET=[REDACTED]\n".repeat(800); + for (input, expected) in [ + (&plain, &plain), + (&with_secret, &masked), + (&early, &early_masked), + (&dense, &dense_masked), + ] { + assert_eq!(&redact(input), expected); + let start = Instant::now(); + for _ in 0..120 { + black_box(redact(black_box(input))); + } + writeln!( + std::io::stdout().lock(), + "120 redactions of {} bytes in {:?}", + input.len(), + start.elapsed() + ) + .unwrap(); + } + } } diff --git a/crates/ai/src/session.rs b/crates/ai/src/session.rs index 0bee37ab..9df9d9b4 100644 --- a/crates/ai/src/session.rs +++ b/crates/ai/src/session.rs @@ -5,7 +5,7 @@ //! session" or "failed but still accepting updates" cannot be built. The //! transitions only decide; the chat performs the side effects they ask for //! and drops async results whose [`Ticket`] is no longer current. -use crate::AgentError; +use crate::{AgentError, model::session::SessionActivity}; /// Where a chat's agent session is. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -69,6 +69,8 @@ pub struct SessionState { failures: u32, /// The running turn was started by the agent for another device. external: bool, + /// Latest explicit provider activity, including events racing a prompt response. + observed_active: bool, } impl SessionState { @@ -216,6 +218,31 @@ impl SessionState { self.phase = SessionPhase::Ready; true } + /// Observe session-wide activity without completing a client-owned prompt. + /// Returns whether the visible turn changed; duplicate observations do not redraw. + pub fn observe_activity(&mut self, activity: SessionActivity) -> bool { + if !matches!( + self.phase, + SessionPhase::Opening + | SessionPhase::Ready + | SessionPhase::Prompting + | SessionPhase::Cancelling + ) { + return false; + } + let was_active = self.observed_active; + self.observed_active = activity == SessionActivity::Active; + if self.observed_active { + self.resume_observed_turn() + } else { + was_active && self.finish_external_turn() + } + } + /// A provider may start another turn before the preceding prompt response arrives. + /// Reconcile after the client has settled its own turn and its tool bookkeeping. + pub fn resume_observed_turn(&mut self) -> bool { + self.observed_active && self.start_external_turn() + } /// The running turn is the agent's own, not one of this chat's prompts. pub fn external_turn(&self) -> bool { self.external && self.generating() @@ -234,19 +261,22 @@ impl SessionState { /// The turn of `ticket` finished. Returns whether it was the running /// one; a stale result changes nothing. pub fn finish_turn(&mut self, ticket: Ticket, completed: bool) -> bool { - if !self.turn_current(ticket) || !self.generating() { + if !self.turn_current(ticket) || !self.generating() || self.external { return false; } self.external = false; self.phase = SessionPhase::Ready; if completed { self.failures = 0; + } else { + self.observed_active = false; } true } /// The agent asks the user to sign in. pub fn require_sign_in(&mut self) { self.phase = SessionPhase::SignInRequired; + self.observed_active = false; } /// Returns whether signing in may start. pub fn begin_sign_in(&mut self) -> bool { @@ -271,6 +301,7 @@ impl SessionState { /// The session ended with an error. Results of its requests are dropped. pub fn fail(&mut self) { self.external = false; + self.observed_active = false; self.phase = SessionPhase::Failed; self.epoch += 1; self.stopped = false; @@ -280,6 +311,8 @@ impl SessionState { /// The chat let its connection go. A failed chat stays failed, so the /// user still sees why; otherwise it is detached until needed again. pub fn detach(&mut self) { + self.external = false; + self.observed_active = false; self.epoch += 1; self.closing = true; if self.phase != SessionPhase::Failed { @@ -288,6 +321,8 @@ impl SessionState { } /// The chat released everything it held, a failure included. pub fn release(&mut self) { + self.external = false; + self.observed_active = false; self.phase = SessionPhase::Detached; self.stopped = false; self.discarding = false; diff --git a/crates/ai/src/session/tests.rs b/crates/ai/src/session/tests.rs index 386e1f7c..b7adae18 100644 --- a/crates/ai/src/session/tests.rs +++ b/crates/ai/src/session/tests.rs @@ -173,3 +173,60 @@ fn a_turn_the_agent_runs_for_another_device_shows_and_ends_on_its_own() { ); assert!(state.finish_turn(ticket, true)); } + +#[test] +fn reported_activity_survives_an_earlier_prompt_response() { + let mut state = ready(); + let local = state.start_turn().unwrap(); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(!state.observe_activity(SessionActivity::Idle)); + assert!( + state.generating(), + "idle never completes the client's request" + ); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.finish_turn(local, true)); + assert!(state.resume_observed_turn()); + assert!(state.generating() && state.busy() && state.external_turn()); + assert!(!state.finish_turn(local, true)); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.start_turn().is_none()); + assert!(state.observe_activity(SessionActivity::Idle)); + assert!(!state.generating()); + assert!(!state.observe_activity(SessionActivity::Idle)); + assert!(state.start_turn().is_some()); +} + +#[test] +fn reported_activity_can_be_cancelled_and_cannot_survive_session_replacement() { + let mut state = ready(); + assert!(state.observe_activity(SessionActivity::Active)); + assert!(state.stop()); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.observe_activity(SessionActivity::Idle)); + assert!(!state.generating() && state.stopped()); + assert!(state.observe_activity(SessionActivity::Active)); + state.detach(); + assert!(!state.observe_activity(SessionActivity::Active)); + state.closed(); + assert!(state.queue()); + state.leased(); + state.opened(); + assert!(!state.resume_observed_turn()); + assert!(!state.generating()); +} + +#[test] +fn normal_prompt_completion_and_cancel_do_not_invent_a_continuation() { + let mut state = ready(); + let turn = state.start_turn().unwrap(); + state.observe_activity(SessionActivity::Active); + state.observe_activity(SessionActivity::Idle); + assert!(state.finish_turn(turn, true)); + assert!(!state.resume_observed_turn()); + let turn = state.start_turn().unwrap(); + state.observe_activity(SessionActivity::Active); + assert!(state.stop()); + assert!(state.finish_turn(turn, false)); + assert!(!state.resume_observed_turn()); +} diff --git a/crates/ai/src/storage.rs b/crates/ai/src/storage.rs index 776f4994..6ee9de82 100644 --- a/crates/ai/src/storage.rs +++ b/crates/ai/src/storage.rs @@ -160,6 +160,14 @@ pub trait ChatRepository: Send + Sync { }) } } + /// Reads the catalog already available on this device. A repository that also + /// refreshes from a remote source must leave that refresh out of this read. + fn catalog_cached_in( + &self, + scope: crate::local_environment::ChatScope, + ) -> StorageFuture> { + self.catalog_in(scope) + } fn load_in( &self, scope: crate::local_environment::ChatScope, diff --git a/crates/ai/src/testing/images.rs b/crates/ai/src/testing/images.rs index 4ce50999..a76c5b9d 100644 --- a/crates/ai/src/testing/images.rs +++ b/crates/ai/src/testing/images.rs @@ -1,7 +1,7 @@ //! Byte-keyed supplied image evidence; never decodes or infers successful evidence. use crate::images::{ - EncodedPreview, ImageCodecError, ImageFacts, ImageInspector, ImageThumbnailer, InspectedImage, - PreviewBounds, + DecodedPreviewSource, EncodedPreview, ImageCodecError, ImageFacts, ImageInspector, + ImageThumbnailer, InspectedImage, PreviewBounds, }; use std::{ collections::{HashMap, HashSet}, @@ -18,6 +18,7 @@ struct Script { previews: HashMap, Result>, requests: Vec, replaced: HashSet>, + reuse_inspected_decode: bool, } #[derive(Clone, Default)] pub struct ScriptedImageCodec { @@ -48,6 +49,12 @@ impl ScriptedImageCodec { pub fn requests(&self) -> Vec { self.script.lock().expect("image script").requests.clone() } + pub fn reuse_inspected_decode(&self) { + self.script + .lock() + .expect("image script") + .reuse_inspected_decode = true; + } } impl ImageInspector for ScriptedImageCodec { fn inspect(&self, bytes: Arc<[u8]>) -> Result { @@ -70,6 +77,29 @@ impl ImageInspector for ScriptedImageCodec { }; InspectedImage::new(bytes, result?) } + + fn inspect_for_preview( + &self, + bytes: Arc<[u8]>, + ) -> Result<(InspectedImage, Option>), ImageCodecError> { + let image = self.inspect(bytes)?; + let script = self.script.lock().expect("image script"); + let decoded = script + .reuse_inspected_decode + .then(|| script.previews.get(image.bytes().as_ref())) + .flatten() + .map(|result| { + Box::new(SuppliedPreview(result.clone())) as Box + }); + Ok((image, decoded)) + } +} + +struct SuppliedPreview(Result); +impl DecodedPreviewSource for SuppliedPreview { + fn thumbnail(self: Box, _: PreviewBounds) -> Result { + self.0 + } } impl ImageThumbnailer for ScriptedImageCodec { fn thumbnail( diff --git a/crates/ai/src/testing/storage.rs b/crates/ai/src/testing/storage.rs index abdc5a70..a3c7bc9e 100644 --- a/crates/ai/src/testing/storage.rs +++ b/crates/ai/src/testing/storage.rs @@ -19,6 +19,7 @@ pub enum StorageOperation { LoadState, SaveState, Catalog, + CachedCatalog, Load(String), /// Pause after materialization while the actual decoded body retains its lease. Decoded(String), @@ -127,6 +128,39 @@ impl InMemoryAgentRepository { pub fn clear_rejection(&self, operation: &StorageOperation) { self.state.lock().unwrap().rejected.remove(operation); } + fn read_catalog( + &self, + scope: ChatScope, + operation: StorageOperation, + ) -> StorageFuture> { + let this = self.clone(); + Box::pin(async move { + this.begin(operation).await?; + let state = this.state.lock().unwrap(); + let mut rows = state + .chats + .get(&scope) + .into_iter() + .flat_map(BTreeMap::iter) + .filter_map(|(id, bytes)| { + history::decode_summary( + bytes, + id, + FileStamp { + bytes: bytes.len() as u64, + modified_nanos: 0, + }, + ) + .ok() + .flatten() + }) + .filter(|row| row.chat_scope() == scope) + .collect::>(); + rows.sort_by_key(|row| std::cmp::Reverse((row.pinned, row.updated))); + rows.truncate(history::MAX_RESTORED); + Ok(rows) + }) + } async fn begin(&self, operation: StorageOperation) -> Result<(), AgentStorageError> { let barrier = { let mut state = self.state.lock().unwrap(); @@ -203,33 +237,10 @@ impl ChatRepository for InMemoryAgentRepository { self.delete_in(scope.into(), id) } fn catalog_in(&self, scope: ChatScope) -> StorageFuture> { - let this = self.clone(); - Box::pin(async move { - this.begin(StorageOperation::Catalog).await?; - let state = this.state.lock().unwrap(); - let mut rows = state - .chats - .get(&scope) - .into_iter() - .flat_map(BTreeMap::iter) - .filter_map(|(id, bytes)| { - history::decode_summary( - bytes, - id, - FileStamp { - bytes: bytes.len() as u64, - modified_nanos: 0, - }, - ) - .ok() - .flatten() - }) - .filter(|row| row.chat_scope() == scope) - .collect::>(); - rows.sort_by_key(|row| std::cmp::Reverse((row.pinned, row.updated))); - rows.truncate(history::MAX_RESTORED); - Ok(rows) - }) + self.read_catalog(scope, StorageOperation::Catalog) + } + fn catalog_cached_in(&self, scope: ChatScope) -> StorageFuture> { + self.read_catalog(scope, StorageOperation::CachedCatalog) } fn load_in(&self, scope: ChatScope, id: String) -> StorageFuture { let this = self.clone(); diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs index f91707f4..9016a61c 100644 --- a/crates/ai/src/tests.rs +++ b/crates/ai/src/tests.rs @@ -82,6 +82,7 @@ fn update(value: serde_json::Value) -> SessionUpdate { Some(serde_json::Value::Null) => Change::Clear, Some(title) => Change::Set(title.as_str().unwrap().into()), }, + activity: None, meta: None, }), "usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new( diff --git a/crates/ai/src/thread/live.rs b/crates/ai/src/thread/live.rs index 6fe22e7f..c746976a 100644 --- a/crates/ai/src/thread/live.rs +++ b/crates/ai/src/thread/live.rs @@ -2,10 +2,18 @@ use super::{Entry, ThreadState}; use crate::{ history::{HistoryCodecError, MAX_RESIDENT_BYTES, retained_value_bytes}, - model::{content::Content, controls::Change, session::SessionUpdate}, + model::{ + content::Content, + controls::Change, + session::SessionUpdate, + tools::{ToolChanges, ToolPatch, ToolRecord}, + }, }; +use std::vec; const MAX_LIVE_ENTRIES: usize = 20_000; +mod tool_rows; +pub use tool_rows::ToolRows; pub fn resident_bytes(state: &ThreadState) -> Result { Ok(retained_value_bytes(&state.entries)? .saturating_add(plan_bytes(state.plan.as_ref())) @@ -58,20 +66,135 @@ pub fn admit_update( current: usize, update: &SessionUpdate, ) -> Result { + if let SessionUpdate::ToolCallUpdate(patch) = update { + return match state.entries.iter().find_map(|entry| match entry { + Entry::Tool(call) if call.id == patch.id => Some(call), + _ => None, + }) { + Some(record) => admit_tool_change(record, &patch.changes, current, state.entries.len()), + None => Ok(current), + }; + } let Some((removed, added, row)) = update_change(state, update)? else { return Ok(current); }; if state.entries.len().saturating_add(usize::from(row)) > MAX_LIVE_ENTRIES { return Err(HistoryCodecError::CollectionLimit); } - let next = current - .saturating_sub(removed) - .saturating_add(added) - .saturating_add(usize::from(row) * 8); - if next > MAX_RESIDENT_BYTES { + checked_bytes( + current + .saturating_sub(removed) + .saturating_add(added) + .saturating_add(usize::from(row) * 8), + ) +} + +fn checked_bytes(bytes: usize) -> Result { + if bytes > MAX_RESIDENT_BYTES { return Err(HistoryCodecError::StructuralLimit); } - Ok(next) + Ok(bytes) +} + +/// Build a replacement from a provider's complete history. Adjacent fragments +/// of a text row share one reservation after they pass the normal live budget. +pub fn replay_history( + title: Option, + updates: Vec, + now: u64, +) -> Result<(ThreadState, usize), HistoryCodecError> { + let mut state = ThreadState { + title, + ..ThreadState::default() + }; + let mut bytes = resident_bytes(&state)?; + let mut updates = updates.into_iter(); + let mut tool_rows = ToolRows::default(); + while let Some(update) = updates.next() { + if let SessionUpdate::ToolCallUpdate(patch) = update { + bytes = replay_tool_patch(&mut state, &mut tool_rows, bytes, *patch)?; + continue; + } + bytes = admit_update(&state, bytes, &update)?; + let rows_before = state.entries.len(); + let kind = match &update { + SessionUpdate::AgentMessageChunk(Content::Text(_)) => Some(false), + SessionUpdate::AgentThoughtChunk(Content::Text(_)) => Some(true), + _ => None, + }; + state.apply(update, now); + if let Some(Entry::Tool(call)) = state.entries.get(rows_before) { + tool_rows.appended(&call.id, rows_before); + } + if let Some(thought) = kind { + let new_row = state.entries.len() != rows_before; + bytes = append_text_run(&mut state, bytes, &mut updates, thought, new_row)?; + } + } + Ok((state, bytes)) +} + +fn replay_tool_patch( + state: &mut ThreadState, + tool_rows: &mut ToolRows, + bytes: usize, + patch: ToolPatch, +) -> Result { + let Some(row) = tool_rows.find(&state.entries, &patch.id) else { + return Ok(bytes); + }; + let rows = state.entries.len(); + let Entry::Tool(call) = &mut state.entries[row] else { + unreachable!("tool row lookup returns a matching tool"); + }; + let bytes = admit_tool_change(call, &patch.changes, bytes, rows)?; + call.apply(patch.changes); + Ok(bytes) +} + +fn text_fragment(update: &SessionUpdate, thought: bool) -> Option<&str> { + match (update, thought) { + (SessionUpdate::AgentMessageChunk(Content::Text(text)), false) + | (SessionUpdate::AgentThoughtChunk(Content::Text(text)), true) => Some(&text.text), + _ => None, + } +} + +fn appended_text_bytes(length: usize) -> usize { + length.saturating_mul(2) +} + +fn append_text_run( + state: &mut ThreadState, + bytes: usize, + updates: &mut vec::IntoIter, + thought: bool, + new_row: bool, +) -> Result { + let (count, length) = updates + .as_slice() + .iter() + .map_while(|update| text_fragment(update, thought)) + .fold((0, 0usize), |(count, length), text| { + (count + 1, length.saturating_add(text.len())) + }); + if count == 0 { + return Ok(bytes); + } + let bytes = checked_bytes(bytes.saturating_add(appended_text_bytes(length)))?; + let Some(Entry::Agent(row) | Entry::Thought(row)) = state.entries.last_mut() else { + unreachable!("applying a text fragment creates or extends a text row"); + }; + if new_row { + row.reserve_exact(length); + } else { + // Metadata can separate runs that still append to the same row. + row.reserve(length); + } + for update in updates.take(count) { + row.push_str(text_fragment(&update, thought).expect("counted text fragment")); + } + Ok(bytes) } fn update_change( @@ -84,7 +207,7 @@ fn update_change( match (content, state.entries.last(), thought) { (Content::Text(text), Some(Entry::Agent(_)), false) | (Content::Text(text), Some(Entry::Thought(_)), true) => { - (0, text.text.len().saturating_mul(2), false) + (0, appended_text_bytes(text.text.len()), false) } _ => (0, retained_value_bytes(content)?.saturating_add(4096), true), } @@ -97,28 +220,25 @@ fn update_change( SessionUpdate::ToolCall(call) => { (0, retained_value_bytes(call)?.saturating_add(4096), true) } - SessionUpdate::ToolCallUpdate(patch) => return tool_change(state, patch), _ => return control_change(state, update), }; Ok(Some(change)) } -fn tool_change( - state: &ThreadState, - patch: &crate::model::tools::ToolPatch, -) -> Result, HistoryCodecError> { - let Some(original) = state.entries.iter().find_map(|entry| match entry { - Entry::Tool(call) if call.id == patch.id => Some(call), - _ => None, - }) else { - return Ok(None); - }; - let mut candidate = original.clone(); - candidate.apply(patch.changes.clone()); - Ok(Some(( - retained_value_bytes(original)?, - retained_value_bytes(&candidate)?, - false, - ))) +/// Admits replacement of a tool row already located by the transcript owner. +/// The owner must still apply the same patch only after the budget succeeds. +pub fn admit_tool_change( + original: &ToolRecord, + changes: &ToolChanges, + current: usize, + rows: usize, +) -> Result { + let candidate = original.projected(changes); + let removed = retained_value_bytes(original)?; + let added = retained_value_bytes(&candidate)?; + if rows > MAX_LIVE_ENTRIES { + return Err(HistoryCodecError::CollectionLimit); + } + checked_bytes(current.saturating_sub(removed).saturating_add(added)) } fn control_change( state: &ThreadState, @@ -151,6 +271,59 @@ fn control_change( #[cfg(test)] mod tests { use super::*; + #[test] + fn replay_preserves_mixed_text_rows_titles_timestamps_and_the_admitted_size() { + use crate::model::session::SessionInfo; + let title = Some("Original".into()); + let updates = vec![ + SessionUpdate::AgentMessageChunk(Content::text("")), + SessionUpdate::AgentMessageChunk(Content::text("λ")), + SessionUpdate::SessionInfoUpdate(SessionInfo { + title: Change::Set("Provider title".into()), + activity: None, + meta: None, + }), + SessionUpdate::AgentMessageChunk(Content::text("中")), + SessionUpdate::AgentMessageChunk(Content::text("🐈")), + SessionUpdate::AgentThoughtChunk(Content::text("think")), + SessionUpdate::AgentThoughtChunk(Content::text("ing")), + SessionUpdate::UserMessageChunk(Content::text("next")), + SessionUpdate::AgentMessageChunk(Content::text("answer")), + ]; + let mut incremental = ThreadState { + title: title.clone(), + ..ThreadState::default() + }; + let mut admitted = resident_bytes(&incremental).unwrap(); + for update in updates.iter().cloned() { + admitted = admit_update(&incremental, admitted, &update).unwrap(); + incremental.apply(update, 17); + } + let (restored, bytes) = replay_history(title, updates, 17).unwrap(); + assert_eq!(restored.title, incremental.title); + assert_eq!(restored.times, incremental.times); + assert_eq!( + serde_json::to_value(restored.entries).unwrap(), + serde_json::to_value(incremental.entries).unwrap() + ); + assert_eq!(bytes, admitted); + } + + #[test] + fn replay_refuses_a_text_run_that_would_exceed_the_live_budget() { + let first = SessionUpdate::AgentMessageChunk(Content::text( + "x".repeat(MAX_RESIDENT_BYTES / 2 - 16 * 1024), + )); + let empty = ThreadState::default(); + let bytes = resident_bytes(&empty).unwrap(); + assert!(admit_update(&empty, bytes, &first).is_ok()); + let tail = SessionUpdate::AgentMessageChunk(Content::text("x".repeat(32 * 1024))); + assert!(matches!( + replay_history(None, vec![first, tail], 17), + Err(HistoryCodecError::StructuralLimit) + )); + } + #[test] fn repeated_small_chunks_refuse_before_changing_the_accepted_transcript() { let mut state = ThreadState::default(); @@ -234,3 +407,9 @@ mod tests { assert!(resident_bytes(&state).unwrap() <= bytes); } } + +#[cfg(test)] +mod tool_admission_tests; + +#[cfg(test)] +mod replay_tool_tests; diff --git a/crates/ai/src/thread/live/replay_tool_tests.rs b/crates/ai/src/thread/live/replay_tool_tests.rs new file mode 100644 index 00000000..cda5bfda --- /dev/null +++ b/crates/ai/src/thread/live/replay_tool_tests.rs @@ -0,0 +1,98 @@ +use super::*; +use crate::model::tools::{ToolPatch, ToolStatus}; + +fn call(id: &str) -> SessionUpdate { + SessionUpdate::ToolCall(Box::new(ToolRecord::new(id, "orig"))) +} + +fn patch(id: &str, title: &str) -> SessionUpdate { + SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + id, + ToolChanges::default() + .title(title) + .status(ToolStatus::Succeeded), + ))) +} + +#[test] +fn replay_patches_match_incremental_reduction_across_duplicate_and_missing_ids() { + let mut updates = vec![patch("same", "before"), call("same")]; + for i in 0..128 { + let id = format!("other-{i}"); + updates.extend([call(&id), patch(&id, "done")]); + } + updates.extend([ + call("same"), + patch("same", "first changed"), + patch("missing", "ignored"), + SessionUpdate::AgentMessageChunk(Content::text("answer")), + SessionUpdate::AgentMessageChunk(Content::text(" continuation")), + call("new"), + patch("new", "last changed"), + ]); + let mut incremental = ThreadState::default(); + let mut bytes = resident_bytes(&incremental).unwrap(); + for update in updates.iter().cloned() { + bytes = admit_update(&incremental, bytes, &update).unwrap(); + incremental.apply(update, 17); + } + let (replayed, replayed_bytes) = replay_history(None, updates, 17).unwrap(); + assert_eq!(replayed_bytes, bytes); + assert_eq!(replayed.times, incremental.times); + assert_eq!( + serde_json::to_value(&replayed.entries).unwrap(), + serde_json::to_value(&incremental.entries).unwrap() + ); + assert!(matches!(&replayed.entries[0], Entry::Tool(call) if call.title == "first changed")); + assert!(matches!(&replayed.entries[129], Entry::Tool(call) if call.title == "orig")); +} + +#[test] +fn replay_rejects_growth_beyond_the_row_ceiling_after_tool_patches() { + let mut updates = (0..MAX_LIVE_ENTRIES) + .map(|i| call(&format!("tool-{i}"))) + .collect::>(); + updates.push(patch("tool-19999", "done")); + updates.push(call("over")); + assert!(matches!( + replay_history(None, updates, 1), + Err(HistoryCodecError::CollectionLimit) + )); +} + +#[test] +#[ignore = "manual complete tool-history replay workload"] +fn measure_history_replay() { + use std::{io::Write as _, time::Instant}; + let rows = std::env::var("NOCTERM_PROFILE_REPLAY_ROWS") + .unwrap_or_else(|_| "16000".into()) + .parse::() + .unwrap(); + let mode = + std::env::var("NOCTERM_PROFILE_REPLAY_MODE").unwrap_or_else(|_| "interleaved".into()); + let mut updates = Vec::new(); + for i in 0..rows { + let id = format!("tool-{i:05}"); + updates.push(call(&id)); + if mode == "interleaved" { + updates.push(patch(&id, "done")); + } + } + if mode == "deferred" { + for i in (0..rows).rev() { + updates.push(patch(&format!("tool-{i:05}"), "done")); + } + } + let start = Instant::now(); + let (state, bytes) = replay_history(None, updates, 17).unwrap(); + let elapsed = start.elapsed(); + assert_eq!(state.entries.len(), rows); + assert!(state.entries.iter().all(|entry| matches!(entry, Entry::Tool(call) if call.title == if mode == "append" { "orig" } else { "done" }))); + assert!(resident_bytes(&state).unwrap() <= bytes); + writeln!( + std::io::stdout().lock(), + "rows={rows} mode={mode} elapsed_ns={} admitted_bytes={bytes}", + elapsed.as_nanos() + ) + .unwrap(); +} diff --git a/crates/ai/src/thread/live/tool_admission_tests.rs b/crates/ai/src/thread/live/tool_admission_tests.rs new file mode 100644 index 00000000..05c24fbf --- /dev/null +++ b/crates/ai/src/thread/live/tool_admission_tests.rs @@ -0,0 +1,144 @@ +use crate::{ + history::{HistoryCodecError, MAX_RESIDENT_BYTES, retained_value_bytes}, + model::{ + extensions::Extensions, + session::SessionUpdate, + tools::{Location, ToolChanges, ToolContent, ToolKind, ToolPatch, ToolRecord, ToolStatus}, + }, + thread::{Entry, ThreadState, live}, +}; +use serde_json::{Value, json}; + +fn tool(payload: usize) -> ToolRecord { + let mut record = ToolRecord::new("call", "literal output") + .name("tool") + .kind(ToolKind::Execute) + .status(ToolStatus::Running) + .content(vec![ToolContent::from("λ".repeat(payload / 2))]) + .raw_input(Some(json!({"input": "i".repeat(payload)}))) + .raw_output(Some(json!({"output": "o".repeat(payload)}))) + .meta(Some(Extensions::from(serde_json::Map::from_iter([( + "ε\\key".into(), + json!([true, null, "m".repeat(payload)]), + )])))); + record.locations = vec![Location { + path: "example.txt".into(), + line: Some(12), + meta: None, + }]; + record +} + +fn state(record: ToolRecord) -> ThreadState { + let mut state = ThreadState::default(); + state.apply(SessionUpdate::ToolCall(Box::new(record)), 42); + state +} + +#[test] +fn tool_admission_matches_owned_reduction_for_sparse_and_clearing_patches() { + let base = tool(128); + for original in [ToolRecord::new("call", ""), base] { + let state = state(original.clone()); + let previous = live::resident_bytes(&state).unwrap(); + let old = retained_value_bytes(&original).unwrap(); + for mask in 0..256 { + let patch = ToolChanges { + kind: (mask & 1 != 0).then_some(ToolKind::Other), + status: (mask & 2 != 0).then_some(ToolStatus::Pending), + title: (mask & 4 != 0).then(String::new), + name: (mask & 8 != 0).then(String::new), + content: (mask & 16 != 0).then(Vec::new), + locations: (mask & 32 != 0).then(Vec::new), + raw_input: (mask & 64 != 0).then_some(Value::Null), + raw_output: (mask & 128 != 0).then_some(Value::Null), + }; + let mut expected = original.clone(); + expected.apply(patch.clone()); + assert_eq!( + serde_json::to_vec(&original.projected(&patch)).unwrap(), + serde_json::to_vec(&expected).unwrap() + ); + let update = SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new("call", patch))); + let admitted = live::admit_update(&state, previous, &update).unwrap(); + assert_eq!( + admitted, + previous - old + retained_value_bytes(&expected).unwrap() + ); + let mut reduced = state.clone(); + reduced.apply(update, 99); + assert!(matches!(&reduced.entries[0], Entry::Tool(actual) if actual == &expected)); + assert_eq!(reduced.times, [42]); + assert_eq!(live::resident_bytes(&reduced).unwrap(), admitted); + } + } +} + +#[test] +fn tool_admission_keeps_the_accepted_row_when_growth_is_rejected() { + let record = tool(1024); + let state = state(record.clone()); + let patch = ToolChanges::default().raw_output(json!({"output":"new".repeat(2048)})); + let update = SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new("call", patch))); + // Represents a document whose other rows already occupy the remaining budget. + assert!(matches!( + live::admit_update(&state, MAX_RESIDENT_BYTES, &update), + Err(HistoryCodecError::StructuralLimit) + )); + assert!(matches!(&state.entries[0], Entry::Tool(actual) if actual == &record)); + let missing = SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new( + "missing", + ToolChanges::default().status(ToolStatus::Succeeded), + ))); + assert_eq!( + live::admit_update(&state, MAX_RESIDENT_BYTES, &missing).unwrap(), + MAX_RESIDENT_BYTES + ); +} + +#[test] +#[ignore = "manual live tool admission CPU and allocation workload"] +fn measure_live_tool_admission() { + use std::{hint::black_box, io::Write as _, time::Instant}; + let payload = std::env::var("NOCTERM_PROFILE_TOOL_BYTES") + .unwrap_or_else(|_| "1048576".into()) + .parse::() + .unwrap(); + let mode = std::env::var("NOCTERM_PROFILE_TOOL_MODE").unwrap_or_else(|_| "status".into()); + let repeats = if payload < 1024 { 100_000 } else { 2_000 }; + let state = state(tool(payload)); + let previous = live::resident_bytes(&state).unwrap(); + let patch = match mode.as_str() { + "status" => ToolChanges::default().status(ToolStatus::Succeeded), + "output" => ToolChanges::default().raw_output(json!({ + "output": "new".repeat(payload / 3) + })), + "reject" => ToolChanges::default().raw_output(json!({ + "output": "new".repeat(payload) + })), + "clear" => ToolChanges::default().content(Vec::new()), + _ => panic!("unknown benchmark mode"), + }; + let update = SessionUpdate::ToolCallUpdate(Box::new(ToolPatch::new("call", patch))); + let current = if mode == "reject" { + MAX_RESIDENT_BYTES + } else { + previous + }; + let expected = live::admit_update(&state, current, &update); + assert_eq!(expected.is_err(), mode == "reject"); + let start = Instant::now(); + let mut digest = 0_usize; + for _ in 0..repeats { + let result = live::admit_update(black_box(&state), black_box(current), black_box(&update)); + digest = digest.wrapping_add(result.unwrap_or(usize::MAX)); + } + let elapsed = start.elapsed(); + assert_eq!(digest, expected.unwrap_or(usize::MAX).wrapping_mul(repeats)); + writeln!( + std::io::stdout().lock(), + "mode={mode} bytes={payload} repeats={repeats} elapsed_ns={} digest={digest}", + elapsed.as_nanos() + ) + .unwrap(); +} diff --git a/crates/ai/src/thread/live/tool_rows.rs b/crates/ai/src/thread/live/tool_rows.rs new file mode 100644 index 00000000..ba2ad8fd --- /dev/null +++ b/crates/ai/src/thread/live/tool_rows.rs @@ -0,0 +1,86 @@ +//! A derived lookup for append-only transcript identities. The accepted row +//! remains the authority; fingerprints only select a possible first match. +use super::MAX_LIVE_ENTRIES; +use crate::{model::ids::ToolId, thread::Entry}; +use std::{collections::HashMap, hash::BuildHasher as _}; + +const INDEX_THRESHOLD: usize = 64; + +/// Derived lookup for a single append-only sequence of tool identities. +/// Start with a fresh index when replacing, truncating or reordering rows. +/// Feed every appended tool once the index is initialized. The row's exact +/// identity, not its fingerprint, determines the first matching entry. +#[derive(Clone, Default)] +pub struct ToolRows { + // One first row per fingerprint, not another copy of provider IDs. + index: Option>, +} + +impl ToolRows { + pub fn find(&mut self, entries: &[Entry], id: &ToolId) -> Option { + // Restored and live transcripts share the 20,000-row ceiling. Do + // not construct an index for a larger, unadmitted synthetic state. + if entries.len() > MAX_LIVE_ENTRIES + || (entries.len() < INDEX_THRESHOLD && self.index.is_none()) + { + return first_match(entries, id); + } + let index = self.index.get_or_insert_with(|| { + let mut index = HashMap::new(); + for (row, entry) in entries.iter().enumerate() { + if let Entry::Tool(call) = entry { + insert_first(&mut index, &call.id, row); + } + } + index + }); + let row = *index.get(&index.hasher().hash_one(id))?; + resolve_candidate(entries, id, row) + } + + pub fn appended(&mut self, id: &ToolId, row: usize) { + if let Some(index) = &mut self.index + && row < MAX_LIVE_ENTRIES + { + insert_first(index, id, row); + } + } +} + +fn insert_first(index: &mut HashMap, id: &ToolId, row: usize) { + let fingerprint = index.hasher().hash_one(id); + index.entry(fingerprint).or_insert(row); +} + +fn first_match(entries: &[Entry], id: &ToolId) -> Option { + entries + .iter() + .position(|entry| matches!(entry, Entry::Tool(call) if &call.id == id)) +} + +fn resolve_candidate(entries: &[Entry], id: &ToolId, row: usize) -> Option { + if matches!(entries.get(row), Some(Entry::Tool(call)) if &call.id == id) { + return Some(row); + } + // Another ID can have the same fingerprint. Never use a hash match + // as identity, and preserve the reducer's first occurrence rule. + first_match(entries, id) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::tools::ToolRecord; + + #[test] + fn a_colliding_fingerprint_resolves_only_the_first_exact_id() { + let entries = [ + Entry::Tool(ToolRecord::new("other", "collision candidate")), + Entry::Tool(ToolRecord::new("wanted", "first")), + Entry::Tool(ToolRecord::new("wanted", "duplicate")), + ]; + assert_eq!(resolve_candidate(&entries, &"wanted".into(), 0), Some(1)); + assert_eq!(resolve_candidate(&entries, &"missing".into(), 0), None); + assert_eq!(resolve_candidate(&entries, &"other".into(), 0), Some(0)); + } +} diff --git a/crates/ai/src/tool_display.rs b/crates/ai/src/tool_display.rs index 37719b02..4f44be15 100644 --- a/crates/ai/src/tool_display.rs +++ b/crates/ai/src/tool_display.rs @@ -1,6 +1,8 @@ //! Client-owned presentation of requested Nocterm operations. This is saved with //! the transcript so a later profile rename or reconnect cannot rewrite history. -use serde::{Deserialize, Serialize}; +use std::borrow::{Borrow, Cow}; + +use serde::{Deserialize, Serialize, de::IgnoredAny}; use serde_json::{Value, json}; use crate::{ @@ -15,25 +17,28 @@ pub const META_KEY: &str = "nocterm/tool-display"; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub enum ToolOutcome { +pub enum ToolOutcome { Pending, - Ok(Value), - Err(String), + Ok(Payload), + Err(Text), } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ToolDisplay { +pub struct ToolDisplay { pub version: u8, - pub tool: String, - pub arguments: Value, - pub destination: Option, + pub tool: Text, + pub arguments: Payload, + pub destination: Option, #[serde(default)] pub redacted: bool, #[serde(default, skip_serializing_if = "Option::is_none")] - pub outcome: Option, + pub outcome: Option>, } +/// Read-only projection of saved metadata; ordinary V2 payloads stay in the record. +pub type ToolDisplayView<'a> = ToolDisplay, Cow<'a, Value>>; + impl ToolDisplay { pub fn new(call: &TerminalCall, destination: Option) -> Self { let (tool, arguments) = request(call); @@ -76,11 +81,16 @@ impl ToolDisplay { .then_some(display) } - /// Display data has already been validated before execution. Redaction can - /// expand its text beyond execution limits, so only deserialize its shape. - /// Never pass this request back to an executor. - pub fn display_request(&self) -> Option { - deserialize(&self.tool, self.arguments.clone()) + /// Borrow saved presentation data without copying the opposite payload. + /// Legacy and unusual JSON representations retain the owned decoding semantics. + pub fn view(call: &ToolRecord) -> Option> { + let value = call.meta.as_ref()?.get(META_KEY)?; + borrowed_view(value).or_else(|| Self::from_call(call).map(owned_view)) + } + + /// Whether the saved annotation is valid without projecting its payload. + pub fn has_valid_metadata(call: &ToolRecord) -> bool { + header_fields(call).is_some() } pub fn redact(&mut self) { @@ -111,21 +121,106 @@ impl ToolDisplay { } } +impl, Payload: Borrow> ToolDisplay { + /// Display data has already been validated before execution. Redaction can + /// expand its text beyond execution limits, so only deserialize its shape. + /// Never pass this request back to an executor. + pub fn display_request(&self) -> Option { + deserialize(self.tool.as_ref(), self.arguments.borrow().clone()) + } +} + +fn borrowed_view(value: &Value) -> Option> { + let shape = ToolDisplay::<&str, IgnoredAny>::deserialize(value).ok()?; + if shape.version != 2 || !value.is_object() || contains_serde_marker(value) { + return None; + } + let outcome = match shape.outcome { + Some(ToolOutcome::Pending) => Some(ToolOutcome::Pending), + Some(ToolOutcome::Ok(_)) => Some(ToolOutcome::Ok(Cow::Borrowed( + value.get("outcome")?.get("Ok")?, + ))), + Some(ToolOutcome::Err(error)) => Some(ToolOutcome::Err(Cow::Borrowed(error))), + None => None, + }; + Some(ToolDisplay { + version: shape.version, + tool: Cow::Borrowed(shape.tool), + arguments: Cow::Borrowed(value.get("arguments")?), + destination: shape.destination.map(Cow::Borrowed), + redacted: shape.redacted, + outcome, + }) +} + +fn owned_view<'a>(display: ToolDisplay) -> ToolDisplayView<'a> { + ToolDisplay { + version: display.version, + tool: Cow::Owned(display.tool), + arguments: Cow::Owned(display.arguments), + destination: display.destination.map(Cow::Owned), + redacted: display.redacted, + outcome: display.outcome.map(|outcome| match outcome { + ToolOutcome::Pending => ToolOutcome::Pending, + ToolOutcome::Ok(value) => ToolOutcome::Ok(Cow::Owned(value)), + ToolOutcome::Err(error) => ToolOutcome::Err(Cow::Owned(error)), + }), + } +} + pub fn operation(tool: &str) -> &'static str { crate::tools::catalog::get(tool).map_or("Tool", |spec| spec.label) } mod identity; pub use identity::{ - bridge_server_name, envelope, fallback_tool, raw_envelope, requested_arguments, requested_call, + RawEnvelope, bridge_server_name, envelope, fallback_tool, raw_envelope, requested_arguments, + requested_call, }; +/// Decode the same strict wire schema while borrowing only header text and +/// skipping arbitrary JSON payloads. Legacy version one still requires the +/// same typed argument shape validation as the owned projection. +fn header_fields(call: &ToolRecord) -> Option<(&str, Option<&str>)> { + let value = call.meta.as_ref()?.get(META_KEY)?; + let display = ToolDisplay::<&str, IgnoredAny>::deserialize(value).ok()?; + let valid = match display.version { + 2 if !contains_serde_marker(value) => true, + 1 | 2 => ToolDisplay::from_call(call).is_some(), + _ => false, + }; + valid.then_some((display.tool, display.destination)) +} + +// serde_json can interpret its private marker maps specially when a Value +// is deserialized into another Value. Keep the owned validation for these +// rare shapes instead of treating an ignored payload as automatically valid. +fn contains_serde_marker(value: &Value) -> bool { + match value { + Value::Object(map) => { + map.keys().next().is_some_and(|key| { + matches!( + key.as_str(), + "$serde_json::private::RawValue" | "$serde_json::private::Number" + ) + }) || map.values().any(contains_serde_marker) + } + Value::Array(values) => values.iter().any(contains_serde_marker), + _ => false, + } +} + pub fn header(call: &ToolRecord) -> String { - let title = ToolDisplay::from_call(call) - .map(|display| display.title()) - .or_else(|| fallback_tool(call).map(|tool| format!("Nocterm · {}", operation(tool)))) - .unwrap_or_else(|| call.title.clone()); - format!("{title} · {}", status_name(call.status)) + let status = status_name(call.status); + if let Some((tool, destination)) = header_fields(call) { + let label = operation(tool); + let destination = destination.unwrap_or("Nocterm"); + format!("{destination} · {label} · {status}") + } else if let Some(tool) = fallback_tool(call) { + format!("Nocterm · {} · {status}", operation(tool)) + } else { + format!("{} · {status}", call.title) + } } /// The status as it has always been shown in a row header. diff --git a/crates/ai/src/tool_display/identity.rs b/crates/ai/src/tool_display/identity.rs index 6b93df69..43b5ef8a 100644 --- a/crates/ai/src/tool_display/identity.rs +++ b/crates/ai/src/tool_display/identity.rs @@ -1,5 +1,6 @@ //! Exact provider spellings for the registered Nocterm bridge. -use serde_json::json; +use serde_json::{Value, json}; +use std::borrow::Cow; use crate::{TerminalCall, model::tools::ToolRecord}; @@ -79,56 +80,81 @@ pub fn envelope(call: &ToolRecord, server: &str) -> Option { /// Exact provider identity and original arguments, including rejected requests. pub fn raw_envelope(call: &ToolRecord, server: &str) -> Option<(String, serde_json::Value)> { - let registration = registration(server)?; - let named = explicit_identity(call)?; - if named.is_some_and(|named| named.registration != registration) { - return None; + let envelope = RawEnvelope::from_call(call)?; + (registration(server) == Some(envelope.registration)) + .then(|| (envelope.tool.into(), envelope.arguments.into_owned())) +} + +/// A borrowed provider request, with consistent explicit name and envelope. +/// It establishes request identity only, never an execution destination. +pub struct RawEnvelope<'a> { + registration: &'a str, + tool: &'a str, + arguments: Cow<'a, Value>, +} + +impl<'a> RawEnvelope<'a> { + pub fn from_call(call: &'a ToolRecord) -> Option { + Self::from_identity(call, explicit_identity(call)?) } - let Some(input) = call.raw_input.as_ref().filter(|input| !input.is_null()) else { - return Some((named?.tool.into(), json!({}))); - }; - if ["server", "tool", "arguments"] - .iter() - .any(|key| input.get(key).is_some()) - { - let envelope_server = input.get("server")?.as_str()?; - let tool = input.get("tool")?.as_str()?; - if self::registration(envelope_server) != Some(registration) - || named.is_some_and(|named| named.tool != tool) + + fn from_identity(call: &'a ToolRecord, named: Option>) -> Option { + let Some(input) = call.raw_input.as_ref().filter(|input| !input.is_null()) else { + let named = named?; + return Some(Self { + registration: named.registration, + tool: named.tool, + arguments: Cow::Owned(json!({})), + }); + }; + if ["server", "tool", "arguments"] + .iter() + .any(|key| input.get(key).is_some()) { - return None; + let registration = registration(input.get("server")?.as_str()?)?; + let tool = input.get("tool")?.as_str()?; + if named.is_some_and(|named| named.registration != registration || named.tool != tool) { + return None; + } + return Some(Self { + registration, + tool, + arguments: Cow::Borrowed(input.get("arguments")?), + }); } - return Some((tool.into(), input.get("arguments")?.clone())); + let named = named?; + Some(Self { + registration: named.registration, + tool: named.tool, + arguments: Cow::Borrowed(input), + }) + } + + /// Compare the exact original request without copying its JSON or name. + pub fn matches(&self, server: &str, request: &(String, Value)) -> bool { + server.strip_prefix(SERVER_PREFIX) == Some(self.registration) + && self.tool == request.0 + && self.arguments.as_ref() == &request.1 } - Some((named?.tool.into(), input.clone())) } /// Presentation identity remains useful even when its arguments are malformed. pub fn fallback_tool(call: &ToolRecord) -> Option<&str> { - requested_arguments(call).map(|(tool, _)| tool) + borrowed_arguments(call).map(|(tool, _)| tool) } /// Original request arguments for display, without executor shape validation. /// Explicit provider names and any server envelope must still agree. -pub fn requested_arguments(call: &ToolRecord) -> Option<(&str, serde_json::Value)> { +pub fn requested_arguments(call: &ToolRecord) -> Option<(&str, Value)> { + let (tool, arguments) = borrowed_arguments(call)?; + Some((tool, arguments.into_owned())) +} + +fn borrowed_arguments(call: &ToolRecord) -> Option<(&str, Cow<'_, Value>)> { match explicit_identity(call) { - Some(Some(named)) => { - if operation(named.tool) == "Tool" { - return None; - } - let server = format!("{SERVER_PREFIX}{}", named.registration); - let (_, arguments) = raw_envelope(call, &server)?; - Some((named.tool, arguments)) - } - Some(None) => { - let input = call.raw_input.as_ref()?; - let server = input.get("server")?.as_str()?; - let tool = input.get("tool")?.as_str()?; - if operation(tool) == "Tool" { - return None; - } - let (_, arguments) = raw_envelope(call, server)?; - Some((tool, arguments)) + Some(named) => { + let envelope = RawEnvelope::from_identity(call, named)?; + (operation(envelope.tool) != "Tool").then_some((envelope.tool, envelope.arguments)) } None => legacy_arguments(call), } @@ -163,13 +189,11 @@ fn legacy_tool(call: &ToolRecord) -> Option<&str> { } } -fn legacy_arguments(call: &ToolRecord) -> Option<(&str, serde_json::Value)> { +fn legacy_arguments(call: &ToolRecord) -> Option<(&str, Cow<'_, Value>)> { let tool = legacy_tool(call)?; - let input = call - .raw_input - .clone() - .filter(|input| !input.is_null()) - .unwrap_or(json!({})); + let Some(input) = call.raw_input.as_ref().filter(|input| !input.is_null()) else { + return Some((tool, Cow::Owned(json!({})))); + }; if ["server", "tool", "arguments"] .iter() .any(|key| input.get(key).is_some()) @@ -177,7 +201,7 @@ fn legacy_arguments(call: &ToolRecord) -> Option<(&str, serde_json::Value)> { if input.get("server")?.as_str()? != "nocterm" || input.get("tool")?.as_str()? != tool { return None; } - return Some((tool, input.get("arguments")?.clone())); + return Some((tool, Cow::Borrowed(input.get("arguments")?))); } - Some((tool, input)) + Some((tool, Cow::Borrowed(input))) } diff --git a/crates/ai/src/tool_display/tests.rs b/crates/ai/src/tool_display/tests.rs index 56411123..77db67b7 100644 --- a/crates/ai/src/tool_display/tests.rs +++ b/crates/ai/src/tool_display/tests.rs @@ -321,3 +321,205 @@ fn old_hermes_server_names_are_display_only() { assert!(requested_call(&call).is_none()); assert!(envelope(&call, "nocterm-3").is_none()); } + +#[test] +fn borrowed_requests_match_the_exact_registration_and_original_json() { + let arguments = json!({"fixture":["a",{"nested":17}]}); + let request = ("fixture".into(), arguments.clone()); + for title in [ + "mcp.nocterm-03.fixture", + "mcp__nocterm-03__fixture", + "mcp_nocterm_03_fixture", + ] { + for input in [ + arguments.clone(), + json!({"server":"nocterm-03","tool":"fixture","arguments":arguments}), + ] { + let call = ToolRecord::new("row", title).raw_input(input); + let borrowed = RawEnvelope::from_call(&call).unwrap(); + assert!(borrowed.matches("nocterm-03", &request)); + assert!(!borrowed.matches("nocterm-3", &request)); + assert!(!borrowed.matches("nocterm-03", &("other".into(), arguments.clone()))); + assert_eq!(raw_envelope(&call, "nocterm-03"), Some(request.clone())); + } + } + let call = ToolRecord::new("row", "activity") + .raw_input(json!({"server":"nocterm-03","tool":"fixture","arguments":null})); + let borrowed = RawEnvelope::from_call(&call).unwrap(); + assert!(borrowed.matches("nocterm-03", &("fixture".into(), json!(null)))); + assert!(!borrowed.matches("nocterm-03", &("fixture".into(), json!({})))); +} + +#[test] +fn borrowed_requests_distinguish_empty_arguments_from_conflicting_envelopes() { + let request = ("fixture".into(), json!({})); + for input in [None, Some(json!(null)), Some(json!({}))] { + let call = ToolRecord::new("row", "mcp.nocterm-3.fixture").raw_input(input); + assert!( + RawEnvelope::from_call(&call) + .unwrap() + .matches("nocterm-3", &request) + ); + } + for input in [ + json!({"server":"nocterm-4","tool":"fixture","arguments":{}}), + json!({"server":"nocterm-3","tool":"other","arguments":{}}), + json!({"server":"nocterm-3","tool":"fixture"}), + json!({"server":"nocterm","tool":"fixture","arguments":{}}), + ] { + let call = ToolRecord::new("row", "mcp.nocterm-3.fixture").raw_input(input); + assert!(RawEnvelope::from_call(&call).is_none()); + assert!(raw_envelope(&call, "nocterm-3").is_none()); + } +} + +#[test] +#[ignore = "manual collapsed tool header projection workload"] +fn measure_tool_header_projection() { + use std::{hint::black_box, io::Write as _, time::Instant}; + let bytes = std::env::var("NOCTERM_PROFILE_HEADER_BYTES") + .unwrap_or_else(|_| "65536".into()) + .parse::() + .unwrap(); + let mode = std::env::var("NOCTERM_PROFILE_HEADER_MODE").unwrap_or_else(|_| "saved".into()); + let input = json!({"terminal_id":"t1","command":"x".repeat(bytes)}); + let title = if mode == "legacy" { + "mcp_nocterm_run_command" + } else { + "mcp.nocterm-3.run_command" + }; + let mut call = ToolRecord::new("fixture", title) + .status(ToolStatus::Succeeded) + .raw_input(input.clone()); + let expected = if mode == "saved" { + let mut display = ToolDisplay::requested("run_command".into(), input); + display.destination = Some("Fixture terminal".into()); + display.finish(Ok(json!({"output":"x".repeat(bytes)}))); + display.attach(&mut call); + "Fixture terminal · Run command · Completed" + } else { + "Nocterm · Run command · Completed" + }; + let repeats = 10_000; + let start = Instant::now(); + for _ in 0..repeats { + assert_eq!(black_box(header(black_box(&call))), expected); + } + let elapsed = start.elapsed(); + writeln!( + std::io::stdout().lock(), + "mode={mode} bytes={bytes} repeats={repeats} elapsed_ns={}", + elapsed.as_nanos() + ) + .unwrap(); +} + +fn assert_projections_match_owned_metadata(value: Value) { + let mut call = ToolRecord::new("row", "Provider row"); + call.meta = Some( + [(META_KEY.into(), value.clone())] + .into_iter() + .collect::>() + .into(), + ); + let owned = ToolDisplay::from_call(&call); + assert_eq!( + ToolDisplay::has_valid_metadata(&call), + owned.is_some(), + "{value}" + ); + let projected = ToolDisplay::view(&call); + assert_eq!( + projected + .as_ref() + .map(|display| serde_json::to_value(display).unwrap()), + owned + .as_ref() + .map(|display| serde_json::to_value(display).unwrap()), + "{value}" + ); + assert_eq!( + projected + .and_then(|display| display.display_request()) + .as_ref() + .map(request), + owned + .as_ref() + .and_then(ToolDisplay::display_request) + .as_ref() + .map(request), + "{value}" + ); + let expected = owned + .map(|display| display.title()) + .unwrap_or_else(|| call.title.clone()); + assert_eq!(header(&call), format!("{expected} · Pending"), "{value}"); +} + +#[test] +fn projections_preserve_owned_metadata_validation() { + for version in [0, 1, 2, 3] { + for arguments in [ + json!({}), + json!({"unexpected":true}), + json!("text"), + json!(null), + ] { + for outcome in [ + json!(null), + json!("Pending"), + json!({"Ok":{"nested":[1,2]}}), + json!({"Err":"error"}), + json!({"Err":17}), + json!({"foreign":1}), + ] { + let value = json!({"version":version,"tool":"list_terminals","arguments":arguments,"destination":"Fixture","outcome":outcome}); + assert_projections_match_owned_metadata(value); + } + } + } +} + +#[test] +fn projections_reject_or_accept_the_same_unusual_wire_shapes() { + let valid = json!({"version":2,"tool":"unknown","arguments":{},"destination":null}); + for field in ["version", "tool", "arguments", "destination"] { + let mut value = valid.clone(); + value.as_object_mut().unwrap().remove(field); + assert_projections_match_owned_metadata(value); + } + for (key, field) in [ + ("extra", json!(true)), + ("version", json!("2")), + ("tool", json!(17)), + ("destination", json!(["bad"])), + ("redacted", json!(1)), + ("outcome", json!({"Ok":1,"Err":"bad"})), + ( + "arguments", + json!({"$serde_json::private::RawValue":"invalid"}), + ), + ( + "arguments", + json!([{"$serde_json::private::Number":"invalid"}]), + ), + ( + "outcome", + json!({"Ok":{"$serde_json::private::RawValue":17}}), + ), + ] { + let mut value = valid.clone(); + value[key] = field; + assert_projections_match_owned_metadata(value); + } + for value in [ + json!([2, "list_terminals", {}, null, false, "Pending"]), + json!([2, "list_terminals", {}, null]), + json!([2,"list_terminals",{},null,false,{"Ok":{"data":"x"}}]), + json!([1, "list_terminals", {}, null, false, null]), + json!([]), + json!(null), + ] { + assert_projections_match_owned_metadata(value); + } +} diff --git a/crates/ai/src/tools/output.rs b/crates/ai/src/tools/output.rs index c89a3d3b..b4de22fe 100644 --- a/crates/ai/src/tools/output.rs +++ b/crates/ai/src/tools/output.rs @@ -1,17 +1,28 @@ //! Agent-facing observations are display data, never execution capabilities. use nocterm_session::command_jobs::CommandSnapshot; use serde::{Deserialize, Serialize}; +use serde_json::Value; /// A bounded terminal snapshot; overlapping line numbers replace earlier text. #[derive(Serialize, Deserialize)] -pub struct TerminalReport { - pub text: String, +pub struct TerminalReport { + pub text: Text, pub first_line: u64, pub next_line: u64, - pub cursor_semantics: String, + pub cursor_semantics: Text, pub truncated: bool, pub alt_screen: bool, } +impl TerminalReport { + /// Decode a report directly from a retained wire value. + pub fn decode<'a>(value: &'a Value) -> Result + where + Text: Deserialize<'a>, + { + Self::deserialize(value) + } +} + impl TerminalReport { pub const CURSOR_SEMANTICS: &str = "inclusive snapshot; replace overlapping lines"; @@ -44,26 +55,46 @@ impl TerminalReport { } #[derive(Serialize, Deserialize)] -pub struct ObservationReport { +pub struct ObservationReport { #[serde(flatten)] - pub terminal: TerminalReport, - pub completion: String, + pub terminal: TerminalReport, + pub completion: Text, pub completed: bool, pub exit_status: Option, } +impl ObservationReport { + /// Decode a report directly from a retained wire value. + pub fn decode<'a>(value: &'a Value) -> Result + where + Text: Deserialize<'a>, + { + Self::deserialize(value) + } +} + /// A snapshot of an admitted command. Its identifier carries no control authority. #[derive(Serialize, Deserialize)] -pub struct CommandReport { - pub command_id: String, - pub state: String, - pub stdout: String, - pub stderr: String, +pub struct CommandReport { + pub command_id: Text, + pub state: Text, + pub stdout: Text, + pub stderr: Text, pub exit_status: Option, pub total_bytes: u64, pub truncated: bool, - pub error: Option, + pub error: Option, +} +impl CommandReport { + /// Decode a report directly from a retained wire value. + pub fn decode<'a>(value: &'a Value) -> Result + where + Text: Deserialize<'a>, + { + Self::deserialize(value) + } } + impl CommandReport { pub fn new(id: &str, snapshot: &CommandSnapshot, redact: bool) -> Self { let text = |value: String| { diff --git a/crates/ai/src/tools/output/tests.rs b/crates/ai/src/tools/output/tests.rs index d3e22509..4123c191 100644 --- a/crates/ai/src/tools/output/tests.rs +++ b/crates/ai/src/tools/output/tests.rs @@ -63,3 +63,90 @@ fn unfinished_commands_report_unknown_exit_and_do_not_mark_exact_output_truncate }) ); } + +#[test] +fn borrowed_report_shapes_match_owned_wire_decoding() { + use serde_json::Value; + + fn command(value: &Value) { + let old = serde_json::from_value::(value.clone()).ok(); + let projected = CommandReport::<&str>::decode(value).ok(); + let owned = CommandReport::::decode(value).ok(); + assert_eq!( + old.as_ref().map(|value| json!(value)), + projected.map(|value| json!(value)) + ); + assert_eq!( + old.map(|value| json!(value)), + owned.map(|value| json!(value)) + ); + } + + fn terminal(value: &Value) { + let old = serde_json::from_value::(value.clone()).ok(); + let projected = TerminalReport::<&str>::decode(value).ok(); + let owned = TerminalReport::::decode(value).ok(); + assert_eq!( + old.as_ref().map(|value| json!(value)), + projected.map(|value| json!(value)) + ); + assert_eq!( + old.map(|value| json!(value)), + owned.map(|value| json!(value)) + ); + } + + fn observation(value: &Value) { + let old = serde_json::from_value::(value.clone()).ok(); + let projected = ObservationReport::<&str>::decode(value).ok(); + let owned = ObservationReport::::decode(value).ok(); + assert_eq!( + old.as_ref().map(|value| json!(value)), + projected.map(|value| json!(value)) + ); + assert_eq!( + old.map(|value| json!(value)), + owned.map(|value| json!(value)) + ); + } + + let command_value = json!({ + "command_id":"c1","state":"exited","stdout":"界\n","stderr":"", + "exit_status":4294967295u32,"total_bytes":7,"truncated":false,"error":null + }); + let terminal_value = json!(TerminalReport::new("界\n".into(), 0, 1, false, false)); + let observation_value = json!( + TerminalReport::new("界\n".into(), 0, 1, false, false).observed("output_idle".into()) + ); + for (valid, check) in [ + (command_value, command as fn(&Value)), + (terminal_value, terminal), + (observation_value, observation), + ] { + check(&valid); + check(&json!(null)); + check(&json!([])); + for key in valid.as_object().unwrap().keys() { + let mut missing = valid.clone(); + missing.as_object_mut().unwrap().remove(key); + check(&missing); + for replacement in [ + json!(null), + json!(true), + json!(17), + json!(-1), + json!(1.5), + json!(""), + json!([]), + json!({}), + ] { + let mut malformed = valid.clone(); + malformed[key] = replacement; + check(&malformed); + } + } + let mut future = valid.clone(); + future["future"] = json!({"$serde_json::private::RawValue":"invalid"}); + check(&future); + } +} diff --git a/crates/ai/src/tools/transfer/tests.rs b/crates/ai/src/tools/transfer/tests.rs index 16303fd5..81d1e99d 100644 --- a/crates/ai/src/tools/transfer/tests.rs +++ b/crates/ai/src/tools/transfer/tests.rs @@ -41,7 +41,7 @@ fn progress(errors: Vec) -> Progress { total_bytes: 1_048_576, sent_bytes: 524_288, discovery_complete: true, - errors, + errors: errors.into(), } } diff --git a/crates/connections-model/Cargo.toml b/crates/connections-model/Cargo.toml index 7df6e6a2..bef94118 100644 --- a/crates/connections-model/Cargo.toml +++ b/crates/connections-model/Cargo.toml @@ -13,7 +13,7 @@ layer = "domain" nocterm-core.workspace = true nocterm-session.workspace = true serde_json.workspace = true -serde.workspace = true +serde = { workspace = true, features = ["rc"] } toml.workspace = true uuid = { version = "1", default-features = false, features = ["std", "serde"] } thiserror.workspace = true diff --git a/crates/connections-model/src/profile_authority.rs b/crates/connections-model/src/profile_authority.rs index 19aef1da..4215c456 100644 --- a/crates/connections-model/src/profile_authority.rs +++ b/crates/connections-model/src/profile_authority.rs @@ -1,7 +1,10 @@ //! Pure live-profile authority: every successful candidate transition advances stamps. use crate::profiles::{ProfileId, Profiles}; use nocterm_session::Target; -use std::collections::HashMap; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ProfileStamp { pub incarnation: u64, @@ -30,7 +33,7 @@ pub struct ProfileAuthorityRow { #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProfilePublication { generation: u64, - rows: HashMap, + rows: Arc>, } impl ProfilePublication { pub fn generation(&self) -> u64 { @@ -57,9 +60,18 @@ impl ObservationEpochs { } } pub fn transition(&mut self, before: &Profiles, after: &Profiles, generation: u64) { - self.live.retain(|id, _| after.get(*id).is_some()); + if after.is_empty() { + self.live.clear(); + return; + } + let surviving: HashSet<_> = after.iter().map(|profile| profile.id).collect(); + self.live.retain(|id, _| surviving.contains(id)); + let mut previous_by_id = HashMap::with_capacity(before.iter().len()); + for profile in before.iter() { + previous_by_id.entry(profile.id).or_insert(profile); + } for profile in after.iter() { - let Some(previous) = before.get(profile.id) else { + let Some(previous) = previous_by_id.get(&profile.id) else { self.live.insert(profile.id, ProfileStamp::at(generation)); continue; }; @@ -81,23 +93,24 @@ impl ObservationEpochs { } } pub fn publication(&self, generation: u64, profiles: &Profiles) -> ProfilePublication { - let rows = profiles - .iter() - .filter_map(|profile| { - self.live.get(&profile.id).map(|stamp| { - ( - profile.id, - ProfileAuthorityRow { - target: profile.target.clone(), - icon: profile.icon.clone(), - country: profile.country.clone(), - stamp: *stamp, - }, - ) - }) + let mut rows = HashMap::with_capacity(self.live.len()); + rows.extend(profiles.iter().filter_map(|profile| { + self.live.get(&profile.id).map(|stamp| { + ( + profile.id, + ProfileAuthorityRow { + target: profile.target.clone(), + icon: profile.icon.clone(), + country: profile.country.clone(), + stamp: *stamp, + }, + ) }) - .collect(); - ProfilePublication { generation, rows } + })); + ProfilePublication { + generation, + rows: Arc::new(rows), + } } } #[cfg(test)] diff --git a/crates/connections-model/src/profile_authority/tests.rs b/crates/connections-model/src/profile_authority/tests.rs index 2264664b..8701e081 100644 --- a/crates/connections-model/src/profile_authority/tests.rs +++ b/crates/connections-model/src/profile_authority/tests.rs @@ -111,3 +111,63 @@ fn changing_only_the_jump_hosts_starts_a_new_endpoint() { assert_eq!(stamp.icon_override, 0); assert_eq!(stamp.country_override, 0); } + +#[test] +#[ignore = "manual release benchmark"] +fn measure_large_connection_catalog_operations() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let mut catalog = Profiles::default(); + for index in 0..4096u32 { + let mut row = profile(); + row.id = crate::profiles::ProfileId::from_bytes(u128::from(index).to_be_bytes()); + row.name = format!("Synthetic connection {index:04}"); + row.description = format!("Test host for profile {index:04}"); + row.group = Some(format!("Group {:02}", index % 32)); + catalog.upsert(row); + } + let mut edited = catalog.clone(); + let mut last = catalog.iter().last().unwrap().clone(); + last.target.host = "new-host".into(); + let id = last.id; + edited.upsert(last); + let original = ObservationEpochs::imported(&catalog); + let publication = original.publication(0, &catalog); + let mut samples: [Vec<_>; 3] = std::array::from_fn(|_| Vec::with_capacity(17)); + for _ in 0..17 { + let start = Instant::now(); + let groups = black_box(catalog.grouped(" CONNECTION 4095 ")).1; + samples[0].push(start.elapsed()); + assert_eq!(groups[0].1[0].id, id); + + let start = Instant::now(); + let retained = black_box(&publication).clone(); + samples[1].push(start.elapsed()); + let mut epochs = original.clone(); + let start = Instant::now(); + epochs.transition(&catalog, &edited, 1); + samples[2].push(start.elapsed()); + assert_eq!(retained.get(id).unwrap().target.host, "host"); + assert_eq!( + epochs + .publication(1, &edited) + .get(id) + .unwrap() + .stamp + .endpoint, + 1 + ); + } + for (label, timings) in ["search", "retain publication", "edit endpoint"] + .into_iter() + .zip(&mut samples) + { + timings.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "4096 profiles, {label}: {:?}", + timings[8] + ) + .unwrap(); + } +} diff --git a/crates/connections-model/src/profiles.rs b/crates/connections-model/src/profiles.rs index 9a6e1b85..d7b7dbe6 100644 --- a/crates/connections-model/src/profiles.rs +++ b/crates/connections-model/src/profiles.rs @@ -1,8 +1,12 @@ //! Pure saved-profile format and checked collection transitions. mod mutation; pub use crate::recents::{MAX_RECENTS, Recent, Recents}; -pub use mutation::{ProfileError, ProfileExpectation, ProfileMutation}; -use std::fmt; +pub use mutation::{CheckedProfile, ProfileError, ProfileExpectation, ProfileMutation}; +use std::{ + collections::{HashMap, HashSet}, + fmt, + sync::Arc, +}; use crate::{credential_scope::CredentialScope, jump_route::JumpHostEntry}; use nocterm_session::{Auth, CredentialId, ShellLaunch, Target}; @@ -80,13 +84,14 @@ pub struct Profiles { /// Remember folders even after their last connection is moved or deleted. #[serde(default, skip_serializing_if = "Vec::is_empty")] folders: Vec, + // Committed and candidate documents share unchanged rows. #[serde(default, rename = "connection")] - list: Vec, + list: Vec>, } impl Profiles { - pub fn iter(&self) -> impl Iterator { - self.list.iter() + pub fn iter(&self) -> impl ExactSizeIterator { + self.list.iter().map(Arc::as_ref) } pub fn is_empty(&self) -> bool { @@ -94,17 +99,36 @@ impl Profiles { } pub fn associate_credential(&mut self, scope: &CredentialScope, id: CredentialId) { - for profile in self - .list - .iter_mut() - .filter(|profile| scope.admits_profile(profile)) - { - profile.credential = Some(id); + for profile in &mut self.list { + if scope.admits_profile(profile) && profile.credential != Some(id) { + Arc::make_mut(profile).credential = Some(id); + } } } pub fn get(&self, id: ProfileId) -> Option<&Profile> { - self.list.iter().find(|profile| profile.id == id) + self.iter().find(|profile| profile.id == id) + } + + /// Resolve a saved-profile association in its canonical display spelling. + pub fn get_by_canonical_id(&self, text: &str) -> Option<&Profile> { + let id: ProfileId = text.parse().ok()?; + let mut buffer = Uuid::encode_buffer(); + if id.0.as_hyphenated().encode_lower(&mut buffer) != text { + return None; + } + self.get(id) + } + + /// Adds a size-checked profile only while its ID is absent. + pub fn insert_missing(&mut self, profile: &CheckedProfile) -> Result<(), ProfileError> { + let profile = profile.as_profile(); + if self.get(profile.id).is_some() { + return Err(ProfileError::Conflict(profile.id)); + } + self.remember_group(profile.group.as_deref()); + self.list.push(Arc::new(profile.clone())); + Ok(()) } /// Replaces the profile with the same id, or adds it at the end. @@ -117,8 +141,8 @@ impl Profiles { .iter_mut() .find(|existing| existing.id == profile.id) { - Some(existing) => *existing = profile, - None => self.list.push(profile), + Some(existing) => *existing = Arc::new(profile), + None => self.list.push(Arc::new(profile)), } } @@ -140,13 +164,17 @@ impl Profiles { // Dropped on its own row: it stays where it is. self.remember_group(self.list[ix].group.clone().as_deref()); self.remember_group(group.as_deref()); - self.list[ix].group = group; + if self.list[ix].group != group { + Arc::make_mut(&mut self.list[ix]).group = group; + } return Ok(()); } let mut profile = self.list.remove(ix); self.remember_group(profile.group.as_deref()); self.remember_group(group.as_deref()); - profile.group = group; + if profile.group != group { + Arc::make_mut(&mut profile).group = group; + } let at = before .filter(|before| *before != id) .and_then(|before| self.list.iter().position(|p| p.id == before)) @@ -159,7 +187,25 @@ impl Profiles { let ix = self.list.iter().position(|profile| profile.id == id)?; let profile = self.list.remove(ix); self.remember_group(profile.group.as_deref()); - Some(profile) + Some(Arc::unwrap_or_clone(profile)) + } + + /// An empty document retaining its folders and fields from other versions. + pub fn without_profiles(&self) -> Self { + let mut known: HashSet<&str> = self.folders.iter().map(String::as_str).collect(); + let mut folders = self.folders.clone(); + folders.extend(self.list.iter().filter_map(|profile| { + let group = profile.group.as_deref()?; + known.insert(group).then(|| group.to_owned()) + })); + if folders.len() != self.folders.len() { + folders.sort(); + } + Self { + extra: self.extra.clone(), + folders, + list: Vec::new(), + } } /// Whether `name` is an existing or remembered folder. @@ -178,7 +224,7 @@ impl Profiles { } for profile in &mut self.list { if profile.group.as_deref() == Some(from) { - profile.group = Some(to.to_owned()); + Arc::make_mut(profile).group = Some(to.to_owned()); } } self.forget_group(from); @@ -189,7 +235,7 @@ impl Profiles { pub fn ungroup(&mut self, group: &str) { for profile in &mut self.list { if profile.group.as_deref() == Some(group) { - profile.group = None; + Arc::make_mut(profile).group = None; } } self.forget_group(group); @@ -203,7 +249,7 @@ impl Profiles { } for profile in &mut self.list { if profile.group.as_deref() == Some(from) && members.contains(&profile.id) { - profile.group = to.map(str::to_owned); + Arc::make_mut(profile).group = to.map(str::to_owned); } } self.forget_group(from); @@ -212,24 +258,24 @@ impl Profiles { /// Deletes the `members` that are in `group`, returning the removed ones. pub fn remove_members(&mut self, group: &str, members: &[ProfileId]) -> Vec { - let (removed, kept) = std::mem::take(&mut self.list) + let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.list) .into_iter() .partition(|profile| { profile.group.as_deref() == Some(group) && members.contains(&profile.id) }); self.list = kept; self.forget_group(group); - removed + removed.into_iter().map(Arc::unwrap_or_clone).collect() } /// Deletes the folder and its connections, returning the removed ones. pub fn remove_group(&mut self, group: &str) -> Vec { - let (removed, kept) = std::mem::take(&mut self.list) + let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.list) .into_iter() .partition(|profile| profile.group.as_deref() == Some(group)); self.list = kept; self.forget_group(group); - removed + removed.into_iter().map(Arc::unwrap_or_clone).collect() } fn forget_group(&mut self, group: &str) { @@ -247,7 +293,7 @@ impl Profiles { /// Existing and remembered folders, sorted case-insensitively. pub fn groups(&self) -> Vec<&str> { - let mut groups: Vec<&str> = self + let names: HashSet<&str> = self .folders .iter() .map(String::as_str) @@ -257,48 +303,53 @@ impl Profiles { .filter_map(|profile| profile.group.as_deref()), ) .collect(); + let mut groups: Vec<_> = names.into_iter().collect(); groups.sort_by_cached_key(|name| (name.to_lowercase(), *name)); - groups.dedup(); groups } /// Group and filter once, rather than rescanning every profile for every /// folder. Members keep the user's order, which drag and drop changes. pub fn grouped(&self, filter: &str) -> (Vec<&Profile>, Vec<(String, Vec<&Profile>)>) { - let filter = filter.trim().to_lowercase(); - let mut groups: Vec<_> = self - .groups() - .into_iter() - .map(|name| (name.to_owned(), Vec::new())) - .collect(); - let indices: std::collections::HashMap<_, _> = groups - .iter() - .enumerate() - .map(|(index, (name, _))| (name.clone(), index)) - .collect(); + let mut filter = ProfileFilter::new(filter); + let mut groups: HashMap<&str, Vec<&Profile>> = HashMap::new(); + if filter.query.is_empty() { + groups.extend(self.folders.iter().map(|name| (name.as_str(), Vec::new()))); + } let mut top = Vec::new(); - for profile in &self.list { - if !profile.matches_normalized(&filter) { + for profile in self.iter() { + if !filter.matches(profile) { continue; } - if let Some(group) = &profile.group { - groups[indices[group]].1.push(profile); + if let Some(group) = profile.group.as_deref() { + groups.entry(group).or_default().push(profile); } else { top.push(profile); } } - if !filter.is_empty() { - groups.retain(|(_, members)| !members.is_empty()); - } + let mut groups: Vec<_> = groups.into_iter().collect(); + groups.sort_by_cached_key(|(name, _)| (name.to_lowercase(), *name)); + let groups = groups + .into_iter() + .map(|(name, members)| (name.to_owned(), members)) + .collect(); (top, groups) } + /// The only profile matching the filter, when there is exactly one. + pub fn single_match(&self, filter: &str) -> Option<&Profile> { + let mut filter = ProfileFilter::new(filter); + let mut matches = self.iter().filter(|profile| filter.matches(profile)); + let first = matches.next()?; + matches.next().is_none().then_some(first) + } + /// The profiles filed under `group` (`None`: at the top level) that match /// `filter`, in the user's order. pub fn in_group<'a>(&'a self, group: Option<&str>, filter: &str) -> Vec<&'a Profile> { - self.list - .iter() - .filter(|profile| profile.group.as_deref() == group && profile.matches(filter)) + let mut filter = ProfileFilter::new(filter); + self.iter() + .filter(|profile| profile.group.as_deref() == group && filter.matches(profile)) .collect() } } @@ -307,19 +358,46 @@ impl Profile { /// Whether `filter` occurs, ignoring case, in the name, the destination or /// the folder. An empty filter matches everything. pub fn matches(&self, filter: &str) -> bool { - self.matches_normalized(&filter.trim().to_lowercase()) + ProfileFilter::new(filter).matches(self) } - fn matches_normalized(&self, filter: &str) -> bool { - filter.is_empty() +} + +struct ProfileFilter { + query: String, + folded: String, +} +impl ProfileFilter { + fn new(query: &str) -> Self { + Self { + query: query.trim().to_lowercase(), + folded: String::new(), + } + } + + fn matches(&mut self, profile: &Profile) -> bool { + self.query.is_empty() || [ - self.name.as_str(), - self.description.as_str(), - self.target.host.as_str(), - self.target.user.as_str(), - self.group.as_deref().unwrap_or_default(), + profile.name.as_str(), + profile.description.as_str(), + profile.target.host.as_str(), + profile.target.user.as_str(), + profile.group.as_deref().unwrap_or_default(), ] - .iter() - .any(|field| field.to_lowercase().contains(filter)) + .into_iter() + .any(|field| self.contains(field)) + } + + fn contains(&mut self, field: &str) -> bool { + if !field.is_ascii() { + return field.to_lowercase().contains(&self.query); + } + if field.len() < self.query.len() { + return false; + } + self.folded.clear(); + self.folded.push_str(field); + self.folded.make_ascii_lowercase(); + self.folded.contains(&self.query) } } diff --git a/crates/connections-model/src/profiles/mutation.rs b/crates/connections-model/src/profiles/mutation.rs index c78af154..1904c302 100644 --- a/crates/connections-model/src/profiles/mutation.rs +++ b/crates/connections-model/src/profiles/mutation.rs @@ -83,6 +83,24 @@ pub enum ProfileMutation { }, } +/// An owned profile that has passed the save size and encoding checks. +pub struct CheckedProfile(Profile); + +impl CheckedProfile { + pub fn new(profile: Profile) -> Result { + validate_profile(&profile)?; + Ok(Self(profile)) + } + + pub fn as_profile(&self) -> &Profile { + &self.0 + } + + pub fn into_profile(self) -> Profile { + self.0 + } +} + impl ProfileMutation { pub fn validate(&self) -> Result<(), ProfileError> { let metadata_bytes = match self { @@ -109,10 +127,7 @@ impl ProfileMutation { return Err(ProfileError::MutationSize); } if let Self::Save { profile, .. } = self { - let text = toml::to_string(profile.as_ref()).map_err(ProfileError::encoding)?; - if text.len() > MAX_PROFILE_BYTES { - return Err(ProfileError::ProfileSize); - } + validate_profile(profile)?; } Ok(()) } @@ -192,6 +207,14 @@ impl ProfileMutation { } } +fn validate_profile(profile: &Profile) -> Result<(), ProfileError> { + let text = toml::to_string(profile).map_err(ProfileError::encoding)?; + if text.len() > MAX_PROFILE_BYTES { + return Err(ProfileError::ProfileSize); + } + Ok(()) +} + fn require_group(profiles: &Profiles, group: &str) -> Result<(), ProfileError> { if profiles.has_group(group) { Ok(()) diff --git a/crates/connections-model/src/profiles/tests.rs b/crates/connections-model/src/profiles/tests.rs index b7742f36..f1b470b6 100644 --- a/crates/connections-model/src/profiles/tests.rs +++ b/crates/connections-model/src/profiles/tests.rs @@ -2,6 +2,8 @@ use std::path::PathBuf; use super::*; +mod snapshots; + fn profile(name: &str, host: &str, group: Option<&str>) -> Profile { Profile { description: String::new(), @@ -419,6 +421,27 @@ fn one_pass_grouped_view_preserves_folders_filters_and_user_order() { assert_eq!(groups[0].1, profiles.in_group(Some("Work"), "BUILD")); } +#[test] +fn single_match_and_groups_agree_on_unicode_fields_and_distinct_folder_names() { + let mut profiles = Profiles::default(); + let mut greek = profile("ΟΣ", "other.test", Some("Work")); + greek.description = "İSTANBUL".into(); + let other = profile("Other", "other.test", Some("work")); + profiles.upsert(other.clone()); + profiles.upsert(greek.clone()); + + assert_eq!(profiles.groups(), ["Work", "work"]); + for query in [" ΟΣ ", "ος", "i\u{307}stanbul"] { + assert_eq!(profiles.single_match(query), Some(&greek)); + assert_eq!( + profiles.grouped(query).1, + [("Work".to_owned(), vec![&greek])] + ); + } + assert_eq!(profiles.single_match(" OTHER.TEST "), None); + assert_eq!(profiles.single_match("os"), None); +} + #[test] fn supplied_ids_round_trip_all_legacy_uuid_spellings_with_typed_parse_causes() { use std::error::Error as _; @@ -444,6 +467,26 @@ fn supplied_ids_round_trip_all_legacy_uuid_spellings_with_typed_parse_causes() { ); } +#[test] +fn saved_profile_association_requires_canonical_spelling() { + let mut profiles = Profiles::default(); + let mut row = profile("source", "source.test", None); + row.id = ProfileId::from_bytes([42; 16]); + profiles.upsert(row.clone()); + let text = row.id.to_string(); + assert_eq!(profiles.get_by_canonical_id(&text), Some(&row)); + for alternate in [ + text.to_uppercase(), + text.replace('-', ""), + format!("{{{text}}}"), + format!("urn:uuid:{text}"), + ProfileId::from_bytes([43; 16]).to_string(), + String::new(), + ] { + assert_eq!(profiles.get_by_canonical_id(&alternate), None); + } +} + #[test] fn profile_encoding_causes_keep_real_codec_error_and_clone_identity() { use std::error::Error; diff --git a/crates/connections-model/src/profiles/tests/snapshots.rs b/crates/connections-model/src/profiles/tests/snapshots.rs new file mode 100644 index 00000000..c715896b --- /dev/null +++ b/crates/connections-model/src/profiles/tests/snapshots.rs @@ -0,0 +1,47 @@ +use super::{Profiles, profile}; + +#[test] +fn a_catalog_edit_preserves_previously_captured_rows_and_their_order() { + let mut catalog = Profiles::default(); + let mut build = profile("Build", "build.local", Some("Work")); + build.description = "large profile field".repeat(2048); + let pi = profile("Pi", "pi.local", None); + catalog.upsert(build.clone()); + catalog.upsert(pi.clone()); + let captured = catalog.clone(); + let original = toml::to_string(&captured).unwrap(); + + catalog.place(build.id, Some("Lab".into()), None).unwrap(); + catalog.rename_group("Lab", "Personal"); + let removed = catalog.remove(build.id).unwrap(); + assert_eq!(removed.group.as_deref(), Some("Personal")); + assert_eq!(removed.description, build.description); + assert!(catalog.iter().eq([&pi])); + assert!(captured.iter().eq([&build, &pi])); + assert_eq!(toml::to_string(&captured).unwrap(), original); + assert_eq!(toml::from_str::(&original).unwrap(), captured); +} + +#[test] +#[ignore = "manual release benchmark"] +fn measure_cloning_a_catalog_with_large_profile_fields() { + use std::{hint::black_box, io::Write, time::Instant}; + + let mut catalog = Profiles::default(); + for index in 0..256 { + let mut row = profile(&format!("host-{index:04}"), "machine.local", None); + row.description = "a".repeat(48 * 1024); + catalog.upsert(row); + } + let start = Instant::now(); + for _ in 0..500 { + black_box(black_box(&catalog).clone()); + } + let elapsed = start.elapsed(); + assert!(catalog.iter().all(|row| row.description.len() == 48 * 1024)); + writeln!( + std::io::stdout().lock(), + "500 snapshots of 256 profiles: {elapsed:?}" + ) + .unwrap(); +} diff --git a/crates/connections-model/src/replica/rules.rs b/crates/connections-model/src/replica/rules.rs index 75f03de1..629853c9 100644 --- a/crates/connections-model/src/replica/rules.rs +++ b/crates/connections-model/src/replica/rules.rs @@ -77,24 +77,29 @@ pub fn plan( ) -> Vec { let latest = latest_changes(changes, state); let local_by_id: HashMap<_, _> = local.iter().map(|profile| (profile.id, profile)).collect(); - let mut remembered: Vec = state.entries().map(|(id, _)| id).collect(); - remembered.sort_unstable(); - let mut seen = HashSet::new(); - local + let mut seen = HashSet::with_capacity(local.iter().len()); + let actions_for = |id| { + let remote = latest.get(&id).copied(); + if remote.is_none() && state.is_unrecognized(id) { + return Vec::new(); + } + reconcile(local_by_id.get(&id).copied(), remote, state.entry(id)) + }; + let mut actions: Vec<_> = local .iter() .map(|profile| profile.id) .chain(changes.iter().map(|change| change.id)) - .chain(remembered) .filter(|id| seen.insert(*id)) - .filter(|id| !state.is_unrecognized(*id) || latest.contains_key(id)) - .flat_map(|id| { - reconcile( - local_by_id.get(&id).copied(), - latest.get(&id).copied(), - state.entry(id), - ) - }) - .collect() + .flat_map(actions_for) + .collect(); + let mut remembered: Vec<_> = state + .entries() + .map(|(id, _)| id) + .filter(|id| !seen.contains(id)) + .collect(); + remembered.sort_unstable(); + actions.extend(remembered.into_iter().flat_map(actions_for)); + actions } /// The change that stands for each profile: the later one of the feed. Late entries older diff --git a/crates/connections-model/src/replica/state.rs b/crates/connections-model/src/replica/state.rs index 5caa9bd8..1cb9df98 100644 --- a/crates/connections-model/src/replica/state.rs +++ b/crates/connections-model/src/replica/state.rs @@ -2,7 +2,10 @@ use super::{ReplicaCursor, ReplicaVersion}; use crate::profiles::{Profile, ProfileId}; use serde::{Deserialize, Serialize}; -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; /// A profile as it was when the local copy and the replica last agreed. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -13,16 +16,25 @@ pub struct SyncedEntry { /// What is persisted between runs: the feed position, the agreed profiles and the /// profiles the replica holds in a form this client cannot read. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct ReplicaState { #[serde(default, skip_serializing_if = "Option::is_none")] cursor: Option, #[serde(default)] - entries: HashMap, + // The desired, writing, and durable snapshots often differ only by cursor. + entries: Arc>, #[serde(default, skip_serializing_if = "HashSet::is_empty")] unrecognized: HashSet, } +impl PartialEq for ReplicaState { + fn eq(&self, other: &Self) -> bool { + self.cursor == other.cursor + && self.unrecognized == other.unrecognized + && (Arc::ptr_eq(&self.entries, &other.entries) || self.entries == other.entries) + } +} + impl ReplicaState { pub fn cursor(&self) -> Option<&ReplicaCursor> { self.cursor.as_ref() @@ -53,13 +65,15 @@ impl ReplicaState { /// version; the replica's version is readable again. pub fn agree(&mut self, id: ProfileId, entry: SyncedEntry) { self.unrecognized.remove(&id); - self.entries.insert(id, entry); + Arc::make_mut(&mut self.entries).insert(id, entry); } /// Neither side holds the profile any more: the agreement goes. pub fn forget(&mut self, id: ProfileId) { self.unrecognized.remove(&id); - self.entries.remove(&id); + if self.entries.contains_key(&id) { + Arc::make_mut(&mut self.entries).remove(&id); + } } pub fn mark_unrecognized(&mut self, id: ProfileId) { diff --git a/crates/connections-model/src/replica/tests.rs b/crates/connections-model/src/replica/tests.rs index efe909a3..2dafa144 100644 --- a/crates/connections-model/src/replica/tests.rs +++ b/crates/connections-model/src/replica/tests.rs @@ -303,6 +303,28 @@ fn replica_state_survives_serialization_with_its_unrecognized_ids() { assert_eq!(restored.cursor().map(ReplicaCursor::as_str), Some("7")); } +#[test] +fn a_saved_replica_snapshot_keeps_its_agreement_after_later_edits() { + let earlier = synced("earlier", 3); + let newer = synced("newer", 5); + let input = serde_json::json!({ + "cursor": "3", + "entries": { (id().to_string()): earlier }, + }); + let saved: ReplicaState = serde_json::from_value(input.clone()).unwrap(); + let mut next = saved.clone(); + next.agree(id(), newer.clone()); + assert_eq!(saved.entry(id()), Some(&earlier)); + assert_eq!(next.entry(id()), Some(&newer)); + assert_eq!(serde_json::to_value(&saved).unwrap(), input); + assert_ne!(saved, next); + next.advance(ReplicaCursor::new("5")); + assert_eq!(saved.cursor().unwrap().as_str(), "3"); + next.forget(id()); + assert!(next.entry(id()).is_none()); + assert_eq!(saved.entry(id()), Some(&earlier)); +} + #[test] fn agreeing_or_forgetting_a_profile_makes_it_readable_again() { let mut state = ReplicaState::default(); diff --git a/crates/connections-store/src/connections.rs b/crates/connections-store/src/connections.rs index b8e55e63..b9074998 100644 --- a/crates/connections-store/src/connections.rs +++ b/crates/connections-store/src/connections.rs @@ -2,7 +2,9 @@ use gpui::{App, AppContext as _, Context, Entity, Task}; use nocterm_session::CredentialId; use nocterm_connections_model::credential_scope::CredentialScope; -use nocterm_connections_model::profiles::{Profile, ProfileId, Profiles, Recent, Recents}; +use nocterm_connections_model::profiles::{ + CheckedProfile, Profile, ProfileError, ProfileId, Profiles, Recent, Recents, +}; use crate::{error::ConnectionsError, publication}; use nocterm_connections_model::recents::RecentUse; @@ -114,6 +116,29 @@ impl ConnectionStore { if let Err(error) = mutation.validate() { return Task::ready(Err(error.into())); } + self.edit_profiles( + move |snapshot, consumed, load_error| snapshot.apply(&mutation, consumed, load_error), + cx, + ) + } + + pub(crate) fn clear_replica_profiles( + &mut self, + cx: &mut Context, + ) -> Task> { + self.edit_profiles(publication::ProfileSnapshot::clear_profiles, cx) + } + + fn edit_profiles( + &mut self, + edit: impl FnOnce( + &mut publication::ProfileSnapshot, + u64, + Option<&Arc>, + ) -> Result<(), ConnectionsError> + + 'static, + cx: &mut Context, + ) -> Task> { let newly_installed = self.state.installed().is_none(); self.state.install(cx); if newly_installed { @@ -123,8 +148,7 @@ impl ConnectionStore { let consumed = installed.consumed(); let load_error = self.load_error.clone(); let edit = move |snapshot: &mut publication::ProfileSnapshot| { - snapshot - .apply(&mutation, consumed.get(), load_error.as_ref()) + edit(snapshot, consumed.get(), load_error.as_ref()) .map_err(nocterm_store::StoreError::edit) }; if installed.memory_only() { @@ -175,6 +199,36 @@ impl ConnectionStore { cx, ) } + + pub(crate) fn is_memory_only(&self) -> bool { + self.state + .installed() + .is_some_and(publication::InstalledPublication::memory_only) + } + + /// Publish one group of checked creations in the in-memory mirror. + pub(crate) fn save_missing_profiles<'a>( + &mut self, + profiles: impl Iterator, + cx: &mut Context, + ) -> Result>, ConnectionsError> { + let installed = self.state.install(cx); + assert!(installed.memory_only()); + let consumed = installed.consumed().get(); + let mut outcomes = Vec::new(); + installed.profiles().update(cx, |state, cx| { + state.update_immediate_checked( + |snapshot| { + outcomes = snapshot + .apply_creates(profiles, consumed) + .map_err(nocterm_store::StoreError::edit)?; + Ok(()) + }, + cx, + ) + })?; + Ok(outcomes) + } pub fn move_profile( &mut self, id: ProfileId, diff --git a/crates/connections-store/src/facts.rs b/crates/connections-store/src/facts.rs index b423ff2a..d3dfeba2 100644 --- a/crates/connections-store/src/facts.rs +++ b/crates/connections-store/src/facts.rs @@ -125,10 +125,20 @@ impl FactsService { pub fn synchronize( &mut self, cx: &mut Context, + ) -> (ProfilePublication, CountryPolicySnapshot) { + self.synchronize_admission(true, cx) + } + fn synchronize_admission( + &mut self, + prune_decisions: bool, + cx: &mut Context, ) -> (ProfilePublication, CountryPolicySnapshot) { let (publication, forgotten, changed) = self.authority.synchronize(cx); let policy = self.policy.read(cx); - self.probes.prune(&publication, cx); + if prune_decisions { + self.probes.prune_decisions(cx); + } + self.probes.prune_slots(&publication, cx); self.locations .prune(&publication, policy, &mut self.probes, cx); if changed && !self.closing(cx) { @@ -144,25 +154,59 @@ impl FactsService { cx, ) }); - } - for (_, row) in publication.iter() { - if let Some(code) = row - .country - .as_deref() - .and_then(|code| CountryCode::new(code).ok()) - { - self.flags - .request(code, self.observations.network_enabled()); - } + self.request_manual_flags(&publication); } (publication, policy) } + fn request_manual_flags(&mut self, publication: &ProfilePublication) { + let network = self.observations.network_enabled(); + let countries = publication + .iter() + .filter_map(|(_, row)| CountryCode::new(row.country.as_deref()?).ok()); + for code in countries { + self.flags.request(code, network); + } + } pub fn request_probe( &mut self, request: ProbeRequest, cx: &mut Context, ) -> Result { - let (publication, policy) = self.synchronize(cx); + self.request_probe_inner(request, true, cx) + } + /// A single foreground admission turn, stopping at the first admitted + /// request or refusal that requires the caller to stop or retry. + pub fn request_probe_turn( + &mut self, + requests: impl IntoIterator, + cx: &mut Context, + ) -> Option<(usize, Result)> { + let mut stop = None; + for (index, request) in requests.into_iter().enumerate() { + let outcome = self.request_probe_inner(request, index == 0, cx); + match outcome { + Ok(ProbeOutcome::Settled) + | Err( + FactsAdmissionError::MissingProfile + | FactsAdmissionError::EndpointMismatch + | FactsAdmissionError::StaleSource, + ) => {} + _ => { + stop = Some((index, outcome)); + break; + } + } + } + self.probes.prune_decisions(cx); + stop + } + fn request_probe_inner( + &mut self, + request: ProbeRequest, + prune_decisions: bool, + cx: &mut Context, + ) -> Result { + let (publication, policy) = self.synchronize_admission(prune_decisions, cx); if self.closing(cx) { return Err(FactsAdmissionError::Closing); } diff --git a/crates/connections-store/src/facts/admission.rs b/crates/connections-store/src/facts/admission.rs index ad838c9f..3deabc61 100644 --- a/crates/connections-store/src/facts/admission.rs +++ b/crates/connections-store/src/facts/admission.rs @@ -118,10 +118,12 @@ impl ProbeLedger { self.slots.remove(&ticket.profile()); true } - pub(super) fn prune(&mut self, publication: &ProfilePublication, cx: &gpui::App) { + pub(super) fn prune_decisions(&mut self, cx: &gpui::App) { self.decisions.retain(|decision| { decision.session.strong_count() > 0 && decision.lifetime.same_session_alive(cx) }); + } + pub(super) fn prune_slots(&mut self, publication: &ProfilePublication, cx: &gpui::App) { self.slots.retain(|_, ticket| ticket.valid(publication, cx)); } } diff --git a/crates/connections-store/src/facts/authority.rs b/crates/connections-store/src/facts/authority.rs index cef5cebd..9e3abb38 100644 --- a/crates/connections-store/src/facts/authority.rs +++ b/crates/connections-store/src/facts/authority.rs @@ -12,7 +12,10 @@ impl ProfileAuthority { } /// Reads the ACTUAL distinct carrier on every call, even before observers execute. pub(super) fn synchronize(&mut self, cx: &App) -> (ProfilePublication, Vec, bool) { - let current = self.carrier.read(cx).current().clone(); + let current = self.carrier.read(cx).current(); + if current == &self.last { + return (current.clone(), Vec::new(), false); + } let removed = self .last .iter() @@ -24,8 +27,7 @@ impl ProfileAuthority { .then_some(id) }) .collect(); - let changed = current != self.last; self.last = current.clone(); - (current, removed, changed) + (current.clone(), removed, true) } } diff --git a/crates/connections-store/src/facts/prepared.rs b/crates/connections-store/src/facts/prepared.rs index 71639d10..83242e02 100644 --- a/crates/connections-store/src/facts/prepared.rs +++ b/crates/connections-store/src/facts/prepared.rs @@ -28,7 +28,7 @@ impl FactsPrepared { shutdown: &ShutdownCoordinator, cx: &mut App, ) -> Result<(Entity, Vec), StoreError> { - let countries: Vec<_> = self + let countries: HashSet<_> = self .known .countries() .filter_map(|code| CountryCode::new(code).ok()) @@ -60,9 +60,11 @@ impl FactsPrepared { policy, }); entity.update(cx, |facts, cx| { - facts.synchronize(cx); + let (publication, _) = facts.synchronize(cx); + facts.request_manual_flags(&publication); + let network = facts.observations.network_enabled(); for code in countries { - let _ = facts.request_flag(code, cx); + facts.flags.request(code, network); } facts.progress(cx); }); diff --git a/crates/connections-store/src/facts/tests/authority.rs b/crates/connections-store/src/facts/tests/authority.rs index d58ecc67..4ded0c5e 100644 --- a/crates/connections-store/src/facts/tests/authority.rs +++ b/crates/connections-store/src/facts/tests/authority.rs @@ -139,3 +139,54 @@ fn exact_session_user_port_and_host_must_match_committed_target(cx: &mut TestApp assert!(fixture.script.calls().is_empty()); assert_eq!(fixture.jobs(cx), 32); } + +#[gpui::test] +fn probe_turn_checks_each_source_and_stops_at_first_admitted_job(cx: &mut TestAppContext) { + let fixture = Fixture::memory(false, cx); + let (settled, revoked, mismatch, next, later) = (fs(), fs(), fs(), fs(), fs()); + fixture.request(settled.clone(), cx).unwrap(); + cx.run_until_parked(); + fixture.source(&revoked).revoke(); + let requests = || { + [&settled, &revoked, &mismatch, &next, &later] + .into_iter() + .enumerate() + .map(|(index, session)| { + let mut target = fixture.profile.target.clone(); + if index == 2 { + target.port += 1; + } + ProbeRequest::new( + fixture.profile.id, + target, + session.clone(), + fixture.source(session), + ) + }) + .collect::>() + }; + for expected in [3, 4] { + let result = fixture + .facts + .update(cx, |facts, cx| facts.request_probe_turn(requests(), cx)); + assert!(matches!( + result, + Some((index, Ok(ProbeOutcome::Admitted { os: true, country: false }))) + if index == expected + )); + cx.run_until_parked(); + assert_eq!(fixture.jobs(cx), 32); + } + let result = fixture + .facts + .update(cx, |facts, cx| facts.request_probe_turn(requests(), cx)); + assert!(result.is_none()); + assert_eq!(fixture.os.calls(), 3); + let observed = fixture.os.sessions(); + for (original, expected) in observed.iter().zip([settled, next, later]) { + assert!(std::sync::Weak::ptr_eq( + original, + &Arc::downgrade(&expected) + )); + } +} diff --git a/crates/connections-store/src/facts/tests/flags.rs b/crates/connections-store/src/facts/tests/flags.rs index 2aba3b16..c3b56489 100644 --- a/crates/connections-store/src/facts/tests/flags.rs +++ b/crates/connections-store/src/facts/tests/flags.rs @@ -97,6 +97,30 @@ fn manual_saved_countries_start_without_a_known_row_or_live_session(cx: &mut Tes assert_eq!(fixture.os.calls(), 0); } +#[gpui::test] +fn committed_manual_country_is_found_before_publication_observers_run(cx: &mut TestAppContext) { + let fixture = Fixture::memory(false, cx); + let mut profile = fixture.profile.clone(); + profile.country = Some("de".into()); + fixture.save(profile, cx); + + let manual = CountryCode::new("de").unwrap(); + assert!( + fixture + .facts + .read_with(cx, |facts, _| facts.flag(manual).is_none()) + ); + let explicit = CountryCode::new("fr").unwrap(); + fixture + .facts + .update(cx, |facts, cx| facts.request_flag(explicit, cx)) + .unwrap(); + fixture.facts.read_with(cx, |facts, _| { + assert!(matches!(facts.flag(manual), Some(FlagState::Unavailable))); + assert!(matches!(facts.flag(explicit), Some(FlagState::Unavailable))); + }); +} + fn transient_flag_failure() -> nocterm_connections_model::observation::ObservationError { nocterm_connections_model::observation::ObservationError::Network(Box::new( std::io::Error::from(std::io::ErrorKind::NotConnected), diff --git a/crates/connections-store/src/prepared.rs b/crates/connections-store/src/prepared.rs index 9db67023..7a96a9e3 100644 --- a/crates/connections-store/src/prepared.rs +++ b/crates/connections-store/src/prepared.rs @@ -36,17 +36,17 @@ impl Prepared { pub(crate) fn recents(&self) -> &Recents { &self.recents } - pub(crate) fn install(&self, cx: &mut App) -> InstalledPublication { + pub(crate) fn install(&mut self, cx: &mut App) -> InstalledPublication { let recents = cx.new(|_| { Persisted::new( - self.recents.clone(), + std::mem::take(&mut self.recents), self.recents_writer.clone(), Publication::Optimistic, MAX_PENDING_WRITES, ) }); let consumed = Rc::new(Cell::new(0)); - let initial = ProfileSnapshot::new(self.profiles.clone()); + let initial = ProfileSnapshot::new(std::mem::take(&mut self.profiles)); let publications = cx.new(|_| ProfilePublications::new(initial.publication())); let hook = ProfileCommitHook::new(recents.clone(), consumed.clone(), publications.clone()); let writer = self.profiles_writer.clone(); diff --git a/crates/connections-store/src/publication/snapshot.rs b/crates/connections-store/src/publication/snapshot.rs index 8edfc0bf..780dac37 100644 --- a/crates/connections-store/src/publication/snapshot.rs +++ b/crates/connections-store/src/publication/snapshot.rs @@ -1,4 +1,6 @@ use super::*; +use nocterm_connections_model::profiles::{CheckedProfile, Profile, ProfileError}; +use std::collections::{HashMap, HashSet}; #[derive(Clone, PartialEq)] pub(crate) struct ProfileSnapshot { profiles: Profiles, @@ -46,23 +48,21 @@ impl ProfileSnapshot { scope: scope.clone(), id: *id, }], - _ => { - let (routed, direct): (Vec<_>, Vec<_>) = self - .profiles - .iter() - .filter(|profile| candidate.get(profile.id).is_none()) - .partition(|profile| !profile.jump_hosts.is_empty()); - let ids = |profiles: Vec<&nocterm_connections_model::profiles::Profile>| -> Vec { - profiles.into_iter().map(|profile| profile.id).collect() - }; - [ - (!direct.is_empty()).then(|| Effect::Unlink(ids(direct))), - (!routed.is_empty()).then(|| Effect::Forget(ids(routed))), - ] - .into_iter() - .flatten() - .collect() + ProfileMutation::Delete(_) + | ProfileMutation::DeleteGroup { .. } + | ProfileMutation::DeleteMembers { .. } => { + let survivors: HashSet<_> = candidate.iter().map(|profile| profile.id).collect(); + removal_effects( + self.profiles + .iter() + .filter(|profile| !survivors.contains(&profile.id)), + ) } + ProfileMutation::Save { .. } + | ProfileMutation::Move { .. } + | ProfileMutation::RenameGroup { .. } + | ProfileMutation::Ungroup(_) + | ProfileMutation::Regroup { .. } => Vec::new(), }; if candidate == self.profiles && effects.is_empty() { return Ok(()); @@ -70,6 +70,60 @@ impl ProfileSnapshot { if let Some(error) = load_error { return Err(ConnectionsError::read_only(error.clone())); } + self.commit(candidate, effects, consumed) + } + + pub(crate) fn apply_creates<'a>( + &mut self, + profiles: impl Iterator, + consumed: u64, + ) -> Result>, ConnectionsError> { + let mut candidate = self.profiles.clone(); + let outcomes: Vec<_> = profiles + .map(|profile| candidate.insert_missing(profile)) + .collect(); + if outcomes.iter().any(Result::is_ok) { + self.commit(candidate, Vec::new(), consumed)?; + } + Ok(outcomes) + } + + pub(crate) fn clear_profiles( + &mut self, + consumed: u64, + load_error: Option<&Arc>, + ) -> Result<(), ConnectionsError> { + if let Some(error) = load_error { + return Err(ConnectionsError::read_only(error.clone())); + } + if self.profiles.is_empty() { + return Ok(()); + } + // Legacy documents can contain several rows with one ID. A recent + // changes only when the last row with that ID is removed. + let last_positions: HashMap<_, _> = self + .profiles + .iter() + .enumerate() + .map(|(position, profile)| (profile.id, position)) + .collect(); + let remaining = self.profiles.without_profiles(); + let effects = removal_effects( + self.profiles + .iter() + .enumerate() + .filter(|(position, profile)| last_positions[&profile.id] == *position) + .map(|(_, profile)| profile), + ); + self.commit(remaining, effects, consumed) + } + + fn commit( + &mut self, + candidate: Profiles, + effects: Vec, + consumed: u64, + ) -> Result<(), ConnectionsError> { let generation = self .generation .checked_add(1) @@ -130,3 +184,22 @@ impl ProfileSnapshot { } } } + +fn removal_effects<'a>(profiles: impl Iterator) -> Vec { + let mut direct = Vec::new(); + let mut routed = Vec::new(); + for profile in profiles { + if profile.jump_hosts.is_empty() { + direct.push(profile.id); + } else { + routed.push(profile.id); + } + } + [ + (!direct.is_empty()).then_some(Effect::Unlink(direct)), + (!routed.is_empty()).then_some(Effect::Forget(routed)), + ] + .into_iter() + .flatten() + .collect() +} diff --git a/crates/connections-store/src/replication.rs b/crates/connections-store/src/replication.rs index 0137dce6..d4a4c733 100644 --- a/crates/connections-store/src/replication.rs +++ b/crates/connections-store/src/replication.rs @@ -14,7 +14,7 @@ pub use feed::ReplicationFeedError; mod status; use crate::ConnectionStore; -use futures::StreamExt as _; +use futures::{FutureExt as _, StreamExt as _, future::Shared}; use gpui::{Context, Entity, EventEmitter, Subscription, Task}; use nocterm_connections_model::{ profiles::ProfileId, @@ -28,6 +28,7 @@ pub use status::{ReplicationEvent, ReplicationFailure, ReplicationStatus}; /// Pending writes of the agreed-state document; its edits are coalesced snapshots. const STATE_WRITES: usize = 8; +type ClearReceipt = Shared>>; /// A standing refusal that has been reported. #[derive(Clone, Copy, PartialEq, Eq, Hash)] @@ -46,6 +47,7 @@ pub struct ProfileReplication { run: Option>, rerun: bool, watcher: Option>, + clearing: Option, /// Refusals already reported and still standing: a remote change the local document /// refused (the cursor stays behind it) and a local profile the replica refused and /// never agreed to. Each pass meets them again but says so once. @@ -73,6 +75,7 @@ impl ProfileReplication { run: None, rerun: false, watcher: None, + clearing: None, refused: HashSet::new(), _publications: subscription, } @@ -91,6 +94,17 @@ impl ProfileReplication { /// The agreed state is kept: a restart continues with the same replica. pub fn attach(&mut self, replica: Arc, cx: &mut Context) { self.stop(cx); + self.replica = Some(replica); + if self.clearing.is_none() { + self.watch(cx); + } + self.start(cx); + } + + fn watch(&mut self, cx: &mut Context) { + let Some(replica) = &self.replica else { + return; + }; let mut changes = replica.watch(); self.watcher = Some(cx.spawn(async move |this, cx| { while changes.next().await.is_some() { @@ -99,8 +113,6 @@ impl ProfileReplication { } } })); - self.replica = Some(replica); - self.start(cx); } /// Stops synchronizing, forgets what was agreed with that replica and empties the store: @@ -109,35 +121,27 @@ impl ProfileReplication { /// mean nothing to another replica either. pub fn detach(&mut self, cx: &mut Context) { self.stop(cx); - self.clear_mirror(cx); - self.state.update(cx, |state, cx| { - if let Err(error) = state.update_latest(|state| *state = ReplicaState::default(), cx) { - tracing::error!(%error, "could not reset the profile replica state"); - } - }); - self.set_status(ReplicationStatus::Detached, cx); - } - - /// Removes every profile from the store. With no replica attached nothing is sent. - fn clear_mirror(&mut self, cx: &mut Context) { - let removals: Vec<_> = self.store.update(cx, |store, cx| { - let ids: Vec = store - .profiles(cx) - .iter() - .map(|profile| profile.id) - .collect(); - ids.into_iter() - .map(|id| store.delete_profile(id, cx)) - .collect() + self.refused.clear(); + let removal = self + .store + .update(cx, |store, cx| store.clear_replica_profiles(cx)); + let reset = self.state.update(cx, |state, cx| { + state + .update_latest(|state| *state = ReplicaState::default(), cx) + .map(|_| ()) + .map_err(ReplicationFailure::State) }); - cx.spawn(async move |_, _| { - for removal in removals { - if let Err(error) = removal.await { - tracing::error!(%error, "could not clear a profile of the mirror"); + self.clearing = Some( + cx.spawn(async move |_, _| { + let result = removal.await.map_err(ReplicationFailure::Local).and(reset); + if let Err(error) = &result { + tracing::error!(%error, "could not clear the profile mirror"); } - } - }) - .detach(); + result + }) + .shared(), + ); + self.set_status(ReplicationStatus::Detached, cx); } pub fn status(&self) -> &ReplicationStatus { @@ -173,8 +177,27 @@ impl ProfileReplication { self.state.clone(), cx.weak_entity(), ); + let clearing = self.clearing.clone(); self.set_status(ReplicationStatus::Syncing, cx); self.run = Some(cx.spawn(async move |this, cx| { + if let Some(clearing) = clearing { + let result = clearing.await; + let ready = this.update(cx, |this, cx| match result { + Ok(()) => { + this.clearing = None; + this.watch(cx); + true + } + Err(failure) => { + this.stop(cx); + this.finish(Outcome::Failed(failure), cx); + false + } + }); + if !matches!(ready, Ok(true)) { + return; + } + } let outcome = round.run(cx).await; if let Some(outcome) = outcome { this.update(cx, |this, cx| this.finish(outcome, cx)).ok(); diff --git a/crates/connections-store/src/replication/round.rs b/crates/connections-store/src/replication/round.rs index 7ebc1fdc..616778ca 100644 --- a/crates/connections-store/src/replication/round.rs +++ b/crates/connections-store/src/replication/round.rs @@ -8,9 +8,9 @@ //! change is offered again instead of being lost. use super::{ProfileReplication, ReplicationEvent, ReplicationFailure}; use crate::{ConnectionStore, ConnectionsError}; -use gpui::{AsyncApp, Entity, WeakEntity}; +use gpui::{App, AppContext, AsyncApp, Entity, WeakEntity}; use nocterm_connections_model::{ - profiles::{Profile, ProfileError, ProfileId, Profiles}, + profiles::{CheckedProfile, Profile, ProfileError, ProfileId}, replica::{ ProfileReplica, RemoteProfile, ReplicaCursor, ReplicaError, ReplicaState, ReplicaVersion, SyncedEntry, @@ -22,6 +22,31 @@ use std::{collections::HashSet, sync::Arc}; /// Passes tried before a profile that keeps changing under us is reported. pub(super) const MAX_ATTEMPTS: usize = 3; +const CREATE_BATCH: usize = 64; + +struct PreparedCreate { + id: ProfileId, + version: ReplicaVersion, + profile: Result, +} + +impl PreparedCreate { + fn check(action: ReplicaAction) -> Self { + let ReplicaAction::SaveLocal { + version, + profile, + expected: None, + } = action + else { + unreachable!("only creations are batched"); + }; + Self { + id: profile.id, + version, + profile: CheckedProfile::new(*profile), + } + } +} pub(super) enum Outcome { Synced, @@ -160,12 +185,13 @@ impl Round { async fn attempt(&self, cx: &mut AsyncApp) -> Result { self.require_readable_local(cx)?; let (changes, cursor) = self.fetch(cx).await?; - let actions = self.plan(&changes, cx)?; + let actions = self.plan(&changes, cx); + drop(changes); match self.apply(actions, cx).await? { Applied::Retry => return Ok(true), - Applied::Refused => self.record(cx, move |state| state.advance(cursor))?, + Applied::Refused => self.advance_cursor(cursor, cx)?, Applied::Done => { - self.record(cx, move |state| state.advance(cursor))?; + self.advance_cursor(cursor, cx)?; self.events .update(cx, |this, _| this.forget_refusals()) .map_err(gone)?; @@ -205,19 +231,21 @@ impl Round { } } - fn plan( - &self, - changes: &[RemoteProfile], - cx: &mut AsyncApp, - ) -> Result, Stop> { - let local: Profiles = self - .store - .read_with(cx, |store, cx| store.profiles(cx).clone()); - let state = self.state.read_with(cx, |state, _| state.visible().clone()); - Ok(rules::plan(&local, changes, &state)) + fn plan(&self, changes: &[RemoteProfile], cx: &mut AsyncApp) -> Vec { + self.store.read_with(cx, |store, cx| { + rules::plan(store.profiles(cx), changes, self.state.read(cx).visible()) + }) } async fn apply(&self, actions: Vec, cx: &mut AsyncApp) -> Result { + if actions.len() > 1 + && self.store.read_with(cx, |store, _| store.is_memory_only()) + && actions + .iter() + .all(|action| matches!(action, ReplicaAction::SaveLocal { expected: None, .. })) + { + return self.apply_creates(actions, cx).await; + } let mut skipped = HashSet::new(); let mut applied = Applied::Done; let mut refused = false; @@ -253,6 +281,86 @@ impl Round { }) } + async fn apply_creates( + &self, + actions: Vec, + cx: &mut AsyncApp, + ) -> Result { + let mut pending = actions.into_iter(); + let mut applied = Applied::Done; + while !pending.as_slice().is_empty() { + let actions: Vec<_> = pending.by_ref().take(CREATE_BATCH).collect(); + let group = cx + .background_executor() + .spawn(async move { actions.into_iter().map(PreparedCreate::check).collect() }) + .await; + cx.update(|cx| self.publish_create_group(group, &mut applied, cx))?; + // Publication observers can close or replace the mirror. Let cancellation + // take effect before processing another group or advancing the cursor. + cx.spawn(async |_| {}).await; + } + Ok(applied) + } + + fn publish_create_group( + &self, + group: Vec, + applied: &mut Applied, + cx: &mut App, + ) -> Result<(), Stop> { + let outcomes = self + .store + .update(cx, |store, cx| { + store.save_missing_profiles( + group.iter().filter_map(|entry| entry.profile.as_ref().ok()), + cx, + ) + }) + .map_err(|error| halt(ReplicationFailure::Local(error)))?; + let mut agreed = Vec::new(); + let mut rejected = Vec::new(); + let mut outcomes = outcomes.into_iter(); + for PreparedCreate { + id, + version, + profile, + } in group + { + let outcome = profile.and_then(|profile| { + outcomes.next().expect("one outcome per checked profile")?; + Ok(profile.into_profile()) + }); + match outcome { + Ok(profile) => agreed.push(SyncedEntry { version, profile }), + Err(ProfileError::Conflict(_)) => *applied = Applied::Retry, + Err(error) => { + if matches!(*applied, Applied::Done) { + *applied = Applied::Deferred; + } + rejected.push((id, error)); + } + } + } + if !agreed.is_empty() { + self.record(cx, move |state| { + for entry in agreed { + state.agree(entry.profile.id, entry); + } + })?; + } + for (id, error) in rejected { + self.skipped( + id, + ReplicationFailure::Rejected { + id, + source: error.into(), + }, + cx, + )?; + } + Ok(()) + } + async fn execute(&self, action: ReplicaAction, cx: &mut AsyncApp) -> Result<(), Flow> { match action { ReplicaAction::SaveLocal { @@ -399,7 +507,7 @@ impl Round { fn record( &self, - cx: &mut AsyncApp, + cx: &mut impl AppContext, edit: impl FnOnce(&mut ReplicaState) + 'static, ) -> Result<(), Stop> { self.state @@ -408,11 +516,26 @@ impl Round { .map_err(|error| halt(ReplicationFailure::State(error))) } + fn advance_cursor(&self, cursor: ReplicaCursor, cx: &mut AsyncApp) -> Result<(), Stop> { + self.state + .update(cx, |state, cx| { + if state.visible().cursor() == Some(&cursor) + && !state.is_closing() + && !state.is_dirty() + { + return Ok(()); + } + state.update_latest(move |state| state.advance(cursor), cx)?; + Ok(()) + }) + .map_err(|error| halt(ReplicationFailure::State(error))) + } + fn skipped( &self, id: ProfileId, failure: ReplicationFailure, - cx: &mut AsyncApp, + cx: &mut impl AppContext, ) -> Result<(), Stop> { self.events .update(cx, |this, cx| this.announce_skip(id, failure, cx)) diff --git a/crates/connections-store/src/replication/tests.rs b/crates/connections-store/src/replication/tests.rs index 4afa2c01..8dfb3fbf 100644 --- a/crates/connections-store/src/replication/tests.rs +++ b/crates/connections-store/src/replication/tests.rs @@ -12,6 +12,7 @@ use std::sync::Mutex; mod conflicts; mod feed; mod lifecycle; +mod performance; fn profile(name: &str) -> Profile { Profile { @@ -81,10 +82,20 @@ impl Fixture { store: ConnectionStore, state: ReplicaState, replica: Arc, + ) -> Self { + Self::with_first_write(cx, store, state, replica, Ok(())) + } + + fn with_first_write( + cx: &mut gpui::TestAppContext, + store: ConnectionStore, + state: ReplicaState, + replica: Arc, + first_write: Result<(), nocterm_store::StoreError>, ) -> Self { let store = cx.new(|_| store); let (writer, release, writes) = gated_writer().into_parts(); - release.send(Ok(())).ok(); + release.send(first_write).unwrap(); let document = cx.new(|_| ProfileReplication::state_document(state, writer)); let replication = { let store = store.clone(); diff --git a/crates/connections-store/src/replication/tests/conflicts.rs b/crates/connections-store/src/replication/tests/conflicts.rs index 4e1f5855..17b22cfd 100644 --- a/crates/connections-store/src/replication/tests/conflicts.rs +++ b/crates/connections-store/src/replication/tests/conflicts.rs @@ -256,3 +256,84 @@ async fn a_local_edit_after_a_refused_remote_change_does_not_end_in_conflicts( "the edit is not stuck retrying against the missed change" ); } + +#[gpui::test] +fn incoming_profiles_publish_in_groups_and_leave_a_refused_entry_ahead_of_the_cursor( + cx: &mut gpui::TestAppContext, +) { + let fixture = Fixture::new(cx, &[]); + let offered: Vec<_> = (0..130) + .map(|index| profile(&format!("incoming-{index:03}"))) + .collect(); + for (index, profile) in offered.iter().enumerate() { + fixture.replica.write_remote(if index == 31 { + let mut escaped = profile.clone(); + // Each control byte expands to a six-byte TOML escape. + escaped.description = "\u{0001}".repeat(12_000); + escaped + } else { + profile.clone() + }); + } + let carrier = fixture.store.update(cx, |store, cx| store.publications(cx)); + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let _subscription = cx.update(|cx| { + cx.observe(&carrier, move |carrier, cx| { + observed + .lock() + .unwrap() + .push(carrier.read(cx).current().iter().count()); + }) + }); + fixture.attach(cx); + assert_eq!(*lengths.lock().unwrap(), [63, 127, 129]); + assert!(fixture.persisted_state().cursor().is_none()); + assert_eq!(rejected_ids(&fixture.events()), [offered[31].id]); + assert!(fixture.store.read_with(cx, |store, cx| { + store.profiles(cx).iter().eq(offered + .iter() + .enumerate() + .filter_map(|(index, profile)| (index != 31).then_some(profile))) + })); + + fixture.replica.write_remote(offered[31].clone()); + cx.run_until_parked(); + assert_eq!(fixture.local(cx, &offered[31]).as_ref(), Some(&offered[31])); + assert!(fixture.persisted_state().cursor().is_some()); + assert!(fixture.replica.writes().is_empty()); +} + +#[gpui::test] +fn a_local_save_between_incoming_groups_is_reconciled_as_a_conflict(cx: &mut gpui::TestAppContext) { + let fixture = Fixture::new(cx, &[]); + let offered: Vec<_> = (0..65) + .map(|index| profile(&format!("incoming-{index:03}"))) + .collect(); + for profile in &offered { + fixture.replica.write_remote(profile.clone()); + } + let last = offered.last().unwrap(); + let local_edit = at_host(last, "local.example"); + let store = fixture.store.clone(); + let carrier = store.update(cx, |store, cx| store.publications(cx)); + let mut pending = Some(local_edit.clone()); + let _subscription = cx.update(|cx| { + cx.observe(&carrier, move |carrier, cx| { + if carrier.read(cx).current().iter().count() == 64 + && let Some(profile) = pending.take() + { + drop(store.update(cx, |store, cx| store.save_profile(profile, cx))); + } + }) + }); + fixture.attach(cx); + assert_eq!(fixture.local(cx, last).as_ref(), Some(last)); + assert!(matches!( + fixture.events().as_slice(), + [ReplicationEvent::Overwritten { id, discarded }] + if *id == last.id && discarded.as_ref() == &local_edit + )); + assert!(fixture.persisted_state().cursor().is_some()); + assert!(fixture.replica.writes().is_empty()); +} diff --git a/crates/connections-store/src/replication/tests/lifecycle.rs b/crates/connections-store/src/replication/tests/lifecycle.rs index 3f8f646c..35bcf1db 100644 --- a/crates/connections-store/src/replication/tests/lifecycle.rs +++ b/crates/connections-store/src/replication/tests/lifecycle.rs @@ -3,6 +3,32 @@ use nocterm_connections_model::repository::{ ConnectionDocument, ConnectionStorageError, StorageOperation, }; +#[gpui::test] +fn an_unchanged_cursor_retries_a_failed_write(cx: &mut gpui::TestAppContext) { + let fixture = Fixture::with_first_write( + cx, + ConnectionStore::with_documents(Profiles::default(), Recents::default()), + ReplicaState::default(), + Arc::new(MemoryReplica::new()), + Err(nocterm_store::StoreError::backend(std::io::Error::other( + "first cursor write failed", + ))), + ); + fixture.attach(cx); + assert_eq!(fixture.writes.lock().unwrap().len(), 1); + let cursor = fixture.persisted_state().cursor().cloned().unwrap(); + + fixture.replica.set_locked(false); + cx.run_until_parked(); + assert_eq!(fixture.writes.lock().unwrap().len(), 2); + assert_eq!(fixture.persisted_state().cursor(), Some(&cursor)); + + fixture.replica.set_locked(false); + cx.run_until_parked(); + assert_eq!(fixture.writes.lock().unwrap().len(), 2); + assert!(matches!(fixture.status(cx), ReplicationStatus::Synced)); +} + #[gpui::test] async fn a_restart_continues_from_the_persisted_state_without_resending( cx: &mut gpui::TestAppContext, @@ -153,3 +179,170 @@ async fn nothing_is_synchronized_while_the_local_document_failed_to_load( ReplicationStatus::Failed(ReplicationFailure::LocalUnavailable) )); } + +#[gpui::test] +fn detaching_at_a_group_publication_clears_the_partial_import_and_agreement( + cx: &mut gpui::TestAppContext, +) { + let fixture = Fixture::new(cx, &[]); + for index in 0..65 { + fixture + .replica + .write_remote(profile(&format!("entry-{index:03}"))); + } + let carrier = fixture.store.update(cx, |store, cx| store.publications(cx)); + let mut attached = Some(fixture.replication.clone()); + let _subscription = cx.update(|cx| { + cx.observe(&carrier, move |carrier, cx| { + if carrier.read(cx).current().iter().count() == 64 + && let Some(replication) = attached.take() + { + replication.update(cx, |replication, cx| replication.detach(cx)); + } + }) + }); + + fixture.attach(cx); + assert!(matches!(fixture.status(cx), ReplicationStatus::Detached)); + assert!( + fixture + .store + .read_with(cx, |store, cx| store.profiles(cx).is_empty()) + ); + let state = fixture.persisted_state(); + assert!(state.cursor().is_none()); + assert_eq!(state.entries().count(), 0); + assert!(fixture.replica.writes().is_empty()); +} + +#[gpui::test] +fn a_replacement_replica_waits_for_the_whole_mirror_to_clear(cx: &mut gpui::TestAppContext) { + let original: Vec<_> = (0..96) + .map(|index| profile(&format!("original-{index:03}"))) + .collect(); + let replica = Arc::new(MemoryReplica::new()); + for profile in &original { + replica.write_remote(profile.clone()); + } + let (writer, release, writes) = gated_writer().into_parts(); + let store = ConnectionStore::with_backends( + profiles_of(&original), + Recents::default(), + writer, + Arc::new(|_| Box::pin(async { Ok(()) })), + ); + let fixture = Fixture::over(cx, store, ReplicaState::default(), replica); + fixture.attach(cx); + assert!(matches!(fixture.status(cx), ReplicationStatus::Synced)); + let replacement = Arc::new(MemoryReplica::new()); + fixture.replication.update(cx, |replication, cx| { + replication.detach(cx); + replication.attach(replacement.clone(), cx); + }); + cx.run_until_parked(); + assert!(replacement.calls().is_empty()); + assert!( + fixture + .store + .read_with(cx, |store, cx| store.profiles(cx).iter().eq(&original)) + ); + assert_eq!(writes.lock().unwrap().len(), 1); + assert!(writes.lock().unwrap()[0].is_empty()); + + let failed = nocterm_store::StoreError::backend(std::io::Error::other("clear failed")); + release.send(Err(failed)).unwrap(); + cx.run_until_parked(); + assert!(matches!( + fixture.status(cx), + ReplicationStatus::Failed(ReplicationFailure::Local(_)) + )); + assert!(replacement.calls().is_empty()); + + fixture.replication.update(cx, |replication, cx| { + replication.detach(cx); + replication.attach(replacement.clone(), cx); + }); + cx.run_until_parked(); + assert!(matches!(fixture.status(cx), ReplicationStatus::Synced)); + assert_eq!(writes.lock().unwrap().len(), 2); + assert!( + fixture + .store + .read_with(cx, |store, cx| store.profiles(cx).is_empty()) + ); + assert!(!replacement.calls().is_empty()); + assert!(replacement.writes().is_empty()); +} + +#[gpui::test] +fn clearing_the_mirror_publishes_once_and_keeps_legacy_folder_and_recent_semantics( + cx: &mut gpui::TestAppContext, +) { + use nocterm_connections_model::{jump_route::JumpHostEntry, profiles::Recent}; + + let direct = profile("direct"); + let mut repeated = profile("repeated"); + repeated.group = Some("first".into()); + let mut routed = repeated.clone(); + routed.group = Some("last".into()); + routed.jump_hosts = vec![JumpHostEntry::Address(Target::new( + "ci", + "gateway.example", + 22, + ))]; + let mut document = + toml::Value::try_from(profiles_of(&[direct.clone(), repeated.clone()])).unwrap(); + document + .get_mut("connection") + .unwrap() + .as_array_mut() + .unwrap() + .push(toml::Value::try_from(&routed).unwrap()); + document + .as_table_mut() + .unwrap() + .insert("future".into(), toml::Value::String("metadata".into())); + let profiles: Profiles = document.try_into().unwrap(); + let mut expected = profiles.clone(); + for item in profiles.iter() { + expected.remove(item.id); + } + let mut recents = Recents::default(); + for profile in [&direct, &repeated] { + recents.record(Recent { + options: profile.options.clone(), + target: profile.target.clone(), + auth: profile.auth.clone(), + profile: Some(profile.id), + last_used: 12, + credential: None, + launch: None, + }); + } + let fixture = Fixture::over( + cx, + ConnectionStore::with_documents(profiles, recents), + ReplicaState::default(), + Arc::new(MemoryReplica::new()), + ); + let carrier = fixture.store.update(cx, |store, cx| store.publications(cx)); + let published = Arc::new(Mutex::new(Vec::new())); + let observed = published.clone(); + let _subscription = cx.update(|cx| { + cx.observe(&carrier, move |carrier, cx| { + observed + .lock() + .unwrap() + .push(carrier.read(cx).current().iter().count()); + }) + }); + fixture.detach(cx); + assert_eq!(*published.lock().unwrap(), [0]); + fixture.store.read_with(cx, |store, cx| { + assert_eq!(store.profiles(cx), &expected); + let recents: Vec<_> = store.recents(cx).iter().collect(); + assert_eq!(recents.len(), 1); + assert_eq!(recents[0].target, direct.target); + assert!(recents[0].profile.is_none()); + }); +} diff --git a/crates/connections-store/src/replication/tests/performance.rs b/crates/connections-store/src/replication/tests/performance.rs new file mode 100644 index 00000000..0031612f --- /dev/null +++ b/crates/connections-store/src/replication/tests/performance.rs @@ -0,0 +1,229 @@ +use super::*; +use nocterm_core::persist::RevisionedFile; +use nocterm_store::{SnapshotWriter, StoreError}; +use std::{ + io::Write as _, + sync::atomic::{AtomicUsize, Ordering}, + time::{Duration, Instant}, +}; + +fn agreed_catalog(cx: &mut gpui::TestAppContext, count: usize) -> (Fixture, Profile) { + let local: Vec<_> = (0..count) + .map(|index| profile(&format!("connection-{index:04}"))) + .collect(); + let replica = Arc::new(MemoryReplica::new()); + let mut state = ReplicaState::default(); + for entry in &local { + let version = replica.write_remote(entry.clone()); + state.agree( + entry.id, + SyncedEntry { + version, + profile: entry.clone(), + }, + ); + } + state.advance(ReplicaCursor::new(count.to_string())); + let last = local.last().unwrap().clone(); + (Fixture::resumed(cx, &local, state, replica), last) +} + +#[gpui::test] +#[ignore = "manual release benchmark"] +fn measure_steady_profile_replication_rounds(cx: &mut gpui::TestAppContext) { + for count in [32, 512, 4096] { + let (fixture, last) = agreed_catalog(cx, count); + fixture.attach(cx); + assert!(matches!(fixture.status(cx), ReplicationStatus::Synced)); + assert!(fixture.writes.lock().unwrap().is_empty()); + let mut unchanged = Vec::with_capacity(9); + let mut changed = Vec::with_capacity(9); + for trial in 0..9 { + let reads = fixture.replica.calls().len(); + let start = Instant::now(); + fixture.replica.set_locked(false); + cx.run_until_parked(); + unchanged.push(start.elapsed()); + assert_eq!(fixture.replica.calls().len(), reads + 1); + assert!(fixture.writes.lock().unwrap().is_empty()); + + let edit = at_host(&last, &format!("updated-{trial}.example")); + let start = Instant::now(); + let version = fixture.replica.write_remote(edit.clone()); + cx.run_until_parked(); + changed.push(start.elapsed()); + assert_eq!(fixture.local(cx, &last).as_ref(), Some(&edit)); + assert!(matches!(fixture.status(cx), ReplicationStatus::Synced)); + assert_eq!( + fixture.persisted_state().entry(last.id).unwrap().version, + version + ); + fixture.writes.lock().unwrap().clear(); + } + assert!(fixture.replica.writes().is_empty()); + unchanged.sort_unstable(); + changed.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} profiles, unchanged {:?}, one incoming edit {:?}", + unchanged[4], + changed[4] + ) + .unwrap(); + } +} + +#[gpui::test] +#[ignore = "manual release benchmark"] +fn measure_profile_replication_detach(cx: &mut gpui::TestAppContext) { + for count in [32, 512, 4096] { + let mut durations = Vec::new(); + for _ in 0..5 { + let (fixture, _) = agreed_catalog(cx, count); + fixture.attach(cx); + assert!(matches!(fixture.status(cx), ReplicationStatus::Synced)); + let start = Instant::now(); + fixture + .replication + .update(cx, |replication, cx| replication.detach(cx)); + cx.run_until_parked(); + durations.push(start.elapsed()); + assert!(matches!(fixture.status(cx), ReplicationStatus::Detached)); + assert!( + fixture + .store + .read_with(cx, |store, cx| store.profiles(cx).is_empty()) + ); + let state = fixture.persisted_state(); + assert_eq!(state.entries().count(), 0); + assert!(state.cursor().is_none()); + assert!(fixture.replica.writes().is_empty()); + } + durations.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} profiles, detach median {:?}", + durations[2] + ) + .unwrap(); + } +} + +#[gpui::test] +#[ignore = "manual release benchmark; use TMPDIR to select the filesystem"] +fn measure_first_profile_replication(cx: &mut gpui::TestAppContext) { + for count in [32, 256, 512] { + let expected: Vec<_> = (0..count) + .map(|index| profile(&format!("initial-{index:04}"))) + .collect(); + for disk in [false, true] { + let mut samples = Vec::new(); + for _ in 0..3 { + samples.push(first_replication(cx, &expected, disk)); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} profiles, file={disk}, {:?}, {} profile file writes", + samples[1].0, + samples[1].1 + ) + .unwrap(); + } + } +} + +#[gpui::test] +#[ignore = "manual release benchmark"] +fn measure_replication_with_large_profile_fields(cx: &mut gpui::TestAppContext) { + for count in [32, 128, 256] { + let expected: Vec<_> = (0..count) + .map(|index| { + let mut item = profile(&format!("large-{index:04}")); + item.description = "a".repeat(48 * 1024); + item + }) + .collect(); + let mut samples: Vec<_> = (0..3) + .map(|_| first_replication(cx, &expected, false).0) + .collect(); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} profiles with 48 KiB descriptions, import median {:?}", + samples[1] + ) + .unwrap(); + } +} + +fn first_replication( + cx: &mut gpui::TestAppContext, + expected: &[Profile], + disk: bool, +) -> (Duration, usize) { + let directory = tempfile::tempdir().unwrap(); + let file = RevisionedFile::new(directory.path().join("connections.toml")); + let writes = Arc::new(AtomicUsize::new(0)); + let store = if disk { + let profiles = file.load::().unwrap().unwrap_or_default(); + let observed = writes.clone(); + let destination = file.clone(); + let writer: SnapshotWriter = Arc::new(move |profiles| { + let observed = observed.clone(); + let destination = destination.clone(); + Box::pin(async move { + destination + .save_preserving(&profiles) + .map_err(StoreError::backend)?; + observed.fetch_add(1, Ordering::Relaxed); + Ok(()) + }) + }); + ConnectionStore::with_backends( + profiles, + Recents::default(), + writer, + Arc::new(|_| Box::pin(async { Ok(()) })), + ) + } else { + ConnectionStore::in_memory() + }; + let store = cx.new(|_| store); + let document = cx.new(|_| { + ProfileReplication::state_document( + ReplicaState::default(), + Arc::new(|_| Box::pin(async { Ok(()) })), + ) + }); + let replication = cx.new(|cx| ProfileReplication::new(store.clone(), document.clone(), cx)); + let replica = Arc::new(MemoryReplica::new()); + for profile in expected { + replica.write_remote(profile.clone()); + } + replica.page_size(64); + let start = Instant::now(); + replication.update(cx, |replication, cx| { + replication.attach(replica.clone(), cx) + }); + cx.run_until_parked(); + let duration = start.elapsed(); + assert!(replication.read_with(cx, |replication, _| { + matches!(replication.status(), ReplicationStatus::Synced) + })); + assert!(store.read_with(cx, |store, cx| store.profiles(cx).iter().eq(expected))); + if disk { + assert!( + file.load::() + .unwrap() + .unwrap() + .iter() + .eq(expected) + ); + } + assert!(replica.writes().is_empty()); + assert!(document.read_with(cx, |state, _| { + state.durable().entries().count() == expected.len() && state.durable().cursor().is_some() + })); + (duration, writes.load(Ordering::Relaxed)) +} diff --git a/crates/connections/src/directory.rs b/crates/connections/src/directory.rs index bdaa3857..216e9f2d 100644 --- a/crates/connections/src/directory.rs +++ b/crates/connections/src/directory.rs @@ -21,8 +21,7 @@ impl Directory { .connections() .read(cx) .profiles(cx) - .iter() - .find(|profile| profile.id.to_string() == id) + .get_by_canonical_id(id) .cloned() } } @@ -88,10 +87,10 @@ fn summary(profile: &Profile, installed: &Installed, cx: &App) -> ConnectionSumm group: profile.group.clone().map(Into::into), description: profile.description.clone().into(), target: profile.target.clone(), - icon: installed.icon(profile, cx), + icon: installed.directory_icon(profile, cx), flag: installed .shown_country(profile, cx) - .and_then(|code| installed.flag(&code, cx)), + .and_then(|code| installed.directory_flag(&code, cx)), } } diff --git a/crates/connections/src/directory/tests.rs b/crates/connections/src/directory/tests.rs index 7ab7c6f2..3ee3facf 100644 --- a/crates/connections/src/directory/tests.rs +++ b/crates/connections/src/directory/tests.rs @@ -1,4 +1,7 @@ -use gpui_kit::{AppContext as _, test::TestWindowExt as _}; +use gpui_kit::{ + AppContext as _, Context, ImageSource, IntoElement, ParentElement, Render, Styled, Window, div, + img, px, test::TestWindowExt as _, +}; use nocterm_session::{Auth, Target}; use super::*; @@ -132,6 +135,19 @@ async fn empty_center_reconnect_uses_normal_directory_and_current_profile( ); } +struct FlagPreviews([ImageSource; 2]); + +impl Render for FlagPreviews { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().children( + self.0 + .iter() + .cloned() + .map(|source| img(source).w(px(16.)).h(px(11.))), + ) + } +} + #[gpui_kit::test] async fn recent_flags_follow_detection_setting_and_keep_manually_chosen_country( cx: &mut gpui_kit::TestAppContext, @@ -164,7 +180,7 @@ async fn recent_flags_follow_detection_setting_and_keep_manually_chosen_country( nocterm_connections_model::test_support::ScriptedObservations::default(), ); observations.flag_next(Ok(Some( - b"".to_vec(), + br#""#.to_vec(), ))); let observations = crate::ObservationDeps::new( observations.clone(), @@ -198,22 +214,47 @@ async fn recent_flags_follow_detection_setting_and_keep_manually_chosen_country( }) .await .unwrap(); - cx.update(|cx| { - let normal = Directory::new(installed.clone()).connections(cx); - let recent = Directory::new(installed.clone()).recent_connections(cx); - assert_eq!(recent.len(), 2); - for server in &recent { + assert_recent_flags_match_directory(&installed, chosen.id, enabled, cx); + } +} + +fn assert_recent_flags_match_directory( + installed: &Installed, + chosen: ProfileId, + enabled: bool, + cx: &mut gpui_kit::TestAppContext, +) { + let flag_pairs = cx.update(|cx| { + let normal = Directory::new(installed.clone()).connections(cx); + let recent = Directory::new(installed.clone()).recent_connections(cx); + assert_eq!(recent.len(), 2); + recent + .into_iter() + .filter_map(|server| { let expected = normal.iter().find(|entry| entry.id == server.id).unwrap(); assert_eq!(server.flag.is_some(), expected.flag.is_some()); assert_eq!( server.flag.is_some(), - server.id == chosen.id.to_string() || enabled + server.id == chosen.to_string() || enabled ); - if let (Some(actual), Some(expected)) = (&server.flag, &expected.flag) { - assert!(std::sync::Arc::ptr_eq(actual, expected)); - } - } - }); + server.flag.zip(expected.flag.clone()) + }) + .collect::>() + }); + for (recent, normal) in flag_pairs { + let (recent, recent_raster) = crate::test_support::capture_raster(&recent); + let (normal, normal_raster) = crate::test_support::capture_raster(&normal); + let (_, window) = cx.add_window_view(|_, _| FlagPreviews([recent, normal])); + window.update(|window, cx| window.draw(cx).clear(cx)); + window.run_until_parked(); + window.update(|window, cx| window.draw(cx).clear(cx)); + let recent = recent_raster + .take() + .expect("expected the recent server flag"); + let normal = normal_raster + .take() + .expect("expected the directory server flag"); + assert_eq!(recent.id, normal.id); } } diff --git a/crates/connections/src/editor/appearance.rs b/crates/connections/src/editor/appearance.rs index 8e2f2924..bb953996 100644 --- a/crates/connections/src/editor/appearance.rs +++ b/crates/connections/src/editor/appearance.rs @@ -116,7 +116,7 @@ impl AppearanceFields { Some(os) => format!("Empty: the {} colour, {}.", os.name, os.color), None => "Empty: grey.".to_owned(), }; - let tiles = self.tiles(detected, color, cx); + let tiles = self.tiles(detected, color, installed, cx); let background = nocterm_ui::hsla( nocterm_ui::TerminalStyle::with_settings( installed @@ -154,6 +154,7 @@ impl AppearanceFields { &self, detected: Option<&'static crate::os::Os>, color: Option, + installed: &crate::Installed, cx: &mut Context, ) -> Vec { let theme = cx.theme(); @@ -185,7 +186,11 @@ impl AppearanceFields { }) .cursor_pointer() .hover(|tile| tile.bg(accent)) - .child(crate::panel::server_icon(os, color.as_deref(), muted)) + .child(crate::panel::server_icon( + os.and_then(|os| installed.presentation().icon_for(os, color.as_deref())), + color.as_deref().and_then(crate::os::rgb), + muted, + )) .tooltip(move |_, cx| { cx.new(|_| gpui_kit::component::tooltip::Tooltip::new(tooltip.clone())) .into() diff --git a/crates/connections/src/editor/authentication.rs b/crates/connections/src/editor/authentication.rs index 365619fc..db026a57 100644 --- a/crates/connections/src/editor/authentication.rs +++ b/crates/connections/src/editor/authentication.rs @@ -3,11 +3,11 @@ use super::{ ConnectionEditor, field, password::PasswordField, text, vault_key::VaultKeyField, watch, }; -use crate::{SavedPasswords, VaultPlace}; +use crate::{SavedPassword, SavedPasswords, VaultPlace}; use gpui_kit::{App, Context, Entity, Subscription, Window, component::input::InputState}; use nocterm_connections_model::draft::{AuthKind, AuthenticationDraft}; use nocterm_connections_model::profiles::Profile; -use nocterm_session::{Auth, Secret}; +use nocterm_session::{Auth, CredentialId, Secret}; use nocterm_ssh_keys::VaultSshKeys; use std::sync::Arc; pub(super) struct AuthenticationFields { @@ -113,11 +113,13 @@ use gpui_kit::{ component::{ ActiveTheme as _, Icon, Selectable as _, Sizable as _, button::{Button, ButtonVariants as _}, - h_flex, v_flex, + h_flex, + scroll::{Scrollbar, ScrollbarMode}, + v_flex, }, div, prelude::*, - rems, + px, rems, uniform_list, }; use nocterm_ui::{IconName, form}; @@ -269,26 +271,10 @@ impl AuthenticationFields { /// The passwords the vault keeps, to sign in with one of them; none when it keeps none. fn saved_passwords_row(&self, cx: &mut Context) -> Option { let field = self.password.read(cx); - if field.listed().is_empty() { + if !field.has_saved_passwords() { return None; } - let chosen = field.chosen(); let query = field.query().clone(); - let matching: Vec<(usize, String, usize, bool)> = field - .matching(cx) - .into_iter() - .map(|(index, saved)| { - let picked = chosen == Some(saved.id); - (index, saved.label.clone(), saved.servers, picked) - }) - .collect(); - let empty = matching.is_empty(); - let rows: Vec = matching - .into_iter() - .map(|(index, label, servers, picked)| { - saved_password_row(index, label, servers, picked, cx) - }) - .collect(); let list = v_flex() .w_full() .gap_0p5() @@ -301,10 +287,7 @@ impl AuthenticationFields { .cleanable(true), ), ) - .children(rows) - .when(empty, |list| { - list.child(form::note("No saved password has this name.", cx)) - }); + .child(render_saved_passwords(field, cx)); Some(form::stacked_row( "Saved passwords", "Sign in with a password the vault keeps. One password can sign in to several \ @@ -316,18 +299,66 @@ impl AuthenticationFields { } } +fn render_saved_passwords(field: &PasswordField, cx: &Context) -> AnyElement { + let count = field.matching_count(); + if count == 0 { + return form::note("No saved password has this name.", cx); + } + if count <= 8 { + return v_flex() + .gap_0p5() + .children((0..count).filter_map(|position| password_at(field, position, cx))) + .into_any_element(); + } + + let scroll = field.scroll(); + div() + .relative() + .id("editor-saved-password-list") + .test_support() + .child( + uniform_list( + "editor-saved-password-rows", + count, + cx.processor(|this, range: std::ops::Range, _, cx| { + let field = this.authentication.password.read(cx); + range + .filter_map(|position| password_at(field, position, cx)) + .map(|row| div().pb_0p5().child(row)) + .collect() + }), + ) + .w_full() + .h(px(216.)) + .track_scroll(&scroll), + ) + .child(Scrollbar::vertical(&scroll).mode(ScrollbarMode::Always)) + .into_any_element() +} + +fn password_at( + field: &PasswordField, + position: usize, + cx: &Context, +) -> Option { + let (index, saved) = field.matching_password(position)?; + Some(saved_password_row(index, saved, field.chosen(), cx)) +} + /// One saved password to sign in with: its name and how many servers use it, left aligned, /// the chosen one marked. fn saved_password_row( index: usize, - label: String, - servers: usize, - picked: bool, - cx: &mut Context, + saved: &SavedPassword, + chosen: Option, + cx: &Context, ) -> AnyElement { let theme = cx.theme(); let hover = theme.foreground.opacity(0.06); - let servers = match servers { + let id = saved.id; + let picked = chosen == Some(id); + let label = SharedString::from(saved.label.as_str()); + let servers = match saved.servers { 0 => "no server yet".to_owned(), 1 => "1 server".to_owned(), n => format!("{n} servers"), @@ -367,7 +398,7 @@ fn saved_password_row( .on_click(cx.listener(move |this, _, window, cx| { this.authentication .password() - .update(cx, |field, cx| field.choose(index, window, cx)); + .update(cx, |field, cx| field.choose(id, window, cx)); })) .into_any_element() } @@ -376,27 +407,10 @@ impl AuthenticationFields { /// The vault's keys to choose from, and ways to add one. fn vault_key_rows(&self, cx: &mut Context) -> Vec { let field = self.vault_key.read(cx); - let keys = field.listed().iter().enumerate().map(|(index, key)| { - Button::new(SharedString::from(format!("vault-key-{index}"))) - .small() - .ghost() - .label(format!("{} \u{b7} {}", key.label, key.fingerprint)) - .selected(field.is_chosen(key)) - .on_click(cx.listener(move |this, _, _, cx| { - this.authentication - .vault_key() - .update(cx, |field, cx| field.choose_listed(index, cx)); - })) - }); - let list = v_flex().gap_1().children(keys).children( - field - .note() - .map(|note| div().text_xs().child(note.to_owned())), - ); let mut rows = vec![form::stacked_row( "Key", "The keys the vault holds.", - list.into_any_element(), + render_vault_keys(field, cx), None, cx, )]; @@ -471,3 +485,67 @@ impl AuthenticationFields { ) } } + +fn vault_key_button( + field: &VaultKeyField, + index: usize, + cx: &Context, +) -> Option(plaintext) { - Ok(Head { v: FORMAT }) => {} - _ => return Decoded::Unrecognized, - } - let Ok(wire) = serde_json::from_slice::(plaintext) else { - return Decoded::Unrecognized; - }; - match serde_json::from_value::(wire.binding) { - Ok(binding) => Decoded::Known(Record { - label: wire.label, - binding, - secret: Secret::new(wire.secret), - }), - Err(_) => Decoded::Unrecognized, +pub(super) fn decode(plaintext: &[u8]) -> Option { + let (CheckedString, binding, OpenedSecret(secret)) = fields(plaintext)?; + Some(Record { binding, secret }) +} + +pub(super) fn metadata(plaintext: &[u8]) -> Option<(String, CredentialBinding)> { + let (label, binding, CheckedString) = fields(plaintext)?; + Some((label, binding)) +} + +fn fields( + plaintext: &[u8], +) -> Option<(L, CredentialBinding, S)> { + // The vault format is a JSON object. Serde also accepts positional structs. + if plaintext.iter().find(|byte| !byte.is_ascii_whitespace()) != Some(&b'{') { + return None; } + let wire: Wire = serde_json::from_slice(plaintext).ok()?; + let binding = serde_json::from_value(wire.binding).ok()?; + Some((wire.label, binding, wire.secret)) } #[cfg(test)] diff --git a/crates/hub-io/src/vault/codec/tests.rs b/crates/hub-io/src/vault/codec/tests.rs index 32202401..fe356910 100644 --- a/crates/hub-io/src/vault/codec/tests.rs +++ b/crates/hub-io/src/vault/codec/tests.rs @@ -6,14 +6,10 @@ use super::*; fn round_trip(binding: CredentialBinding) { let bytes = encode("label", &binding, &Secret::new("s3cret")).unwrap(); - match decode(&bytes) { - Decoded::Known(record) => { - assert_eq!(record.label, "label"); - assert_eq!(record.binding, binding); - assert_eq!(record.secret.expose(), "s3cret"); - } - Decoded::Unrecognized => panic!("a record this client wrote must read back"), - } + let record = decode(&bytes).expect("a record this client wrote must read back"); + assert_eq!(metadata(&bytes), Some(("label".into(), binding.clone()))); + assert_eq!(record.binding, binding); + assert_eq!(record.secret.expose(), "s3cret"); } #[test] @@ -34,19 +30,19 @@ fn every_binding_kind_round_trips() { #[test] fn a_binding_of_an_unknown_kind_is_unrecognized() { let text = br#"{"v":1,"label":"x","binding":{"kind":"hardware_token","slot":3},"secret":"s"}"#; - assert!(matches!(decode(text), Decoded::Unrecognized)); + assert!(decode(text).is_none()); } #[test] fn a_newer_format_version_is_unrecognized() { let text = br#"{"v":2,"label":"x","binding":{"kind":"private_key","public_key":"k"},"secret":"s","extra":1}"#; - assert!(matches!(decode(text), Decoded::Unrecognized)); + assert!(decode(text).is_none()); } #[test] fn text_that_is_not_a_record_is_unrecognized() { - assert!(matches!(decode(b"not json"), Decoded::Unrecognized)); - assert!(matches!(decode(br#"{"v":1}"#), Decoded::Unrecognized)); + assert!(decode(b"not json").is_none()); + assert!(decode(br#"{"v":1}"#).is_none()); } #[test] @@ -69,9 +65,8 @@ fn a_password_the_web_panel_keeps_reads_here_bound_to_its_address() { "binding": {"kind": "password", "target": target}, "secret": "s3cret", }); - let Decoded::Known(record) = decode(plain.to_string().as_bytes()) else { - panic!("the web panel's record reads here"); - }; + let record = + decode(plain.to_string().as_bytes()).expect("the web panel's record reads here"); assert_eq!( record.binding, CredentialBinding::password([Target::new("ops", "prod.example.com", port)]) @@ -91,14 +86,15 @@ fn a_key_the_web_panel_keeps_reads_here_bound_to_its_public_half() { "binding": {"kind": "private_key", "public_key": public_key}, "secret": "-----BEGIN OPENSSH PRIVATE KEY-----\n…\n-----END OPENSSH PRIVATE KEY-----\n", }); - let Decoded::Known(record) = decode(plain.to_string().as_bytes()) else { - panic!("the web panel's key reads here"); - }; + let record = decode(plain.to_string().as_bytes()).expect("the web panel's key reads here"); assert_eq!( record.binding, CredentialBinding::PrivateKey { public_key: public_key.to_owned(), } ); - assert_eq!(record.label, "prod"); + assert_eq!( + metadata(plain.to_string().as_bytes()), + Some(("prod".into(), record.binding)) + ); } diff --git a/crates/hub-io/src/vault/ledger.rs b/crates/hub-io/src/vault/ledger.rs index b13d6b39..9d641402 100644 --- a/crates/hub-io/src/vault/ledger.rs +++ b/crates/hub-io/src/vault/ledger.rs @@ -10,11 +10,11 @@ use std::collections::BTreeMap; use std::sync::Arc; use nocterm_hubs_model::HubError; -use nocterm_keys::random_bytes; +use nocterm_keys::{CollectionKey, random_bytes}; use nocterm_session::{CredentialId, Secret}; use nocterm_vault::{CredentialBinding, CredentialInfo, VaultError}; -use super::codec::{self, Decoded, KIND}; +use super::codec::{self, KIND}; use crate::account::{OpenKeys, Slot, source::CapturedAccount}; mod access; use super::snapshot_budget::{SnapshotBudget, merge_vault}; @@ -25,6 +25,8 @@ use access::LedgerAccess; /// How often a write retries after another device changed the same record. const WRITE_ATTEMPTS: usize = 2; +const LIST_WORK_PER_POLL: usize = 64 * 1024; +const MIN_RECORD_WORK: usize = 1024; pub(crate) struct Ledger { access: LedgerAccess, @@ -138,22 +140,30 @@ impl Ledger { Ok(()) } - /// Opens one cached object: `Ok(None)` when it is a tombstone or another kind, and an - /// error when it does not authenticate. - fn open( + fn key(keys: &OpenKeys, vault: &VaultCopy) -> Result, VaultError> { + keys.own_collection(&vault.collection_id, &vault.key_envelope) + .map_err(|_| VaultError::Authentication) + } + + /// Opens one cached credential, rejecting ciphertext that does not authenticate. + fn open( keys: &OpenKeys, - collection: &str, - envelope: &[u8], + vault: &VaultCopy, object_id: &str, object: &ObjectCopy, - ) -> Result, VaultError> { + decode: impl FnOnce(&[u8]) -> Option, + ) -> Result, VaultError> { if object.deleted || object.kind != KIND { return Ok(None); } - let key = keys - .own_collection(collection, envelope) - .map_err(|_| VaultError::Authentication)?; - codec::open_sealed(&key, collection, object_id, object) + let key = Self::key(keys, vault)?; + codec::open_sealed( + &key, + &vault.collection_id, + object_id, + &object.ciphertext, + decode, + ) } fn cached(&self) -> Result>, VaultError> { @@ -162,27 +172,41 @@ impl Ledger { } pub(super) async fn list(&self) -> Result, VaultError> { + let _listing = self.access.vault_list().await?; let _operation = self.access.operation().await?; let keys = self.keys()?; self.sync(&keys).await?; let Some(vault) = self.cached()? else { return Ok(Vec::new()); }; + let mut collection_key = None; let mut listed = Vec::new(); + let mut budget = LIST_WORK_PER_POLL; for (object_id, object) in &vault.objects { - if let Some(Decoded::Known(record)) = Self::open( - &keys, + if object.deleted || object.kind != KIND { + continue; + } + // Charge for decoding each record as well as handling its sealed bytes. + // A single record's authentication stays atomic even when it exceeds the budget. + let work = object.ciphertext.len().max(MIN_RECORD_WORK); + if work > budget && budget < LIST_WORK_PER_POLL { + tokio::task::yield_now().await; + budget = LIST_WORK_PER_POLL; + } + budget = budget.saturating_sub(work); + let key = match &collection_key { + Some(key) => key, + None => collection_key.insert(Self::key(&keys, &vault)?), + }; + if let Some((label, binding)) = codec::open_sealed( + key, &vault.collection_id, - &vault.key_envelope, object_id, - object, + &object.ciphertext, + codec::metadata, )? && let Ok(id) = object_id.parse::() { - listed.push(CredentialInfo { - id, - label: record.label, - binding: record.binding, - }); + listed.push(CredentialInfo { id, label, binding }); } } Ok(listed) @@ -227,25 +251,9 @@ impl Ledger { /// The readable record `object_id` of the cached vault. fn record(&self, keys: &Arc, object_id: &str) -> Result { - let personal = self.access.read(|cache| { - let vault = cache?.vault.as_ref()?; - let object = vault - .objects - .get(object_id) - .filter(|object| !object.deleted)?; - Some(( - vault.collection_id.clone(), - vault.key_envelope.clone(), - object.clone(), - )) - })?; - let Some((collection, envelope, object)) = personal else { - return Err(VaultError::NotFound); - }; - match Self::open(keys, &collection, &envelope, object_id, &object)? { - Some(Decoded::Known(record)) => Ok(record), - Some(Decoded::Unrecognized) | None => Err(VaultError::NotFound), - } + let vault = self.cached()?.ok_or(VaultError::NotFound)?; + let object = vault.objects.get(object_id).ok_or(VaultError::NotFound)?; + Self::open(keys, &vault, object_id, object, codec::decode)?.ok_or(VaultError::NotFound) } pub(super) async fn put( @@ -350,14 +358,8 @@ impl Ledger { Err(VaultError::NotFound) }; } - match Self::open( - keys, - &vault.collection_id, - &vault.key_envelope, - object_id, - object, - )? { - Some(Decoded::Known(_)) => Ok(object.version), + match Self::open(keys, &vault, object_id, object, codec::metadata)? { + Some(_) => Ok(object.version), _ if creating => Err(VaultError::Format), _ => Err(VaultError::NotFound), } diff --git a/crates/hub-io/src/vault/ledger/access.rs b/crates/hub-io/src/vault/ledger/access.rs index 7086b0f2..2eb8dbfb 100644 --- a/crates/hub-io/src/vault/ledger/access.rs +++ b/crates/hub-io/src/vault/ledger/access.rs @@ -13,6 +13,14 @@ pub(super) struct LedgerAccess { } impl LedgerAccess { + pub(super) async fn vault_list(&self) -> Result { + self.slot + .cache_work() + .vault_list() + .await + .map_err(|error| VaultError::Io(std::io::Error::other(error))) + } + pub(super) async fn operation(&self) -> Result { self.slot .cache_work() diff --git a/crates/hub-io/src/vault/ledger/tests.rs b/crates/hub-io/src/vault/ledger/tests.rs index a01062a0..e4e98228 100644 --- a/crates/hub-io/src/vault/ledger/tests.rs +++ b/crates/hub-io/src/vault/ledger/tests.rs @@ -243,6 +243,92 @@ async fn write_foreign(device: &Device, hub: &Arc, object_id: &str, t .unwrap(); } +#[tokio::test] +async fn a_credential_can_be_read_while_four_dense_lists_wait() { + let hub = Arc::new(MemoryHub::default()); + let (device, _) = device(&hub); + let binding = password_binding(); + let plain = codec::encode("Work", &binding, &Secret::new("pw")).unwrap(); + let store = Store::new(hub.clone(), device.slot.open().unwrap()); + let at = store.ensure(VAULT_KIND).await.unwrap(); + let first = CredentialId::from_bytes([0; 16]); + for index in 0..128 { + let id = CredentialId::from_bytes([index; 16]); + store + .put(&at, KIND, &id.to_string(), &plain, 0) + .await + .unwrap(); + } + let expected = device.ledger.list().await.unwrap(); + assert_eq!(expected.len(), 128); + hub.set_offline(true); + tokio::task::yield_now().await; + + let mut lists: Vec<_> = (0..4).map(|_| Box::pin(device.ledger.list())).collect(); + for list in &mut lists { + assert!(futures::poll!(list.as_mut()).is_pending()); + } + let read = std::pin::pin!(device.ledger.get(first, binding)); + let std::task::Poll::Ready(Ok(secret)) = futures::poll!(read) else { + panic!("a credential read has room while the lists are pending"); + }; + assert_eq!(secret.expose(), "pw"); + for list in futures::future::join_all(lists).await { + let rows = list.unwrap(); + assert_eq!(rows.len(), expected.len()); + assert!( + rows.iter() + .zip(&expected) + .all(|(a, b)| { a.id == b.id && a.label == b.label && a.binding == b.binding }) + ); + } +} + +#[tokio::test] +async fn only_well_formed_credentials_are_listed_and_read() { + let hub = Arc::new(MemoryHub::default()); + let (device, _) = device(&hub); + let binding = CredentialBinding::PrivateKey { + public_key: "k".into(), + }; + let known = CredentialId::from_bytes([0; 16]); + let text = r#"{"label":"Line\nbreak","binding":{"kind":"private_key","public_key":"k"},"secret":"\u03b4\n\"","v":1,"future":true}"#; + write_foreign(&device, &hub, &known.to_string(), text).await; + let invalid = [ + r#"{"v":1,"label":"x","binding":{"kind":"private_key","public_key":"k"},"secret":null}"#, + r#"{"v":1,"label":"x","binding":{"kind":"private_key","public_key":"k"},"secret":"\uD800"}"#, + r#"{"v":1,"label":"x","binding":{"kind":"private_key","public_key":"k"},"secret":"x","secret":"y"}"#, + r#"{"v":2,"label":"x","binding":{"kind":"private_key","public_key":"k"},"secret":"x"}"#, + r#"[1,"x",{"kind":"private_key","public_key":"k"},"x"]"#, + ]; + let mut hidden = Vec::new(); + for (index, text) in (1u8..).zip(invalid) { + let id = CredentialId::from_bytes([index; 16]); + write_foreign(&device, &hub, &id.to_string(), text).await; + hidden.push(id); + } + let listed = device.ledger.list().await.unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].id, known); + assert_eq!(listed[0].label, "Line\nbreak"); + assert_eq!(listed[0].binding, binding); + assert_eq!( + device + .ledger + .get(known, binding.clone()) + .await + .unwrap() + .expose(), + "δ\n\"" + ); + for id in hidden { + assert!(matches!( + device.ledger.get(id, binding.clone()).await, + Err(VaultError::NotFound) + )); + } +} + #[tokio::test] async fn a_record_of_an_unknown_kind_is_hidden_and_never_changed() { let hub = Arc::new(MemoryHub::default()); diff --git a/crates/hub-io/src/vault/tests.rs b/crates/hub-io/src/vault/tests.rs index 7d1a06c4..fff53df8 100644 --- a/crates/hub-io/src/vault/tests.rs +++ b/crates/hub-io/src/vault/tests.rs @@ -8,6 +8,7 @@ use super::*; use crate::account::testing::NativeVault; use crate::account::testing::{PASSWORD, signed_in}; use crate::store::memory::MemoryHub; +mod read_profile; mod refresh; mod source_binding; diff --git a/crates/hub-io/src/vault/tests/read_profile.rs b/crates/hub-io/src/vault/tests/read_profile.rs new file mode 100644 index 00000000..8eafb4bd --- /dev/null +++ b/crates/hub-io/src/vault/tests/read_profile.rs @@ -0,0 +1,146 @@ +use std::{ + hint::black_box, + io::{Write as _, stdout}, + time::Instant, +}; + +use super::*; +use crate::store::{Store, VAULT_KIND}; +use crate::vault::codec::{KIND, encode}; + +fn key_binding() -> CredentialBinding { + CredentialBinding::PrivateKey { + public_key: "ssh-ed25519 benchmark-key".into(), + } +} + +fn credential_id(index: u128) -> CredentialId { + CredentialId::from_bytes(index.to_be_bytes()) +} + +async fn fixture(count: u128, key_text: &str) -> (NativeVault, Arc, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let (_accounts, slot, record) = signed_in(dir.path()); + let hub = Arc::new(MemoryHub::default()); + hub.set_keyset(Some(record)); + let store = Store::new(hub.clone(), slot.open().unwrap()); + let at = store.ensure(VAULT_KIND).await.unwrap(); + for index in 0..count { + let (binding, secret) = if index % 4 == 0 { + (key_binding(), Secret::new(key_text)) + } else { + (binding(), Secret::new("sample password")) + }; + let plain = encode(&format!("Credential {index}"), &binding, &secret).unwrap(); + store + .put(&at, KIND, &credential_id(index).to_string(), &plain, 0) + .await + .unwrap(); + } + (NativeVault::new(slot, hub.clone()), hub, dir) +} + +fn report(out: &mut impl std::io::Write, size: u128, operation: &str, mut samples: Vec) { + samples.sort_unstable(); + writeln!( + out, + "{size} credentials {operation} n={} p50={:.1?} p95={:.1?}", + samples.len(), + samples[samples.len() / 2], + samples[(samples.len() - 1) * 95 / 100], + ) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "manual encrypted vault read profile"] +async fn measure_hub_vault_credential_reads() { + let key_text = "synthetic OpenSSH key line +/\\\"\n".repeat(128); + for (count, iterations) in [(32, 256), (1_024, 128)] { + let (vault, hub, _dir) = fixture(count, &key_text).await; + let expected = vault.list().await.unwrap(); + assert_eq!(expected.len() as u128, count); + assert!(expected.iter().enumerate().all(|(index, row)| { + row.id == credential_id(index as u128) && row.label == format!("Credential {index}") + })); + hub.set_offline(true); + let mut list = Vec::with_capacity(iterations); + let mut get = Vec::with_capacity(iterations * 8); + writeln!(stdout(), "vault profile begin {count}").unwrap(); + for _ in 0..iterations { + let started = Instant::now(); + let rows = vault.list().await.unwrap(); + list.push(started.elapsed()); + assert_eq!(rows.len(), expected.len()); + for (row, expected) in rows.iter().zip(&expected) { + assert_eq!(row.id, expected.id); + assert_eq!(row.label, expected.label); + assert_eq!(row.binding, expected.binding); + } + for _ in 0..8 { + let started = Instant::now(); + let secret = vault.get(credential_id(0), key_binding()).await.unwrap(); + get.push(started.elapsed()); + assert_eq!(black_box(secret.expose()), key_text); + } + } + let mut out = stdout().lock(); + writeln!(out, "vault profile end {count}").unwrap(); + report(&mut out, count, "list", list); + report(&mut out, count, "get", get); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "manual Hub worker latency profile with overlapping vault reads"] +async fn measure_hub_latency_during_parallel_vault_reads() { + const RECORDS: u128 = 4_096; + const WAVES: usize = 32; + let key_text = "synthetic OpenSSH key line +/\\\"\n".repeat(128); + let (vault, hub, _dir) = fixture(RECORDS, &key_text).await; + let expected = vault.list().await.unwrap(); + assert_eq!(expected.len() as u128, RECORDS); + + for (offline, readers) in [(true, 0), (true, 1), (true, 2), (true, 4), (false, 2)] { + hub.set_offline(offline); + let mut lists = Vec::with_capacity(WAVES * readers); + let mut gets = Vec::with_capacity(WAVES); + let mut scheduler = Vec::with_capacity(WAVES); + for _ in 0..WAVES { + let wave = futures::future::join_all((0..readers).map(|_| { + let started = Instant::now(); + let result = vault.list(); + async move { + let rows = result.await.unwrap(); + (started.elapsed(), rows) + } + })); + let get = async { + let started = Instant::now(); + let secret = vault.get(credential_id(1), binding()).await.unwrap(); + gets.push(started.elapsed()); + assert_eq!(secret.expose(), "sample password"); + }; + let ping = async { + let started = Instant::now(); + tokio::spawn(async {}).await.unwrap(); + scheduler.push(started.elapsed()); + }; + let (answers, (), ()) = tokio::join!(wave, get, ping); + for (duration, rows) in answers { + lists.push(duration); + assert_eq!(rows.len(), expected.len()); + assert!(rows.iter().zip(&expected).all(|(a, b)| { + a.id == b.id && a.label == b.label && a.binding == b.binding + })); + } + } + let mut out = stdout().lock(); + writeln!(out, "parallel vault reads={readers} offline={offline}").unwrap(); + if !lists.is_empty() { + report(&mut out, RECORDS, "list", lists); + } + report(&mut out, RECORDS, "get", gets); + report(&mut out, RECORDS, "scheduler", scheduler); + } +} diff --git a/crates/hub-io/tests/hub.rs b/crates/hub-io/tests/hub.rs index f5363263..93720799 100644 --- a/crates/hub-io/tests/hub.rs +++ b/crates/hub-io/tests/hub.rs @@ -22,6 +22,8 @@ use nocterm_session::{RelayDialer as _, RelayError, RelayRefusal, Secret, Target mod account; #[path = "hub/chats.rs"] mod chats; +#[path = "hub/replica_performance.rs"] +mod replica_performance; #[path = "hub/revocation.rs"] mod revocation; diff --git a/crates/hub-io/tests/hub/chats.rs b/crates/hub-io/tests/hub/chats.rs index 128dc11e..ad213299 100644 --- a/crates/hub-io/tests/hub/chats.rs +++ b/crates/hub-io/tests/hub/chats.rs @@ -5,24 +5,202 @@ use super::{Hub, hub, links, sign_in}; use futures::executor::block_on; use nocterm_ai::agents::AgentLaunch; -use nocterm_ai::model::content::Content; +use nocterm_ai::history::ContextId; +use nocterm_ai::local_environment::{ChatScope, LocalEnvironment}; +use nocterm_ai::model::content::{Content, Image}; use nocterm_ai::model::controls::{ConfigCategory, ConfigKind, ConfigOption, ConfigSetting}; use nocterm_ai::model::ids::SessionId; -use nocterm_ai::model::session::{PromptRequest, RestoreSession, SessionOpen, SetConfigOption}; -use nocterm_ai::{AgentCommands, AgentConnector as _, ConnectRequest}; +use nocterm_ai::model::session::{ + PromptOutcome, PromptRequest, RestoreSession, SessionOpen, SessionUpdate, SetConfigOption, + StopReason, +}; +use nocterm_ai::{ + AgentCommands, AgentConnection, AgentConnector as _, AgentError, AgentEvent, ConnectRequest, +}; +use nocterm_ai::{storage::ChatRepository as _, testing::InMemoryAgentRepository}; use nocterm_hub_agents_model::{ - AgentDraft, ApprovalMode, HubAgentDirectory as _, HubServers as _, NewServer, ProviderDraft, - ProviderKind, + AgentDraft, ApprovalMode, HubAgentDirectory as _, HubChange, HubChanges as _, HubServers as _, + NewServer, ProviderDraft, ProviderKind, }; -use nocterm_hub_io::{HubAgentConnector, HubAgentsLink, HubLinks}; +use nocterm_hub_io::{HubAgentConnector, HubAgentsLink, HubChatRepository, HubLinks}; use std::sync::Arc; +use std::sync::mpsc::Receiver; use std::time::{Duration, Instant}; /// A host key the hub accepts; no server answers with it, and none needs to. const HOST_KEY: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"; -fn connect(links: &HubLinks, launch: &AgentLaunch) -> Arc { +/// The harness waits for `wire fixture ready`, delays ListChats on the server and creates +/// `start` in NOCTERM_CATALOG_WIRE_GATE. Creating `stop` ends the fixture after observation. +#[test] +#[ignore = "manual ListChats burst profile against an isolated Hub"] +fn measure_catalog_burst_while_the_hub_is_slow() { + use std::io::Write as _; + let hub = hub().expect("configure the private Hub fixture"); + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &hub).unwrap(); + let partition = links + .open_account(&hub.id()) + .unwrap() + .local_source() + .unwrap() + .partition(); + let scope = ChatScope::new(LocalEnvironment::HubAccount(partition), ContextId::General); + let repository = HubChatRepository::new( + &links, + Arc::new(InMemoryAgentRepository::default()), + dir.path().join("catalog"), + ); + let phase = std::path::PathBuf::from(std::env::var_os("NOCTERM_CATALOG_WIRE_GATE").unwrap()); + writeln!(std::io::stdout().lock(), "wire fixture ready").unwrap(); + wait_for_profile_gate(&phase.join("start")); + let started = Instant::now(); + for _ in 0..100 { + block_on(repository.catalog_in(scope.clone())).unwrap(); + } + writeln!( + std::io::stdout().lock(), + "wire burst complete: {} us", + started.elapsed().as_micros() + ) + .unwrap(); + wait_for_profile_gate(&phase.join("stop")); +} + +fn wait_for_profile_gate(path: &std::path::Path) { + let limit = Instant::now() + Duration::from_secs(25); + while !path.exists() { + assert!(Instant::now() < limit, "timed out waiting for {path:?}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +#[test] +#[ignore = "requires two isolated, independently signed-in Hub fixtures"] +fn refreshing_one_hub_does_not_request_another_hubs_catalog() { + let first = hub().expect("configure the first private Hub fixture"); + let second = second_hub(); + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &first).unwrap(); + sign_in(&links, &second).unwrap(); + let directory = HubAgentsLink::new(&links); + let (agent, provider) = agent_record(&directory, &first, "https://models.example/v1"); + create_chat_without_sending(&links, &first, &agent); + let mut reading_first = block_on(directory.watch(&first.id())).unwrap(); + let mut reading_second = block_on(directory.watch(&second.id())).unwrap(); + let repository = HubChatRepository::new( + &links, + Arc::new(InMemoryAgentRepository::default()), + dir.path().join("catalog"), + ); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + block_on(repository.catalog_in(hub_scope(&links, &first))).unwrap(); + let refreshed_first = runtime.block_on(async { + tokio::time::timeout(Duration::from_secs(5), reading_first.next()).await + }); + let changed_second = runtime.block_on(async { + tokio::time::timeout(Duration::from_millis(750), reading_second.next()).await + }); + if matches!(&changed_second, Ok(Ok(Some(HubChange::Chats)))) { + block_on(repository.catalog_in(hub_scope(&links, &second))).unwrap(); + std::thread::sleep(Duration::from_millis(250)); + } + block_on(directory.delete_agent(&first.id(), &agent.id)).unwrap(); + block_on(directory.delete_provider(&first.id(), &provider)).unwrap(); + assert_eq!( + refreshed_first.unwrap().unwrap(), + Some(HubChange::ChatCatalogPublished) + ); + assert!( + changed_second.is_err(), + "the unrelated Hub stream stays idle" + ); +} + +#[test] +#[ignore = "manual Hub catalog publication feedback profile"] +fn a_catalog_publication_can_be_read_without_fetching_it_again() { + let hub = hub().expect("configure the private Hub fixture"); + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &hub).unwrap(); + let directory = HubAgentsLink::new(&links); + let (agent, provider) = agent_record(&directory, &hub, "https://models.example/v1"); + create_chat_without_sending(&links, &hub, &agent); + let mut watcher = block_on(directory.watch(&hub.id())).unwrap(); + let repository = HubChatRepository::new( + &links, + Arc::new(InMemoryAgentRepository::default()), + dir.path().join("catalog"), + ); + let scope = hub_scope(&links, &hub); + block_on(repository.catalog_in(scope.clone())).unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let change = runtime + .block_on(async { tokio::time::timeout(Duration::from_secs(5), watcher.next()).await }) + .unwrap() + .unwrap(); + assert_eq!(change, Some(HubChange::ChatCatalogPublished)); + let rows = block_on(repository.catalog_cached_in(scope)).unwrap(); + assert_eq!(rows.len(), 1); + std::thread::sleep(Duration::from_millis(250)); + block_on(directory.delete_agent(&hub.id(), &agent.id)).unwrap(); + block_on(directory.delete_provider(&hub.id(), &provider)).unwrap(); +} + +fn second_hub() -> Hub { + let setting = |name: &str| std::env::var(name).expect("configure the second Hub fixture"); + Hub { + address: setting("NOCTERM_HUB_B_ADDRESS").parse().unwrap(), + fingerprint: setting("NOCTERM_HUB_B_FINGERPRINT").parse().unwrap(), + username: setting("NOCTERM_HUB_B_USERNAME"), + password: setting("NOCTERM_HUB_B_PASSWORD"), + } +} + +fn hub_scope(links: &HubLinks, hub: &Hub) -> ChatScope { + let source = links + .open_account(&hub.id()) + .unwrap() + .local_source() + .unwrap(); + ChatScope::new( + LocalEnvironment::HubAccount(source.partition()), + ContextId::General, + ) +} + +fn create_chat_without_sending( + links: &HubLinks, + hub: &Hub, + agent: &nocterm_hub_agents_model::HubAgent, +) -> SessionId { + let launch = AgentLaunch::hub_agent(hub.id(), agent.id.to_string(), agent.name.clone()); + let commands = connect(links, &launch).commands; + let opened = block_on(commands.new_session(SessionOpen { + working_directory: std::env::temp_dir(), + endpoints: Vec::new(), + })) + .unwrap(); + let error = block_on(commands.prompt(PromptRequest { + session: opened.session.clone(), + content: vec![Content::Image(Image::new("!", "image/png"))], + })) + .unwrap_err(); + assert!(error.to_string().contains("The image could not be read")); + opened.session +} + +fn connect(links: &HubLinks, launch: &AgentLaunch) -> AgentConnection { let request = ConnectRequest { launch: launch.clone(), working_directory: std::env::temp_dir(), @@ -31,9 +209,7 @@ fn connect(links: &HubLinks, launch: &AgentLaunch) -> Arc { resources: Default::default(), cancellation: Default::default(), }; - block_on(HubAgentConnector::new(links).connect(request)) - .expect("the hub agent connects") - .commands + block_on(HubAgentConnector::new(links).connect(request)).expect("the hub agent connects") } /// Whether the options show the server flag `id`, and whether it is on. @@ -75,7 +251,7 @@ fn a_server_attached_before_the_first_message_stays_with_the_chat() { let (agent, provider, server) = records(&directory, &hub); let launch = AgentLaunch::hub_agent(hub.id(), agent.id.to_string(), agent.name.clone()); - let here = connect(&links, &launch); + let here = connect(&links, &launch).commands; let open = SessionOpen { working_directory: std::env::temp_dir(), endpoints: Vec::new(), @@ -99,7 +275,7 @@ fn a_server_attached_before_the_first_message_stays_with_the_chat() { }); std::thread::spawn(move || drop(block_on(prompt))); - let elsewhere = connect(&links, &launch); + let elsewhere = connect(&links, &launch).commands; assert_eq!( flag(&reopened(&elsewhere, &opened.session), &id), Some(true) @@ -113,7 +289,7 @@ fn a_server_attached_before_the_first_message_stays_with_the_chat() { flag(&block_on(here.set_config_option(detach)).unwrap(), &id), Some(false) ); - let again = connect(&links, &launch); + let again = connect(&links, &launch).commands; assert_eq!(flag(&reopened(&again, &opened.session), &id), Some(false)); block_on(directory.remove_server(&hub.id(), &server.id)).expect("the server is removed"); @@ -122,21 +298,364 @@ fn a_server_attached_before_the_first_message_stays_with_the_chat() { let _ = block_on(nocterm_hubs_model::HubSignIn::sign_out(&*links, &hub.id())); } -/// An agent with a provider, and a server of the account, as the web panel makes them. -fn records( +#[test] +fn detaching_a_server_is_saved_after_the_first_attachment_fails() { + let Some(hub) = hub() else { return }; + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &hub).expect("the account signs in"); + let directory = HubAgentsLink::new(&links); + let (agent, provider, server) = records(&directory, &hub); + let launch = AgentLaunch::hub_agent(hub.id(), agent.id.to_string(), agent.name.clone()); + let here = connect(&links, &launch).commands; + let opened = block_on(here.new_session(SessionOpen { + working_directory: std::env::temp_dir(), + endpoints: Vec::new(), + })) + .unwrap(); + let id = server.id.to_string(); + let changed = |attached| SetConfigOption { + session: opened.session.clone(), + config: format!("server:{id}").into(), + setting: ConfigSetting::Boolean(attached), + }; + assert_eq!( + flag( + &block_on(here.set_config_option(changed(true))).unwrap(), + &id + ), + Some(true) + ); + reject_then_correct_first_model(&here, &opened.session); + let invalid = || PromptRequest { + session: opened.session.clone(), + content: vec![Content::Image(Image::new("!", "image/png"))], + }; + for _ in 0..3 { + let error = block_on(here.prompt(invalid())).unwrap_err(); + assert!(error.to_string().contains("The image could not be read")); + } + let elsewhere = connect(&links, &launch).commands; + assert_eq!( + flag(&reopened(&elsewhere, &opened.session), &id), + Some(true) + ); + assert_eq!( + flag( + &block_on(here.set_config_option(changed(false))).unwrap(), + &id + ), + Some(false) + ); + assert_eq!( + flag(&reopened(&elsewhere, &opened.session), &id), + Some(false) + ); + + block_on(directory.remove_server(&hub.id(), &server.id)).unwrap(); + block_on(directory.delete_agent(&hub.id(), &agent.id)).unwrap(); + block_on(directory.delete_provider(&hub.id(), &provider)).unwrap(); +} + +fn reject_then_correct_first_model(commands: &Arc, session: &SessionId) { + let model = |name: &str| SetConfigOption { + session: session.clone(), + config: "model".into(), + setting: ConfigSetting::Choice(name.into()), + }; + block_on(commands.set_config_option(model("missing"))).unwrap(); + let rejected = block_on(commands.prompt(PromptRequest { + session: session.clone(), + content: vec![Content::text("hello")], + })); + assert!(matches!(rejected, Err(AgentError::Io(_)))); + let absent = block_on(commands.restore_session(RestoreSession { + session: session.clone(), + working_directory: std::env::temp_dir(), + endpoints: Vec::new(), + fork: false, + })); + assert!(matches!(absent, Err(AgentError::Io(message)) + if message == nocterm_hubs_model::HubError::NotFound.to_string())); + block_on(commands.set_config_option(model("m1"))).unwrap(); +} + +/// The fixture's OpenAI-compatible endpoint streams "Hub λ", " 中" and " 🐈" as separate +/// deltas, pausing beyond the worker's debounce interval after each delta. +#[test] +#[ignore = "requires the isolated Hub streaming provider at NOCTERM_HUB_STREAM_PROVIDER_URL"] +fn a_streamed_model_answer_reaches_the_chat_once() { + let chunks = streamed_answer("hello", None); + assert!(chunks.len() > 1, "the answer arrived in multiple chunks"); + assert_eq!(chunks.concat(), "Hub λ 中 🐈"); +} + +/// The fixture streams 96 ordered 8 KiB parts, each with its decimal index at the start. +#[test] +#[ignore = "manual queue profile against the isolated Hub streaming provider"] +fn measure_streamed_answer_with_a_paused_receiver() { + let chunks = streamed_answer("queue profile", Some(Duration::from_secs(9))); + let expected: String = (0..96) + .map(|part| format!("{part:04}{}", "λ".repeat(4094))) + .collect(); + assert!(chunks.len() > 1, "the answer arrived in multiple chunks"); + assert_eq!(chunks.concat(), expected); +} + +/// A transparent proxy disconnects Watch mid-answer while the provider continues. +/// The fixture streams 144 × 6 KiB, within Hub's durable item limit. +#[test] +#[ignore = "requires the isolated Hub streaming and disconnect fixture"] +fn reconnecting_mid_answer_recovers_all_durable_text() { + let chunks = streamed_answer("reconnect profile", Some(Duration::from_secs(10))); + let expected: String = (0..144) + .map(|part| format!("{part:04}{}", "λ".repeat(3070))) + .collect(); + assert!(chunks.len() > 1, "a prefix was visible before reconnect"); + assert!( + chunks.concat() == expected, + "the complete answer appears exactly once" + ); +} + +/// A larger stream exceeds both Hub's draft window and durable item limit. +#[test] +#[ignore = "requires the isolated Hub streaming and disconnect fixture"] +fn reconnecting_to_an_oversized_answer_keeps_the_visible_prefix() { + let chunks = streamed_answer("oversized profile", Some(Duration::from_secs(10))); + let expected: String = (0..144) + .map(|part| format!("{part:04}{}", "λ".repeat(12286))) + .collect(); + let shown = chunks.concat(); + assert!( + shown.len() > 1024 * 1024, + "the visible draft exceeds the Hub snapshot" + ); + assert!( + expected.starts_with(&shown), + "no text is duplicated or reordered" + ); +} + +#[test] +#[ignore = "requires the isolated Hub streaming provider"] +fn closing_a_chat_with_a_full_receiver_releases_the_pending_prompt() { + with_streamed_prompt("queue profile", None, |connection, session, done| { + let deadline = Instant::now() + Duration::from_secs(12); + while !connection.events.is_full() { + assert!(Instant::now() < deadline, "the receiver never filled"); + std::thread::sleep(Duration::from_millis(10)); + } + block_on(connection.commands.close_session(session.clone())).unwrap(); + let error = done + .recv_timeout(Duration::from_secs(2)) + .expect("closing the chat releases its waiter") + .unwrap_err(); + assert!(error.to_string().contains("chat closed")); + connection.commands.cancel(session.clone()); + }); +} + +/// The isolated Hub seeds 621 consecutive transcript items when this test creates its chat. +/// A wide fixture additionally appends NOCTERM_HUB_BACKLOG_PADDING ASCII bytes to each item. +#[test] +#[ignore = "requires the isolated Hub fixture with a large backlog on chat creation"] +fn a_large_watch_backlog_reaches_the_open_chat_in_order() { + let hub = hub().expect("configure the private Hub fixture"); + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &hub).unwrap(); + let directory = HubAgentsLink::new(&links); + let (agent, provider) = agent_record(&directory, &hub, "https://models.example/v1"); + let launch = AgentLaunch::hub_agent(hub.id(), agent.id.to_string(), agent.name); + let connection = connect(&links, &launch); + let opened = block_on(connection.commands.new_session(SessionOpen { + working_directory: std::env::temp_dir(), + endpoints: Vec::new(), + })) + .unwrap(); + let started = Instant::now(); + let rejected = block_on(connection.commands.prompt(PromptRequest { + session: opened.session.clone(), + content: vec![Content::Image(Image::new("!", "image/png"))], + })) + .unwrap_err(); + assert!(rejected.to_string().contains("The image could not be read")); + + let received = read_backlog(&connection, &opened.session, started); + block_on(directory.delete_agent(&hub.id(), &agent.id)).unwrap(); + block_on(directory.delete_provider(&hub.id(), &provider)).unwrap(); + assert_backlog(received); +} + +#[test] +#[ignore = "requires the isolated Hub fixture with seeded chat history"] +fn a_seeded_hub_chat_restores_its_history_in_order() { + let hub = hub().expect("configure the private Hub fixture"); + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &hub).unwrap(); + let directory = HubAgentsLink::new(&links); + let (agent, provider) = agent_record(&directory, &hub, "https://models.example/v1"); + let session = create_chat_without_sending(&links, &hub, &agent); + let launch = AgentLaunch::hub_agent(hub.id(), agent.id.to_string(), agent.name); + let connection = connect(&links, &launch); + let result = block_on(connection.commands.restore_session(RestoreSession { + session, + working_directory: std::env::temp_dir(), + endpoints: Vec::new(), + fork: false, + })); + block_on(directory.delete_agent(&hub.id(), &agent.id)).unwrap(); + block_on(directory.delete_provider(&hub.id(), &provider)).unwrap(); + let restored = result.expect("a seeded chat restores its transcript"); + let received = restored + .history + .expect("a Hub chat supplies the reopened history") + .into_iter() + .map(|update| match update { + SessionUpdate::AgentMessageChunk(Content::Text(chunk)) => chunk.text, + _ => panic!("the seeded history contains only text"), + }) + .collect(); + assert_backlog(received); +} + +fn assert_backlog(received: Vec) { + assert_eq!(received.len(), 621); + let padding = std::env::var("NOCTERM_HUB_BACKLOG_PADDING") + .map(|size| size.parse().unwrap()) + .unwrap_or(0); + let padding = "x".repeat(padding); + for (index, text) in received.into_iter().enumerate() { + let prefix = format!("{:04} λ", index + 1); + assert_eq!(text.strip_suffix(&padding), Some(prefix.as_str())); + } +} + +fn read_backlog( + connection: &AgentConnection, + session: &SessionId, + started: Instant, +) -> Vec { + let mut received = Vec::new(); + while started.elapsed() < Duration::from_secs(11) && received.len() < 621 { + match connection.events.try_recv() { + Ok(AgentEvent::Session(notice)) if ¬ice.session == session => { + if let SessionUpdate::AgentMessageChunk(Content::Text(text)) = notice.update { + received.push(text.text); + } + } + Ok(_) => {} + Err(async_channel::TryRecvError::Empty) => std::thread::sleep(Duration::from_millis(2)), + Err(async_channel::TryRecvError::Closed) => break, + } + } + use std::io::Write as _; + writeln!( + std::io::stdout().lock(), + "watch backlog: {} items in {:?}", + received.len(), + started.elapsed() + ) + .unwrap(); + received +} + +fn streamed_answer(prompt: &str, pause: Option) -> Vec { + with_streamed_prompt(prompt, pause, |connection, session, done| { + let (outcome, chunks) = receive_answer(connection, session, done); + assert_eq!(outcome.stop_reason, StopReason::EndTurn); + chunks + }) +} + +fn with_streamed_prompt( + prompt: &str, + pause: Option, + check: impl FnOnce(&AgentConnection, &SessionId, &Receiver>) -> T, +) -> T { + use std::io::{Write as _, stdout}; + let hub = hub().expect("configure the private Hub fixture"); + let url = std::env::var("NOCTERM_HUB_STREAM_PROVIDER_URL").expect("configure the stub model"); + let dir = tempfile::tempdir().unwrap(); + let links = links(&dir); + sign_in(&links, &hub).unwrap(); + let directory = HubAgentsLink::new(&links); + let (agent, provider) = agent_record(&directory, &hub, &url); + let launch = AgentLaunch::hub_agent(hub.id(), agent.id.to_string(), agent.name.clone()); + let connection = connect(&links, &launch); + let opened = block_on(connection.commands.new_session(SessionOpen { + working_directory: std::env::temp_dir(), + endpoints: Vec::new(), + })) + .unwrap(); + if pause.is_some() { + writeln!(stdout().lock(), "draft profile begin paused receiver").unwrap(); + } + let result = connection.commands.prompt(PromptRequest { + session: opened.session.clone(), + content: vec![Content::text(prompt)], + }); + let (send, done) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = send.send(block_on(result)); + }); + if let Some(pause) = pause { + std::thread::sleep(pause); + let queued = connection.events.len(); + writeln!( + stdout().lock(), + "draft profile end paused receiver; queued={queued}" + ) + .unwrap(); + } + let checked = check(&connection, &opened.session, &done); + block_on(directory.delete_agent(&hub.id(), &agent.id)).unwrap(); + block_on(directory.delete_provider(&hub.id(), &provider)).unwrap(); + checked +} + +fn receive_answer( + connection: &AgentConnection, + session: &SessionId, + done: &Receiver>, +) -> (PromptOutcome, Vec) { + use std::sync::mpsc::RecvTimeoutError; + let deadline = Instant::now() + Duration::from_secs(20); + let mut chunks = Vec::new(); + loop { + let outcome = done.recv_timeout(Duration::from_millis(5)); + while let Ok(event) = connection.events.try_recv() { + if let AgentEvent::Session(notice) = event + && ¬ice.session == session + && let SessionUpdate::AgentMessageChunk(Content::Text(text)) = notice.update + { + chunks.push(text.text); + } + } + match outcome { + Ok(result) => return (result.unwrap(), chunks), + Err(RecvTimeoutError::Timeout) if Instant::now() < deadline => {} + Err(error) => panic!("the streamed answer did not finish: {error}"), + } + } +} + +fn agent_record( directory: &HubAgentsLink, hub: &Hub, + base_url: &str, ) -> ( nocterm_hub_agents_model::HubAgent, nocterm_hub_agents_model::ProviderId, - nocterm_hub_agents_model::HubServer, ) { let provider = block_on(directory.create_provider( &hub.id(), ProviderDraft { kind: ProviderKind::OpenAi, name: "Stub".into(), - base_url: "https://models.example/v1".into(), + base_url: base_url.into(), models: vec!["m1".into()], api_key: None, }, @@ -155,16 +674,29 @@ fn records( }, )) .expect("an agent"); + (agent, provider.id) +} + +/// An agent with a provider, and a server of the account, as the web panel makes them. +fn records( + directory: &HubAgentsLink, + hub: &Hub, +) -> ( + nocterm_hub_agents_model::HubAgent, + nocterm_hub_agents_model::ProviderId, + nocterm_hub_agents_model::HubServer, +) { + let (agent, provider) = agent_record(directory, hub, "https://models.example/v1"); let server = block_on(directory.add_server( &hub.id(), NewServer { name: "build".into(), - host: "build.example".into(), + host: format!("{}.example", agent.id), port: 22, user: "ops".into(), host_key: HOST_KEY.into(), }, )) .expect("a server"); - (agent, provider.id, server) + (agent, provider, server) } diff --git a/crates/hub-io/tests/hub/replica_performance.rs b/crates/hub-io/tests/hub/replica_performance.rs new file mode 100644 index 00000000..82282fbf --- /dev/null +++ b/crates/hub-io/tests/hub/replica_performance.rs @@ -0,0 +1,107 @@ +use super::{account::Device, account::unique, hub}; +use futures::executor::block_on; +use nocterm_connections_model::{ + profiles::Profile, + replica::{ProfileReplica, RemoteBody, ReplicaCursor}, + test_support::profile_id_for, +}; +use nocterm_session::{Auth, Target}; +use std::{io::Write as _, time::Instant}; + +fn profile(name: String) -> Profile { + Profile { + id: profile_id_for(&name), + name, + description: String::new(), + options: Default::default(), + target: Target::new("ci", "initial.example", 22), + auth: Auth::Password, + credential: None, + launch: None, + icon: None, + icon_color: None, + country: None, + group: None, + jump_hosts: Vec::new(), + } +} + +fn read_all( + replica: &dyn ProfileReplica, + mut cursor: Option, +) -> (ReplicaCursor, Vec, usize) { + let mut bodies = Vec::new(); + for pages in 1..=256 { + let page = block_on(replica.changes(cursor.clone())).unwrap(); + bodies.extend(page.changes.into_iter().map(|change| change.body)); + if !page.more { + return (page.cursor, bodies, pages); + } + assert_ne!(cursor.as_ref(), Some(&page.cursor)); + cursor = Some(page.cursor); + } + panic!("profile feed exceeded the application page limit"); +} + +#[test] +#[ignore = "manual benchmark on a dedicated live Hub account"] +fn measure_live_profile_feed() { + let hub = hub().expect("configure a dedicated live Hub account"); + let (first, _) = Device::sign_in(&hub); + let (second, _) = Device::sign_in(&hub); + let sender = first.account(&hub).replica().unwrap(); + let receiver = second.account(&hub).replica().unwrap(); + let (start_cursor, _, _) = read_all(receiver.as_ref(), None); + let prefix = unique("perf-profile"); + let mut sent: Vec<_> = (0..512) + .map(|index| { + let profile = profile(format!("{prefix}-{index:04}")); + let version = block_on(sender.put(profile.clone(), None)).unwrap(); + (profile, version) + }) + .collect(); + + let start = Instant::now(); + let (mut cursor, received, pages) = read_all(receiver.as_ref(), Some(start_cursor)); + let catch_up = start.elapsed(); + assert!( + received.into_iter().eq(sent + .iter() + .map(|(profile, _)| RemoteBody::Present(Box::new(profile.clone())))) + ); + + let (profile, version) = sent.last_mut().unwrap(); + let mut empty = Vec::with_capacity(9); + let mut edit = Vec::with_capacity(9); + for trial in 0..9 { + let start = Instant::now(); + let page = block_on(receiver.changes(Some(cursor.clone()))).unwrap(); + empty.push(start.elapsed()); + assert!(page.changes.is_empty() && !page.more); + assert_eq!(page.cursor, cursor); + + profile.target.host = format!("updated-{trial}.example"); + *version = block_on(sender.put(profile.clone(), Some(*version))).unwrap(); + let start = Instant::now(); + let page = block_on(receiver.changes(Some(cursor))).unwrap(); + edit.push(start.elapsed()); + assert!(!page.more); + let [change] = page.changes.as_slice() else { + panic!("expected exactly one remote edit"); + }; + assert_eq!(change.body, RemoteBody::Present(Box::new(profile.clone()))); + assert_eq!(change.version, *version); + cursor = page.cursor; + } + for (profile, version) in sent { + block_on(sender.delete(profile.id, version)).unwrap(); + } + empty.sort_unstable(); + edit.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "512 profiles, {pages} pages, catch-up {catch_up:?}, unchanged {:?}, one incoming edit {:?}", + empty[4], edit[4] + ) + .unwrap(); +} diff --git a/crates/hubs-model/src/settings.rs b/crates/hubs-model/src/settings.rs index 998bb99f..35c8a4f1 100644 --- a/crates/hubs-model/src/settings.rs +++ b/crates/hubs-model/src/settings.rs @@ -43,10 +43,12 @@ pub struct HubRecord { impl HubRecord { pub fn new(address: HubAddress, trust: TrustPolicy, label: impl Into) -> Self { + let mut label = label.into(); + sanitize_label(&mut label); Self { address, trust, - label: clean_label(&label.into()), + label, color: None, } } @@ -72,8 +74,29 @@ impl HubRecord { } fn clean_label(label: &str) -> String { - let printable: String = label.chars().filter(|c| !c.is_control()).collect(); - printable.trim().chars().take(MAX_LABEL_CHARS).collect() + let mut label = label.to_owned(); + sanitize_label(&mut label); + label +} + +fn sanitize_label(label: &mut String) { + label.retain(|c| !c.is_control()); + let start = label.len() - label.trim_start().len(); + let end = label.trim_end().len(); + if start >= end { + label.clear(); + } else { + label.truncate(end); + if start != 0 { + drop(label.drain(..start)); + } + if let Some((end, _)) = label.char_indices().nth(MAX_LABEL_CHARS) { + label.truncate(end); + } + } + if label.capacity() > MAX_LABEL_CHARS * 4 { + label.shrink_to_fit(); + } } /// The shape of one `[[hubs.servers]]` table. @@ -255,10 +278,18 @@ impl SettingsSection for HubsSettings { /// Keeps the first server of each address, shortens labels and bounds the key lock. fn sanitize(&mut self) { self.key_lock_minutes = self.key_lock_minutes.min(MAX_KEY_LOCK_MINUTES); - let mut seen = HashSet::new(); - self.servers.retain(|record| seen.insert(record.id())); + let unique = { + let mut seen = HashSet::with_capacity(self.servers.len()); + self.servers + .iter() + .all(|record| seen.insert(&record.address)) + }; + if !unique { + let mut seen = HashSet::new(); + self.servers.retain(|record| seen.insert(record.id())); + } for record in &mut self.servers { - record.label = clean_label(&record.label); + sanitize_label(&mut record.label); } } } diff --git a/crates/hubs-model/src/settings/tests.rs b/crates/hubs-model/src/settings/tests.rs index 8e53fa3a..f41be6ea 100644 --- a/crates/hubs-model/src/settings/tests.rs +++ b/crates/hubs-model/src/settings/tests.rs @@ -245,3 +245,22 @@ fn the_hub_keys_stay_open_by_default_and_their_lock_is_bounded() { let read: HubsSettings = toml::from_str("key_lock_minutes = 30").unwrap(); assert_eq!(read.key_lock(), Some(std::time::Duration::from_secs(1800))); } + +#[test] +fn direct_settings_edit_sanitizes_unicode_labels_and_retains_first_duplicate() { + let mut first = pinned("first.example", ""); + first.label = format!(" \u{2003}\n{}末 emoji ", "界".repeat(64)); + let mut second = pinned("second.example", ""); + second.label = "\u{2003}\t \n".into(); + let mut settings = HubsSettings { + servers: vec![first, second, pinned("FIRST.example:7443", "duplicate")], + ..Default::default() + }; + settings.sanitize(); + assert_eq!(settings.servers.len(), 2); + assert_eq!(settings.servers[0].label, "界".repeat(64)); + assert!(settings.servers[1].label.is_empty()); + let expected = settings.clone(); + settings.sanitize(); + assert_eq!(settings, expected); +} diff --git a/crates/hubs/src/registry.rs b/crates/hubs/src/registry.rs index 913d0b5c..ee324d55 100644 --- a/crates/hubs/src/registry.rs +++ b/crates/hubs/src/registry.rs @@ -1,6 +1,6 @@ //! Every hub this device knows, with the connection status every window shares. -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; use gpui::{AppContext as _, Context, Entity, EventEmitter, Subscription, Task}; use nocterm_hubs_model::{ @@ -56,7 +56,7 @@ impl Hubs { pub(crate) fn new(deps: Deps, settings: SettingsHandle, cx: &mut Context) -> Self { settings.register::(cx); let weak = cx.weak_entity(); - let observed = settings.observe(cx, move |cx| { + let observed = settings.observe_section::(cx, move |cx| { weak.update(cx, |hubs, cx| hubs.sync(cx)).ok(); }); let keys = Self::redraw_on_key_changes(&deps, cx); @@ -119,13 +119,15 @@ impl Hubs { } fn entry(&self, hub: &HubId) -> Option<&HubEntry> { - self.entries.iter().find(|entry| entry.record.id() == *hub) + self.entries + .iter() + .find(|entry| &entry.record.address == hub.address()) } fn entry_mut(&mut self, hub: &HubId) -> Option<&mut HubEntry> { self.entries .iter_mut() - .find(|entry| entry.record.id() == *hub) + .find(|entry| &entry.record.address == hub.address()) } /// Brings the entries in line with the published settings: new servers start @@ -138,35 +140,54 @@ impl Hubs { { return; } - let records = records.clone(); - let mut previous = std::mem::take(&mut self.entries); let mut reconnect = Vec::new(); - for record in records { - let id = record.id(); - let kept = previous.iter().position(|entry| entry.record.id() == id); - let entry = match kept { - Some(index) => { - let mut entry = previous.remove(index); - if entry.record.trust != record.trust { - reconnect.push(id); - } - entry.record = record; - entry + if records.len() == self.entries.len() + && records + .iter() + .zip(&self.entries) + .all(|(record, entry)| record.address == entry.record.address) + { + // Metadata-only edits retain the existing status and attempt in place. + for (index, (record, entry)) in records.iter().zip(&mut self.entries).enumerate() { + if entry.record.trust != record.trust { + reconnect.push(index); } - None => { - reconnect.push(id); - HubEntry { - record, - status: HubStatus::Connecting, - failures: 0, - attempt: None, - } + if &entry.record != record { + entry.record = record.clone(); } - }; - self.entries.push(entry); + } + } else { + let mut previous: HashMap<_, _> = std::mem::take(&mut self.entries) + .into_iter() + .map(|entry| (entry.record.address.clone(), entry)) + .collect(); + self.entries.reserve(records.len()); + for (index, record) in records.iter().enumerate() { + let entry = match previous.remove(&record.address) { + Some(mut entry) => { + if entry.record.trust != record.trust { + reconnect.push(index); + } + if &entry.record != record { + entry.record = record.clone(); + } + entry + } + None => { + reconnect.push(index); + HubEntry { + record: record.clone(), + status: HubStatus::Connecting, + failures: 0, + attempt: None, + } + } + }; + self.entries.push(entry); + } } - for hub in reconnect { - self.connect(&hub, cx); + for index in reconnect { + self.connect_at(index, cx); } cx.emit(HubsEvent::Changed); cx.notify(); @@ -174,16 +195,24 @@ impl Hubs { /// Connects to a hub with the trust the settings state. fn connect(&mut self, hub: &HubId, cx: &mut Context) { - let Some(index) = self.entries.iter().position(|e| e.record.id() == *hub) else { + let Some(index) = self + .entries + .iter() + .position(|e| &e.record.address == hub.address()) + else { return; }; + self.connect_at(index, cx); + } + + fn connect_at(&mut self, index: usize, cx: &mut Context) { let entry = &mut self.entries[index]; entry.status = HubStatus::Connecting; let connecting = self.deps.sign_in.connect(HubEndpointSpec { address: entry.record.address.clone(), trust: entry.record.trust, }); - let hub = hub.clone(); + let hub = entry.record.id(); entry.attempt = Some(cx.spawn(async move |this, cx| { let result = connecting.await; this.update(cx, |hubs, cx| hubs.settled(&hub, result, cx)) diff --git a/crates/hubs/src/registry/tests.rs b/crates/hubs/src/registry/tests.rs index 5a26cd91..ec4c3ff9 100644 --- a/crates/hubs/src/registry/tests.rs +++ b/crates/hubs/src/registry/tests.rs @@ -349,3 +349,99 @@ async fn an_unrelated_settings_edit_does_not_publish_a_hub_change(cx: &mut TestA assert_eq!(fx.hub.count(FakeOp::Connect), 1); assert_eq!(fx.status(cx), Some(HubStatus::Online)); } + +#[gpui::test] +#[ignore = "manual release profiling of hub registry reconciliation"] +fn measure_hub_registry_publications(cx: &mut TestAppContext) { + use futures::FutureExt as _; + use nocterm_hubs_model::{HubsSettings, testing::FakeServer}; + use nocterm_session::LocalShellSettings; + use std::io::Write as _; + let count = std::env::var("NOCTERM_PROFILE_HUB_COUNT") + .map_or(Ok(128), |count| count.parse::()) + .unwrap(); + let mut hub = FakeHub::new(); + let mut records = Vec::new(); + for index in 0..count { + let address = format!("hub-{index}.example.test:7443"); + let server = FakeServer::new(&address, 7); + records.push(server.pinned_record("Original")); + hub = hub.with_server(server); + } + let fx = fixture(cx, hub, records); + cx.run_until_parked(); + assert_eq!(fx.hub.count(FakeOp::Connect), count); + for mode in ["unrelated", "label"] { + for sample in 0..7 { + let start = std::time::Instant::now(); + for step in 0..128 { + cx.update(|cx| { + let task = if mode == "unrelated" { + fx.settings.update::(cx, move |s| { + s.program = Some(if step % 2 == 0 { "bash" } else { "sh" }.into()); + }) + } else { + fx.settings.update::(cx, move |s| { + s.servers[0].label = + if step % 2 == 0 { "First" } else { "Second" }.into(); + }) + }; + task.now_or_never().unwrap().unwrap(); + }); + } + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} hubs={count} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); + } + } + assert_eq!(fx.hub.count(FakeOp::Connect), count); + assert_eq!(fx.hubs.read_with(cx, |hubs, _| hubs.list().len()), count); +} + +#[gpui::test] +async fn metadata_and_order_changes_keep_existing_connections_and_add_only_new_hubs( + cx: &mut TestAppContext, +) { + use nocterm_hubs_model::{HubId, HubsSettings, testing::FakeServer}; + let first = server(); + let second = FakeServer::new("other.example.test:7443", 7); + let third = FakeServer::new("new.example.test:7443", 7); + let records = [ + first.pinned_record("First"), + second.pinned_record("Second"), + third.pinned_record("Third"), + ]; + let hub = FakeHub::new() + .with_server(first) + .with_server(second) + .with_server(third); + hub.sign_in_as(&records[0].id(), "ada"); + let fx = fixture(cx, hub, records[..2].to_vec()); + cx.run_until_parked(); + assert_eq!(fx.hub.count(FakeOp::Connect), 2); + let first_id = records[0].id(); + let second_id = records[1].id(); + let third_id = records[2].id(); + let new_record = records[2].clone(); + cx.update(|cx| { + fx.settings.update::(cx, move |s| { + s.servers[0].label = "Renamed".into(); + s.servers.swap(0, 1); + s.servers.push(new_record); + }) + }) + .await + .unwrap(); + cx.run_until_parked(); + let rows = fx.hubs.read_with(cx, |hubs, _| hubs.list()); + assert_eq!( + rows.iter().map(|row| &row.id).collect::>(), + [&second_id, &first_id, &third_id] + ); + assert_eq!(rows[1].label, "Renamed"); + assert_eq!(rows[1].status, HubStatus::Online); + assert_eq!(fx.hub.count(FakeOp::Connect), 3); +} diff --git a/crates/image-codec/Cargo.toml b/crates/image-codec/Cargo.toml index 9e18cd58..46552afd 100644 --- a/crates/image-codec/Cargo.toml +++ b/crates/image-codec/Cargo.toml @@ -10,5 +10,6 @@ layer = "adapter" [dependencies] nocterm-ai.workspace = true image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp"] } +png = "0.18" [lints] workspace = true diff --git a/crates/image-codec/src/lib.rs b/crates/image-codec/src/lib.rs index e9c89bdc..41c8528a 100644 --- a/crates/image-codec/src/lib.rs +++ b/crates/image-codec/src/lib.rs @@ -1,25 +1,39 @@ -//! Bounded native image decoding and PNG previews over AI's pure contracts. +//! Bounded native image decoding and thumbnails over AI's pure contracts. //! -//! Owns: PNG/JPEG/GIF/WebP decoder limits, physical validation and preview encoding. +//! Owns: PNG/JPEG/GIF/WebP decoder limits, physical validation and thumbnail generation. //! Does not own: workers, filesystem access, prompt admission or UI/cache lifecycle. //! Ports provided: ImageInspector and ImageThumbnailer; ports used: none. //! Settings section: none. Globals: none. //! Invariants: source preflight precedes allocation; decode is capped at 4096 and -//! 64 MiB; PNG previews stay within requested dimensions, 640 pixels and 4 MiB. +//! 64 MiB; previews stay within requested dimensions and 640 pixels per axis. use image::{GenericImageView as _, ImageEncoder as _}; use nocterm_ai::images::{ - self, EncodedPreview, ImageCodecError, ImageFacts, ImageInspector, ImageThumbnailer, - InspectedImage, PreviewBounds, + self, DecodedPreviewSource, EncodedPreview, ImageCodecError, ImageFacts, ImageInspector, + ImageThumbnailer, InspectedImage, PreviewBounds, PreviewImage, PreviewPixels, }; use std::{ io::{Cursor, Write}, sync::Arc, }; + +mod png_preview; +mod png_rows; + #[derive(Clone, Copy, Default)] pub struct NativeImageCodec; impl NativeImageCodec { - fn decode(bytes: &[u8]) -> Result<(image::DynamicImage, ImageFacts), ImageCodecError> { + fn preview(bytes: &[u8], bounds: PreviewBounds) -> Result { let facts = images::preflight(bytes)?; + if let Some(pixels) = png_preview::try_resize(bytes, facts, bounds)? { + return Ok(pixels); + } + Ok(resize(Self::decode_frame(bytes, facts)?, bounds)) + } + + fn decode_frame( + bytes: &[u8], + facts: ImageFacts, + ) -> Result { let mut reader = image::ImageReader::new(Cursor::new(bytes)) .with_guessed_format() .map_err(|source| ImageCodecError::InvalidHeader { @@ -39,28 +53,69 @@ impl NativeImageCodec { limits.max_image_height = Some(images::MAX_DECODE_DIMENSION); limits.max_alloc = Some(images::MAX_DECODE_BYTES); reader.limits(limits); - let decoded = reader.decode().map_err(|source| { - if matches!(source, image::ImageError::Limits(_)) { - ImageCodecError::AllocationLimit { - source: images::ImageCodecCause::new(source), - } - } else { - ImageCodecError::InvalidData { - source: images::ImageCodecCause::new(source), - } - } - })?; + let decoded = reader.decode().map_err(decode_error)?; if decoded.dimensions() != (facts.width(), facts.height()) { return Err(ImageCodecError::InvalidEvidence); } - Ok((decoded, facts)) + Ok(decoded) } } + +fn decode_error(source: image::ImageError) -> ImageCodecError { + let at_limit = matches!(source, image::ImageError::Limits(_)); + let source = images::ImageCodecCause::new(source); + if at_limit { + ImageCodecError::AllocationLimit { source } + } else { + ImageCodecError::InvalidData { source } + } +} + impl ImageInspector for NativeImageCodec { fn inspect(&self, bytes: Arc<[u8]>) -> Result { - let (_, facts) = Self::decode(&bytes)?; + let facts = images::preflight(&bytes)?; + if png_rows::supports_rows(&bytes, facts) { + png_rows::validate(&bytes, facts)?; + } else { + Self::decode_frame(&bytes, facts)?; + } InspectedImage::new(bytes, facts) } + fn inspect_for_preview( + &self, + bytes: Arc<[u8]>, + ) -> Result<(InspectedImage, Option>), ImageCodecError> { + let facts = images::preflight(&bytes)?; + if png_rows::minimum_frame_bytes(&bytes, facts) + .is_some_and(|size| size > images::MAX_PREVIEW_BYTES) + { + let mut reader = png_rows::open(&bytes, facts)?; + if png_rows::matches_canvas(&reader) { + // Large PNG previews can shrink decoder rows under their own permit. + png_rows::finish(&mut reader)?; + return InspectedImage::new(bytes, facts).map(|original| (original, None)); + } + } + let decoded = Self::decode_frame(&bytes, facts)?; + let original = InspectedImage::new(bytes, facts)?; + Ok((original, Some(Box::new(DecodedImage(decoded))))) + } +} +struct DecodedImage(image::DynamicImage); +impl DecodedPreviewSource for DecodedImage { + fn thumbnail( + self: Box, + bounds: PreviewBounds, + ) -> Result { + encode_preview(resize(self.0, bounds), bounds) + } + + fn render_preview( + self: Box, + bounds: PreviewBounds, + ) -> Result { + pixel_preview(resize(self.0, bounds), bounds) + } } impl ImageThumbnailer for NativeImageCodec { fn thumbnail( @@ -68,23 +123,50 @@ impl ImageThumbnailer for NativeImageCodec { bytes: Arc<[u8]>, bounds: PreviewBounds, ) -> Result { - let (image, _) = Self::decode(&bytes)?; - let thumbnail = image.thumbnail(bounds.width(), bounds.height()).to_rgba8(); - let mut sink = PreviewSink::default(); - let result = image::codecs::png::PngEncoder::new(&mut sink).write_image( - thumbnail.as_raw(), - thumbnail.width(), - thumbnail.height(), - image::ExtendedColorType::Rgba8, - ); - if sink.exceeded { - return Err(ImageCodecError::PreviewOutputLimit); - } - result.map_err(|source| ImageCodecError::Encode { - source: images::ImageCodecCause::new(source), - })?; - EncodedPreview::new(sink.bytes.into(), bounds) + encode_preview(Self::preview(&bytes, bounds)?, bounds) + } + + fn render_preview( + &self, + bytes: Arc<[u8]>, + bounds: PreviewBounds, + ) -> Result { + pixel_preview(Self::preview(&bytes, bounds)?, bounds) + } +} + +fn resize(image: image::DynamicImage, bounds: PreviewBounds) -> image::RgbaImage { + image + .thumbnail(bounds.width(), bounds.height()) + .into_rgba8() +} + +fn pixel_preview( + pixels: image::RgbaImage, + bounds: PreviewBounds, +) -> Result { + PreviewPixels::new(pixels.width(), pixels.height(), pixels.into_raw(), bounds) + .map(PreviewImage::Pixels) +} + +fn encode_preview( + thumbnail: image::RgbaImage, + bounds: PreviewBounds, +) -> Result { + let mut sink = PreviewSink::default(); + let result = image::codecs::png::PngEncoder::new(&mut sink).write_image( + thumbnail.as_raw(), + thumbnail.width(), + thumbnail.height(), + image::ExtendedColorType::Rgba8, + ); + if sink.exceeded { + return Err(ImageCodecError::PreviewOutputLimit); } + result.map_err(|source| ImageCodecError::Encode { + source: images::ImageCodecCause::new(source), + })?; + EncodedPreview::new(sink.bytes.into(), bounds) } #[derive(Default)] struct PreviewSink { diff --git a/crates/image-codec/src/png_preview.rs b/crates/image-codec/src/png_preview.rs new file mode 100644 index 00000000..2b29d899 --- /dev/null +++ b/crates/image-codec/src/png_preview.rs @@ -0,0 +1,124 @@ +//! Shrink PNG rows directly into bounded RGBA display pixels. + +use super::png_rows; +use image::RgbaImage; +use nocterm_ai::images::{ImageCodecError, ImageFacts, PreviewBounds}; +use std::{io::Cursor, ops::Range}; + +pub(super) fn try_resize( + bytes: &[u8], + facts: ImageFacts, + bounds: PreviewBounds, +) -> Result, ImageCodecError> { + if !png_rows::supports_rows(bytes, facts) + || (facts.width() <= bounds.width() && facts.height() <= bounds.height()) + { + return Ok(None); + } + + let mut reader = png_rows::open(bytes, facts)?; + if !png_rows::matches_canvas(&reader) { + return Ok(None); + } + + let size = fitted_size(facts, bounds); + let pixels = match reader.output_color_type() { + (png::ColorType::Rgb, png::BitDepth::Eight) => shrink::<3>(&mut reader, facts, size)?, + (png::ColorType::Rgba, png::BitDepth::Eight) => shrink::<4>(&mut reader, facts, size)?, + _ => return Ok(None), + }; + RgbaImage::from_raw(size.0, size.1, pixels) + .map(Some) + .ok_or(ImageCodecError::InvalidEvidence) +} + +fn fitted_size(facts: ImageFacts, bounds: PreviewBounds) -> (u32, u32) { + // Match image::DynamicImage::thumbnail's aspect fit and rounding. + let width = f64::from(facts.width()); + let height = f64::from(facts.height()); + let scale = (f64::from(bounds.width()) / width).min(f64::from(bounds.height()) / height); + ( + ((width * scale).round() as u32).max(1), + ((height * scale).round() as u32).max(1), + ) +} + +fn windows(source: u32, destination: u32) -> impl Iterator> { + // Match image::imageops::thumbnail's downscaling window edges. + let ratio = source as f32 / destination as f32; + (0..destination).map(move |index| { + let edge = index as f32 * ratio; + let start = (edge.ceil() as u32).min(source - 1); + let end = ((edge + ratio).ceil() as u32).min(source); + start as usize..end as usize + }) +} + +fn shrink( + reader: &mut png::Reader>, + facts: ImageFacts, + (width, height): (u32, u32), +) -> Result, ImageCodecError> { + let columns = windows(facts.width(), width).collect::>(); + let mut previous = vec![[0u32; CHANNELS]; columns.len()]; + let mut totals = vec![[0u32; CHANNELS]; columns.len()]; + let mut pixels = Vec::with_capacity(width as usize * height as usize * 4); + let mut read = 0; + for band in windows(facts.height(), height) { + if band.start < read { + // Rounded adjacent boundaries can overlap by one row. + totals.copy_from_slice(&previous); + } else { + totals.fill([0; CHANNELS]); + } + while read < band.end { + let row = reader + .next_row() + .map_err(png_rows::png_error)? + .ok_or(ImageCodecError::InvalidEvidence)?; + if row.data().len() != facts.width() as usize * CHANNELS { + return Err(ImageCodecError::InvalidEvidence); + } + if read >= band.start { + accumulate( + row.data().as_chunks::().0, + &columns, + &mut previous, + &mut totals, + ); + } + read += 1; + } + for (columns, sum) in columns.iter().zip(&totals) { + // The input pixel limit keeps even a single full-size sum in u32. + let area = (columns.len() * band.len()) as u32; + let mut pixel = [255; 4]; + for (dst, value) in pixel.iter_mut().zip(sum) { + *dst = ((value + area / 2) / area) as u8; + } + pixels.extend_from_slice(&pixel); + } + } + png_rows::finish(reader)?; + Ok(pixels) +} + +fn accumulate( + row: &[[u8; CHANNELS]], + columns: &[Range], + previous: &mut [[u32; CHANNELS]], + totals: &mut [[u32; CHANNELS]], +) { + for ((columns, last), total) in columns.iter().zip(previous).zip(totals) { + let mut sum = [0; CHANNELS]; + for pixel in &row[columns.clone()] { + for (channel, sample) in sum.iter_mut().zip(pixel) { + *channel += u32::from(*sample); + } + } + *last = sum; + for (channel, value) in total.iter_mut().zip(sum) { + *channel += value; + } + } +} diff --git a/crates/image-codec/src/png_rows.rs b/crates/image-codec/src/png_rows.rs new file mode 100644 index 00000000..63d667c7 --- /dev/null +++ b/crates/image-codec/src/png_rows.rs @@ -0,0 +1,76 @@ +//! Bounded decoding of ordinary RGB/RGBA PNGs into reusable row storage. + +use nocterm_ai::images::{ImageCodecError, ImageFacts, ImageFormat, MAX_DECODE_BYTES}; +use std::io::Cursor; + +pub(super) fn supports_rows(bytes: &[u8], facts: ImageFacts) -> bool { + // IHDR fields: bit depth, color type, compression, filter and interlace. + facts.format() == ImageFormat::Png && matches!(bytes.get(24..29), Some([8, 2 | 6, 0, 0, 0])) +} + +pub(super) fn minimum_frame_bytes(bytes: &[u8], facts: ImageFacts) -> Option { + supports_rows(bytes, facts).then(|| { + let channels = if bytes[25] == 6 { 4 } else { 3 }; + facts.width() as usize * facts.height() as usize * channels + }) +} + +pub(super) fn matches_canvas(reader: &png::Reader>) -> bool { + let info = reader.info(); + info.frame_control + .is_none_or(|frame| (frame.width, frame.height) == info.size()) +} + +pub(super) fn validate(bytes: &[u8], facts: ImageFacts) -> Result<(), ImageCodecError> { + finish(&mut open(bytes, facts)?) +} + +pub(super) fn open( + bytes: &[u8], + facts: ImageFacts, +) -> Result>, ImageCodecError> { + let bytes_limit = MAX_DECODE_BYTES as usize; + let mut decoder = + png::Decoder::new_with_limits(Cursor::new(bytes), png::Limits { bytes: bytes_limit }); + // Match the native image PNG decoder's chunk checks and output transform. + decoder.set_ignore_text_chunk(false); + let header = decoder.read_header_info().map_err(png_error)?; + if (header.width, header.height) != (facts.width(), facts.height()) { + return Err(ImageCodecError::InvalidEvidence); + } + decoder.set_transformations(png::Transformations::EXPAND); + let reader = decoder.read_info().map_err(png_error)?; + if !reader + .output_buffer_size() + .is_some_and(|size| size <= bytes_limit) + { + return Err(png_error(png::DecodingError::LimitsExceeded)); + } + Ok(reader) +} + +pub(super) fn finish(reader: &mut png::Reader>) -> Result<(), ImageCodecError> { + // Read through the end of the first frame's data, including its final checksum. + while reader.next_row().map_err(png_error)?.is_some() {} + Ok(()) +} + +pub(super) fn png_error(error: png::DecodingError) -> ImageCodecError { + use image::error::{ + DecodingError, LimitError, LimitErrorKind, ParameterError, ParameterErrorKind, + }; + + let source = match error { + png::DecodingError::IoError(error) => image::ImageError::IoError(error), + png::DecodingError::Format(_) => { + image::ImageError::Decoding(DecodingError::new(image::ImageFormat::Png.into(), error)) + } + png::DecodingError::Parameter(_) => image::ImageError::Parameter( + ParameterError::from_kind(ParameterErrorKind::Generic(error.to_string())), + ), + png::DecodingError::LimitsExceeded => { + image::ImageError::Limits(LimitError::from_kind(LimitErrorKind::InsufficientMemory)) + } + }; + super::decode_error(source) +} diff --git a/crates/image-codec/src/tests.rs b/crates/image-codec/src/tests.rs index 07dbe744..e9a09e49 100644 --- a/crates/image-codec/src/tests.rs +++ b/crates/image-codec/src/tests.rs @@ -24,6 +24,35 @@ fn every_supported_format_is_fully_decoded_and_preserves_prompt_payload() { assert_eq!(image.bytes(), bytes); assert_eq!(image.mime_type(), expected.mime()); assert_eq!(image.dimensions(), (2, 2)); + let bounds = PreviewBounds::new(24, 24).unwrap(); + let (prepared, decoded) = + PromptImage::validate_for_preview(bytes.clone(), &NativeImageCodec).unwrap(); + assert_eq!(prepared.bytes(), bytes); + assert_eq!(prepared.encoded_data(), image.encoded_data()); + let reused = decoded.unwrap().thumbnail(bounds).unwrap(); + let separate = NativeImageCodec + .thumbnail(image.shared_bytes(), bounds) + .unwrap(); + assert_eq!(reused.bytes(), separate.bytes()); + let expected = image::load_from_memory(separate.bytes()) + .unwrap() + .into_rgba8(); + let (_, decoded) = NativeImageCodec + .inspect_for_preview(image.shared_bytes()) + .unwrap(); + let PreviewImage::Pixels(reused) = decoded.unwrap().render_preview(bounds).unwrap() else { + panic!("the native inspection source returns pixels for display"); + }; + let PreviewImage::Pixels(direct) = NativeImageCodec + .render_preview(image.shared_bytes(), bounds) + .unwrap() + else { + panic!("the native decoder returns pixels for display"); + }; + assert_eq!(reused.dimensions(), expected.dimensions()); + assert_eq!(direct.dimensions(), expected.dimensions()); + assert_eq!(reused.into_rgba(), *expected.as_raw()); + assert_eq!(direct.into_rgba(), expected.into_raw()); } } #[test] @@ -31,6 +60,12 @@ fn corrupt_data_header_bombs_and_source_limits_preserve_typed_refusals() { use std::error::Error as _; let mut bytes = encoded(image::ImageFormat::Png, 2, 2); bytes.truncate(33); + assert!(matches!( + PromptImage::validate_for_preview(bytes.clone(), &NativeImageCodec), + Err(PromptImageError::Decode( + ImageCodecError::InvalidData { .. } + )) + )); let error = PromptImage::validate(bytes, &NativeImageCodec).unwrap_err(); assert!(matches!(error, PromptImageError::Decode(_))); assert!(error.source().is_some()); @@ -60,14 +95,103 @@ fn bounded_preview_downsizes_with_aspect_and_preserves_alpha() { .write_to(&mut source, image::ImageFormat::Png) .unwrap(); let bounds = PreviewBounds::new(640, 640).unwrap(); - let preview = NativeImageCodec - .thumbnail(source.into_inner().into(), bounds) - .unwrap(); + let source: Arc<[u8]> = source.into_inner().into(); + let preview = NativeImageCodec.thumbnail(source.clone(), bounds).unwrap(); assert_eq!(preview.dimensions(), (640, 320)); assert!(preview.bytes().len() <= images::MAX_PREVIEW_BYTES); let decoded = image::load_from_memory(preview.bytes()).unwrap().to_rgba8(); assert_eq!(decoded.get_pixel(100, 100).0[3], 77); + let PreviewImage::Pixels(raw) = NativeImageCodec.render_preview(source, bounds).unwrap() else { + panic!("the native decoder returns pixels for display"); + }; + assert_eq!(raw.dimensions(), (640, 320)); + assert_eq!(raw.into_rgba(), decoded.into_raw()); +} + +#[test] +#[ignore = "manual release benchmark"] +fn measure_native_image_validation_and_preview() { + use std::time::Instant; + + let codec = NativeImageCodec; + let bounds = PreviewBounds::new(640, 640).unwrap(); + for (width, height, preview_size) in [ + (320, 180, (640, 360)), + (1920, 1080, (640, 360)), + (3840, 2160, (640, 360)), + (4096, 4096, (640, 640)), + ] { + let source = image::RgbaImage::from_fn(width, height, |x, y| { + image::Rgba([(x % 256) as u8, (y % 256) as u8, 71, 77]) + }); + let mut encoded = Cursor::new(Vec::new()); + source + .write_to(&mut encoded, image::ImageFormat::Png) + .unwrap(); + drop(source); + let encoded = encoded.into_inner(); + let preview_source: Arc<[u8]> = encoded.clone().into(); + let mut validation_times = Vec::with_capacity(9); + let mut preview_times = Vec::with_capacity(9); + let mut reused_times = Vec::with_capacity(9); + let mut render_times = Vec::with_capacity(9); + for _ in 0..9 { + let input = encoded.clone(); + let start = Instant::now(); + let checked = PromptImage::validate(input, &codec).unwrap(); + validation_times.push(start.elapsed()); + assert_eq!(checked.dimensions(), (width, height)); + assert_eq!(checked.bytes(), encoded); + drop(checked); + + let input = Arc::clone(&preview_source); + let start = Instant::now(); + let preview = codec.thumbnail(input, bounds).unwrap(); + preview_times.push(start.elapsed()); + assert_eq!(preview.dimensions(), preview_size); + let decoded = image::load_from_memory(preview.bytes()) + .unwrap() + .into_rgba8(); + assert_eq!(decoded.get_pixel(100, 100).0[3], 77); + + let input = Arc::clone(&preview_source); + let start = Instant::now(); + let PreviewImage::Pixels(display) = codec.render_preview(input, bounds).unwrap() else { + panic!("the native decoder returns pixels for display"); + }; + render_times.push(start.elapsed()); + assert_eq!(display.dimensions(), preview.dimensions()); + assert_eq!(display.into_rgba(), decoded.into_raw()); + + let input = encoded.clone(); + let start = Instant::now(); + let (original, decoded) = PromptImage::validate_for_preview(input, &codec).unwrap(); + let prepared = match decoded { + Some(decoded) => decoded.thumbnail(bounds), + None => codec.thumbnail(original.shared_bytes(), bounds), + } + .unwrap(); + reused_times.push(start.elapsed()); + assert_eq!(original.bytes(), encoded); + assert_eq!(prepared.bytes(), preview.bytes()); + } + validation_times.sort_unstable(); + preview_times.sort_unstable(); + reused_times.sort_unstable(); + render_times.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{width}x{height} RGBA PNG ({} bytes), validation {:?}, PNG preview {:?}, inspection and PNG preview {:?}, pixel preview {:?}", + encoded.len(), + validation_times[4], + preview_times[4], + reused_times[4], + render_times[4], + ) + .unwrap(); + } } + #[test] fn png_sink_refuses_the_first_byte_over_its_limit() { let mut sink = PreviewSink::default(); @@ -77,6 +201,134 @@ fn png_sink_refuses_the_first_byte_over_its_limit() { std::io::ErrorKind::FileTooLarge ); } +#[test] +fn png_validation_rejects_a_bad_checksum_after_the_final_pixel_rows() { + let mut bytes = encoded(image::ImageFormat::Png, 1536, 1024); + let mut chunk = 8; + let mut last_data_crc = None; + while chunk < bytes.len() { + let length = u32::from_be_bytes(bytes[chunk..chunk + 4].try_into().unwrap()) as usize; + let crc = chunk + 8 + length; + if &bytes[chunk + 4..chunk + 8] == b"IDAT" { + last_data_crc = Some(crc); + } + chunk = crc + 4; + } + bytes[last_data_crc.unwrap()] ^= 1; + let bytes: Arc<[u8]> = bytes.into(); + assert!(matches!( + NativeImageCodec.inspect(Arc::clone(&bytes)), + Err(ImageCodecError::InvalidData { .. }) + )); + assert!(matches!( + NativeImageCodec.inspect_for_preview(Arc::clone(&bytes)), + Err(ImageCodecError::InvalidData { .. }) + )); + let bounds = PreviewBounds::new(640, 640).unwrap(); + assert!(matches!( + NativeImageCodec.thumbnail(Arc::clone(&bytes), bounds), + Err(ImageCodecError::InvalidData { .. }) + )); + assert!(matches!( + NativeImageCodec.render_preview(bytes, bounds), + Err(ImageCodecError::InvalidData { .. }) + )); +} + +#[test] +fn png_preview_pixels_match_reference_across_fractional_and_asymmetric_bounds() { + let pattern = |x: u32, y: u32| { + [ + (x ^ (y * 17)) as u8, + (x * 3 + y * 11) as u8, + (x * y) as u8, + ((x + y) * 29) as u8, + ] + }; + for (width, height) in [(253, 839), (839, 253), (1024, 1)] { + let rgba = image::RgbaImage::from_fn(width, height, |x, y| image::Rgba(pattern(x, y))); + for raster in [ + image::DynamicImage::from(rgba.clone()).into_rgb8().into(), + rgba.into(), + ] { + let mut output = Cursor::new(Vec::new()); + image::DynamicImage::write_to(&raster, &mut output, image::ImageFormat::Png).unwrap(); + let source: Arc<[u8]> = output.into_inner().into(); + for (bound_width, bound_height) in [(1, 1), (255, 511), (640, 640), (608, 107)] { + let bounds = PreviewBounds::new(bound_width, bound_height).unwrap(); + let expected = raster.thumbnail(bound_width, bound_height).into_rgba8(); + let native = NativeImageCodec + .render_preview(Arc::clone(&source), bounds) + .unwrap(); + let PreviewImage::Pixels(native) = native else { + panic!("expected display pixels"); + }; + assert_eq!(native.dimensions(), expected.dimensions()); + assert_eq!(&native.into_rgba(), expected.as_raw()); + let encoded = NativeImageCodec + .thumbnail(Arc::clone(&source), bounds) + .unwrap(); + let round_trip = image::load_from_memory(encoded.bytes()) + .unwrap() + .into_rgba8(); + assert_eq!(round_trip, expected); + } + } + } +} + +#[test] +fn large_rgb_pngs_validate_for_attachment_without_retaining_a_full_frame() { + let codec = NativeImageCodec; + for (width, height) in [(1920, 800), (800, 1920)] { + let bytes = encoded(image::ImageFormat::Png, width, height); + let image = image::load_from_memory(&bytes).unwrap(); + let source: Arc<[u8]> = bytes.into(); + let (original, retained) = codec.inspect_for_preview(Arc::clone(&source)).unwrap(); + assert!(Arc::ptr_eq(original.bytes(), &source)); + assert_eq!( + (original.facts().width(), original.facts().height()), + (width, height) + ); + assert!(retained.is_none()); + + let bounds = PreviewBounds::new(503, 417).unwrap(); + let expected = image + .thumbnail(bounds.width(), bounds.height()) + .into_rgba8(); + let PreviewImage::Pixels(pixels) = codec.render_preview(source, bounds).unwrap() else { + panic!("expected display pixels"); + }; + assert_eq!(pixels.dimensions(), expected.dimensions()); + assert_eq!(&pixels.into_rgba(), expected.as_raw()); + } +} + +#[test] +fn large_rgba_png_inspection_keeps_the_original_and_matches_preview_inspection() { + let mut output = Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 257, + 511, + image::Rgba([41, 79, 111, 53]), + )) + .write_to(&mut output, image::ImageFormat::Png) + .unwrap(); + let source: Arc<[u8]> = output.into_inner().into(); + let inspected = NativeImageCodec.inspect(Arc::clone(&source)).unwrap(); + let (preview_inspected, decoded) = NativeImageCodec + .inspect_for_preview(Arc::clone(&source)) + .unwrap(); + assert!(decoded.is_some()); + assert_eq!(inspected.facts(), preview_inspected.facts()); + assert_eq!( + (inspected.facts().width(), inspected.facts().height()), + (257, 511) + ); + assert!(Arc::ptr_eq(inspected.bytes(), &source)); + assert!(Arc::ptr_eq(preview_inspected.bytes(), &source)); +} + #[test] fn header_dimension_corruption_never_becomes_trusted_evidence() { let mut bytes = encoded(image::ImageFormat::Png, 2, 2); diff --git a/crates/keymap-ui/src/lib.rs b/crates/keymap-ui/src/lib.rs index 99cbe277..3ec3ce9f 100644 --- a/crates/keymap-ui/src/lib.rs +++ b/crates/keymap-ui/src/lib.rs @@ -10,6 +10,7 @@ //! Ports used: `KeymapHandle`; provided: UI `SettingsPageSpec`. //! Settings section: none (bindings use the keymap file). Globals: none. //! Invariants: edits go through the keymap owner; the page does not rewrite other bindings. +mod listing; mod rows; mod view; @@ -24,6 +25,7 @@ pub fn settings_page(keymap: nocterm_keymap::KeymapHandle) -> SettingsPageSpec { cx.new(|cx| KeymapView::new(keymap.clone(), window, cx)) }) .with_icon(nocterm_ui::IconName::Keyboard) + .with_viewport() } #[cfg(test)] diff --git a/crates/keymap-ui/src/listing.rs b/crates/keymap-ui/src/listing.rs new file mode 100644 index 00000000..86bab2d6 --- /dev/null +++ b/crates/keymap-ui/src/listing.rs @@ -0,0 +1,79 @@ +//! The page retains one binding revision and the row indices for its current query. +use gpui_kit::{App, ListAlignment, ListState, SharedString, component::input::InputState, px}; +use nocterm_keymap::KeymapHandle; + +use crate::rows::{Query, Row, SearchTerms, rows}; + +pub(super) struct Listing { + rows: Vec<(Row, SearchTerms)>, + matches: Vec, + revision: Option, + query: SharedString, + scroll: ListState, +} + +impl Default for Listing { + fn default() -> Self { + Self { + rows: Vec::new(), + matches: Vec::new(), + revision: None, + query: SharedString::default(), + scroll: ListState::new(0, ListAlignment::Top, px(96.)), + } + } +} + +impl Listing { + pub(super) fn prepare(&mut self, keymap: &KeymapHandle, input: &InputState, cx: &App) { + // Local edits may render before the deferred keymap observation. + let revision = keymap.revision(cx); + let revision_changed = self.revision != Some(revision); + if revision_changed { + self.rows = rows(keymap, cx) + .into_iter() + .map(|row| { + let terms = SearchTerms::new(&row); + (row, terms) + }) + .collect(); + self.revision = Some(revision); + } + let query_changed = input.text() != self.query.as_ref(); + if !revision_changed && !query_changed { + return; + } + + if query_changed { + self.query = input.value(); + } + let matcher = Query::new(&self.query); + let matches = self + .rows + .iter() + .enumerate() + .filter_map(|(index, (_, terms))| matcher.matches(terms).then_some(index)) + .collect::>(); + if revision_changed || matches != self.matches { + let offset = self.scroll.logical_scroll_top(); + self.scroll + .reset_with_uniform_height(matches.len(), px(52.)); + if !query_changed { + self.scroll.scroll_to(offset); + } + self.matches = matches; + } + } + + pub(super) fn scroll(&self) -> ListState { + self.scroll.clone() + } + + pub(super) fn row(&self, index: usize) -> &Row { + &self.rows[self.matches[index]].0 + } + + pub(super) fn is_empty(&self) -> bool { + self.matches.is_empty() + } +} diff --git a/crates/keymap-ui/src/render.rs b/crates/keymap-ui/src/render.rs index d9b6ce21..54d1b7f0 100644 --- a/crates/keymap-ui/src/render.rs +++ b/crates/keymap-ui/src/render.rs @@ -9,7 +9,7 @@ use gpui_kit::{ kbd::Kbd, v_flex, }, - div, + div, list, prelude::*, px, rems, }; @@ -17,7 +17,7 @@ use nocterm_keymap::Source; use nocterm_ui::{IconName, form}; use crate::{ - rows::{Query, Row}, + rows::Row, view::{KeymapView, Recording}, }; @@ -88,7 +88,7 @@ impl KeymapView { } #[expect(clippy::too_many_lines, reason = "predates the limit")] - fn row(&self, index: usize, row: Row, cx: &mut Context) -> AnyElement { + fn row(&self, index: usize, row: &Row, cx: &mut Context) -> AnyElement { let theme = cx.theme(); let (muted, border, accent) = ( theme.muted_foreground, @@ -230,38 +230,46 @@ impl KeymapView { impl Render for KeymapView { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - // Local actions may render before deferred owner observations are delivered. - // Read the semantic key here; unchanged frames still reuse all prepared rows. - let revision = self.keymap.revision(cx); - if revision != self.rows_revision { - self.rows = std::rc::Rc::new(crate::rows::rows(&self.keymap, cx)); - self.rows_revision = revision; - } - let query = Query::new(&self.search.read(cx).value()); - let listed: Vec = self - .rows - .iter() - .filter(|row| query.matches(row)) - .cloned() - .collect(); - let count = listed.len(); + self.listing.prepare(&self.keymap, self.search.read(cx), cx); let file_error = self .keymap .error(cx) .map(ToString::to_string) .or_else(|| self.keymap.publication_error(cx).map(ToString::to_string)); - let mut table = v_flex().id("keymap-table").test_support().w_full(); - table = table.child(Self::column_titles(cx)); - for (index, row) in listed.into_iter().enumerate() { - table = table.child(self.row(index, row, cx)); - } - if count == 0 { - table = table.child(form::note("No command matches.", cx)); - } + let table = v_flex() + .id("keymap-table") + .test_support() + .w_full() + .flex_1() + .min_h_0() + .child(Self::column_titles(cx)) + .when_else( + self.listing.is_empty(), + |table| table.child(form::note("No command matches.", cx)), + |table| { + table.child( + div() + .id("keymap-results") + .test_support() + .flex_1() + .min_h_0() + .child( + list( + self.listing.scroll(), + cx.processor(|this, index, _, cx| { + this.row(index, this.listing.row(index), cx) + }), + ) + .size_full(), + ), + ) + }, + ); v_flex() .id("keymap-page") .test_support() - .w_full() + .size_full() + .min_h_0() .gap_3() .track_focus(&self.focus_handle(cx)) .child(form::page_header( diff --git a/crates/keymap-ui/src/rows.rs b/crates/keymap-ui/src/rows.rs index 313f3204..da949d79 100644 --- a/crates/keymap-ui/src/rows.rs +++ b/crates/keymap-ui/src/rows.rs @@ -76,10 +76,34 @@ pub(crate) fn rows(keymap: &KeymapHandle, cx: &App) -> Vec { rows } -/// Whether `row` matches `query`: every word of it appears in the command's -/// name, description, shortcut or context, ignoring case. A query that reads -/// as a shortcut (`ctrl-shift-p`, `shift-ctrl-p`) also matches the shortcut -/// however its modifiers are ordered. +/// Search data prepared once per authoritative binding revision. +pub(crate) struct SearchTerms { + text: String, + keys: Option, +} + +impl SearchTerms { + pub(crate) fn new(row: &Row) -> Self { + let text = format!( + "{} {} {} {} {}", + row.label, + row.action, + row.description, + row.keystrokes.as_deref().unwrap_or("unbound"), + row.context.as_deref().unwrap_or_default(), + ) + .to_lowercase(); + let keys = row + .keystrokes + .as_deref() + .and_then(|keys| normalize(keys).ok()) + .map(|keys| keys.to_lowercase()); + Self { text, keys } + } +} + +/// All query words must appear somewhere in the row. A normalized shortcut +/// also matches regardless of the order of its modifiers. pub(crate) struct Query { text: String, keys: Option, @@ -94,27 +118,14 @@ impl Query { .map(|keys| keys.to_lowercase()); Self { text, keys } } - pub(crate) fn matches(&self, row: &Row) -> bool { - if self.text.is_empty() { - return true; - } - if let (Some(wanted), Some(keys)) = (&self.keys, &row.keystrokes) - && normalize(keys).is_ok_and(|keys| keys.to_lowercase() == *wanted) - { - return true; - } - let haystack = format!( - "{} {} {} {} {}", - row.label, - row.action, - row.description, - row.keystrokes.as_deref().unwrap_or("unbound"), - row.context.as_deref().unwrap_or_default(), - ) - .to_lowercase(); - self.text - .split_whitespace() - .all(|word| haystack.contains(word)) + pub(crate) fn matches(&self, row: &SearchTerms) -> bool { + self.keys + .as_ref() + .is_some_and(|keys| row.keys.as_ref() == Some(keys)) + || self + .text + .split_whitespace() + .all(|word| row.text.contains(word)) } } @@ -122,7 +133,7 @@ impl Query { mod tests { use super::*; fn matches(row: &Row, query: &str) -> bool { - Query::new(query).matches(row) + Query::new(query).matches(&SearchTerms::new(row)) } fn row(keys: Option<&str>) -> Row { diff --git a/crates/keymap-ui/src/tests.rs b/crates/keymap-ui/src/tests.rs index 7847f230..f2e81a9e 100644 --- a/crates/keymap-ui/src/tests.rs +++ b/crates/keymap-ui/src/tests.rs @@ -24,6 +24,13 @@ context = "Workspace" "#; fn setup(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity, KeymapHandle) { + setup_with_defaults(DEFAULTS, cx) +} + +fn setup_with_defaults( + defaults: &str, + cx: &mut TestAppContext, +) -> (gpui_kit::AnyWindowHandle, Entity, KeymapHandle) { cx.update(|cx| { gpui_kit::init(cx); nocterm_ui::init( @@ -31,7 +38,7 @@ fn setup(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity String { + use std::fmt::Write as _; + + let mut defaults = DEFAULTS.to_owned(); + for first in 'a'..='j' { + for last in 'a'..='z' { + writeln!( + defaults, + "\"ctrl-alt-f11 {first} {last}\" = \"workspace::ToggleSidebar\"" + ) + .unwrap(); + } + } + defaults +} + +#[gpui_kit::test] +fn scrolling_leaves_search_reachable_and_a_filtered_shortcut_can_be_rebound( + cx: &mut TestAppContext, +) { + use gpui_kit::{ScrollDelta, point, px}; + + let (handle, _, keymap) = setup_with_defaults(&expanded_keymap(), cx); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + let search_bounds = window.find("keymap-search").bounds(); + assert!(window.try_find(("keymap-row", 0usize)).is_some()); + for _ in 0..10 { + window.scroll( + "keymap-results", + ScrollDelta::Pixels(point(px(0.), px(-120.))), + cx, + ); + } + assert!(window.try_find(("keymap-row", 0usize)).is_none()); + assert_eq!(window.find("keymap-search").bounds(), search_bounds); + + window.click("keymap-search", cx); + window.input("ctrl-alt-f11 j z", cx); + window.render_frame(cx); + assert!(window.try_find(("keymap-row", 1usize)).is_none()); + window.click(("keymap-keys", 0usize), cx); + window.press("alt-s", cx); + window.render_frame(cx); + assert!(window.try_find(("keymap-row", 0usize)).is_none()); + }) + .unwrap(); + assert_eq!(bound(&keymap, cx, "alt-s"), ["workspace::ToggleSidebar"]); + assert!(bound(&keymap, cx, "ctrl-alt-f11 j z").is_empty()); +} + +#[gpui_kit::test] +#[ignore = "expanded keymap rendering performance fixture; run in isolation"] +fn measure_expanded_keymap_filtering(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let defaults = expanded_keymap(); + for _ in 0..3 { + let (handle, _, _) = setup_with_defaults(&defaults, cx); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.click("keymap-search", cx); + }) + .unwrap(); + let start = Instant::now(); + for letter in "toggle sidebar".chars() { + cx.simulate_input(handle, letter.encode_utf8(&mut [0; 4])); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + let elapsed = start.elapsed(); + cx.update_window(handle, |_, window, cx| { + // The broad query still shows editable shortcut rows. + assert!(window.try_find(("keymap-keys", 0usize)).is_some()); + window.press("ctrl-a", cx); + window.input("ctrl-alt-f11 j z", cx); + window.render_frame(cx); + assert!(window.try_find(("keymap-keys", 0usize)).is_some()); + assert!(window.try_find(("keymap-keys", 1usize)).is_none()); + }) + .unwrap(); + writeln!( + std::io::stdout().lock(), + "260 shortcuts, 14 edits: {elapsed:.2?}" + ) + .unwrap(); + } +} diff --git a/crates/keymap-ui/src/view.rs b/crates/keymap-ui/src/view.rs index 08313dae..089b9bc6 100644 --- a/crates/keymap-ui/src/view.rs +++ b/crates/keymap-ui/src/view.rs @@ -7,7 +7,7 @@ use gpui_kit::{ use nocterm_keymap::{KeymapError, KeymapHandle, humanize}; use nocterm_ui::SettingsPage; -use crate::rows::default_context; +use crate::{listing::Listing, rows::default_context}; #[path = "render.rs"] mod render; @@ -35,8 +35,7 @@ pub struct KeymapView { _subscription: Subscription, keymap: KeymapHandle, _keymap_subscription: Subscription, - rows: std::rc::Rc>, - rows_revision: u64, + listing: Listing, } impl KeymapView { @@ -53,8 +52,6 @@ impl KeymapView { let keymap_subscription = keymap.observe(cx, move |cx| { let _ = view.update(cx, |_, cx| cx.notify()); }); - let rows = std::rc::Rc::new(crate::rows::rows(&keymap, cx)); - let rows_revision = keymap.revision(cx); Self { keymap, _keymap_subscription: keymap_subscription, @@ -64,8 +61,7 @@ impl KeymapView { message: None, interceptor: None, _subscription: subscription, - rows, - rows_revision, + listing: Listing::default(), } } diff --git a/crates/keymap/src/file.rs b/crates/keymap/src/file.rs index 1055d14d..8e83282c 100644 --- a/crates/keymap/src/file.rs +++ b/crates/keymap/src/file.rs @@ -71,11 +71,8 @@ pub fn normalize(keystrokes: &str) -> Result { Ok(parts.join(" ")) } -fn key(context: &Option, keystrokes: &str) -> (Option, String) { - ( - context.clone(), - normalize(keystrokes).unwrap_or_else(|_| keystrokes.to_owned()), - ) +fn canonical_keys(keystrokes: &str) -> String { + normalize(keystrokes).unwrap_or_else(|_| keystrokes.to_owned()) } impl KeymapFile { @@ -94,9 +91,9 @@ impl KeymapFile { /// The action `keystrokes` runs in `context`, if this file binds it. pub fn action_for(&self, context: &Option, keystrokes: &str) -> Option<&str> { - let wanted = key(context, keystrokes); + let wanted = canonical_keys(keystrokes); self.here() - .filter(|(c, k, _)| key(c, k) == wanted) + .filter(|(c, k, _)| *c == context && canonical_keys(k) == wanted) .last() .map(|(_, _, action)| action.as_str()) } @@ -122,19 +119,19 @@ impl KeymapFile { /// Binds `keystrokes` to `action` in `context`, replacing what it ran. pub fn set(&mut self, context: &Option, keystrokes: &str, action: &str) { self.remove(context, keystrokes); - let keystrokes = key(context, keystrokes).1; + let keystrokes = canonical_keys(keystrokes); self.bindings_mut(context) .insert(keystrokes, action.to_owned()); } /// Forgets what this file says about `keystrokes` in `context`. pub fn remove(&mut self, context: &Option, keystrokes: &str) { - let wanted = key(context, keystrokes); + let wanted = canonical_keys(keystrokes); for section in &mut self.sections { - if section.context == wanted.0 { + if section.context == *context { section .bindings - .retain(|keys, _| key(context, keys).1 != wanted.1); + .retain(|keys, _| canonical_keys(keys) != wanted); } } self.sections.retain(|section| !section.bindings.is_empty()); @@ -155,26 +152,36 @@ impl KeymapFile { /// The bindings in effect: the defaults, with the user's entries replacing /// or removing the ones with the same keystrokes and context. pub fn merge(defaults: &KeymapFile, user: &KeymapFile) -> Vec { - let mut bindings: Vec = Vec::new(); - let mut apply = |context: &Option, keys: &String, action: &String, source| { - let wanted = key(context, keys); - bindings.retain(|binding| key(&binding.context, &binding.keystrokes) != wanted); + let mut bindings = Vec::new(); + let mut positions: BTreeMap<_, Vec> = BTreeMap::new(); + let entries = defaults + .here() + .map(|entry| (entry, Source::Default)) + .chain(user.here().map(|entry| (entry, Source::User))); + for ((context, keys, action), source) in entries { + let wanted = (context.as_deref(), canonical_keys(keys)); + if let Some(replaced) = positions.remove(&wanted) { + for position in replaced { + bindings[position] = None; + } + } if action != UNBOUND { - bindings.push(Binding { + // GPUI can serialize a key override into a spelling whose next + // normalization changes it. Compare against the published spelling, + // as if we had read it back from each previous binding. + positions + .entry((wanted.0, canonical_keys(&wanted.1))) + .or_default() + .push(bindings.len()); + bindings.push(Some(Binding { context: context.clone(), keystrokes: wanted.1, action: action.clone(), source, - }); + })); } - }; - for (context, keys, action) in defaults.here() { - apply(context, keys, action, Source::Default); } - for (context, keys, action) in user.here() { - apply(context, keys, action, Source::User); - } - bindings + bindings.into_iter().flatten().collect() } #[cfg(test)] @@ -212,6 +219,87 @@ context = "Workspace" assert_eq!(find("ctrl-j").unwrap().source, Source::Default); } + #[test] + fn unbinding_a_normalized_override_removes_all_matches_in_its_context() { + let defaults = file( + r#" +[[section]] +[section.bindings] +"A->global" = "global" +[[section]] +context = "Workspace" +[section.bindings] +"A->x" = "first" +"A->y" = "second" +"ctrl-j" = "keep" +"ctrl-k" = "old" +"invalid-key" = "legacy" +[[section]] +os = ["unavailable-test-platform"] +context = "Workspace" +[section.bindings] +"ctrl-q" = "unavailable" +"#, + ); + let mut user = file( + r#" +[[section]] +context = "Workspace" +[section.bindings] +"ctrl-k" = "new" +"invalid-key" = "none" +"#, + ); + let actions = |user: &KeymapFile| { + merge(&defaults, user) + .into_iter() + .map(|binding| binding.action) + .collect::>() + }; + assert_eq!(actions(&user), ["global", "first", "second", "keep", "new"]); + user.set(&Some("Workspace".into()), "shift-a", UNBOUND); + assert_eq!(actions(&user), ["global", "keep", "new"]); + } + + #[test] + #[ignore = "manual performance measurement"] + fn measure_large_keymap_merge() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let section = |start, end| Section { + context: Some("Workspace".into()), + bindings: (start..end) + .map(|index| (format!("ctrl-alt-f11 k{index} z"), format!("Action{index}"))) + .collect(), + ..Section::default() + }; + for size in [64, 260, 1024] { + let defaults = KeymapFile { + sections: vec![section(0, size / 3)], + }; + let user = KeymapFile { + sections: vec![section(size / 6, size)], + }; + let mut durations = [std::time::Duration::ZERO; 11]; + for duration in &mut durations { + let start = Instant::now(); + let bindings = black_box(merge(black_box(&defaults), black_box(&user))); + *duration = start.elapsed(); + assert_eq!(bindings.len(), size); + assert_eq!(bindings.first().unwrap().action, "Action0"); + assert_eq!(bindings[size / 6 - 1].source, Source::Default); + assert_eq!(bindings[size / 6].source, Source::User); + } + durations.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{size} bindings, median {:?}", + durations[durations.len() / 2] + ) + .unwrap(); + } + } + #[test] fn keystrokes_are_compared_as_written_by_the_keymap() { assert_eq!( diff --git a/crates/layout-ui/src/fit.rs b/crates/layout-ui/src/fit.rs index 06af970d..d1a3f5ea 100644 --- a/crates/layout-ui/src/fit.rs +++ b/crates/layout-ui/src/fit.rs @@ -13,7 +13,7 @@ use std::{ use gpui_kit::{Pixels, px}; use nocterm_plugin_model::{PluginSet, Zone}; -use nocterm_window_layout::{ResolvedItem, ResolvedMember}; +use nocterm_window_layout::{ResolvedGroup, ResolvedItem, ResolvedMember}; use crate::{ face::{GAP_WIDTH, PILL_PADDING}, @@ -61,21 +61,19 @@ impl Plan { } } -/// The width the preview's box was drawn with last time, and the plan made for it. +/// The last observed box width and the width requirements of its contents. /// /// The estimate of a chip is generous, so that a bar that is said to fit does. #[derive(Clone, Default)] pub(crate) struct Fit { width: Rc>>, - /// The last plan, which holds while the layout, the plugins and the width are the same. - planned: Rc>>, + measured: Rc>>, } -struct Planned { +struct Measured { snapshot: Rc, catalog: Arc, - width: Option, - plan: Plan, + widths: WidthRequirements, } /// An average advance of the small text of a chip. @@ -110,104 +108,117 @@ impl Fit { /// How to draw the bar in a box as wide as the last one seen. Before any is seen, in full. pub(crate) fn plan(&self, snapshot: &Rc, catalog: &Arc) -> Plan { - let width = self.width.get(); - if let Some(planned) = self.planned.borrow().as_ref() - && Rc::ptr_eq(&planned.snapshot, snapshot) - && Arc::ptr_eq(&planned.catalog, catalog) - && planned.width == width + let Some(width) = self.width.get() else { + return Plan { + density: Density::Full, + spread: Spread::Centred, + scroll: None, + }; + }; + if let Some(measured) = self.measured.borrow().as_ref() + && Rc::ptr_eq(&measured.snapshot, snapshot) + && Arc::ptr_eq(&measured.catalog, catalog) { - return planned.plan; + return measured.widths.plan(width); } - let plan = plan_for(width, snapshot, catalog); - self.planned.replace(Some(Planned { + let widths = WidthRequirements::measure(snapshot, catalog); + self.measured.replace(Some(Measured { snapshot: snapshot.clone(), catalog: catalog.clone(), - width, - plan, + widths, })); - plan + widths.plan(width) } } -fn plan_for(width: Option, snapshot: &Snapshot, catalog: &PluginSet) -> Plan { - let Some(width) = width else { - return Plan { - density: Density::Full, - spread: Spread::Centred, - scroll: None, +#[derive(Clone, Copy)] +struct WidthRequirements { + full_centred: f32, + compact_centred: f32, + compact_packed: f32, +} + +impl WidthRequirements { + fn measure(snapshot: &Snapshot, catalog: &PluginSet) -> Self { + let [left, centre, right] = + [Zone::Left, Zone::Center, Zone::Right].map(|zone| zone_width(snapshot, catalog, zone)); + // Centred, the wider of the two sides counts on both, as in the real bar. + Self { + full_centred: total_width(2. * left.full.max(right.full), centre.full), + compact_centred: total_width(2. * left.compact.max(right.compact), centre.compact), + compact_packed: total_width(left.compact + right.compact, centre.compact), + } + } + + fn plan(self, width: Pixels) -> Plan { + let room = f32::from(width); + let (density, spread, need) = if self.full_centred <= room { + (Density::Full, Spread::Centred, self.full_centred) + } else if self.compact_centred <= room { + (Density::Compact, Spread::Centred, self.compact_centred) + } else { + (Density::Compact, Spread::Packed, self.compact_packed) }; - }; - let room = f32::from(width); - let fits = |density, spread| needed(snapshot, catalog, density, spread) <= room; - let (density, spread) = [ - (Density::Full, Spread::Centred), - (Density::Compact, Spread::Centred), - (Density::Compact, Spread::Packed), - ] - .into_iter() - .find(|(density, spread)| fits(*density, *spread)) - .unwrap_or((Density::Compact, Spread::Packed)); - let need = needed(snapshot, catalog, density, spread); - Plan { - density, - spread, - scroll: (need > room).then(|| px(need)), + Plan { + density, + spread, + scroll: (need > room).then(|| px(need)), + } } } -/// The width the bar takes at `density`. Centred, the wider of the two sides counts on both, as -/// the real bar centres its middle. -fn needed(snapshot: &Snapshot, catalog: &PluginSet, density: Density, spread: Spread) -> f32 { - let width = |zone| zone_width(snapshot, catalog, zone, density); - let (left, centre, right) = (width(Zone::Left), width(Zone::Center), width(Zone::Right)); - let sides = match spread { - Spread::Centred => 2. * left.max(right), - Spread::Packed => left + right, - }; +fn total_width(sides: f32, centre: f32) -> f32 { BOX_PADDING + sides + centre + 2. * ZONE_GAP } -fn zone_width(snapshot: &Snapshot, catalog: &PluginSet, zone: Zone, density: Density) -> f32 { +#[derive(Default)] +struct ZoneWidth { + full: f32, + compact: f32, +} + +fn zone_width(snapshot: &Snapshot, catalog: &PluginSet, zone: Zone) -> ZoneWidth { let items = snapshot.layout().zone(zone); - let entries: f32 = items - .iter() - .map(|item| match item { + let mut entries = ZoneWidth::default(); + for item in items { + let (base, label) = match item { ResolvedItem::Widget(id) => { - let text = catalog.contribution(id).map_or(0, |spec| { + let chars = catalog.contribution(id).map_or(0, |spec| { spec.preview().unwrap_or(spec.title()).chars().count() }); - chip(density, Some(text)) - } - ResolvedItem::Separator => SEPARATOR, - ResolvedItem::Group(group) if group.is_solo() => chip(density, None), - ResolvedItem::Group(group) => { - let members: Vec = group - .members() - .iter() - .map(|member| match member { - ResolvedMember::Panel(_) => chip(density, None), - ResolvedMember::Separator => SEPARATOR, - }) - .collect(); - if members.is_empty() { - let title = snapshot.group_title(group).chars().count() as f32 * CHAR; - 2. * PILL_PADDING + title + CHIP_FRAME - } else { - // The border, and a gap around every member. - 2. + members.iter().sum::() + (members.len() + 1) as f32 * GAP_WIDTH - } + (CHIP_WIDTH, INNER_GAP + chars as f32 * CHAR) } - }) - .sum(); + ResolvedItem::Separator => (SEPARATOR, 0.), + ResolvedItem::Group(group) => (group_width(snapshot, group), 0.), + }; + entries.compact += base; + entries.full += base + label; + } let gaps = (items.len() + 1) as f32 * GAP_WIDTH; - (ZONE_BORDER + entries + gaps).max(EMPTY) + ZoneWidth { + full: (ZONE_BORDER + entries.full + gaps).max(EMPTY), + compact: (ZONE_BORDER + entries.compact + gaps).max(EMPTY), + } } -/// One chip: an icon, and the text of a widget when the density shows it. -fn chip(density: Density, text: Option) -> f32 { - let label = match (density, text) { - (Density::Full, Some(chars)) => INNER_GAP + chars as f32 * CHAR, - _ => 0., - }; - CHIP_FRAME + ICON + label +const CHIP_WIDTH: f32 = CHIP_FRAME + ICON; + +fn group_width(snapshot: &Snapshot, group: &ResolvedGroup) -> f32 { + if group.is_solo() { + return CHIP_WIDTH; + } + let members = group.members(); + if members.is_empty() { + let title = snapshot.group_title(group).chars().count() as f32 * CHAR; + return 2. * PILL_PADDING + title + CHIP_FRAME; + } + let width: f32 = members + .iter() + .map(|member| match member { + ResolvedMember::Panel(_) => CHIP_WIDTH, + ResolvedMember::Separator => SEPARATOR, + }) + .sum(); + // The border, and a gap around every member. + 2. + width + (members.len() + 1) as f32 * GAP_WIDTH } diff --git a/crates/layout-ui/src/lib.rs b/crates/layout-ui/src/lib.rs index a0bc0d43..efa6a884 100644 --- a/crates/layout-ui/src/lib.rs +++ b/crates/layout-ui/src/lib.rs @@ -24,8 +24,8 @@ //! built-in layout in use saves a custom copy that stays in use; history is dropped when //! anything else changes the layouts. //! Undo is bounded to 100 steps and 8 MiB of cloned snapshots per editor. The layout shown is -//! resolved once for each settings revision, set of plugins and layout picked, and its bar is -//! fitted once for each width, so a drag, which draws the window on every move, redraws cheaply. +//! resolved once for each layout and enablement snapshot, set of plugins and layout picked. The preview +//! measures those contents once, then selects its presentation for the current width. mod about; mod commands; diff --git a/crates/layout-ui/src/section.rs b/crates/layout-ui/src/section.rs index 2488b645..b0eb756e 100644 --- a/crates/layout-ui/src/section.rs +++ b/crates/layout-ui/src/section.rs @@ -1,6 +1,6 @@ //! The editor entity: which layout and item are shown, the writes it sends and what they led to. -use std::{rc::Rc, sync::Arc}; +use std::{cell::Cell, rc::Rc, sync::Arc}; use gpui_kit::{ App, Context, FocusHandle, Focusable, InteractiveElement as _, IntoElement, ParentElement as _, @@ -86,9 +86,16 @@ impl LayoutEditorSection { settings.register::(cx); let history = History::new(settings.setting::(cx).presets.clone()); let weak = cx.weak_entity(); - let changed = settings.observe(cx, move |cx| { - let _ = weak.update(cx, |section, cx| section.stored_changed(cx)); - }); + let seen_revision = Rc::new(Cell::new(settings.revision(cx))); + let observed_settings = settings.clone(); + let changed = move |cx: &mut App| { + let revision = observed_settings.revision(cx); + if seen_revision.replace(revision) != revision { + let _ = weak.update(cx, |section, cx| section.stored_changed(cx)); + } + }; + let layouts = settings.observe_section::(cx, changed.clone()); + let enablement = settings.observe_section::(cx, changed); let catalog = source.current(cx); let weak = cx.weak_entity(); let plugins = source.observe( @@ -115,7 +122,7 @@ impl LayoutEditorSection { focus: cx.focus_handle(), fit: Fit::default(), snapshots: Snapshots::default(), - _subscriptions: vec![changed, plugins], + _subscriptions: vec![layouts, enablement, plugins], observed, } } @@ -124,16 +131,14 @@ impl LayoutEditorSection { /// the plugins and the layout picked. pub(crate) fn snapshot(&mut self, cx: &App) -> Rc { let (settings, catalog, shown) = (&self.settings, &self.catalog, self.selection.shown()); - self.snapshots - .get(settings.revision(cx), catalog, shown, || { - Snapshot::new( - settings.setting::(cx), - settings.setting::(cx), - self.legacy_swapped, - shown, - catalog, - ) - }) + let document = settings.document(cx); + self.snapshots.get( + document.section_snapshot::(), + document.section_snapshot::(), + catalog, + shown, + self.legacy_swapped, + ) } pub(crate) fn mode(&self) -> &Mode { diff --git a/crates/layout-ui/src/snapshot.rs b/crates/layout-ui/src/snapshot.rs index b78f1287..0e3e1656 100644 --- a/crates/layout-ui/src/snapshot.rs +++ b/crates/layout-ui/src/snapshot.rs @@ -316,8 +316,8 @@ impl Snapshot { } /// The snapshot of the layout shown, built again only when what it is drawn from changed: the -/// settings, by their revision, the set of plugins, or the layout picked. An editor never -/// changes its `legacy_swapped`. It holds the one snapshot drawn last. +/// typed layout and enablement snapshots, the set of plugins, or the layout picked. +/// An editor never changes its `legacy_swapped`. It holds the one snapshot drawn last. #[derive(Default)] pub(crate) struct Snapshots { last: Option<(Drawn, Rc)>, @@ -325,31 +325,41 @@ pub(crate) struct Snapshots { /// What a snapshot was built from. struct Drawn { - revision: u64, + layouts: Arc, + enablement: Arc, catalog: Arc, shown: Option, } impl Snapshots { - /// The snapshot for these inputs: the last one when they are the same, else what `build` - /// makes of them. + /// The snapshot for these inputs: the last one when their identities match, else a + /// fresh resolution. Each typed snapshot stays shared with the published document. pub(crate) fn get( &mut self, - revision: u64, + layouts: Arc, + enablement: Arc, catalog: &Arc, shown: Option<&PresetId>, - build: impl FnOnce() -> Snapshot, + legacy_swapped: bool, ) -> Rc { if let Some((drawn, snapshot)) = &self.last - && drawn.revision == revision + && Arc::ptr_eq(&drawn.layouts, &layouts) + && Arc::ptr_eq(&drawn.enablement, &enablement) && Arc::ptr_eq(&drawn.catalog, catalog) && drawn.shown.as_ref() == shown { return snapshot.clone(); } - let snapshot = Rc::new(build()); + let snapshot = Rc::new(Snapshot::new( + &layouts, + &enablement, + legacy_swapped, + shown, + catalog, + )); let drawn = Drawn { - revision, + layouts, + enablement, catalog: catalog.clone(), shown: shown.cloned(), }; diff --git a/crates/layout-ui/src/tests/editing.rs b/crates/layout-ui/src/tests/editing.rs index 14a3d335..a7f9e5a7 100644 --- a/crates/layout-ui/src/tests/editing.rs +++ b/crates/layout-ui/src/tests/editing.rs @@ -187,3 +187,40 @@ fn a_layouts_table_that_does_not_read_is_not_overwritten(cx: &mut TestAppContext }); assert!(fixture.has("layout-notice", cx), "the user is told why"); } + +#[gpui_kit::test] +fn a_combined_layout_and_plugin_publication_updates_the_preview(cx: &mut TestAppContext) { + use nocterm_plugin_enablement::PluginEnablement; + use nocterm_plugin_model::{ContributionId, PluginId}; + use nocterm_window_layout::{LayoutPreset, LayoutSettings, PresetId}; + + let fixture = open(cx); + assert_eq!( + fixture.label("layout-preview:tools.clock", cx).as_deref(), + Some("Clock") + ); + let receipt = cx.update(|cx| { + fixture.settings.edit(cx, |document| { + document.update::(|settings| { + settings.presets.push(LayoutPreset { + id: PresetId::new("p1"), + name: "External".into(), + tray: vec![ContributionId::new("shell.files")], + ..Default::default() + }); + settings.active = Some(PresetId::new("p1")); + }); + document.update::(|settings| { + settings.disabled.push(PluginId::new("tools")); + }); + }) + }); + cx.foreground_executor().block_test(receipt).unwrap(); + cx.run_until_parked(); + assert!(fixture.has("layout-choice:p1", cx)); + assert!(fixture.has("layout-tray:shell.files", cx)); + assert_eq!( + fixture.label("layout-preview:tools.clock", cx).as_deref(), + Some("Clock (disabled)") + ); +} diff --git a/crates/layout-ui/src/tests/geometry.rs b/crates/layout-ui/src/tests/geometry.rs index a107a61f..76de60aa 100644 --- a/crates/layout-ui/src/tests/geometry.rs +++ b/crates/layout-ui/src/tests/geometry.rs @@ -164,3 +164,139 @@ fn the_tray_stays_below_the_bar_and_inside_the_editor(cx: &mut TestAppContext) { assert!(inside(tray, bounds(&fixture, "layout-editor", cx))); } } + +#[gpui_kit::test] +fn changing_the_layout_at_the_same_width_refits_the_preview(cx: &mut TestAppContext) { + use nocterm_plugin_model::ContributionId; + use nocterm_window_layout::{LayoutPreset, LayoutSettings, PresetId}; + + let fixture = super::open_with( + LayoutSettings { + presets: vec![LayoutPreset { + id: PresetId::new("p1"), + name: "Spare".into(), + tray: [ + "shell.servers", + "shell.files", + "shell.agent", + "shell.terminal", + "tools.clock", + "tools.cpu", + "plain.note", + "off.item", + ] + .map(ContributionId::new) + .into(), + ..LayoutPreset::default() + }], + ..LayoutSettings::default() + }, + cx, + ); + fixture.resize(660., cx); + let id = "layout-preview:shell.transfers"; + let tight = bounds(&fixture, id, cx).size.width; + fixture.click("layout-choice:p1", cx); + let roomy = bounds(&fixture, id, cx).size.width; + assert!(roomy > tight + gpui_kit::px(20.), "{roomy:?} / {tight:?}"); + + fixture.click("layout-choice:default", cx); + assert_eq!(bounds(&fixture, id, cx).size.width, tight); +} + +#[gpui_kit::test] +#[ignore = "manual layout editor resize workload"] +fn measure_preview_during_repeated_resizes(cx: &mut TestAppContext) { + use std::io::Write as _; + + let fixture = open(cx); + let mut elapsed = Vec::new(); + for _ in 0..7 { + let start = std::time::Instant::now(); + for width in (1..=24).chain((1..=24).rev()) { + fixture.resize(250. + width as f32 * 48., cx); + } + elapsed.push(start.elapsed()); + } + elapsed.sort_unstable(); + let preview = bounds(&fixture, "layout-preview", cx); + let tray = bounds(&fixture, "layout-tray", cx); + assert!(preview.bottom() <= tray.top()); + assert_eq!( + fixture.stored(cx), + nocterm_window_layout::LayoutSettings::default() + ); + writeln!( + std::io::stdout().lock(), + "48 preview resizes per sample, median {:?}", + elapsed[3] + ) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "manual layout editor profile of settings publications and subsequent frames"] +fn measure_layout_editor_publications(cx: &mut TestAppContext) { + use gpui_kit::test::TestWindowExt as _; + use nocterm_plugin_enablement::PluginEnablement; + use nocterm_plugin_model::{ContributionId, PluginId}; + use nocterm_ui::TerminalSettings; + use nocterm_window_layout::{LayoutPreset, LayoutSettings, PresetId}; + use std::io::Write as _; + + let count = std::env::var("NOCTERM_PROFILE_PRESETS") + .map_or(Ok(32), |count| count.parse::()) + .unwrap(); + let fixture = super::open_with( + LayoutSettings { + presets: (1..=count) + .map(|i| LayoutPreset { + id: PresetId::from_owned(format!("p{i}")), + name: format!("Saved layout {i}"), + tray: ["shell.files", "plain.note"] + .map(ContributionId::new) + .into(), + ..Default::default() + }) + .collect(), + ..Default::default() + }, + cx, + ); + cx.update(|cx| fixture.settings.register::(cx)); + for mode in ["unrelated", "enablement"] { + for sample in 0..7 { + let start = std::time::Instant::now(); + for i in 0..32 { + let receipt = cx.update(|cx| { + if mode == "unrelated" { + fixture + .settings + .update::(cx, move |settings| { + settings.scrollback_lines = 10_001 + i % 2; + }) + } else { + fixture + .settings + .update::(cx, move |settings| { + settings.disabled.retain(|id| id.as_str() != "tools"); + if i % 2 == 0 { + settings.disabled.push(PluginId::new("tools")); + } + }) + } + }); + cx.foreground_executor().block_test(receipt).unwrap(); + fixture.frame(cx, |window, _| { + assert!(window.try_find("layout-preview").is_some()); + }); + } + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} presets={count} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); + } + } +} diff --git a/crates/layout-ui/src/tests/history.rs b/crates/layout-ui/src/tests/history.rs index e60a9cee..0faee0a8 100644 --- a/crates/layout-ui/src/tests/history.rs +++ b/crates/layout-ui/src/tests/history.rs @@ -124,3 +124,23 @@ fn an_undo_pressed_right_after_a_move_leaves_the_move_alone(cx: &mut TestAppCont fixture.keys("ctrl-z", cx); assert_eq!(fixture.left_to_right(&RIGHT, cx), ORIGINAL); } + +#[gpui_kit::test] +fn changing_terminal_settings_does_not_discard_layout_undo(cx: &mut TestAppContext) { + use nocterm_ui::TerminalSettings; + + let fixture = open(cx); + fixture.click("layout-preview:shell.transfers", cx); + fixture.keys("alt-left", cx); + assert_ne!(fixture.left_to_right(&RIGHT, cx), ORIGINAL); + let receipt = cx.update(|cx| { + fixture.settings.register::(cx); + fixture.settings.update::(cx, |settings| { + settings.scrollback_lines = 10_001; + }) + }); + cx.foreground_executor().block_test(receipt).unwrap(); + fixture.click("layout-undo", cx); + assert_eq!(fixture.left_to_right(&RIGHT, cx), ORIGINAL); + assert!(fixture.stored(cx).presets.is_empty()); +} diff --git a/crates/local/Cargo.toml b/crates/local/Cargo.toml index 4a800e52..c7107318 100644 --- a/crates/local/Cargo.toml +++ b/crates/local/Cargo.toml @@ -19,12 +19,13 @@ futures.workspace = true tracing.workspace = true tempfile.workspace = true thiserror.workspace = true -chrono = { version = "0.4", default-features = false, features = ["clock"] } +jiff = "1.1" [target.'cfg(unix)'.dependencies] nix = { version = "0.28", features = ["signal", "fs", "event", "poll"] } [target.'cfg(target_os = "linux")'.dependencies] +async-io.workspace = true filedescriptor = "0.8.3" rustix = { version = "1.1.5", features = ["process"] } diff --git a/crates/local/src/clock.rs b/crates/local/src/clock.rs index 5757716c..cd367770 100644 --- a/crates/local/src/clock.rs +++ b/crates/local/src/clock.rs @@ -1,22 +1,44 @@ //! The local wall clock, read from the operating system. -use chrono::{Local, Offset as _}; +use std::sync::Mutex; + +use jiff::{Timestamp, tz::TimeZone}; use nocterm_core::clock::{WallClock, WallTime}; /// Reads the system time and the local time zone, so the zone is the one in effect at that /// instant (daylight saving included). A zone the system cannot report is UTC. -#[derive(Clone, Copy, Debug, Default)] -pub struct SystemClock; +#[derive(Debug, Default)] +pub struct SystemClock { + zone: Mutex>, +} -impl WallClock for SystemClock { - fn now(&self) -> WallTime { - let now = Local::now(); +impl SystemClock { + // Jiff's system timezone cache otherwise expires after five minutes. Keep one + // observation per wall-clock second, including fallback UTC, for all consumers + // of this adapter. A clock step also changes the key; no work runs when idle. + fn read(&self, now: Timestamp, load_zone: impl FnOnce() -> TimeZone) -> WallTime { + // Unix seconds label the containing second, including before the epoch. + let seconds = now.as_second() - i64::from(now.subsec_nanosecond() < 0); + let mut cached = self.zone.lock().unwrap_or_else(|e| e.into_inner()); + if cached.as_ref().is_some_and(|(last, _)| *last != seconds) { + *cached = None; + } + let (_, zone) = cached.get_or_insert_with(|| (seconds, load_zone())); WallTime { - unix_seconds: now.timestamp(), - utc_offset_seconds: now.offset().fix().local_minus_utc(), + unix_seconds: seconds, + utc_offset_seconds: zone.to_offset(now).seconds(), } } } +impl WallClock for SystemClock { + fn now(&self) -> WallTime { + self.read(Timestamp::now(), || { + jiff::tz::reset_system_time_zone_cache(); + TimeZone::system() + }) + } +} + #[cfg(test)] mod tests; diff --git a/crates/local/src/clock/tests.rs b/crates/local/src/clock/tests.rs index 217b32c3..04db5c07 100644 --- a/crates/local/src/clock/tests.rs +++ b/crates/local/src/clock/tests.rs @@ -6,7 +6,7 @@ const LARGEST_OFFSET: i32 = 14 * 3600; #[test] fn the_offset_is_a_real_time_zone() { - let time = SystemClock.now(); + let time = SystemClock::default().now(); assert!( (-LARGEST_OFFSET..=LARGEST_OFFSET).contains(&time.utc_offset_seconds), "offset {}", @@ -20,7 +20,7 @@ fn the_time_follows_the_system_clock() { .duration_since(UNIX_EPOCH) .unwrap() .as_secs() as i64; - let time = SystemClock.now(); + let time = SystemClock::default().now(); let after = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() @@ -30,6 +30,37 @@ fn the_time_follows_the_system_clock() { #[test] fn the_local_time_is_of_the_day() { - let (hour, minute) = SystemClock.now().local_hour_minute(); + let (hour, minute) = SystemClock::default().now().local_hour_minute(); assert!(hour < 24 && minute < 60); } + +#[test] +fn shared_clock_refreshes_local_zone_without_refreshing_every_read() { + use std::cell::Cell; + let clock = SystemClock::default(); + let now: Timestamp = "2024-03-10T07:01:00Z".parse().unwrap(); + let refreshes = Cell::new(0); + let read = |timestamp, offset| { + clock.read(timestamp, || { + refreshes.set(refreshes.get() + 1); + TimeZone::fixed(jiff::tz::offset(offset)) + }) + }; + assert_eq!(read(now, -5).utc_offset_seconds, -5 * 3600); + assert_eq!(read(now, -4).utc_offset_seconds, -5 * 3600); + assert_eq!(refreshes.get(), 1); + let later = now + std::time::Duration::from_secs(1); + assert_eq!(read(later, -4).utc_offset_seconds, -4 * 3600); + // A backward clock step must also refresh. + assert_eq!(read(now, -5).utc_offset_seconds, -5 * 3600); + assert_eq!(refreshes.get(), 3); +} + +#[test] +fn fractional_time_before_epoch_uses_containing_unix_second() { + let clock = SystemClock::default(); + let now: Timestamp = "1969-12-31T23:59:59.999Z".parse().unwrap(); + let value = clock.read(now, || TimeZone::UTC); + assert_eq!(value.unix_seconds, -1); + assert_eq!(value.local_hour_minute_second(), (23, 59, 59)); +} diff --git a/crates/local/src/exec.rs b/crates/local/src/exec.rs index 55f5e3ae..77367b15 100644 --- a/crates/local/src/exec.rs +++ b/crates/local/src/exec.rs @@ -3,29 +3,26 @@ use std::{ io::{Read, Write}, process::{ChildStderr, ChildStdin, ChildStdout}, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, + sync::Arc, thread, time::Duration, }; use futures::{FutureExt, channel::oneshot, executor::block_on, select}; use nocterm_session::{ - ErrorTail, ExecError, ExecFuture, ExecOutput, ExecRequest, ExecSink, HostExec, Session, - ShellLaunch, TerminalRequest, + ConnectionSource, ErrorTail, ExecError, ExecFuture, ExecOutput, ExecRequest, ExecSink, + HostExec, Session, ShellLaunch, TerminalRequest, }; mod admission; mod process; +mod stop; use admission::{Admission, Permit}; +use stop::Stop; #[cfg(all(test, unix))] mod tests; const READ_BUFFER: usize = 16 * 1024; -#[cfg(not(unix))] -const EXIT_POLL: Duration = Duration::from_millis(100); const ERROR_GRACE: Duration = Duration::from_millis(200); /// One explicitly shared native-command admission owner. @@ -104,7 +101,7 @@ fn start( let (Some(stdout), Some(stderr)) = (process.stdout(), process.stderr()) else { return Err(ExecError::Failed("no output pipe".into())); }; - let stopped = Arc::new(AtomicBool::new(false)); + let stopped = Arc::new(Stop::new()); if let (Some(input), Some(stdin)) = (request.stdin, process.stdin()) { write_input( stdin, @@ -113,35 +110,20 @@ fn start( stopped.clone(), permit.clone(), ) - .inspect_err(|_| stopped.store(true, Ordering::Release))?; + .inspect_err(|_| stopped.signal())?; } let (sink, output) = ExecOutput::channel_with_source(source.clone()); let sink = Arc::new(sink); let drained = read_output(stdout, sink.clone(), stopped.clone(), permit.clone()) - .inspect_err(|_| stopped.store(true, Ordering::Release))?; - let errors = read_errors(stderr, stopped.clone(), permit.clone()) - .inspect_err(|_| stopped.store(true, Ordering::Release))?; + .inspect_err(|_| stopped.signal())?; + let errors = + read_errors(stderr, stopped.clone(), permit.clone()).inspect_err(|_| stopped.signal())?; let failed = stopped.clone(); spawn("nocterm-exec-wait", move || { - // Observe the leader independently from pipe EOF: descendants may - // retain both output pipes after the leader has exited. let _permit = permit; - let mut pause = Duration::from_millis(1); - let natural = loop { - if sink.is_closed() || source.check().is_err() { - break false; - } - match process.exited() { - Ok(true) => break true, - Ok(false) => { - thread::sleep(pause); - pause = (pause * 2).min(Duration::from_millis(100)); - } - Err(_) => break false, - } - }; + let natural = wait_for_leader(&mut process, &source, &sink); let status = process.stop().filter(|_| natural); - stopped.store(true, Ordering::Release); + stopped.signal(); block_on(async { select! { _ = drained.fuse() => (), @@ -151,15 +133,60 @@ fn start( let tail = errors.recv_timeout(ERROR_GRACE).unwrap_or_default(); sink.finish(tail.exit(status)); }) - .inspect_err(|_| failed.store(true, Ordering::Release))?; + .inspect_err(|_| failed.signal())?; Ok(output) } +fn wait_for_leader( + process: &mut process::Process, + source: &ConnectionSource, + sink: &ExecSink, +) -> bool { + // Descendants can keep both pipes open after the leader exits. + #[cfg(target_os = "linux")] + if !source.is_restricted() + && let Some(exited) = block_on(wait_for_pidfd(process, sink)) + { + return exited; + } + + // Restricted sources have synchronous guards without a revocation signal. + let mut pause = Duration::from_millis(1); + while !sink.is_closed() && source.check().is_ok() { + match process.exited() { + Ok(true) => return true, + Ok(false) => { + thread::sleep(pause); + pause = (pause * 2).min(Duration::from_millis(100)); + } + Err(_) => return false, + } + } + false +} + +#[cfg(target_os = "linux")] +async fn wait_for_pidfd(process: &mut process::Process, sink: &ExecSink) -> Option { + use std::io; + + let descriptor = async_io::Async::new_nonblocking(process.pidfd().ok()?).ok()?; + futures::select_biased! { + () = sink.closed().fuse() => Some(false), + observed = descriptor.read_with(|_| { + if process.exited()? { + Ok(()) + } else { + Err(io::ErrorKind::WouldBlock.into()) + } + }).fuse() => observed.ok().map(|()| !sink.is_closed()), + } +} + fn write_input( mut stdin: ChildStdin, input: Vec, source: nocterm_session::ConnectionSource, - stopped: Arc, + stopped: Arc, permit: Arc, ) -> Result<(), ExecError> { #[cfg(unix)] @@ -167,12 +194,12 @@ fn write_input( spawn("nocterm-exec-in", move || { let _permit = permit; let mut remaining = input.as_slice(); - while !remaining.is_empty() && source.check().is_ok() && !stopped.load(Ordering::Acquire) { + while !remaining.is_empty() && source.check().is_ok() && !stopped.is_signalled() { match stdin.write(&remaining[..remaining.len().min(1024)]) { Ok(0) => break, Ok(n) => remaining = &remaining[n..], Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { - wait_writable(&stdin) + stopped.wait_writable(&stdin) } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} Err(_) => break, @@ -184,7 +211,7 @@ fn write_input( fn read_output( mut stdout: ChildStdout, sink: Arc, - stopped: Arc, + stopped: Arc, permit: Arc, ) -> Result, ExecError> { #[cfg(unix)] @@ -203,10 +230,10 @@ fn read_output( } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { - if stopped.load(Ordering::Acquire) || sink.is_closed() { + if stopped.is_signalled() || sink.is_closed() { break; } - wait_readable(&stdout); + stopped.wait_readable(&stdout); } Err(_) => break, } @@ -218,7 +245,7 @@ fn read_output( fn read_errors( mut stderr: ChildStderr, - stopped: Arc, + stopped: Arc, permit: Arc, ) -> Result, ExecError> { #[cfg(unix)] @@ -234,10 +261,10 @@ fn read_errors( Ok(read) => tail.push(&buffer[..read]), Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { - if stopped.load(Ordering::Acquire) { + if stopped.is_signalled() { break; } - wait_readable(&stderr); + stopped.wait_readable(&stderr); } Err(_) => break, } @@ -254,25 +281,3 @@ fn spawn(name: &str, body: impl FnOnce() + Send + 'static) -> Result<(), ExecErr .map(drop) .map_err(|error| ExecError::Failed(error.to_string())) } - -#[cfg(unix)] -fn wait_readable(pipe: &impl std::os::fd::AsFd) { - wait_pipe(pipe, nix::poll::PollFlags::POLLIN); -} -#[cfg(unix)] -fn wait_writable(pipe: &impl std::os::fd::AsFd) { - wait_pipe(pipe, nix::poll::PollFlags::POLLOUT); -} -#[cfg(unix)] -fn wait_pipe(pipe: &impl std::os::fd::AsFd, events: nix::poll::PollFlags) { - let mut fds = [nix::poll::PollFd::new(pipe.as_fd(), events)]; - let _ = nix::poll::poll(&mut fds, 100u16); -} -#[cfg(not(unix))] -fn wait_readable(_: &T) { - thread::sleep(EXIT_POLL); -} -#[cfg(not(unix))] -fn wait_writable(_: &T) { - thread::sleep(EXIT_POLL); -} diff --git a/crates/local/src/exec/process.rs b/crates/local/src/exec/process.rs index bdadcbfa..6eddc6b8 100644 --- a/crates/local/src/exec/process.rs +++ b/crates/local/src/exec/process.rs @@ -107,6 +107,11 @@ impl Process { } } + #[cfg(target_os = "linux")] + pub(super) fn pidfd(&self) -> rustix::io::Result { + self.observer.as_ref().unwrap().pidfd() + } + pub(super) fn stop(&mut self) -> Option { let mut child = self.child.take()?; #[cfg(unix)] diff --git a/crates/local/src/exec/process/unix.rs b/crates/local/src/exec/process/unix.rs index 553807ff..d04162af 100644 --- a/crates/local/src/exec/process/unix.rs +++ b/crates/local/src/exec/process/unix.rs @@ -35,6 +35,14 @@ impl Observer { )?; Ok(!matches!(status, WaitStatus::StillAlive)) } + + #[cfg(target_os = "linux")] + pub(super) fn pidfd(&self) -> rustix::io::Result { + use rustix::process::{Pid, PidfdFlags, pidfd_open}; + + let pid = Pid::from_raw(self.0.as_raw()).ok_or(rustix::io::Errno::INVAL)?; + pidfd_open(pid, PidfdFlags::empty()) + } } #[cfg(any( diff --git a/crates/local/src/exec/stop.rs b/crates/local/src/exec/stop.rs new file mode 100644 index 00000000..c0a8a0f3 --- /dev/null +++ b/crates/local/src/exec/stop.rs @@ -0,0 +1,88 @@ +//! Wakes command I/O when the leader exits or command startup fails. + +use std::sync::atomic::{AtomicBool, Ordering}; + +#[cfg(unix)] +use nix::poll::{PollFd, PollFlags, poll}; +#[cfg(unix)] +use std::os::fd::AsFd; +#[cfg(target_os = "linux")] +use std::{os::fd::OwnedFd, sync::Mutex}; + +pub(super) struct Stop { + signalled: AtomicBool, + #[cfg(target_os = "linux")] + wake: Option, +} + +#[cfg(target_os = "linux")] +struct Wake { + closed: OwnedFd, + writer: Mutex>, +} + +impl Stop { + pub(super) fn new() -> Self { + #[cfg(target_os = "linux")] + let wake = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC) + .ok() + .map(|(closed, writer)| Wake { + closed, + writer: Mutex::new(Some(writer)), + }); + Self { + signalled: AtomicBool::new(false), + #[cfg(target_os = "linux")] + wake, + } + } + + pub(super) fn signal(&self) { + #[cfg(target_os = "linux")] + if !self.signalled.swap(true, Ordering::AcqRel) + && let Some(wake) = &self.wake + { + // Closing the write end wakes all pipe pollers without consuming a byte. + drop(wake.writer.lock().unwrap().take()); + } + #[cfg(not(target_os = "linux"))] + self.signalled.store(true, Ordering::Release); + } + + pub(super) fn is_signalled(&self) -> bool { + self.signalled.load(Ordering::Acquire) + } +} + +#[cfg(unix)] +impl Stop { + pub(super) fn wait_readable(&self, pipe: &impl AsFd) { + self.wait(pipe, PollFlags::POLLIN); + } + + pub(super) fn wait_writable(&self, pipe: &impl AsFd) { + self.wait(pipe, PollFlags::POLLOUT); + } + + fn wait(&self, pipe: &impl AsFd, events: PollFlags) { + let pipe = PollFd::new(pipe.as_fd(), events); + #[cfg(target_os = "linux")] + if let Some(wake) = &self.wake { + let mut fds = [pipe, PollFd::new(wake.closed.as_fd(), PollFlags::POLLIN)]; + let _ = poll(&mut fds, nix::poll::PollTimeout::NONE); + return; + } + let _ = poll(&mut [pipe], 100u16); + } +} + +#[cfg(not(unix))] +impl Stop { + pub(super) fn wait_readable(&self, _: &T) { + std::thread::sleep(std::time::Duration::from_millis(100)); + } + + pub(super) fn wait_writable(&self, _: &T) { + std::thread::sleep(std::time::Duration::from_millis(100)); + } +} diff --git a/crates/local/src/exec/tests.rs b/crates/local/src/exec/tests.rs index 63ac7a42..36d6cd6c 100644 --- a/crates/local/src/exec/tests.rs +++ b/crates/local/src/exec/tests.rs @@ -12,6 +12,124 @@ fn collect(mut output: ExecOutput) -> String { }) } +#[cfg(target_os = "linux")] +#[test] +#[ignore = "native performance measurement; run alone with --ignored --nocapture"] +fn idle_native_commands_benchmark() { + fn worker_counters() -> (u64, u64, u64) { + let mut counters = (0, 0, 0); + for worker in std::fs::read_dir("/proc/self/task").unwrap() { + let worker = worker.unwrap().path(); + let Ok(name) = std::fs::read_to_string(worker.join("comm")) else { + continue; + }; + if !matches!( + name.trim_end(), + "nocterm-exec-ou" | "nocterm-exec-er" | "nocterm-exec-wa" + ) { + continue; + } + // A worker can exit while cancellation is being observed. + let Ok(times) = std::fs::read_to_string(worker.join("schedstat")) else { + continue; + }; + let fields: Vec = times + .split_whitespace() + .map(|field| field.parse().unwrap()) + .collect(); + counters.0 += fields[0]; + counters.1 += fields[2]; + counters.2 += 1; + } + counters + } + for count in [1, 16] { + let executor = LocalExec::default(); + let jobs: Vec<_> = (0..count) + .map(|_| { + block_on( + executor.exec( + ExecRequest::new("sh") + .arg("-c") + .arg("echo ready; exec sleep 30"), + ), + ) + .unwrap() + }) + .collect(); + let mut jobs = jobs; + for job in &mut jobs { + assert_eq!(block_on(job.next()).as_deref(), Some(&b"ready\n"[..])); + } + thread::sleep(Duration::from_millis(200)); + let before = worker_counters(); + assert_eq!(before.2, count * 3); + let started = Instant::now(); + thread::sleep(Duration::from_secs(2)); + let after = worker_counters(); + assert_eq!(after.2, before.2); + writeln!( + std::io::stdout().lock(), + "{count} quiet commands over {:.3}s: {:.3}ms worker CPU, {} scheduler slices", + started.elapsed().as_secs_f64(), + (after.0 - before.0) as f64 / 1_000_000., + after.1 - before.1 + ) + .unwrap(); + drop(jobs); + let deadline = Instant::now() + Duration::from_secs(2); + while worker_counters().2 != 0 { + assert!( + Instant::now() < deadline, + "idle worker cancellation stalled" + ); + thread::sleep(Duration::from_millis(20)); + } + } +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "native performance measurement; run alone with --ignored --nocapture"] +fn measure_native_command_exit_with_inherited_pipes() { + use nix::{sys::stat::Mode, unistd::mkfifo}; + + let directory = tempfile::tempdir().unwrap(); + let trigger = directory.path().join("trigger"); + mkfifo(&trigger, Mode::S_IRUSR | Mode::S_IWUSR).unwrap(); + let exec = LocalExec::default(); + let mut timings = Vec::new(); + for sample in 0..20 { + let request = ExecRequest::new("sh") + .args([ + "-c", + "sleep 10 & printf 'ready\\n'; IFS= read -r trigger < \"$1\"; exit 7", + "measure", + ]) + .arg(trigger.to_str().unwrap()); + let mut output = block_on(exec.exec(request)).unwrap(); + assert_eq!(block_on(output.next()).as_deref(), Some(&b"ready\n"[..])); + let mut signal = std::fs::OpenOptions::new() + .write(true) + .open(&trigger) + .unwrap(); + thread::sleep(Duration::from_millis(180 + (sample * 37) % 100)); + let started = Instant::now(); + signal.write_all(b"go\n").unwrap(); + let exit = block_on(output.exit()); + timings.push(started.elapsed()); + assert_eq!(exit.status, Some(7)); + } + timings.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "FIFO release to collected exit with inherited pipes: p50 {:.3}ms p95 {:.3}ms", + timings[timings.len() / 2].as_secs_f64() * 1_000., + timings[timings.len() * 95 / 100 - 1].as_secs_f64() * 1_000. + ) + .unwrap(); +} + #[test] fn runs_a_script_from_its_input() { let request = ExecRequest::new("sh") @@ -37,6 +155,29 @@ fn dropping_the_output_stops_the_program_and_its_children() { assert!(!file.exists(), "the background child was stopped too"); } +#[test] +fn revoking_a_running_command_stops_its_children_while_its_output_is_retained() { + use nocterm_session::testing::ScriptedConnectionSource; + + let marker = tempfile::tempdir().unwrap(); + let file = marker.path().join("alive"); + let source = ScriptedConnectionSource::default(); + let exec = ScopedLocalExec::new(source.source()); + let request = ExecRequest::new("sh") + .args([ + "-c", + "(sleep 0.5; touch \"$1\") & echo started; wait", + "revocation", + ]) + .arg(file.to_str().unwrap()); + let mut output = block_on(exec.exec(request)).unwrap(); + assert_eq!(block_on(output.next()).as_deref(), Some(&b"started\n"[..])); + source.revoke(); + thread::sleep(Duration::from_millis(700)); + assert!(!file.exists()); + assert_eq!(block_on(output.next()), None); +} + #[test] fn programs_report_their_exit_and_errors() { let request = ExecRequest::new("sh") diff --git a/crates/local/src/lib.rs b/crates/local/src/lib.rs index 119a878d..13348808 100644 --- a/crates/local/src/lib.rs +++ b/crates/local/src/lib.rs @@ -6,11 +6,13 @@ //! recording::OutputLogFactory, nocterm_core::clock::WallClock (`SystemClock`). Output-log //! operations run only on their caller executor. //! Settings section: local options are composed by the app. Globals: none. -//! Linux PTY reads wait for descriptor readiness, owner closure or the owned leader's pidfd; +//! Linux PTY reads and writes wait for readiness, owner closure or the owned leader's pidfd; //! kernels denying pidfds and other platforms retain bounded process-status polling. //! Invariants: PTY/exec cancellation owns process cleanup; external editors instead //! retain a bounded independent wait owner and survive receipt/application exit. +#[cfg(not(target_os = "linux"))] +use std::time::Duration; use std::{ io::{Read, Write}, path::Path, @@ -19,7 +21,6 @@ use std::{ atomic::{AtomicBool, Ordering}, }, thread, - time::Duration, }; use futures::{FutureExt, executor::block_on, select}; @@ -289,6 +290,10 @@ fn start( let _ = child.wait(); return Err(error.into()); } + #[cfg(target_os = "linux")] + let readiness = Arc::new(readiness); + #[cfg(target_os = "linux")] + let write_readiness = readiness.clone(); let (done_tx, done_rx) = async_channel::bounded::<()>(1); let command_driver = driver.clone(); let closed_by_user = Arc::new(AtomicBool::new(false)); @@ -315,6 +320,14 @@ fn start( } }); thread::spawn(move || { + #[cfg(target_os = "linux")] + let wait_writable = + || write_readiness.wait_writable(command_driver.source().is_restricted()); + #[cfg(not(target_os = "linux"))] + let wait_writable = || { + thread::sleep(Duration::from_millis(10)); + Ok(()) + }; loop { let (finished, next) = block_on(async { select! { @@ -327,8 +340,14 @@ fn start( } match next { Some(Command::Input(bytes)) => { - if write_input(writer.as_mut(), &bytes, &command_driver, &done_rx).is_err() { - if !done_rx.is_closed() { + if let Err(error) = write_input( + writer.as_mut(), + &bytes, + &command_driver, + &done_rx, + wait_writable, + ) { + if error.kind() != std::io::ErrorKind::Interrupted && !done_rx.is_closed() { kill_process(killer.as_mut(), &command_master, shell_group); } break; @@ -376,7 +395,7 @@ fn start( break; } #[cfg(target_os = "linux")] - if let Err(error) = readiness.wait() { + if let Err(error) = readiness.wait_readable() { read_failure = Some(error); let mut failed_killer = child.clone_killer(); kill_process(failed_killer.as_mut(), &master, shell_group); @@ -441,6 +460,7 @@ fn write_input( bytes: &[u8], driver: &nocterm_session::SessionDriver, done: &async_channel::Receiver<()>, + wait_writable: impl Fn() -> std::io::Result<()>, ) -> std::io::Result<()> { let mut offset = 0; while offset < bytes.len() { @@ -455,7 +475,7 @@ fn write_input( Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()), Ok(count) => offset += count, Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)) + wait_writable()?; } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} Err(error) => return Err(error), @@ -471,7 +491,7 @@ fn write_input( driver.source().check().map_err(std::io::Error::other)?; match writer.flush() { Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)) + wait_writable()?; } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} result => return result, diff --git a/crates/local/src/readiness.rs b/crates/local/src/readiness.rs index 91f82732..93d2baba 100644 --- a/crates/local/src/readiness.rs +++ b/crates/local/src/readiness.rs @@ -65,22 +65,40 @@ impl Readiness { Ok(()) } - pub(super) fn wait(&self) -> io::Result<()> { - let mut descriptors = vec![ - PollFd::new(self.pty.as_fd(), PollFlags::POLLIN), - PollFd::new(self.closing.as_fd(), PollFlags::POLLIN), - ]; - if let Some(leader) = &self.leader { - descriptors.push(PollFd::new(leader.as_fd(), PollFlags::POLLIN)); + pub(super) fn wait_readable(&self) -> io::Result<()> { + self.wait(PollFlags::POLLIN, false).map(|_| ()) + } + + pub(super) fn wait_writable(&self, restricted: bool) -> io::Result<()> { + if self.wait(PollFlags::POLLOUT, restricted)? { + return Err(io::Error::new(io::ErrorKind::Interrupted, "PTY closed")); } - let timeout = if self.leader.is_some() { + Ok(()) + } + + fn wait(&self, interest: PollFlags, restricted: bool) -> io::Result { + let pty = PollFd::new(self.pty.as_fd(), interest); + let closing = PollFd::new(self.closing.as_fd(), PollFlags::POLLIN); + // Authority revocation has no descriptor, so restricted writes still recheck it. + let timeout = if self.leader.is_some() && !restricted { PollTimeout::NONE } else { PollTimeout::from(10u16) }; - match poll(&mut descriptors, timeout) { - Ok(_) | Err(Errno::EINTR) => Ok(()), - Err(error) => Err(error.into()), + if let Some(leader) = &self.leader { + let leader = PollFd::new(leader.as_fd(), PollFlags::POLLIN); + return wait(&mut [pty, closing, leader], timeout); } + wait(&mut [pty, closing], timeout) + } +} + +fn wait(descriptors: &mut [PollFd<'_>], timeout: PollTimeout) -> io::Result { + match poll(descriptors, timeout) { + Ok(_) => Ok(descriptors[1..] + .iter() + .any(|fd| fd.revents().is_some_and(|events| !events.is_empty()))), + Err(Errno::EINTR) => Ok(false), + Err(error) => Err(error.into()), } } diff --git a/crates/local/src/tests.rs b/crates/local/src/tests.rs index 83c6c18c..d67b8bb2 100644 --- a/crates/local/src/tests.rs +++ b/crates/local/src/tests.rs @@ -634,12 +634,29 @@ fn background_hangup_ignoring_job_cannot_block_close() { #[cfg(unix)] #[test] fn large_input_survives_nonblocking_backpressure_without_partial_writes() { + measure_pty_input(500_000, "sleep 0.2;"); +} + +#[test] +#[ignore = "native PTY performance fixture; run alone in both builds"] +fn measure_large_input_delivery_to_a_native_pty() { + for _ in 0..9 { + let elapsed = measure_pty_input(1024 * 1024, ""); + writeln!( + std::io::stdout().lock(), + "1 MiB input delivery: {:.3} ms", + elapsed.as_secs_f64() * 1_000.0 + ) + .unwrap(); + } +} + +fn measure_pty_input(count: usize, delay: &str) -> std::time::Duration { + let command = + format!("stty raw -echo; printf ready-input; {delay} head -c {count} | tr -cd x | wc -c"); let launch = ShellLaunch { program: Some("/bin/sh".into()), - args: vec![ - "-c".into(), - "stty raw -echo; printf ready-input; sleep 0.2; head -c 500000 | wc -c".into(), - ], + args: vec!["-c".into(), command], integration: false, ..Default::default() }; @@ -651,23 +668,26 @@ fn large_input_survives_nonblocking_backpressure_without_partial_writes() { out.extend(bytes); } } - assert!(session.input(vec![b'x'; 500_000])); + let input = vec![b'x'; count]; + let start = std::time::Instant::now(); + assert!(session.input(input)); out.clear(); - loop { - match next(&rx) { - Event::Output(bytes) => out.extend(bytes), - Event::Closed(reason) => { - assert_eq!(reason, CloseReason::Exited(Some(0))); - break; + let received = loop { + if let Event::Output(bytes) = next(&rx) { + out.extend(bytes); + if out.ends_with(b"\n") { + break start.elapsed(); } - _ => {} + } + }; + loop { + if let Event::Closed(reason) = next(&rx) { + assert_eq!(reason, CloseReason::Exited(Some(0))); + break; } } - assert!( - String::from_utf8_lossy(&out).contains("500000"), - "lost/repeated input bytes: {}", - String::from_utf8_lossy(&out) - ); + assert_eq!(String::from_utf8_lossy(&out).trim(), count.to_string()); + received } #[cfg(target_os = "linux")] diff --git a/crates/local/src/tests/leader_exit.rs b/crates/local/src/tests/leader_exit.rs index fadb8828..0eb3447b 100644 --- a/crates/local/src/tests/leader_exit.rs +++ b/crates/local/src/tests/leader_exit.rs @@ -1,6 +1,6 @@ //! A child-exit wake is independent from slave EOF and preserves the leader's tail. use super::*; -use std::time::Instant; +use std::time::{Duration, Instant}; #[test] fn an_exited_leader_closes_after_its_tail_even_when_a_child_holds_the_slave() { diff --git a/crates/localfs/src/cursor.rs b/crates/localfs/src/cursor.rs index b7dc0be4..d39e7935 100644 --- a/crates/localfs/src/cursor.rs +++ b/crates/localfs/src/cursor.rs @@ -22,8 +22,7 @@ pub(crate) fn open(directory: &DirectoryCapability) -> LocalResult LocalResult> { #[cfg(unix)] - let entries = rustix::fs::Dir::read_from(directory.file()) - .map_err(|error| LocalFsError::from_io(directory.path(), error.into()))?; + let entries = read_unix(directory)?; #[cfg(not(unix))] let entries = std::fs::read_dir(directory.path()) .map_err(|error| LocalFsError::from_io(directory.path(), error))?; @@ -32,6 +31,11 @@ pub(crate) fn open(directory: &DirectoryCapability) -> LocalResult LocalResult { + rustix::fs::Dir::read_from(directory.file()) + .map_err(|error| LocalFsError::from_io(directory.path(), error.into())) +} #[cfg(not(windows))] impl LocalCursor for Cursor { fn next(&mut self) -> LocalResult> { diff --git a/crates/localfs/src/lib.rs b/crates/localfs/src/lib.rs index aeeac899..833c4b24 100644 --- a/crates/localfs/src/lib.rs +++ b/crates/localfs/src/lib.rs @@ -73,6 +73,16 @@ impl LocalFs for LocalFilesystem { ) -> LocalResult { listing::browse(&self.resolve(path), limits, cancel) } + #[cfg(target_os = "linux")] + fn browse_entries( + &self, + path: &Path, + limits: ListingLimits, + cancel: &CancelFlag, + purpose: BrowsePurpose, + ) -> LocalResult { + listing::browse_entries(&self.resolve(path), limits, cancel, purpose) + } fn open_directory(&self, path: &Path) -> LocalResult> { Ok(Arc::new(directory::DirectoryCapability::strict( &self.resolve(path), diff --git a/crates/localfs/src/listing.rs b/crates/localfs/src/listing.rs index dcc49448..e116d28c 100644 --- a/crates/localfs/src/listing.rs +++ b/crates/localfs/src/listing.rs @@ -42,3 +42,85 @@ pub(crate) fn browse( entries, }) } + +#[cfg(target_os = "linux")] +pub(crate) fn browse_entries( + path: &Path, + limits: ListingLimits, + cancel: &CancelFlag, + purpose: BrowsePurpose, +) -> LocalResult { + use rustix::fs::{AtFlags, statat}; + use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _}; + + cancel.check()?; + let directory = DirectoryCapability::browse(path)?; + let cursor = crate::cursor::read_unix(&directory)?; + let mut entries = Vec::new(); + let mut name_bytes = 0usize; + let mut count = 0; + for entry in cursor { + let entry = entry.map_err(|error| LocalFsError::from_io(path, error.into()))?; + let bytes = entry.file_name().to_bytes(); + if matches!(bytes, b"." | b"..") { + continue; + } + cancel.check()?; + let name = OsStr::from_bytes(bytes); + // Reading directory records alone need not authorize looking up their names. + if count == 0 { + statat(directory.file(), c".", AtFlags::SYMLINK_NOFOLLOW) + .map_err(|error| LocalFsError::from_io(path.join(name), error.into()))?; + } + let (kind, is_symlink) = entry_kind(&directory, name, entry.file_type())?; + count += 1; + name_bytes = name_bytes.saturating_add(name.to_string_lossy().len()); + if count > limits.entries() || name_bytes > limits.name_bytes() { + return Err(LocalFsError::BoundExceeded("Explorer listing")); + } + if purpose == BrowsePurpose::Files + || kind == EntryKind::Directory + || is_symlink && directory.target_is_directory(name) + { + entries.push(LocalEntry { + name: name.to_owned(), + kind, + is_symlink, + }); + } + } + cancel.check()?; + entries.sort_by_cached_key(|entry| { + ( + entry.kind != EntryKind::Directory, + entry.name.to_string_lossy().to_lowercase(), + entry.name.clone(), + ) + }); + cancel.check()?; + Ok(LocalEntries { + directory: path.to_owned(), + entries, + }) +} + +#[cfg(target_os = "linux")] +fn entry_kind( + directory: &DirectoryCapability, + name: &std::ffi::OsStr, + kind: rustix::fs::FileType, +) -> LocalResult<(EntryKind, bool)> { + use rustix::fs::FileType; + Ok(match kind { + FileType::Unknown => { + let metadata = directory + .inspect(name)? + .ok_or_else(|| LocalFsError::NotFound(directory.path().join(name)))?; + (metadata.kind, metadata.is_symlink) + } + FileType::Directory => (EntryKind::Directory, false), + FileType::RegularFile => (EntryKind::File, false), + FileType::Symlink => (EntryKind::Other, true), + _ => (EntryKind::Other, false), + }) +} diff --git a/crates/localfs/src/scan.rs b/crates/localfs/src/scan.rs index 6df610fe..6ee123f4 100644 --- a/crates/localfs/src/scan.rs +++ b/crates/localfs/src/scan.rs @@ -30,10 +30,11 @@ impl Frame { let Some(name) = self.cursor.next()? else { return Ok(Step::Finished); }; - let path = self.directory.location().join(&name); + let entry_path = || self.directory.location().join(&name); let metadata = match self.directory.metadata(&name) { Ok(Some(metadata)) => metadata, Ok(None) => { + let path = entry_path(); return Ok(failed_entry( count, path.clone(), @@ -41,14 +42,14 @@ impl Frame { )); } Err(error) => { - return Ok(failed_entry(count, path, error)); + return Ok(failed_entry(count, entry_path(), error)); } }; match count.observe(&metadata, self.depth + 1, self.depth == 0, &name) { ScanDecision::Enter => match self.directory.child(&name) { Ok(child) => Ok(Step::Child(child)), Err(error) => { - count.record_failure(path, error); + count.record_failure(entry_path(), error); Ok(Step::Skip) } }, diff --git a/crates/localfs/src/source.rs b/crates/localfs/src/source.rs index 51d2dbaf..657404de 100644 --- a/crates/localfs/src/source.rs +++ b/crates/localfs/src/source.rs @@ -6,9 +6,30 @@ use std::{ path::{Path, PathBuf}, }; +const MAX_SOURCE_CHUNK: usize = 32 * 1024; +#[cfg(target_os = "linux")] +const SMALL_SOURCE_LIMIT: usize = 4 * 1024; + struct Source { file: File, path: PathBuf, + #[cfg(target_os = "linux")] + small: bool, +} + +#[cfg(target_os = "linux")] +impl Source { + // Keep the scratch buffer off the path for ordinary large reads. + #[inline(never)] + fn read_small(&mut self, max_bytes: usize) -> LocalResult> { + let mut scratch = [std::mem::MaybeUninit::uninit(); MAX_SOURCE_CHUNK]; + let (bytes, _) = rustix::io::read(&self.file, &mut scratch[..max_bytes]) + .map_err(|error| LocalFsError::from_io(&self.path, error.into()))?; + // A source can grow after opening. Return this read in full and then + // read directly into the returned buffer for subsequent chunks. + self.small = bytes.len() <= SMALL_SOURCE_LIMIT; + Ok(bytes.to_vec()) + } } pub(crate) fn open(path: &Path) -> LocalResult> { let (directory, name) = parent(path)?; @@ -75,6 +96,8 @@ pub(crate) fn open_relative( Ok(Box::new(Source { file, path: path.to_owned(), + #[cfg(target_os = "linux")] + small: metadata.len() <= SMALL_SOURCE_LIMIT as u64, })) } impl LocalSource for Source { @@ -85,9 +108,13 @@ impl LocalSource for Source { .map_err(|error| LocalFsError::from_io(&self.path, error)) } fn read(&mut self, max_bytes: usize) -> LocalResult> { - if max_bytes == 0 || max_bytes > 32 * 1024 { + if max_bytes == 0 || max_bytes > MAX_SOURCE_CHUNK { return Err(LocalFsError::BoundExceeded("source chunk")); } + #[cfg(target_os = "linux")] + if self.small && max_bytes > SMALL_SOURCE_LIMIT { + return self.read_small(max_bytes); + } let mut bytes = vec![0; max_bytes]; let count = self .file diff --git a/crates/localfs/src/stage.rs b/crates/localfs/src/stage.rs index c7ad33c3..5c24211a 100644 --- a/crates/localfs/src/stage.rs +++ b/crates/localfs/src/stage.rs @@ -6,6 +6,9 @@ use rustix::fs::{self, AtFlags, Mode, OFlags}; use std::ffi::OsString; use std::{ffi::OsStr, io::Write}; +#[cfg(unix)] +const HEX: &[u8; 16] = b"0123456789abcdef"; + struct Stage { directory: DirectoryCapability, #[cfg(unix)] @@ -24,13 +27,13 @@ pub(crate) fn create(directory: DirectoryCapability) -> LocalResult() - ); + let mut name = String::with_capacity(".nocterm-.part".len() + bytes.len() * 2); + name.push_str(".nocterm-"); + for byte in bytes { + name.push(char::from(HEX[usize::from(byte >> 4)])); + name.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + name.push_str(".part"); let fd = match fs::openat( directory.file(), name.as_str(), @@ -154,19 +157,17 @@ impl LocalStage for Stage { if bytes.len() > 32 * 1024 { return Err(LocalFsError::BoundExceeded("stage chunk")); } - let path = self.directory.path().to_owned(); self.file_mut()? .write_all(bytes) - .map_err(|error| LocalFsError::from_io(path, error))?; + .map_err(|error| LocalFsError::from_io(self.directory.path(), error))?; self.synced = false; Ok(()) } fn sync(&mut self) -> LocalResult<()> { self.writable()?; - let path = self.directory.path().to_owned(); self.file_mut()? .sync_all() - .map_err(|error| LocalFsError::from_io(path, error))?; + .map_err(|error| LocalFsError::from_io(self.directory.path(), error))?; self.synced = true; Ok(()) } diff --git a/crates/localfs/src/stage/windows.rs b/crates/localfs/src/stage/windows.rs index 351f4d1c..b8b36a8f 100644 --- a/crates/localfs/src/stage/windows.rs +++ b/crates/localfs/src/stage/windows.rs @@ -49,19 +49,17 @@ impl LocalStage for Stage { if bytes.len() > 32 * 1024 { return Err(LocalFsError::BoundExceeded("stage chunk")); } - let path = self.directory.path().to_owned(); self.file_mut()? .write_all(bytes) - .map_err(|error| LocalFsError::from_io(path, error))?; + .map_err(|error| LocalFsError::from_io(self.directory.path(), error))?; self.synced = false; Ok(()) } fn sync(&mut self) -> LocalResult<()> { self.writable()?; - let path = self.directory.path().to_owned(); self.file_mut()? .sync_all() - .map_err(|error| LocalFsError::from_io(path, error))?; + .map_err(|error| LocalFsError::from_io(self.directory.path(), error))?; self.synced = true; Ok(()) } diff --git a/crates/localfs/tests/capabilities.rs b/crates/localfs/tests/capabilities.rs index 70922b85..a9ba5ffe 100644 --- a/crates/localfs/tests/capabilities.rs +++ b/crates/localfs/tests/capabilities.rs @@ -89,6 +89,38 @@ fn listing_and_sources_preserve_names_bounds_and_same_opened_metadata() { )); } +#[cfg(target_os = "linux")] +#[test] +fn reading_a_small_source_at_eof_can_see_later_appends() { + const CHUNK: usize = 32 * 1024; + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("source"); + std::fs::write(&path, b"start").unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + let mut source = fs.open_source(&path).unwrap(); + for bound in [0, CHUNK + 1] { + assert!(matches!( + source.read(bound), + Err(LocalFsError::BoundExceeded("source chunk")) + )); + } + assert_eq!(source.read(CHUNK).unwrap(), b"start"); + assert!(source.read(CHUNK).unwrap().is_empty()); + assert!(source.read(CHUNK).unwrap().is_empty()); + + let appended = vec![b'x'; CHUNK + 5]; + std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(&appended) + .unwrap(); + assert_eq!(source.read(CHUNK).unwrap(), appended[..CHUNK]); + assert_eq!(source.read(CHUNK).unwrap(), appended[CHUNK..]); + assert!(source.read(CHUNK).unwrap().is_empty()); + source.close().unwrap(); +} + #[cfg(unix)] #[test] fn browsing_links_is_read_only_and_strict_handles_survive_ancestor_swaps() { @@ -165,10 +197,9 @@ fn fifo_replacement_is_rejected_without_waiting_for_a_writer() { std::fs::write(&source, b"regular").unwrap(); assert!(std::fs::metadata(&source).unwrap().is_file()); std::fs::remove_file(&source).unwrap(); - rustix::fs::mkfifoat( - rustix::fs::CWD, + nix::unistd::mkfifo( &source, - rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR, + nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR, ) .unwrap(); let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); diff --git a/crates/localfs/tests/listing_projection.rs b/crates/localfs/tests/listing_projection.rs new file mode 100644 index 00000000..9e0c0cfe --- /dev/null +++ b/crates/localfs/tests/listing_projection.rs @@ -0,0 +1,192 @@ +use nocterm_localfs::LocalFilesystem; +use nocterm_session::local_fs::{BrowsePurpose, CancelFlag, ListingLimits, LocalFs, LocalFsError}; +use std::{fs, path::Path}; + +const PURPOSES: [BrowsePurpose; 2] = [BrowsePurpose::Files, BrowsePurpose::DirectoryCompletion]; + +#[test] +fn projected_listings_keep_native_order_and_charge_skipped_names_to_both_bounds() { + let root = tempfile::tempdir().unwrap(); + fs::create_dir(root.path().join("Beta")).unwrap(); + fs::create_dir(root.path().join("alpha")).unwrap(); + fs::write(root.path().join("long-regular-file"), b"content").unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + + for purpose in PURPOSES { + let relative = Path::new("."); + let cancel = CancelFlag::default(); + let complete = fs.browse(relative, Default::default(), &cancel).unwrap(); + let projected = fs + .browse_entries(relative, Default::default(), &cancel, purpose) + .unwrap(); + assert_eq!(projected, complete.project(purpose)); + assert_eq!(projected.entries[0].name, "alpha"); + assert_eq!(projected.entries[1].name, "Beta"); + for limits in [ + ListingLimits::new(2, 100).unwrap(), + ListingLimits::new(3, 9).unwrap(), + ] { + assert!(matches!( + fs.browse_entries(relative, limits, &cancel, purpose), + Err(LocalFsError::BoundExceeded(_)) + )); + } + assert!(matches!( + fs.browse_entries(Path::new("missing"), Default::default(), &cancel, purpose), + Err(LocalFsError::NotFound(_)) + )); + assert!( + fs.browse_entries( + Path::new("long-regular-file"), + Default::default(), + &cancel, + purpose, + ) + .is_err() + ); + cancel.cancel(); + assert!(matches!( + fs.browse_entries(relative, Default::default(), &cancel, purpose), + Err(LocalFsError::Cancelled) + )); + } +} + +#[cfg(unix)] +#[test] +fn projected_listings_keep_link_identity_and_complete_only_directory_targets() { + use std::{ + ffi::OsStr, + os::unix::{ffi::OsStrExt as _, fs::symlink}, + }; + + let root = tempfile::tempdir().unwrap(); + let folder = root.path().join("folder"); + let non_utf8 = OsStr::from_bytes(b"native-\xff"); + fs::create_dir(&folder).unwrap(); + fs::create_dir(root.path().join(non_utf8)).unwrap(); + fs::write(folder.join("file"), b"").unwrap(); + symlink("folder", root.path().join("a-directory-link")).unwrap(); + symlink("folder/file", root.path().join("b-file-link")).unwrap(); + symlink("missing", root.path().join("c-dangling")).unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + let cancel = CancelFlag::default(); + let relative = Path::new("a-directory-link/.."); + let complete = fs.browse(relative, Default::default(), &cancel).unwrap(); + + for purpose in PURPOSES { + let projected = fs + .browse_entries(relative, Default::default(), &cancel, purpose) + .unwrap(); + assert_eq!(projected.directory, root.path().join(relative)); + assert_eq!(projected.entries[1].name, non_utf8); + assert_eq!(projected.entries[2].name, "a-directory-link"); + assert!(projected.entries[2].is_symlink); + assert_eq!( + projected.entries.len(), + if purpose == BrowsePurpose::Files { + 5 + } else { + 3 + } + ); + assert_eq!( + projected.entries, + fs.browse(relative, Default::default(), &cancel) + .unwrap() + .project(purpose) + .entries + ); + } + assert!(fs.open_directory(Path::new("a-directory-link")).is_err()); + assert_eq!(complete.entries.len(), 5); +} + +#[cfg(unix)] +#[test] +fn projected_listings_preserve_typed_directory_access_denials() { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("private"); + fs::create_dir(&target).unwrap(); + fs::write(target.join("file"), b"").unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + let cancel = CancelFlag::default(); + + for mode in [0o400, 0o100] { + fs::set_permissions(&target, fs::Permissions::from_mode(mode)).unwrap(); + let complete = fs.browse(&target, Default::default(), &cancel); + let actual = PURPOSES + .map(|purpose| fs.browse_entries(&target, Default::default(), &cancel, purpose)); + fs::set_permissions(&target, fs::Permissions::from_mode(0o700)).unwrap(); + for (purpose, actual) in PURPOSES.into_iter().zip(actual) { + match &complete { + Err(LocalFsError::PermissionDenied(_)) => { + assert!(matches!(actual, Err(LocalFsError::PermissionDenied(_)))); + } + // A test running as root can still access the fixture. + Ok(complete) => assert_eq!(actual.unwrap(), complete.clone().project(purpose)), + Err(error) => panic!("unexpected full-listing failure: {error}"), + } + } + } +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "manual native directory enumeration performance fixture"] +fn measure_full_metadata_and_projected_native_listings() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let root = tempfile::tempdir().unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + let cancel = CancelFlag::default(); + for (count, directory_period) in [(32, 8), (2_048, 8), (32_768, 64), (32_768, 4)] { + let workload = root.path().join(format!("{count}-{directory_period}")); + seed_workload(&workload, count, directory_period); + for purpose in PURPOSES { + let full = || { + fs.browse(&workload, Default::default(), &cancel) + .unwrap() + .project(purpose) + }; + let projected = || { + fs.browse_entries(&workload, Default::default(), &cancel, purpose) + .unwrap() + }; + let expected = full(); + assert_eq!(projected(), expected); + for pair in 0..12 { + for offset in 0..2 { + let before = (pair + offset) % 2 == 0; + let start = Instant::now(); + let result = black_box(if before { full() } else { projected() }); + let elapsed = start.elapsed().as_nanos(); + assert_eq!(result, expected); + writeln!( + std::io::stdout().lock(), + "{count} {directory_period} {purpose:?} {before} {elapsed}" + ) + .unwrap(); + } + } + } + } +} + +#[cfg(target_os = "linux")] +fn seed_workload(directory: &Path, count: usize, period: usize) { + use std::os::unix::fs::symlink; + + fs::create_dir(directory).unwrap(); + for index in 0..count { + let prefix = if index % 2 == 0 { "Entry" } else { "entry" }; + let path = directory.join(format!("{prefix}-{index:06}")); + match index % period { + 0 => fs::create_dir(path).unwrap(), + 1 => symlink("Entry-000000", path).unwrap(), + _ => fs::write(path, b"").unwrap(), + } + } +} diff --git a/crates/localfs/tests/publication.rs b/crates/localfs/tests/publication.rs index 8b31ac11..cd402082 100644 --- a/crates/localfs/tests/publication.rs +++ b/crates/localfs/tests/publication.rs @@ -5,6 +5,56 @@ use nocterm_session::{ }; use std::ffi::OsStr; +#[test] +#[ignore = "manual native staging and publication performance fixture"] +fn measure_small_publications_and_streamed_writes() { + use std::{ + io::{self, Write}, + time::{Duration, Instant}, + }; + + let root = tempfile::tempdir().unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + let directory = fs.open_directory(root.path()).unwrap(); + for (files, chunks, chunk_size) in [(128, 1, 128), (2, 256, 32 * 1024)] { + let chunk = vec![0x5a; chunk_size]; + let mut create = Duration::ZERO; + let mut write = Duration::ZERO; + let mut file_sync = Duration::ZERO; + let mut publish = Duration::ZERO; + for index in 0..files { + let name = format!("output-{chunks}-{index}"); + let began = Instant::now(); + let mut stage = directory.stage().unwrap(); + create += began.elapsed(); + let began = Instant::now(); + for _ in 0..chunks { + stage.write(&chunk).unwrap(); + } + write += began.elapsed(); + let began = Instant::now(); + stage.sync().unwrap(); + file_sync += began.elapsed(); + let began = Instant::now(); + assert!(matches!( + stage + .publish(OsStr::new(&name), UploadMode::Create) + .unwrap(), + PublicationOutcome::Published + )); + publish += began.elapsed(); + let contents = std::fs::read(root.path().join(name)).unwrap(); + assert_eq!(contents.len(), chunks * chunk_size); + assert!(contents.iter().all(|&byte| byte == 0x5a)); + } + writeln!( + io::stdout().lock(), + "{files} files, {chunks} chunks of {chunk_size} B: create={create:?}, write={write:?}, file sync={file_sync:?}, publish={publish:?}" + ) + .unwrap(); + } +} + #[test] fn staging_preserves_old_file_handles_collision_and_does_not_publish_on_drop() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/localfs/tests/statistics.rs b/crates/localfs/tests/statistics.rs index f0e1deaa..cb5b38a4 100644 --- a/crates/localfs/tests/statistics.rs +++ b/crates/localfs/tests/statistics.rs @@ -87,3 +87,51 @@ fn skipped_symlinks_cannot_bypass_the_entry_walk_limit() { assert_eq!(result.inaccessible, 1); assert!(result.complete); } + +#[test] +#[ignore = "manual timing of native recursive directory statistics"] +fn measure_native_folder_statistics() { + use std::{io::Write as _, time::Instant}; + + for (count, nested) in [(32, false), (16_384, false), (16_384, true)] { + let root = tempfile::tempdir().unwrap(); + let fs = LocalFilesystem::with_base(root.path().to_owned()).unwrap(); + let policy = ScanPolicy::new(vec![], 100_000, 256).unwrap(); + for index in 0..count { + let directory = if nested { + let path = root.path().join(format!("group-{}", index / 256)); + if index % 256 == 0 { + std::fs::create_dir(&path).unwrap(); + } + path + } else { + root.path().to_owned() + }; + std::fs::write(directory.join(format!("file-{index:05}")), b"x").unwrap(); + } + + let mut elapsed = Vec::new(); + for _ in 0..10 { + let start = Instant::now(); + let result = fs + .scan(root.path(), &policy, &CancelFlag::default(), &|_| {}) + .unwrap(); + elapsed.push(start.elapsed()); + assert!(result.complete); + assert!(result.errors.is_empty()); + let (files, directories) = if nested { (0, count / 256) } else { (count, 0) }; + assert_eq!( + (result.files, result.directories, result.bytes), + (files, directories, count) + ); + } + elapsed.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} files, nested={nested}, scan p50={:?}, max={:?}", + elapsed[elapsed.len() / 2], + elapsed.last().unwrap(), + ) + .unwrap(); + } +} diff --git a/crates/localfs/tests/windows_held.rs b/crates/localfs/tests/windows_held.rs new file mode 100644 index 00000000..bafd6f9b --- /dev/null +++ b/crates/localfs/tests/windows_held.rs @@ -0,0 +1,168 @@ +//! Windows strict capabilities hold their ancestry and refuse reparse points. +#![cfg(windows)] +use nocterm_localfs::LocalFilesystem; +use nocterm_session::{ + fs::UploadMode, + local_fs::{LocalDirectory, LocalFs, LocalFsError, PublicationOutcome}, +}; +use std::{ffi::OsStr, path::Path, process::Command, sync::Arc}; + +fn filesystem(root: &Path) -> LocalFilesystem { + LocalFilesystem::with_base(root.to_owned()).unwrap() +} +fn junction(link: &Path, target: &Path) { + let status = Command::new("cmd") + .arg("/C") + .arg("mklink") + .arg("/J") + .arg(link) + .arg(target) + .status() + .unwrap(); + assert!(status.success(), "mklink /J failed"); +} +fn publish(directory: &Arc, name: &str, bytes: &[u8]) { + let mut stage = directory.stage().unwrap(); + stage.write(bytes).unwrap(); + stage.sync().unwrap(); + assert!(matches!( + stage + .publish(OsStr::new(name), UploadMode::Replace) + .unwrap(), + PublicationOutcome::Published | PublicationOutcome::PublishedWithWarning(_) + )); +} + +#[test] +fn strict_directories_have_native_identity_and_pin_every_ancestor() { + let root = tempfile::tempdir().unwrap(); + let root_path = std::fs::canonicalize(root.path()).unwrap(); + std::fs::create_dir_all(root_path.join("a").join("b")).unwrap(); + let fs = filesystem(&root_path); + let held = fs.open_directory(&root_path.join("a").join("b")).unwrap(); + assert!(held.identity().is_held()); + let child = held.create_child(OsStr::new("c")).unwrap(); + assert!(child.identity().is_held()); + assert_ne!(held.identity(), child.identity()); + assert_eq!( + fs.open_directory(&root_path.join("a").join("b").join("c")) + .unwrap() + .identity(), + child.identity() + ); + // Neither the leaf nor an ancestor can be renamed away while it is held. + assert!( + std::fs::rename( + root_path.join("a").join("b").join("c"), + root_path.join("moved-c") + ) + .is_err() + ); + assert!(std::fs::rename(root_path.join("a"), root_path.join("moved-a")).is_err()); + drop(child); + drop(held); + std::fs::rename(root_path.join("a"), root_path.join("moved-a")).unwrap(); +} + +#[test] +fn junctions_are_refused_as_roots_ancestors_and_generated_children() { + let root = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let root_path = std::fs::canonicalize(root.path()).unwrap(); + std::fs::write(outside.path().join("secret.json"), b"secret").unwrap(); + junction(&root_path.join("link"), outside.path()); + let fs = filesystem(&root_path); + assert!(matches!( + fs.open_directory(&root_path.join("link")), + Err(LocalFsError::LinkRefused(_)) + )); + assert!(matches!( + fs.open_directory(&root_path.join("link").join("inner")), + Err(LocalFsError::LinkRefused(_) | LocalFsError::NotFound(_)) + )); + let directory = fs.open_directory(&root_path).unwrap(); + for create in [false, true] { + let opened = if create { + directory.create_child(OsStr::new("link")) + } else { + directory.child(OsStr::new("link")) + }; + assert!(matches!(opened, Err(LocalFsError::LinkRefused(_)))); + } + assert!( + directory + .metadata(OsStr::new("link")) + .unwrap() + .unwrap() + .is_symlink + ); + assert!(matches!( + directory.open_source(OsStr::new("link")), + Err(LocalFsError::NotRegular(_) | LocalFsError::LinkRefused(_)) + )); + assert_eq!( + std::fs::read(outside.path().join("secret.json")).unwrap(), + b"secret" + ); +} + +#[test] +fn staged_publication_replaces_atomically_and_cancel_leaves_the_old_document() { + let root = tempfile::tempdir().unwrap(); + let root_path = std::fs::canonicalize(root.path()).unwrap(); + let fs = filesystem(&root_path); + let directory = fs + .open_directory(&root_path) + .unwrap() + .create_child(OsStr::new("history")) + .unwrap(); + publish(&directory, "chat.json", b"first"); + publish(&directory, "chat.json", b"second"); + assert_eq!( + std::fs::read(root_path.join("history").join("chat.json")).unwrap(), + b"second" + ); + let mut stage = directory.stage().unwrap(); + stage.write(b"interrupted").unwrap(); + stage.cancel().unwrap(); + assert_eq!( + std::fs::read(root_path.join("history").join("chat.json")).unwrap(), + b"second" + ); + let mut names = Vec::new(); + let mut entries = directory.entries().unwrap(); + while let Some(name) = entries.next().unwrap() { + names.push(name); + } + assert_eq!(names, vec![std::ffi::OsString::from("chat.json")]); + let mut source = directory.open_source(OsStr::new("chat.json")).unwrap(); + assert_eq!(source.read(1024).unwrap(), b"second"); + directory.remove_file(OsStr::new("chat.json")).unwrap(); + assert!( + directory + .metadata(OsStr::new("chat.json")) + .unwrap() + .is_none() + ); +} + +#[test] +fn a_read_only_target_is_reported_as_a_failed_write_without_losing_the_old_document() { + let root = tempfile::tempdir().unwrap(); + let root_path = std::fs::canonicalize(root.path()).unwrap(); + let fs = filesystem(&root_path); + let directory = fs.open_directory(&root_path).unwrap(); + publish(&directory, "chat.json", b"kept"); + let target = root_path.join("chat.json"); + let original = std::fs::metadata(&target).unwrap().permissions(); + let mut read_only = original.clone(); + read_only.set_readonly(true); + std::fs::set_permissions(&target, read_only).unwrap(); + let mut stage = directory.stage().unwrap(); + stage.write(b"replacement").unwrap(); + let refused = stage.publish(OsStr::new("chat.json"), UploadMode::Replace); + assert!(refused.is_err()); + stage.cancel().unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"kept"); + std::fs::set_permissions(&target, original).unwrap(); +} diff --git a/crates/monitor-service/src/tests.rs b/crates/monitor-service/src/tests.rs index 6b79312c..0bb3ab80 100644 --- a/crates/monitor-service/src/tests.rs +++ b/crates/monitor-service/src/tests.rs @@ -5,6 +5,8 @@ use nocterm_monitor::{MetricSet, MonitorMetric, Platform}; use nocterm_session::{ExecExit, HostExec, testing::FakeExec}; use std::{sync::Arc, time::Duration}; +mod recovery; + fn plan(metric: MonitorMetric, seconds: u64) -> WatchPlan { WatchPlan { metrics: [metric].into_iter().collect(), diff --git a/crates/monitor-service/src/tests/recovery.rs b/crates/monitor-service/src/tests/recovery.rs new file mode 100644 index 00000000..2ef15a39 --- /dev/null +++ b/crates/monitor-service/src/tests/recovery.rs @@ -0,0 +1,163 @@ +use super::*; +use crate::MonitorWatch; +use gpui::Entity; +use nocterm_session::ExecSink; + +fn subscribe(exec: &Arc, cx: &mut TestAppContext) -> (Entity, Entity<()>) { + let registry = MonitorWatches::default(); + let result = cx.update(|cx| { + let consumer = cx.new(|_| ()); + let watch = registry.watch(exec.clone(), false, Some(Platform::Linux), cx); + watch.update(cx, |watch, cx| { + watch.subscribe(consumer.entity_id(), plan(MonitorMetric::Memory, 2), cx) + }); + (watch, consumer) + }); + cx.run_until_parked(); + result +} + +fn sample(sink: &ExecSink, available: u32, cx: &mut TestAppContext) { + futures::executor::block_on(sink.send( + format!("@@meminfo\nMemTotal: 1000\nMemAvailable: {available}\n@@end\n").into_bytes(), + )); + cx.run_until_parked(); +} + +fn advance(duration: Duration, cx: &mut TestAppContext) { + cx.executor().advance_clock(duration); + cx.run_until_parked(); +} + +fn stop(sink: ExecSink, cx: &mut TestAppContext) { + sink.finish(ExecExit::default()); + drop(sink); + cx.run_until_parked(); +} + +fn pause(seconds: u64, cx: &mut TestAppContext) { + advance(Duration::from_secs(seconds), cx); +} + +#[gpui::test] +fn a_running_monitor_resumes_with_a_new_reading_after_one_second(cx: &mut TestAppContext) { + let exec = Arc::new(FakeExec::default()); + let ended = exec.queue_stream("sh"); + let restarted = exec.queue_stream("sh"); + let (watch, _consumer) = subscribe(&exec, cx); + + sample(&ended, 250, cx); + pause(1, cx); + sample(&ended, 251, cx); + stop(ended, cx); + watch.read_with(cx, |watch, _| { + assert!(matches!(watch.status(), WatchStatus::Failed(_))) + }); + + advance(Duration::from_millis(999), cx); + assert_eq!(exec.requests().len(), 1); + advance(Duration::from_millis(1), cx); + assert_eq!(exec.requests().len(), 2); + sample(&restarted, 300, cx); + watch.read_with(cx, |watch, _| { + assert_eq!(watch.status(), &WatchStatus::Running); + assert_eq!( + watch.reading().unwrap().1.memory, + Some((1000 * 1024, 300 * 1024)) + ); + }); +} + +#[gpui::test] +fn another_short_run_waits_ten_seconds_and_sustained_collection_rearms_recovery( + cx: &mut TestAppContext, +) { + let exec = Arc::new(FakeExec::default()); + let first = exec.queue_stream("sh"); + let short = exec.queue_stream("sh"); + let sustained = exec.queue_stream("sh"); + let resumed = exec.queue_stream("sh"); + let (_watch, _consumer) = subscribe(&exec, cx); + + sample(&first, 200, cx); + pause(1, cx); + sample(&first, 201, cx); + stop(first, cx); + pause(1, cx); + assert_eq!(exec.requests().len(), 2); + + sample(&short, 202, cx); + pause(1, cx); + sample(&short, 203, cx); + stop(short, cx); + pause(9, cx); + assert_eq!(exec.requests().len(), 2); + pause(1, cx); + assert_eq!(exec.requests().len(), 3); + + sample(&sustained, 204, cx); + pause(10, cx); + sample(&sustained, 205, cx); + stop(sustained, cx); + pause(1, cx); + assert_eq!(exec.requests().len(), 4); + assert!(!resumed.is_closed()); +} + +#[gpui::test] +fn burst_only_collector_waits_ten_seconds_and_unsubscribe_cancels_recovery( + cx: &mut TestAppContext, +) { + let exec = Arc::new(FakeExec::default()); + let burst = exec.queue_stream("sh"); + let retry = exec.queue_stream("sh"); + let (watch, consumer) = subscribe(&exec, cx); + + sample(&burst, 250, cx); + sample(&burst, 260, cx); + stop(burst, cx); + pause(9, cx); + assert_eq!(exec.requests().len(), 1); + pause(1, cx); + assert_eq!(exec.requests().len(), 2); + stop(retry, cx); + watch.update(cx, |watch, cx| watch.unsubscribe(consumer.entity_id(), cx)); + pause(20, cx); + assert_eq!(exec.requests().len(), 2); + watch.read_with(cx, |watch, _| assert_eq!(watch.status(), &WatchStatus::Off)); +} + +#[gpui::test] +#[ignore = "manual retry work count over three virtual minutes"] +fn measure_monitor_retry_attempts(cx: &mut TestAppContext) { + use std::io::Write as _; + for warmed in [false, true] { + let exec = Arc::new(FakeExec::new(vec![( + "sh", + Ok(( + "@@meminfo\nMemTotal: 1000\nMemAvailable: 250\n@@end\n", + 17, + "", + )), + )])); + let first = warmed.then(|| exec.queue_stream("sh")); + let (_watch, _consumer) = subscribe(&exec, cx); + if let Some(first) = first { + sample(&first, 249, cx); + pause(1, cx); + sample(&first, 250, cx); + stop(first, cx); + } + pause(1, cx); + let first_second = exec.requests().len(); + pause(179, cx); + let launches = exec.requests().len(); + assert_eq!(first_second, if warmed { 2 } else { 1 }); + assert_eq!(launches, 19); + writeln!( + std::io::stdout().lock(), + "previously running={warmed} starts by 1 s={first_second} by 180 s={launches}" + ) + .unwrap(); + } +} diff --git a/crates/monitor-service/src/watch.rs b/crates/monitor-service/src/watch.rs index b11517ef..ee989130 100644 --- a/crates/monitor-service/src/watch.rs +++ b/crates/monitor-service/src/watch.rs @@ -5,6 +5,10 @@ use nocterm_monitor::{Platform, Watch, detect}; use nocterm_session::{ExecError, HostExec}; use std::{sync::Arc, time::Duration}; +const RETRY_DELAY: Duration = Duration::from_secs(10); +const QUICK_RETRY: Duration = Duration::from_secs(1); +const MIN_READING_SPAN: Duration = Duration::from_millis(500); + pub(super) async fn watch( this: WeakEntity, exec: Arc, @@ -14,6 +18,7 @@ pub(super) async fn watch( generation: u64, cx: &mut AsyncApp, ) { + let mut quick_retry_used = false; loop { let outcome = run( &this, @@ -25,6 +30,7 @@ pub(super) async fn watch( cx, ) .await; + let reading_span = outcome.as_ref().copied().unwrap_or_default(); let retry = this.update(cx, |this, cx| { if this.generation != generation || this.plan.is_none() { return false; @@ -44,7 +50,7 @@ pub(super) async fn watch( return false; } Err(error) => WatchStatus::Failed(error), - Ok(()) => { + Ok(_) => { WatchStatus::Failed(ExecError::Failed("The monitor script stopped.".into())) } }; @@ -54,9 +60,17 @@ pub(super) async fn watch( if !matches!(retry, Ok(true)) { return; } - cx.background_executor() - .timer(Duration::from_secs(10)) - .await; + // A dead or burst-only collector keeps the slow cadence. Once a quick + // retry has been used, only a sustained stream earns another. + let delay = if reading_span >= MIN_READING_SPAN + && (!quick_retry_used || reading_span >= RETRY_DELAY) + { + quick_retry_used = true; + QUICK_RETRY + } else { + RETRY_DELAY + }; + cx.background_executor().timer(delay).await; } } async fn run( @@ -67,7 +81,7 @@ async fn run( plan: WatchPlan, generation: u64, cx: &mut AsyncApp, -) -> Result<(), ExecError> { +) -> Result { let detected = match platform.clone() { Some(platform) => platform, None => { @@ -91,6 +105,8 @@ async fn run( } }; let mut watch = Watch::start(exec, detected, plan.metrics, plan.interval).await?; + let mut first_reading = None; + let mut reading_span = Duration::ZERO; while let Some(reading) = watch.next().await { if container && reading.container.as_ref().is_none_or(|counters| { @@ -103,8 +119,10 @@ async fn run( this.update(cx, |this, cx| this.accept(generation, reading, cx)), Ok(true) ) { - return Ok(()); + return Ok(Duration::ZERO); } + let now = cx.background_executor().now(); + reading_span = now.duration_since(*first_reading.get_or_insert(now)); } - Ok(()) + Ok(reading_span) } diff --git a/crates/monitor-ui/src/cores.rs b/crates/monitor-ui/src/cores.rs new file mode 100644 index 00000000..8bcf1c04 --- /dev/null +++ b/crates/monitor-ui/src/cores.rs @@ -0,0 +1,167 @@ +//! Core cells within the details panel's existing scroll. + +use gpui_kit::{ + AnyElement, App, AvailableSpace, Bounds, Element, ElementId, GlobalElementId, Hsla, + InspectorElementId, LayoutId, Pixels, Rems, Style, Window, + component::{ActiveTheme as _, h_flex, v_flex}, + div, point, + prelude::*, + rems, size, +}; +use nocterm_monitor::format; + +use crate::graph; + +const DENSE_COLUMNS: usize = 8; +const ROW_GAP: Rems = rems(0.25); + +pub(super) fn grid(cores: &[f32], color: Hsla, cx: &App) -> AnyElement { + if cores.len() > 64 { + return VisibleCores { + loads: cores.to_vec(), + color, + } + .into_any_element(); + } + let columns = if cores.len() > 16 { DENSE_COLUMNS } else { 4 }; + cells(cores, 0, columns, color, cx).into_any_element() +} + +fn cells(cores: &[f32], first: usize, columns: usize, color: Hsla, cx: &App) -> gpui_kit::Div { + div() + .grid() + .grid_cols(columns as u16) + .gap_x_3() + .gap_y(ROW_GAP) + .children( + cores + .iter() + .enumerate() + .map(|(index, load)| cell(first + index, *load, color, cx)), + ) +} + +fn cell(index: usize, load: f32, color: Hsla, cx: &App) -> gpui_kit::Div { + v_flex() + .gap_0p5() + .child( + h_flex() + .text_xs() + .child( + div() + .flex_1() + .text_color(cx.theme().muted_foreground) + .child(format!("{index}")), + ) + .child(format::percent(load)), + ) + .child(graph::meter(load, color, cx)) +} + +/// The layout reserves all rows. Only rows crossing the parent's clip have elements. +struct VisibleCores { + loads: Vec, + color: Hsla, +} + +impl IntoElement for VisibleCores { + type Element = Self; + + fn into_element(self) -> Self { + self + } +} + +impl Element for VisibleCores { + type RequestLayoutState = Pixels; + type PrepaintState = Option; + + fn id(&self) -> Option { + None + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, Pixels) { + let row_height = cell(0, 100., self.color, cx) + .into_any_element() + .layout_as_root( + size(AvailableSpace::MaxContent, AvailableSpace::MaxContent), + window, + cx, + ) + .height; + let gap = window.pixel_snap(ROW_GAP.to_pixels(window.rem_size())); + let pitch = row_height + gap; + let rows = self.loads.len().div_ceil(DENSE_COLUMNS); + let mut style = Style::default(); + style.size.height = (pitch * rows - gap).into(); + (window.request_layout(style, [], cx), pitch) + } + + fn prepaint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + bounds: Bounds, + pitch: &mut Pixels, + window: &mut Window, + cx: &mut App, + ) -> Option { + let clip = bounds + .intersect(&window.content_mask().bounds) + .intersect(&Bounds::new(Default::default(), window.viewport_size())); + if clip.size.height <= Pixels::ZERO || clip.size.width <= Pixels::ZERO { + return None; + } + let first = ((clip.top() - bounds.top()) / *pitch).floor() as usize; + let last = ((clip.bottom() - bounds.top()) / *pitch).ceil() as usize; + let start = first * DENSE_COLUMNS; + let end = (last * DENSE_COLUMNS).min(self.loads.len()); + let mut visible = cells( + self.loads.get(start..end)?, + start, + DENSE_COLUMNS, + self.color, + cx, + ) + .w(bounds.size.width) + .into_any_element(); + visible.prepaint_as_root( + point(bounds.left(), bounds.top() + *pitch * first), + size( + AvailableSpace::Definite(bounds.size.width), + AvailableSpace::MaxContent, + ), + window, + cx, + ); + Some(visible) + } + + fn paint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut Pixels, + visible: &mut Option, + window: &mut Window, + cx: &mut App, + ) { + if let Some(visible) = visible { + visible.paint(window, cx); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/monitor-ui/src/cores/tests.rs b/crates/monitor-ui/src/cores/tests.rs new file mode 100644 index 00000000..02b0790f --- /dev/null +++ b/crates/monitor-ui/src/cores/tests.rs @@ -0,0 +1,130 @@ +use super::*; +use gpui_kit::{ + Context, Quad, ScrollDelta, TestAppContext, TestSupportExt as _, WindowOptions, px, rgb, + test::TestWindowExt as _, +}; +use nocterm_settings::SettingsDocument; +use nocterm_store::SettingsConfig; +use nocterm_ui::DesignTokens; + +struct Grid { + loads: Vec, + virtualized: bool, +} + +fn fill_color() -> Hsla { + rgb(0x20dc30).into() +} + +impl Render for Grid { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let grid = if self.virtualized { + grid(&self.loads, fill_color(), cx) + } else { + cells(&self.loads, 0, DENSE_COLUMNS, fill_color(), cx).into_any_element() + }; + div() + .id("core-grid-viewport") + .test_support() + .w(rems(26.)) + .h(px(185.)) + .overflow_y_scroll() + .child(grid) + } +} + +fn window(cx: &mut TestAppContext, virtualized: bool) -> gpui_kit::AnyWindowHandle { + cx.update(|cx| { + gpui_kit::open_window(WindowOptions::default(), cx, |_, cx| { + cx.new(|_| Grid { + loads: (0..257).map(|index| 10. + (index % 57) as f32).collect(), + virtualized, + }) + }) + .unwrap() + .0 + }) +} + +fn meter_quads( + cx: &mut TestAppContext, + handle: gpui_kit::AnyWindowHandle, + scale: f32, + rem: f32, + scroll: f32, +) -> Vec { + cx.update_window(handle, |_, window, cx| { + window.set_scale_factor(scale); + window.set_rem_size(px(rem)); + window.render_frame(cx); + if scroll != 0. { + window.scroll( + "core-grid-viewport", + ScrollDelta::Pixels(point(px(0.), px(-scroll))), + cx, + ); + window.render_frame(cx); + } + let viewport = window + .find("core-grid-viewport") + .bounds() + .scale(window.scale_factor()); + let mut meters = window + .painted_quads() + .into_iter() + .filter(|quad| { + quad.background.as_solid() == Some(fill_color()) + && quad.bounds.intersects(&viewport) + }) + .collect::>(); + for quad in &mut meters { + quad.order = 0; + quad.content_mask.bounds = quad + .content_mask + .bounds + .intersect(&quad.bounds) + .intersect(&viewport); + } + meters.sort_by(|left, right| { + left.bounds + .top() + .partial_cmp(&right.bounds.top()) + .unwrap() + .then_with(|| { + left.bounds + .left() + .partial_cmp(&right.bounds.left()) + .unwrap() + }) + }); + meters + }) + .unwrap() +} + +#[gpui_kit::test] +fn the_visible_meter_geometry_matches_the_full_grid_when_scrolled_and_scaled( + cx: &mut TestAppContext, +) { + cx.update(|cx| { + gpui_kit::init(cx); + nocterm_ui::init( + DesignTokens::builtin(), + SettingsConfig::in_memory(SettingsDocument::default()).install(cx), + cx, + ); + }); + for (scale, rem) in [(1., 16.), (1.25, 16.), (1.5, 17.), (2., 16.)] { + let full = window(cx, false); + let clipped = window(cx, true); + for scroll in [0., 285., 2500., -33.] { + let expected = meter_quads(cx, full, scale, rem, scroll); + let actual = meter_quads(cx, clipped, scale, rem, scroll); + assert!(!expected.is_empty()); + assert_eq!( + actual, expected, + "scale {scale}, rem {rem}, scroll {scroll}" + ); + } + } +} diff --git a/crates/monitor-ui/src/details.rs b/crates/monitor-ui/src/details.rs index d5e33034..3c364888 100644 --- a/crates/monitor-ui/src/details.rs +++ b/crates/monitor-ui/src/details.rs @@ -328,7 +328,7 @@ fn section( block( "Cores", strong(format!("{}", cores.len())), - cores_grid(cores, theme.chart_1, cx), + crate::cores::grid(cores, theme.chart_1, cx), cx, ) } @@ -480,33 +480,6 @@ fn section( }) } -/// A cell per core: its number, its load and a bar. -fn cores_grid(cores: &[f32], color: Hsla, cx: &App) -> impl IntoElement { - let columns = if cores.len() > 16 { 8 } else { 4 }; - let theme = cx.theme(); - div() - .grid() - .grid_cols(columns) - .gap_x_3() - .gap_y_1() - .children(cores.iter().enumerate().map(|(index, load)| { - v_flex() - .gap_0p5() - .child( - h_flex() - .text_xs() - .child( - div() - .flex_1() - .text_color(theme.muted_foreground) - .child(format!("{index}")), - ) - .child(format::percent(*load)), - ) - .child(graph::meter(*load, color, cx)) - })) -} - fn temperature_color(celsius: f32, cx: &App) -> Hsla { let theme = cx.theme(); if celsius >= 85.0 { diff --git a/crates/monitor-ui/src/graph.rs b/crates/monitor-ui/src/graph.rs index 679acac7..fe1baae5 100644 --- a/crates/monitor-ui/src/graph.rs +++ b/crates/monitor-ui/src/graph.rs @@ -100,6 +100,9 @@ pub(crate) fn sparkline( canvas( |_, _, _| {}, move |bounds, (), window, _| { + if !bounds.intersects(&window.content_mask().bounds) { + return; + } for line in &lines { paint(line, bounds, now, span.max(1.0), top, window); } @@ -110,7 +113,7 @@ pub(crate) fn sparkline( } fn paint(line: &Line, bounds: Bounds, now: f64, span: f64, top: f32, window: &mut Window) { - let visible: Vec<_> = line + let mut visible = line .points .iter() .filter(|(time, _)| now - time <= span) @@ -119,29 +122,28 @@ fn paint(line: &Line, bounds: Bounds, now: f64, span: f64, top: f32, win let height = (value / top).clamp(0.0, 1.0); let y = bounds.bottom() - (bounds.size.height - px(2.)) * height - px(1.); point(x, y) - }) - .collect(); - let (Some(first), Some(last)) = (visible.first(), visible.last()) else { + }); + let Some(first) = visible.next() else { return; }; - if visible.len() > 1 { + let mut stroke = PathBuilder::stroke(px(1.5)); + stroke.move_to(first); + if let Some(second) = visible.next() { let mut area = PathBuilder::fill(); area.move_to(point(first.x, bounds.bottom())); - for at in &visible { - area.line_to(*at); + area.line_to(first); + let mut last = first; + for at in std::iter::once(second).chain(visible) { + area.line_to(at); + stroke.line_to(at); + last = at; } area.line_to(point(last.x, bounds.bottom())); area.close(); if let Ok(path) = area.build() { window.paint_path(path, line.color.opacity(0.18)); } - } - let mut stroke = PathBuilder::stroke(px(1.5)); - stroke.move_to(*first); - for at in &visible[1..] { - stroke.line_to(*at); - } - if visible.len() == 1 { + } else { stroke.line_to(point(first.x - px(1.), first.y)); } if let Ok(path) = stroke.build() { diff --git a/crates/monitor-ui/src/lib.rs b/crates/monitor-ui/src/lib.rs index 3c9a16b2..9979494d 100644 --- a/crates/monitor-ui/src/lib.rs +++ b/crates/monitor-ui/src/lib.rs @@ -20,6 +20,7 @@ //! Invariants: one script collects the current metric union; eight retained records stay //! distinct by surface and resource; unavailable projects never use a local fallback. //! Container CPU uses a labeled one-CPU basis; cgroup memory never uses host capacity. +mod cores; mod details; mod installed; pub use installed::{Installed, install}; diff --git a/crates/monitor-ui/src/model.rs b/crates/monitor-ui/src/model.rs index e11392d9..6842d23d 100644 --- a/crates/monitor-ui/src/model.rs +++ b/crates/monitor-ui/src/model.rs @@ -83,6 +83,7 @@ pub(crate) struct HostMonitor { collectors: MonitorWatches, watch: Option, generation: u64, + source_refresh_pending: bool, _subscriptions: Vec, } @@ -105,28 +106,37 @@ impl HostMonitor { installed: &crate::Installed, cx: &mut Context, ) -> Self { - let follow = cx.subscribe(workspace, |_, workspace, event, cx| { + let follow = cx.subscribe(workspace, |monitor, workspace, event, cx| { if matches!( event, WorkspaceEvent::ContextChanged | WorkspaceEvent::ActiveSessionChanged | WorkspaceEvent::ActiveItemChanged | WorkspaceEvent::ItemsChanged - ) { + ) && !monitor.source_refresh_pending + { + monitor.source_refresh_pending = true; let workspace = workspace.downgrade(); let this = cx.entity().downgrade(); cx.defer(move |cx| { - if let Some(workspace) = workspace.upgrade() { - let source = workspace.read(cx).monitor_source(cx); - let _ = this.update(cx, |this, cx| this.follow(source, cx)); - } + let source = workspace + .upgrade() + .map(|workspace| workspace.read(cx).monitor_source(cx)); + let _ = this.update(cx, |this, cx| { + this.source_refresh_pending = false; + if let Some(source) = source { + this.follow(source, cx); + } + }); }); } }); let weak = cx.weak_entity(); - let observation = installed.settings().observe(cx, move |cx| { - let _ = weak.update(cx, |this, cx| this.refresh(cx)); - }); + let observation = installed + .settings() + .observe_section::(cx, move |cx| { + let _ = weak.update(cx, |this, cx| this.refresh(cx)); + }); let mut this = Self { consumer: cx.entity_id(), local: installed.local(), @@ -140,6 +150,7 @@ impl HostMonitor { collectors: installed.collectors().clone(), watch: None, generation: 0, + source_refresh_pending: false, _subscriptions: vec![ follow, observation, @@ -197,7 +208,10 @@ impl HostMonitor { /// Starts, restarts or stops the watch to match the session, the /// settings and the details. fn refresh(&mut self, cx: &mut Context) { - let settings = self.settings(cx).clone(); + let settings = self + .settings + .document(cx) + .section_snapshot::(); let host = watched_source(&self.source, self.local.as_ref(), &settings); let plan = Plan::new(&settings, self.open); let history = settings.history_points as usize; diff --git a/crates/monitor-ui/src/page.rs b/crates/monitor-ui/src/page.rs index 956d10be..4d54c17b 100644 --- a/crates/monitor-ui/src/page.rs +++ b/crates/monitor-ui/src/page.rs @@ -150,7 +150,7 @@ impl MonitorPage { ]; let weak = cx.weak_entity(); let window_handle = window.window_handle(); - let observed = settings.observe(cx, move |cx| { + let observed = settings.observe_section::(cx, move |cx| { let _ = window_handle.update(cx, |_, window, cx| { let _ = weak.update(cx, |page, cx| { for number in &mut page.numbers { diff --git a/crates/monitor-ui/src/tests/sources.rs b/crates/monitor-ui/src/tests/sources.rs index af2350d5..1c24deef 100644 --- a/crates/monitor-ui/src/tests/sources.rs +++ b/crates/monitor-ui/src/tests/sources.rs @@ -450,3 +450,162 @@ fn cpu_only_container_details_render_the_available_cpu_without_memory(cx: &mut T }) .unwrap(); } + +#[gpui_kit::test] +#[ignore = "manual release profiling of selected source queries and monitor event bursts"] +fn measure_selected_monitor_source(cx: &mut TestAppContext) { + use futures::FutureExt as _; + use std::io::Write as _; + let count = std::env::var("NOCTERM_PROFILE_SESSION_COUNT") + .map_or(Ok(128), |count| count.parse::()) + .unwrap(); + let (window, workspace, monitor, installed) = fixture_with_installation(cx, None); + let host = FakeHost::new("Linux"); + let items = cx + .update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + (0..count) + .map(|_| { + let item = SessionProbe::new(spec(), true, cx); + item.update(cx, |item, cx| item.set_executor(host.clone(), cx)); + workspace.add_item(item.clone(), window, cx); + item + }) + .collect::>() + }) + }) + .unwrap(); + cx.run_until_parked(); + assert!(host.programs().iter().any(|program| program == "uname")); + for mode in ["query", "events", "settings"] { + for sample in 0..7 { + let start = std::time::Instant::now(); + match mode { + "query" => cx.update(|cx| { + for _ in 0..128 { + let source = std::hint::black_box(workspace.read(cx).monitor_source(cx)); + assert!(source.session().unwrap().connected); + } + }), + "events" => cx.update(|cx| { + workspace.update(cx, |_, cx| { + for _ in 0..64 { + cx.emit(nocterm_workspace::WorkspaceEvent::ItemsChanged); + } + }); + }), + _ => { + for step in 0..128 { + cx.update(|cx| { + installed + .settings() + .update::(cx, move |s| { + s.program = + Some(if step % 2 == 0 { "bash" } else { "sh" }.into()); + }) + .now_or_never() + .unwrap() + .unwrap(); + }); + } + } + } + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} sessions={count} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); + } + } + assert_eq!(items.len(), count); + assert_eq!(status(cx, &monitor), Status::Starting); + assert_eq!( + host.programs() + .iter() + .filter(|program| *program == "uname") + .count(), + 1 + ); +} + +#[gpui_kit::test] +fn selected_source_reads_only_the_focused_terminal_and_keeps_central_fallback( + cx: &mut TestAppContext, +) { + let (window, workspace, _) = fixture(cx, None); + let (remote, local) = cx + .update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + let remote = SessionProbe::new(spec(), true, cx); + workspace.add_item(remote.clone(), window, cx); + let local = SessionProbe::new(spec(), true, cx); + local.update(cx, |local, cx| local.set_local(true, cx)); + workspace.add_local_terminal(local.clone(), window, cx); + assert!(workspace.activate_item_by_id(local.entity_id(), window, cx)); + (remote, local) + }) + }) + .unwrap(); + cx.update(|cx| { + let before = [remote.read(cx).title_reads(), local.read(cx).title_reads()]; + let source = workspace.read(cx).monitor_source(cx); + assert!(source.local()); + assert!(source.session().is_none()); + assert_eq!( + [remote.read(cx).title_reads(), local.read(cx).title_reads()], + before + ); + }); + cx.update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + assert!(workspace.activate_item_by_id(remote.entity_id(), window, cx)) + }); + }) + .unwrap(); + cx.update(|cx| { + let before = [remote.read(cx).title_reads(), local.read(cx).title_reads()]; + let source = workspace.read(cx).monitor_source(cx); + assert!(!source.local()); + assert_eq!(source.session().unwrap().target, spec().target); + assert_eq!( + [remote.read(cx).title_reads(), local.read(cx).title_reads()], + before + ); + }); +} + +#[gpui_kit::test] +fn burst_selection_starts_only_the_final_host_and_later_selection_still_updates( + cx: &mut TestAppContext, +) { + let (window, workspace, monitor) = fixture(cx, None); + let first_host = FakeHost::new("Linux"); + let final_host = FakeHost::new("Linux"); + let first = cx + .update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + let first = SessionProbe::new(spec(), true, cx); + first.update(cx, |item, cx| item.set_executor(first_host.clone(), cx)); + workspace.add_item(first.clone(), window, cx); + let final_item = SessionProbe::new(spec(), true, cx); + final_item.update(cx, |item, cx| item.set_executor(final_host.clone(), cx)); + workspace.add_item(final_item, window, cx); + first + }) + }) + .unwrap(); + cx.run_until_parked(); + assert!(first_host.programs().is_empty()); + assert!(final_host.reading(0)); + cx.update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + assert!(workspace.activate_item_by_id(first.entity_id(), window, cx)) + }); + }) + .unwrap(); + cx.run_until_parked(); + assert!(first_host.reading(0)); + assert!(!final_host.reading(0)); + assert_eq!(status(cx, &monitor), Status::Starting); +} diff --git a/crates/monitor-ui/src/tests/status_popover.rs b/crates/monitor-ui/src/tests/status_popover.rs index 73881190..1430c17d 100644 --- a/crates/monitor-ui/src/tests/status_popover.rs +++ b/crates/monitor-ui/src/tests/status_popover.rs @@ -54,3 +54,115 @@ fn a_right_zone_opens_the_details_leftwards_from_the_summary(cx: &mut TestAppCon "{details:?} ends at {summary:?}" ); } + +fn dense_details( + cores: usize, + samples: usize, + cx: &mut TestAppContext, +) -> (gpui_kit::AnyWindowHandle, Arc) { + let host = FakeHost::new("Linux"); + let (_, _, monitor, installed) = fixture_with_installation(cx, Some(host.clone())); + cx.update(|cx| { + installed + .settings() + .update::(cx, |settings| { + settings.history_points = 600; + settings.details = vec![ + MonitorMetric::Cpu, + MonitorMetric::Cores, + MonitorMetric::Memory, + ]; + }) + .detach(); + }); + monitor.update(cx, |monitor, cx| monitor.set_open(true, cx)); + cx.run_until_parked(); + for time in 1..=samples { + emit_reading(&host, cores, time, cx); + } + let (window, _) = cx.update(|cx| { + gpui_kit::open_window(WindowOptions::default(), cx, |_, cx| { + let details = cx.new(|cx| crate::details::DetailsView::new(monitor.clone(), cx)); + cx.new(|_| Dense(details)) + }) + .unwrap() + }); + (window, host) +} + +struct Dense(Entity); + +impl Render for Dense { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().child(self.0.clone()) + } +} + +fn emit_reading(host: &FakeHost, cores: usize, time: usize, cx: &mut TestAppContext) { + use std::fmt::Write as _; + + let mut reading = + format!("@@uptime\n{time}\n@@meminfo\nMemTotal: 10000\nMemAvailable: 6000\n@@stat\n"); + writeln!(reading, "cpu {} 0 0 {} 0 0 0 0", time * 90, time * 110).unwrap(); + for core in 0..cores { + let busy = time * (10 + core % 51); + writeln!( + reading, + "cpu{core} {busy} 0 0 {} 0 0 0 0", + time * 100 - busy + ) + .unwrap(); + } + reading.push_str("@@end\n"); + host.print(&reading); + cx.run_until_parked(); +} + +#[gpui_kit::test] +fn dense_core_details_keep_the_memory_section_reachable(cx: &mut TestAppContext) { + let (window, _) = dense_details(512, 2, cx); + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + assert!(window.find("host-monitor-section-Cores").visible()); + assert!(!window.find("host-monitor-section-Memory").visible()); + window.scroll( + "host-monitor-details", + gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), px(-6000.))), + cx, + ); + window.render_frame(cx); + assert!(window.find("host-monitor-section-Memory").visible()); + }) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "manual timing of native GPUI details frames with dense monitor samples"] +fn measure_dense_monitor_details(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + for cores in [12, 512] { + let (window, host) = dense_details(cores, 602, cx); + let mut timings = Vec::new(); + for time in 603..=642 { + emit_reading(&host, cores, time, cx); + let elapsed = cx + .update_window(window, |_, window, cx| { + let started = Instant::now(); + window.render_frame(cx); + started.elapsed() + }) + .unwrap(); + timings.push(elapsed); + } + timings.sort_unstable(); + writeln!( + std::io::stderr(), + "{cores} cores, {:.3}ms p50, {:.3}ms p95 over {} frames", + timings[20].as_secs_f64() * 1000., + timings[37].as_secs_f64() * 1000., + timings.len() + ) + .unwrap(); + } +} diff --git a/crates/monitor/src/container.rs b/crates/monitor/src/container.rs index a6abc051..0625fe8d 100644 --- a/crates/monitor/src/container.rs +++ b/crates/monitor/src/container.rs @@ -25,7 +25,7 @@ pub struct ContainerSnapshot { pub(crate) fn request(metrics: MetricSet, interval: Duration) -> ExecRequest { script::request(metrics, interval) } -pub(crate) fn parse(frame: &[String]) -> Reading { +pub(crate) fn parse(frame: &str) -> Reading { let mut counters = ContainerCounters::default(); let mut clock = None; let members = section(frame, "@@cgroup"); @@ -95,13 +95,12 @@ pub(crate) fn parse(frame: &[String]) -> Reading { ..Reading::default() } } -fn section<'a>(frame: &'a [String], name: &str) -> Vec<&'a str> { +fn section<'a>(frame: &'a str, name: &str) -> Vec<&'a str> { frame - .iter() - .skip_while(|line| line.as_str() != name) + .split_terminator('\n') + .skip_while(|line| *line != name) .skip(1) .take_while(|line| !line.starts_with("@@")) - .map(String::as_str) .collect() } fn value<'a>(section: &[&'a str], key: &str) -> Option<&'a str> { @@ -129,7 +128,7 @@ fn verified( mod tests { use super::*; use crate::Sampler; - fn frame(version: u8, path: &str, cpu: u64, memory: &str, limit: &str) -> Vec { + fn frame(version: u8, path: &str, cpu: u64, memory: &str, limit: &str) -> String { let (member, mount, unit, limit_key) = if version == 2 { ( "0::/a", @@ -145,7 +144,9 @@ mod tests { "limit_v1", ) }; - format!("@@cgroup\n{member}\n@@mountinfo\n{mount}\n@@selected\ncpu_path {path}\nmemory_path {path}\ncpu_version {version}\nmemory_version {version}\n@@container\nclock 10\n{unit} {cpu}\nmemory {memory}\n{limit_key} {limit}\n").lines().map(str::to_owned).collect() + format!( + "@@cgroup\n{member}\n@@mountinfo\n{mount}\n@@selected\ncpu_path {path}\nmemory_path {path}\ncpu_version {version}\nmemory_version {version}\n@@container\nclock 10\n{unit} {cpu}\nmemory {memory}\n{limit_key} {limit}\n" + ) } #[test] fn v2_and_v1_use_their_declared_cpu_units_and_memory_scope() { @@ -176,8 +177,11 @@ mod tests { let counters = reading.container.unwrap(); assert_eq!(counters.cpu_nanoseconds, None); assert_eq!(counters.memory_current, None); - let mut missing = frame(2, "/cg/a", 10, "55", "100"); - missing.retain(|line| !line.starts_with("1 2")); + let missing = frame(2, "/cg/a", 10, "55", "100").replacen( + "1 2 0:1 / /cg ro - cgroup2 cgroup rw\n", + "", + 1, + ); assert_eq!( parse(&missing).container.unwrap(), ContainerCounters::default() diff --git a/crates/monitor/src/container/membership.rs b/crates/monitor/src/container/membership.rs index 90c81a33..61c0d003 100644 --- a/crates/monitor/src/container/membership.rs +++ b/crates/monitor/src/container/membership.rs @@ -4,19 +4,17 @@ pub(super) fn resolve(members: &[&str], mounts: &[&str], controller: &str) -> Op if members.len() > 256 || mounts.len() > 4096 { return None; } - let memberships: Vec<_> = members - .iter() - .filter_map(|line| { - let mut fields = line.splitn(3, ':'); - let hierarchy = fields.next()?; - let controllers = fields.next()?; - let path = fields.next()?; - ((controller == "v2" && hierarchy == "0" && controllers.is_empty()) - || controllers.split(',').any(|item| item == controller)) - .then_some(path) - }) - .collect(); - if memberships.len() != 1 { + let mut memberships = members.iter().filter_map(|line| { + let mut fields = line.splitn(3, ':'); + let hierarchy = fields.next()?; + let controllers = fields.next()?; + let path = fields.next()?; + ((controller == "v2" && hierarchy == "0" && controllers.is_empty()) + || controllers.split(',').any(|item| item == controller)) + .then_some(path) + }); + let member = memberships.next()?; + if memberships.next().is_some() { return None; } let mut found = None; @@ -25,15 +23,18 @@ pub(super) fn resolve(members: &[&str], mounts: &[&str], controller: &str) -> Op return None; } let (before, after) = line.split_once(" - ")?; - let fields: Vec<_> = before.split_whitespace().collect(); - let filesystem: Vec<_> = after.split_whitespace().collect(); - if fields.len() < 6 || filesystem.len() < 3 { - return None; - } + let mut fields = before.split_whitespace().skip(3); + let root = fields.next()?; + let mount = fields.next()?; + let _mount_options = fields.next()?; + let mut filesystem = after.split_whitespace(); + let kind = filesystem.next()?; + let _source = filesystem.next()?; + let options = filesystem.next()?; let matches = if controller == "v2" { - filesystem[0] == "cgroup2" + kind == "cgroup2" } else { - filesystem[0] == "cgroup" && filesystem[2].split(',').any(|item| item == controller) + kind == "cgroup" && options.split(',').any(|item| item == controller) }; if !matches { continue; @@ -41,9 +42,8 @@ pub(super) fn resolve(members: &[&str], mounts: &[&str], controller: &str) -> Op if found.is_some() { return None; } - let root = decode(fields[3])?; - let mount = decode(fields[4])?; - let member = memberships[0]; + let root = decode(root)?; + let mount = decode(mount)?; if !valid(member) || !valid(&root) || !valid(&mount) { return None; } @@ -53,8 +53,9 @@ pub(super) fn resolve(members: &[&str], mounts: &[&str], controller: &str) -> Op "/" } else { member - .strip_prefix(&format!("{root}/")) - .map_or(member, |rest| rest) + .strip_prefix(root.as_str()) + .and_then(|rest| rest.strip_prefix('/')) + .unwrap_or(member) }; let joined = if relative == "/" { mount @@ -122,6 +123,17 @@ mod tests { Some("/memory/b") ); } + #[test] + fn malformed_unrelated_mounts_invalidate_the_proof() { + let target = mount("/", "/cg", "cgroup2", "rw"); + for invalid in [ + "1 2 0:1 / /tmp - tmpfs tmpfs rw", + "1 2 0:1 / /tmp ro - tmpfs tmpfs", + ] { + assert!(resolve(&["0::/a"], &[&target, invalid], "v2").is_none()); + } + } + #[test] fn ambiguous_missing_and_outside_namespace_memberships_are_refused() { let one = mount("/", "/cg", "cgroup2", "rw"); diff --git a/crates/monitor/src/frame.rs b/crates/monitor/src/frame.rs index f95aed11..2dda8890 100644 --- a/crates/monitor/src/frame.rs +++ b/crates/monitor/src/frame.rs @@ -5,11 +5,13 @@ pub(crate) const END: &str = "@@end"; const MAX_FRAME: usize = 1024 * 1024; const MAX_LINE: usize = 64 * 1024; const MAX_LINES: usize = 16 * 1024; +const RETAINED_FRAME: usize = 64 * 1024; #[derive(Default)] pub(crate) struct FrameReader { partial: Vec, - lines: Vec, + frame: String, + lines: usize, size: usize, discarding: bool, long_line: bool, @@ -18,7 +20,7 @@ pub(crate) struct FrameReader { impl FrameReader { /// Delivers complete frames individually, without buffering the chunk's /// potentially unbounded number of frames. - pub(crate) fn push(&mut self, bytes: &[u8], mut complete: impl FnMut(Vec)) { + pub(crate) fn push(&mut self, bytes: &[u8], mut complete: impl FnMut(&str)) { let mut rest = bytes; while let Some(newline) = rest.iter().position(|byte| *byte == b'\n') { self.fragment(&rest[..newline]); @@ -41,7 +43,7 @@ impl FrameReader { } } - fn line(&mut self, complete: &mut impl FnMut(Vec)) { + fn line(&mut self, complete: &mut impl FnMut(&str)) { if self.long_line { self.long_line = false; return; @@ -49,29 +51,24 @@ impl FrameReader { let raw = self.partial.strip_suffix(b"\r").unwrap_or(&self.partial); if raw == END.as_bytes() { if !self.discarding { - complete(std::mem::take(&mut self.lines)); + complete(&self.frame); } + self.reset_frame(); self.discarding = false; - self.size = 0; } else if !self.discarding { - // Account for lossy UTF-8 expansion and Vec capacity, even - // for empty lines, before allocating the decoded string. + // Keep the same conservative byte allowance per line, including + // empty lines and the worst-case expansion of lossy UTF-8. let cost = raw .len() .saturating_mul(3) .saturating_add(2 * std::mem::size_of::() + 1); - if self.lines.len() >= MAX_LINES || cost > MAX_FRAME.saturating_sub(self.size) { + if self.lines >= MAX_LINES || cost > MAX_FRAME.saturating_sub(self.size) { self.discard(); } else { self.size += cost; - // Box conversion removes decoder growth slack so the retained - // text fits the conservative byte budget above. - self.lines.push( - String::from_utf8_lossy(raw) - .into_owned() - .into_boxed_str() - .into_string(), - ); + self.lines += 1; + self.frame.push_str(&String::from_utf8_lossy(raw)); + self.frame.push('\n'); } } self.partial.clear(); @@ -79,7 +76,16 @@ impl FrameReader { fn discard(&mut self) { self.discarding = true; - self.lines.clear(); + self.reset_frame(); + } + + fn reset_frame(&mut self) { + if self.frame.capacity() > RETAINED_FRAME { + self.frame = String::new(); + } else { + self.frame.clear(); + } + self.lines = 0; self.size = 0; } } @@ -90,7 +96,9 @@ mod tests { fn push(reader: &mut FrameReader, bytes: &[u8]) -> Vec> { let mut frames = Vec::new(); - reader.push(bytes, |frame| frames.push(frame)); + reader.push(bytes, |frame| { + frames.push(frame.split_terminator('\n').map(str::to_owned).collect()) + }); frames } @@ -99,7 +107,7 @@ mod tests { let mut reader = FrameReader::default(); let empty = vec![b'\n'; 2_000_000]; assert!(push(&mut reader, &empty).is_empty()); - assert!(reader.lines.len() <= MAX_LINES); + assert!(reader.lines <= MAX_LINES); assert!(push(&mut reader, b"tail\n@@end\n").is_empty()); assert_eq!(push(&mut reader, b"ok\n@@end\n"), [vec!["ok"]]); } @@ -123,6 +131,16 @@ mod tests { assert_eq!(frames, [vec!["@@a", "three"]]); } + #[test] + fn fragmented_frames_preserve_empty_lines_and_replace_invalid_utf8() { + let mut reader = FrameReader::default(); + assert!(push(&mut reader, b"\nname \xc3").is_empty()); + assert_eq!( + push(&mut reader, b"\xb6\xff\r\r\n@@end\n@@end\n"), + [vec!["", "name ö�\r"], vec![]] + ); + } + #[test] fn runaway_output_is_dropped() { let mut reader = FrameReader::default(); diff --git a/crates/monitor/src/linux/mod.rs b/crates/monitor/src/linux/mod.rs index 3ce53355..baa1fb48 100644 --- a/crates/monitor/src/linux/mod.rs +++ b/crates/monitor/src/linux/mod.rs @@ -1,8 +1,8 @@ //! Linux hosts: a POSIX `sh` script reading `/proc` and `/sys`. //! //! The script travels on standard input to `sh -s`, so it runs the same -//! under any login shell (bash, zsh, fish, busybox). It sticks to shell -//! builtins: only `sleep`, and `df` when disk space is asked for, fork. +//! under any login shell (bash, zsh, fish, busybox). It uses shell builtins +//! except for `sleep` and, when disk space is requested, `df` with `timeout`. mod parse; @@ -36,16 +36,60 @@ const STAT: &str = r#"printf '@@stat\n' while read -r n r; do case $n in cpu*) printf '%s %s\n' "$n" "$r";; *) break;; esac; done /dev/null; then +net_ifs=$IFS +IFS=' +' +net_skip=2 +while mapfile -t -n 64 -s "$net_skip" net_rows && [ "${#net_rows[@]}" -ne 0 ]; do +printf '%s\n' "${net_rows[*]}" +net_skip=0 +done /dev/null || $T df -kP "#; -const TEMP: &str = r#"printf '@@temp\n' +// Batch the rows so reads that wait for a driver don't wake the reader one by one. +const TEMP: &str = r#"temp_rows='@@temp +' s= for h in /sys/class/hwmon/hwmon*; do [ -r "$h/name" ] || continue read -r n <"$h/name" for t in "$h"/temp*_input; do -[ -r "$t" ] && read -r v <"$t" || continue -l=; [ -r "${t%_input}_label" ] && read -r l <"${t%_input}_label" -printf '%s %s %s\n' "$v" "$n" "$l"; s=1 +read -r v <"$t" || continue +l=; read -r l <"${t%_input}_label" +temp_rows=$temp_rows"$v $n $l"' +' +s=1 +if [ "${#temp_rows}" -ge 1024 ]; then +printf '%s' "$temp_rows" +temp_rows= +fi done done +printf '%s' "$temp_rows" if [ -z "$s" ]; then for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && read -r v <"$z/temp" && read -r n <"$z/type" && printf '%s %s\n' "$v" "$n" @@ -81,9 +134,13 @@ fn script(metrics: MetricSet, interval: Duration) -> String { let mut frame = String::from("printf '@@uptime\\n'\nread -r u _ Vec { + let script = script(metrics, Duration::from_secs(1)); // Two frames: stop the endless loop after the first sleep. let script = script.replacen("H=1; f; H=; sleep 1", "H=1; f; H=; f; exit", 1); + let output = execute_script(&script); + let frames: Vec<_> = output + .split("@@end\n") + .filter(|frame| !frame.is_empty()) + .map(parse) + .collect(); + assert_eq!(frames.len(), 2, "{output}"); + frames + } + + #[cfg(target_os = "linux")] + fn execute_script(script: &str) -> String { + use std::process::{Command, Stdio}; let output = Command::new("sh") .arg("-c") - .arg(&script) + .arg(script) .stdout(Stdio::piped()) .output() .unwrap(); - let text = String::from_utf8_lossy(&output.stdout); - let frames: Vec> = text - .split("@@end\n") - .filter(|frame| !frame.is_empty()) - .map(|frame| frame.lines().map(str::to_owned).collect()) + assert!(output.status.success(), "{output:?}"); + String::from_utf8_lossy(&output.stdout).into_owned() + } + + #[cfg(target_os = "linux")] + #[test] + fn memory_and_swap_readings_support_legacy_and_partial_counter_files() { + let script = script( + [MonitorMetric::Memory, MonitorMetric::Swap] + .into_iter() + .collect(), + Duration::from_secs(1), + ) + .replace( + ""$chip/name" +printf '30000\n' >"$zone/temp" +printf 'ACPI zone\n' >"$zone/type" +i=0 +while [ "$i" -lt 128 ]; do +key=$(printf 'temp%03d' "$i") +printf '45000\n' >"$chip/${key}_input" +if [ "$i" -lt 127 ]; then +printf 'Sensor %s\n' "$i" >"$chip/${key}_label" +fi +i=$((i+1)) +done +"#; + let collector = script( + [MonitorMetric::Temperature].into_iter().collect(), + Duration::from_secs(1), + ) + .replace("/sys/class/hwmon", "\"$fixture\"/hwmon") + .replace("/sys/class/thermal", "\"$fixture\"/thermal") + .replacen( + "H=1; f; H=; sleep 1", + "f; mv \"$chip\" \"$fixture\"; f; exit", + 1, + ); + let output = execute_script(&format!("{fixture}\n{collector}")); + let mut frames = output.split_terminator("@@end\n").map(parse); + let sensors = frames.next().unwrap().temperatures.unwrap(); + assert_eq!(sensors.len(), 128); + for (index, sensor) in sensors[..127].iter().enumerate() { + assert_eq!(sensor.label, format!("chip Sensor {index}")); + } + assert_eq!(sensors[127].label, "chip"); + let zones = frames.next().unwrap().temperatures.unwrap(); + assert_eq!(zones.len(), 1); + assert_eq!(zones[0].label, "ACPI zone"); + assert_eq!(zones[0].celsius, 30.0); + assert!(frames.next().is_none()); + } + + #[cfg(target_os = "linux")] + #[test] + #[ignore = "native thermal collection timing with real Linux sysfs"] + fn measure_linux_monitor_collecting_temperatures() { + use std::{io::Write as _, time::Instant}; + + let script = script( + [MonitorMetric::Temperature].into_iter().collect(), + Duration::from_secs(1), + ) + .replacen( + "H=1; f; H=; sleep 1", + "i=0; while [ \"$i\" -lt 32 ]; do f; i=$((i+1)); done; exit", + 1, + ); + let started = Instant::now(); + let output = execute_script(&script); + let elapsed = started.elapsed(); + let count = output + .split_terminator("@@end\n") + .map(|report| parse(report).temperatures.unwrap().len()) + .sum::(); + assert_eq!(output.matches("@@end\n").count(), 32); + writeln!( + std::io::stdout().lock(), + "32 thermal reports, {count} sensor rows, {:.3}ms", + elapsed.as_secs_f64() * 1_000. + ) + .unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + #[ignore = "native timing measurement with the production shell and real /proc"] + fn measure_linux_monitor_collecting_frames() { + use std::{io::Write as _, time::Instant}; + + for with_network in [false, true] { + let mut metrics = vec![MonitorMetric::Cpu, MonitorMetric::Memory]; + if with_network { + metrics.push(MonitorMetric::Network); + } + let script = script(metrics.into_iter().collect(), Duration::from_secs(1)); + let (collector, _) = script.split_once("H=1; f; H=; sleep 1").unwrap(); + let script = + format!("{collector}i=0\nwhile [ \"$i\" -lt 256 ]; do f; i=$((i+1)); done\n}}"); + let started = Instant::now(); + let output = execute_script(&script); + let elapsed = started.elapsed(); + let mut count = 0; + for frame in output.split_terminator("@@end\n") { + let reading = parse(frame); + assert!(reading.cpu.is_some() && reading.memory.is_some()); + assert_eq!(reading.network.is_some(), with_network); + count += 1; + } + assert_eq!(count, 256); + let metrics = if with_network { + "CPU, memory, network" + } else { + "CPU, memory" + }; + writeln!( + std::io::stdout().lock(), + "{metrics}: {count} host samples in {:.3}ms, {} output bytes", + elapsed.as_secs_f64() * 1_000., + output.len() + ) + .unwrap(); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn cpu_and_memory_watch_reads_only_the_aggregate_cpu_counters() { + if !std::path::Path::new("/proc/stat").exists() { + return; + } + let metrics = [MonitorMetric::Cpu, MonitorMetric::Memory] + .into_iter() .collect(); - assert_eq!(frames.len(), 2, "{text}"); - let first = parse(&frames[0]); + for reading in collect_two_frames(metrics) { + assert!(reading.cpu.is_some()); + assert!(reading.memory.is_some()); + assert!(reading.cores.is_none()); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn the_script_runs_under_sh_and_parses() { + if !std::path::Path::new("/proc/stat").exists() { + return; + } + let frames = collect_two_frames(MetricSet::all()); + let first = &frames[0]; assert!(first.clock.is_some()); assert!( first @@ -167,6 +421,6 @@ mod tests { assert!(first.load.is_some()); assert!(first.network.is_some()); assert!(first.disk_io.is_some()); - assert!(parse(&frames[1]).host.is_none()); + assert!(frames[1].host.is_none()); } } diff --git a/crates/monitor/src/linux/parse.rs b/crates/monitor/src/linux/parse.rs index a097f04d..c592abd6 100644 --- a/crates/monitor/src/linux/parse.rs +++ b/crates/monitor/src/linux/parse.rs @@ -18,12 +18,8 @@ const VIRTUAL_FILESYSTEMS: &[&str] = &[ const VIRTUAL_MOUNTS: &[&str] = &["/proc", "/sys", "/dev", "/run", "/snap", "/var/lib/docker"]; /// Turns a frame's lines into a reading. -#[expect( - clippy::cognitive_complexity, - clippy::too_many_lines, - reason = "predates the limit" -)] -pub(crate) fn parse(lines: &[String]) -> Reading { +#[expect(clippy::too_many_lines, reason = "predates the limit")] +pub(crate) fn parse(frame: &str) -> Reading { let mut reading = Reading::default(); let mut section = ""; let mut host = HostInfo::default(); @@ -31,17 +27,21 @@ pub(crate) fn parse(lines: &[String]) -> Reading { let mut memory = Memory::default(); let mut network: Option = None; let mut blocks = HashSet::new(); - let mut disks: Vec<(String, DiskCounters)> = Vec::new(); - let mut filesystems: Vec<(String, Filesystem)> = Vec::new(); + let mut disks = Vec::new(); + let mut filesystem_sources = HashSet::new(); let mut temperatures = Vec::new(); - for line in lines { + let mut has_diskstats = false; + for line in frame.split_terminator('\n') { if let Some(name) = line.strip_prefix("@@") { section = name; match section { "netdev" => network = Some(NetworkCounters::default()), "temp" => reading.temperatures = Some(Vec::new()), - "df" => reading.filesystems = Some(Vec::new()), + "df" => { + reading.filesystems.get_or_insert_with(Vec::new); + } + "diskstats" => has_diskstats = true, _ => {} } continue; @@ -65,11 +65,12 @@ pub(crate) fn parse(lines: &[String]) -> Reading { } "meminfo" => memory.line(line), "loadavg" => { - let values: Vec = line + let mut values = line .split_whitespace() - .filter_map(|v| v.parse().ok()) - .collect(); - if let [one, five, fifteen] = values[..] { + .filter_map(|v| v.parse::().ok()); + if let (Some(one), Some(five), Some(fifteen), None) = + (values.next(), values.next(), values.next(), values.next()) + { reading.load = Some([one, five, fifteen]); } } @@ -80,7 +81,7 @@ pub(crate) fn parse(lines: &[String]) -> Reading { } } "blocks" => { - blocks.insert(line.trim().to_owned()); + blocks.insert(line.trim()); } "diskstats" => { if let Some(disk) = disk_line(line) { @@ -88,8 +89,11 @@ pub(crate) fn parse(lines: &[String]) -> Reading { } } "df" => { - if let Some(filesystem) = df_line(line) { - filesystems.push(filesystem); + if let Some(filesystem) = df_line(line, &mut filesystem_sources) { + reading + .filesystems + .get_or_insert_with(Vec::new) + .push(filesystem); } } "temp" => { @@ -110,24 +114,16 @@ pub(crate) fn parse(lines: &[String]) -> Reading { reading.memory = memory.memory(); reading.swap = memory.swap(); reading.network = network; - if lines.iter().any(|line| line == "@@diskstats") { + if has_diskstats { let mut total = DiskCounters::default(); for (name, counters) in disks { - if physical_disk(&name, &blocks) { + if physical_disk(name, &blocks) { total.read = total.read.saturating_add(counters.read); total.written = total.written.saturating_add(counters.written); } } reading.disk_io = Some(total); } - if let Some(list) = reading.filesystems.as_mut() { - let mut sources = HashSet::new(); - for (source, filesystem) in filesystems { - if sources.insert(source) { - list.push(filesystem); - } - } - } if let Some(list) = reading.temperatures.as_mut() { *list = temperatures; } @@ -156,12 +152,10 @@ fn host_line(host: &mut HostInfo, line: &str) { fn cpu_line(line: &str) -> Option<(&str, CpuTimes)> { let mut fields = line.split_whitespace(); let name = fields.next()?; - let values: Vec = fields.take(8).filter_map(|v| v.parse().ok()).collect(); - if values.len() < 4 { - return None; - } - let total: u64 = values.iter().sum(); - let idle = values[3] + values.get(4).copied().unwrap_or_default(); + let mut values = fields.take(8).filter_map(|v| v.parse::().ok()); + let active = values.next()? + values.next()? + values.next()?; + let idle = values.next()? + values.next().unwrap_or_default(); + let total = active + idle + values.sum::(); Some(( name, CpuTimes { @@ -228,32 +222,33 @@ fn interface_line(line: &str) -> Option { { return None; } - let values: Vec = counters + let mut values = counters .split_whitespace() - .filter_map(|v| v.parse().ok()) - .collect(); + .filter_map(|v| v.parse::().ok()); Some(NetworkCounters { - received: *values.first()?, - sent: *values.get(8)?, + received: values.next()?, + sent: values.nth(7)?, }) } /// `major minor name reads merged sectors_read ms writes merged sectors_written …` -fn disk_line(line: &str) -> Option<(String, DiskCounters)> { - let fields: Vec<&str> = line.split_whitespace().collect(); - let sectors = |index: usize| fields.get(index)?.parse::().ok(); +fn disk_line(line: &str) -> Option<(&str, DiskCounters)> { + let mut fields = line.split_whitespace(); + let name = fields.nth(2)?; + let read = fields.nth(2)?.parse::().ok()?; + let written = fields.nth(3)?.parse::().ok()?; // Sectors in diskstats are always 512 bytes, whatever the device's own size. Some(( - (*fields.get(2)?).to_owned(), + name, DiskCounters { - read: sectors(5)?.saturating_mul(512), - written: sectors(9)?.saturating_mul(512), + read: read.saturating_mul(512), + written: written.saturating_mul(512), }, )) } /// Whole physical disks only: partitions would count their disk twice. -fn physical_disk(name: &str, blocks: &HashSet) -> bool { +fn physical_disk(name: &str, blocks: &HashSet<&str>) -> bool { if VIRTUAL_DISKS.iter().any(|prefix| name.starts_with(prefix)) { return false; } @@ -286,25 +281,28 @@ fn digits(text: &str) -> bool { } /// `source 1024-blocks used available capacity mount…` -fn df_line(line: &str) -> Option<(String, Filesystem)> { +fn df_line<'a>(line: &'a str, sources: &mut HashSet<&'a str>) -> Option { let mut fields = line.split_whitespace(); let source = fields.next()?; let size: u64 = fields.next()?.parse().ok()?; let _used: u64 = fields.next()?.parse().ok()?; let available: u64 = fields.next()?.parse().ok()?; let _capacity = fields.next()?; - let mount = fields.collect::>().join(" "); + let first = fields.next()?; let virtual_source = VIRTUAL_FILESYSTEMS.contains(&source) || source.starts_with("/dev/loop"); - let virtual_mount = VIRTUAL_MOUNTS - .iter() - .any(|prefix| mount == *prefix || mount.starts_with(&format!("{prefix}/"))); - if size == 0 || mount.is_empty() || virtual_source || virtual_mount { + let virtual_mount = VIRTUAL_MOUNTS.iter().any(|prefix| { + first.strip_prefix(prefix).is_some_and(|suffix| { + suffix.starts_with('/') || (suffix.is_empty() && fields.clone().next().is_none()) + }) + }); + if size == 0 || virtual_source || virtual_mount || !sources.insert(source) { return None; } + let mount = join_words(first, fields); let total = size.saturating_mul(1024); // Space reserved for root counts as used, as df's own percentage does. let used = total.saturating_sub(available.saturating_mul(1024)); - Some((source.to_owned(), Filesystem { mount, total, used })) + Some(Filesystem { mount, total, used }) } /// `millidegrees name [label…]` @@ -314,20 +312,28 @@ fn temperature_line(line: &str) -> Option { if !(-40.0..=150.0).contains(&celsius) || celsius == 0.0 { return None; } - Some(Temperature { - label: label.split_whitespace().collect::>().join(" "), - celsius, - }) + let mut words = label.split_whitespace(); + let label = words + .next() + .map_or_else(String::new, |first| join_words(first, words)); + Some(Temperature { label, celsius }) +} + +fn join_words(first: &str, remaining: std::str::SplitWhitespace<'_>) -> String { + let length = first.len() + remaining.clone().map(|word| 1 + word.len()).sum::(); + let mut value = String::with_capacity(length); + value.push_str(first); + for word in remaining { + value.push(' '); + value.push_str(word); + } + value } #[cfg(test)] mod tests { use super::*; - fn lines(text: &str) -> Vec { - text.lines().map(str::to_owned).collect() - } - const FRAME: &str = "@@uptime 3600.50 @@host @@ -373,7 +379,7 @@ tmpfs 100 10 90 10% /run #[test] fn a_full_frame_is_read() { - let reading = parse(&lines(FRAME)); + let reading = parse(FRAME); assert_eq!(reading.clock, Some(3600.5)); let host = reading.host.unwrap(); assert_eq!(host.os, "Ubuntu 24.04 LTS"); @@ -416,9 +422,7 @@ tmpfs 100 10 90 10% /run #[test] fn missing_sections_stay_unknown() { - let reading = parse(&lines( - "@@uptime\n12.0\n@@meminfo\nMemTotal: 100\nMemFree: 10\nCached: 20\n", - )); + let reading = parse("@@uptime\n12.0\n@@meminfo\nMemTotal: 100\nMemFree: 10\nCached: 20\n"); assert_eq!(reading.memory, Some((102_400, 30_720))); assert_eq!(reading.cpu, None); assert_eq!(reading.network, None); @@ -426,6 +430,93 @@ tmpfs 100 10 90 10% /run assert_eq!(reading.host, None); } + #[test] + fn full_reports_keep_the_first_eligible_mount_and_numeric_field_rules() { + let report = parse( + "@@loadavg\n0.1 skipped 0.2 0.3\n10 20 30 40\n\ + @@netdev\neth0: 10 bad 1 2 3 4 5 6 7 20 99\n\ + @@diskstats\n8 0 sda 1 2 7 4 5 6 11\n8 1 sdb 1 2 invalid 4 5 6 99\n\ + @@blocks\nsda\nsdb\n\ + @@df\n/dev/sda1 1000 2 3 80% /proc/subdir\n\ + /dev/sda1 1000 2 3 80% /mnt/First Mount\n\ + @@df\n/dev/sda1 999 2 3 80% /mnt/Secondary\n\ + /dev/sdb1 1000 2 3 80% /proc\n\ + /dev/sdb1 1000 2 3 80% /proc unrelated\n\ + /dev/sdc1 1000 2 3 80% /proc-sim\n\ + @@temp\n45000 coretemp\tPackage 0\n45001 \n", + ); + assert_eq!(report.load, Some([0.1, 0.2, 0.3])); + assert_eq!( + report.network, + Some(NetworkCounters { + received: 10, + sent: 20 + }) + ); + assert_eq!( + report.disk_io, + Some(DiskCounters { + read: 7 * 512, + written: 11 * 512 + }) + ); + let mounts = report.filesystems.unwrap(); + let names = mounts + .iter() + .map(|entry| entry.mount.as_str()) + .collect::>(); + assert_eq!(names, ["/mnt/First Mount", "/proc unrelated", "/proc-sim"]); + let temperatures = report.temperatures.unwrap(); + assert_eq!(temperatures[0].label, "coretemp Package 0"); + assert!(temperatures[1].label.is_empty()); + } + + #[test] + #[ignore = "manual release benchmark for full Linux monitoring reports"] + fn full_linux_report_benchmark() { + use std::{ + fmt::Write as _, + hint::black_box, + io::Write as _, + time::{Duration, Instant}, + }; + + for rows in [2, 128] { + let mut frame = String::from(FRAME); + writeln!(frame, "@@df").unwrap(); + for index in 0..rows { + for mount in ["Primary", "Duplicate"] { + writeln!( + frame, + "/dev/probe{index} 1000 200 300 67% /mnt/{mount} Mount {index}" + ) + .unwrap(); + } + } + writeln!(frame, "@@netdev").unwrap(); + for index in 0..rows { + writeln!(frame, "eth{index}: 10 1 2 3 4 5 6 7 20 9 10 11 12 13 14 15").unwrap(); + } + let mut timings = [Duration::ZERO; 7]; + for elapsed in &mut timings { + let start = Instant::now(); + for _ in 0..4_000 { + let reading = black_box(parse(black_box(&frame))); + assert_eq!(reading.filesystems.unwrap().len(), rows + 2); + assert_eq!(reading.network.unwrap().sent, 20 * rows as u64); + } + *elapsed = start.elapsed(); + } + timings.sort_unstable(); + writeln!( + std::io::stderr(), + "{rows} rows, {:.2} µs per report", + timings[3].as_secs_f64() * 250. + ) + .unwrap(); + } + } + #[test] fn whole_disks_are_recognised_without_sys() { let none = HashSet::new(); diff --git a/crates/monitor/src/platform.rs b/crates/monitor/src/platform.rs index 31baefbc..2e54e33c 100644 --- a/crates/monitor/src/platform.rs +++ b/crates/monitor/src/platform.rs @@ -31,7 +31,7 @@ impl Platform { } } - pub(crate) fn parse(&self, frame: &[String]) -> Reading { + pub(crate) fn parse(&self, frame: &str) -> Reading { match self { Self::Linux => linux::parse(frame), Self::LinuxContainer => crate::container::parse(frame), diff --git a/crates/monitor/src/watch.rs b/crates/monitor/src/watch.rs index 41e79d23..3f12de60 100644 --- a/crates/monitor/src/watch.rs +++ b/crates/monitor/src/watch.rs @@ -51,7 +51,7 @@ impl Watch { if pending.len() == MAX_PENDING { pending.pop_front(); } - pending.push_back(platform.parse(&frame)); + pending.push_back(platform.parse(frame)); }); } } @@ -113,4 +113,54 @@ mod tests { )); assert!(matches!(unsupported, Err(ExecError::Unsupported))); } + + #[test] + #[ignore = "manual release benchmark for monitor stream decoding"] + fn host_frame_decoding_benchmark() { + use std::{fmt::Write as _, hint::black_box, io::Write as _, time::Instant}; + + const BATCH: usize = 32; + const REPEATS: usize = 200; + for cores in [0, 12, 128, 512] { + let mut frame = "@@uptime\n10.25\n@@stat\ncpu 100 0 100 700 100 0 0 0\n".to_owned(); + for core in 0..cores { + writeln!(frame, "cpu{core} 50 0 50 350 50 0 0 0").unwrap(); + } + frame.push_str("@@meminfo\nMemTotal: 32000\nMemAvailable: 16000\n@@end\n"); + let bytes = frame.repeat(BATCH); + let mut timings = [Duration::ZERO; 7]; + for timing in &mut timings { + let start = Instant::now(); + for _ in 0..REPEATS { + let exec = FakeExec::new(vec![("sh", Ok((&bytes, 0, "")))]); + futures::executor::block_on(async { + let mut watch = Watch::start( + &exec, + Platform::Linux, + MetricSet::all(), + Duration::from_secs(1), + ) + .await + .unwrap(); + for _ in 0..BATCH { + let reading = black_box(watch.next().await.unwrap()); + assert_eq!(reading.cpu.unwrap().busy, 200); + assert_eq!(reading.memory, Some((32_768_000, 16_384_000))); + assert_eq!(reading.cores.as_ref().map_or(0, Vec::len), cores); + } + assert!(watch.next().await.is_none()); + }); + } + *timing = start.elapsed(); + } + timings.sort_unstable(); + let us_per_frame = timings[3].as_secs_f64() * 1_000_000.0 / (BATCH * REPEATS) as f64; + writeln!( + std::io::stderr(), + "{cores:3} cores, {:5} bytes, {us_per_frame:.2} µs/frame", + frame.len() + ) + .unwrap(); + } + } } diff --git a/crates/monitor/src/windows.rs b/crates/monitor/src/windows.rs index 4d47ca87..9cc1bf2b 100644 --- a/crates/monitor/src/windows.rs +++ b/crates/monitor/src/windows.rs @@ -111,11 +111,11 @@ fn script(metrics: MetricSet, interval: Duration) -> String { /// Turns a frame's lines into a reading. #[expect(clippy::too_many_lines, reason = "predates the limit")] -pub(crate) fn parse(lines: &[String]) -> Reading { +pub(crate) fn parse(frame: &str) -> Reading { let mut reading = Reading::default(); let mut host = HostInfo::default(); let mut cores: Vec<(Vec, CpuTimes)> = Vec::new(); - for line in lines { + for line in frame.split_terminator('\n') { let (key, rest) = line.split_once(' ').unwrap_or((line, "")); let values: Vec<&str> = rest.split_whitespace().collect(); let int = |index: usize| values.get(index).and_then(|v| integer(v)); @@ -237,7 +237,7 @@ mod tests { #[test] fn a_frame_is_read() { - let frame: Vec = "@@win + let frame = "@@win clock 12345.678 hostname DESKTOP-1 os Microsoft Windows 11 Pro 10.0.22631 @@ -252,11 +252,8 @@ up 86400 net 1000 2000 disk 300 400 fs 1000 250 C: -temp 310.15 \\_TZ.CPUZ" - .lines() - .map(str::to_owned) - .collect(); - let reading = parse(&frame); +temp 310.15 \\_TZ.CPUZ"; + let reading = parse(frame); assert_eq!(reading.clock, Some(12345.678)); assert_eq!(reading.host.unwrap().hostname, "DESKTOP-1"); assert_eq!( diff --git a/crates/plugin-abi/src/borrowed_storage.rs b/crates/plugin-abi/src/borrowed_storage.rs new file mode 100644 index 00000000..4d22f5c4 --- /dev/null +++ b/crates/plugin-abi/src/borrowed_storage.rs @@ -0,0 +1,98 @@ +//! Guest decoding that keeps storage strings borrowed for the lifetime of the input. + +use alloc::{string::String, vec::Vec}; +use nocterm_plugin_api::{ContributionContext, EffectOutcome, Event, HostError, LocalId, Snapshot}; +use serde::Deserialize; + +use crate::{AbiError, MAX_INPUT_BYTES, WireObserved, WireSetting, WireSnapshot, codec::decode}; + +/// Stored strings from a decoded call. Values borrow the encoded input. +#[derive(Deserialize)] +#[serde(transparent)] +pub struct BorrowedStorage<'a>(#[serde(borrow)] Vec<(&'a str, &'a str)>); + +impl BorrowedStorage<'_> { + /// Returns the value that the owned snapshot would expose for this key. + pub fn get(&self, key: &str) -> Option<&str> { + // The ABI accepts arbitrary order and the owned map keeps the last value. + self.0 + .iter() + .rev() + .find_map(|&(name, value)| (name == key).then_some(value)) + } +} + +#[derive(Deserialize)] +struct SnapshotWire<'a> { + observations: Vec<(String, Result)>, + settings: Vec<(String, WireSetting)>, + #[serde(borrow)] + storage: BorrowedStorage<'a>, + context: ContributionContext, + outcomes: Vec, +} + +// Serialized variants and field order match Call. Owned and borrowed decoders accept +// the same values. Only the representation of the decoded storage strings differs. +#[derive(Deserialize)] +enum CallWire<'a> { + Render { + local: LocalId, + #[serde(borrow)] + snapshot: SnapshotWire<'a>, + }, + Event { + local: LocalId, + event: Event, + #[serde(borrow)] + snapshot: SnapshotWire<'a>, + }, + RenderTerminalBar { + local: LocalId, + terminal: String, + #[serde(borrow)] + snapshot: SnapshotWire<'a>, + }, + TerminalBarEvent { + local: LocalId, + terminal: String, + event: Event, + #[serde(borrow)] + snapshot: SnapshotWire<'a>, + }, +} + +/// Decodes a call with storage held separately from its otherwise complete snapshot. +pub fn decode_call_borrowing_storage( + bytes: &[u8], +) -> Result<(LocalId, Option, Snapshot, BorrowedStorage<'_>), AbiError> { + let call = decode(bytes, MAX_INPUT_BYTES)?; + let (local, event, source, terminal) = match call { + CallWire::Render { local, snapshot } => (local, None, snapshot, None), + CallWire::Event { + local, + event, + snapshot, + } => (local, Some(event), snapshot, None), + CallWire::RenderTerminalBar { + local, + terminal, + snapshot, + } => (local, None, snapshot, Some(terminal)), + CallWire::TerminalBarEvent { + local, + terminal, + event, + snapshot, + } => (local, Some(event), snapshot, Some(terminal)), + }; + let mut snapshot = Snapshot::from(WireSnapshot { + observations: source.observations, + settings: source.settings, + storage: Vec::new(), + context: source.context, + outcomes: source.outcomes, + }); + snapshot.terminal = terminal; + Ok((local, event, snapshot, source.storage)) +} diff --git a/crates/plugin-abi/src/call_ref.rs b/crates/plugin-abi/src/call_ref.rs new file mode 100644 index 00000000..9a68617d --- /dev/null +++ b/crates/plugin-abi/src/call_ref.rs @@ -0,0 +1,156 @@ +//! Postcard-compatible views of the owned call shapes in `wire`. + +use alloc::{collections::BTreeMap, string::String}; +use nocterm_plugin_api::{ + Event, HostError, LocalId, Observed, SnapshotRef, + capability::{ + clock::ClockNow, monitor::Usage, notifications::OwnNotices, transfers::Counts, + workspace::WorkspaceState, + }, +}; +use nocterm_plugin_model::{SettingValue, SettingValues}; +use serde::{Serialize, Serializer, ser::SerializeStruct}; + +// The variant indices and field order match Call. The owned types still decode the bytes. +#[derive(Serialize)] +pub(crate) enum CallRef<'a> { + Render { + local: &'a LocalId, + snapshot: WireSnapshotRef<'a>, + }, + Event { + local: &'a LocalId, + event: &'a Event, + snapshot: WireSnapshotRef<'a>, + }, + RenderTerminalBar { + local: &'a LocalId, + terminal: &'a str, + snapshot: WireSnapshotRef<'a>, + }, + TerminalBarEvent { + local: &'a LocalId, + terminal: &'a str, + event: &'a Event, + snapshot: WireSnapshotRef<'a>, + }, +} + +impl<'a> CallRef<'a> { + pub(crate) fn render(local: &'a LocalId, source: SnapshotRef<'a>) -> Self { + let snapshot = WireSnapshotRef(source); + match source.terminal { + Some(terminal) => Self::RenderTerminalBar { + local, + terminal, + snapshot, + }, + None => Self::Render { local, snapshot }, + } + } + + pub(crate) fn event(local: &'a LocalId, event: &'a Event, source: SnapshotRef<'a>) -> Self { + let snapshot = WireSnapshotRef(source); + match source.terminal { + Some(terminal) => Self::TerminalBarEvent { + local, + terminal, + event, + snapshot, + }, + None => Self::Event { + local, + event, + snapshot, + }, + } + } +} + +pub(crate) struct WireSnapshotRef<'a>(SnapshotRef<'a>); + +impl Serialize for WireSnapshotRef<'_> { + fn serialize(&self, serializer: S) -> Result { + let snapshot = self.0; + let mut wire = serializer.serialize_struct("WireSnapshot", 5)?; + wire.serialize_field("observations", &ObservationList(snapshot.observations))?; + wire.serialize_field("settings", &SettingList(snapshot.settings))?; + wire.serialize_field("storage", &StorageList(snapshot.storage))?; + wire.serialize_field("context", &snapshot.context)?; + wire.serialize_field("outcomes", snapshot.outcomes)?; + wire.end() + } +} + +struct ObservationList<'a>(&'a BTreeMap>); +struct SettingList<'a>(&'a SettingValues); +struct StorageList<'a>(&'a BTreeMap); + +// BTreeMap-backed iterators have a known size and yield the same ordered pairs as WireSnapshot. +impl Serialize for ObservationList<'_> { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq( + self.0 + .iter() + .map(|(id, entry)| (id, entry.as_ref().map(ObservedRef::from))), + ) + } +} + +impl Serialize for SettingList<'_> { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq( + self.0 + .iter() + .map(|(id, value)| (id, SettingRef::from(value))), + ) + } +} + +impl Serialize for StorageList<'_> { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.0.iter()) + } +} + +#[derive(Serialize)] +enum ObservedRef<'a> { + Clock(&'a ClockNow), + Workspace(&'a WorkspaceState), + Usage(&'a Usage), + Counts(&'a Counts), + Notices(&'a OwnNotices), +} + +impl<'a> From<&'a Observed> for ObservedRef<'a> { + fn from(observed: &'a Observed) -> Self { + match observed { + Observed::Clock(data) => Self::Clock(data), + Observed::Workspace(data) => Self::Workspace(data), + Observed::Usage(data) => Self::Usage(data), + Observed::Counts(data) => Self::Counts(data), + Observed::Notices(data) => Self::Notices(data), + } + } +} + +#[derive(Serialize)] +enum SettingRef<'a> { + Bool(bool), + Choice(&'a str), + Choices(&'a [String]), + Number(i32), + Text(&'a str), +} + +impl<'a> From<&'a SettingValue> for SettingRef<'a> { + fn from(value: &'a SettingValue) -> Self { + match value { + SettingValue::Bool(on) => Self::Bool(*on), + SettingValue::Choice(choice) => Self::Choice(choice), + SettingValue::Choices(choices) => Self::Choices(choices), + SettingValue::Number(number) => Self::Number(*number), + SettingValue::Text(text) => Self::Text(text), + } + } +} diff --git a/crates/plugin-abi/src/codec.rs b/crates/plugin-abi/src/codec.rs index b68e0aa1..c7bcef9b 100644 --- a/crates/plugin-abi/src/codec.rs +++ b/crates/plugin-abi/src/codec.rs @@ -2,10 +2,12 @@ use alloc::vec::Vec; -use serde::{Serialize, de::DeserializeOwned}; +use nocterm_plugin_api::{Event, LocalId, Snapshot, SnapshotRef}; +use postcard::ser_flavors::Flavor; +use serde::{Deserialize, Serialize}; use thiserror::Error; -use crate::{Call, MAX_INPUT_BYTES, MAX_REPLY_BYTES, Reply}; +use crate::{Call, MAX_INPUT_BYTES, MAX_REPLY_BYTES, Reply, call_ref::CallRef}; /// Why bytes are not a call or a reply. #[derive(Clone, Debug, PartialEq, Eq, Error)] @@ -28,7 +30,46 @@ fn encode(value: &T, max: usize) -> Result, AbiError> { Ok(bytes) } -fn decode(bytes: &[u8], max: usize) -> Result { +/// An HTTP body can itself exceed the call limit. Refuse it while encoding, +/// before copying it into a buffer the caller would have to discard. +struct CallBuffer(Vec); + +impl CallBuffer { + fn reserve(&mut self, additional: usize) -> postcard::Result<()> { + let len = self.0.len(); + if additional > MAX_INPUT_BYTES - len { + return Err(postcard::Error::SerializeBufferFull); + } + let required = len + additional; + if required > self.0.capacity() { + let capacity = (self.0.capacity() * 2).max(required).min(MAX_INPUT_BYTES); + self.0.reserve_exact(capacity - len); + } + Ok(()) + } +} + +impl Flavor for CallBuffer { + type Output = Vec; + + fn try_push(&mut self, byte: u8) -> postcard::Result<()> { + self.reserve(1)?; + self.0.push(byte); + Ok(()) + } + + fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> { + self.reserve(bytes.len())?; + self.0.extend_from_slice(bytes); + Ok(()) + } + + fn finalize(self) -> postcard::Result { + Ok(self.0) + } +} + +pub(crate) fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8], max: usize) -> Result { if bytes.len() > max { return Err(AbiError::TooLarge { max }); } @@ -45,6 +86,48 @@ pub fn encode_call(call: &Call) -> Result, AbiError> { encode(call, MAX_INPUT_BYTES) } +/// Encodes a render call directly from the snapshot, including its terminal when present. +pub fn encode_render_call(local: &LocalId, snapshot: &Snapshot) -> Result, AbiError> { + encode_render_call_borrowed(local, snapshot.into()) +} + +/// Encodes a render from the host's call-scoped references. +pub fn encode_render_call_borrowed( + local: &LocalId, + snapshot: SnapshotRef<'_>, +) -> Result, AbiError> { + encode(&CallRef::render(local, snapshot), MAX_INPUT_BYTES) +} + +/// Encodes an event call directly from the snapshot, including its terminal when present. +pub fn encode_event_call( + local: &LocalId, + event: &Event, + snapshot: &Snapshot, +) -> Result, AbiError> { + encode_event_call_borrowed(local, event, snapshot.into()) +} + +/// Encodes an event from the host's call-scoped references. +pub fn encode_event_call_borrowed( + local: &LocalId, + event: &Event, + snapshot: SnapshotRef<'_>, +) -> Result, AbiError> { + let call = CallRef::event(local, event, snapshot); + if !matches!(event, Event::Response { .. }) { + return encode(&call, MAX_INPUT_BYTES); + } + postcard::serialize_with_flavor(&call, CallBuffer(Vec::with_capacity(8))).map_err(|error| { + match error { + postcard::Error::SerializeBufferFull => AbiError::TooLarge { + max: MAX_INPUT_BYTES, + }, + error => AbiError::Encode(error), + } + }) +} + /// A call as the guest reads it. pub fn decode_call(bytes: &[u8]) -> Result { decode(bytes, MAX_INPUT_BYTES) diff --git a/crates/plugin-abi/src/lib.rs b/crates/plugin-abi/src/lib.rs index 95cdcd92..8d3b983b 100644 --- a/crates/plugin-abi/src/lib.rs +++ b/crates/plugin-abi/src/lib.rs @@ -20,12 +20,18 @@ extern crate alloc; #[cfg(test)] extern crate std; +mod borrowed_storage; +mod call_ref; mod codec; pub mod names; mod samples; mod wire; -pub use codec::{AbiError, decode_call, decode_reply, encode_call, encode_reply}; +pub use borrowed_storage::{BorrowedStorage, decode_call_borrowing_storage}; +pub use codec::{ + AbiError, decode_call, decode_reply, encode_call, encode_event_call, + encode_event_call_borrowed, encode_render_call, encode_render_call_borrowed, encode_reply, +}; pub use samples::{Sample, samples}; pub use wire::{Answer, Call, Reply, WireObserved, WireSetting, WireSnapshot}; diff --git a/crates/plugin-abi/src/tests.rs b/crates/plugin-abi/src/tests.rs index 4fb3ab68..45a55a6a 100644 --- a/crates/plugin-abi/src/tests.rs +++ b/crates/plugin-abi/src/tests.rs @@ -1,10 +1,10 @@ //! Behavior tests of the ABI types and codec. -use alloc::{collections::BTreeMap, string::String, vec, vec::Vec}; +use alloc::{collections::BTreeMap, format, string::String, vec, vec::Vec}; use nocterm_plugin_api::{ ContributionContext, EffectOutcome, Event, HostError, Kind, LocalId, NodeKind, Observed, - PluginIcon, Snapshot, Zone, + PluginIcon, Snapshot, SnapshotRef, Zone, capability::{ clock::ClockNow, monitor::Usage, @@ -17,7 +17,9 @@ use nocterm_plugin_model::{SettingValue, SettingValues}; use crate::{ ABI_VERSION, AbiError, Answer, Call, MAX_INPUT_BYTES, MAX_REPLY_BYTES, Reply, WireObserved, - WireSnapshot, decode_call, decode_reply, encode_call, encode_reply, pack, samples, unpack, + WireSnapshot, decode_call, decode_call_borrowing_storage, decode_reply, encode_call, + encode_event_call, encode_event_call_borrowed, encode_render_call, encode_render_call_borrowed, + encode_reply, pack, samples, unpack, }; fn snapshot() -> Snapshot { @@ -97,6 +99,353 @@ fn a_snapshot_survives_the_wire_with_every_observation_and_setting_kind() { assert_eq!(Snapshot::from(back), snapshot); } +#[test] +fn direct_snapshot_encoding_matches_all_owned_call_shapes() { + let local = LocalId::parse("bar").unwrap(); + let event = Event::Activated { + key: "start".into(), + }; + let mut snapshot = snapshot(); + let storage = core::mem::take(&mut snapshot.storage); + for terminal in [None, Some("terminal-42".into())] { + snapshot.terminal = terminal; + let input = SnapshotRef { + storage: &storage, + ..(&snapshot).into() + }; + let owned = input.to_owned(); + let render = Call::render(local.clone(), &owned); + assert_eq!( + encode_render_call_borrowed(&local, input), + encode_call(&render) + ); + let event_call = Call::event(local.clone(), event.clone(), &owned); + assert_eq!( + encode_event_call_borrowed(&local, &event, input), + encode_call(&event_call) + ); + } +} + +#[test] +fn borrowed_storage_reads_match_owned_calls_and_keep_the_last_duplicate() { + let local = LocalId::parse("bar").unwrap(); + let event = Event::Activated { + key: "start".into(), + }; + let mut original = snapshot(); + for terminal in [None, Some("terminal-42".into())] { + original.terminal = terminal; + for mut call in [ + Call::render(local.clone(), &original), + Call::event(local.clone(), event.clone(), &original), + ] { + let wire = match &mut call { + Call::Render { snapshot, .. } + | Call::Event { snapshot, .. } + | Call::RenderTerminalBar { snapshot, .. } + | Call::TerminalBarEvent { snapshot, .. } => snapshot, + }; + wire.storage = vec![ + ("k".into(), "early".into()), + ("a".into(), "два".into()), + ("k".into(), "last".into()), + ]; + let bytes = encode_call(&call).unwrap(); + let (name, event, mut owned) = decode_call(&bytes).unwrap().into_parts(); + let (borrowed_name, borrowed_event, context, storage) = + decode_call_borrowing_storage(&bytes).unwrap(); + assert_eq!((borrowed_name, borrowed_event), (name, event)); + for (key, value) in core::mem::take(&mut owned.storage) { + let stored = storage.get(&key).unwrap(); + assert_eq!(stored, value); + assert!(bytes.as_ptr_range().contains(&stored.as_ptr())); + } + assert_eq!(storage.get("missing"), None); + assert_eq!(context, owned); + } + } +} + +#[test] +fn the_borrowed_decoder_refuses_the_same_invalid_size_tail_and_utf8() { + let local = LocalId::parse("bar").unwrap(); + let mut original = snapshot(); + original.storage.insert("k".into(), "unique-value".into()); + let mut invalid = encode_render_call(&local, &original).unwrap(); + let mut trailing = invalid.clone(); + trailing.push(0); + let index = invalid + .windows("unique-value".len()) + .position(|bytes| bytes == b"unique-value") + .unwrap(); + invalid[index] = 0xff; + for bytes in [vec![0; MAX_INPUT_BYTES + 1], trailing, invalid] { + assert_eq!( + decode_call_borrowing_storage(&bytes).err().unwrap(), + decode_call(&bytes).err().unwrap(), + ); + } +} + +#[test] +fn direct_snapshot_encoding_enforces_the_call_limit() { + let local = LocalId::parse("face").unwrap(); + let mut snapshot = snapshot(); + snapshot.terminal = Some("terminal-42".into()); + snapshot + .storage + .insert("k".into(), "x".repeat(MAX_INPUT_BYTES)); + let error = Err(AbiError::TooLarge { + max: MAX_INPUT_BYTES, + }); + assert_eq!(encode_render_call(&local, &snapshot), error); + assert_eq!( + encode_event_call( + &local, + &Event::VisibilityChanged { visible: true }, + &snapshot + ), + error + ); +} + +#[test] +fn an_http_event_fits_only_when_its_snapshot_and_body_fit_together() { + let local = LocalId::parse("face").unwrap(); + let mut snapshot = snapshot(); + snapshot.terminal = Some("terminal-42".into()); + for item in 0..15 { + snapshot + .storage + .insert(format!("item-{item}"), "x".repeat(4 * 1024)); + } + let event = |bytes| Event::Response { + key: "download".into(), + status: 200, + body: "x".repeat(bytes), + }; + let starter = 128 * 1024; + let overhead = encode_event_call(&local, &event(starter), &snapshot) + .unwrap() + .len() + - starter; + let limit = MAX_INPUT_BYTES - overhead; + let fitting = event(limit); + let encoded = encode_event_call(&local, &fitting, &snapshot).unwrap(); + assert_eq!(encoded.len(), MAX_INPUT_BYTES); + assert_eq!( + encoded, + encode_call(&Call::event(local.clone(), fitting, &snapshot)).unwrap() + ); + assert_eq!( + encode_event_call(&local, &event(limit + 1), &snapshot), + Err(AbiError::TooLarge { + max: MAX_INPUT_BYTES, + }) + ); +} + +#[test] +#[ignore = "release timing of accepted and oversized HTTP events"] +fn measure_encoding_http_response_limits() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let local = LocalId::parse("face").unwrap(); + let mut snapshot = snapshot(); + for item in 0..15 { + snapshot + .storage + .insert(format!("item-{item}"), "x".repeat(4 * 1024)); + } + for (case, size, accepted) in [ + ("small", 1024, true), + ("fits with storage", 128 * 1024, true), + ("requires more room for storage", 240 * 1024, false), + ("body reaches the ABI limit", MAX_INPUT_BYTES, false), + ( + "body expanded while decoding UTF-8", + 3 * MAX_INPUT_BYTES, + false, + ), + ] { + let event = Event::Response { + key: "download".into(), + status: 200, + body: "x".repeat(size), + }; + assert_eq!( + encode_event_call(&local, &event, &snapshot).is_ok(), + accepted + ); + let mut samples = [0; 2_000]; + for sample in &mut samples { + let start = Instant::now(); + let result = encode_event_call(&local, &event, &snapshot); + *sample = start.elapsed().as_nanos(); + let _ = black_box(result); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{case}, {size} body bytes: median={} ns, p95={} ns", + samples[samples.len() / 2], + samples[samples.len() * 95 / 100] + ) + .unwrap(); + } +} + +#[test] +#[ignore = "release timing fixture"] +fn encoding_snapshots_with_storage_reports_the_cost_of_a_complete_call() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let local = LocalId::parse("face").unwrap(); + for (entries, bytes) in [(0, 0), (16, 485), (128, 470), (512, 110)] { + let mut snapshot = snapshot(); + for index in 0..entries { + snapshot + .storage + .insert(alloc::format!("row-{index:04}"), "x".repeat(bytes)); + } + let expected = encode_call(&Call::render(local.clone(), &snapshot)).unwrap(); + assert_eq!(encode_render_call(&local, &snapshot).unwrap(), expected); + let mut elapsed = [0; 21]; + for sample in &mut elapsed { + let start = Instant::now(); + for _ in 0..256 { + black_box(encode_render_call(&local, black_box(&snapshot)).unwrap()); + } + *sample = start.elapsed().as_nanos() / 256; + } + elapsed.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{} wire bytes, median {} ns, p95 {} ns", + expected.len(), + elapsed[10], + elapsed[19] + ) + .unwrap(); + } +} + +#[test] +#[ignore = "release timing fixture"] +fn measure_encoding_with_host_owned_or_borrowed_storage() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let local = LocalId::parse("face").unwrap(); + let fields = snapshot(); + for entries in [0, 128, 512] { + let storage = (0..entries) + .map(|index| (format!("sample-{index:04}"), "x".repeat(110))) + .collect::>(); + let input = SnapshotRef { + storage: &storage, + ..(&fields).into() + }; + let encode = |copy_storage| { + let input = black_box(input); + if copy_storage { + let storage = input.storage.clone(); + encode_render_call_borrowed( + &local, + SnapshotRef { + storage: &storage, + ..input + }, + ) + } else { + encode_render_call_borrowed(&local, input) + } + .unwrap() + }; + assert_eq!(encode(true), encode(false)); + for copy_storage in [true, false, false, true] { + let mut ns = [0; 21]; + for sample in &mut ns { + let start = Instant::now(); + for _ in 0..256 { + black_box(encode(copy_storage)); + } + *sample = start.elapsed().as_nanos() / 256; + } + ns.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "entries={entries} copy_storage={copy_storage} p50_ns={} p95_ns={}", + ns[10], + ns[19] + ) + .unwrap(); + } + } +} + +#[test] +#[ignore = "release timing fixture"] +fn decoding_calls_for_two_stored_keys_reports_the_owned_and_borrowed_cost() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let local = LocalId::parse("face").unwrap(); + for (entries, bytes) in [(0, 0), (128, 470), (512, 110)] { + let mut snapshot = snapshot(); + for index in 0..entries { + snapshot + .storage + .insert(alloc::format!("row-{index:04}"), "x".repeat(bytes)); + } + let input = encode_render_call(&local, &snapshot).unwrap(); + let owned = || { + let (_, _, snapshot) = decode_call(black_box(&input)).unwrap().into_parts(); + black_box(snapshot.storage.get("k")); + black_box(snapshot.storage.get("row-0000")); + }; + let borrowed = || { + let (_, _, _, storage) = decode_call_borrowing_storage(black_box(&input)).unwrap(); + black_box(storage.get("k")); + black_box(storage.get("row-0000")); + }; + assert_eq!( + decode_call_borrowing_storage(&input).unwrap().3.get("k"), + Some("v") + ); + assert_eq!( + decode_call_borrowing_storage(&input) + .unwrap() + .3 + .get("row-0000"), + snapshot.storage.get("row-0000").map(String::as_str), + ); + let mut timings = [Vec::with_capacity(21), Vec::with_capacity(21)]; + let runners: [&dyn Fn(); 2] = [&owned, &borrowed]; + for sample in 0..21 { + for lane in if sample % 2 == 0 { [0, 1] } else { [1, 0] } { + let start = Instant::now(); + for _ in 0..256 { + runners[lane](); + } + timings[lane].push(start.elapsed().as_nanos() / 256); + } + } + for lane in &mut timings { + lane.sort_unstable(); + } + writeln!( + std::io::stdout().lock(), + "{entries} extra entries, {} wire bytes, owned median/p95 {}/{} ns, borrowed {}/{} ns", + input.len(), + timings[0][10], + timings[0][19], + timings[1][10], + timings[1][19] + ) + .unwrap(); + } +} + #[test] fn every_sample_decodes_and_encodes_to_the_same_bytes() { let all = samples(); diff --git a/crates/plugin-api/src/base64.rs b/crates/plugin-api/src/base64.rs index fd3a0bb5..f935dfd3 100644 --- a/crates/plugin-api/src/base64.rs +++ b/crates/plugin-api/src/base64.rs @@ -1,64 +1,156 @@ //! Standard base64 (RFC 4648, with padding), for the bytes of files and request bodies that a //! plugin passes through as text. -use alloc::{string::String, vec::Vec}; +use alloc::{string::String, vec, vec::Vec}; const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +// Each table places six bits in the decoded word. Invalid bytes set its high bits. +const fn decoder(shift: u32) -> [u32; 256] { + let mut table = [u32::MAX; 256]; + let mut index = 0; + while index < ALPHABET.len() { + table[ALPHABET[index] as usize] = (index as u32) << shift; + index += 1; + } + table +} + +const FIRST: [u32; 256] = decoder(18); +const SECOND: [u32; 256] = decoder(12); +const THIRD: [u32; 256] = decoder(6); +const FOURTH: [u32; 256] = decoder(0); + +const fn encode_pairs() -> [[u8; 2]; 4096] { + let mut table = [[0; 2]; 4096]; + let mut index = 0; + while index < table.len() { + table[index] = [ALPHABET[index >> 6], ALPHABET[index & 63]]; + index += 1; + } + table +} + +const PAIRS: [[u8; 2]; 4096] = encode_pairs(); + /// The base64 text of `bytes`. pub fn encode(bytes: &[u8]) -> String { - let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); - for chunk in bytes.chunks(3) { - let b = [ - chunk[0], - chunk.get(1).copied().unwrap_or(0), - chunk.get(2).copied().unwrap_or(0), - ]; - let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); - for (i, shift) in [18, 12, 6, 0].into_iter().enumerate() { - if i <= chunk.len() { - out.push(char::from(ALPHABET[((n >> shift) & 63) as usize])); - } else { - out.push('='); + let mut out = vec![0; bytes.len().div_ceil(3) * 4]; + let (chunks, tail) = bytes.as_chunks(); + let (output, _) = out.as_chunks_mut::<4>(); + encode_groups(chunks, output); + if !tail.is_empty() { + encode_tail(tail, &mut output[chunks.len()]); + } + String::from_utf8(out).expect("base64 output is ASCII") +} + +/// Encodes consecutive byte slices as one Base64 value without joining them first. +pub fn encode_segments(segments: &[impl AsRef<[u8]>]) -> String { + let len = segments + .iter() + .map(|segment| segment.as_ref().len()) + .sum::(); + let mut out = vec![0; len.div_ceil(3) * 4]; + let (mut output, _) = out.as_chunks_mut::<4>(); + let mut pending = [0; 3]; + let mut filled = 0; + for mut segment in segments.iter().map(AsRef::as_ref) { + if filled != 0 { + let take = (3 - filled).min(segment.len()); + pending[filled..filled + take].copy_from_slice(&segment[..take]); + filled += take; + if filled < 3 { + continue; } + output[0] = encode_chunk(pending); + output = &mut output[1..]; + segment = &segment[take..]; } + let (chunks, tail) = segment.as_chunks::<3>(); + let (completed, remainder) = output.split_at_mut(chunks.len()); + encode_groups(chunks, completed); + output = remainder; + pending[..tail.len()].copy_from_slice(tail); + filled = tail.len(); + } + if filled != 0 { + encode_tail(&pending[..filled], &mut output[0]); } - out + String::from_utf8(out).expect("base64 output is ASCII") } -fn value(byte: u8) -> Option { - match byte { - b'A'..=b'Z' => Some(u32::from(byte - b'A')), - b'a'..=b'z' => Some(u32::from(byte - b'a') + 26), - b'0'..=b'9' => Some(u32::from(byte - b'0') + 52), - b'+' => Some(62), - b'/' => Some(63), - _ => None, +fn encode_groups(chunks: &[[u8; 3]], output: &mut [[u8; 4]]) { + for (&chunk, quad) in chunks.iter().zip(output) { + *quad = encode_chunk(chunk); } } +fn encode_tail(tail: &[u8], quad: &mut [u8; 4]) { + *quad = encode_chunk([tail[0], tail.get(1).copied().unwrap_or(0), 0]); + quad[tail.len() + 1..].fill(b'='); +} + +fn encode_chunk([a, b, c]: [u8; 3]) -> [u8; 4] { + let [first, second] = PAIRS[usize::from(a) << 4 | usize::from(b >> 4)]; + let [third, fourth] = PAIRS[usize::from(b & 15) << 8 | usize::from(c)]; + [first, second, third, fourth] +} + +fn decode_word([a, b, c, d]: [u8; 4]) -> u32 { + FIRST[usize::from(a)] | SECOND[usize::from(b)] | THIRD[usize::from(c)] | FOURTH[usize::from(d)] +} + +fn unpack(word: u32) -> [u8; 3] { + let [_, a, b, c] = word.to_be_bytes(); + [a, b, c] +} + +fn decode_quad(quad: [u8; 4]) -> Option<[u8; 3]> { + let word = decode_word(quad); + (word < 1 << 24).then(|| unpack(word)) +} + +fn decode_four(quads: [[u8; 4]; 4]) -> Option<[[u8; 3]; 4]> { + let words = quads.map(decode_word); + let [a, b, c, d] = words; + // Check four complete groups with a single test for invalid bytes. + (a | b | c | d < 1 << 24).then(|| words.map(unpack)) +} + /// The bytes of base64 `text`, or `None` when it is not valid padded base64. pub fn decode(text: &str) -> Option> { - let bytes = text.as_bytes(); - if !bytes.len().is_multiple_of(4) { + let (quads, tail) = text.as_bytes().as_chunks(); + if !tail.is_empty() { return None; } - let mut out = Vec::with_capacity(bytes.len() / 4 * 3); - let quads = bytes.len() / 4; - for (index, quad) in bytes.chunks(4).enumerate() { - let last = index + 1 == quads; - let padding = quad.iter().rev().take_while(|&&byte| byte == b'=').count(); - if padding > 2 || (padding > 0 && !last) { - return None; - } - let mut n = 0u32; - for &byte in &quad[..4 - padding] { - n = (n << 6) | value(byte)?; - } - n <<= 6 * padding as u32; - let decoded = [(n >> 16) as u8, (n >> 8) as u8, n as u8]; - out.extend_from_slice(&decoded[..3 - padding]); + let Some((&last, complete)) = quads.split_last() else { + return Some(Vec::new()); + }; + let padding = match last { + [_, _, b'=', b'='] => 2, + [_, _, _, b'='] => 1, + _ => 0, + }; + // 'A' contributes zero bits in the positions occupied by padding. + let mut last = last; + last[4 - padding..].fill(b'A'); + let decoded_suffix = decode_quad(last)?; + // Reject a bad first group before initializing the whole output. + if let Some(&first) = complete.first() { + decode_quad(first)?; + } + let mut out = vec![0; quads.len() * 3 - padding]; + let (triples, suffix) = out.split_at_mut(complete.len() * 3); + let (blocks, extra) = complete.as_chunks(); + let (output, output_tail) = triples.as_chunks_mut::<3>().0.as_chunks_mut(); + for (&block, block_output) in blocks.iter().zip(output) { + *block_output = decode_four(block)?; + } + for (&quad, quad_output) in extra.iter().zip(output_tail) { + *quad_output = decode_quad(quad)?; } + suffix.copy_from_slice(&decoded_suffix[..3 - padding]); Some(out) } diff --git a/crates/plugin-api/src/capability/terminals.rs b/crates/plugin-api/src/capability/terminals.rs index 1541a951..8fdd11c7 100644 --- a/crates/plugin-api/src/capability/terminals.rs +++ b/crates/plugin-api/src/capability/terminals.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize}; use super::{Capability, sealed}; use crate::{Edge, LimitError, LocalId, error::key_syntax, sanitize_display}; -use nocterm_plugin_model::sanitize_text; +use nocterm_plugin_model::sanitized_text_chars; /// Longest terminal key. pub const MAX_TERMINAL_KEY: usize = 32; @@ -131,16 +131,14 @@ impl Capability for ShowTerminalBar { /// clipboard, open a link or answer queries through the screen. pub fn terminal_output(text: &str) -> String { let mut out = String::with_capacity(text.len() + text.len() / 16); - let mut run = String::new(); - let mut chars = text.chars().peekable(); + let mut run_start = 0; + let mut chars = text.chars(); while let Some(c) = chars.next() { if !c.is_control() { - run.push(c); continue; } - // A run of plain text loses invisible and direction characters as view text does. - out.push_str(&sanitize_text(&run)); - run.clear(); + let end = text.len() - chars.as_str().len() - c.len_utf8(); + append_text(&mut out, &text[run_start..end]); match c { '\n' => out.push_str("\r\n"), '\t' => out.push('\t'), @@ -155,47 +153,64 @@ pub fn terminal_output(text: &str) -> String { '\u{90}' | '\u{98}' | '\u{9d}' | '\u{9e}' | '\u{9f}' => skip_string(&mut chars), _ => {} } + run_start = text.len() - chars.as_str().len(); } - out.push_str(&sanitize_text(&run)); + append_text(&mut out, &text[run_start..]); out } +fn append_text(out: &mut String, run: &str) { + // Each printable ASCII byte resets the combining-mark count. + let ascii = run + .bytes() + .position(|byte| !matches!(byte, b' '..=b'~')) + .unwrap_or(run.len()); + let (prefix, rest) = run.split_at(ascii); + out.push_str(prefix); + out.extend(sanitized_text_chars(rest)); +} + +/// Like [`terminal_output`], reusing the supplied buffer for printable ASCII and tabs. +pub fn terminal_output_owned(text: String) -> String { + if text.capacity() <= MAX_WRITE && text.bytes().all(|byte| matches!(byte, b' '..=b'~' | b'\t')) + { + text + } else { + terminal_output(&text) + } +} + /// Reads a control sequence after its introducer: parameters, intermediates and the final byte. /// Returns the parameters and the final byte when it is well formed. -fn control_sequence( - chars: &mut core::iter::Peekable>, -) -> Option<(String, char)> { - let mut params = String::new(); +fn control_sequence<'a>(chars: &mut core::str::Chars<'a>) -> Option<(&'a str, char)> { + let source = chars.as_str(); + let mut count = 0; let mut plain = true; for next in chars.by_ref() { match next { - '0'..='9' | ';' if plain => { - if params.len() < 32 { - params.push(next); - } - } + '0'..='9' | ';' if plain => count += 1, '\u{30}'..='\u{3f}' | '\u{20}'..='\u{2f}' => plain = false, - '\u{40}'..='\u{7e}' => return plain.then_some((params, next)), + '\u{40}'..='\u{7e}' => return plain.then_some((&source[..count.min(32)], next)), _ => return None, } } None } -fn keep_colour(chars: &mut core::iter::Peekable>, out: &mut String) { +fn keep_colour(chars: &mut core::str::Chars<'_>, out: &mut String) { if let Some((params, 'm')) = control_sequence(chars) { out.push_str("\u{1b}["); - out.push_str(¶ms); + out.push_str(params); out.push('m'); } } /// Skips a string sequence (OSC, DCS, APC, PM, SOS) up to its BEL or string terminator. -fn skip_string(chars: &mut core::iter::Peekable>) { +fn skip_string(chars: &mut core::str::Chars<'_>) { while let Some(next) = chars.next() { match next { '\u{7}' | '\u{9c}' => return, - '\u{1b}' if chars.peek() == Some(&'\\') => { + '\u{1b}' if chars.clone().next() == Some('\\') => { chars.next(); return; } diff --git a/crates/plugin-api/src/declarative.rs b/crates/plugin-api/src/declarative.rs index 668f4f71..9482a2a8 100644 --- a/crates/plugin-api/src/declarative.rs +++ b/crates/plugin-api/src/declarative.rs @@ -3,8 +3,8 @@ use alloc::{boxed::Box, collections::BTreeMap, string::String}; use crate::{ - Effects, Event, LocalId, Package, PluginInstance, PluginRuntime, RuntimeError, Snapshot, View, - template::ViewTemplate, + Effects, Event, LocalId, Package, PluginInstance, PluginRuntime, RuntimeError, Snapshot, + SnapshotRef, View, template::ViewTemplate, }; /// Interprets the templates of a package. @@ -28,24 +28,43 @@ impl PluginRuntime for DeclarativeRuntime { impl PluginInstance for Declarative { fn render(&self, local: &LocalId, snapshot: &Snapshot) -> Result { + self.render_borrowed(local, snapshot.into()) + } + + fn render_borrowed( + &self, + local: &LocalId, + snapshot: SnapshotRef<'_>, + ) -> Result { let template = self .views .get(local.as_str()) .ok_or_else(|| RuntimeError::UnknownContribution(local.clone()))?; - template.render(snapshot).map_err(|error| match error { - crate::template::RenderError::Invalid(view) => RuntimeError::View(view), - crate::template::RenderError::TooManyNodes => { - RuntimeError::View(crate::ViewError::TooManyNodes) - } - }) + template + .render_borrowed(snapshot) + .map_err(|error| match error { + crate::template::RenderError::Invalid(view) => RuntimeError::View(view), + crate::template::RenderError::TooManyNodes => { + RuntimeError::View(crate::ViewError::TooManyNodes) + } + }) } /// A declarative package has no code, so no event produces an effect. fn on_event( + &self, + local: &LocalId, + event: Event, + snapshot: &Snapshot, + ) -> Result { + self.on_event_borrowed(local, event, snapshot.into()) + } + + fn on_event_borrowed( &self, local: &LocalId, _event: Event, - _snapshot: &Snapshot, + _snapshot: SnapshotRef<'_>, ) -> Result { if self.views.contains_key(local.as_str()) { Ok(Effects::default()) diff --git a/crates/plugin-api/src/lib.rs b/crates/plugin-api/src/lib.rs index b17ea44f..73b24fe1 100644 --- a/crates/plugin-api/src/lib.rs +++ b/crates/plugin-api/src/lib.rs @@ -80,7 +80,7 @@ pub use ports::{ }; pub use runtimes::Runtimes; pub use sanitize::{sanitize_code, sanitize_display}; -pub use snapshot::{Observed, Snapshot}; +pub use snapshot::{Observed, Snapshot, SnapshotRef}; pub use surface::{ EFFECT_REQUESTS, EVENTS, FILTERS, HOST_ERRORS, Key, KeyType, LIMITS, MANIFEST_KEYS, REFRESHES, RUNTIMES, SETTINGS_KINDS, @@ -88,8 +88,8 @@ pub use surface::{ pub use version::{API_VERSION, ApiVersion, VersionError}; pub use view::{ MAX_BADGE, MAX_BUTTON, MAX_CHART_POINTS, MAX_CHART_SERIES, MAX_CODE, MAX_DEPTH, MAX_LIST_ITEMS, - MAX_NODE_KEY, MAX_NODES, MAX_TEXT, MIN_REFRESH_MS, Node, NodeKind, Refresh, Tone, View, - ViewError, + MAX_NODE_KEY, MAX_NODES, MAX_TEXT, MIN_REFRESH_MS, Node, NodeKind, Refresh, Tone, + ValidatedView, View, ViewError, }; #[cfg(test)] diff --git a/crates/plugin-api/src/ports.rs b/crates/plugin-api/src/ports.rs index 8bec0a6b..55db4d21 100644 --- a/crates/plugin-api/src/ports.rs +++ b/crates/plugin-api/src/ports.rs @@ -13,7 +13,7 @@ use thiserror::Error; use crate::{ ApiVersion, ContentHash, Effects, Event, LocalId, Manifest, ManifestError, PackageKind, - Runtime, SectionError, Snapshot, View, ViewError, + Runtime, SectionError, Snapshot, SnapshotRef, View, ViewError, }; /// The largest declarative package (a TOML manifest), in bytes. @@ -221,6 +221,25 @@ pub trait PluginInstance: Send + Sync { event: Event, snapshot: &Snapshot, ) -> Result; + + /// Renders directly from the host's borrowed input for this call. + fn render_borrowed( + &self, + local: &LocalId, + snapshot: SnapshotRef<'_>, + ) -> Result { + self.render(local, &snapshot.to_owned()) + } + + /// Handles an event without requiring the host to copy its stored data. + fn on_event_borrowed( + &self, + local: &LocalId, + event: Event, + snapshot: SnapshotRef<'_>, + ) -> Result { + self.on_event(local, event, &snapshot.to_owned()) + } } /// Sends a plugin's requests. An adapter implements it over an HTTP client: no cookies, no diff --git a/crates/plugin-api/src/sanitize.rs b/crates/plugin-api/src/sanitize.rs index 37f19b16..ecfcba88 100644 --- a/crates/plugin-api/src/sanitize.rs +++ b/crates/plugin-api/src/sanitize.rs @@ -1,7 +1,7 @@ //! Sanitizing of every string a guest supplies. use alloc::string::String; -use nocterm_plugin_model::sanitize_text; +use nocterm_plugin_model::sanitized_text_chars; /// `text` as one inert line of at most `cap` characters. /// @@ -10,18 +10,76 @@ use nocterm_plugin_model::sanitize_text; /// base character. It applies to every guest string: view text, labels, help and option labels. /// There is no normalization, because it would add a dependency and names are ASCII. pub fn sanitize_display(text: &str, cap: usize) -> String { - sanitize_text(text).chars().take(cap).collect() + if let Some(prefix) = text + .get(..text.len().min(cap)) + .filter(|prefix| printable_ascii(prefix)) + { + return String::from(prefix); + } + collect_text(sanitized_text_chars(text).take(cap), text.len().min(cap)) +} + +pub(crate) fn sanitize_display_in_place(text: &mut String, cap: usize) { + if text.capacity() > cap || !printable_ascii(text) { + *text = sanitize_display(text, cap); + } +} + +pub(crate) fn is_sanitized_display(text: &str) -> bool { + printable_ascii(text) || sanitized_text_chars(text).eq(text.chars()) +} + +fn printable_ascii(text: &str) -> bool { + text.bytes().all(|byte| matches!(byte, b' '..=b'~')) } /// `text` as inert lines of at most `cap` characters in all: each line as /// [`sanitize_display`] keeps it, tabs as four spaces, and `\n` between the lines. pub fn sanitize_code(text: &str, cap: usize) -> String { - let mut out = String::with_capacity(text.len().min(cap)); - for (index, line) in text.split('\n').enumerate() { - if index > 0 { - out.push('\n'); - } - out.push_str(&sanitize_text(&line.replace('\t', " "))); + if let Some(prefix) = text + .get(..text.len().min(cap)) + .filter(|prefix| printable_code_ascii(prefix)) + { + return String::from(prefix); + } + collect_text(code_chars(text).take(cap), text.len().min(cap)) +} + +pub(crate) fn sanitize_code_in_place(text: &mut String, cap: usize) { + if text.capacity() > cap || !printable_code_ascii(text) { + *text = sanitize_code(text, cap); + } +} + +pub(crate) fn is_sanitized_code(text: &str) -> bool { + printable_code_ascii(text) || code_chars(text).eq(text.chars()) +} + +fn printable_code_ascii(text: &str) -> bool { + text.bytes().all(|byte| matches!(byte, b' '..=b'~' | b'\n')) +} + +fn collect_text(mut characters: impl Iterator, byte_hint: usize) -> String { + let Some(first) = characters.next() else { + return String::new(); + }; + let mut output = String::with_capacity(byte_hint); + output.push(first); + output.extend(characters); + if output.len() < output.capacity() / 2 { + output.shrink_to_fit(); } - out.chars().take(cap).collect() + output +} + +fn code_chars(text: &str) -> impl Iterator + '_ { + // A new line or the spaces of an expanded tab reset the combining-mark count. + text.split_inclusive(['\n', '\t']).flat_map(|segment| { + let (content, suffix) = match segment.as_bytes().last() { + Some(b'\n') => (&segment[..segment.len() - 1], "\n"), + Some(b'\t') => (&segment[..segment.len() - 1], " "), + _ => (segment, ""), + }; + sanitized_text_chars(content).chain(suffix.chars()) + }) } diff --git a/crates/plugin-api/src/snapshot.rs b/crates/plugin-api/src/snapshot.rs index 777b32bb..29371209 100644 --- a/crates/plugin-api/src/snapshot.rs +++ b/crates/plugin-api/src/snapshot.rs @@ -95,3 +95,43 @@ impl Snapshot { self.observations.get(capability) } } + +/// Borrowed input of one host call. Runtimes can consume it before the call +/// returns without copying the plugin's storage. Guest code still receives +/// its own snapshot through the ABI. +#[derive(Clone, Copy, Debug)] +pub struct SnapshotRef<'a> { + pub observations: &'a BTreeMap>, + pub settings: &'a SettingValues, + pub storage: &'a BTreeMap, + pub context: ContributionContext, + pub outcomes: &'a [EffectOutcome], + pub terminal: Option<&'a str>, +} + +impl SnapshotRef<'_> { + /// Materializes this input for a runtime using the owned snapshot API. + pub fn to_owned(self) -> Snapshot { + Snapshot { + observations: self.observations.clone(), + settings: self.settings.clone(), + storage: self.storage.clone(), + context: self.context, + outcomes: self.outcomes.to_vec(), + terminal: self.terminal.map(String::from), + } + } +} + +impl<'a> From<&'a Snapshot> for SnapshotRef<'a> { + fn from(snapshot: &'a Snapshot) -> Self { + Self { + observations: &snapshot.observations, + settings: &snapshot.settings, + storage: &snapshot.storage, + context: snapshot.context, + outcomes: &snapshot.outcomes, + terminal: snapshot.terminal.as_deref(), + } + } +} diff --git a/crates/plugin-api/src/template/eval.rs b/crates/plugin-api/src/template/eval.rs index 404f433c..209939b0 100644 --- a/crates/plugin-api/src/template/eval.rs +++ b/crates/plugin-api/src/template/eval.rs @@ -1,12 +1,12 @@ //! Evaluation of a checked template against a snapshot. -use alloc::{format, string::String, string::ToString}; +use alloc::{collections::BTreeMap, format, string::String, string::ToString}; -use nocterm_plugin_model::SettingValue; +use nocterm_plugin_model::{SettingValue, SettingValues}; use super::{Filter, Placeholder, Segment, Source, Template}; use crate::{ - Snapshot, Tone, + HostError, Observed, Snapshot, SnapshotRef, Tone, capability::{Value, notifications::OwnNotice}, }; @@ -21,6 +21,32 @@ pub struct Context<'a> { pub item: Option<&'a OwnNotice>, } +#[derive(Clone, Copy)] +pub(super) struct EvalContext<'a> { + pub(super) observations: &'a BTreeMap>, + pub(super) settings: &'a SettingValues, + pub(super) item: Option<&'a OwnNotice>, +} + +impl<'a> From> for EvalContext<'a> { + fn from(snapshot: SnapshotRef<'a>) -> Self { + Self { + observations: snapshot.observations, + settings: snapshot.settings, + item: None, + } + } +} + +impl<'a> Context<'a> { + fn borrowed(&self) -> EvalContext<'a> { + EvalContext { + item: self.item, + ..EvalContext::from(SnapshotRef::from(self.snapshot)) + } + } +} + /// What an expression gave. enum Evaluated { Value(Value), @@ -33,6 +59,10 @@ impl Template { /// /// The result is not sanitized or cut: the caller applies `sanitize_display`. pub fn render(&self, cx: &Context<'_>) -> String { + self.render_borrowed(&cx.borrowed()) + } + + pub(super) fn render_borrowed(&self, cx: &EvalContext<'_>) -> String { let mut text = String::new(); for segment in &self.segments { match segment { @@ -51,6 +81,10 @@ impl Template { impl Placeholder { /// The number a number expression gives, if it is available. pub fn number(&self, cx: &Context<'_>) -> Option { + self.number_borrowed(&cx.borrowed()) + } + + pub(super) fn number_borrowed(&self, cx: &EvalContext<'_>) -> Option { match self.evaluate(cx)? { Evaluated::Value(Value::Number(number)) if number.is_finite() => Some(number), _ => None, @@ -59,6 +93,10 @@ impl Placeholder { /// The switch value a boolean expression gives, if it is available. pub fn switch(&self, cx: &Context<'_>) -> Option { + self.switch_borrowed(&cx.borrowed()) + } + + pub(super) fn switch_borrowed(&self, cx: &EvalContext<'_>) -> Option { match self.evaluate(cx)? { Evaluated::Value(Value::Bool(on)) => Some(on), _ => None, @@ -67,13 +105,17 @@ impl Placeholder { /// The tone a threshold expression gives, if it is available. pub fn tone(&self, cx: &Context<'_>) -> Option { + self.tone_borrowed(&cx.borrowed()) + } + + pub(super) fn tone_borrowed(&self, cx: &EvalContext<'_>) -> Option { match self.evaluate(cx)? { Evaluated::Tone(tone) => Some(tone), _ => None, } } - fn evaluate(&self, cx: &Context<'_>) -> Option { + fn evaluate(&self, cx: &EvalContext<'_>) -> Option { let mut current = Evaluated::Value(self.source.read(cx)?); for filter in &self.filters { current = filter.apply(current)?; @@ -83,16 +125,16 @@ impl Placeholder { } impl Source { - fn read(&self, cx: &Context<'_>) -> Option { + fn read(&self, cx: &EvalContext<'_>) -> Option { match self { Self::Capability { capability, field } => { - let observed = cx.snapshot.observation(capability.id)?.as_ref().ok()?; + let observed = cx.observations.get(capability.id)?.as_ref().ok()?; match field { Some(field) => observed.field(field), None => observed.whole(), } } - Self::Setting(key) => match cx.snapshot.settings.get(key)? { + Self::Setting(key) => match cx.settings.get(key)? { SettingValue::Bool(on) => Some(Value::Bool(*on)), SettingValue::Choice(text) | SettingValue::Text(text) => { Some(Value::Text(text.clone())) diff --git a/crates/plugin-api/src/template/view.rs b/crates/plugin-api/src/template/view.rs index ecc8762d..e822698a 100644 --- a/crates/plugin-api/src/template/view.rs +++ b/crates/plugin-api/src/template/view.rs @@ -10,11 +10,14 @@ use nocterm_plugin_model::SettingsSchema; use serde::{Deserialize, Serialize}; use thiserror::Error; -use super::{Context, MAX_PLACEHOLDERS, Output, Placeholder, Scope, Template, TemplateError}; +use super::{ + MAX_PLACEHOLDERS, Output, Placeholder, Scope, Template, TemplateError, eval::EvalContext, +}; use crate::{ Glyph, LimitError, MAX_BADGE, MAX_BUTTON, MAX_DEPTH, MAX_LIST_ITEMS, MAX_NODE_KEY, MAX_NODES, - MAX_TEXT, MIN_REFRESH_MS, Node, NodeKind, Refresh, Snapshot, Tone, View, ViewError, - capability::Capability, capability::notifications::Own, error::key_syntax, sanitize_display, + MAX_TEXT, MIN_REFRESH_MS, Node, NodeKind, Refresh, Snapshot, SnapshotRef, Tone, View, + ViewError, capability::Capability, capability::notifications::Own, error::key_syntax, + sanitize_display, }; /// The kinds of node an author writes. @@ -260,11 +263,12 @@ impl ViewTemplate { /// /// List expansion counts toward the node limit before a node is made. pub fn render(&self, snapshot: &Snapshot) -> Result { + self.render_borrowed(snapshot.into()) + } + + pub(crate) fn render_borrowed(&self, snapshot: SnapshotRef<'_>) -> Result { let mut nodes = Vec::new(); - let cx = Context { - snapshot, - item: None, - }; + let cx = EvalContext::from(snapshot); for (index, entry) in self.entries.iter().enumerate() { if entry.parent.is_none() { self.emit(index, None, &cx, &mut nodes)?; @@ -281,7 +285,7 @@ impl ViewTemplate { &self, index: usize, parent: Option, - cx: &Context<'_>, + cx: &EvalContext<'_>, out: &mut Vec, ) -> Result<(), RenderError> { let entry = &self.entries[index]; @@ -291,14 +295,14 @@ impl ViewTemplate { } out.push(entry.node(parent, cx)); if matches!(entry.content, Content::List { each: true }) { - let items = match cx.snapshot.observation(Own::ID) { + let items = match cx.observations.get(Own::ID) { Some(Ok(crate::Observed::Notices(notices))) => notices.0.as_slice(), _ => &[], }; for item in items.iter().take(MAX_LIST_ITEMS) { - let inner = Context { - snapshot: cx.snapshot, + let inner = EvalContext { item: Some(item), + ..*cx }; for child in &self.children[index] { self.emit(*child, Some(at), &inner, out)?; @@ -355,25 +359,25 @@ impl Entry { own + usize::from(self.tone_when.is_some()) } - fn node(&self, parent: Option, cx: &Context<'_>) -> Node { + fn node(&self, parent: Option, cx: &EvalContext<'_>) -> Node { let kind = match &self.content { Content::Row => NodeKind::Row, Content::Column => NodeKind::Column, Content::Text(template) => { - NodeKind::Text(sanitize_display(&template.render(cx), MAX_TEXT)) + NodeKind::Text(sanitize_display(&template.render_borrowed(cx), MAX_TEXT)) } Content::Icon(icon) => NodeKind::Icon(*icon), Content::Meter(value) => { - let percent = value.number(cx).unwrap_or(0.0).clamp(0.0, 100.0); + let percent = value.number_borrowed(cx).unwrap_or(0.0).clamp(0.0, 100.0); NodeKind::Meter(percent as u8) } Content::Badge(template) => { - NodeKind::Badge(sanitize_display(&template.render(cx), MAX_BADGE)) + NodeKind::Badge(sanitize_display(&template.render_borrowed(cx), MAX_BADGE)) } Content::Button(template) => { - NodeKind::Button(sanitize_display(&template.render(cx), MAX_BUTTON)) + NodeKind::Button(sanitize_display(&template.render_borrowed(cx), MAX_BUTTON)) } - Content::Toggle(value) => NodeKind::Toggle(value.switch(cx).unwrap_or(false)), + Content::Toggle(value) => NodeKind::Toggle(value.switch_borrowed(cx).unwrap_or(false)), Content::List { .. } => NodeKind::List, Content::Divider => NodeKind::Divider, Content::Spacer => NodeKind::Spacer, @@ -382,10 +386,10 @@ impl Entry { count, folded, } => NodeKind::Section { - title: sanitize_display(&title.render(cx), MAX_BUTTON), + title: sanitize_display(&title.render_borrowed(cx), MAX_BUTTON), count: count .as_ref() - .map(|count| sanitize_display(&count.render(cx), MAX_BADGE)), + .map(|count| sanitize_display(&count.render_borrowed(cx), MAX_BADGE)), folded: *folded, }, Content::Item { @@ -393,27 +397,27 @@ impl Entry { detail, icon, } => NodeKind::Item { - title: sanitize_display(&title.render(cx), MAX_TEXT), + title: sanitize_display(&title.render_borrowed(cx), MAX_TEXT), detail: detail .as_ref() - .map(|detail| sanitize_display(&detail.render(cx), MAX_TEXT)), + .map(|detail| sanitize_display(&detail.render_borrowed(cx), MAX_TEXT)), icon: *icon, selected: false, }, Content::IconButton { icon, label } => NodeKind::IconButton { icon: *icon, - label: sanitize_display(&label.render(cx), MAX_BUTTON), + label: sanitize_display(&label.render_borrowed(cx), MAX_BUTTON), }, Content::Caption(text) => { - NodeKind::Caption(sanitize_display(&text.render(cx), MAX_TEXT)) + NodeKind::Caption(sanitize_display(&text.render_borrowed(cx), MAX_TEXT)) } Content::Field { label, value } => NodeKind::Field { - label: sanitize_display(&label.render(cx), MAX_BUTTON), - value: sanitize_display(&value.render(cx), MAX_TEXT), + label: sanitize_display(&label.render_borrowed(cx), MAX_BUTTON), + value: sanitize_display(&value.render_borrowed(cx), MAX_TEXT), }, }; let tone = match &self.tone_when { - Some(expression) => expression.tone(cx).unwrap_or(Tone::Muted), + Some(expression) => expression.tone_borrowed(cx).unwrap_or(Tone::Muted), None => self.tone, }; Node { diff --git a/crates/plugin-api/src/tests/files.rs b/crates/plugin-api/src/tests/files.rs index 26a66239..0e95a8f9 100644 --- a/crates/plugin-api/src/tests/files.rs +++ b/crates/plugin-api/src/tests/files.rs @@ -29,6 +29,32 @@ fn base64_round_trips_every_length_and_refuses_what_is_not_base64() { } } +#[test] +fn segmented_base64_only_pads_the_end_and_keeps_bytes_across_every_split() { + let bytes: Vec = (0..=255).collect(); + assert!(base64::encode_segments(&[&[][..], &[]]).is_empty()); + for len in 0..=28 { + let expected = base64::encode(&bytes[..len]); + for first in 0..=len { + for second in first..=len { + let parts = [ + &bytes[..first], + &[], + &bytes[first..second], + &bytes[second..len], + ]; + assert_eq!(base64::encode_segments(&parts), expected); + } + } + } + + let file = bytes.repeat(MAX_FILE_BYTES / bytes.len()); + assert_eq!( + base64::encode_segments(&file.chunks(32 * 1024).collect::>()), + base64::encode(&file), + ); +} + #[test] fn the_host_asks_only_about_plain_absolute_paths() { for good in ["/", "/plugins", "/plugins/", "/a b/c.yml"] { @@ -102,3 +128,71 @@ fn a_bytes_request_carries_base64() { assert_eq!(request("TWFu").check(), Ok(())); assert!(request("not base64").check().is_err()); } + +#[test] +fn base64_keeps_full_plugin_files_and_the_established_padding_contract() { + let bytes: Vec = (0..MAX_FILE_BYTES) + .map(|offset| ((offset >> 7) ^ offset) as u8) + .collect(); + for length in MAX_FILE_BYTES - 2..=MAX_FILE_BYTES { + let input = &bytes[..length]; + let encoded = base64::encode(input); + assert_eq!(encoded.len(), length.div_ceil(3) * 4); + assert_eq!(base64::decoded_len(&encoded), Some(length)); + assert_eq!(base64::decode(&encoded).as_deref(), Some(input)); + assert_eq!(reply(FileAnswer::Content(encoded)).check(), Ok(())); + } + + assert_eq!(base64::decode("AB=="), Some(vec![0])); + assert_eq!(base64::decode("AAB="), Some(vec![0, 0])); + for malformed in ["AAAAA=AA", "AAA=AAAA", "AAAAA==="] { + assert_eq!(base64::decode(malformed), None, "{malformed}"); + } + + let encoded = base64::encode(&bytes); + for offset in [0, encoded.len() / 2, encoded.len() - 4] { + let mut malformed = encoded.clone(); + malformed.replace_range(offset..offset + 1, "%"); + assert_eq!(base64::decoded_len(&malformed), Some(MAX_FILE_BYTES)); + assert_eq!(base64::decode(&malformed), None); + } +} + +#[test] +#[ignore = "manual timing of Base64 for plugin file and network payloads"] +fn measure_plugin_file_base64() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + for count in [64, 4096, MAX_FILE_BYTES] { + let input: Vec = (0..count) + .map(|offset| ((offset >> 7) ^ offset) as u8) + .collect(); + let encoded = base64::encode(&input); + assert_eq!(base64::decode(&encoded).as_deref(), Some(input.as_slice())); + + let repeats = (8_000_000 / count).max(64); + let mut encode_ns = [0; 7]; + let mut decode_ns = [0; 7]; + for (enc, dec) in encode_ns.iter_mut().zip(&mut decode_ns) { + let start = Instant::now(); + for _ in 0..repeats { + black_box(base64::encode(black_box(&input))); + } + *enc = start.elapsed().as_nanos() / repeats as u128; + let start = Instant::now(); + for _ in 0..repeats { + black_box(base64::decode(black_box(&encoded))); + } + *dec = start.elapsed().as_nanos() / repeats as u128; + } + encode_ns.sort_unstable(); + decode_ns.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} bytes, median encode {} ns, median decode {} ns", + encode_ns[3], + decode_ns[3], + ) + .unwrap(); + } +} diff --git a/crates/plugin-api/src/tests/sanitize.rs b/crates/plugin-api/src/tests/sanitize.rs index 533cddb5..e5a8299a 100644 --- a/crates/plugin-api/src/tests/sanitize.rs +++ b/crates/plugin-api/src/tests/sanitize.rs @@ -1,6 +1,8 @@ +use alloc::{string::String, vec, vec::Vec}; +use nocterm_plugin_model::sanitize_text; use proptest::prelude::*; -use crate::sanitize_display; +use crate::{Node, NodeKind, View, sanitize_code, sanitize_display}; #[test] fn invisible_and_directional_characters_are_removed() { @@ -41,4 +43,151 @@ proptest! { prop_assert_eq!(sanitize_display(&once, cap), once.clone()); prop_assert!(once.chars().all(clean)); } + + #[test] + fn text_and_code_match_the_full_sanitized_prefix( + characters in proptest::collection::vec( + prop_oneof![ + any::(), + proptest::sample::select(vec![ + 'a', ' ', '\t', '\n', '\r', '\0', '\u{7f}', '\u{85}', + '\u{301}', '\u{302}', '\u{303}', '\u{200d}', '\u{202e}', '\u{fe0f}', + ]), + ], + 0..256, + ), + cap in 0usize..300, + ) { + let raw: String = characters.into_iter().collect(); + let plain: String = sanitize_text(&raw).chars().take(cap).collect(); + let code: String = legacy_code(&raw).chars().take(cap).collect(); + prop_assert_eq!(sanitize_display(&raw, cap), plain); + prop_assert_eq!(sanitize_code(&raw, cap), code); + } +} + +fn legacy_code(text: &str) -> String { + let mut output = String::new(); + for (index, line) in text.split('\n').enumerate() { + if index > 0 { + output.push('\n'); + } + output.push_str(&sanitize_text(&line.replace('\t', " "))); + } + output +} + +#[test] +fn a_code_cap_can_cut_through_tab_expansion_without_losing_line_breaks() { + assert_eq!(sanitize_code("\n\t\u{301}\u{302}\u{303}\n", 3), "\n "); + assert_eq!( + sanitize_code("\n\t\u{301}\u{302}\u{303}\n", 40), + "\n \u{301}\u{302}\n", + ); + assert_eq!(sanitize_display("safe\0\u{202e}suffix", 4), "safe"); + assert_eq!(sanitize_display("a\u{007f}b", 3), "ab"); +} + +#[test] +fn accepted_text_does_not_keep_oversized_or_empty_guest_buffers() { + let mut reserved = String::with_capacity(1024 * 1024); + reserved.push_str("status"); + let invisible = "\u{200d}".repeat(crate::MAX_CODE); + let accepted = View { + nodes: vec![ + Node::new(NodeKind::Text(reserved)), + Node::new(NodeKind::Code(invisible.clone())), + Node::new(NodeKind::Code(invisible + "a")), + ], + refresh: None, + } + .validated() + .unwrap(); + let [label, empty, sparse] = accepted.nodes() else { + panic!("the accepted view has three nodes"); + }; + let NodeKind::Text(label) = &label.kind else { + panic!("status is a text node"); + }; + let (NodeKind::Code(empty), NodeKind::Code(sparse)) = (&empty.kind, &sparse.kind) else { + panic!("the other nodes contain code"); + }; + assert_eq!(label, "status"); + assert!(label.capacity() <= crate::MAX_TEXT); + assert_eq!(empty.capacity(), 0); + assert_eq!(sparse, "a"); + assert!(sparse.capacity() <= 8); +} + +#[test] +#[ignore = "manual release timing fixture"] +fn measure_guest_text_validation() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + for (name, input, code, count) in [ + ( + "ascii", + "ordinary status text, source ready. ".repeat(5), + false, + 256, + ), + ( + "mixed", + "Статус 🧪 café a\u{301}\u{302}\u{303} ".repeat(10), + false, + 256, + ), + ( + "controls", + "\u{202e}一\u{85}a\u{200d}\u{301}\u{302}\u{303}\0".repeat(400), + false, + 16, + ), + ( + "code", + "build:\n\t echo a\u{202e}\u{301}\u{302}\u{303}\n".repeat(180), + true, + 16, + ), + ] { + let node = |text| { + Node::new(if code { + NodeKind::Code(text) + } else { + NodeKind::Text(text) + }) + }; + let raw = View { + nodes: vec![node(input.clone()); count], + refresh: None, + }; + let expected_text: String = if code { + legacy_code(&input).chars().take(crate::MAX_CODE).collect() + } else { + sanitize_text(&input) + .chars() + .take(crate::MAX_TEXT) + .collect() + }; + let expected = vec![node(expected_text); count]; + let mut durations = [0; 25]; + for batch in &mut durations { + let samples = vec![raw.clone(); 24]; + let start = Instant::now(); + let checked: Vec<_> = samples + .into_iter() + .map(|sample| black_box(sample).validated().unwrap()) + .collect(); + *batch = start.elapsed().as_nanos() / 24; + assert!(checked.iter().all(|view| view.nodes() == expected)); + } + durations.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{name} {count} nodes median/p95 ns: {}/{}", + durations[12], + durations[23] + ) + .unwrap(); + } } diff --git a/crates/plugin-api/src/tests/terminals.rs b/crates/plugin-api/src/tests/terminals.rs index 7e9da511..c17bf145 100644 --- a/crates/plugin-api/src/tests/terminals.rs +++ b/crates/plugin-api/src/tests/terminals.rs @@ -5,7 +5,7 @@ use alloc::string::String; use super::support::{dto, host}; use crate::{ ContributionError, LocalId, Manifest, ManifestError, - capability::terminals::{Bar, Open, Write, terminal_output}, + capability::terminals::{Bar, MAX_WRITE, Open, Write, terminal_output, terminal_output_owned}, }; use nocterm_plugin_model::{ContributionKind, Edge}; @@ -26,6 +26,73 @@ fn terminal_text_keeps_colours_and_line_breaks_and_drops_every_other_sequence() assert_eq!(terminal_output("a\u{202e}b\u{200b}c\r"), "abc"); } +#[test] +fn terminal_output_keeps_only_the_supported_parameters_and_printable_spans() { + let params = "1;".repeat(16); + let cases = [ + ("plain ASCII\t", String::from("plain ASCII\t")), + ( + "a\u{301}\u{300}\u{302}\t界\u{301}\u{300}\u{302}\n", + String::from("a\u{301}\u{300}\t界\u{301}\u{300}\r\n"), + ), + ( + "plain text\u{200d}\u{202e}Unicode\r\n", + String::from("plain textUnicode\r\n"), + ), + ( + "\u{1b}[?25mA\u{1b}[1 mB\u{1b}[1\u{e9}C\u{1b}[12", + String::from("ABC"), + ), + ]; + for (input, expected) in cases { + assert_eq!(terminal_output(input), expected); + assert_eq!(terminal_output_owned(input.into()), expected); + } + + let input = alloc::format!("\u{1b}[{params}33m\u{e9}\u{1b}[m\n"); + let expected = alloc::format!("\u{1b}[{params}m\u{e9}\u{1b}[m\r\n"); + assert_eq!(terminal_output(&input), expected); + assert_eq!(terminal_output_owned(input), expected); +} + +#[test] +#[ignore = "manual CPU timing for plugin terminal output"] +fn measure_plugin_terminal_output() { + use alloc::vec::Vec; + use std::{hint::black_box, io::Write as _, time::Instant}; + + for (name, pattern) in [ + ("plain", "Status OK 0123456789 "), + ("lines", "Status OK 0123456789\n"), + ("colours", "\u{1b}[32mStatus OK\u{1b}[0m\n"), + ("Unicode", "Status OK \u{00e9} \u{6771}\u{4eac}\n"), + ] { + for size in [64, 4096, MAX_WRITE] { + let input = pattern.repeat(size / pattern.len()); + let expected = terminal_output(&input); + assert_eq!(terminal_output_owned(input.clone()), expected); + let repeats = (1_000_000 / size).max(64); + let mut timings = [0; 7]; + for time in &mut timings { + let samples: Vec<_> = (0..repeats).map(|_| input.clone()).collect(); + let start = Instant::now(); + for sample in samples { + black_box(terminal_output_owned(black_box(sample))); + } + *time = start.elapsed().as_nanos() / repeats as u128; + } + timings.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{name} {} bytes, median {} ns", + input.len(), + timings[3], + ) + .unwrap(); + } + } +} + #[test] fn a_terminal_has_a_key_and_a_plain_title_and_a_write_is_bounded() { let local = LocalId::parse("servers").unwrap(); diff --git a/crates/plugin-api/src/view.rs b/crates/plugin-api/src/view.rs index 7d9c9eb2..8f7ab987 100644 --- a/crates/plugin-api/src/view.rs +++ b/crates/plugin-api/src/view.rs @@ -16,7 +16,13 @@ use alloc::{collections::BTreeSet, string::String, vec, vec::Vec}; use serde::{Deserialize, Serialize}; use thiserror::Error; -use crate::{Glyph, LimitError, error::key_syntax, sanitize::sanitize_code, sanitize_display}; +use crate::{ + Glyph, LimitError, + error::key_syntax, + sanitize::{ + is_sanitized_code, is_sanitized_display, sanitize_code_in_place, sanitize_display_in_place, + }, +}; /// Most nodes in one view. pub const MAX_NODES: usize = 256; @@ -239,6 +245,25 @@ pub struct View { pub refresh: Option, } +/// A sanitized and validated view. Read-only access preserves the validation result. +#[derive(Debug)] +pub struct ValidatedView(View); + +impl ValidatedView { + pub fn nodes(&self) -> &[Node] { + &self.0.nodes + } + + pub fn refresh(&self) -> Option { + self.0.refresh + } + + /// Returns the ordinary, editable view. + pub fn into_view(self) -> View { + self.0 + } +} + /// A view the host refuses to draw. The host draws a fixed-width fault chip instead. #[derive(Clone, Debug, PartialEq, Eq, Error)] pub enum ViewError { @@ -272,27 +297,27 @@ impl View { pub fn sanitize(&mut self) { for node in &mut self.nodes { match &mut node.kind { - NodeKind::Text(text) => *text = sanitize_display(text, MAX_TEXT), - NodeKind::Badge(text) => *text = sanitize_display(text, MAX_BADGE), - NodeKind::Button(text) => *text = sanitize_display(text, MAX_BUTTON), - NodeKind::Code(text) => *text = sanitize_code(text, MAX_CODE), - NodeKind::Caption(text) => *text = sanitize_display(text, MAX_TEXT), + NodeKind::Text(text) => sanitize_display_in_place(text, MAX_TEXT), + NodeKind::Badge(text) => sanitize_display_in_place(text, MAX_BADGE), + NodeKind::Button(text) => sanitize_display_in_place(text, MAX_BUTTON), + NodeKind::Code(text) => sanitize_code_in_place(text, MAX_CODE), + NodeKind::Caption(text) => sanitize_display_in_place(text, MAX_TEXT), NodeKind::Section { title, count, .. } => { - *title = sanitize_display(title, MAX_BUTTON); + sanitize_display_in_place(title, MAX_BUTTON); if let Some(count) = count { - *count = sanitize_display(count, MAX_BADGE); + sanitize_display_in_place(count, MAX_BADGE); } } NodeKind::Item { title, detail, .. } => { - *title = sanitize_display(title, MAX_TEXT); + sanitize_display_in_place(title, MAX_TEXT); if let Some(detail) = detail { - *detail = sanitize_display(detail, MAX_TEXT); + sanitize_display_in_place(detail, MAX_TEXT); } } - NodeKind::IconButton { label, .. } => *label = sanitize_display(label, MAX_BUTTON), + NodeKind::IconButton { label, .. } => sanitize_display_in_place(label, MAX_BUTTON), NodeKind::Field { label, value } => { - *label = sanitize_display(label, MAX_BUTTON); - *value = sanitize_display(value, MAX_TEXT); + sanitize_display_in_place(label, MAX_BUTTON); + sanitize_display_in_place(value, MAX_TEXT); } _ => {} } @@ -300,10 +325,15 @@ impl View { } /// Sanitizes, then validates. - pub fn into_validated(mut self) -> Result { + pub fn into_validated(self) -> Result { + self.validated().map(ValidatedView::into_view) + } + + /// Sanitizes and validates a view for handoff to downstream consumers. + pub fn validated(mut self) -> Result { self.sanitize(); self.validate()?; - Ok(self) + Ok(ValidatedView(self)) } /// Checks the arena: at most 256 nodes, every parent earlier and able to hold children, @@ -354,7 +384,7 @@ fn check_content(index: usize, kind: &NodeKind) -> Result<(), ViewError> { if text.chars().count() > max { return Err(limit(LimitError::TooLong { field, max })); } - if sanitize_display(text, max) != text { + if !is_sanitized_display(text) { return Err(limit(LimitError::Unsanitized { field })); } Ok(()) @@ -370,7 +400,7 @@ fn check_content(index: usize, kind: &NodeKind) -> Result<(), ViewError> { max: MAX_CODE, })); } - if sanitize_code(text, MAX_CODE) != *text { + if !is_sanitized_code(text) { return Err(limit(LimitError::Unsanitized { field: "code" })); } Ok(()) diff --git a/crates/plugin-host/src/cadence.rs b/crates/plugin-host/src/cadence.rs index 89e7bb8c..9da2d652 100644 --- a/crates/plugin-host/src/cadence.rs +++ b/crates/plugin-host/src/cadence.rs @@ -37,35 +37,39 @@ impl Cadence { call: &crate::Call, now: Instant, ) -> Result<(), u32> { + let matches_call = |(window, plugin, local): &(WindowId, PluginId, LocalId)| { + *window == call.window && plugin == &call.plugin && local == &call.local + }; self.waiting .retain(|(_, seen)| now.saturating_duration_since(*seen) < Duration::from_secs(2)); - let key = (call.window, call.plugin.clone(), call.local.clone()); - if let Some((_, seen)) = self.waiting.iter_mut().find(|(waiting, _)| *waiting == key) { + let queued = self + .waiting + .iter_mut() + .find(|(waiting, _)| matches_call(waiting)); + let queued = if let Some((_, seen)) = queued { *seen = now; - } - if self.waiting.front().is_some_and(|(first, _)| *first != key) { - self.wait_for(key, now); - return Err(100); - } - match self.admit_render(now) { - Ok(()) => { - if self.waiting.front().is_some_and(|(first, _)| *first == key) { - self.waiting.pop_front(); - } - Ok(()) - } - Err(wait) => { - self.wait_for(key, now); - Err(wait) - } - } - } - fn wait_for(&mut self, key: (WindowId, PluginId, LocalId), now: Instant) { - if !self.waiting.iter().any(|(waiting, _)| *waiting == key) - && self.waiting.len() < MAX_SAMPLES + true + } else { + false + }; + let result = if self + .waiting + .front() + .is_some_and(|(first, _)| !matches_call(first)) { + Err(100) + } else { + self.admit_render(now) + }; + if result.is_ok() { + if queued { + self.waiting.pop_front(); + } + } else if !queued && self.waiting.len() < MAX_SAMPLES { + let key = (call.window, call.plugin.clone(), call.local.clone()); self.waiting.push_back((key, now)); } + result } /// The last sample if it is younger than the cadence, else a fresh one from `read`. /// diff --git a/crates/plugin-host/src/deferred.rs b/crates/plugin-host/src/deferred.rs index d77b3200..0274880a 100644 --- a/crates/plugin-host/src/deferred.rs +++ b/crates/plugin-host/src/deferred.rs @@ -7,9 +7,15 @@ //! Disabling, replacing, removing or faulting a plugin forgets its timers and stops counting //! its requests, whose late answers are then dropped. -use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc, time::Duration}; +use std::{ + cell::RefCell, + collections::{BTreeMap, VecDeque}, + rc::Rc, + sync::Arc, + time::{Duration, Instant}, +}; -use gpui::{Context, Task, WindowId}; +use gpui::{AsyncApp, Context, Task, WeakEntity, WindowId}; use nocterm_plugin_api::{ ContentHash, Event, HostError, PluginNet, capability::{ @@ -96,10 +102,28 @@ impl InFlight { /// The waiting timers by plugin and key, each with the window it fires in. type Timers = BTreeMap<(PluginId, String), (WindowId, u64, Task<()>)>; +const RESPONSE_BUDGET: Duration = Duration::from_millis(8); +const RESPONSE_PAUSE: Duration = Duration::from_millis(1); + +struct ReadyResponse { + target: Target, + epoch: u64, + event: Event, +} + +/// Completed HTTP requests still hold their original in-flight slot until delivery. +#[derive(Default)] +struct Responses { + queue: VecDeque, + draining: bool, + resume_at: Option, +} + pub(crate) struct Deferred { net: Option>, admitted: Vec, in_flight: Rc>, + responses: Rc>, timers: Rc>, next_timer: u64, } @@ -110,6 +134,7 @@ impl Deferred { net, admitted: Vec::new(), in_flight: Rc::default(), + responses: Rc::default(), timers: Rc::default(), next_timer: 0, } @@ -191,18 +216,28 @@ impl Deferred { let plugin = target.call.plugin.clone(); let epoch = self.in_flight.borrow_mut().add(&plugin); let in_flight = self.in_flight.clone(); + let responses = self.responses.clone(); let answer = cx .background_executor() .spawn(async move { net.send(&call) }); cx.spawn(async move |host, cx| { let answer = answer.await; - in_flight.borrow_mut().done(&plugin, epoch); if in_flight.borrow().epoch(&plugin) != epoch { return; } - let _ = host.update(cx, |host, cx| { - deliver(host, &target, response(key, answer), cx); - }); + { + let mut responses = responses.borrow_mut(); + responses.queue.push_back(ReadyResponse { + target, + epoch, + event: response(key, answer), + }); + if responses.draining { + return; + } + responses.draining = true; + } + drain_responses(host, &in_flight, &responses, cx).await; }) .detach(); } @@ -239,6 +274,10 @@ impl Deferred { .borrow_mut() .retain(|(owner, _), _| owner != plugin); self.in_flight.borrow_mut().forget(plugin); + self.responses + .borrow_mut() + .queue + .retain(|answer| answer.target.call.plugin != *plugin); } /// A window closed: the timers that would wake its contributions go. @@ -251,6 +290,48 @@ impl Deferred { } } +async fn drain_responses( + host: WeakEntity, + in_flight: &RefCell, + responses: &RefCell, + cx: &mut AsyncApp, +) { + let executor = cx.background_executor().clone(); + let mut slice_start = executor.now(); + loop { + let resume_at = { + let mut responses = responses.borrow_mut(); + if responses.queue.is_empty() { + responses.draining = false; + return; + } + responses.resume_at.take() + }; + if let Some(delay) = + resume_at.and_then(|deadline| deadline.checked_duration_since(executor.now())) + { + // Pending platform input can run before the next synchronous guest call. + executor.timer(delay).await; + slice_start = executor.now(); + } + let Some(answer) = responses.borrow_mut().queue.pop_front() else { + continue; + }; + let plugin = &answer.target.call.plugin; + if in_flight.borrow().epoch(plugin) != answer.epoch { + continue; + } + in_flight.borrow_mut().done(plugin, answer.epoch); + let _ = host.update(cx, |host, cx| { + deliver(host, &answer.target, answer.event, cx); + }); + let now = executor.now(); + if now.duration_since(slice_start) >= RESPONSE_BUDGET { + responses.borrow_mut().resume_at = now.checked_add(RESPONSE_PAUSE); + } + } +} + fn answer_later(target: Target, key: String, answer: NetAnswer, cx: &mut Context) { cx.spawn(async move |host, cx| { let _ = host.update(cx, |host, cx| { diff --git a/crates/plugin-host/src/host.rs b/crates/plugin-host/src/host.rs index 5c978b40..01de0150 100644 --- a/crates/plugin-host/src/host.rs +++ b/crates/plugin-host/src/host.rs @@ -2,16 +2,16 @@ use std::{rc::Rc, sync::Arc}; -use gpui::{Context, Task, WindowId}; +use gpui::{Context, EventEmitter, Task, WindowId}; use nocterm_plugin_api::{ ContentHash, Effects, Event, Grant, Manifest, Package, PackageError, PluginInstance, - PluginPackages, PluginRuntime, Runtime, RuntimeError, View, + PluginPackages, PluginRuntime, Runtime, RuntimeError, SnapshotRef, ValidatedView, View, }; use nocterm_plugin_model::{PluginId, SettingValues, UserEntry}; use nocterm_plugin_ports::PluginProviders; use crate::{ - AuditEntry, BrokenPackage, Call, CallError, HostPorts, ManageError, PluginData, + AuditEntry, BrokenPackage, Call, CallError, GuestChanged, HostPorts, ManageError, PluginData, PluginDataChange, PluginDataDoc, PluginRecord, PluginRecords, PluginSummary, PreparedPlugin, RecordsError, broker::{Broker, Checked, Queued}, @@ -40,6 +40,8 @@ pub struct PluginHost { publication_error: Option, } +impl EventEmitter for PluginHost {} + impl PluginHost { pub fn new(ports: HostPorts) -> Self { Self { @@ -110,8 +112,8 @@ impl PluginHost { self.registry.summaries() } - /// Counts every change of what is installed, enabled, placeable or valued, so a reader can - /// tell that its copy is stale. + /// Counts management changes. Guest calls report their affected plugin through + /// [`GuestChanged`]. pub fn revision(&self) -> u64 { self.registry.revision() } @@ -480,6 +482,17 @@ impl PluginHost { providers: &PluginProviders, cx: &mut Context, ) -> Result { + self.render_validated(call, providers, cx) + .map(ValidatedView::into_view) + } + + /// Renders a contribution and carries its validation result to the renderer. + pub fn render_validated( + &mut self, + call: &Call, + providers: &PluginProviders, + cx: &mut Context, + ) -> Result { let now = cx.background_executor().now(); self.check_running(call)?; self.cadence @@ -487,10 +500,10 @@ impl PluginHost { .map_err(|retry_after_ms| CallError::Throttled { retry_after_ms })?; let outcomes = self.broker.outcomes(&call.plugin); let answer = self.guest(call, providers, outcomes, now, cx, |instance, snapshot| { - instance.render(&call.local, snapshot) + instance.render_borrowed(&call.local, snapshot) }); match answer { - Ok(view) => view.into_validated().map_err(|error| { + Ok(view) => view.validated().map_err(|error| { self.refused_reply(&call.plugin, cx); CallError::from(error) }), @@ -515,7 +528,7 @@ impl PluginHost { .mint(&call.plugin, call.window, &call.local, &event, input, now); let outcomes = self.broker.take_outcomes(&call.plugin); let answer = self.guest(call, providers, outcomes, now, cx, |instance, snapshot| { - instance.on_event(&call.local, event, snapshot) + instance.on_event_borrowed(&call.local, event, snapshot) }); let effects = match answer { Ok(effects) => effects, @@ -606,8 +619,7 @@ impl PluginHost { return Err(CallError::NotRunning(call.plugin.clone())); } let handled = self.handle(call, Input::Host, event, providers, cx); - self.registry.touch(); - cx.notify(); + cx.emit(GuestChanged(call.plugin.clone())); handled } @@ -619,10 +631,7 @@ impl PluginHost { outcomes: Vec, now: std::time::Instant, cx: &mut Context, - run: impl FnOnce( - &dyn nocterm_plugin_api::PluginInstance, - &nocterm_plugin_api::Snapshot, - ) -> Result, + run: impl FnOnce(&dyn PluginInstance, SnapshotRef<'_>) -> Result, ) -> Result { let Some(ready) = self.registry.running(&call.plugin, None) else { return Err(RuntimeError::Trap); @@ -638,8 +647,9 @@ impl PluginHost { providers, ) .for_terminal(call.terminal.as_deref()); - let snapshot = assemble(ready, &subject, &mut self.cadence, outcomes, now, cx); - run(ready.instance(self.runtime.as_ref())?, &snapshot) + let fields = assemble(ready, &subject, &mut self.cadence, outcomes, now, cx); + let (instance, data) = ready.instance_and_data(self.runtime.as_ref())?; + run(instance, fields.with_storage(&data.storage)) } /// Counts a runtime failure when it is the plugin's fault. diff --git a/crates/plugin-host/src/lib.rs b/crates/plugin-host/src/lib.rs index 7c42f545..d39b4bc1 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -19,6 +19,7 @@ //! written. //! Owns: checked publication receipts and prepared package/runtime admission, bounded //! per-window samples and fair retry admission; closing a window releases its retained samples. +//! Host-originated guest calls invalidate that plugin's views through a typed event. //! Does not own: any provider or the `Observe`/`Apply` traits (`nocterm-plugin-ports`), the //! packages on disk (`PluginPackages`), a runtime, views, consent dialogs, settings forms or any //! settings section. @@ -76,5 +77,14 @@ pub use records::{ pub use registry::{PluginStatus, PluginSummary, RestoredPlugin}; pub use session::{SessionData, SessionRecords}; +/// A host-originated guest call may have changed what this plugin shows. +pub struct GuestChanged(nocterm_plugin_model::PluginId); + +impl GuestChanged { + pub fn plugin(&self) -> &nocterm_plugin_model::PluginId { + &self.0 + } +} + #[cfg(test)] mod tests; diff --git a/crates/plugin-host/src/registry.rs b/crates/plugin-host/src/registry.rs index 27e7081a..e04e0f30 100644 --- a/crates/plugin-host/src/registry.rs +++ b/crates/plugin-host/src/registry.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use nocterm_plugin_api::{ ContentHash, Grant, Package, PluginInstance, PluginRuntime, RuntimeError, }; -use nocterm_plugin_model::{PluginId, SettingValues, resolve}; +use nocterm_plugin_model::{PluginId, SettingValues, resolve, resolve_visible}; use crate::{ BrokenPackage, ManageError, PluginDataDoc, PluginDataError, PluginRecord, RecordsDoc, @@ -112,15 +112,15 @@ impl Ready { } /// The running instance, created on first use. - pub(crate) fn instance( + pub(crate) fn instance_and_data( &mut self, runtime: &dyn PluginRuntime, - ) -> Result<&dyn PluginInstance, RuntimeError> { + ) -> Result<(&dyn PluginInstance, &PluginDataDoc), RuntimeError> { if self.instance.is_none() { self.instance = Some(runtime.instantiate(&self.package)?); } match &self.instance { - Some(instance) => Ok(instance.as_ref()), + Some(instance) => Ok((instance.as_ref(), self.data())), None => Err(RuntimeError::Trap), } } @@ -195,6 +195,11 @@ impl Ready { crate::net::bind_credential(self.package.manifest(), &self.settings(), values.clone()) } + pub(crate) fn visible_settings(&self) -> SettingValues { + let schema = self.package.manifest().plugin().settings(); + resolve_visible(schema, |key| self.data().values.get(key).map(Into::into)) + } + pub(crate) fn settings(&self) -> SettingValues { let schema = self.package.manifest().plugin().settings(); resolve(schema, &self.data().setting_values()).0 diff --git a/crates/plugin-host/src/snapshot.rs b/crates/plugin-host/src/snapshot.rs index b4929a2e..ad59a438 100644 --- a/crates/plugin-host/src/snapshot.rs +++ b/crates/plugin-host/src/snapshot.rs @@ -1,12 +1,13 @@ //! What a plugin is shown: the snapshot the host assembles for one call. -use std::time::Instant; +use std::{collections::BTreeMap, time::Instant}; use gpui::App; use nocterm_plugin_api::{ - ContributionContext, EffectOutcome, Family, HostError, Snapshot, capability::capability, + ContributionContext, EffectOutcome, Family, HostError, Observed, SnapshotRef, + capability::capability, }; -use nocterm_plugin_model::PluginId; +use nocterm_plugin_model::{PluginId, SettingValues}; use nocterm_plugin_ports::PluginProviders; use crate::{cadence::Cadence, registry::Ready}; @@ -45,20 +46,44 @@ impl<'a> Subject<'a> { } } +/// The per-call fields assembled by the host. Persistent storage stays in Ready. +pub(crate) struct CallFields<'a> { + observations: BTreeMap>, + settings: SettingValues, + context: ContributionContext, + outcomes: Vec, + terminal: Option<&'a str>, +} + +impl CallFields<'_> { + pub(crate) fn with_storage<'a>( + &'a self, + storage: &'a BTreeMap, + ) -> SnapshotRef<'a> { + SnapshotRef { + observations: &self.observations, + settings: &self.settings, + storage, + context: self.context, + outcomes: &self.outcomes, + terminal: self.terminal, + } + } +} + /// The snapshot for a plugin: its granted observations (sampled no faster than the cadence), /// its resolved settings, its storage and the outcomes of its last effects. -pub(crate) fn assemble( +pub(crate) fn assemble<'a>( ready: &Ready, - subject: &Subject<'_>, + subject: &Subject<'a>, cadence: &mut Cadence, outcomes: Vec, now: Instant, cx: &App, -) -> Snapshot { +) -> CallFields<'a> { let manifest = ready.package().manifest(); let hash = ready.package().hash(); - let mut snapshot = Snapshot::new(subject.context); - snapshot.terminal = subject.terminal.map(str::to_owned); + let mut observations = BTreeMap::new(); let declared = manifest .required() .iter() @@ -66,9 +91,7 @@ pub(crate) fn assemble( .chain(manifest.optional().iter().map(|optional| optional.id())); for id in declared { let Some(entry) = capability(id) else { - snapshot - .observations - .insert(id.to_owned(), Err(HostError::Unavailable)); + observations.insert(id.to_owned(), Err(HostError::Unavailable)); continue; }; if entry.family != Family::Observe { @@ -83,14 +106,13 @@ pub(crate) fn assemble( ), Err(error) => Err(error), }; - snapshot.observations.insert(entry.id.to_owned(), result); + observations.insert(entry.id.to_owned(), result); + } + CallFields { + observations, + settings: ready.visible_settings(), + context: subject.context, + outcomes, + terminal: subject.terminal, } - // A plugin names its secret settings for the host to send and never reads them. - snapshot.settings = manifest - .plugin() - .settings() - .without_secrets(&ready.settings()); - snapshot.storage = ready.data().storage.clone(); - snapshot.outcomes = outcomes; - snapshot } diff --git a/crates/plugin-host/src/test_support.rs b/crates/plugin-host/src/test_support.rs index 2a27b973..843a8dc3 100644 --- a/crates/plugin-host/src/test_support.rs +++ b/crates/plugin-host/src/test_support.rs @@ -247,6 +247,8 @@ struct ScriptState { snapshots: Vec, seen: Vec, instances: usize, + #[cfg(test)] + response_clock: Option, } impl Default for Script { @@ -268,6 +270,8 @@ impl Script { snapshots: Vec::new(), seen: Vec::new(), instances: 0, + #[cfg(test)] + response_clock: None, })), } } @@ -288,6 +292,11 @@ impl Script { self.state().events.push_back(answer); } + #[cfg(test)] + pub(crate) fn spend_time_on_each_response(&self, executor: gpui::BackgroundExecutor) { + self.state().response_clock = Some(executor); + } + /// Every snapshot the guest was given, oldest first. pub fn snapshots(&self) -> Vec { self.state().snapshots.clone() @@ -337,6 +346,12 @@ impl PluginInstance for ScriptedInstance { ) -> Result { let mut state = self.0.state(); state.snapshots.push(snapshot.clone()); + #[cfg(test)] + if matches!(event, Event::Response { .. }) + && let Some(clock) = &state.response_clock + { + clock.advance_clock(std::time::Duration::from_millis(9)); + } state.seen.push(event); state.events.pop_front().unwrap_or(Ok(Effects::default())) } diff --git a/crates/plugin-host/src/tests/calls.rs b/crates/plugin-host/src/tests/calls.rs index c1e0d59c..72c3190e 100644 --- a/crates/plugin-host/src/tests/calls.rs +++ b/crates/plugin-host/src/tests/calls.rs @@ -212,6 +212,34 @@ fn waiting_contributions_get_a_turn_before_a_busy_window_renders_again(cx: &mut rig.render("face", cx).unwrap(); } +#[gpui::test] +fn retrying_keeps_a_contributions_place_until_it_stops_retrying(cx: &mut TestAppContext) { + let rig = Rig::new(cx); + rig.installed(cx); + for _ in 0..MAX_RENDERS_PER_SECOND { + rig.render("face", cx).unwrap(); + } + let mut other = rig.call("face"); + other.window = super::rig::windows(cx)[1]; + let render_other = |cx: &mut TestAppContext| { + rig.host + .update(cx, |host, cx| host.render(&other, &rig.providers, cx)) + }; + assert!(matches!(render_other(cx), Err(CallError::Throttled { .. }))); + + cx.executor().advance_clock(Duration::from_millis(750)); + assert!(matches!(render_other(cx), Err(CallError::Throttled { .. }))); + + cx.executor().advance_clock(Duration::from_millis(1_250)); + assert!(matches!( + rig.render("face", cx), + Err(CallError::Throttled { .. }) + )); + + cx.executor().advance_clock(Duration::from_millis(750)); + rig.render("face", cx).unwrap(); +} + #[gpui::test] fn renders_are_capped_across_plugins_and_come_back_each_second(cx: &mut TestAppContext) { let rig = Rig::new(cx); diff --git a/crates/plugin-host/src/tests/deferred.rs b/crates/plugin-host/src/tests/deferred.rs index 713c398c..50b5ab31 100644 --- a/crates/plugin-host/src/tests/deferred.rs +++ b/crates/plugin-host/src/tests/deferred.rs @@ -144,6 +144,80 @@ fn at_most_four_requests_are_in_flight(cx: &mut TestAppContext) { assert!(limited, "the fifth request is refused"); } +fn start_slow_response_burst(cx: &mut TestAppContext) -> Rig { + let rig = connected("https://service.example", "k", cx); + rig.script.spend_time_on_each_response(cx.executor()); + rig.script.answer_event(Ok(effects( + ["a", "b", "c", "d"] + .into_iter() + .map(|key| (Some(key), request("/x"))) + .collect(), + ))); + rig.event("face", Input::Host, Event::SettingsChanged, cx) + .unwrap(); + while cx.executor().tick() {} + rig +} + +fn response_keys(rig: &Rig) -> Vec { + rig.script + .events() + .into_iter() + .filter_map(|event| match event { + Event::Response { key, .. } => Some(key), + _ => None, + }) + .collect() +} + +#[gpui::test] +fn other_events_can_run_before_a_slow_response_burst_finishes(cx: &mut TestAppContext) { + let rig = start_slow_response_burst(cx); + assert_eq!(rig.net.calls().len(), 4); + assert_eq!(response_keys(&rig).len(), 1); + rig.event("face", Input::Host, Event::SettingsChanged, cx) + .unwrap(); + assert_eq!(rig.script.events().last(), Some(&Event::SettingsChanged)); + for delivered in 2..=4 { + cx.executor().advance_clock(Duration::from_millis(1)); + while cx.executor().tick() {} + assert_eq!(response_keys(&rig).len(), delivered); + } + let mut keys = response_keys(&rig); + keys.sort(); + assert_eq!(keys, ["a", "b", "c", "d"]); +} + +#[gpui::test] +fn disabling_the_plugin_discards_ready_responses(cx: &mut TestAppContext) { + let rig = start_slow_response_burst(cx); + let delivered = response_keys(&rig); + assert_eq!(delivered.len(), 1); + let plugin = crate::test_support::plugin_id(); + rig.host + .update(cx, |host, cx| host.set_enabled(&plugin, false, cx)) + .unwrap(); + cx.executor().advance_clock(Duration::from_secs(1)); + while cx.executor().tick() {} + assert_eq!(response_keys(&rig), delivered); +} + +#[gpui::test] +fn collected_responses_keep_their_request_slots_until_delivery(cx: &mut TestAppContext) { + let rig = start_slow_response_burst(cx); + rig.script.answer_event(Ok(effects(vec![ + (Some("e"), request("/available")), + (Some("f"), request("/over-limit")), + ]))); + rig.event("face", Input::Host, Event::SettingsChanged, cx) + .unwrap(); + while cx.executor().tick() {} + let calls = rig.net.calls(); + assert_eq!(calls.len(), 5); + assert!(calls.iter().any(|call| call.url.ends_with("/available"))); + assert_eq!(response_keys(&rig).len(), 1); +} + #[gpui::test] fn a_timer_wakes_the_plugin_once_and_a_disabled_plugin_hears_nothing(cx: &mut TestAppContext) { let rig = connected("https://service.example", "k", cx); diff --git a/crates/plugin-host/src/tests/lifecycle.rs b/crates/plugin-host/src/tests/lifecycle.rs index aa8cd39f..126b02e5 100644 --- a/crates/plugin-host/src/tests/lifecycle.rs +++ b/crates/plugin-host/src/tests/lifecycle.rs @@ -1,5 +1,5 @@ use gpui::TestAppContext; -use nocterm_plugin_api::{ContentHash, HostError}; +use nocterm_plugin_api::{ContentHash, Event, HostError}; use super::rig::{Rig, activated, effects, post_effect}; use crate::{ @@ -503,7 +503,19 @@ async fn a_failed_records_publication_is_returned_and_does_not_destroy_original_ .unwrap(); rig.records.refuse_writes(); rig.host - .update(cx, |host, cx| host.replace(package(2), &[], true, cx)) + .update(cx, |host, cx| { + host.replace(package(2), &[], true, cx)?; + // A guest callback may arrive while this records receipt is still pending. + host.deliver( + &rig.call("board"), + None, + Event::VisibilityChanged { visible: true }, + &rig.providers, + cx, + ) + .expect("the replacement can receive events"); + Ok::<_, ManageError>(()) + }) .unwrap(); let failed = rig.host.update(cx, |host, _| host.take_publication()).await; assert!(matches!(failed, Err(crate::RecordsError::Write(_)))); diff --git a/crates/plugin-model/src/lib.rs b/crates/plugin-model/src/lib.rs index 994dda04..f949da44 100644 --- a/crates/plugin-model/src/lib.rs +++ b/crates/plugin-model/src/lib.rs @@ -50,8 +50,8 @@ pub use plugin::SystemPlugin; pub use schema::{ ChoiceOption, FieldEdit, FieldError, FieldGroup, FieldIssue, FieldKind, FieldSpec, MAX_FIELDS, MAX_GROUPS, MAX_HELP, MAX_KEY, MAX_LABEL, MAX_OPTIONS, MAX_TEXT_LEN, SchemaError, SchemaLimit, - SettingValue, SettingValues, SettingsSchema, apply, bounded, resolve, sanitize_text, - toggle_choice, + SettingValue, SettingValues, SettingsSchema, apply, bounded, resolve, resolve_visible, + sanitize_text, sanitized_text_chars, toggle_choice, }; pub use set::{PluginSet, PluginSetError, SetOwner, UserAvailability, UserEntry}; pub use user::{ diff --git a/crates/plugin-model/src/schema.rs b/crates/plugin-model/src/schema.rs index b5831d8a..bc5e73e6 100644 --- a/crates/plugin-model/src/schema.rs +++ b/crates/plugin-model/src/schema.rs @@ -19,8 +19,8 @@ mod validate; mod values; pub use edit::{FieldError, apply, bounded, toggle_choice}; -pub use resolve::{FieldIssue, resolve}; -pub use text::sanitize_text; +pub use resolve::{FieldIssue, resolve, resolve_visible}; +pub use text::{sanitize_text, sanitized_text_chars}; pub use validate::{ MAX_FIELDS, MAX_GROUPS, MAX_HELP, MAX_KEY, MAX_LABEL, MAX_OPTIONS, MAX_TEXT_LEN, SchemaError, SchemaLimit, diff --git a/crates/plugin-model/src/schema/edit.rs b/crates/plugin-model/src/schema/edit.rs index cdda7474..58ce418a 100644 --- a/crates/plugin-model/src/schema/edit.rs +++ b/crates/plugin-model/src/schema/edit.rs @@ -4,7 +4,8 @@ use alloc::{string::String, string::ToString, vec::Vec}; use thiserror::Error; use super::{ - ChoiceOption, FieldEdit, FieldKind, SettingValue, SettingValues, SettingsSchema, sanitize_text, + ChoiceOption, FieldEdit, FieldKind, FieldSpec, SettingValue, SettingValues, SettingsSchema, + sanitize_text, }; /// An edit the schema refuses. The text is meant to appear under the field. @@ -36,6 +37,15 @@ pub fn apply( let field = schema .field(key) .ok_or_else(|| FieldError::UnknownKey(key.to_string()))?; + apply_field(field, current, edit) +} + +pub(super) fn apply_field( + field: &FieldSpec, + current: &SettingValues, + edit: FieldEdit, +) -> Result { + let key = field.key.as_ref(); let wrong_kind = || FieldError::WrongKind { key: key.to_string(), }; @@ -68,7 +78,6 @@ pub fn apply( }, FieldEdit::Toggle { option, on }, ) => { - let key = field.key.as_ref(); check_option(key, options, &option)?; let base = field .current(current) diff --git a/crates/plugin-model/src/schema/resolve.rs b/crates/plugin-model/src/schema/resolve.rs index 12a2fa75..005bcebe 100644 --- a/crates/plugin-model/src/schema/resolve.rs +++ b/crates/plugin-model/src/schema/resolve.rs @@ -3,7 +3,10 @@ use alloc::{string::String, string::ToString, vec::Vec}; use thiserror::Error; -use super::{FieldEdit, FieldError, SettingValues, SettingsSchema, apply}; +use super::{ + FieldEdit, FieldError, FieldSpec, SettingValue, SettingValues, SettingsSchema, + edit::apply_field, +}; /// A stored value the schema could not keep. The field shows its default instead. #[derive(Clone, Debug, PartialEq, Eq, Error)] @@ -25,37 +28,46 @@ pub enum FieldIssue { /// default and is reported as an issue. /// - A field the document does not hold takes its default. /// -/// Every value passes through [`apply`], so text is sanitized and bounded as an edit would be. +/// Every value passes through [`apply`](super::apply), so text is sanitized and bounded as an edit would be. pub fn resolve(schema: &SettingsSchema, raw: &SettingValues) -> (SettingValues, Vec) { let mut values = SettingValues::default(); let mut issues = Vec::new(); for field in schema.fields() { - let stored = raw.get(&field.key).or_else(|| { - field - .renamed_from - .as_deref() - .and_then(|previous| raw.get(previous)) + let value = read_field(field, |key| raw.get(key).cloned()).unwrap_or_else(|error| { + issues.push(issue(error, &field.key)); + field.kind.default_value() }); - let value = match stored { - None => field.kind.default_value(), - Some(stored) => match apply( - schema, - &SettingValues::default(), - &field.key, - FieldEdit::Set(stored.clone()), - ) { - Ok(value) => value, - Err(error) => { - issues.push(issue(error, &field.key)); - field.kind.default_value() - } - }, - }; values.insert(field.key.to_string(), value); } (values, issues) } +/// Resolves the settings a user plugin may read. Secret fields are omitted +/// before reading the persisted values. The current key takes precedence over +/// a legacy alias, and invalid or missing values take the field's default. +pub fn resolve_visible( + schema: &SettingsSchema, + mut get: impl FnMut(&str) -> Option, +) -> SettingValues { + let mut visible = SettingValues::default(); + for field in schema.fields().filter(|field| !field.kind.is_secret()) { + let value = read_field(field, &mut get).unwrap_or_else(|_| field.kind.default_value()); + visible.insert(field.key.as_ref(), value); + } + visible +} + +fn read_field( + field: &FieldSpec, + mut get: impl FnMut(&str) -> Option, +) -> Result { + let stored = get(&field.key).or_else(|| field.renamed_from.as_deref().and_then(get)); + match stored { + None => Ok(field.kind.default_value()), + Some(stored) => apply_field(field, &SettingValues::default(), FieldEdit::Set(stored)), + } +} + fn issue(error: FieldError, key: &str) -> FieldIssue { match error { FieldError::UnknownOption { option, .. } => FieldIssue::RemovedOption { diff --git a/crates/plugin-model/src/schema/resolve_tests.rs b/crates/plugin-model/src/schema/resolve_tests.rs index 245fab33..fe090450 100644 --- a/crates/plugin-model/src/schema/resolve_tests.rs +++ b/crates/plugin-model/src/schema/resolve_tests.rs @@ -210,3 +210,35 @@ fn renamed_from_must_be_a_fresh_valid_key() { )); assert!(schema_of(vec![moved]).validate(&[]).is_ok()); } + +#[test] +fn a_guest_reads_visible_fields_and_legacy_aliases_without_reading_secret_values() { + let mut schema = renamed(); + let mut secret = field("token", text("", 16)); + secret.renamed_from = Some(Cow::Borrowed("old_token")); + if let FieldKind::Text { secret, .. } = &mut secret.kind { + *secret = true; + } + schema.groups.to_mut()[0].fields.to_mut().push(secret); + let stored = values(&[ + ("city", SettingValue::Text("Rome".into())), + ("token", SettingValue::Text("example".into())), + ("old_token", SettingValue::Text("example".into())), + ("ignored", SettingValue::Bool(true)), + ]); + let mut lookups = vec![]; + let visible = resolve_visible(&schema, |key| { + lookups.push(key.to_string()); + stored.get(key).cloned() + }); + + assert_eq!(lookups, ["town", "city"]); + assert_eq!( + visible, + schema.without_secrets(&resolve(&schema, &stored).0) + ); + assert_eq!( + visible.get("town"), + Some(&SettingValue::Text("Rome".into())) + ); +} diff --git a/crates/plugin-model/src/schema/text.rs b/crates/plugin-model/src/schema/text.rs index e5ad286b..7f768cc8 100644 --- a/crates/plugin-model/src/schema/text.rs +++ b/crates/plugin-model/src/schema/text.rs @@ -19,19 +19,24 @@ const MAX_MARKS: usize = 2; /// spelling. That is deliberate: an invisible character cannot be told from a hidden payload. pub fn sanitize_text(raw: &str) -> String { let mut text = String::with_capacity(raw.len()); + text.extend(sanitized_text_chars(raw)); + text +} + +/// Produces the same characters as [`sanitize_text`] without building a string. +pub fn sanitized_text_chars(raw: &str) -> impl Iterator + '_ { let mut marks = 0; - for character in raw.chars().filter(|character| !is_invisible(*character)) { + raw.chars().filter(move |&character| { + if is_invisible(character) { + return false; + } if is_stacking_mark(character) { marks += 1; - if marks > MAX_MARKS { - continue; - } } else { marks = 0; } - text.push(character); - } - text + marks <= MAX_MARKS + }) } /// A control character, a line or paragraph separator, an interlinear annotation character or a diff --git a/crates/plugin-net/src/lib.rs b/crates/plugin-net/src/lib.rs index 3d4c918c..fcac669d 100644 --- a/crates/plugin-net/src/lib.rs +++ b/crates/plugin-net/src/lib.rs @@ -14,7 +14,10 @@ //! failure is a status-0 answer with words for the plugin, not an error of the application. //! Calls block: the host runs them on a background thread. -use std::{io::Read as _, time::Duration}; +use std::{ + io::{self, Read as _}, + time::Duration, +}; use nocterm_plugin_api::{ PluginNet, @@ -110,25 +113,29 @@ fn checked_url(call: &NetCall) -> Result { fn answer(response: reqwest::blocking::Response) -> NetAnswer { let status = response.status().as_u16(); - let mut bytes = Vec::new(); - if let Err(error) = response.take(MAX_RESPONSE as u64).read_to_end(&mut bytes) { - return NetAnswer::failed(format!("the answer broke off: {error}")); - } - NetAnswer { - status, - body: String::from_utf8_lossy(&bytes).into_owned(), - } + let bytes = match read_body(response, MAX_RESPONSE) { + Ok(bytes) => bytes, + Err(error) => return NetAnswer::failed(format!("the answer broke off: {error}")), + }; + // Reuse a full buffer for valid text. Finalize a partially filled buffer as + // compact text so the response event does not keep the spare read capacity. + let body = if bytes.capacity() == bytes.len() { + String::from_utf8(bytes) + .unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned()) + } else { + String::from_utf8_lossy(&bytes).into_owned() + }; + NetAnswer { status, body } } /// The answer to a `bytes` request: its bytes as base64, or status 0 when there are more than /// [`MAX_BYTES_RESPONSE`], since a cut file would be a wrong one. fn answer_bytes(response: reqwest::blocking::Response) -> NetAnswer { let status = response.status().as_u16(); - let mut bytes = Vec::new(); - let limit = MAX_BYTES_RESPONSE as u64 + 1; - if let Err(error) = response.take(limit).read_to_end(&mut bytes) { - return NetAnswer::failed(format!("the answer broke off: {error}")); - } + let bytes = match read_body(response, MAX_BYTES_RESPONSE + 1) { + Ok(bytes) => bytes, + Err(error) => return NetAnswer::failed(format!("the answer broke off: {error}")), + }; if bytes.len() > MAX_BYTES_RESPONSE { return NetAnswer::failed(format!( "the answer is larger than {} KiB", @@ -141,6 +148,54 @@ fn answer_bytes(response: reqwest::blocking::Response) -> NetAnswer { } } +fn read_body(response: reqwest::blocking::Response, limit: usize) -> io::Result> { + const PREFIX: usize = 8 * 1024; + let length = response.content_length(); + let mut reader = response.take(limit as u64); + let Some(length) = length else { + return read_stream(&mut reader, PREFIX.min(limit), limit); + }; + let expected = length.min(limit as u64) as usize; + // Wait for a prefix before reserving a large advertised body. + let mut bytes = Vec::with_capacity(expected.min(PREFIX)); + if expected > PREFIX { + reader + .by_ref() + .take(PREFIX as u64) + .read_to_end(&mut bytes)?; + if bytes.len() == PREFIX { + bytes.reserve_exact(expected - PREFIX); + } + } + reader.read_to_end(&mut bytes)?; + Ok(bytes) +} + +fn read_stream(reader: &mut impl io::Read, mut end: usize, limit: usize) -> io::Result> { + let mut bytes = Vec::new(); + loop { + reader + .by_ref() + .take((end - bytes.len()) as u64) + .read_to_end(&mut bytes)?; + if bytes.len() < end || end == limit { + return Ok(bytes); + } + + // The stream may end at a buffer boundary. Grow only after reading more. + let mut next = [0]; + match reader.read(&mut next) { + Ok(0) => return Ok(bytes), + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + } + end = (end * 2).min(limit); + bytes.reserve_exact(end - bytes.len()); + bytes.push(next[0]); + } +} + /// Words for a failed request, without the address or anything the request carried. fn failure(error: &reqwest::Error) -> &'static str { if error.is_timeout() { diff --git a/crates/plugin-net/src/tests.rs b/crates/plugin-net/src/tests.rs index 40610af4..5eb069ae 100644 --- a/crates/plugin-net/src/tests.rs +++ b/crates/plugin-net/src/tests.rs @@ -9,7 +9,7 @@ use std::{ use nocterm_plugin_api::{ PluginNet, - capability::net::{MAX_RESPONSE, Method, NetCall, Origin}, + capability::net::{MAX_BYTES_RESPONSE, MAX_RESPONSE, Method, NetCall, Origin}, }; use crate::HttpPluginNet; @@ -70,6 +70,17 @@ fn reply_with(body: &[u8]) -> Vec { reply } +fn chunked_reply(body: &[u8]) -> Vec { + let mut reply = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec(); + for chunk in body.chunks(4 * 1024) { + write!(reply, "{:x}\r\n", chunk.len()).unwrap(); + reply.extend_from_slice(chunk); + reply.extend_from_slice(b"\r\n"); + } + reply.extend_from_slice(b"0\r\n\r\n"); + reply +} + #[test] fn a_bytes_request_sends_raw_bytes_and_answers_with_base64_of_every_byte() { let binary: Vec = (0..=255).collect(); @@ -91,13 +102,31 @@ fn a_bytes_request_sends_raw_bytes_and_answers_with_base64_of_every_byte() { #[test] fn a_bytes_answer_larger_than_its_limit_is_refused_and_not_cut() { - let large = vec![b'x'; nocterm_plugin_api::capability::net::MAX_BYTES_RESPONSE + 1]; - let (origin, _seen) = serve_bytes(reply_with(&large)); - let mut read = call(&origin, Method::Get, "/files/contents?file=/big", None); - read.bytes = true; - let answer = HttpPluginNet::new().send(&read); - assert_eq!(answer.status, 0); - assert!(answer.body.contains("larger than"), "{}", answer.body); + let large = vec![b'x'; MAX_BYTES_RESPONSE + 1]; + for reply in [reply_with(&large), chunked_reply(&large)] { + let (origin, _seen) = serve_bytes(reply); + let mut read = call(&origin, Method::Get, "/files/contents?file=/big", None); + read.bytes = true; + let answer = HttpPluginNet::new().send(&read); + assert_eq!(answer.status, 0); + assert!(answer.body.contains("larger than"), "{}", answer.body); + } +} + +#[test] +fn a_binary_body_at_the_limit_is_delivered_whole() { + let body: Vec = (0..=255).cycle().take(MAX_BYTES_RESPONSE).collect(); + for reply in [reply_with(&body), chunked_reply(&body)] { + let (origin, _) = serve_bytes(reply); + let mut read = call(&origin, Method::Get, "/body", None); + read.bytes = true; + let answer = HttpPluginNet::new().send(&read); + assert_eq!(answer.status, 200); + assert_eq!( + nocterm_plugin_api::base64::decode(&answer.body), + Some(body.clone()) + ); + } } #[test] @@ -131,18 +160,34 @@ fn a_redirect_is_answered_as_it_came_and_never_followed() { #[test] fn an_answer_is_cut_at_the_response_limit() { - let body: &'static str = Box::leak( - format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", - MAX_RESPONSE + 10, - "x".repeat(MAX_RESPONSE + 10) - ) - .into_boxed_str(), - ); - let (origin, _) = serve_once(body); - let answer = HttpPluginNet::new().send(&call(&origin, Method::Get, "/big", None)); + let mut body = vec![b'x'; MAX_RESPONSE - 1]; + body.extend_from_slice("界".as_bytes()); + for reply in [reply_with(&body), chunked_reply(&body)] { + let (origin, _) = serve_bytes(reply); + let answer = HttpPluginNet::new().send(&call(&origin, Method::Get, "/big", None)); + assert_eq!(answer.status, 200); + assert_eq!(answer.body, String::from_utf8_lossy(&body[..MAX_RESPONSE])); + } +} + +#[test] +fn a_body_delimited_by_connection_close_keeps_every_byte() { + let message = "hello 界".repeat(8 * 1024); + let mut reply = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".to_vec(); + reply.extend_from_slice(message.as_bytes()); + let (origin, _) = serve_bytes(reply); + let answer = HttpPluginNet::new().send(&call(&origin, Method::Get, "/body", None)); assert_eq!(answer.status, 200); - assert_eq!(answer.body.len(), MAX_RESPONSE); + assert_eq!(answer.body, message); +} + +#[test] +fn a_body_that_breaks_off_early_reports_failure() { + let (origin, _) = + serve_once("HTTP/1.1 200 OK\r\nContent-Length: 262144\r\nConnection: close\r\n\r\na"); + let answer = HttpPluginNet::new().send(&call(&origin, Method::Get, "/body", None)); + assert_eq!(answer.status, 0); + assert!(answer.body.starts_with("the answer broke off")); } #[test] @@ -163,3 +208,66 @@ fn an_unreachable_server_is_a_status_zero_answer_in_plain_words() { assert_eq!(answer.status, 0); assert!(!answer.body.contains("127.0.0.1"), "{}", answer.body); } + +fn concurrent_reads( + client: &HttpPluginNet, + reply: &[u8], + expected: &str, + workers: usize, +) -> std::time::Duration { + let calls: Vec<_> = (0..workers) + .map(|_| { + let (origin, received) = serve_bytes(reply.to_vec()); + (call(&origin, Method::Get, "/body", None), received) + }) + .collect(); + let ready = std::sync::Barrier::new(workers); + thread::scope(|scope| { + let jobs: Vec<_> = calls + .into_iter() + .map(|(call, received)| { + let ready = &ready; + scope.spawn(move || { + ready.wait(); + let start = std::time::Instant::now(); + let answer = client.send(&call); + let elapsed = start.elapsed(); + assert_eq!(answer.status, 200); + assert_eq!(answer.body, expected); + assert!(received.recv().unwrap().starts_with("GET /body ")); + elapsed + }) + }) + .collect(); + jobs.into_iter() + .map(|job| job.join().unwrap()) + .max() + .unwrap() + }) +} + +#[test] +#[ignore = "release measurement of real fixed-length and streaming responses"] +fn measure_plugin_http_body_reads() { + const REPEATS: usize = 11; + let client = HttpPluginNet::new(); + let body = "x".repeat(MAX_RESPONSE); + for (framing, reply) in [ + ("length", reply_with(body.as_bytes())), + ("chunked", chunked_reply(body.as_bytes())), + ] { + for workers in [1, 8] { + let mut samples = [std::time::Duration::ZERO; REPEATS]; + for sample in &mut samples { + *sample = concurrent_reads(&client, &reply, &body, workers); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "framing={framing} requests={workers} median_batch_request={:?}", + samples[REPEATS / 2] + ) + .unwrap(); + } + } +} diff --git a/crates/plugin-packages/src/parse.rs b/crates/plugin-packages/src/parse.rs index f1982192..915451c6 100644 --- a/crates/plugin-packages/src/parse.rs +++ b/crates/plugin-packages/src/parse.rs @@ -25,6 +25,29 @@ pub fn sha256(bytes: &[u8]) -> ContentHash { /// within the declared API, and the declared runtime must be the one the kind of file runs on. pub fn parse_package(bytes: Vec, reserved_names: &[&str]) -> Result { let hash = sha256(&bytes); + parse_hashed_package(bytes, reserved_names, hash) +} + +/// Verifies the freshly read bytes before parsing, then uses that exact digest +/// for the receipt. A mismatch is not a parse error and the store may continue +/// its existing search for the consented version. +pub(super) fn parse_matching_package( + bytes: Vec, + reserved_names: &[&str], + expected: &ContentHash, +) -> Result, PackageError> { + let hash = sha256(&bytes); + if &hash != expected { + return Ok(None); + } + parse_hashed_package(bytes, reserved_names, hash).map(Some) +} + +fn parse_hashed_package( + bytes: Vec, + reserved_names: &[&str], + hash: ContentHash, +) -> Result { let package_kind = kind(&bytes); let source = match package_kind { PackageKind::Manifest => bytes.as_slice(), diff --git a/crates/plugin-packages/src/store.rs b/crates/plugin-packages/src/store.rs index f42c5835..106f11cb 100644 --- a/crates/plugin-packages/src/store.rs +++ b/crates/plugin-packages/src/store.rs @@ -11,7 +11,7 @@ use nocterm_plugin_api::{ }; use nocterm_plugin_model::PluginId; -use crate::parse::{parse_package, sha256}; +use crate::parse::{parse_matching_package, parse_package, sha256}; /// The kinds of package file, in the order an installed plugin is looked for. const KINDS: [PackageKind; 2] = [PackageKind::Module, PackageKind::Manifest]; @@ -151,14 +151,17 @@ impl PluginPackages for PackageStore { self.path_of(plugin, file_kind)?, ] { match Self::read_bytes(&path) { - Ok(bytes) if sha256(&bytes) == *expected => { - let package = self.parse(bytes)?; - if package.manifest().plugin().id() != plugin { - return Err(PackageError::HashChanged); + Ok(bytes) => { + let names: Vec<&str> = + self.reserved_names.iter().map(String::as_str).collect(); + if let Some(package) = parse_matching_package(bytes, &names, expected)? { + if package.manifest().plugin().id() != plugin { + return Err(PackageError::HashChanged); + } + return Ok(package); } - return Ok(package); + outcome = PackageError::HashChanged; } - Ok(_) => outcome = PackageError::HashChanged, Err(PackageError::NotFound) => {} Err(error) => { if outcome == PackageError::NotFound { diff --git a/crates/plugin-packages/src/tests/code_packages.rs b/crates/plugin-packages/src/tests/code_packages.rs index b6b8ed86..da32a2e8 100644 --- a/crates/plugin-packages/src/tests/code_packages.rs +++ b/crates/plugin-packages/src/tests/code_packages.rs @@ -297,3 +297,40 @@ fn read_package_checks_a_file_the_way_an_install_does() { PackageError::NotFound ); } + +#[test] +#[ignore = "release profile for loading consented package bytes"] +fn measure_installed_package_load() { + use std::{io::Write as _, time::Instant}; + let size = std::env::var("NOCTERM_PROFILE_PACKAGE_BYTES") + .map_or(Ok(2 * 1024 * 1024), |size| size.parse::()) + .unwrap(); + assert!((1024..=MAX_MODULE_BYTES as usize).contains(&size)); + let mut bytes = module(CODE_MANIFEST); + let padding = size - bytes.len() - if size < 16384 { 7 } else { 8 }; + bytes.extend(custom_section("pad", &vec![0; padding])); + let directory = TempDir::new().unwrap(); + let store = store(directory.path()); + let package = parse_package(bytes, &[]).unwrap(); + store.publish(&package, false).unwrap(); + let plugin = package.manifest().plugin().id(); + let hash = package.hash(); + let mut samples = std::array::from_fn::<_, 51, _>(|_| { + let started = Instant::now(); + let loaded = store.load(plugin, hash).unwrap(); + let elapsed = started.elapsed(); + assert_eq!(loaded.bytes(), package.bytes()); + assert_eq!(loaded.hash(), hash); + assert_eq!(loaded.manifest().plugin().id(), plugin); + elapsed + }); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "bytes={} load_p50={:?} load_max={:?}", + package.bytes().len(), + samples[25], + samples[50] + ) + .unwrap(); +} diff --git a/crates/plugin-sdk/src/cx.rs b/crates/plugin-sdk/src/cx.rs index c63cd959..bbeedd8f 100644 --- a/crates/plugin-sdk/src/cx.rs +++ b/crates/plugin-sdk/src/cx.rs @@ -2,7 +2,7 @@ use alloc::{string::String, vec::Vec}; -use nocterm_plugin_abi::MAX_LOG_LINES; +use nocterm_plugin_abi::{BorrowedStorage, MAX_LOG_LINES}; use nocterm_plugin_api::{EffectOutcome, LocalId, Snapshot}; use nocterm_plugin_model::SettingValue; @@ -10,17 +10,49 @@ use crate::observe::{Observable, ObserveError}; /// The context of one `render` or `on_event` call: the contribution it is for, the snapshot the /// host assembled, and the log lines the reply will carry. -pub struct Cx<'a> { +#[doc(hidden)] +pub struct CallContext<'a, S> { local: &'a LocalId, snapshot: &'a Snapshot, + storage: S, log: Vec, } +/// Guest context providing access to the full snapshot. +pub type Cx<'a> = CallContext<'a, ()>; + +/// Guest context for plugins that read individual values from storage. +pub type TypedCx<'a> = CallContext<'a, BorrowedStorage<'a>>; + impl<'a> Cx<'a> { pub(crate) fn new(local: &'a LocalId, snapshot: &'a Snapshot) -> Self { + Self::with_storage(local, snapshot, ()) + } + + /// The whole snapshot, for what the typed reads do not cover. + pub fn snapshot(&self) -> &Snapshot { + self.snapshot + } + + /// A value the plugin stored with `storage.set`. + pub fn stored(&self, key: &str) -> Option<&str> { + self.snapshot.storage.get(key).map(String::as_str) + } +} + +impl TypedCx<'_> { + /// A value the plugin stored with `storage.set`. + pub fn stored(&self, key: &str) -> Option<&str> { + self.storage.get(key) + } +} + +impl<'a, S> CallContext<'a, S> { + pub(crate) fn with_storage(local: &'a LocalId, snapshot: &'a Snapshot, storage: S) -> Self { Self { local, snapshot, + storage, log: Vec::new(), } } @@ -47,11 +79,6 @@ impl<'a> Cx<'a> { && self.snapshot.context.zone != crate::api::Zone::Center } - /// The whole snapshot, for what the typed reads do not cover. - pub fn snapshot(&self) -> &Snapshot { - self.snapshot - } - /// The observation of a capability the manifest declares. /// /// `Missing` means the manifest does not declare it; `Host` carries the refusal for an @@ -69,11 +96,6 @@ impl<'a> Cx<'a> { self.snapshot.settings.get(key) } - /// A value the plugin stored with `storage.set`. - pub fn stored(&self, key: &str) -> Option<&str> { - self.snapshot.storage.get(key).map(String::as_str) - } - /// What happened to the effects of the previous call. pub fn outcomes(&self) -> &[EffectOutcome] { &self.snapshot.outcomes diff --git a/crates/plugin-sdk/src/dispatch.rs b/crates/plugin-sdk/src/dispatch.rs index bee32b0e..6b61a336 100644 --- a/crates/plugin-sdk/src/dispatch.rs +++ b/crates/plugin-sdk/src/dispatch.rs @@ -2,9 +2,11 @@ use alloc::vec::Vec; -use nocterm_plugin_abi::{AbiError, Answer, Reply, decode_call, encode_reply}; +use nocterm_plugin_abi::{ + AbiError, Answer, Reply, decode_call, decode_call_borrowing_storage, encode_reply, +}; -use crate::{Cx, Plugin}; +use crate::{Cx, Plugin, TypedCx, TypedPlugin}; /// Decodes a call, runs the plugin and encodes the reply. pub fn dispatch(plugin: &mut P, input: &[u8]) -> Result, AbiError> { @@ -14,11 +16,24 @@ pub fn dispatch(plugin: &mut P, input: &[u8]) -> Result, AbiE None => Answer::View(plugin.render(&mut cx)), Some(event) => Answer::Effects(plugin.on_event(&mut cx, &event)), }; - let reply = Reply { + encode_reply(&Reply { answer, log: cx.into_log(), + }) +} + +/// Dispatches a plugin using borrowed storage reads. +pub fn dispatch_typed(plugin: &mut P, input: &[u8]) -> Result, AbiError> { + let (local, event, snapshot, storage) = decode_call_borrowing_storage(input)?; + let mut cx = TypedCx::with_storage(&local, &snapshot, storage); + let answer = match event { + None => Answer::View(plugin.render(&mut cx)), + Some(event) => Answer::Effects(plugin.on_event(&mut cx, &event)), }; - encode_reply(&reply) + encode_reply(&Reply { + answer, + log: cx.into_log(), + }) } /// What `export!` expands against. Not an API: it changes with the macro. @@ -28,5 +43,5 @@ pub mod __private { pub use nocterm_plugin_abi::{ABI_VERSION, MAX_INPUT_BYTES, pack}; - pub use super::dispatch; + pub use super::{dispatch, dispatch_typed}; } diff --git a/crates/plugin-sdk/src/export.rs b/crates/plugin-sdk/src/export.rs index 19c6ef10..ae19abd3 100644 --- a/crates/plugin-sdk/src/export.rs +++ b/crates/plugin-sdk/src/export.rs @@ -4,6 +4,7 @@ /// /// `$plugin` is the plugin type; `$manifest` is the path of its `plugin.toml`, as /// `include_bytes!` reads it (an expression, so `concat!(env!("CARGO_MANIFEST_DIR"), ..)` works). +/// Use `export!(MyPlugin, manifest, typed)` to export a [`TypedPlugin`](crate::TypedPlugin). /// The expansion, on `wasm32` only: /// /// - puts the manifest into the custom section `nocterm.manifest`, which is what makes the @@ -28,8 +29,14 @@ #[macro_export] macro_rules! export { ($plugin:ty, $manifest:expr $(,)?) => { + $crate::export!(@implementation $plugin, $manifest, Plugin, dispatch); + }; + ($plugin:ty, $manifest:expr, typed $(,)?) => { + $crate::export!(@implementation $plugin, $manifest, TypedPlugin, dispatch_typed); + }; + (@implementation $plugin:ty, $manifest:expr, $trait:ident, $dispatch:ident) => { const _: () = { - const fn __assert_plugin() {} + const fn __assert_plugin() {} __assert_plugin::<$plugin>(); #[cfg(not(target_arch = "wasm32"))] @@ -114,7 +121,7 @@ macro_rules! export { let plugin = slot .plugin .get_or_insert_with(<$plugin as ::core::default::Default>::default); - match $crate::__private::dispatch(plugin, &slot.input[..len]) { + match $crate::__private::$dispatch(plugin, &slot.input[..len]) { ::core::result::Result::Ok(reply) => { slot.reply = reply; $crate::__private::pack(slot.reply.as_ptr() as u32, slot.reply.len() as u32) diff --git a/crates/plugin-sdk/src/lib.rs b/crates/plugin-sdk/src/lib.rs index 0253ae1d..85c91128 100644 --- a/crates/plugin-sdk/src/lib.rs +++ b/crates/plugin-sdk/src/lib.rs @@ -48,7 +48,7 @@ mod view; #[cfg(any(test, feature = "testing"))] pub mod testing; -pub use cx::Cx; +pub use cx::{Cx, TypedCx}; pub use observe::{Observable, ObserveError}; pub use view::{Chart, Item, NodeId, Section, ViewBuilder}; @@ -80,7 +80,7 @@ pub mod api { use api::{Effects, Event, View}; /// A code plugin. The host makes one value per instance with `Default` and calls it for every -/// contribution of the package; [`Cx::local`] says which. A trap or a fault drops the value, and +/// contribution of the package; `cx.local()` says which. A trap or a fault drops the value, and /// the next call starts again from `Default`. pub trait Plugin: Default { /// Draws the contribution `cx.local()`. @@ -94,5 +94,18 @@ pub trait Plugin: Default { } } +/// A code plugin whose storage access uses individual keys. Its typed context borrows +/// the encoded values during each call. Use [`Plugin`] when the whole snapshot is needed. +pub trait TypedPlugin: Default { + /// Draws the contribution `cx.local()`. + fn render(&mut self, cx: &mut TypedCx<'_>) -> View; + + /// Answers an event of the contribution `cx.local()` with effects. + fn on_event(&mut self, cx: &mut TypedCx<'_>, event: &Event) -> Effects { + let _ = (cx, event); + Effects::default() + } +} + #[cfg(test)] mod tests; diff --git a/crates/plugin-sdk/src/testing.rs b/crates/plugin-sdk/src/testing.rs index c31e90fd..af392976 100644 --- a/crates/plugin-sdk/src/testing.rs +++ b/crates/plugin-sdk/src/testing.rs @@ -51,7 +51,10 @@ use nocterm_plugin_api::{ use nocterm_plugin_model::{ContributionId, ContributionKind, SettingValue, SettingValues}; use thiserror::Error; -use crate::{__private::dispatch, Observable, Plugin}; +use crate::{ + __private::{dispatch, dispatch_typed}, + Observable, Plugin, TypedPlugin, +}; /// Why a test call did not produce what the plugin meant. #[derive(Debug, Error)] @@ -169,7 +172,7 @@ impl Host { /// Renders the contribution `local`; the host's validation applies to the view. pub fn render(&mut self, plugin: &mut P, local: &str) -> Result { - self.draw(plugin, local, None, Zone::Center) + self.draw(|bytes| dispatch(plugin, bytes), local, None, Zone::Center) } /// Renders the bar of the terminal `terminal`, which the toolbar `local` draws in that tab, @@ -180,7 +183,12 @@ impl Host { local: &str, terminal: &str, ) -> Result { - self.draw(plugin, local, Some(terminal), Zone::Center) + self.draw( + |bytes| dispatch(plugin, bytes), + local, + Some(terminal), + Zone::Center, + ) } /// As [`Host::render_bar`] for a bar the user moved to a side, which runs as a column: @@ -191,7 +199,12 @@ impl Host { local: &str, terminal: &str, ) -> Result { - self.draw(plugin, local, Some(terminal), Zone::Left) + self.draw( + |bytes| dispatch(plugin, bytes), + local, + Some(terminal), + Zone::Left, + ) } /// Sends `event` to the contribution `local` and applies the effects it answers with. @@ -201,7 +214,7 @@ impl Host { local: &str, event: Event, ) -> Result { - self.report(plugin, local, None, event) + self.report(|bytes| dispatch(plugin, bytes), local, None, event) } /// Sends `event` from the bar of the terminal `terminal` to the contribution `local`, which @@ -213,34 +226,95 @@ impl Host { terminal: &str, event: Event, ) -> Result { - self.report(plugin, local, Some(terminal), event) + self.report( + |bytes| dispatch(plugin, bytes), + local, + Some(terminal), + event, + ) + } + + /// Renders a plugin that uses typed storage reads. + pub fn render_typed( + &mut self, + plugin: &mut P, + local: &str, + ) -> Result { + self.draw( + |bytes| dispatch_typed(plugin, bytes), + local, + None, + Zone::Center, + ) + } + + /// Renders a typed plugin's terminal bar in the given zone. + pub fn render_typed_bar( + &mut self, + plugin: &mut P, + local: &str, + terminal: &str, + zone: Zone, + ) -> Result { + self.draw( + |bytes| dispatch_typed(plugin, bytes), + local, + Some(terminal), + zone, + ) + } + + /// Sends an event to a typed plugin and applies its effects. + pub fn event_typed( + &mut self, + plugin: &mut P, + local: &str, + event: Event, + ) -> Result { + self.report(|bytes| dispatch_typed(plugin, bytes), local, None, event) } - fn draw( + /// Sends an event from a terminal bar to a typed plugin and applies its effects. + pub fn typed_bar_event( &mut self, plugin: &mut P, local: &str, + terminal: &str, + event: Event, + ) -> Result { + self.report( + |bytes| dispatch_typed(plugin, bytes), + local, + Some(terminal), + event, + ) + } + + fn draw( + &mut self, + run: impl FnOnce(&[u8]) -> Result, AbiError>, + local: &str, terminal: Option<&str>, along: Zone, ) -> Result { let local = self.contribution(local)?; let snapshot = self.snapshot(&local, terminal, along); - match self.call(plugin, &Call::render(local, &snapshot))? { + match self.call(run, &Call::render(local, &snapshot))? { Answer::View(view) => view.into_validated().map_err(TestError::View), Answer::Effects(_) => Err(TestError::Answer), } } - fn report( + fn report( &mut self, - plugin: &mut P, + run: impl FnOnce(&[u8]) -> Result, AbiError>, local: &str, terminal: Option<&str>, event: Event, ) -> Result { let local = self.contribution(local)?; let snapshot = self.snapshot(&local, terminal, Zone::Center); - let Answer::Effects(effects) = self.call(plugin, &Call::event(local, event, &snapshot))? + let Answer::Effects(effects) = self.call(run, &Call::event(local, event, &snapshot))? else { return Err(TestError::Answer); }; @@ -264,9 +338,13 @@ impl Host { } } - fn call(&mut self, plugin: &mut P, call: &Call) -> Result { + fn call( + &mut self, + run: impl FnOnce(&[u8]) -> Result, AbiError>, + call: &Call, + ) -> Result { let input = encode_call(call).map_err(TestError::Abi)?; - let output = dispatch(plugin, &input).map_err(TestError::Abi)?; + let output = run(&input).map_err(TestError::Abi)?; let reply = decode_reply(&output).map_err(TestError::Abi)?; let lines = accepted_log(&reply.log).map_err(TestError::Reply)?; self.log.extend(lines); diff --git a/crates/plugin-sdk/src/tests/host.rs b/crates/plugin-sdk/src/tests/host.rs index c549c8f4..8557303a 100644 --- a/crates/plugin-sdk/src/tests/host.rs +++ b/crates/plugin-sdk/src/tests/host.rs @@ -11,7 +11,7 @@ use nocterm_plugin_api::{ use nocterm_plugin_model::SettingValue; use crate::{ - Cx, Plugin, ViewBuilder, effect, + Cx, Plugin, TypedCx, TypedPlugin, ViewBuilder, effect, observe::{Clock, Notices, Usage}, testing::{Host, TestError}, }; @@ -568,3 +568,43 @@ fn a_terminal_bar_is_drawn_and_used_for_the_terminal_it_names() { .expect("answered"); assert_eq!(servers.restarted.as_deref(), Some("srv")); } + +#[derive(Default)] +struct TypedBar; + +impl TypedPlugin for TypedBar { + fn render(&mut self, cx: &mut TypedCx<'_>) -> View { + let mut view = ViewBuilder::new(); + let value = cx.stored(cx.terminal().unwrap()).unwrap_or("empty"); + view.text(None, if cx.is_column() { "column" } else { "row" }); + view.text(None, value); + view.build() + } + + fn on_event(&mut self, cx: &mut TypedCx<'_>, _event: &Event) -> Effects { + cx.log(String::from(cx.terminal().unwrap())); + Effects::default() + } +} + +#[test] +fn typed_terminal_calls_read_the_selected_key_and_report_the_same_terminal() { + use nocterm_plugin_api::Zone; + + let mut host = Host::new(PANEL).unwrap(); + host.store("one", "first").store("two", "second"); + let mut plugin = TypedBar; + let view = host + .render_typed_bar(&mut plugin, "bar", "two", Zone::Left) + .unwrap(); + assert_eq!(view.nodes[0].kind, NodeKind::Text("column".into())); + assert_eq!(view.nodes[1].kind, NodeKind::Text("second".into())); + host.typed_bar_event( + &mut plugin, + "bar", + "one", + Event::Activated { key: "open".into() }, + ) + .unwrap(); + assert_eq!(host.log(), ["one"]); +} diff --git a/crates/plugin-view/src/chart.rs b/crates/plugin-view/src/chart.rs index 5d178451..ff5c40d6 100644 --- a/crates/plugin-view/src/chart.rs +++ b/crates/plugin-view/src/chart.rs @@ -19,39 +19,26 @@ const BAR_SLOTS: usize = 28; /// How much of a series' colour its fill keeps. const FILL: f32 = 0.18; -/// One series and the colour it is drawn in. -pub(crate) struct Line { - pub(crate) values: Vec, - pub(crate) color: Hsla, -} - -/// The chart of `lines`, from 0 to `max` (the largest value when `None`), its width holding +/// The chart of `series`, from 0 to `max` (the largest value when `None`), its width holding /// `span` values (the longest series when `None`). A panel draws it full width in a light /// frame; a bar draws a short line of its newest values. pub(crate) fn chart( kind: FrameKind, - lines: Vec, + series: &[Vec], + colors: [Hsla; 2], max: Option, span: Option, frame: Hsla, ) -> AnyElement { - let longest = lines - .iter() - .map(|line| line.values.len()) - .max() - .unwrap_or(0); - let mut slots = span.map_or(longest, usize::from).max(1); + let mut slots = span + .map(usize::from) + .unwrap_or_else(|| series.iter().map(Vec::len).max().unwrap_or(0)) + .max(1); if matches!(kind, FrameKind::Bar | FrameKind::Strip) { slots = slots.min(BAR_SLOTS); } let top = max - .unwrap_or_else(|| { - lines - .iter() - .flat_map(|line| line.values.iter().copied()) - .max() - .unwrap_or(0) - }) + .unwrap_or_else(|| series.iter().flatten().copied().max().unwrap_or(0)) .max(1); let panel = kind == FrameKind::Panel; div() @@ -70,15 +57,21 @@ pub(crate) fn chart( .border_1() .border_color(frame.opacity(0.4)) }) - .children(lines.iter().map(|line| layer(line, slots, top))) + .children( + series + .iter() + .zip(colors) + .map(|(values, color)| layer(values, color, slots, top)), + ) .into_any_element() } /// One series over the whole chart: a slot per value, right-aligned, each filled to its value /// with the line along its top. -fn layer(line: &Line, slots: usize, top: u32) -> AnyElement { - let shown = &line.values[line.values.len().saturating_sub(slots)..]; +fn layer(values: &[u32], color: Hsla, slots: usize, top: u32) -> AnyElement { + let shown = &values[values.len().saturating_sub(slots)..]; let width = relative(1. / slots as f32); + let fill = color.opacity(FILL); div() .absolute() .inset_0() @@ -93,9 +86,9 @@ fn layer(line: &Line, slots: usize, top: u32) -> AnyElement { .w(width) .h(relative(height)) .min_h(px(1.)) - .bg(line.color.opacity(FILL)) + .bg(fill) .border_t_1() - .border_color(line.color) + .border_color(color) })) .into_any_element() } diff --git a/crates/plugin-view/src/lib.rs b/crates/plugin-view/src/lib.rs index ca32342a..c6bf5005 100644 --- a/crates/plugin-view/src/lib.rs +++ b/crates/plugin-view/src/lib.rs @@ -1,7 +1,8 @@ //! Renders validated user plugin views inside a host frame, as the application draws its own. //! -//! A plugin returns a [`View`](nocterm_plugin_api::View) of plain nodes. [`PluginView`] checks it -//! again and draws it with the colours of a [`ViewStyle`]. The components of the contract +//! A plugin returns a [`View`](nocterm_plugin_api::View) of plain nodes. [`PluginView`] draws +//! checked views with the colours of a [`ViewStyle`] and checks raw views passed directly to it. +//! The components of the contract //! (section, item, icon button, caption, field, and a chart drawn as the application draws its //! graphs) are drawn with the measures of the application's own panels, so a plugin needs no //! styling to fit in. The frame is the host's: a bar item and a toolbar (a strip across, a rail diff --git a/crates/plugin-view/src/paint.rs b/crates/plugin-view/src/paint.rs index 0973410d..6f865cde 100644 --- a/crates/plugin-view/src/paint.rs +++ b/crates/plugin-view/src/paint.rs @@ -167,15 +167,14 @@ impl<'a> Painter<'a> { } else { color }; - let lines = series - .iter() - .zip([first, self.style.chart[1]]) - .map(|(values, color)| crate::chart::Line { - values: values.clone(), - color, - }) - .collect(); - crate::chart::chart(self.kind, lines, *max, *span, self.style.border) + crate::chart::chart( + self.kind, + series, + [first, self.style.chart[1]], + *max, + *span, + self.style.border, + ) } } } diff --git a/crates/plugin-view/src/tests.rs b/crates/plugin-view/src/tests.rs index 329e2887..34b3613b 100644 --- a/crates/plugin-view/src/tests.rs +++ b/crates/plugin-view/src/tests.rs @@ -1,13 +1,15 @@ use std::{cell::RefCell, rc::Rc}; use gpui::{ - App, Bounds, FocusHandle, Hsla, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke, Pixels, - TestAppContext, VisualTestContext, WindowHandle, hsla, px, + App, AppContext as _, Bounds, FocusHandle, Hsla, IntoElement, KeyDownEvent, KeyUpEvent, + Keystroke, Pixels, TestAppContext, VisualTestContext, WindowHandle, hsla, px, }; -use nocterm_plugin_api::{Event, Glyph, Node, NodeKind, Tone, View}; +use nocterm_plugin_api::{Event, Glyph, Node, NodeKind, Refresh, Tone, View}; use super::*; +mod performance; + #[derive(Clone, Default)] struct Harness { seen: Rc>>, @@ -115,6 +117,79 @@ fn bounds(cx: &mut VisualTestContext, selector: &'static str) -> Option>() + }) + }) + .unwrap() + }; + + let [primary, secondary] = painted_series(cx); + let [last] = secondary.as_slice() else { + panic!("one newest point in the second series"); + }; + assert!(!primary.is_empty()); + assert!( + primary + .iter() + .all(|slot| { slot.bottom() == last.bottom() && slot.size.height == last.size.height }) + ); + let primary_width: f32 = primary.iter().map(|slot| slot.size.width.0).sum(); + assert!((primary_width - 28. * last.size.width.0).abs() < 0.1); + + show(window, chart(Some(240)), cx); + let [full_history_scale, _] = painted_series(cx); + assert_eq!(primary, full_history_scale); + show(window, chart(Some(120)), cx); + let [visible_only_scale, _] = painted_series(cx); + assert!(visible_only_scale[0].size.height > primary[0].size.height); +} + +#[gpui::test] +fn equal_checked_nodes_stay_quiet_and_recover_after_a_fault(cx: &mut TestAppContext) { + let shown = view(vec![node(NodeKind::Text("12:00".into()))]); + let (_, window, cx) = open(cx, FrameKind::Panel, shown.clone()); + window + .update(cx, |plugin, _, cx| { + let refresh_only = View { + refresh: Some(Refresh::NextMinute), + ..shown.clone() + }; + assert!(!plugin.show_validated(refresh_only.validated().unwrap())); + plugin.fault(); + assert!(plugin.is_fault()); + assert!(plugin.show_validated(shown.validated().unwrap())); + assert!(!plugin.is_fault()); + cx.notify(); + }) + .unwrap(); + cx.run_until_parked(); + assert!(bounds(cx, "plugin-panel").is_some()); +} + fn centre(cx: &mut VisualTestContext, selector: &'static str) -> gpui::Point { bounds(cx, selector) .unwrap_or_else(|| panic!("{selector} was not drawn")) @@ -414,6 +489,48 @@ fn the_user_folds_a_section_without_asking_the_plugin_and_the_fold_outlives_a_ne ); } +#[gpui::test] +fn interleaved_nodes_keep_their_parent_and_order_when_a_section_folds(cx: &mut TestAppContext) { + let button = |parent, key: &str| keyed(parent, key, NodeKind::Button(key.into())); + let (harness, _, cx) = open( + cx, + FrameKind::Panel, + view(vec![ + keyed(None, "section", section_kind("Group", false)), + node(NodeKind::Column), + button(Some(0), "first"), + button(Some(1), "separate"), + button(Some(0), "second"), + button(None, "root"), + ]), + ); + for (selector, key) in [ + ("plugin-control-0", "first"), + ("plugin-control-1", "second"), + ("plugin-control-2", "separate"), + ("plugin-control-3", "root"), + ] { + let control = centre(cx, selector); + cx.simulate_click(control, Default::default()); + assert_eq!( + harness.seen().last().map(|event| event.event.clone()), + Some(Event::Activated { key: key.into() }) + ); + } + + let heading = centre(cx, "plugin-section-0"); + cx.simulate_click(heading, Default::default()); + assert!(bounds(cx, "plugin-control-2").is_none()); + let first = centre(cx, "plugin-control-0"); + cx.simulate_click(first, Default::default()); + assert_eq!( + harness.seen().last().map(|event| event.event.clone()), + Some(Event::Activated { + key: "separate".into(), + }) + ); +} + #[gpui::test] fn a_section_the_plugin_starts_folded_shows_its_content_when_the_user_opens_it( cx: &mut TestAppContext, diff --git a/crates/plugin-view/src/tests/performance.rs b/crates/plugin-view/src/tests/performance.rs new file mode 100644 index 00000000..ad4ede76 --- /dev/null +++ b/crates/plugin-view/src/tests/performance.rs @@ -0,0 +1,164 @@ +use gpui::{AppContext as _, TestAppContext}; +use nocterm_plugin_api::NodeKind; + +use super::{FrameKind, Harness, PluginView, child, node, open, style, view}; + +#[test] +#[ignore = "manual release timing fixture"] +fn measure_changed_and_equal_plugin_view_handoffs() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let mut output = std::io::stdout().lock(); + for count in [8, 64, nocterm_plugin_api::MAX_NODES] { + let snapshot = |first| { + view( + (0..count) + .map(|index| { + let line = if index == 0 { first } else { index }; + node(NodeKind::Text(format!( + "{line:03} {}", + "A bounded plugin row with visible status and details. ".repeat(4) + ))) + }) + .collect(), + ) + }; + let initial = snapshot(0).into_validated().unwrap(); + let mut legacy = PluginView::new( + "Fixture", + FrameKind::Panel, + style(), + Harness::default().hooks(), + ); + let mut checked = PluginView::new( + "Fixture", + FrameKind::Panel, + style(), + Harness::default().hooks(), + ); + legacy.show(initial.clone()).unwrap(); + assert!(checked.show_validated(snapshot(0).validated().unwrap())); + let mut last = initial; + for changes in [true, false] { + let mut timings = [Vec::new(), Vec::new()]; + for step in 0..240 { + let first = if changes { 1 + step % 2 } else { 2 }; + let raw = snapshot(first).into_validated().unwrap(); + let accepted = snapshot(first).validated().unwrap(); + let [legacy_timing, checked_timing] = &mut timings; + let legacy_handoff = || { + let now = Instant::now(); + let changed = last.nodes != raw.nodes; + if changed { + legacy.show(raw.clone()).unwrap(); + } + last = raw; + legacy_timing.push(now.elapsed().as_nanos()); + assert_eq!(changed, changes); + }; + let checked_handoff = || { + let now = Instant::now(); + let changed = checked.show_validated(black_box(accepted)); + checked_timing.push(now.elapsed().as_nanos()); + assert_eq!(changed, changes); + }; + if step % 2 == 0 { + legacy_handoff(); + checked_handoff(); + } else { + checked_handoff(); + legacy_handoff(); + } + } + let [legacy, checked] = timings.map(|mut samples| { + samples.sort_unstable(); + (samples[120], samples[228]) + }); + writeln!( + output, + "{count} nodes, changes={changes}, median/p95 ns, legacy={legacy:?}, checked={checked:?}" + ) + .unwrap(); + } + } +} + +#[test] +#[ignore = "manual release timing fixture for the bounded grouped view"] +fn measure_installing_a_changing_grouped_view() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let mut plugin = PluginView::new( + "Fixture", + FrameKind::Panel, + style(), + Harness::default().hooks(), + ); + let mut samples = Vec::with_capacity(2_000); + for pass in 0..2_000 { + let mut nodes = vec![node(NodeKind::Column)]; + while nodes.len() + 3 <= nocterm_plugin_api::MAX_NODES { + let group = u16::try_from(nodes.len()).unwrap(); + nodes.push(child(0, NodeKind::Row)); + nodes.push(child(group, NodeKind::Meter((pass % 100) as u8))); + nodes.push(child(group, NodeKind::Meter(50))); + } + let accepted = view(nodes).validated().unwrap(); + let start = Instant::now(); + let changed = plugin.show_validated(black_box(accepted)); + samples.push(start.elapsed().as_nanos()); + assert!(changed); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "grouped view handoff median/p95 ns: {}/{}", + samples[1_000], + samples[1_900] + ) + .unwrap(); +} + +#[gpui::test] +#[ignore = "manual release timing fixture for chart layout and paint"] +fn measure_redrawing_plugin_charts(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let chart = |index: u32| { + node(NodeKind::Chart { + series: [17, 29] + .map(|step| (0..120).map(|point| (point * step + index) % 97).collect()) + .into(), + max: None, + span: Some(120), + }) + }; + let (_, window, cx) = open(cx, FrameKind::Panel, view((0..6).map(chart).collect())); + let mut samples = Vec::with_capacity(240); + for pass in 0..256 { + let next = view((pass..pass + 6).map(chart).collect()); + window + .update(cx, |plugin, _, cx| { + plugin.show(next).unwrap(); + cx.notify(); + }) + .unwrap(); + let duration = cx + .update_window(*window, |_, window, cx| { + window.refresh(); + let start = Instant::now(); + window.draw(cx).clear(cx); + start.elapsed().as_nanos() + }) + .unwrap(); + samples.extend((pass >= 16).then_some(duration)); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "six charts draw median/p95 ns: {}/{}", + samples[120], + samples[228] + ) + .unwrap(); +} diff --git a/crates/plugin-view/src/tree.rs b/crates/plugin-view/src/tree.rs index c1b43a28..35cd5a1d 100644 --- a/crates/plugin-view/src/tree.rs +++ b/crates/plugin-view/src/tree.rs @@ -1,35 +1,52 @@ //! The arena of a view as a tree. -use nocterm_plugin_api::{Node, View, ViewError}; +use nocterm_plugin_api::{Node, ValidatedView}; /// A validated view with the children of each node. pub(crate) struct Tree { nodes: Vec, - children: Vec>, - roots: Vec, + entries: Vec, + starts: Vec, } impl Tree { - /// Sanitizes and validates a view; a view the host would refuse is an error. - pub(crate) fn new(view: View) -> Result { - let view = view.into_validated()?; - let mut children = vec![Vec::new(); view.nodes.len()]; - let mut roots = Vec::new(); - for (index, node) in view.nodes.iter().enumerate() { - match node.parent { - Some(parent) => children[usize::from(parent)].push(index), - None => roots.push(index), - } + pub(crate) fn new(view: ValidatedView) -> Self { + let nodes = view.into_view().nodes; + if nodes.is_empty() { + return Self { + nodes, + entries: Vec::new(), + starts: Vec::new(), + }; + } + // The roots occupy bucket zero. Bucket i + 1 holds the children + // of node i, with one trailing offset to close the last bucket. + let mut starts = vec![0; nodes.len() + 2]; + for node in &nodes { + let bucket = node.parent.map_or(0, |parent| usize::from(parent) + 1); + starts[bucket] += 1; + } + let mut end = 0; + for offset in &mut starts { + end += *offset; + *offset = end; + } + let mut entries = vec![0; nodes.len()]; + // Each end becomes its bucket's start as entries fill backwards. + for (index, node) in nodes.iter().enumerate().rev() { + let bucket = node.parent.map_or(0, |parent| usize::from(parent) + 1); + starts[bucket] -= 1; + entries[starts[bucket]] = index; + } + Self { + nodes, + entries, + starts, } - Ok(Self { - nodes: view.nodes, - children, - roots, - }) } pub(crate) fn roots(&self) -> &[usize] { - &self.roots + &self.entries[..self.starts.get(1).copied().unwrap_or(0)] } pub(crate) fn nodes(&self) -> &[Node] { @@ -41,6 +58,6 @@ impl Tree { } pub(crate) fn children(&self, index: usize) -> &[usize] { - &self.children[index] + &self.entries[self.starts[index + 1]..self.starts[index + 2]] } } diff --git a/crates/plugin-view/src/view.rs b/crates/plugin-view/src/view.rs index b03596dc..086a86b9 100644 --- a/crates/plugin-view/src/view.rs +++ b/crates/plugin-view/src/view.rs @@ -5,7 +5,7 @@ use std::{cell::RefCell, collections::BTreeMap, rc::Rc}; use gpui::{ AnyElement, AnyView, App, Context, FocusHandle, IntoElement, Render, SharedString, Window, }; -use nocterm_plugin_api::{Event, Glyph, NodeKind, View, ViewError}; +use nocterm_plugin_api::{Event, Glyph, NodeKind, ValidatedView, View, ViewError}; use crate::{ FrameKind, ViewStyle, @@ -102,10 +102,9 @@ impl PluginView { /// Shows a view. One the host refuses becomes the fault chip and the error is returned. /// The caller redraws the entity afterwards. pub fn show(&mut self, view: View) -> Result<(), ViewError> { - match Tree::new(view) { - Ok(tree) => { - self.keep_folds(&tree); - self.content = Content::View(tree); + match view.validated() { + Ok(view) => { + self.show_validated(view); Ok(()) } Err(error) => { @@ -115,6 +114,18 @@ impl PluginView { } } + /// Installs a checked view and reports whether the displayed content changed. + /// The caller handles refresh deadlines independently of the displayed nodes. + pub fn show_validated(&mut self, view: ValidatedView) -> bool { + if matches!(&self.content, Content::View(tree) if tree.nodes() == view.nodes()) { + return false; + } + let tree = Tree::new(view); + self.keep_folds(&tree); + self.content = Content::View(tree); + true + } + /// Keeps the folds of the sections the new view still has, and starts each new one as the /// plugin asks; the map never holds more keys than the view. fn keep_folds(&self, tree: &Tree) { diff --git a/crates/plugin-wasm/src/cache.rs b/crates/plugin-wasm/src/cache.rs index 7148ced7..450499fa 100644 --- a/crates/plugin-wasm/src/cache.rs +++ b/crates/plugin-wasm/src/cache.rs @@ -6,7 +6,9 @@ use std::{ }; use nocterm_plugin_api::{Cause, ContentHash, ModuleError, Package, RuntimeError}; -use wasmi::{Engine, Module}; +use wasmi::Module; + +use crate::engine::engine; /// Compiled modules kept at once; the oldest is evicted first. const MAX_MODULES: usize = 16; @@ -19,25 +21,26 @@ pub(crate) struct ModuleCache { impl ModuleCache { /// The compiled module of `package`: from the cache, or compiled now. A module wasmi /// refuses (malformed, or past a limit) is `ModuleError::Invalid` and is not cached. - pub(crate) fn get_or_compile( - &self, - engine: &Engine, - package: &Package, - ) -> Result { + pub(crate) fn get_or_compile(&self, package: &Package) -> Result { if let Some(module) = self.find(package.hash()) { return Ok(module); } - // Compiled outside the lock: a slow module must not block other windows. - let module = Module::new(engine, package.bytes()) + // Wasmi keeps code until its engine drops. Each module owns its engine so an + // eviction can release that code once the last guest using the module is gone. + let module = Module::new(&engine(), package.bytes()) .map_err(|error| ModuleError::Invalid(Cause::new(error)))?; let mut entries = self.lock(); if let Some((_, existing)) = entries.iter().find(|(hash, _)| hash == package.hash()) { return Ok(existing.clone()); } - if entries.len() == MAX_MODULES { - entries.pop_front(); - } + let evicted = if entries.len() == MAX_MODULES { + entries.pop_front() + } else { + None + }; entries.push_back((*package.hash(), module.clone())); + drop(entries); + drop(evicted); Ok(module) } diff --git a/crates/plugin-wasm/src/guest.rs b/crates/plugin-wasm/src/guest.rs index 8b89da03..b1665de1 100644 --- a/crates/plugin-wasm/src/guest.rs +++ b/crates/plugin-wasm/src/guest.rs @@ -6,7 +6,7 @@ use nocterm_plugin_abi::{ unpack, }; use nocterm_plugin_api::{Cause, ModuleError, ProtocolError, RuntimeError}; -use wasmi::{Engine, ExternType, Linker, Memory, Module, Store, StoreLimits, TypedFunc, ValType}; +use wasmi::{ExternType, Linker, Memory, Module, Store, StoreLimits, TypedFunc, ValType}; use crate::{engine::store_limits, trap::runtime_error}; @@ -23,11 +23,12 @@ impl Guest { /// /// The module must import nothing and export `memory` and the three functions with the ABI /// types; its start function and `nocterm_abi_version` run under [`START_FUEL`]. - pub(crate) fn start(engine: &Engine, module: &Module) -> Result { + pub(crate) fn start(module: &Module) -> Result { if module.imports().next().is_some() { return Err(ModuleError::Imports.into()); } check_exports(module)?; + let engine = module.engine(); let mut store = Store::new(engine, store_limits()); store.limiter(|limits| limits); store.set_fuel(START_FUEL).map_err(runtime_error)?; @@ -87,12 +88,19 @@ impl Guest { } .into()); } - let mut bytes = vec![0; reply_len]; - self.memory - .read(&self.store, reply_ptr as usize, &mut bytes) - .map_err(|_| ProtocolError::OutsideMemory)?; + let start = reply_ptr as usize; + let end = start + .checked_add(reply_len) + .ok_or(ProtocolError::OutsideMemory)?; + // Execution has returned. The shared store borrow keeps the bytes stable until + // decoding produces an owned reply. + let bytes = self + .memory + .data(&self.store) + .get(start..end) + .ok_or(ProtocolError::OutsideMemory)?; let reply = - decode_reply(&bytes).map_err(|error| ProtocolError::Undecodable(Cause::new(error)))?; + decode_reply(bytes).map_err(|error| ProtocolError::Undecodable(Cause::new(error)))?; if reply.log.len() > MAX_LOG_LINES { return Err(ProtocolError::TooManyLogLines { max: MAX_LOG_LINES }.into()); } diff --git a/crates/plugin-wasm/src/instance.rs b/crates/plugin-wasm/src/instance.rs index bcb2380d..17ef1148 100644 --- a/crates/plugin-wasm/src/instance.rs +++ b/crates/plugin-wasm/src/instance.rs @@ -2,11 +2,14 @@ use std::sync::{Arc, Mutex, PoisonError}; -use nocterm_plugin_abi::{Answer, Call, encode_call}; +use nocterm_plugin_abi::{ + AbiError, Answer, encode_event_call_borrowed, encode_render_call_borrowed, +}; use nocterm_plugin_api::{ - Effects, Event, LocalId, Manifest, PluginInstance, ProtocolError, RuntimeError, Snapshot, View, + Effects, Event, LocalId, Manifest, PluginInstance, ProtocolError, RuntimeError, Snapshot, + SnapshotRef, View, }; -use wasmi::{Engine, Module}; +use wasmi::Module; use crate::{ budget::LiveSlot, @@ -23,7 +26,6 @@ struct Running { pub(crate) struct WasmInstance { running: Mutex, module: Module, - engine: Engine, manifest: Manifest, _slot: LiveSlot, } @@ -31,13 +33,12 @@ pub(crate) struct WasmInstance { impl WasmInstance { /// Starts the first guest, so a module the ABI refuses is refused at instantiation. pub(crate) fn start( - engine: Engine, module: Module, manifest: Manifest, sink: Arc, slot: LiveSlot, ) -> Result { - let guest = Guest::start(&engine, &module)?; + let guest = Guest::start(&module)?; let plugin = manifest.plugin().id().clone(); Ok(Self { running: Mutex::new(Running { @@ -45,20 +46,19 @@ impl WasmInstance { log: LogBudget::new(plugin, sink), }), module, - engine, manifest, _slot: slot, }) } - /// Sends `call` to the guest and takes the part of the answer `pick` wants. + /// Encodes and sends a call to the guest and takes the part of the answer `pick` wants. /// /// A guest that is missing (it failed before) is started again from the cached module, so /// its state is fresh. A guest that fails, or whose answer `pick` refuses, is dropped. fn run( &self, local: &LocalId, - call: &Call, + encode: impl FnOnce() -> Result, AbiError>, pick: fn(Answer) -> Option, ) -> Result { if !self.manifest.has_contribution(local) { @@ -66,7 +66,7 @@ impl WasmInstance { } // Encoded before the guest is taken: a call the host cannot encode is no fault of the // plugin and leaves its state alone. - let input = encode_call(call).map_err(|_| RuntimeError::InputTooLarge)?; + let input = encode().map_err(|_| RuntimeError::InputTooLarge)?; let mut running = self.running.lock().unwrap_or_else(PoisonError::into_inner); if self.running.is_poisoned() { // A panic left the guest in an unknown state. @@ -75,7 +75,7 @@ impl WasmInstance { } let mut guest = match running.guest.take() { Some(guest) => guest, - None => Guest::start(&self.engine, &self.module)?, + None => Guest::start(&self.module)?, }; let reply = guest.call(&input)?; let Some(value) = pick(reply.answer) else { @@ -89,11 +89,22 @@ impl WasmInstance { impl PluginInstance for WasmInstance { fn render(&self, local: &LocalId, snapshot: &Snapshot) -> Result { - let call = Call::render(local.clone(), snapshot); - self.run(local, &call, |answer| match answer { - Answer::View(view) => Some(view), - Answer::Effects(_) => None, - }) + self.render_borrowed(local, snapshot.into()) + } + + fn render_borrowed( + &self, + local: &LocalId, + snapshot: SnapshotRef<'_>, + ) -> Result { + self.run( + local, + || encode_render_call_borrowed(local, snapshot), + |answer| match answer { + Answer::View(view) => Some(view), + Answer::Effects(_) => None, + }, + ) } fn on_event( @@ -102,10 +113,43 @@ impl PluginInstance for WasmInstance { event: Event, snapshot: &Snapshot, ) -> Result { - let call = Call::event(local.clone(), event, snapshot); - self.run(local, &call, |answer| match answer { - Answer::Effects(effects) => Some(effects), - Answer::View(_) => None, - }) + self.on_event_borrowed(local, event, snapshot.into()) + } + + fn on_event_borrowed( + &self, + local: &LocalId, + event: Event, + snapshot: SnapshotRef<'_>, + ) -> Result { + self.run( + local, + || encode_event(local, event, snapshot), + |answer| match answer { + Answer::Effects(effects) => Some(effects), + Answer::View(_) => None, + }, + ) + } +} + +fn encode_event( + local: &LocalId, + event: Event, + snapshot: SnapshotRef<'_>, +) -> Result, AbiError> { + let encoded = encode_event_call_borrowed(local, &event, snapshot); + if matches!(encoded, Err(AbiError::TooLarge { .. })) + && let Event::Response { key, .. } = event + { + // Keep the original correlation key. Cutting the body here could turn + // a successful binary download into a different file. + let failed = Event::Response { + key, + status: 0, + body: "the answer is too large for the plugin".into(), + }; + return encode_event_call_borrowed(local, &failed, snapshot); } + encoded } diff --git a/crates/plugin-wasm/src/lib.rs b/crates/plugin-wasm/src/lib.rs index 6677cfe3..67ee01ae 100644 --- a/crates/plugin-wasm/src/lib.rs +++ b/crates/plugin-wasm/src/lib.rs @@ -2,7 +2,8 @@ //! [`PluginRuntime`](nocterm_plugin_api::PluginRuntime) port. //! //! Owns: the wasmi engine configuration, the compiled-module cache, the live-instance budget, -//! one guest per instance (store, memory and the ABI exports), the mapping of traps to +//! one engine per cached module, one guest per instance (store, memory and the ABI exports), +//! the mapping of traps to //! `RuntimeError` and the bounded guest log. //! Does not own: package files and hashing (nocterm-plugin-packages), the wire types and the //! ABI constants (nocterm-plugin-abi), manifests, views and effects diff --git a/crates/plugin-wasm/src/runtime.rs b/crates/plugin-wasm/src/runtime.rs index 2b871d7e..38388e68 100644 --- a/crates/plugin-wasm/src/runtime.rs +++ b/crates/plugin-wasm/src/runtime.rs @@ -3,16 +3,12 @@ use std::sync::Arc; use nocterm_plugin_api::{Package, PluginInstance, PluginRuntime, RuntimeError}; -use wasmi::Engine; -use crate::{ - budget::Budget, cache::ModuleCache, engine::engine, instance::WasmInstance, log::GuestLog, -}; +use crate::{budget::Budget, cache::ModuleCache, instance::WasmInstance, log::GuestLog}; /// Runs `runtime = "wasm"` packages on wasmi. One runtime serves every window: modules are /// compiled once per package hash and at most `MAX_LIVE_INSTANCES` guests are alive. pub struct WasmRuntime { - engine: Engine, modules: ModuleCache, budget: Budget, log: Arc, @@ -22,7 +18,6 @@ impl WasmRuntime { /// A runtime whose guests log to `log`. pub fn new(log: Arc) -> Self { Self { - engine: engine(), modules: ModuleCache::default(), budget: Budget::default(), log, @@ -35,9 +30,8 @@ impl PluginRuntime for WasmRuntime { /// module's ABI is checked here, so a refusal is reported before any view is asked for. fn instantiate(&self, package: &Package) -> Result, RuntimeError> { let slot = self.budget.claim()?; - let module = self.modules.get_or_compile(&self.engine, package)?; + let module = self.modules.get_or_compile(package)?; let instance = WasmInstance::start( - self.engine.clone(), module, package.manifest().clone(), Arc::clone(&self.log), diff --git a/crates/plugin-wasm/src/tests.rs b/crates/plugin-wasm/src/tests.rs index 26472f44..0ee1a5b1 100644 --- a/crates/plugin-wasm/src/tests.rs +++ b/crates/plugin-wasm/src/tests.rs @@ -4,11 +4,11 @@ mod fixtures; use fixtures::{ - Spec, effects_reply, growing, local, plugin_id, recording_runtime, reply, snapshot, spinning, - trapping_after_first, view, view_reply, + DEFAULT_MEMORY_BYTES, Spec, effects_reply, growing, local, plugin_id, recording_runtime, reply, + snapshot, spinning, trapping_after_first, view, view_reply, }; use nocterm_plugin_abi::{ - Answer, MAX_INPUT_BYTES, MAX_LIVE_INSTANCES, MAX_LOG_LINES, MAX_REPLY_BYTES, + Answer, MAX_INPUT_BYTES, MAX_LIVE_INSTANCES, MAX_LOG_LINES, MAX_REPLY_BYTES, encode_event_call, names::EXPORT_ALLOC, }; use nocterm_plugin_api::{ @@ -17,7 +17,7 @@ use nocterm_plugin_api::{ capability::notifications::{NoticeTone, Post}, }; -use crate::{WasmRuntime, cache::ModuleCache, engine::engine}; +use crate::{WasmRuntime, cache::ModuleCache}; fn instance(spec: &Spec) -> (Box, WasmRuntime) { let (runtime, _) = recording_runtime(); @@ -64,12 +64,87 @@ fn render_returns_the_view_the_guest_replied() { assert_eq!(render(instance.as_ref()), Ok(view("12:30"))); } +#[test] +#[ignore = "manual warm WASM reply latency fixture"] +fn measure_decoding_guest_render_replies() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let local = local("face"); + let snapshot = snapshot(); + for count in [1, 64, 256] { + let mut answer = view(&"Nocterm plugin status. ".repeat(8)); + answer.nodes.resize(count, answer.nodes[0].clone()); + let spec = Spec::replying(&reply(Answer::View(answer.clone()), &[])) + .ending_at(DEFAULT_MEMORY_BYTES); + let (instance, _runtime) = instance(&spec); + assert_eq!(instance.render(&local, &snapshot).unwrap(), answer); + let mut samples = Vec::with_capacity(2_000); + for _ in 0..samples.capacity() { + let start = Instant::now(); + let rendered = instance.render(&local, &snapshot).unwrap(); + samples.push(start.elapsed().as_nanos()); + black_box(rendered); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} nodes, {} reply bytes, median={} ns, p95={} ns", + spec.reply.len(), + samples[samples.len() / 2], + samples[samples.len() * 95 / 100] + ) + .unwrap(); + } +} + #[test] fn an_event_returns_the_effects_the_guest_replied() { let (instance, _runtime) = instance(&Spec::replying(&effects_reply(note()))); assert_eq!(activate(instance.as_ref()), Ok(note())); } +#[test] +fn an_http_response_that_exceeds_the_call_limit_arrives_as_a_keyed_failure() { + let local = local("board"); + let mut snapshot = snapshot(); + for item in 0..15 { + snapshot + .storage + .insert(format!("item-{item}"), "x".repeat(4 * 1024)); + } + let failure = Event::Response { + key: "download".into(), + status: 0, + body: "the answer is too large for the plugin".into(), + }; + let encoded = encode_event_call(&local, &failure, &snapshot).unwrap(); + let reply = effects_reply(note()); + let (plugin, _runtime) = instance(&Spec::replying(&reply).expecting_input(&encoded)); + + // The data would fit by itself, but the plugin needs the snapshot too. + let answer = Event::Response { + key: "download".into(), + status: 200, + body: "x".repeat(240 * 1024), + }; + assert_eq!(plugin.on_event(&local, answer, &snapshot), Ok(note())); +} + +#[test] +fn an_http_response_that_fits_reaches_the_guest_with_its_body() { + let local = local("board"); + let snapshot = snapshot(); + let event = Event::Response { + key: "download".into(), + status: 206, + body: "aGVsbG8K".repeat(128), + }; + let encoded = encode_event_call(&local, &event, &snapshot).unwrap(); + let reply = effects_reply(note()); + let (plugin, _runtime) = instance(&Spec::replying(&reply).expecting_input(&encoded)); + assert_eq!(plugin.on_event(&local, event, &snapshot), Ok(note())); +} + #[test] fn a_context_the_package_does_not_declare_is_unknown() { let (instance, _runtime) = instance(&Spec::replying(&view_reply("x"))); @@ -195,11 +270,20 @@ fn bytes_that_are_not_a_module_are_refused() { )); } +#[test] +fn a_reply_can_end_at_the_last_byte_of_guest_memory() { + let spec = Spec::replying(&view_reply("edge")).ending_at(DEFAULT_MEMORY_BYTES); + let (instance, _runtime) = instance(&spec); + assert_eq!(render(instance.as_ref()), Ok(view("edge"))); +} + #[test] fn a_reply_outside_the_guest_memory_is_malformed() { for spec in [ - Spec::pointing(1_048_000, 1000), + Spec::pointing(DEFAULT_MEMORY_BYTES - 1, 2), + Spec::pointing(DEFAULT_MEMORY_BYTES + 1, 0), Spec::pointing(0xFFFF_0000, 16), + Spec::pointing(u32::MAX, 1), ] { let (instance, _runtime) = instance(&spec); assert_eq!( @@ -211,8 +295,8 @@ fn a_reply_outside_the_guest_memory_is_malformed() { #[test] fn a_reply_over_the_size_bound_is_malformed() { - for len in [MAX_REPLY_BYTES as u32 + 1, u32::MAX] { - let (instance, _runtime) = instance(&Spec::pointing(0, len)); + for (ptr, len) in [(0, MAX_REPLY_BYTES as u32 + 1), (u32::MAX, u32::MAX)] { + let (instance, _runtime) = instance(&Spec::pointing(ptr, len)); assert_eq!( render(instance.as_ref()), Err(RuntimeError::Malformed(ProtocolError::ReplyTooLarge { @@ -222,6 +306,15 @@ fn a_reply_over_the_size_bound_is_malformed() { } } +#[test] +fn an_empty_reply_at_the_end_of_memory_reaches_the_decoder() { + let (instance, _runtime) = instance(&Spec::pointing(DEFAULT_MEMORY_BYTES, 0)); + assert!(matches!( + render(instance.as_ref()), + Err(RuntimeError::Malformed(ProtocolError::Undecodable(_))) + )); +} + #[test] fn a_reply_that_is_not_postcard_is_malformed_and_keeps_the_decoder_cause() { use std::error::Error as _; @@ -305,23 +398,49 @@ fn a_refused_module_does_not_keep_its_place() { #[test] fn a_module_is_compiled_once_per_hash_and_the_cache_is_bounded() { - let engine = engine(); let cache = ModuleCache::default(); let bytes = Spec::replying(&view_reply("x")).wasm(); let package = |hash: u8| -> Package { fixtures::package(bytes.clone(), hash) }; - cache.get_or_compile(&engine, &package(1)).unwrap(); - cache.get_or_compile(&engine, &package(1)).unwrap(); + let first = cache.get_or_compile(&package(1)).unwrap(); + let same = cache.get_or_compile(&package(1)).unwrap(); + assert!(wasmi::Engine::same(first.engine(), same.engine())); + drop(same); assert_eq!(cache.len(), 1); for hash in 2..40 { - cache.get_or_compile(&engine, &package(hash)).unwrap(); + cache.get_or_compile(&package(hash)).unwrap(); } assert_eq!(cache.len(), 16); + let reloaded = cache.get_or_compile(&package(1)).unwrap(); + assert!(!wasmi::Engine::same(first.engine(), reloaded.engine())); + let released = first.engine().weak(); + drop(first); + assert!( + released.upgrade().is_none(), + "evicted code has no live owner" + ); // A refused module is not cached. let broken = fixtures::package(b"\0asm\x01\0\0\0x".to_vec(), 200); - assert!(cache.get_or_compile(&engine, &broken).is_err()); + assert!(cache.get_or_compile(&broken).is_err()); assert_eq!(cache.len(), 16); } +#[test] +fn an_instance_can_restart_after_its_module_leaves_the_cache() { + let (runtime, _) = recording_runtime(); + let original = trapping_after_first(&view_reply("original")); + let running = runtime.instantiate(&original.package(0)).unwrap(); + assert_eq!(render(running.as_ref()), Ok(view("original"))); + + let replacement = Spec::replying(&view_reply("replacement")).wasm(); + for hash in 1..=16 { + let package = fixtures::package(replacement.clone(), hash); + assert!(runtime.instantiate(&package).is_ok()); + } + + assert_eq!(render(running.as_ref()), Err(RuntimeError::Trap)); + assert_eq!(render(running.as_ref()), Ok(view("original"))); +} + #[test] fn log_lines_are_cleaned_cut_and_attributed() { let long = "x".repeat(300); diff --git a/crates/plugin-wasm/src/tests/fixtures.rs b/crates/plugin-wasm/src/tests/fixtures.rs index 5a23e21c..50a17b0c 100644 --- a/crates/plugin-wasm/src/tests/fixtures.rs +++ b/crates/plugin-wasm/src/tests/fixtures.rs @@ -1,6 +1,9 @@ //! Guests written as WAT text and the packages that carry them. -use std::sync::{Arc, Mutex}; +use std::{ + fmt::Write as _, + sync::{Arc, Mutex}, +}; use nocterm_plugin_abi::{Answer, Reply, encode_reply, pack}; use nocterm_plugin_api::{ @@ -15,12 +18,14 @@ use crate::GuestLog; const REPLY_AT: u32 = 1024; /// The buffer `nocterm_alloc` hands out; 16 pages leave room for the largest call. const INPUT_AT: u32 = 65_536; +pub(super) const DEFAULT_MEMORY_BYTES: u32 = 16 * 65_536; /// The parts of a test guest. Anything not set is a well-behaved guest that replies `reply`. pub(super) struct Spec { pub pages: u32, pub version: i32, pub reply: Vec, + reply_at: u32, pub imports: String, pub globals: String, pub alloc: String, @@ -40,6 +45,7 @@ impl Spec { pages: 16, version: 1, reply, + reply_at: REPLY_AT, imports: String::new(), globals: String::new(), alloc: format!( @@ -49,6 +55,39 @@ impl Spec { } } + pub(super) fn ending_at(mut self, end: u32) -> Self { + let len = self.reply.len() as u32; + self.reply_at = end - len; + self.body = format!("(i64.const {})", pack(self.reply_at, len) as i64); + self + } + + /// A guest that checks the complete host call before replying. + pub(super) fn expecting_input(mut self, expected: &[u8]) -> Self { + const EXPECTED_AT: u32 = DEFAULT_MEMORY_BYTES / 2; + let mut data = String::new(); + for byte in expected { + write!(data, "\\{byte:02x}").unwrap(); + } + self.globals = format!(r#"(data (i32.const {EXPECTED_AT}) "{data}")"#); + self.body = format!( + "(local $i i32) + (if (i32.ne (local.get 1) (i32.const {length})) (then unreachable)) + (block $done (loop $check + (br_if $done (i32.eq (local.get $i) (local.get 1))) + (if (i32.ne + (i32.load8_u (i32.add (local.get 0) (local.get $i))) + (i32.load8_u offset={EXPECTED_AT} (local.get $i))) + (then unreachable)) + (local.set $i (i32.add (local.get $i) (i32.const 1))) + (br $check))) + {body}", + length = expected.len(), + body = self.body, + ); + self + } + /// A guest that returns the pair `(ptr, len)` without writing anything there. pub(super) fn pointing(ptr: u32, len: u32) -> Self { let mut spec = Self::bytes(Vec::new()); @@ -67,13 +106,14 @@ impl Spec { {imports} {globals} (memory (export "memory") {pages}) - (data (i32.const {REPLY_AT}) "{data}") + (data (i32.const {reply_at}) "{data}") (func (export "nocterm_abi_version") (result i32) (i32.const {version})) {alloc} (func (export "nocterm_call") (param i32 i32) (result i64) {body}))"#, imports = self.imports, globals = self.globals, pages = self.pages, + reply_at = self.reply_at, version = self.version, alloc = self.alloc, body = self.body, diff --git a/crates/project-container-fs/src/filesystem/codec.rs b/crates/project-container-fs/src/filesystem/codec.rs index 8e37e626..430ed45c 100644 --- a/crates/project-container-fs/src/filesystem/codec.rs +++ b/crates/project-container-fs/src/filesystem/codec.rs @@ -8,11 +8,24 @@ pub(super) fn text(bytes: &[u8]) -> Result<&str, FsError> { } pub(super) fn metadata(bytes: &[u8]) -> Result { let data = text(bytes)?.trim(); - let fields: Vec<_> = data.split(':').collect(); - if fields.len() != 8 { + let mut fields = data.split(':'); + let [ + Some(_), + Some(_), + Some(mode), + Some(size), + Some(permissions), + Some(uid), + Some(gid), + Some(modified), + ] = std::array::from_fn(|_| fields.next()) + else { + return Err(malformed()); + }; + if fields.next().is_some() { return Err(malformed()); } - let mode = u32::from_str_radix(fields[2], 16).map_err(|_| malformed())?; + let mode = u32::from_str_radix(mode, 16).map_err(|_| malformed())?; Ok(FileMetadata { kind: match mode & 0o170000 { 0o040000 => EntryKind::Directory, @@ -20,11 +33,11 @@ pub(super) fn metadata(bytes: &[u8]) -> Result { _ => EntryKind::Other, }, is_symlink: mode & 0o170000 == 0o120000, - size: Some(fields[3].parse().map_err(|_| malformed())?), - permissions: Some(u32::from_str_radix(fields[4], 8).map_err(|_| malformed())?), - uid: Some(fields[5].parse().map_err(|_| malformed())?), - gid: Some(fields[6].parse().map_err(|_| malformed())?), - modified: fields[7].parse::().ok(), + size: Some(size.parse().map_err(|_| malformed())?), + permissions: Some(u32::from_str_radix(permissions, 8).map_err(|_| malformed())?), + uid: Some(uid.parse().map_err(|_| malformed())?), + gid: Some(gid.parse().map_err(|_| malformed())?), + modified: modified.parse::().ok(), }) } pub(super) fn entry(name: String, metadata: FileMetadata) -> DirEntry { @@ -36,22 +49,21 @@ pub(super) fn entry(name: String, metadata: FileMetadata) -> DirEntry { } } pub(super) fn listing(bytes: &[u8]) -> Result, FsError> { - if !bytes.is_empty() && bytes.last() != Some(&0) { - return Err(malformed()); + if bytes.is_empty() { + return Ok(Vec::new()); } - let parts: Vec<_> = bytes - .strip_suffix(&[0]) - .unwrap_or(bytes) - .split(|byte| *byte == 0) - .filter(|_| !bytes.is_empty()) - .collect(); - let (pairs, remainder) = parts.as_chunks::<2>(); - if !remainder.is_empty() || pairs.len() > 100_000 { + let Some(data) = bytes.strip_suffix(&[0]) else { + return Err(malformed()); + }; + let mut parts = data.split(|byte| *byte == 0); + let fields = parts.clone().count(); + if !fields.is_multiple_of(2) || fields / 2 > 100_000 { return Err(malformed()); } let mut names = 0usize; - let mut entries = Vec::with_capacity(pairs.len()); - for [name, details] in pairs { + let mut entries = Vec::with_capacity(fields / 2); + while let Some(name) = parts.next() { + let details = parts.next().ok_or_else(malformed)?; names = names.saturating_add(name.len()); if name.is_empty() || name.len() > 4096 || name.contains(&b'/') || names > 8 * 1024 * 1024 { return Err(malformed()); diff --git a/crates/project-container-fs/src/filesystem/download.rs b/crates/project-container-fs/src/filesystem/download.rs index 2e77aa96..2b344dc4 100644 --- a/crates/project-container-fs/src/filesystem/download.rs +++ b/crates/project-container-fs/src/filesystem/download.rs @@ -11,6 +11,7 @@ use std::{ pub(super) struct Download { output: Option, pending: Vec, + offset: usize, size: Option, received: u64, done: bool, @@ -29,6 +30,7 @@ impl Download { let mut download = Self { output: Some(output), pending: Vec::new(), + offset: 0, size: None, received: 0, done: false, @@ -36,7 +38,13 @@ impl Download { alive, }; let first = download.read(1).await?; - download.pending.splice(0..0, first); + // Admission waits for the first byte or checked EOF without consuming + // that byte for the caller. A complete one-byte chunk may have moved out. + if download.offset != 0 { + download.offset -= first.len(); + } else { + download.pending = first; + } Ok(download) } pub(super) fn alive(&self) -> bool { @@ -48,8 +56,12 @@ impl Download { "container output chunk exceeds bound".into(), )); } - self.pending.extend(chunk); if self.size.is_none() { + if self.pending.is_empty() { + self.pending = chunk; + } else { + self.pending.extend(chunk); + } if let Some(end) = self.pending.iter().position(|byte| *byte == 0) { if end > 32 { return Err(FsError::Other("malformed download admission".into())); @@ -57,14 +69,18 @@ impl Download { let size = super::codec::text(&self.pending[..end])? .parse::() .map_err(|_| FsError::Other("malformed download size".into()))?; - self.pending.drain(..=end); + self.offset = end + 1; self.size = Some(size); - self.received = self.pending.len() as u64; + self.received = (self.pending.len() - self.offset) as u64; } else if self.pending.len() > 32 { return Err(FsError::Other("malformed download admission".into())); } } else { - self.received += self.pending.len() as u64; + // The preceding chunk is exhausted. Adopt transport-owned storage + // rather than copying it into a buffer that is shifted on each read. + self.received += chunk.len() as u64; + self.pending = chunk; + self.offset = 0; } if self.size.is_some_and(|size| self.received > size) { return Err(FsError::Other("download changed size".into())); @@ -88,9 +104,15 @@ impl Download { let result = timed( async { loop { - if self.size.is_some() && !self.pending.is_empty() { - let count = max.min(self.pending.len()); - return Ok(self.pending.drain(..count).collect()); + if self.size.is_some() && self.offset < self.pending.len() { + let count = max.min(self.pending.len() - self.offset); + if self.offset == 0 && count == self.pending.len() { + return Ok(std::mem::take(&mut self.pending)); + } + let end = self.offset + count; + let bytes = self.pending[self.offset..end].to_vec(); + self.offset = end; + return Ok(bytes); } match output.next().await { Some(chunk) => { diff --git a/crates/project-container-fs/src/tests/filesystem.rs b/crates/project-container-fs/src/tests/filesystem.rs index 4b194b84..9cdcc00e 100644 --- a/crates/project-container-fs/src/tests/filesystem.rs +++ b/crates/project-container-fs/src/tests/filesystem.rs @@ -120,6 +120,84 @@ fn typed_metadata_missing_permission_and_malformed_names_are_preserved() { response(&exec, Engine::Docker, vec![255, 0], 0); assert!(block_on(fs.read_dir("/")).is_err()); } + +#[test] +fn container_listings_require_complete_name_metadata_pairs() { + let exec = FakeExec::default(); + let fs = open(&exec, Engine::Docker); + ready(&exec, Engine::Docker); + response(&exec, Engine::Docker, vec![], 0); + assert!(block_on(fs.read_dir("/directory")).unwrap().is_empty()); + for malformed in [ + &b"entry\0"[..], + &b"entry\x001:2:81a4:3:644:1:2:5"[..], + &b"\x001:2:81a4:3:644:1:2:5\0"[..], + &b"entry\x001:2:81a4:3:644:1:2\0"[..], + &b"entry\x001:2:81a4:3:644:1:2:5:extra\0"[..], + ] { + response(&exec, Engine::Docker, malformed, 0); + assert!(block_on(fs.read_dir("/directory")).is_err()); + } + response(&exec, Engine::Docker, b"1:2:81a4:3:644:1:2:".to_vec(), 0); + let metadata = block_on(fs.metadata("/directory/entry")).unwrap(); + assert_eq!(metadata.size, Some(3)); + assert_eq!(metadata.modified, None); +} + +#[test] +#[ignore = "release profile for large container directory listings through RemoteFs"] +fn measure_container_directory_listing() { + use nocterm_session::EntryKind; + use std::io::Write as _; + let count = std::env::var("NOCTERM_PROFILE_DIRECTORY_COUNT") + .map_or(Ok(4096), |count| count.parse::()) + .unwrap(); + assert!((1..=100_000).contains(&count)); + let exec = FakeExec::default(); + let filesystem = open(&exec, Engine::Docker); + ready(&exec, Engine::Docker); + response(&exec, Engine::Docker, b"/root".to_vec(), 0); + assert_eq!(block_on(filesystem.home()).unwrap(), "/root"); + let mut payload = Vec::new(); + for index in 0..count { + write!(&mut payload, "entry-{index:06}\0").unwrap(); + let mode = match index % 3 { + 0 => "81a4", + 1 => "41ed", + _ => "a1ff", + }; + write!(&mut payload, "1:2:{mode}:{index}:644:1:2:5\0").unwrap(); + } + let mut samples = std::array::from_fn::<_, 25, _>(|_| { + response(&exec, Engine::Docker, payload.clone(), 0); + let started = std::time::Instant::now(); + let entries = block_on(filesystem.read_dir("/directory")).unwrap(); + let elapsed = started.elapsed(); + assert_eq!(entries.len(), count); + for (index, entry) in entries.iter().enumerate() { + assert_eq!(entry.name, format!("entry-{index:06}")); + assert_eq!(entry.size, Some(index as u64)); + assert_eq!(entry.is_symlink, index % 3 == 2); + assert_eq!( + entry.kind, + match index % 3 { + 0 => EntryKind::File, + 1 => EntryKind::Directory, + _ => EntryKind::Other, + } + ); + } + elapsed + }); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "entries={count} listing_p50={:?} listing_max={:?}", + samples[12], + samples[24] + ) + .unwrap(); +} #[test] fn upload_collision_seals_writes_and_allows_same_parent_publication_retry() { let exec = FakeExec::default(); @@ -230,6 +308,45 @@ fn download_refuses_special_files_and_detects_truncation() { assert!(block_on(download.read(8)).is_err()); } +#[test] +fn download_preserves_first_byte_across_admission_and_chunk_boundaries() { + let exec = FakeExec::default(); + let fs = open(&exec, Engine::Docker); + ready(&exec, Engine::Docker); + for (chunks, expected) in [ + (vec![&b"0\0"[..]], &b""[..]), + (vec![&b"1\0"[..], &b"x"[..]], &b"x"[..]), + ( + vec![&b"1"[..], &b"2\0abc"[..], &b"defghijkl"[..]], + &b"abcdefghijkl"[..], + ), + (vec![&b"5\0abcde"[..]], &b"abcde"[..]), + ] { + let sink = exec.queue_stream("docker exec"); + for chunk in chunks { + assert_eq!(sink.send(chunk.to_vec()).now_or_never(), Some(true)); + } + sink.finish(ExecExit { + status: Some(0), + stderr: String::new(), + }); + drop(sink); + let mut download = block_on(fs.download("/file")).unwrap(); + let mut actual = Vec::new(); + for max in [1, 3, 2, 32768].into_iter().cycle() { + let bytes = block_on(download.read(max)).unwrap(); + assert!(bytes.len() <= max); + if bytes.is_empty() { + break; + } + actual.extend(bytes); + } + assert_eq!(actual, expected); + assert!(block_on(download.read(1)).unwrap().is_empty()); + block_on(download.close()).unwrap(); + } +} + async fn observed(exec: &FakeExec, count: usize) { for _ in 0..1000 { if exec.requests().len() >= count { @@ -338,3 +455,65 @@ fn an_upload_batch_uses_one_acknowledged_container_command() { response(&exec, Engine::Docker, vec![], 0); block_on(upload.cancel()).unwrap(); } + +#[test] +#[ignore = "release profile of container download through RemoteFs"] +fn measure_container_download() { + use std::{io::Write as _, time::Instant}; + let read_size = std::env::var("NOCTERM_PROFILE_READ_SIZE") + .map_or(Ok(32768), |size| size.parse::()) + .unwrap(); + let output_size = std::env::var("NOCTERM_PROFILE_OUTPUT_SIZE") + .map_or(Ok(32768), |size| size.parse::()) + .unwrap(); + assert!((1..=32768).contains(&read_size)); + assert!((1..=256 * 1024).contains(&output_size)); + let data: Vec<_> = (0..8 * 1024 * 1024 + 33) + .map(|index| (index % 251) as u8) + .collect(); + let exec = FakeExec::default(); + let fs = open(&exec, Engine::Docker); + ready(&exec, Engine::Docker); + response(&exec, Engine::Docker, b"/root".to_vec(), 0); + assert_eq!(block_on(fs.home()).unwrap(), "/root"); + let mut samples = Vec::new(); + let mut reads = 0usize; + for _ in 0..7 { + let sink = exec.queue_stream("docker exec"); + let started = Instant::now(); + std::thread::scope(|scope| { + let source = &data; + let producer = scope.spawn(move || { + block_on(async { + assert!(sink.send(format!("{}\0", source.len()).into_bytes()).await); + for chunk in source.chunks(output_size) { + assert!(sink.send(chunk.to_vec()).await); + } + sink.finish(ExecExit { + status: Some(0), + stderr: String::new(), + }); + }); + }); + let mut download = block_on(fs.download("/large")).unwrap(); + let mut actual = Vec::with_capacity(data.len()); + loop { + let chunk = block_on(download.read(read_size)).unwrap(); + assert!(chunk.len() <= read_size); + if chunk.is_empty() { + break; + } + reads += 1; + actual.extend(chunk); + } + block_on(download.close()).unwrap(); + producer.join().unwrap(); + samples.push(started.elapsed()); + assert_eq!(actual, data); + }); + } + samples.sort_unstable(); + writeln!(std::io::stdout().lock(), + "output_size={output_size} read_size={read_size} reads={reads} transfer_p50={:?} transfer_max={:?}", + samples[3], samples[6]).unwrap(); +} diff --git a/crates/project-environment/src/environment.rs b/crates/project-environment/src/environment.rs index e04df87e..a0ffeed1 100644 --- a/crates/project-environment/src/environment.rs +++ b/crates/project-environment/src/environment.rs @@ -57,7 +57,7 @@ impl WorkspaceEnvironment for NativeWorkspaceEnvironment { cancel, progress, ); - let snapshot = probe::inspect(commands.as_ref(), &source).await?; + let snapshot = probe::observe(commands.as_ref()).await?; install(commands.as_ref(), &snapshot, &selections, false).await?; probe::inspect(commands.as_ref(), &source).await } @@ -145,10 +145,8 @@ pub(crate) async fn install_created( location.to_target().map_err(EnvironmentError::from)?, commands.executor(), )?; - let scoped = commands.with_executor(Arc::new(EnvironmentExec { - source: source.clone(), - })); - let snapshot = probe::inspect(scoped.as_ref(), &source).await?; + let scoped = commands.with_executor(Arc::new(EnvironmentExec { source })); + let snapshot = probe::observe(scoped.as_ref()).await?; if selections.is_empty() { return platform::InstallPlatform::new(&snapshot, true)? .prepare(scoped.as_ref(), &snapshot, selections) diff --git a/crates/project-environment/src/environment/probe.rs b/crates/project-environment/src/environment/probe.rs index 248a2b83..99cf2824 100644 --- a/crates/project-environment/src/environment/probe.rs +++ b/crates/project-environment/src/environment/probe.rs @@ -25,9 +25,8 @@ emit node "$(node --version 2>/dev/null | head -c 256)" emit java "$(java -version 2>&1 | head -n 1 | head -c 256)" "#; -pub(super) async fn inspect( +pub(super) async fn observe( commands: &dyn EnvironmentCommands, - source: &EnvironmentSource, ) -> Result { let output = commands .observation(None) @@ -41,7 +40,16 @@ pub(super) async fn inspect( nocterm_project_providers::ProjectSetupError::TimedOut => EnvironmentError::TimedOut, error => EnvironmentError::Probe(Box::new(error)), })?; - let mut snapshot = decode(&output)?; + let snapshot = decode(&output)?; + commands.check()?; + Ok(snapshot) +} + +pub(super) async fn inspect( + commands: &dyn EnvironmentCommands, + source: &EnvironmentSource, +) -> Result { + let mut snapshot = observe(commands).await?; if let Ok(location) = ContainerLocation::from_target(source.target()) { let mut facts = ContainerFacts { engine: location.engine(), @@ -65,10 +73,10 @@ pub(super) async fn inspect( { decode_container_metadata(&mut facts, &output); } + commands.check()?; } snapshot.container = Some(facts); } - commands.check()?; Ok(snapshot) } fn decode_container_metadata(facts: &mut ContainerFacts, output: &str) { diff --git a/crates/project-providers/src/testing.rs b/crates/project-providers/src/testing.rs index adae2c94..de3ed285 100644 --- a/crates/project-providers/src/testing.rs +++ b/crates/project-providers/src/testing.rs @@ -18,6 +18,7 @@ struct PreparationScript { discarded: Vec, inventories: VecDeque>, discovered: Vec>, + discovery_gate: Option>, prepared: Vec>, updates: VecDeque>, gate: Option>, @@ -43,6 +44,13 @@ impl FakeProjectPreparation { .push_back(inventory); Ok(()) } + pub fn suspend_discovery(&self, gate: BoxFuture<'static, ()>) -> Result<(), ProjectSetupError> { + self.state + .lock() + .map_err(|_| ProjectSetupError::Canceled)? + .discovery_gate = Some(gate); + Ok(()) + } pub fn discovered(&self) -> Result>, ProjectSetupError> { Ok(self .state @@ -109,9 +117,18 @@ impl ProjectPreparation for FakeProjectPreparation { fn discover(&self, exec: Arc) -> SetupFuture> { let state = self.state.clone(); async move { - let mut state = state.lock().map_err(|_| ProjectSetupError::Canceled)?; - state.discovered.push(exec); - Ok(state.inventories.pop_front().unwrap_or_default()) + let (gate, inventory) = { + let mut state = state.lock().map_err(|_| ProjectSetupError::Canceled)?; + state.discovered.push(exec); + ( + state.discovery_gate.take(), + state.inventories.pop_front().unwrap_or_default(), + ) + }; + if let Some(gate) = gate { + gate.await; + } + Ok(inventory) } .boxed() } diff --git a/crates/projects/src/editor.rs b/crates/projects/src/editor.rs index 2014ffaa..de4aa29f 100644 --- a/crates/projects/src/editor.rs +++ b/crates/projects/src/editor.rs @@ -352,6 +352,7 @@ impl ProjectEditor { } fn dismiss(&mut self, cx: &mut App) { self.dismissed.store(true, Ordering::Release); + self.controls.cancel_inventory(cx); if let Some(environment) = &self.environment { environment.update(cx, |environment, _| environment.cancel()); } diff --git a/crates/projects/src/editor/controls.rs b/crates/projects/src/editor/controls.rs index 182fc545..6bb27434 100644 --- a/crates/projects/src/editor/controls.rs +++ b/crates/projects/src/editor/controls.rs @@ -160,6 +160,11 @@ impl ProjectControls { options.update(cx, |options, cx| options.lock(locked, cx)); } } + pub(super) fn cancel_inventory(&self, cx: &mut App) { + if let Some(options) = &self.options { + options.update(cx, WorkspaceOptions::cancel_inventory); + } + } pub(super) fn directory_check( &self, cx: &App, diff --git a/crates/projects/src/editor/options.rs b/crates/projects/src/editor/options.rs index 83994a34..09205fa5 100644 --- a/crates/projects/src/editor/options.rs +++ b/crates/projects/src/editor/options.rs @@ -3,7 +3,9 @@ mod container_picker; mod container_row; use container_picker::{ContainerPicker, ContainerPickerEvent}; mod image_picker; +mod inventory; mod registry_search; +mod search; use super::navigation::WizardStep; use crate::Installed; use crate::languages::{LanguageChooser, LanguagesChanged}; @@ -11,7 +13,7 @@ use gpui_kit::{ App, AppContext as _, Context, Entity, EventEmitter, Subscription, Window, component::input::{InputEvent, InputState}, }; -use image_picker::{ImageChanged, ImagePicker}; +use image_picker::{ImageChanged, ImagePicker, ImageSourceChanged}; use nocterm_containers::Engine; use nocterm_explorer::directory::Directory; use nocterm_project_model::{HostLocator, ProjectId, RootPath}; @@ -130,7 +132,8 @@ impl WorkspaceOptions { |this, containers, event: &ContainerPickerEvent, cx| match event { ContainerPickerEvent::Changed => this.draft_changed(cx), ContainerPickerEvent::Inventory => this.controls.images.update(cx, |images, cx| { - images.inventory(containers.read(cx).inventory()); + let containers = containers.read(cx); + images.inventory(containers.inventory(), containers.loading()); cx.notify() }), }, @@ -143,6 +146,12 @@ impl WorkspaceOptions { this.draft_changed(cx); }), ); + subscriptions.push(cx.subscribe( + &controls.images, + |this, _, _: &ImageSourceChanged, cx| { + this.update_inventory_demand(cx); + }, + )); subscriptions.push( cx.subscribe(&controls.languages, |this, _, _: &LanguagesChanged, cx| { this.draft_changed(cx) @@ -259,6 +268,7 @@ impl WorkspaceOptions { } pub(super) fn show_step(&mut self, step: WizardStep, cx: &mut Context) { self.step = step; + self.update_inventory_demand(cx); cx.notify(); } fn path(&self, cx: &App) -> String { @@ -392,12 +402,32 @@ impl WorkspaceOptions { self.locked, cx, ); - images.inventory(self.containers.read(cx).inventory()); + let containers = self.containers.read(cx); + images.inventory(containers.inventory(), containers.loading()); cx.notify(); }); self.controls .languages .update(cx, |languages, cx| languages.configure(self.locked, cx)); + self.update_inventory_demand(cx); + } + + fn update_inventory_demand(&self, cx: &mut Context) { + let needed = self.step == WizardStep::Connection + && !self.locked + && match self.choices.mode { + CreationMode::Direct => false, + CreationMode::Existing => true, + CreationMode::New => self.controls.images.read(cx).shows_local_images(), + }; + self.containers + .update(cx, |containers, cx| containers.set_demand(needed, cx)); + } + + pub(super) fn cancel_inventory(&mut self, cx: &mut Context) { + self.locked = true; + self.containers + .update(cx, ContainerPicker::cancel_discovery); } } diff --git a/crates/projects/src/editor/options/container_picker.rs b/crates/projects/src/editor/options/container_picker.rs index 138b70ff..876752fc 100644 --- a/crates/projects/src/editor/options/container_picker.rs +++ b/crates/projects/src/editor/options/container_picker.rs @@ -1,9 +1,14 @@ //! Original-host container discovery, filtering and exact resource selection. -use super::container_row; +use super::{ + container_row, + inventory::{Inventory, InventoryList, RowContent}, +}; use gpui_kit::{ - App, AppContext as _, Context, Entity, EventEmitter, FocusHandle, Focusable as _, IntoElement, - Render, Subscription, Window, + AnyElement, App, AppContext as _, Context, DispatchPhase, Entity, EventEmitter, FocusHandle, + Focusable as _, HitboxBehavior, IntoElement, IsZero, ListSizingBehavior, ListState, Pixels, + Render, ScrollWheelEvent, Subscription, Task, Window, base::TestSupportExt as _, + canvas, component::{ ActiveTheme as _, Disableable as _, Sizable as _, StyledExt as _, button::{Button, ButtonVariants as _}, @@ -11,27 +16,34 @@ use gpui_kit::{ input::{Input, InputEvent, InputState}, v_flex, }, - div, + div, list, prelude::*, px, }; use nocterm_containers::Engine; use nocterm_project_model::HostLocator; -use nocterm_project_providers::{EngineInventory, ProjectPreparation, ProjectSetupError}; +use nocterm_project_providers::{ProjectPreparation, ProjectSetupError}; use nocterm_workspace_ports::ProjectCreationSource; use std::sync::Arc; pub(super) enum ContainerPickerEvent { Changed, Inventory, } +struct Selection { + engine: Engine, + id: String, + name: Option, +} + pub(super) struct ContainerPicker { source: ProjectCreationSource, preparation: Option>, - inventory: Vec, - loading: bool, + inventory: InventoryList, + discovery: Option>, + discovered: bool, error: Option, search: Entity, - selected: Option<(Engine, String)>, + selected: Option, locked: bool, _subscriptions: Vec, } @@ -46,26 +58,31 @@ impl ContainerPicker { let search = cx.new(|cx| { InputState::new(window, cx).placeholder("Name, image, container ID or engine") }); - let subscription = cx.subscribe(&search, |_, _, _: &InputEvent, cx| cx.notify()); - let mut this = Self { + let subscription = cx.subscribe(&search, |_, _, event: &InputEvent, cx| { + if matches!(event, InputEvent::Change) { + cx.notify(); + } + }); + Self { source, preparation, - inventory: vec![], - loading: false, + inventory: InventoryList::default(), + discovery: None, + discovered: false, error: None, search, selected: None, locked: false, _subscriptions: vec![subscription], - }; - this.discover(cx); - this + } } - pub(super) fn inventory(&self) -> &[EngineInventory] { - &self.inventory + pub(super) fn inventory(&self) -> &Inventory { + self.inventory.inventory() } pub(super) fn selected(&self) -> Option<(Engine, String)> { - self.selected.clone() + self.selected + .as_ref() + .map(|selection| (selection.engine, selection.id.clone())) } pub(super) fn focus(&self, cx: &App) -> FocusHandle { self.search.focus_handle(cx) @@ -74,39 +91,27 @@ impl ContainerPicker { self.locked = locked; cx.notify(); } - fn matches( - &self, - engine: Engine, - container: &nocterm_containers::Container, - images: &[nocterm_containers::Image], - cx: &App, - ) -> bool { - let query = self.search.read(cx).value().trim().to_ascii_lowercase(); - let engine = match engine { - Engine::Docker => "docker", - Engine::Podman => "podman", - }; - [ - container.name.as_str(), - &container.id, - &container.image, - engine, - ] - .iter() - .any(|text| text.to_ascii_lowercase().contains(&query)) - || images - .iter() - .filter(|image| image.id == container.image) - .any(|image| { - format!( - "{}:{}", - image.repository.as_deref().unwrap_or(""), - image.tag.as_deref().unwrap_or("") - ) - .to_ascii_lowercase() - .contains(&query) - }) + pub(super) fn set_demand(&mut self, needed: bool, cx: &mut Context) { + if needed { + if !self.discovered { + self.discover(cx); + } + } else { + self.cancel_discovery(cx); + } + } + + pub(super) fn loading(&self) -> bool { + self.discovery.is_some() } + + pub(super) fn cancel_discovery(&mut self, cx: &mut Context) { + if self.discovery.take().is_some() { + cx.emit(ContainerPickerEvent::Inventory); + cx.notify(); + } + } + fn discover(&mut self, cx: &mut Context) { let Some(preparation) = self.preparation.clone() else { return; @@ -114,99 +119,97 @@ impl ContainerPicker { let Some(exec) = self.source.executor() else { return; }; - if self.loading { + if self.loading() || self.locked { return; } - self.loading = true; self.error = None; - cx.notify(); - cx.spawn(async move |this, cx| { + self.discovery = Some(cx.spawn(async move |this, cx| { let result = cx .background_executor() - .spawn(preparation.discover(exec)) + .spawn(async move { preparation.discover(exec).await.map(Inventory::new) }) .await; let _ = this.update(cx, |this, cx| { - this.loading = false; + this.discovery.take(); + this.discovered = true; match result { Ok(inventory) => { - this.inventory = inventory; + if let Some(selection) = &mut this.selected { + selection.name = inventory + .container_name(selection.engine, &selection.id) + .map(str::to_owned); + } + this.inventory.replace(inventory); } Err(error) => this.error = Some(error), }; cx.emit(ContainerPickerEvent::Inventory); cx.notify(); }); - }) - .detach(); + })); + cx.emit(ContainerPickerEvent::Inventory); + cx.notify(); } - fn engine_inventory( - &self, - inventory: &EngineInventory, - cx: &mut Context, - ) -> impl IntoElement + use<> { - let engine = inventory.engine; - let label = match engine { - Engine::Docker => "Docker", - Engine::Podman => "Podman", - }; - v_flex() - .gap_1() - .when_some(inventory.containers.as_ref().err(), |view, error| { - view.child( - div() - .id(gpui_kit::SharedString::from(format!( - "project-container-engine-error-{label}" - ))) - .test_support() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(format!("{label}: {error}")), - ) - }) - .when_some(inventory.containers.as_ref().ok(), |view, containers| { - view.when(containers.is_empty(), |view| { - view.child( + fn render_inventory(&self, height: Pixels, cx: &mut Context) -> impl IntoElement + use<> { + let (inventory, rows, scroll) = self.inventory.visible_source(); + let wheel = wheel_scroll(scroll.clone()); + div() + .id("project-container-list") + .test_support() + .relative() + .w_full() + .min_w_0() + .max_h(height) + .child( + list( + scroll, + cx.processor(move |this, index, _, cx| { + let item = match inventory.content(rows[index]) { + RowContent::Status(engine, error) => { + Self::status_row(engine, error, cx) + } + RowContent::Container(engine, container, image_label) => this + .container_row(engine, container, image_label, cx) + .into_any_element(), + }; div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(format!("{label}: no containers")), - ) - }) - .children( - containers - .iter() - .filter(|container| { - self.matches( - engine, - container, - inventory.images.as_deref().unwrap_or(&[]), - cx, - ) - }) - .collect::>() - .into_iter() - .map(|container| { - self.container_row( - engine, - label, - container, - inventory.images.as_deref().unwrap_or(&[]), - cx, - ) - }), + .w_full() + .min_w_0() + .when(index + 1 < rows.len(), |row| row.pb_1()) + .child(item) + .into_any_element() + }), ) - }) + .with_sizing_behavior(ListSizingBehavior::Infer) + .w_full() + .max_h(height), + ) + .child(wheel) + } + + fn status_row( + engine: Engine, + error: Option<&nocterm_containers::ContainersError>, + cx: &App, + ) -> AnyElement { + let label = engine.name(); + let row = div().text_xs().text_color(cx.theme().muted_foreground); + match error { + Some(error) => row + .id(gpui_kit::SharedString::from(format!( + "project-container-engine-error-{label}" + ))) + .test_support() + .child(format!("{label}: {error}")) + .into_any_element(), + None => row + .child(format!("{label}: no containers")) + .into_any_element(), + } } - fn selected_summary(&self, engine: Engine, id: &str) -> impl IntoElement + use<> { - let name = self - .inventory - .iter() - .filter(|inventory| inventory.engine == engine) - .filter_map(|inventory| inventory.containers.as_ref().ok()) - .flatten() - .find(|container| container.id == id) - .map(|container| container.name.as_str()) - .unwrap_or("Unavailable container"); + + fn selected_summary(selection: &Selection) -> impl IntoElement + use<> { + let Selection { engine, id, name } = selection; + let name = name.as_deref().unwrap_or("Unavailable container"); let full = format!("Selected {name} · {engine:?}: {id}"); let tooltip = full.clone(); let compact = id.chars().take(12).collect::(); @@ -238,25 +241,34 @@ impl ContainerPicker { fn container_row( &self, engine: Engine, - label: &str, container: &nocterm_containers::Container, - images: &[nocterm_containers::Image], + image_label: String, cx: &mut Context, ) -> Button { let id = container.id.clone(); let selected = self .selected .as_ref() - .is_some_and(|(selected_engine, selected_id)| { - *selected_engine == engine && selected_id == &id - }); - container_row::ContainerRow::new(container, images, label, selected) + .is_some_and(|selection| selection.engine == engine && selection.id == id); + container_row::ContainerRow::new(container, image_label, engine.name(), selected) .render(cx) .disabled(self.locked) .on_click(cx.listener(move |this, _, _, cx| { - let selected = (engine, id.clone()); - if this.selected.as_ref() != Some(&selected) { - this.selected = Some(selected); + if !this + .selected + .as_ref() + .is_some_and(|selection| selection.engine == engine && selection.id == id) + { + let name = this + .inventory + .inventory() + .container_name(engine, &id) + .map(str::to_owned); + this.selected = Some(Selection { + engine, + id: id.clone(), + name, + }); cx.emit(ContainerPickerEvent::Changed); cx.notify(); } @@ -268,35 +280,43 @@ impl Render for ContainerPicker { let height = (window.viewport_size().height - px(520.)) .max(px(80.)) .min(px(200.)); - let matches = self - .inventory - .iter() - .filter_map(|inventory| { - inventory - .containers - .as_ref() - .ok() - .map(|containers| (inventory, containers)) - }) - .any(|(inventory, containers)| { - containers.iter().any(|container| { - self.matches( - inventory.engine, - container, - inventory.images.as_deref().unwrap_or(&[]), - cx, - ) - }) - }); + let query = self.search.read(cx).value(); + let matches = self.inventory.prepare(&query); v_flex().gap_1().w_full().min_w_0() .child(h_flex().justify_between().child(div().text_sm().font_medium().child(if matches!(self.source.parent().host(), HostLocator::Local) { "Containers on this computer" } else { "Containers on this server" })) - .child(Button::new("project-container-refresh").ghost().xsmall().label("Refresh").disabled(self.loading || self.locked).on_click(cx.listener(|this, _, _, cx| this.discover(cx))))) + .child(Button::new("project-container-refresh").ghost().xsmall().label("Refresh").disabled(self.loading() || self.locked).on_click(cx.listener(|this, _, _, cx| this.discover(cx))))) .child(div().id("project-container-search").test_support().child(Input::new(&self.search).id("input").aria_label("Search containers").small().disabled(self.locked))) - .when_some(self.selected.as_ref(), |view, (engine, id)| view.child(self.selected_summary(*engine, id))) - .when(self.loading, |view| view.child(div().text_xs().text_color(cx.theme().muted_foreground).child("Loading Docker and Podman containers…"))) + .when_some(self.selected.as_ref(), |view, selection| view.child(Self::selected_summary(selection))) + .when(self.loading(), |view| view.child(div().text_xs().text_color(cx.theme().muted_foreground).child("Loading Docker and Podman containers…"))) .when(self.source.executor().is_none(), |view| view.child(div().text_xs().text_color(cx.theme().muted_foreground).child("This session does not offer command execution. Reconnect to list containers."))) - .when(!matches && !self.loading && !self.search.read(cx).value().is_empty(), |view| view.child(div().id("project-container-no-matches").test_support().text_xs().child("No containers match this search. Clear the search to see all containers."))) - .child(v_flex().id("project-container-list").test_support().w_full().min_w_0().gap_1().max_h(height).overflow_y_scroll().children(self.inventory.iter().map(|inventory| self.engine_inventory(inventory, cx)))) + .when(!matches && !self.loading() && !query.is_empty(), |view| view.child(div().id("project-container-no-matches").test_support().text_xs().child("No containers match this search. Clear the search to see all containers."))) + .child(self.render_inventory(height, cx)) .when_some(self.error.as_ref(), |view, error| view.child(nocterm_ui::form::error_text(error.to_string(), cx))) } } + +fn wheel_scroll(scroll: ListState) -> impl IntoElement { + canvas( + |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal), + move |_, hitbox, window, _| { + let line_height = window.line_height(); + let view = window.current_view(); + window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || !hitbox.should_handle_scroll(window) { + return; + } + let delta = event.delta.pixel_delta(line_height); + if event.delta.precise() && !delta.y.is_zero() { + return; + } + let vertical = if delta.y.is_zero() { delta.x } else { delta.y }; + if scroll.scroll_wheel_pixels(vertical) { + cx.notify(view); + cx.stop_propagation(); + } + }); + }, + ) + .absolute() + .inset_0() +} diff --git a/crates/projects/src/editor/options/container_row.rs b/crates/projects/src/editor/options/container_row.rs index 541a0303..1201a636 100644 --- a/crates/projects/src/editor/options/container_row.rs +++ b/crates/projects/src/editor/options/container_row.rs @@ -10,24 +10,24 @@ use gpui_kit::{ div, prelude::*, }; -use nocterm_containers::{Container, Image}; +use nocterm_containers::Container; pub(super) struct ContainerRow<'a> { container: &'a Container, - images: &'a [Image], + image_label: String, engine: &'a str, selected: bool, } impl<'a> ContainerRow<'a> { pub(super) fn new( container: &'a Container, - images: &'a [Image], + image_label: String, engine: &'a str, selected: bool, ) -> Self { Self { container, - images, + image_label, engine, selected, } @@ -55,7 +55,12 @@ impl<'a> ContainerRow<'a> { .min_w_0() .gap_3() .items_start() - .child(self.description(&key, cx)) + .child(Self::description( + self.container, + &key, + self.image_label, + cx, + )) .child( v_flex() .flex_shrink_0() @@ -79,23 +84,22 @@ impl<'a> ContainerRow<'a> { ), ) } - fn description(&self, key: &str, cx: &App) -> impl IntoElement + use<> { + fn description( + container: &Container, + key: &str, + image_label: String, + cx: &App, + ) -> impl IntoElement + use<> { v_flex() .flex_1() .min_w_0() .gap_1() - .child(Self::line( - key, - "name", - self.container.name.clone(), - true, - cx, - )) - .child(Self::line(key, "image", self.image_label(), false, cx)) + .child(Self::line(key, "name", container.name.clone(), true, cx)) + .child(Self::line(key, "image", image_label, false, cx)) .child(Self::line( key, "status", - self.container.status.clone(), + container.status.clone(), false, cx, )) @@ -120,18 +124,4 @@ impl<'a> ContainerRow<'a> { }) .child(text) } - fn image_label(&self) -> String { - let reference = &self.container.image; - let digest = reference.strip_prefix("sha256:").unwrap_or(reference); - if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return reference.clone(); - } - if let Some(image) = self.images.iter().find(|image| { - image.id.strip_prefix("sha256:").unwrap_or(&image.id) == digest - && image.repository.is_some() - }) { - return image.name(); - } - format!("Image sha256:{}", &digest[..12]) - } } diff --git a/crates/projects/src/editor/options/image_picker.rs b/crates/projects/src/editor/options/image_picker.rs index a7b3acd4..c1d3d3e7 100644 --- a/crates/projects/src/editor/options/image_picker.rs +++ b/crates/projects/src/editor/options/image_picker.rs @@ -1,5 +1,9 @@ //! Image draft, immediate local filtering and captured-host registry search. -use super::registry_search::{RegistrySearchState, SearchKey, SearchStatus}; +use super::{ + inventory::{ImageResult, Inventory}, + registry_search::{RegistrySearchState, SearchKey, SearchStatus}, + search::AsciiSearch, +}; use gpui_kit::{ App, AppContext as _, Context, Entity, EventEmitter, IntoElement, Render, SharedString, Subscription, Window, @@ -16,18 +20,85 @@ use gpui_kit::{ px, }; use nocterm_containers::{Engine, Image}; -use nocterm_project_providers::{ - EngineInventory, ImageSearch, ImageSearchQuery, RegistryImage, WorkspaceImage, -}; +use nocterm_project_providers::{ImageSearch, ImageSearchQuery, RegistryImage, WorkspaceImage}; use nocterm_workspace_ports::ProjectCreationSource; use std::{sync::Arc, time::Duration}; pub(super) struct ImageChanged; impl EventEmitter for ImagePicker {} +pub(super) struct ImageSourceChanged; +impl EventEmitter for ImagePicker {} #[derive(Default)] struct LocalImages { - images: Vec, - error: Option, + images: Option>, + query: Option, + matches: Vec, + loading: bool, +} + +impl LocalImages { + fn replace(&mut self, images: Option>) { + if let (Some(old), Some(new)) = (&self.images, &images) + && Arc::ptr_eq(old, new) + { + return; + } + self.images = images; + self.query = None; + } + + fn filter(&mut self, query: &str) { + if self + .query + .as_deref() + .is_some_and(|previous| previous.eq_ignore_ascii_case(query.trim())) + { + return; + } + let mut search = AsciiSearch::new(query); + let images = self + .images + .as_deref() + .and_then(|images| images.as_ref().ok()); + self.matches.clear(); + self.matches.extend( + images + .into_iter() + .flatten() + .enumerate() + .filter_map(|(index, image)| image_matches(image, &mut search).then_some(index)) + .take(25), + ); + self.query = Some(search.into_needle()); + } + + fn rows(&self) -> impl Iterator { + let images = self + .images + .as_deref() + .and_then(|images| images.as_ref().ok()); + self.matches + .iter() + .filter_map(move |index| images.and_then(|images| images.get(*index))) + } + + fn error(&self) -> Option<&nocterm_containers::ContainersError> { + self.images + .as_deref() + .and_then(|images| images.as_ref().err()) + } +} + +fn image_matches(image: &Image, search: &mut AsciiSearch) -> bool { + match (&image.repository, &image.tag) { + (Some(repository), Some(tag)) => { + search.contains(repository) + || search.contains(tag) + || search.contains_tagged(repository, tag) + } + (Some(repository), None) => search.contains(repository), + (None, tag) => search.contains(tag.as_deref().unwrap_or("")) || search.contains(&image.id), + } } pub(super) struct ImagePicker { source: ProjectCreationSource, @@ -104,22 +175,13 @@ impl ImagePicker { } cx.notify(); } - pub(super) fn inventory(&mut self, inventories: &[EngineInventory]) { - self.local = match inventories - .iter() - .find(|inventory| inventory.engine == self.engine) - .map(|inventory| &inventory.images) - { - Some(Ok(images)) => LocalImages { - images: images.clone(), - error: None, - }, - Some(Err(error)) => LocalImages { - images: vec![], - error: Some(error.to_string()), - }, - None => LocalImages::default(), - }; + pub(super) fn shows_local_images(&self) -> bool { + self.is_custom() && self.results_source == 0 + } + + pub(super) fn inventory(&mut self, inventory: &Inventory, loading: bool) { + self.local.replace(inventory.images(self.engine)); + self.local.loading = loading; } fn refresh(&mut self, cx: &mut Context) { let draft = self.input.read(cx).value().to_string(); @@ -184,36 +246,22 @@ impl ImagePicker { cx.notify(); } fn local_images( - &self, + &mut self, height: gpui_kit::Pixels, cx: &mut Context, ) -> impl IntoElement + use<> { - let query = self.input.read(cx).value().trim().to_ascii_lowercase(); - let rows: Vec<_> = self - .local - .images - .iter() - .filter(|image| { - [ - image.repository.as_deref().unwrap_or(""), - image.tag.as_deref().unwrap_or(""), - &Self::reference(image), - ] - .iter() - .any(|text| text.to_ascii_lowercase().contains(&query)) - }) - .take(25) - .collect(); + self.local.filter(&self.input.read(cx).value()); + let error = self.local.error(); v_flex() .w_full() .min_w_0() .gap_1() - .when_some(self.local.error.as_ref(), |view, error| { + .when_some(error, |view, error| { view.child( div() .text_xs() .text_color(cx.theme().muted_foreground) - .child(error.clone()), + .child(error.to_string()), ) }) .child( @@ -224,15 +272,31 @@ impl ImagePicker { .min_w_0() .max_h(height) .overflow_y_scroll() - .when(rows.is_empty() && self.local.error.is_none(), |view| { + .when(self.local.loading, |view| { view.child( div() + .id("project-local-images-loading") + .test_support() + .role(gpui_kit::Role::Status) .text_xs() .text_color(cx.theme().muted_foreground) - .child("No matching local images. You can enter a full reference."), + .child("Loading local images…"), ) }) - .children(rows.into_iter().map(|image| { + .when( + !self.local.loading && self.local.matches.is_empty() && error.is_none(), + |view| { + view.child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child( + "No matching local images. You can enter a full reference.", + ), + ) + }, + ) + .children(self.local.rows().map(|image| { let reference = Self::reference(image); self.image_row( format!("project-local-image-{}", image.id), @@ -301,8 +365,11 @@ impl ImagePicker { ) .on_click(move |index, _, cx| { let _ = owner.update(cx, |this, cx| { - this.results_source = *index; - cx.notify(); + if this.results_source != *index { + this.results_source = *index; + cx.emit(ImageSourceChanged); + cx.notify(); + } }); }) } @@ -409,7 +476,11 @@ impl Render for ImagePicker { .selected(std::mem::discriminant(&self.image) == std::mem::discriminant(&image)) .disabled(self.locked) .on_click(cx.listener(move |this, _, _, cx| { + let showed_local = this.shows_local_images(); this.image = image.clone(); + if showed_local != this.shows_local_images() { + cx.emit(ImageSourceChanged); + } this.refresh(cx); cx.emit(ImageChanged); cx.notify(); diff --git a/crates/projects/src/editor/options/inventory.rs b/crates/projects/src/editor/options/inventory.rs new file mode 100644 index 00000000..778572d9 --- /dev/null +++ b/crates/projects/src/editor/options/inventory.rs @@ -0,0 +1,255 @@ +//! Prepared rows of one captured host's Docker and Podman inventory. +use std::{collections::HashMap, rc::Rc, sync::Arc}; + +use gpui_kit::{ListAlignment, ListState, px}; +use nocterm_containers::{Container, ContainersError, Engine, Image}; +use nocterm_project_providers::EngineInventory; + +use super::search::AsciiSearch; + +pub(super) type ImageResult = Result, ContainersError>; + +#[derive(Default)] +pub(super) struct Inventory { + engines: Vec, +} + +struct EngineRows { + engine: Engine, + containers: Result, ContainersError>, + images: Arc, + by_image: HashMap, ImageAliases>, +} + +struct ImageAliases { + first: usize, + rest: Vec, +} + +impl From for EngineRows { + fn from(inventory: EngineInventory) -> Self { + let mut by_image: HashMap, ImageAliases> = HashMap::new(); + if let Ok(images) = &inventory.images + && inventory + .containers + .as_ref() + .is_ok_and(|containers| !containers.is_empty()) + { + for (index, image) in images.iter().enumerate() { + let key = without_digest_prefix(&image.id); + if let Some(aliases) = by_image.get_mut(key) { + aliases.rest.push(index); + } else { + by_image.insert( + key.into(), + ImageAliases { + first: index, + rest: Vec::new(), + }, + ); + } + } + } + Self { + engine: inventory.engine, + containers: inventory.containers, + images: Arc::new(inventory.images), + by_image, + } + } +} + +impl EngineRows { + fn aliases<'a>(&'a self, key: &str) -> impl Iterator { + let images = self.images.as_ref().as_deref().unwrap_or_default(); + self.by_image + .get(without_digest_prefix(key)) + .into_iter() + .flat_map(|aliases| std::iter::once(aliases.first).chain(aliases.rest.iter().copied())) + .map(|index| &images[index]) + } + + fn image_label(&self, reference: &str) -> String { + let digest = without_digest_prefix(reference); + if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return reference.to_owned(); + } + self.aliases(reference) + .find(|image| image.repository.is_some()) + .map_or_else(|| format!("Image sha256:{}", &digest[..12]), Image::name) + } + + fn matches(&self, container: &Container, search: &mut AsciiSearch) -> bool { + [container.name.as_str(), &container.id, &container.image] + .into_iter() + .any(|text| search.contains(text)) + || self.aliases(&container.image).any(|image| { + image.id == container.image + && search.contains_tagged( + image.repository.as_deref().unwrap_or(""), + image.tag.as_deref().unwrap_or(""), + ) + }) + } +} + +fn without_digest_prefix(reference: &str) -> &str { + reference.strip_prefix("sha256:").unwrap_or(reference) +} + +#[derive(Clone, Copy)] +pub(super) enum Row { + Status(usize), + Container { engine: usize, index: usize }, +} + +pub(super) enum RowContent<'a> { + Status(Engine, Option<&'a ContainersError>), + Container(Engine, &'a Container, String), +} + +impl Inventory { + pub(super) fn new(inventory: Vec) -> Self { + Self { + engines: inventory.into_iter().map(EngineRows::from).collect(), + } + } + + pub(super) fn images(&self, engine: Engine) -> Option> { + self.engines + .iter() + .find(|rows| rows.engine == engine) + .map(|rows| rows.images.clone()) + } + + pub(super) fn container_name(&self, engine: Engine, id: &str) -> Option<&str> { + self.engines + .iter() + .filter(|rows| rows.engine == engine) + .filter_map(|rows| rows.containers.as_deref().ok()) + .flatten() + .find(|container| container.id == id) + .map(|container| container.name.as_str()) + } + + fn identity(&self, row: Row) -> (Engine, Option<&str>) { + match row { + Row::Status(engine) => (self.engines[engine].engine, None), + Row::Container { engine, index } => { + let rows = &self.engines[engine]; + let container = &rows.containers.as_deref().unwrap_or_default()[index]; + (rows.engine, Some(&container.id)) + } + } + } + + pub(super) fn content(&self, row: Row) -> RowContent<'_> { + match row { + Row::Status(engine) => { + let rows = &self.engines[engine]; + RowContent::Status(rows.engine, rows.containers.as_ref().err()) + } + Row::Container { engine, index } => { + let rows = &self.engines[engine]; + let container = &rows.containers.as_deref().unwrap_or_default()[index]; + RowContent::Container(rows.engine, container, rows.image_label(&container.image)) + } + } + } + + fn filtered(&self, search: &mut AsciiSearch) -> Vec { + let mut filtered = Vec::new(); + for (engine, rows) in self.engines.iter().enumerate() { + match rows.containers.as_deref() { + Ok(containers) if !containers.is_empty() => { + let engine_matches = search.contains(rows.engine.name()); + filtered.extend(containers.iter().enumerate().filter_map( + |(index, container)| { + (engine_matches || rows.matches(container, search)) + .then_some(Row::Container { engine, index }) + }, + )); + } + _ => filtered.push(Row::Status(engine)), + } + } + filtered + } +} + +pub(super) struct InventoryList { + inventory: Arc, + rows: Rc>, + query: Option, + has_matches: bool, + scroll: ListState, +} + +impl Default for InventoryList { + fn default() -> Self { + Self { + inventory: Arc::default(), + rows: Rc::default(), + query: None, + has_matches: false, + scroll: ListState::new(0, ListAlignment::Top, px(96.)), + } + } +} + +impl InventoryList { + pub(super) fn replace(&mut self, inventory: Inventory) { + if let Some(query) = self.query.as_deref() { + let rows = inventory.filtered(&mut AsciiSearch::new(query)); + let mut position = self.scroll.logical_scroll_top(); + let current = self + .rows + .get(position.item_ix) + .map(|row| self.inventory.identity(*row)); + if let Some(index) = current.and_then(|identity| { + rows.iter() + .position(|row| inventory.identity(*row) == identity) + }) { + position.item_ix = index; + } else { + position.item_ix = position.item_ix.min(rows.len().saturating_sub(1)); + position.offset_in_item = px(0.); + } + self.install_rows(rows); + self.scroll.scroll_to(position); + } + self.inventory = Arc::new(inventory); + } + + pub(super) fn inventory(&self) -> &Inventory { + &self.inventory + } + + pub(super) fn prepare(&mut self, query: &str) -> bool { + if !self + .query + .as_deref() + .is_some_and(|previous| previous.eq_ignore_ascii_case(query.trim())) + { + let mut search = AsciiSearch::new(query); + let rows = self.inventory.filtered(&mut search); + self.install_rows(rows); + self.query = Some(search.into_needle()); + } + self.has_matches + } + + fn install_rows(&mut self, rows: Vec) { + self.has_matches = rows.iter().any(|row| matches!(row, Row::Container { .. })); + self.scroll.reset_with_uniform_height(rows.len(), px(80.)); + self.rows = Rc::new(rows); + } + + pub(super) fn visible_source(&self) -> (Arc, Rc>, ListState) { + ( + self.inventory.clone(), + self.rows.clone(), + self.scroll.clone(), + ) + } +} diff --git a/crates/projects/src/editor/options/search.rs b/crates/projects/src/editor/options/search.rs new file mode 100644 index 00000000..70bb5b71 --- /dev/null +++ b/crates/projects/src/editor/options/search.rs @@ -0,0 +1,40 @@ +//! ASCII-insensitive literal matching for native inventory controls. +pub(super) struct AsciiSearch { + needle: String, + folded: String, +} + +impl AsciiSearch { + pub(super) fn new(input: &str) -> Self { + Self { + needle: input.trim().to_ascii_lowercase(), + folded: String::new(), + } + } + + pub(super) fn into_needle(self) -> String { + self.needle + } + + pub(super) fn contains(&mut self, text: &str) -> bool { + if text.contains(&self.needle) { + return true; + } + if text.len() < self.needle.len() || !text.bytes().any(|byte| byte.is_ascii_uppercase()) { + return false; + } + self.folded.clear(); + self.folded.push_str(text); + self.folded.make_ascii_lowercase(); + self.folded.contains(&self.needle) + } + + pub(super) fn contains_tagged(&mut self, repository: &str, tag: &str) -> bool { + self.folded.clear(); + self.folded.push_str(repository); + self.folded.push(':'); + self.folded.push_str(tag); + self.folded.make_ascii_lowercase(); + self.folded.contains(&self.needle) + } +} diff --git a/crates/projects/src/panel.rs b/crates/projects/src/panel.rs index 99c308ba..e43f488f 100644 --- a/crates/projects/src/panel.rs +++ b/crates/projects/src/panel.rs @@ -27,7 +27,7 @@ pub struct ProjectsPanel { search: Entity, parent: Option, can_create: bool, - folded: bool, + library: ProjectLibrary, _subscriptions: Vec, } impl ProjectsPanel { @@ -42,12 +42,15 @@ impl ProjectsPanel { let native_window = window.window_handle(); let mut subscriptions = vec![ installed.observe(cx, move |cx| { - let _ = weak.update(cx, |_, cx| cx.notify()); + let _ = weak.update(cx, |this, cx| { + this.library.catalog_changed(); + cx.notify(); + }); }), // Only an edit refilters; the cursor blink and moves change no match. - cx.subscribe(&search, |_, _, event: &InputEvent, cx| { + cx.subscribe(&search, |this, _, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { - cx.notify(); + this.invalidate_library(cx); } }), ]; @@ -83,14 +86,20 @@ impl ProjectsPanel { search, parent: None, can_create: false, - folded: false, + library: ProjectLibrary::default(), _subscriptions: subscriptions, } } fn refresh(&mut self, window: &Window, cx: &mut Context) { - self.parent = self.workspace.upgrade().and_then(|workspace| { + let parent = self.workspace.upgrade().and_then(|workspace| { context::current(workspace.read(cx), &self.installed, window, cx) }); + if self.parent.as_ref().map(ProjectParentDescriptor::host) + != parent.as_ref().map(ProjectParentDescriptor::host) + { + self.library.invalidate(); + } + self.parent = parent; self.can_create = self.workspace.upgrade().is_some_and(|workspace| { context::capture_current(workspace.read(cx), &self.installed, window, cx).is_ok() }); @@ -117,8 +126,8 @@ impl ProjectsPanel { ), } } - fn toggle_other(&mut self, cx: &mut Context) { - self.folded = !self.folded; + fn invalidate_library(&mut self, cx: &mut Context) { + self.library.invalidate(); cx.notify(); } fn header(&self, cx: &mut Context) -> impl IntoElement + use<> { @@ -167,18 +176,13 @@ impl Focusable for ProjectsPanel { } impl Render for ProjectsPanel { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - let parent_key = self - .parent - .as_ref() - .and_then(|parent| parent.host().parent_key().ok()); - let query = self.search.read(cx).value(); - let groups = - self.installed - .catalog(cx) - .partition_by(parent_key.as_ref(), &query, |target| { - crate::location::host(target).and_then(|host| host.parent_key().ok()) - }); - let library = ProjectLibrary::new(groups, self.folded, !query.trim().is_empty()); + if self.library.needs_projection() { + self.library.prepare( + self.installed.catalog(cx), + self.parent.as_ref(), + &self.search.read(cx).value(), + ); + } let theme = cx.theme().clone(); let error = self .installed @@ -208,11 +212,13 @@ impl Render for ProjectsPanel { .child(error), ) }) - .child(library.render( + .child(self.library.render( self.installed.clone(), self.workspace.clone(), - cx.listener(|this, _, _, cx| this.toggle_other(cx)), - cx, + cx.listener(|this, _, _, cx| { + this.library.toggle_other(); + cx.notify(); + }), )) } } diff --git a/crates/projects/src/panel/library.rs b/crates/projects/src/panel/library.rs index 20726c84..d6cf8c0e 100644 --- a/crates/projects/src/panel/library.rs +++ b/crates/projects/src/panel/library.rs @@ -1,98 +1,219 @@ -//! A bounded rendered catalog snapshot; grouping rules belong to project-model. +//! The panel retains ordered IDs and lays out only the viewport and its overdraw. mod row; use crate::Installed; use gpui_kit::{ - AnyElement, App, ClickEvent, WeakEntity, Window, + AnyElement, App, ClickEvent, DispatchPhase, HitboxBehavior, IsZero, ListAlignment, ListState, + ScrollWheelEvent, WeakEntity, Window, + base::TestSupportExt as _, + canvas, component::{ ActiveTheme as _, Sizable as _, StyledExt as _, button::{Button, ButtonVariants as _}, v_flex, }, - div, + div, list, prelude::*, + px, }; -use nocterm_project_model::{ProjectDefinition, ProjectGroups}; +use nocterm_project_model::{Catalog, ProjectId}; use nocterm_ui::IconName; use nocterm_workspace::Workspace; +use nocterm_workspace_ports::ProjectParentDescriptor; use row::ProjectRow; +use std::rc::Rc; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Row { + Current, + Project(ProjectId), + Other { count: usize, folded: bool }, + Empty { searching: bool }, +} pub(super) struct ProjectLibrary { - current: Vec, - other: Vec, + rows: Rc>, + scroll: ListState, folded: bool, - searching: bool, + dirty: bool, } -impl ProjectLibrary { - pub(super) fn new(groups: ProjectGroups<'_>, folded: bool, searching: bool) -> Self { +impl Default for ProjectLibrary { + fn default() -> Self { Self { - current: groups.current.into_iter().cloned().collect(), - other: groups.other.into_iter().cloned().collect(), - folded, - searching, + rows: Rc::default(), + scroll: ListState::new(0, ListAlignment::Top, px(100.)), + folded: false, + dirty: true, } } +} +impl ProjectLibrary { + pub(super) fn invalidate(&mut self) { + self.dirty = true; + } + + pub(super) fn catalog_changed(&mut self) { + // The same ID can acquire or lose a server caption when its target changes. + self.scroll.remeasure_items(0..self.rows.len()); + self.invalidate(); + } + + pub(super) fn needs_projection(&self) -> bool { + self.dirty + } + + pub(super) fn toggle_other(&mut self) { + self.folded = !self.folded; + self.invalidate(); + } + + pub(super) fn prepare( + &mut self, + catalog: &Catalog, + parent: Option<&ProjectParentDescriptor>, + query: &str, + ) { + let parent_key = parent.and_then(|parent| parent.host().parent_key().ok()); + let groups = catalog.partition_by(parent_key.as_ref(), query, |target| { + crate::location::host(target).and_then(|host| host.parent_key().ok()) + }); + let mut rows = Vec::new(); + if !groups.current.is_empty() { + rows.push(Row::Current); + rows.extend( + groups + .current + .into_iter() + .map(|project| Row::Project(project.id())), + ); + } + if !groups.other.is_empty() { + rows.push(Row::Other { + count: groups.other.len(), + folded: self.folded, + }); + if !self.folded { + rows.extend( + groups + .other + .into_iter() + .map(|project| Row::Project(project.id())), + ); + } + } + if rows.is_empty() { + rows.push(Row::Empty { + searching: !query.trim().is_empty(), + }); + } + + self.dirty = false; + if rows != *self.rows { + let offset = self.scroll.logical_scroll_top(); + // Actual measured row heights replace the initial extent estimate. + self.scroll.reset_with_uniform_height(rows.len(), px(52.)); + self.scroll.scroll_to(offset); + self.rows = Rc::new(rows); + } + } + pub(super) fn render( - self, + &self, installed: Installed, workspace: WeakEntity, on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, - cx: &App, ) -> AnyElement { - let theme = cx.theme().clone(); - let empty = self.current.is_empty() && self.other.is_empty(); - let count = self.other.len(); - let row = |definition| ProjectRow::new(definition, installed.clone(), workspace.clone()); - v_flex() + let rows = self.rows.clone(); + let on_toggle = Rc::new(on_toggle); + div() .id("projects-list") + .test_support() + .relative() .flex_1() .min_h_0() - .overflow_y_scroll() - .when(!self.current.is_empty(), |list| { - list.child( - div() + .child( + list(self.scroll.clone(), move |index, _, cx| match rows[index] { + Row::Current => div() .px_3() .pt_2() .pb_1() .text_xs() .font_medium() - .text_color(theme.muted_foreground) - .child("For this host"), - ) - .children(self.current.into_iter().map(row)) - }) - .when(empty, |list| { - list.child( - div() + .text_color(cx.theme().muted_foreground) + .child("For this host") + .into_any_element(), + Row::Project(id) => installed.catalog(cx).get(id).map_or_else( + || div().into_any_element(), + |definition| { + v_flex() + .w_full() + .min_w_0() + .child(ProjectRow::new( + definition.clone(), + installed.clone(), + workspace.clone(), + )) + .into_any_element() + }, + ), + Row::Other { count, folded } => { + let on_toggle = on_toggle.clone(); + Button::new("projects-other") + .ghost() + .small() + .w_full() + .justify_start() + .icon(if folded { + IconName::ChevronRight + } else { + IconName::ChevronDown + }) + .label(format!("All other workspaces ({count})")) + .on_click(move |event, window, cx| on_toggle(event, window, cx)) + .into_any_element() + } + Row::Empty { searching } => div() .px_3() .py_4() .text_sm() - .text_color(theme.muted_foreground) - .child(if self.searching { + .text_color(cx.theme().muted_foreground) + .child(if searching { "No matching workspaces." } else { "Use + to create a workspace on this host." - }), - ) - }) - .when(count > 0, |list| { - list.child( - Button::new("projects-other") - .ghost() - .small() - .w_full() - .justify_start() - .icon(if self.folded { - IconName::ChevronRight - } else { - IconName::ChevronDown }) - .label(format!("All other workspaces ({count})")) - .on_click(on_toggle), - ) - .when(!self.folded, |list| { - list.children(self.other.into_iter().map(row)) + .into_any_element(), }) - }) + .size_full(), + ) + .child(self.wheel_scroll()) .into_any_element() } + + fn wheel_scroll(&self) -> impl IntoElement + use<> { + let scroll = self.scroll.clone(); + // Match the previous overflow scroll container's line height and axis fallback. + canvas( + |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal), + move |_, hitbox, window, _| { + let line_height = window.line_height(); + let view = window.current_view(); + window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || !hitbox.should_handle_scroll(window) { + return; + } + let delta = event.delta.pixel_delta(line_height); + if event.delta.precise() && !delta.y.is_zero() { + return; + } + let vertical = if delta.y.is_zero() { delta.x } else { delta.y }; + if scroll.scroll_wheel_pixels(vertical) { + cx.notify(view); + cx.stop_propagation(); + } + }); + }, + ) + .absolute() + .inset_0() + } } diff --git a/crates/projects/src/tests.rs b/crates/projects/src/tests.rs index 0a5b1d93..8341c796 100644 --- a/crates/projects/src/tests.rs +++ b/crates/projects/src/tests.rs @@ -17,6 +17,7 @@ mod creation; mod creation_layout; mod environment; mod image_selection; +mod inventory_discovery; mod library; mod lifecycle; mod plugin; diff --git a/crates/projects/src/tests/container_selection.rs b/crates/projects/src/tests/container_selection.rs index fffdbee5..ea826a55 100644 --- a/crates/projects/src/tests/container_selection.rs +++ b/crates/projects/src/tests/container_selection.rs @@ -84,6 +84,10 @@ fn local_attach_preserves_the_selected_engine_and_full_container_id(cx: &mut Tes fill(window, "project-name", "Selected container", cx); wizard_field(window, "project-mode-existing", cx); window.click("project-mode-existing", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); assert_rows_fit(window); let selected = format!("project-container-Docker-{:064x}", 2); @@ -207,6 +211,10 @@ fn shaped_container_rows_keep_separate_lines_and_a_reachable_footer() { window.render_frame(cx); wizard_field(window, "project-mode-existing", cx); window.click("project-mode-existing", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(window, |_, window, cx| { window.render_frame(cx); window.click(format!("project-container-Docker-{:064x}", 2), cx); window.render_frame(cx); @@ -246,6 +254,10 @@ fn container_search_matches_name_full_id_image_and_engine_without_changing_selec cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); window.click("project-mode-existing", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); fill(window, "project-container-search", "Podman", cx); window.render_frame(cx); @@ -282,6 +294,9 @@ fn container_search_matches_name_full_id_image_and_engine_without_changing_selec assert!(window.try_find("project-container-no-matches").is_some()); fill(window, "project-container-search", "", cx); window.render_frame(cx); + assert!(window.try_find("project-container-no-matches").is_none()); + fill(window, "project-container-search", "Podman", cx); + window.render_frame(cx); assert_eq!( window .find(format!("project-container-Podman-{:064x}", 2)) @@ -318,6 +333,10 @@ fn container_search_keeps_independent_engine_errors_visible(cx: &mut TestAppCont cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); window.click("project-mode-existing", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); fill(window, "project-container-search", "missing", cx); window.render_frame(cx); @@ -330,3 +349,303 @@ fn container_search_keeps_independent_engine_errors_visible(cx: &mut TestAppCont }) .unwrap(); } + +fn dense_inventory(count: usize) -> EngineInventory { + EngineInventory { + engine: Engine::Docker, + containers: Ok((0..count) + .map(|index| Container { + id: format!("c{index:05}"), + name: format!("audit-workspace-{index:05}"), + image: format!("sha256:{index:064x}"), + state: State::Running, + status: "Up 3 hours".into(), + project: None, + service: None, + }) + .collect()), + images: Ok((0..count) + .map(|index| Image { + id: format!("sha256:{index:064x}"), + repository: Some(format!("registry.example/team/workspace-{index:05}")), + tag: Some("stable".into()), + size: "2GB".into(), + created: "today".into(), + }) + .collect()), + } +} + +fn scroll_inventory(window: &mut gpui_kit::Window, steps: usize, cx: &mut App) { + use gpui_kit::{ScrollDelta, point, px}; + + for _ in 0..steps { + window.scroll( + "project-container-list", + ScrollDelta::Pixels(point(px(0.), px(-84.))), + cx, + ); + } +} + +fn row_at_list_center(window: &gpui_kit::Window, index: usize) -> bool { + let midpoint = window.find("project-container-list").bounds().center().y; + window + .try_find(format!("project-container-Docker-{index:064x}")) + .is_some_and(|row| { + let bounds = row.bounds(); + bounds.top() <= midpoint && midpoint < bounds.bottom() + }) +} + +#[gpui_kit::test] +#[ignore = "manual workstation inventory benchmark"] +fn measure_filtering_and_scrolling_a_large_container_inventory(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let count = std::env::var("NOCTERM_PROJECT_BENCH_ROWS") + .map(|value| value.parse::().unwrap()) + .unwrap_or(2048); + let preparation = FakeProjectPreparation::default(); + preparation.inventory(vec![dense_inventory(count)]).unwrap(); + let (rig, _, _) = Fixture::local(preparation, cx); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + window.click("project-new", cx); + }) + .unwrap(); + cx.run_until_parked(); + let start = Instant::now(); + cx.update_window(rig.window, |_, window, cx| { + window.click("project-mode-existing", cx) + }) + .unwrap(); + cx.run_until_parked(); + let (entry, misses, scroll) = cx + .update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("project-container-Docker-c00000").is_some()); + let entry = start.elapsed(); + let start = Instant::now(); + for index in 0..6 { + fill( + window, + "project-container-search", + &format!("absent-{index}"), + cx, + ); + window.render_frame(cx); + assert!(window.try_find("project-container-no-matches").is_some()); + } + let misses = start.elapsed(); + let query = format!("workspace-{:05}:stable", count - 1); + fill(window, "project-container-search", &query, cx); + window.render_frame(cx); + assert!( + window + .try_find(format!("project-container-Docker-c{:05}", count - 1)) + .is_some() + ); + fill(window, "project-container-search", "", cx); + window.render_frame(cx); + let start = Instant::now(); + scroll_inventory(window, 12, cx); + (entry, misses, start.elapsed()) + }) + .unwrap(); + writeln!( + std::io::stdout().lock(), + "{count} containers and images: open {entry:?}, 6 search misses {misses:?}, 12 scroll steps {scroll:?}" + ) + .unwrap(); +} + +#[gpui_kit::test] +fn an_offscreen_container_can_be_scrolled_to_and_used_after_filtering_it_out( + cx: &mut TestAppContext, +) { + let preparation = FakeProjectPreparation::default(); + let mut inventory = dense_inventory(120); + for (index, container) in inventory + .containers + .as_mut() + .unwrap() + .iter_mut() + .enumerate() + { + container.id = format!("{index:064x}"); + } + preparation.inventory(vec![inventory]).unwrap(); + preparation + .respond(Ok(PreparedProject { + target: definition(20).target().clone(), + owned: None, + })) + .unwrap(); + let (rig, exec, _) = Fixture::local(preparation.clone(), cx); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + window.click("project-new", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { + window.click("project-mode-existing", cx) + }) + .unwrap(); + cx.run_until_parked(); + let selected = cx + .update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert!( + window + .try_find(format!("project-container-Docker-{:064x}", 0)) + .is_some() + ); + assert!( + window + .try_find(format!("project-container-Docker-{:064x}", 15)) + .is_none() + ); + scroll_inventory(window, 14, cx); + assert!( + window + .try_find(format!("project-container-Docker-{:064x}", 0)) + .is_none() + ); + let selected = (1..120) + .find(|index| row_at_list_center(window, *index)) + .unwrap(); + window.click(format!("project-container-Docker-{selected:064x}"), cx); + fill( + window, + "project-container-search", + "no-matching-inventory-entry", + cx, + ); + window.render_frame(cx); + assert!(window.try_find("project-container-no-matches").is_some()); + assert!( + window + .find("project-container-selected") + .label() + .unwrap() + .contains(&format!("audit-workspace-{selected:05}")) + ); + window.click("project-next", cx); + window.render_frame(cx); + fill(window, "project-name", "Offscreen workspace", cx); + window.click("project-save", cx); + selected + }) + .unwrap(); + cx.run_until_parked(); + assert!(matches!(&preparation.requests().unwrap()[0].mode, + SetupMode::Attach { engine: Engine::Docker, container, .. } if container == &format!("{selected:064x}"))); + assert!(Arc::ptr_eq(&preparation.prepared().unwrap()[0], &exec)); +} + +#[gpui_kit::test] +fn refreshing_the_host_replaces_search_aliases_and_updates_the_selected_name( + cx: &mut TestAppContext, +) { + let preparation = FakeProjectPreparation::default(); + let initial = inventory(Engine::Docker); + let mut refreshed = inventory(Engine::Docker); + refreshed.containers.as_mut().unwrap()[0].name = "renamed container".into(); + let images = refreshed.images.as_mut().unwrap(); + let mut new_alias = images[0].clone(); + new_alias.tag = Some("refreshed-tag".into()); + images[0].tag = Some("primary-tag".into()); + images.push(new_alias); + preparation.inventory(vec![initial]).unwrap(); + preparation.inventory(vec![refreshed]).unwrap(); + let (rig, _, _) = Fixture::local(preparation, cx); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + window.click("project-new", cx); + }) + .unwrap(); + cx.run_until_parked(); + let id = format!("project-container-Docker-{:064x}", 1); + cx.update_window(rig.window, |_, window, cx| { + window.click("project-mode-existing", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + fill(window, "project-container-search", "development:stable", cx); + window.render_frame(cx); + window.click(id.clone(), cx); + window.click("project-container-refresh", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find(id.clone()).is_none()); + assert!(window.try_find("project-container-no-matches").is_some()); + assert!( + window + .find("project-container-selected") + .label() + .unwrap() + .contains("renamed container") + ); + fill( + window, + "project-container-search", + "DEVELOPMENT:REFRESHED-TAG", + cx, + ); + window.render_frame(cx); + assert_eq!(window.find(id).checked(), Some(true)); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn an_inserted_container_during_refresh_keeps_the_current_rows_in_view(cx: &mut TestAppContext) { + let preparation = FakeProjectPreparation::default(); + let count = 80; + preparation.inventory(vec![dense_inventory(count)]).unwrap(); + let mut updated = dense_inventory(count); + let rows = updated.containers.as_mut().unwrap(); + let mut before_first = rows[0].clone(); + before_first.id = "inserted".into(); + rows.insert(0, before_first); + preparation.inventory(vec![updated]).unwrap(); + let (rig, _, _) = Fixture::local(preparation, cx); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + window.click("project-new", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { + window.click("project-mode-existing", cx) + }) + .unwrap(); + cx.run_until_parked(); + let (row, top) = cx + .update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + scroll_inventory(window, 9, cx); + let center = window.find("project-container-list").bounds().center().y; + let visible = (1..count).find_map(|index| { + let id = format!("project-container-Docker-c{index:05}"); + let bounds = window.try_find(id.clone())?.bounds(); + (bounds.top() <= center && center < bounds.bottom()).then_some((id, bounds.top())) + }); + window.click("project-container-refresh", cx); + visible.unwrap() + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert_eq!(window.find(row).bounds().top(), top); + }) + .unwrap(); +} diff --git a/crates/projects/src/tests/creation.rs b/crates/projects/src/tests/creation.rs index 793103ed..3388bb38 100644 --- a/crates/projects/src/tests/creation.rs +++ b/crates/projects/src/tests/creation.rs @@ -363,7 +363,7 @@ fn an_empty_workspace_creates_a_local_folder_with_shared_home_navigation(cx: &mu owned: None, })) .unwrap(); - let (rig, exec, _) = Fixture::local(preparation.clone(), cx); + let (rig, _, _) = Fixture::local(preparation.clone(), cx); cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); assert_eq!( @@ -389,7 +389,7 @@ fn an_empty_workspace_creates_a_local_folder_with_shared_home_navigation(cx: &mu assert_eq!(saved.host_folder().unwrap().1.as_str(), "/home/alice"); assert_eq!(rig.workspace.read(cx).items(cx).count(), 0); }); - assert!(Arc::ptr_eq(&preparation.discovered().unwrap()[0], &exec)); + assert!(preparation.discovered().unwrap().is_empty()); } #[gpui_kit::test] diff --git a/crates/projects/src/tests/creation_layout.rs b/crates/projects/src/tests/creation_layout.rs index 75d47eb7..b97cd855 100644 --- a/crates/projects/src/tests/creation_layout.rs +++ b/crates/projects/src/tests/creation_layout.rs @@ -99,6 +99,10 @@ fn native_discovery( cx.update_window(window, |_, window, cx| { window.render_frame(cx); window.click("project-mode-existing", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(window, |_, window, cx| { window.render_frame(cx); fill(window, "project-container-search", "Podman", cx); window.render_frame(cx); diff --git a/crates/projects/src/tests/image_selection.rs b/crates/projects/src/tests/image_selection.rs index 0b865bb0..467213ea 100644 --- a/crates/projects/src/tests/image_selection.rs +++ b/crates/projects/src/tests/image_selection.rs @@ -91,6 +91,7 @@ fn image_form( window.render_frame(cx); }) .unwrap(); + cx.run_until_parked(); (rig, preparation, exec) } fn wait_for_search(cx: &mut TestAppContext) { diff --git a/crates/projects/src/tests/inventory_discovery.rs b/crates/projects/src/tests/inventory_discovery.rs new file mode 100644 index 00000000..712f9d30 --- /dev/null +++ b/crates/projects/src/tests/inventory_discovery.rs @@ -0,0 +1,104 @@ +//! Demand, cancellation and reuse through the workspace wizard controls. +use super::{container_selection::inventory, support::*, *}; +use nocterm_containers::Engine; +use nocterm_project_providers::testing::FakeProjectPreparation; + +fn click(rig: &Fixture, id: &'static str, cx: &mut TestAppContext) { + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + window.click(id, cx); + }) + .unwrap(); + cx.run_until_parked(); +} + +fn pending_discovery(preparation: &FakeProjectPreparation) -> async_channel::Sender<()> { + let (release, pending) = async_channel::bounded(1); + preparation + .suspend_discovery(Box::pin(async move { + let _ = pending.recv().await; + })) + .unwrap(); + release +} + +#[gpui_kit::test] +fn only_inventory_views_query_the_original_host_and_share_completed_results( + cx: &mut TestAppContext, +) { + let preparation = FakeProjectPreparation::default(); + preparation + .inventory(vec![inventory(Engine::Docker)]) + .unwrap(); + let (rig, host, _) = Fixture::local(preparation.clone(), cx); + click(&rig, "project-new", cx); + click(&rig, "project-mode-new", cx); + assert!(preparation.discovered().unwrap().is_empty()); + + click(&rig, "project-image-Custom image", cx); + let requested = preparation.discovered().unwrap(); + assert_eq!(requested.len(), 1); + assert!(Arc::ptr_eq(&requested[0], &host)); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert!( + window + .try_find(format!("project-local-image-sha256:{}", "a".repeat(64))) + .is_some() + ); + }) + .unwrap(); + + click(&rig, "project-mode-existing", cx); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert!( + window + .try_find(format!("project-container-Docker-{:064x}", 1)) + .is_some() + ); + }) + .unwrap(); + assert_eq!(preparation.discovered().unwrap().len(), 1); +} + +#[gpui_kit::test] +fn hiding_local_images_cancels_discovery_and_reopening_the_source_retries(cx: &mut TestAppContext) { + let preparation = FakeProjectPreparation::default(); + let first = pending_discovery(&preparation); + let (rig, _, _) = Fixture::local(preparation.clone(), cx); + click(&rig, "project-new", cx); + click(&rig, "project-mode-new", cx); + click(&rig, "project-image-Custom image", cx); + cx.update_window(rig.window, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("project-local-images-loading").is_some()); + }) + .unwrap(); + assert!(!first.is_closed()); + + click(&rig, "project-image-source-registry", cx); + assert!(first.is_closed()); + assert_eq!(preparation.discovered().unwrap().len(), 1); + + let second = pending_discovery(&preparation); + click(&rig, "project-image-source-local", cx); + assert_eq!(preparation.discovered().unwrap().len(), 2); + assert!(!second.is_closed()); + click(&rig, "project-mode-direct", cx); + assert!(second.is_closed()); +} + +#[gpui_kit::test] +fn closing_a_wizard_drops_its_pending_inventory_request(cx: &mut TestAppContext) { + let preparation = FakeProjectPreparation::default(); + let pending = pending_discovery(&preparation); + let (rig, _, _) = Fixture::local(preparation.clone(), cx); + click(&rig, "project-new", cx); + assert!(preparation.discovered().unwrap().is_empty()); + click(&rig, "project-mode-existing", cx); + assert_eq!(preparation.discovered().unwrap().len(), 1); + assert!(!pending.is_closed()); + click(&rig, "project-cancel", cx); + assert!(pending.is_closed()); +} diff --git a/crates/projects/src/tests/library.rs b/crates/projects/src/tests/library.rs index ec8f1ef5..c8e8f928 100644 --- a/crates/projects/src/tests/library.rs +++ b/crates/projects/src/tests/library.rs @@ -268,3 +268,125 @@ fn renaming_saved_metadata_updates_the_open_tab_without_replacing_its_scope( ); }); } + +fn full_library(cx: &mut TestAppContext) -> Fixture { + let definitions = (u8::MIN..=u8::MAX) + .map(|value| { + let mut draft = definition(value).to_draft(); + draft.name = format!("Workspace {value:03}"); + ProjectDefinition::try_from(draft).unwrap() + }) + .collect(); + Fixture::loaded(definitions, cx) +} + +fn wheel_catalog(handle: AnyWindowHandle, repeats: usize, cx: &mut TestAppContext) { + use gpui_kit::{ScrollDelta, point, px}; + + for _ in 0..repeats { + cx.update_window(handle, |_, window, cx| { + window.scroll( + "projects-list", + ScrollDelta::Pixels(point(px(0.), px(-64.))), + cx, + ); + }) + .unwrap(); + } +} + +#[gpui_kit::test] +fn either_wheel_axis_moves_the_workspace_catalog_by_the_same_distance(cx: &mut TestAppContext) { + use gpui_kit::{ScrollDelta, point}; + + let fixture = full_library(cx); + cx.update_window(fixture.window, |_, window, cx| { + window.render_frame(cx); + let row = format!("project-row-{}", definition(3).id()); + let top = window.find(row.clone()).bounds().top(); + window.scroll("projects-list", ScrollDelta::Lines(point(0., -3.)), cx); + assert!(window.find(row.clone()).bounds().top() < top); + window.scroll("projects-list", ScrollDelta::Lines(point(3., 0.)), cx); + assert_eq!(window.find(row).bounds().top(), top); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn searching_from_a_scrolled_catalog_reveals_the_matching_workspace(cx: &mut TestAppContext) { + let fixture = full_library(cx); + cx.update_window(fixture.window, |_, window, cx| { + window.render_frame(cx); + assert!( + window + .try_find(format!("project-row-{}", definition(0).id())) + .is_some() + ); + }) + .unwrap(); + wheel_catalog(fixture.window, 30, cx); + cx.update_window(fixture.window, |_, window, cx| { + assert!( + window + .try_find(format!("project-row-{}", definition(0).id())) + .is_none() + ); + window.click("project-search", cx); + window.input("project-255", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(fixture.window, |_, window, cx| { + window.render_frame(cx); + let last = definition(255).id(); + assert_eq!( + window.find(format!("project-row-name-{last}")).label(), + Some("Workspace 255") + ); + window.hover(format!("project-row-{last}"), cx); + window.click(format!("project-edit-{last}"), cx); + window.render_frame(cx); + assert!(window.try_find("project-name").is_some()); + }) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "full catalog rendering performance fixture; run in isolation"] +fn measure_workspace_catalog_scroll_and_search(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + for _ in 0..3 { + let fixture = full_library(cx); + cx.update_window(fixture.window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + let start = Instant::now(); + wheel_catalog(fixture.window, 30, cx); + let scroll = start.elapsed(); + cx.update_window(fixture.window, |_, window, cx| { + window.click("project-search", cx) + }) + .unwrap(); + let start = Instant::now(); + for letter in "project-255".chars() { + cx.simulate_input(fixture.window, letter.encode_utf8(&mut [0; 4])); + cx.update_window(fixture.window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + let search = start.elapsed(); + cx.update_window(fixture.window, |_, window, _| { + assert_eq!( + window + .find(format!("project-row-name-{}", definition(255).id())) + .label(), + Some("Workspace 255") + ); + }) + .unwrap(); + writeln!( + std::io::stdout().lock(), + "256 workspaces, 30 wheel events: {scroll:.2?}, 11 search edits: {search:.2?}" + ) + .unwrap(); + } +} diff --git a/crates/projects/src/tests/settings.rs b/crates/projects/src/tests/settings.rs index 776e2972..91e18e6c 100644 --- a/crates/projects/src/tests/settings.rs +++ b/crates/projects/src/tests/settings.rs @@ -53,6 +53,10 @@ fn open_container(rig: &Fixture, attach: bool, cx: &mut TestAppContext) { }, cx, ); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(rig.window, |_, window, cx| { window.render_frame(cx); if attach { window.click(format!("project-container-Docker-{:064x}", 1), cx); diff --git a/crates/projects/src/tests/terminals.rs b/crates/projects/src/tests/terminals.rs index 30ccb16b..4c8c0927 100644 --- a/crates/projects/src/tests/terminals.rs +++ b/crates/projects/src/tests/terminals.rs @@ -532,7 +532,7 @@ fn a_local_workspace_without_a_terminal_can_create_another_local_workspace( }) .unwrap(); cx.run_until_parked(); - assert_eq!(preparation.discovered().unwrap().len(), 1); + assert!(preparation.discovered().unwrap().is_empty()); } #[gpui_kit::test] diff --git a/crates/projects/src/view.rs b/crates/projects/src/view.rs index 8532fc3e..ec476d20 100644 --- a/crates/projects/src/view.rs +++ b/crates/projects/src/view.rs @@ -41,11 +41,7 @@ impl ProjectPresentation { parent_item, } } - fn caption( - &self, - icon: Option>, - cx: &App, - ) -> impl IntoElement + use<> { + fn caption(&self, icon: Option, cx: &App) -> impl IntoElement + use<> { let theme = cx.theme(); h_flex() .gap_2() diff --git a/crates/session/src/fs.rs b/crates/session/src/fs.rs index 57c28692..ea754399 100644 --- a/crates/session/src/fs.rs +++ b/crates/session/src/fs.rs @@ -49,6 +49,12 @@ pub trait RemoteFs: Send + Sync + 'static { /// The entries of a directory, without `.` and `..`, in no particular order. fn read_dir(&self, path: &str) -> FsFuture>; + /// The entries for a recursive walk that skips symbolic links. Link flags + /// remain available, and kinds or sizes of link targets may be unresolved. + fn read_dir_for_walk(&self, path: &str) -> FsFuture> { + self.read_dir(path) + } + /// Metadata for the path itself, without following its final symlink. fn stat(&self, _path: &str) -> FsFuture> { Box::pin(async { Err(FsError::Unsupported("file metadata".into())) }) @@ -210,11 +216,14 @@ pub fn valid_publication_name(name: &str) -> bool { pub mod path { /// `parent` with `name` appended. pub fn join(parent: &str, name: &str) -> String { - if parent.ends_with('/') { - format!("{parent}{name}") - } else { - format!("{parent}/{name}") + let separator = !parent.ends_with('/'); + let mut path = String::with_capacity(parent.len() + name.len() + usize::from(separator)); + path.push_str(parent); + if separator { + path.push('/'); } + path.push_str(name); + path } /// The directory containing `path`; the root is its own parent. @@ -251,6 +260,9 @@ pub mod path { assert_eq!(join("/", "etc"), "/etc"); assert_eq!(join("/etc", "ssh"), "/etc/ssh"); assert_eq!(join("/etc/", "ssh"), "/etc/ssh"); + assert_eq!(join("", "資料"), "/資料"); + assert_eq!(join("/etc", ""), "/etc/"); + assert_eq!(join("/data//", "/child"), "/data///child"); } #[test] diff --git a/crates/session/src/local_fs.rs b/crates/session/src/local_fs.rs index 62ce942a..c9383e4a 100644 --- a/crates/session/src/local_fs.rs +++ b/crates/session/src/local_fs.rs @@ -4,7 +4,7 @@ mod error; mod policy; mod statistics; -use crate::{FileMetadata, FsCapabilities, fs::UploadMode}; +use crate::{EntryKind, FileMetadata, FsCapabilities, fs::UploadMode}; pub use error::{DurabilityWarning, LocalFsError, LocalResult, PublicationOutcome}; pub use policy::{ CancelFlag, DirectoryIdentity, ListingLimits, RemovalLimits, ScanPolicy, valid_native_name, @@ -31,6 +31,19 @@ pub trait LocalFs: Send + Sync + 'static { limits: ListingLimits, cancel: &CancelFlag, ) -> LocalResult; + /// Read the ordered native names and types needed for presentation or completion. + /// Both purposes respect the full enumeration bounds. Observed types can go + /// stale and confer no authority for subsequent filesystem operations. + fn browse_entries( + &self, + path: &Path, + limits: ListingLimits, + cancel: &CancelFlag, + purpose: BrowsePurpose, + ) -> LocalResult { + self.browse(path, limits, cancel) + .map(|listing| listing.project(purpose)) + } /// Acquire a strict capability: reject links in every component. Operations /// retain held native identity where the platform supports it. A path-based /// adapter must document and recheck its active-ancestor race limitation. @@ -107,6 +120,42 @@ pub struct LocalListing { pub directory: PathBuf, pub entries: Vec, } +impl LocalListing { + pub fn project(self, purpose: BrowsePurpose) -> LocalEntries { + LocalEntries { + directory: self.directory, + entries: self + .entries + .into_iter() + .filter(|entry| purpose == BrowsePurpose::Files || entry.completion_directory) + .map(|entry| LocalEntry { + name: entry.name, + kind: entry.metadata.kind, + is_symlink: entry.metadata.is_symlink, + }) + .collect(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BrowsePurpose { + Files, + /// Only directories and links resolving to directories. + DirectoryCompletion, +} +#[derive(Debug, PartialEq, Eq)] +pub struct LocalEntry { + pub name: OsString, + /// The entry's own kind, even in directory completion. + pub kind: EntryKind, + pub is_symlink: bool, +} +#[derive(Debug, PartialEq, Eq)] +pub struct LocalEntries { + pub directory: PathBuf, + pub entries: Vec, +} #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct RemovalOutcome { pub removed: usize, diff --git a/crates/settings-ui/Cargo.toml b/crates/settings-ui/Cargo.toml index 7fe083c8..a318326a 100644 --- a/crates/settings-ui/Cargo.toml +++ b/crates/settings-ui/Cargo.toml @@ -20,4 +20,5 @@ gpui-kit.workspace = true workspace = true [dev-dependencies] +nocterm-settings.workspace = true gpui-kit = { workspace = true, features = ["test-support"] } diff --git a/crates/settings-ui/src/lib.rs b/crates/settings-ui/src/lib.rs index 2eac1931..64b6f587 100644 --- a/crates/settings-ui/src/lib.rs +++ b/crates/settings-ui/src/lib.rs @@ -163,16 +163,24 @@ impl SettingsView { let _ = weak.update(cx, |_, cx| cx.notify()); }); }); + let selected_page = pages.default_index(); + let nav = PageNav::new(&pages); + let pages = PageBook::new(&pages, context, window, cx); + // Pages observe their own data. The host only follows shared diagnostics. let weak = cx.weak_entity(); let original_window = window.window_handle(); + let observed = installed.clone(); + let mut previous = installed.section_error_snapshot(cx); let settings = installed.observe(cx, move |cx| { - let _ = original_window.update(cx, |_, _, cx| { - let _ = weak.update(cx, |_, cx| cx.notify()); - }); + let current = observed.section_error_snapshot(cx); + let changed = !std::sync::Arc::ptr_eq(&previous, ¤t) && previous != current; + previous = current; + if changed { + let _ = original_window.update(cx, |_, _, cx| { + let _ = weak.update(cx, |_, cx| cx.notify()); + }); + } }); - let selected_page = pages.default_index(); - let nav = PageNav::new(&pages); - let pages = PageBook::new(&pages, context, window, cx); Self { installed, selected_page, @@ -253,32 +261,35 @@ impl Item for SettingsView { } impl Render for SettingsView { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let slot = &self.pages.slots[self.selected_page]; + let viewport = slot.spec.uses_viewport(); let back = self.nav.back_link(&self.pages, self.selected_page, cx); let content = self .pages .selected(self.selected_page) .map(|page| page.view().into_any_element()) .unwrap_or_else(|| div().into_any_element()); - let section_errors: Vec<_> = self.installed.section_errors(cx) - .iter() - .map(|error| { - format!( - "The [{}] section of settings.toml has an error and uses its defaults until it is fixed or changed here: {}", - error.key, error.error - ) - }) - .collect(); + let content = if viewport { + div().flex_1().min_h_0().child(content).into_any_element() + } else { + content + }; + let section_errors = self.installed.section_error_snapshot(cx); let content = v_flex() .w_full() .max_w(form::page_width(cx)) .px_8() .py_6() .children(back) - .children( - section_errors - .into_iter() - .map(|error| form::error_text(error, cx)), - ) + .children(section_errors.iter().map(|error| { + form::error_text( + format!( + "The [{}] section of settings.toml has an error and uses its defaults until it is fixed or changed here: {}", + error.key, error.error + ), + cx, + ) + })) .when_some(self.feedback.error(cx), |content, error| { content.child( div() @@ -288,19 +299,14 @@ impl Render for SettingsView { .child(form::error_text(error, cx)), ) }) - .child(content); + .child(content) + .when(viewport, |content| content.h_full().min_h_0()); h_flex() .id("settings-view") .test_support() .size_full() .min_h_0() - .bg(nocterm_ui::hsla( - nocterm_ui::TerminalStyle::with_settings( - self.installed.setting::(cx), - cx, - ) - .background, - )) + .bg(nocterm_ui::hsla(nocterm_ui::terminal_background(cx))) .track_focus(&self.focus) .child(self.nav.render(&self.pages, self.selected_page, cx)) .child( @@ -309,8 +315,10 @@ impl Render for SettingsView { .flex_1() .min_w_0() .h_full() - .overflow_y_scroll() - .track_scroll(&self.pages.slots[self.selected_page].scroll) + .when(viewport, |body| body.overflow_hidden()) + .when(!viewport, |body| { + body.overflow_y_scroll().track_scroll(&slot.scroll) + }) .child(content), ) } diff --git a/crates/settings-ui/src/tests.rs b/crates/settings-ui/src/tests.rs index 6440804e..efe08b63 100644 --- a/crates/settings-ui/src/tests.rs +++ b/crates/settings-ui/src/tests.rs @@ -763,3 +763,5 @@ fn opening_a_page_at_a_section_scrolls_the_page_to_it(cx: &mut TestAppContext) { }) .unwrap(); } + +mod diagnostics; diff --git a/crates/settings-ui/src/tests/diagnostics.rs b/crates/settings-ui/src/tests/diagnostics.rs new file mode 100644 index 00000000..ac5c7f39 --- /dev/null +++ b/crates/settings-ui/src/tests/diagnostics.rs @@ -0,0 +1,221 @@ +use super::*; +use gpui_kit::AnyWindowHandle; +use nocterm_settings::SettingsDocument; +use nocterm_ui::{AppearanceSettings, TerminalSettings}; +use std::io::Write as _; + +fn hosts( + count: usize, + malformed: bool, + cx: &mut TestAppContext, +) -> (SettingsHandle, Vec<(AnyWindowHandle, Entity)>) { + cx.update(|cx| { + gpui_kit::init(cx); + let document = if malformed { + SettingsDocument::from_table( + "[terminal]\nfont_szie = 1\n[foreign]\nvalue = 1\n" + .parse() + .unwrap(), + ) + } else { + SettingsDocument::default() + }; + let installed = nocterm_store::SettingsConfig::in_memory(document).install(cx); + nocterm_ui::init(nocterm_ui::DesignTokens::builtin(), installed.clone(), cx); + installed.register::(cx); + installed.register::(cx); + let views = (0..count) + .map(|_| { + let builtins = ["appearance", "terminal", "local-shell", "ssh", "ai"].map(|id| { + SettingsPageSpec::contextual(id, id, |_, _, cx| { + cx.new(|cx| EmptyPage { + focus: cx.focus_handle(), + }) + }) + }); + gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { + cx.new(|cx| { + SettingsView::with_pages( + test_catalog(builtins, Vec::new()), + installed.clone(), + window, + cx, + ) + }) + }) + .unwrap() + }) + .collect(); + (installed, views) + }) +} + +#[gpui_kit::test] +#[ignore = "manual release profile of settings host publication and rendering"] +fn measure_settings_host_publications(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_HOSTS") + .map_or(Ok(16), |count| count.parse::()) + .unwrap(); + let malformed = std::env::var("NOCTERM_PROFILE_MALFORMED").is_ok_and(|value| value == "1"); + let (settings, hosts) = hosts(count, malformed, cx); + cx.run_until_parked(); + let notifications = Rc::new(Cell::new(0usize)); + let _observations: Vec<_> = cx.update(|cx| { + hosts + .iter() + .map(|(_, host)| { + let count = notifications.clone(); + cx.observe(host, move |_, _| count.set(count.get() + 1)) + }) + .collect() + }); + for mode in ["publication", "frames"] { + for sample in 0..7 { + notifications.set(0); + let start = std::time::Instant::now(); + for i in 0..32 { + let receipt = cx.update(|cx| { + settings.update::(cx, move |value| { + value.detect_server_country = i % 2 == 0; + }) + }); + cx.foreground_executor().block_test(receipt).unwrap(); + if mode == "frames" { + for (window, _) in &hosts { + cx.update_window(*window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + } + } + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} hosts={count} malformed={malformed} notifications={} elapsed_ns={}", + notifications.get(), + start.elapsed().as_nanos() + ) + .unwrap(); + } + } + for (_, host) in hosts { + cx.update(|cx| assert_eq!(host.read(cx).selected_page_id(), "appearance")); + } +} + +#[gpui_kit::test] +fn the_host_refreshes_when_a_broken_section_is_repaired_not_for_unrelated_edits( + cx: &mut TestAppContext, +) { + let (settings, hosts) = hosts(1, true, cx); + let (_, host) = &hosts[0]; + cx.run_until_parked(); + let notifications = Rc::new(Cell::new(0)); + let count = notifications.clone(); + let _observation = cx.update(|cx| cx.observe(host, move |_, _| count.set(count.get() + 1))); + let publish = cx.update(|cx| { + settings.update::(cx, |settings| { + settings.detect_server_country = false; + }) + }); + cx.foreground_executor().block_test(publish).unwrap(); + assert_eq!(notifications.get(), 0); + cx.update(|cx| assert_eq!(settings.section_errors(cx).len(), 2)); + + let repair = cx.update(|cx| { + settings.update::(cx, |settings| { + settings.font_size = Some(18.); + }) + }); + cx.foreground_executor().block_test(repair).unwrap(); + cx.run_until_parked(); + assert_eq!(notifications.get(), 1); + cx.update(|cx| { + let remaining = settings.section_errors(cx); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].key, "foreign"); + assert_eq!(host.read(cx).selected_page_id(), "appearance"); + }); +} + +struct ObservingPage { + settings: SettingsHandle, + focus: FocusHandle, + _follow: Subscription, +} + +impl ObservingPage { + fn new(settings: SettingsHandle, cx: &mut Context) -> Self { + let weak = cx.weak_entity(); + let follow = settings.observe_section::(cx, move |cx| { + let _ = weak.update(cx, |_, cx| cx.notify()); + }); + Self { + settings, + focus: cx.focus_handle(), + _follow: follow, + } + } +} + +impl Focusable for ObservingPage { + fn focus_handle(&self, _: &App) -> FocusHandle { + self.focus.clone() + } +} + +impl Render for ObservingPage { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let text = if self + .settings + .setting::(cx) + .detect_server_country + { + "Detection enabled" + } else { + "Detection disabled" + }; + div() + .id("observed-setting") + .aria_label(text) + .test_support() + .child(text) + } +} +impl SettingsPage for ObservingPage {} + +#[gpui_kit::test] +fn an_independent_page_updates_without_invalidating_the_host(cx: &mut TestAppContext) { + let (settings, window, host) = cx.update(|cx| { + let fixture = host_fixture(cx); + let settings = fixture.installed; + let page = SettingsPageSpec::contextual("owner", "Owner", |context, _, cx| { + cx.new(|cx| ObservingPage::new(context.settings().clone(), cx)) + }); + let catalog = + SettingsCatalog::new(vec![SettingsPageRegistration::eager(page)], "owner").unwrap(); + let (window, host) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { + cx.new(|cx| SettingsView::with_pages(catalog, settings.clone(), window, cx)) + }) + .unwrap(); + (settings, window, host) + }); + cx.run_until_parked(); + let count = Rc::new(Cell::new(0)); + let observer = count.clone(); + let _observation = + cx.update(|cx| cx.observe(&host, move |_, _| observer.set(observer.get() + 1))); + let label = |cx: &mut TestAppContext| { + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + window.find("observed-setting").label().unwrap().to_owned() + }) + .unwrap() + }; + assert_eq!(label(cx), "Detection enabled"); + let changed = cx.update(|cx| { + settings.update::(cx, |settings| settings.detect_server_country = false) + }); + cx.foreground_executor().block_test(changed).unwrap(); + cx.run_until_parked(); + assert_eq!(count.get(), 0); + assert_eq!(label(cx), "Detection disabled"); +} diff --git a/crates/settings/src/document.rs b/crates/settings/src/document.rs index 958af3d3..fed6b416 100644 --- a/crates/settings/src/document.rs +++ b/crates/settings/src/document.rs @@ -4,7 +4,7 @@ use std::{ any::{Any, TypeId}, collections::{BTreeMap, HashMap}, fmt, - sync::{Mutex, OnceLock, PoisonError}, + sync::{Arc, Mutex, OnceLock, PoisonError}, }; use crate::SettingsSection; @@ -16,20 +16,27 @@ use crate::SettingsSection; /// by [`errors`](Self::errors) and is written back unchanged until the /// section is changed. Tables that no registered section claims are kept as /// they are. -#[derive(Default)] +#[derive(Clone, Default)] pub struct SettingsDocument { - raw: toml::Table, - sections: BTreeMap<&'static str, Box>, + // Original tables are immutable and shared by every snapshot of this load. + raw: Arc, + // Each registered value is immutable until its own section is edited. + sections: BTreeMap<&'static str, Arc>, /// Tables that could not be read and have not been changed since. broken: BTreeMap<&'static str, String>, + // Shared across value-only edits; registration and repairing a broken section + // detach it before it can describe a different document. + errors: Arc>>, } impl SettingsDocument { /// A document over the tables of a settings file. No section is read yet. pub fn from_table(raw: toml::Table) -> Self { Self { - raw, - ..Self::default() + raw: Arc::new(raw), + sections: BTreeMap::new(), + broken: BTreeMap::new(), + errors: Arc::default(), } } @@ -48,7 +55,8 @@ impl SettingsDocument { }), }; section.sanitize(); - self.sections.insert(S::KEY, Box::new(section)); + self.sections.insert(S::KEY, Arc::new(section)); + self.invalidate_errors(); } /// Whether section `S` was registered. @@ -77,34 +85,69 @@ impl SettingsDocument { } } + /// Retains an immutable typed value across document publications. + /// Registered values share their allocation until the section is replaced. + pub fn section_snapshot(&self) -> Arc { + match self.sections.get(S::KEY) { + Some(section) => { + let typed: Arc = section.clone(); + typed + .downcast::() + .unwrap_or_else(|_| panic!("two settings sections share the key `{}`", S::KEY)) + } + None => Arc::new(self.get::().clone()), + } + } + /// Changes section `S`, then sanitizes it. A broken table that is /// changed is rewritten, so its error is cleared. Returns whether the /// section changed. pub fn update(&mut self, edit: impl FnOnce(&mut S)) -> bool { self.register::(); - let section = self - .sections - .get_mut(S::KEY) - .and_then(|section| section.as_any_mut().downcast_mut::()) - .unwrap_or_else(|| panic!("two settings sections share the key `{}`", S::KEY)); - let before = section.clone(); - edit(section); - section.sanitize(); - let changed = *section != before; - if changed { - self.broken.remove(S::KEY); - } - changed + let mut value = self.get::().clone(); + edit(&mut value); + self.replace_registered(value) } /// Replaces section `S`. pub fn set(&mut self, value: S) -> bool { - self.update::(|section| *section = value) + self.register::(); + self.replace_registered(value) + } + + fn replace_registered(&mut self, mut value: S) -> bool { + value.sanitize(); + let changed = value != *self.get::(); + self.sections.insert(S::KEY, Arc::new(value)); + if changed && self.broken.remove(S::KEY).is_some() { + self.invalidate_errors(); + } + changed } /// Tables that could not be read and have not been changed since, /// followed by tables no registered section claims, by name. pub fn errors(&self) -> Vec { + self.error_snapshot().to_vec() + } + + /// The shared diagnostic projection, sorted by section name. Value-only edits retain + /// it; registering a section or repairing a broken table replaces it. + pub fn error_snapshot(&self) -> Arc<[SectionError]> { + self.errors + .get_or_init(|| self.collect_errors().into()) + .clone() + } + + fn invalidate_errors(&mut self) { + if let Some(cache) = Arc::get_mut(&mut self.errors) { + cache.take(); + } else { + self.errors = Arc::default(); + } + } + + fn collect_errors(&self) -> Vec { let mut errors: Vec<_> = self .broken .iter() @@ -114,21 +157,24 @@ impl SettingsDocument { }) .collect(); if !self.sections.is_empty() { - let known = self - .sections + let mut known = None; + for key in self + .raw .keys() - .copied() - .collect::>() - .join("`, `"); - errors.extend( - self.raw - .keys() - .filter(|key| !self.sections.contains_key(key.as_str())) - .map(|key| SectionError { - key: key.clone(), - error: format!("unknown section, expected one of `{known}`"), - }), - ); + .filter(|key| !self.sections.contains_key(key.as_str())) + { + let known = known.get_or_insert_with(|| { + self.sections + .keys() + .copied() + .collect::>() + .join("`, `") + }); + errors.push(SectionError { + key: key.clone(), + error: format!("unknown section, expected one of `{known}`"), + }); + } } errors.sort_by(|left, right| left.key.cmp(&right.key)); errors @@ -147,7 +193,7 @@ impl SettingsDocument { table.insert((*key).to_owned(), toml::Value::Table(values)); } } - for (key, value) in &self.raw { + for (key, value) in self.raw.iter() { if !self.owns(key) { table.insert(key.clone(), value.clone()); } @@ -161,20 +207,6 @@ impl SettingsDocument { } } -impl Clone for SettingsDocument { - fn clone(&self) -> Self { - Self { - raw: self.raw.clone(), - sections: self - .sections - .iter() - .map(|(key, section)| (*key, section.clone_box())) - .collect(), - broken: self.broken.clone(), - } - } -} - impl PartialEq for SettingsDocument { fn eq(&self, other: &Self) -> bool { self.broken == other.broken @@ -211,21 +243,15 @@ impl fmt::Display for SectionError { } } -/// A section behind a type-erased box. +/// An immutable section behind a type-erased shared value. trait AnySection: Any + Send + Sync + fmt::Debug { - fn clone_box(&self) -> Box; fn same(&self, other: &dyn AnySection) -> bool; /// The section's values that differ from its defaults. fn to_pruned_table(&self) -> toml::Table; fn as_any(&self) -> &dyn Any; - fn as_any_mut(&mut self) -> &mut dyn Any; } impl AnySection for S { - fn clone_box(&self) -> Box { - Box::new(self.clone()) - } - fn same(&self, other: &dyn AnySection) -> bool { other.as_any().downcast_ref::() == Some(self) } @@ -239,10 +265,6 @@ impl AnySection for S { fn as_any(&self) -> &dyn Any { self } - - fn as_any_mut(&mut self) -> &mut dyn Any { - self - } } fn to_table(section: &S) -> toml::Table { diff --git a/crates/settings/src/document/tests.rs b/crates/settings/src/document/tests.rs index e3df4ca0..115c6521 100644 --- a/crates/settings/src/document/tests.rs +++ b/crates/settings/src/document/tests.rs @@ -76,3 +76,120 @@ fn documents_compare_by_their_sections() { left.update::(|monitor| monitor.interval_secs = 3); assert_ne!(left, copy); } + +#[test] +fn copies_read_original_tables_and_edit_their_own_sections() { + let mut original = document("[terminal]\nfont_szie = 12\n[monitor]\ninterval_secs = 7\n"); + original.register::(); + let mut edited = original.clone(); + edited.update::(|terminal| terminal.copy_on_select = true); + edited.update::(|monitor| monitor.interval_secs += 1); + + assert_eq!(edited.get::().interval_secs, 8); + assert!(edited.get::().copy_on_select); + assert!(edited.errors().is_empty()); + original.register::(); + assert_eq!(original.get::().interval_secs, 7); + assert!(!original.get::().copy_on_select); + assert_eq!(original.errors()[0].key, "terminal"); + assert_eq!( + original.to_table()["terminal"]["font_szie"], + toml::Value::Integer(12) + ); +} + +#[test] +fn replacing_and_editing_a_registered_nested_section_keeps_retained_snapshots_independent() { + use crate::fixtures::{Agent, Agents}; + let mut original = + document("[ai.agents.one]\ncommand = '/one'\n[ai.agents.two]\ncommand = '/two'\n"); + original.register::(); + let mut first = original.clone(); + assert!(first.update::( + |agents| agents.agents.get_mut("one").unwrap().command = Some("/new".into()) + )); + let retained = first.clone(); + assert!(first.set(Agents { + agents: [("three".into(), Agent::default())].into() + })); + assert_eq!( + original.get::().agents["one"].command.as_deref(), + Some("/one") + ); + assert_eq!( + retained.get::().agents["one"].command.as_deref(), + Some("/new") + ); + assert_eq!( + retained.get::().agents["two"].command.as_deref(), + Some("/two") + ); + assert_eq!( + first.get::().agents.keys().collect::>(), + ["three"] + ); + assert!(!first.set(first.get::().clone())); +} + +#[test] +fn snapshot_equality_uses_section_values_even_for_nonreflexive_values() { + #[derive( + Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema, + )] + struct UnsanitizedFloat { + value: f32, + } + impl SettingsSection for UnsanitizedFloat { + const KEY: &'static str = "float"; + } + let mut document = SettingsDocument::default(); + document.set(UnsanitizedFloat { value: f32::NAN }); + let copy = document.clone(); + assert_ne!(document, copy); + assert!(document.get::().value.is_nan()); + assert!(copy.get::().value.is_nan()); +} + +#[test] +fn diagnostics_are_shared_across_value_edits_and_detached_on_repair() { + let mut original = document( + "[terminal]\nfont_szie = 1\n[monitor]\ninterval_secs = 7\n[foreign]\nflag = true\n", + ); + original.register::(); + original.register::(); + let initial = original.error_snapshot(); + assert_eq!( + initial + .iter() + .map(|error| error.key.as_str()) + .collect::>(), + ["foreign", "terminal"] + ); + + let mut edited = original.clone(); + edited.update::(|monitor| monitor.interval_secs = 8); + assert!(Arc::ptr_eq(&initial, &edited.error_snapshot())); + edited.update::(|terminal| terminal.font_size = Some(18.)); + let repaired = edited.error_snapshot(); + assert_eq!(repaired.len(), 1); + assert_eq!(repaired[0].key, "foreign"); + assert_eq!(edited.errors(), repaired.as_ref()); + assert_eq!(original.errors(), initial.as_ref()); + assert!(Arc::ptr_eq(&initial, &original.error_snapshot())); +} + +#[test] +fn registration_detaches_even_an_unread_diagnostic_projection() { + let raw = document("[monitor]\ninterval_secs = 7\n[foreign]\nflag = true\n"); + let mut first = raw.clone(); + let mut second = raw; + first.register::(); + second.register::(); + let first_errors = first.error_snapshot(); + let second_errors = second.error_snapshot(); + assert_eq!(first_errors.len(), 2); + assert_eq!(second_errors.len(), 1); + assert_eq!(second_errors[0].key, "foreign"); + assert!(first_errors[0].error.contains("`terminal`")); + assert!(second_errors[0].error.contains("`monitor`")); +} diff --git a/crates/settings/src/section.rs b/crates/settings/src/section.rs index 9410378b..1d8122b6 100644 --- a/crates/settings/src/section.rs +++ b/crates/settings/src/section.rs @@ -10,6 +10,8 @@ use serde::{Serialize, de::DeserializeOwned}; /// The crate that uses a section defines it; this crate only reads and /// writes the tables. Each section is read on its own, so a mistake in one /// leaves the others working. +/// A section is a value: published snapshots are immutable, and changes go +/// through the document’s edit operations, not through shared references. pub trait SettingsSection: Serialize + DeserializeOwned diff --git a/crates/settings/src/store/tests.rs b/crates/settings/src/store/tests.rs index 9a93ef9a..636d918d 100644 --- a/crates/settings/src/store/tests.rs +++ b/crates/settings/src/store/tests.rs @@ -21,6 +21,81 @@ fn missing_file_loads_the_defaults() { assert!(document.errors().is_empty()); } +#[test] +#[ignore = "settings performance fixture; run alone in both builds"] +fn measure_settings_snapshot_clones() { + use std::{fmt::Write as _, hint::black_box, io::Write as _, time::Instant}; + + let (_directory, file) = file(); + let value = "x".repeat(256); + for count in [16, 512, 4096] { + let mut text = String::from("[future]\n"); + for index in 0..count { + writeln!(text, "key{index} = \"{value}\"").unwrap(); + } + fs::write(file.path(), &text).unwrap(); + let snapshot = load(&file); + assert_eq!(snapshot.errors()[0].key, "future"); + + let start = Instant::now(); + for _ in 0..500 { + black_box(black_box(&snapshot).clone()); + } + writeln!( + std::io::stdout().lock(), + "{} bytes, 500 clones: {:.3} ms", + text.len(), + start.elapsed().as_secs_f64() * 1_000., + ) + .unwrap(); + } +} + +#[test] +#[ignore = "durable settings publication fixture; run alone in both builds"] +fn measure_settings_publication_with_unowned_tables() { + use std::{fmt::Write as _, io::Write as _, time::Instant}; + + let value = "x".repeat(256); + for (kind, has_values) in [("values", true), ("comments", false)] { + for count in [16, 512, 4096] { + let (_directory, file) = file(); + let mut unowned = String::from("[future]\n"); + for index in 0..count { + if has_values { + writeln!(unowned, "key{index} = \"{value}\"").unwrap(); + } else { + writeln!(unowned, "# {value}").unwrap(); + } + } + unowned.push_str("enabled = true\n"); + fs::write(file.path(), &unowned).unwrap(); + let mut document = load(&file); + let mut samples = Vec::with_capacity(12); + for step in 1_u8..=12 { + document.update::(|terminal| { + terminal.font_size = Some(14. + f32::from(step)) + }); + let start = Instant::now(); + file.save(&document).unwrap(); + samples.push(start.elapsed().as_micros()); + } + assert!( + fs::read_to_string(file.path()) + .unwrap() + .starts_with(&unowned) + ); + assert_eq!(load(&file).get::().font_size, Some(26.)); + writeln!( + std::io::stdout().lock(), + "{kind}, {} bytes, twelve durable saves in µs {samples:?}", + unowned.len(), + ) + .unwrap(); + } + } +} + #[test] fn only_changed_settings_are_written() { let (_directory, file) = file(); @@ -191,3 +266,57 @@ fn a_second_settings_owner_reports_conflict_instead_of_losing_a_parallel_edit() )); assert!(load(&first).get::().copy_on_select); } + +#[test] +#[ignore = "release profile of registered typed settings snapshots and unrelated edits"] +fn measure_registered_settings_snapshots() { + use std::{hint::black_box, io::Write as _, time::Instant}; + let count = std::env::var("NOCTERM_PROFILE_TYPED_ROWS") + .map_or(Ok(512), |value| value.parse::()) + .unwrap(); + assert!(count <= 4096); + let mut document = registered(SettingsDocument::default()); + document.set(Agents { + agents: (0..count) + .map(|index| { + ( + format!("agent-{index:04}"), + Agent { + command: Some(format!("/opt/profile/{}-{index}", "x".repeat(128))), + ..Default::default() + }, + ) + }) + .collect(), + }); + let mut clones = Vec::new(); + let mut edits = Vec::new(); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..128 { + black_box(black_box(&document).clone()); + } + clones.push(start.elapsed()); + let start = Instant::now(); + for step in 0..128 { + let mut candidate = black_box(&document).clone(); + assert!(candidate.update::(|monitor| monitor.interval_secs = 3 + step)); + assert_ne!(candidate, document); + black_box(candidate); + } + edits.push(start.elapsed()); + } + assert_eq!(document.get::().agents.len(), count); + assert_eq!(document.get::(), &Monitor::default()); + clones.sort_unstable(); + edits.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "typed_rows={count} clone_p50={:?} clone_max={:?} edits_p50={:?} edits_max={:?}", + clones[3], + clones[6], + edits[3], + edits[6] + ) + .unwrap(); +} diff --git a/crates/snippets-io/src/tests.rs b/crates/snippets-io/src/tests.rs index 12170878..20c20dc4 100644 --- a/crates/snippets-io/src/tests.rs +++ b/crates/snippets-io/src/tests.rs @@ -116,3 +116,79 @@ fn native_identity_is_generated_only_when_the_supplied_port_is_called() { assert_eq!(second.get_version_num(), 4); assert_ne!(first, second); } + +#[test] +fn native_load_preserves_long_unicode_commands_with_escapes_and_continuations() { + let prefix = "x".repeat(31); + let suffix = "🇯🇵 日本語 ".repeat(20); + let content = format!("{prefix}{suffix}\n\"quoted\" \\path {suffix}"); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("snippets.toml"); + let id = uuid::Uuid::from_u128(42); + let repository = FileSnippetRepository::new(path.clone()); + + for encoded in [ + format!(r#""{prefix}{suffix}\n\"quoted\" \\path {suffix}""#), + format!("\"\"\"\n{prefix}{suffix}\n\"quoted\" \\\\path \\\n {suffix}\"\"\""), + ] { + std::fs::write( + &path, + format!("[[snippets]]\nid = \"{id}\"\nname = \"Deploy\"\ncontent = {encoded}\n"), + ) + .unwrap(); + + let loaded = repository.load().unwrap().unwrap(); + loaded.validate().unwrap(); + assert_eq!(loaded.snippets[0].id, id); + assert_eq!(loaded.snippets[0].content, content); + } +} + +#[test] +#[ignore = "manual persisted-library performance measurement"] +fn persisted_library_load_cost_for_short_and_large_profiles() { + use std::hint::black_box; + use std::io::Write as _; + use std::time::Instant; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("snippets.toml"); + let repository = FileSnippetRepository::new(path.clone()); + for (count, body) in [ + (25, "printf 'Deploy stage 日本語'\n".repeat(4)), + (1_500, "printf 'Deploy stage 日本語'\n".repeat(125)), + (1_500, "printf '\\n%s' \"''' Deploy 日本語\"\n".repeat(125)), + (20_000, String::from("echo ok")), + ] { + let expected = Library { + snippets: (0..count) + .map(|index| Snippet { + name: format!("Deploy stage {index}"), + content: body.clone(), + ..Snippet::new(uuid::Uuid::from_u128(index as u128 + 1)) + }) + .collect(), + }; + repository.save(&expected).unwrap(); + assert_eq!(repository.load().unwrap(), Some(expected)); + let bytes = std::fs::metadata(&path).unwrap().len(); + let mut durations: Vec<_> = (0..41) + .map(|_| { + let start = Instant::now(); + let loaded = repository.load().unwrap().unwrap(); + loaded.validate().unwrap(); + assert_eq!(black_box(loaded.snippets.len()), count); + drop(loaded); + start.elapsed() + }) + .collect(); + durations.sort_unstable(); + writeln!( + std::io::stderr().lock(), + "snippets={count} bytes={bytes} p50={:?} p95={:?}", + durations[20], + durations[38] + ) + .unwrap(); + } +} diff --git a/crates/snippets/Cargo.toml b/crates/snippets/Cargo.toml index 78635cd1..338d4d95 100644 --- a/crates/snippets/Cargo.toml +++ b/crates/snippets/Cargo.toml @@ -13,6 +13,7 @@ layer = "domain" test-support = [] [dependencies] +memchr.workspace = true serde.workspace = true thiserror.workspace = true uuid.workspace = true diff --git a/crates/snippets/src/lib.rs b/crates/snippets/src/lib.rs index 8f7a0961..3024f9fc 100644 --- a/crates/snippets/src/lib.rs +++ b/crates/snippets/src/lib.rs @@ -6,6 +6,7 @@ //! Invariants: identity is supplied by the caller; stale expected records cannot //! overwrite or delete a newer saved record; validation performs no I/O. mod repository; +mod search; pub use repository::{SnippetIds, SnippetRepository, SnippetStorageError, StorageOperation}; #[cfg(feature = "test-support")] pub mod test_support; @@ -225,21 +226,7 @@ impl Library { group: Option<&str>, query: &str, ) -> (Vec, Vec) { - let query = query.trim().to_lowercase(); - let (current, other): (Vec<_>, Vec<_>) = self - .snippets - .iter() - .enumerate() - .filter(|(_, snippet)| { - query.is_empty() - || snippet.name.to_lowercase().contains(&query) - || snippet.description.to_lowercase().contains(&query) - || snippet.content.to_lowercase().contains(&query) - }) - .partition(|(_, snippet)| snippet.matches(profile, group)); - let indices = - |records: Vec<(usize, &Snippet)>| records.into_iter().map(|(index, _)| index).collect(); - (indices(current), indices(other)) + search::partition(self, profile, group, query) } } #[cfg(test)] diff --git a/crates/snippets/src/search.rs b/crates/snippets/src/search.rs new file mode 100644 index 00000000..7b3d5e71 --- /dev/null +++ b/crates/snippets/src/search.rs @@ -0,0 +1,57 @@ +//! Literal matching with whole-string Unicode lowercase for non-ASCII fields. +use memchr::{memchr2, memmem::Finder}; + +use crate::Library; + +pub(super) fn partition( + library: &Library, + profile: Option<&str>, + group: Option<&str>, + query: &str, +) -> (Vec, Vec) { + let query = query.trim().to_lowercase(); + let finder = (!query.is_empty() && query.is_ascii()).then(|| Finder::new(query.as_bytes())); + let mut folded = String::new(); + let (mut current, mut other) = (Vec::new(), Vec::new()); + for (index, snippet) in library.snippets.iter().enumerate() { + if query.is_empty() + || [&snippet.name, &snippet.description, &snippet.content] + .into_iter() + .any(|text| contains(text, &query, finder.as_ref(), &mut folded)) + { + if snippet.matches(profile, group) { + current.push(index); + } else { + other.push(index); + } + } + } + (current, other) +} + +fn contains(text: &str, query: &str, finder: Option<&Finder<'_>>, folded: &mut String) -> bool { + if !text.is_ascii() { + return text.to_lowercase().contains(query); + } + let Some(finder) = finder else { return false }; + let needle = query.as_bytes(); + let text_bytes = text.as_bytes(); + let Some(prefix) = text_bytes.get(..needle.len()) else { + return false; + }; + let has = |byte: u8| memchr2(byte, byte.to_ascii_uppercase(), text_bytes).is_some(); + if needle.len() == 1 { + return has(needle[0]); + } + if prefix.eq_ignore_ascii_case(needle) { + return true; + } + // On longer fields a missing edge byte can rule out the copy and search. + if text.len() > 128 && (!has(needle[0]) || !has(needle[needle.len() - 1])) { + return false; + } + folded.clear(); + folded.push_str(text); + folded.make_ascii_lowercase(); + finder.find(folded.as_bytes()).is_some() +} diff --git a/crates/snippets/src/tests.rs b/crates/snippets/src/tests.rs index 2a197fe1..338f28d7 100644 --- a/crates/snippets/src/tests.rs +++ b/crates/snippets/src/tests.rs @@ -65,6 +65,92 @@ fn partition_filters_and_orders_context_before_other_snippets() { assert!(library.partition(None, None, "absent").1.is_empty()); } +#[test] +fn literal_search_preserves_unicode_case_and_context_order() { + let library = Library { + snippets: vec![ + Snippet { + name: "Run [check]".into(), + description: "ΟΣ".into(), + content: "x".repeat(130) + " MarkerUNIQUE", + ..Snippet::new(Uuid::from_u128(1)) + }, + Snippet { + name: "Linux Service".into(), + description: "ος".into(), + content: "Kelvin and İSTANBUL".into(), + profiles: vec!["selected".into()], + ..Snippet::new(Uuid::from_u128(2)) + }, + Snippet { + name: "Other".into(), + content: "ΑΟΣΑ".into(), + groups: vec!["Ops".into()], + ..Snippet::new(Uuid::from_u128(3)) + }, + ], + }; + for (query, current, other) in [ + (" ", vec![1, 2], vec![0]), + ("[CHECK]", vec![], vec![0]), + ("markerunique", vec![], vec![0]), + ("linux service", vec![1], vec![]), + ("ος", vec![1], vec![0]), + ("οσ", vec![2], vec![]), + ("KELVIN", vec![1], vec![]), + ("i\u{307}stanbul", vec![1], vec![]), + ("[", vec![], vec![0]), + ("markeruniquE!", vec![], vec![]), + ] { + assert_eq!( + library.partition_indices(Some("selected"), Some("Ops"), query), + (current, other), + "{query}" + ); + } +} + +#[test] +#[ignore = "manual release benchmark for a large snippet library"] +fn search_large_library_benchmark() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let mut library = Library::default(); + let body = "Linux Service CLI and diagnostic text. ".repeat(104); + for index in 0..1500 { + let mut record = Snippet::new(Uuid::from_u128(index + 1)); + record.name = format!("Audit snippet {index:04}"); + record.description = "Read-only diagnostics fixture".into(); + record.content = body.clone(); + if index == 1499 { + record.content.push_str(" MarkerUnique Café ΣΟΣ"); + } + library.snippets.push(record); + } + for (query, count) in [ + ("Audit", 1500), + ("linux service", 1500), + ("markerunique", 1), + ("Linux Service CLI and diagnostic text unknown text", 0), + ("é σος", 1), + ] { + let mut samples = [0.; 7]; + for sample in &mut samples { + let start = Instant::now(); + for _ in 0..50 { + let (_, matches) = black_box(library.partition_indices(None, None, query)); + assert_eq!(matches.len(), count); + if count == 1 { + assert_eq!(matches[0], 1499); + } + } + *sample = start.elapsed().as_secs_f64() * 1000. / 50.; + } + samples.sort_by(f64::total_cmp); + writeln!(std::io::stderr(), "{query}: {:.3} ms/query", samples[3]).unwrap(); + } +} + #[test] fn supplied_identities_and_validation_errors_remain_distinct() { let mut one = Snippet::new(uuid::Uuid::from_u128(1)); diff --git a/crates/ssh/src/host_keys.rs b/crates/ssh/src/host_keys.rs index db3ec4a9..df12cb68 100644 --- a/crates/ssh/src/host_keys.rs +++ b/crates/ssh/src/host_keys.rs @@ -6,7 +6,10 @@ use russh::keys::{ ssh_key::known_hosts::{Entry, HostPatterns, Marker}, }; use sha1::Sha1; -use std::{path::PathBuf, sync::Mutex}; +use std::{ + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; mod replacement; static MUTATIONS: Mutex<()> = Mutex::new(()); @@ -45,23 +48,50 @@ impl std::fmt::Display for TrustError { } } -#[derive(Clone, Debug)] +#[derive(Debug)] pub(crate) struct HostKeys { writable: PathBuf, - records: Vec, + records: HostKeyRecords, snapshots: Vec, read_only: Vec, } + +/// Read-only verification records captured for one link. Only these are needed +/// by the protocol handler, whose lifetime extends beyond the initial login. #[derive(Clone, Debug)] +pub(crate) struct HostKeyRecords(Arc>); + +#[derive(Debug)] struct Recorded { - file: PathBuf, + file: Arc, line: usize, entry: Entry, } impl HostKeys { pub(crate) fn load(writable: PathBuf, read_only: Vec) -> Result { + Self::read(writable, read_only, None) + } + + pub(crate) fn load_link( + writable: PathBuf, + read_only: Vec, + host: &str, + port: u16, + ) -> Result { + let label = host_label(host, port); + // Validate the entire store before keeping the records for this link. + Self::read(writable, read_only, Some(&label)) + } + + fn read( + writable: PathBuf, + read_only: Vec, + label: Option<&str>, + ) -> Result { + let mut count = 0; let mut records = Vec::new(); let mut snapshots = Vec::new(); + let mut normalized = String::new(); for file in std::iter::once(&writable).chain(read_only.iter()) { let bytes = match crate::file::read(file, MAX_STORE) { Ok(bytes) => bytes, @@ -77,20 +107,18 @@ impl HostKeys { }); } }; - snapshots.push( - replacement::Snapshot::capture(file, bytes.to_vec()).map_err(|error| { - TrustError { - file: file.clone(), - line: None, - reason: error.to_string(), - } - })?, - ); - let text = std::str::from_utf8(&bytes).map_err(|error| TrustError { + let snapshot = + replacement::Snapshot::capture(file, bytes).map_err(|error| TrustError { + file: file.clone(), + line: None, + reason: error.to_string(), + })?; + let text = std::str::from_utf8(snapshot.bytes()).map_err(|error| TrustError { file: file.clone(), line: None, reason: error.to_string(), })?; + let record_file = Arc::::from(file.as_path()); for (index, line) in text.lines().enumerate() { let number = index + 1; let invalid = |reason: &str| TrustError { @@ -105,61 +133,37 @@ impl HostKeys { if line.is_empty() || line.starts_with('#') { continue; } - if records.len() == MAX_RECORDS { + if count == MAX_RECORDS { return Err(invalid("too many host records")); } - // The upstream entry parser expects ordinary single spaces. OpenSSH - // also accepts tabs and repeated whitespace between these fields. - let fields: Vec<_> = line.split_whitespace().collect(); - let key_start = usize::from(fields[0].starts_with('@')); - if fields.len() < key_start + 3 { - return Err(invalid("invalid host record")); + let entry = parse_record(line, &mut normalized) + .ok_or_else(|| invalid("invalid host record"))?; + count += 1; + if label.is_some_and(|label| !host_matches(entry.host_patterns(), label)) { + continue; } - let normalized = fields[..key_start + 3].join(" "); - let entry: Entry = normalized - .parse() - .map_err(|_| invalid("invalid host record"))?; records.push(Recorded { - file: file.clone(), + file: Arc::clone(&record_file), line: number, entry, }); } + snapshots.push(snapshot); } + // The handler retains these records for the link's entire lifetime. + records.shrink_to_fit(); Ok(Self { writable, - records, + records: HostKeyRecords(Arc::new(records)), snapshots, read_only, }) } + pub(crate) fn records(&self) -> HostKeyRecords { + self.records.clone() + } pub(crate) fn check(&self, host: &str, port: u16, key: &PublicKey) -> Verdict { - let recorded: Vec<_> = self.matching(host, port).collect(); - if let Some(record) = recorded.iter().find(|record| { - record.entry.marker() == Some(&Marker::Revoked) - && record.entry.public_key().key_data() == key.key_data() - }) { - return Verdict::Revoked { - known_hosts: record.file.clone(), - line: record.line, - }; - } - if recorded.iter().any(|record| { - record.entry.marker().is_none() - && record.entry.public_key().key_data() == key.key_data() - }) { - return Verdict::Known; - } - recorded - .into_iter() - .find(|record| { - record.entry.marker().is_none() - && same_kind(&record.entry.public_key().algorithm(), &key.algorithm()) - }) - .map_or(Verdict::Unknown, |record| Verdict::Changed { - known_hosts: record.file.clone(), - line: record.line, - }) + self.records.check(host, port, key) } /// The OpenSSH texts of the plain keys recorded for the host, oldest record first. pub(crate) fn public_keys(&self, host: &str, port: u16) -> Vec { @@ -198,16 +202,70 @@ impl HostKeys { .map_err(|error| RememberError::Write(error.to_string())) } fn matching<'a>(&'a self, host: &str, port: u16) -> impl Iterator { - let label = if port == 22 { - host.to_owned() - } else { - format!("[{host}]:{port}") - }; - self.records + self.records.matching(host, port) + } +} + +impl HostKeyRecords { + pub(crate) fn check(&self, host: &str, port: u16, key: &PublicKey) -> Verdict { + let recorded: Vec<_> = self.matching(host, port).collect(); + if let Some(record) = recorded.iter().find(|record| { + record.entry.marker() == Some(&Marker::Revoked) + && record.entry.public_key().key_data() == key.key_data() + }) { + return Verdict::Revoked { + known_hosts: record.file.to_path_buf(), + line: record.line, + }; + } + if recorded.iter().any(|record| { + record.entry.marker().is_none() + && record.entry.public_key().key_data() == key.key_data() + }) { + return Verdict::Known; + } + recorded + .into_iter() + .find(|record| { + record.entry.marker().is_none() + && same_kind(&record.entry.public_key().algorithm(), &key.algorithm()) + }) + .map_or(Verdict::Unknown, |record| Verdict::Changed { + known_hosts: record.file.to_path_buf(), + line: record.line, + }) + } + fn matching<'a>(&'a self, host: &str, port: u16) -> impl Iterator { + let label = host_label(host, port); + self.0 .iter() .filter(move |record| host_matches(record.entry.host_patterns(), &label)) } } +/// The upstream parser expects single spaces between the required fields. +/// OpenSSH also accepts tabs and repeated whitespace and ignores the comment. +fn parse_record(line: &str, normalized: &mut String) -> Option { + let mut fields = line.split_whitespace(); + let first = fields.next()?; + let remaining = if first.starts_with('@') { 3 } else { 2 }; + normalized.clear(); + normalized.push_str(first); + for _ in 0..remaining { + normalized.push(' '); + normalized.push_str(fields.next()?); + } + normalized.parse().ok() +} + +/// The host as known-hosts files spell it. +pub(crate) fn host_label(host: &str, port: u16) -> String { + if port == nocterm_session::DEFAULT_PORT { + host.to_owned() + } else { + format!("[{host}]:{port}") + } +} + fn host_matches(patterns: &HostPatterns, host: &str) -> bool { match patterns { HostPatterns::HashedName { salt, hash } => Hmac::::new_from_slice(salt) @@ -278,6 +336,15 @@ mod tests { ) .unwrap() } + fn load_link(dir: &Path, host: &str, port: u16) -> HostKeys { + HostKeys::load_link( + dir.join("known_hosts"), + vec![dir.join("system_known_hosts")], + host, + port, + ) + .unwrap() + } #[test] fn concurrent_unknown_confirmations_do_not_append_a_changed_key() { let dir = tempfile::tempdir().unwrap(); @@ -358,7 +425,7 @@ mod tests { let system = dir.path().join("system_known_hosts"); fs::write(&system, format!("@revoked *.com,!safe.com {KEY_A}\n")).unwrap(); assert_eq!( - load(dir.path()).check("example.com", 22, &key(KEY_A)), + load_link(dir.path(), "example.com", 22).check("example.com", 22, &key(KEY_A)), Verdict::Revoked { known_hosts: system, line: 1 @@ -375,20 +442,20 @@ mod tests { fs::write( dir.path().join("known_hosts"), format!( - "*.example.com,alias,!bad.example.com\t{KEY_A}\n[*.example.com]:2222 {KEY_B}\n" + "*.example.com,alias,!bad.example.com\t{KEY_A} comment with extra fields\n[*.example.com]:2222\u{2003} {KEY_B}\n" ), ) .unwrap(); - let hosts = load(dir.path()); for host in ["a.example.com", "A.EXAMPLE.COM", "alias"] { + let hosts = load_link(dir.path(), host, 22); assert_eq!(hosts.check(host, 22, &key(KEY_A)), Verdict::Known); } assert_eq!( - hosts.check("bad.example.com", 22, &key(KEY_A)), + load_link(dir.path(), "bad.example.com", 22).check("bad.example.com", 22, &key(KEY_A)), Verdict::Unknown ); assert_eq!( - hosts.check("a.example.com", 2222, &key(KEY_B)), + load_link(dir.path(), "a.example.com", 2222).check("a.example.com", 2222, &key(KEY_B)), Verdict::Known ); assert!(glob(b"ab?*d", b"abczzzD")); @@ -403,16 +470,16 @@ mod tests { format!("|1|YWFhYWFhYWFhYWFhYWFhYWFhYWE=|lMugv7ii5/R8LZHkQxdKDhSoGRY= {KEY_A}\n"); fs::write(dir.path().join("known_hosts"), &hashed).unwrap(); assert_eq!( - load(dir.path()).check("example.com", 22, &key(KEY_A)), + load_link(dir.path(), "example.com", 22).check("example.com", 22, &key(KEY_A)), Verdict::Known ); assert_eq!( - load(dir.path()).check("other.com", 22, &key(KEY_A)), + load_link(dir.path(), "other.com", 22).check("other.com", 22, &key(KEY_A)), Verdict::Unknown ); fs::write(dir.path().join("known_hosts"), format!("@revoked {hashed}")).unwrap(); assert!(matches!( - load(dir.path()).check("example.com", 22, &key(KEY_A)), + load_link(dir.path(), "example.com", 22).check("example.com", 22, &key(KEY_A)), Verdict::Revoked { .. } )); fs::write( @@ -421,7 +488,7 @@ mod tests { ) .unwrap(); assert_eq!( - load(dir.path()).check("example.com", 2222, &key(KEY_A)), + load_link(dir.path(), "example.com", 2222).check("example.com", 2222, &key(KEY_A)), Verdict::Known ); assert_eq!( @@ -439,6 +506,25 @@ mod tests { ); } #[test] + fn unrelated_records_count_towards_the_limit_across_files() { + let dir = tempfile::tempdir().unwrap(); + let writable = dir.path().join("known_hosts"); + let system = dir.path().join("system_known_hosts"); + let other = format!("unrelated.example {KEY_A}\n"); + fs::write(&writable, other.repeat(MAX_RECORDS)).unwrap(); + assert_eq!( + load_link(dir.path(), "my.example", 22).check("my.example", 22, &key(KEY_A)), + Verdict::Unknown + ); + fs::write(&system, format!("# comment\nmy.example {KEY_A}\n")).unwrap(); + let error = + HostKeys::load_link(writable, vec![system.clone()], "my.example", 22).unwrap_err(); + assert!(error.to_string().contains(&format!( + "{} (line 2): too many host records", + system.display() + ))); + } + #[test] fn damaged_nonregular_or_oversized_stores_fail_closed() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("known_hosts"); diff --git a/crates/ssh/src/host_keys/replacement.rs b/crates/ssh/src/host_keys/replacement.rs index 42ff42d6..70feeb35 100644 --- a/crates/ssh/src/host_keys/replacement.rs +++ b/crates/ssh/src/host_keys/replacement.rs @@ -2,11 +2,12 @@ use super::*; use russh::keys::HashAlg; use std::{fs, io, path::Path}; +use zeroize::Zeroizing; -#[derive(Clone, Debug)] +#[derive(Debug)] pub(super) struct Snapshot { path: PathBuf, - bytes: Option>, + bytes: Option>>, stamp: Option, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -36,17 +37,23 @@ impl Snapshot { stamp: None, } } - pub(super) fn capture(path: &Path, bytes: Vec) -> io::Result { + pub(super) fn capture(path: &Path, bytes: Zeroizing>) -> io::Result { Ok(Self { path: path.to_owned(), bytes: Some(bytes), stamp: Some(Stamp::new(&fs::metadata(path)?)), }) } + pub(super) fn bytes(&self) -> &[u8] { + self.bytes + .as_ref() + .expect("snapshot captured from present file") + .as_slice() + } fn unchanged(&self) -> bool { match crate::file::read(&self.path, MAX_STORE) { Ok(bytes) => { - self.bytes.as_deref() == Some(bytes.as_slice()) + self.bytes.as_ref().map(|data| data.as_slice()) == Some(bytes.as_slice()) && fs::metadata(&self.path) .is_ok_and(|metadata| Some(Stamp::new(&metadata)) == self.stamp) } @@ -121,7 +128,10 @@ impl HostKeys { if records.is_empty() { return Some("There are no conflicting records to replace.".into()); } - if records.iter().any(|record| record.file != self.writable) { + if records + .iter() + .any(|record| record.file.as_ref() != self.writable) + { return Some("A conflicting key is in a read-only SSH trust file. Update that file yourself after verifying the new fingerprint, or connect once.".into()); } if records diff --git a/crates/ssh/src/login.rs b/crates/ssh/src/login.rs index 8cee5a66..9db449ff 100644 --- a/crates/ssh/src/login.rs +++ b/crates/ssh/src/login.rs @@ -22,7 +22,7 @@ use tokio::io::{AsyncRead, AsyncWrite}; use crate::{ SshConfig, - host_keys::{HostKeys, RememberError, Verdict, same_kind}, + host_keys::{HostKeyRecords, HostKeys, RememberError, Verdict, host_label, same_kind}, }; /// Unanswered keepalives after which the connection counts as lost. @@ -83,7 +83,7 @@ pub(crate) fn take_disconnect(observed: &Arc>) -> Option /// The protocol callbacks of one connection. pub(crate) struct Client { - host_keys: Option, + host_keys: HostKeyRecords, host: String, port: u16, observed: Arc>, @@ -106,10 +106,7 @@ impl client::Handler for Client { return Ok(false); }; - let Some(host_keys) = &self.host_keys else { - return Ok(false); - }; - let verdict = host_keys.check(&self.host, self.port, key); + let verdict = self.host_keys.check(&self.host, self.port, key); let acceptable = !matches!(verdict, Verdict::Revoked { .. }); lock(&self.observed).host_key = Some((key.clone(), verdict)); Ok(acceptable) @@ -133,10 +130,15 @@ impl client::Handler for Client { /// Loads the trust records afresh. Every login reloads them, because accepting a /// key writes the file but not the snapshot of a login that has already loaded it. -pub(crate) async fn load_host_keys(config: &SshConfig) -> Result { +pub(crate) async fn load_host_keys( + config: &SshConfig, + target: &Target, +) -> Result { let writable = config.known_hosts.clone(); let read_only = config.read_only_known_hosts.clone(); - tokio::task::spawn_blocking(move || HostKeys::load(writable, read_only)) + let host = target.host.clone(); + let port = target.port; + tokio::task::spawn_blocking(move || HostKeys::load_link(writable, read_only, &host, port)) .await .map_err(|error| SessionError::Other(format!("cannot load host trust records: {error}")))? .map_err(|error| SessionError::Other(error.to_string())) @@ -158,6 +160,7 @@ where // Ask for a kind of key that is already on record, if there is one. let known = host_keys.known_algorithms(host, *port); let mut preferred = Preferred::default(); + prefer_accelerated_cipher(&mut preferred, has_accelerated_aes_gcm()); let mut algorithms = preferred.key.to_vec(); algorithms.sort_by_key(|algorithm| !known.iter().any(|known| same_kind(known, algorithm))); preferred.key = Cow::Owned(algorithms); @@ -169,7 +172,7 @@ where ..client::Config::default() }; let client = Client { - host_keys: Some(host_keys.clone()), + host_keys: host_keys.records(), host: host.clone(), port: *port, observed: observed.clone(), @@ -183,11 +186,37 @@ where }) } +fn has_accelerated_aes_gcm() -> bool { + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + std::arch::is_x86_feature_detected!("aes") + && std::arch::is_x86_feature_detected!("pclmulqdq") + } + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + { + false + } +} + +fn prefer_accelerated_cipher(preferred: &mut Preferred, accelerated: bool) { + // Move an already-supported AEAD to the front. Preserve the relative order + // of every other cipher offered to the server. + if accelerated + && let Some(index) = preferred + .cipher + .iter() + .position(|name| *name == russh::cipher::AES_256_GCM) + && index != 0 + { + preferred.cipher.to_mut()[..=index].rotate_right(1); + } +} + /// Makes sure the user trusts the host before anything secret is sent to it. pub(crate) async fn verify_host( handle: &Handle, login: &Login<'_>, - host_keys: &HostKeys, + host_keys: HostKeys, driver: &SessionDriver, observed: &Arc>, ) -> Result<(), SessionError> { @@ -217,7 +246,7 @@ pub(crate) async fn verify_host( reply, }, _ => Prompt::UnknownHostKey { - host: host_label(target), + host: host_label(&target.host, target.port), algorithm: key.algorithm().as_str().to_owned(), fingerprint: key.fingerprint(HashAlg::Sha256).to_string(), hop: login.hop(), @@ -241,10 +270,9 @@ pub(crate) async fn verify_host( Ok(()) } HostKeyDecision::AcceptAndRemember if changed => { - let records = host_keys.clone(); let host = host.clone(); let port = target.port; - tokio::task::spawn_blocking(move || records.replace(&host, port, &key)) + tokio::task::spawn_blocking(move || host_keys.replace(&host, port, &key)) .await .map_err(|error| { SessionError::Other(format!("Could not save the new host key: {error}")) @@ -272,16 +300,30 @@ fn revoked(host: &str, file: &Path, line: usize) -> SessionError { )) } -/// The host as known-hosts files spell it. -fn host_label(target: &Target) -> String { - if target.port == nocterm_session::DEFAULT_PORT { - target.host.clone() - } else { - format!("[{}]:{}", target.host, target.port) - } -} - fn lock(observed: &Arc>) -> MutexGuard<'_, Observed> { // The state is plain data, valid even if a holder panicked. observed.lock().unwrap_or_else(PoisonError::into_inner) } + +#[cfg(test)] +mod tests { + use super::*; + use russh::cipher; + + #[test] + fn hardware_acceleration_reorders_only_aes_gcm() { + let mut preferred = Preferred::default(); + let initial = preferred.cipher.clone(); + prefer_accelerated_cipher(&mut preferred, false); + assert_eq!(preferred.cipher, initial); + prefer_accelerated_cipher(&mut preferred, true); + let (first, other_ciphers) = preferred.cipher.split_first().unwrap(); + assert_eq!(*first, cipher::AES_256_GCM); + assert!( + other_ciphers.iter().copied().eq(initial + .iter() + .copied() + .filter(|name| *name != cipher::AES_256_GCM)) + ); + } +} diff --git a/crates/ssh/src/route.rs b/crates/ssh/src/route.rs index 5b40e75b..8f909b02 100644 --- a/crates/ssh/src/route.rs +++ b/crates/ssh/src/route.rs @@ -163,7 +163,9 @@ async fn link( Some(hop) => at_hop(hop.index, &hop.target, error), None => error, }; - let host_keys = login::load_host_keys(config).await.map_err(own)?; + let host_keys = login::load_host_keys(config, login.target()) + .await + .map_err(own)?; driver .emit(Event::Connecting(ConnectStage::Connecting { hop: login.hop().map(|hop| hop.index), @@ -175,7 +177,7 @@ async fn link( Fault::Own(error) => own(error), Fault::Forward(error) => forward_fault(route, error), })?; - login::verify_host(&handle, login, &host_keys, driver, observed) + login::verify_host(&handle, login, host_keys, driver, observed) .await .map_err(own)?; diff --git a/crates/ssh/src/sftp.rs b/crates/ssh/src/sftp.rs index a2b7a14f..a0de16df 100644 --- a/crates/ssh/src/sftp.rs +++ b/crates/ssh/src/sftp.rs @@ -8,7 +8,7 @@ use nocterm_session::{ use russh::client::Handle; use russh_sftp::{ client::{RawSftpSession, error::Error as SftpError}, - protocol::{FileAttributes, FileType, OpenFlags, Packet, StatusCode}, + protocol::{FileAttributes, FileType, OpenFlags, Packet, SftpHandle, StatusCode}, }; use std::{collections::HashMap, sync::Arc}; use tokio::{ @@ -30,7 +30,7 @@ const MAX_ENTRY_NAME: usize = 4096; pub(crate) enum FsRequest { Home(Answer), - ReadDir(String, Answer>), + ReadDir(String, ListingPurpose, Answer>), Stat(String, Answer>), Metadata(String, Answer), Rename(String, String, Answer<()>), @@ -49,6 +49,10 @@ pub(crate) enum FsRequest { ReadBatch(Uuid, usize, usize, Answer>>), CloseDownload(Uuid, Answer<()>), } +pub(crate) enum ListingPurpose { + Browse, + Walk, +} enum Cleanup { Upload(Uuid), Download(Uuid), @@ -83,6 +87,11 @@ pub(crate) fn channel(source: nocterm_session::ConnectionSource) -> (SshFs, FsRe ) } impl SshFs { + fn read_directory(&self, path: &str, purpose: ListingPurpose) -> FsFuture> { + let path = path.to_owned(); + self.request(move |reply| FsRequest::ReadDir(path, purpose, reply)) + } + fn request( &self, request: impl FnOnce(Answer) -> FsRequest + Send + 'static, @@ -133,8 +142,10 @@ impl RemoteFs for SshFs { self.request(FsRequest::Home) } fn read_dir(&self, path: &str) -> FsFuture> { - let path = path.to_owned(); - self.request(move |reply| FsRequest::ReadDir(path, reply)) + self.read_directory(path, ListingPurpose::Browse) + } + fn read_dir_for_walk(&self, path: &str) -> FsFuture> { + self.read_directory(path, ListingPurpose::Walk) } fn stat(&self, path: &str) -> FsFuture> { let path = path.to_owned(); @@ -155,7 +166,7 @@ impl RemoteFs for SshFs { } struct Download { source: String, - handle: Option, + handle: Option, offset: u64, eof: bool, } @@ -164,7 +175,7 @@ type Downloads = Arc>>>>; struct Upload { temporary: String, destination: String, - handle: Option, + handle: Option, offset: u64, mode: UploadMode, failed: bool, diff --git a/crates/ssh/src/sftp/actor.rs b/crates/ssh/src/sftp/actor.rs index caa4eb48..1d8ba86e 100644 --- a/crates/ssh/src/sftp/actor.rs +++ b/crates/ssh/src/sftp/actor.rs @@ -117,12 +117,12 @@ pub(super) async fn dispatch( Err(e) => Err(e), }); } - FsRequest::ReadDir(path, mut reply) => { + FsRequest::ReadDir(path, purpose, mut reply) => { if reply.is_canceled() { return; } let result = match result { - Ok(s) => read_dir(&s, &path, &mut reply).await, + Ok(s) => read_dir(&s, &path, purpose, &mut reply).await, Err(e) => Err(e), }; let _ = reply.send(result); diff --git a/crates/ssh/src/sftp/listing.rs b/crates/ssh/src/sftp/listing.rs index 868096ad..95f23382 100644 --- a/crates/ssh/src/sftp/listing.rs +++ b/crates/ssh/src/sftp/listing.rs @@ -1,5 +1,12 @@ //! Directory listing within entry and byte budgets. use super::*; +use futures::stream::{self, FuturesUnordered}; +use std::iter::repeat_with; + +const INITIAL_PAGE_WINDOW: usize = 2; +const PAGE_WINDOW: usize = 8; +const LINK_WINDOW: usize = 8; + #[derive(Default)] pub(super) struct ListingBudget { pub(super) entries: usize, @@ -38,6 +45,7 @@ impl ListingBudget { pub(super) async fn read_dir( sftp: &Sftp, dir: &str, + purpose: ListingPurpose, reply: &mut Answer>, ) -> Result, FsError> { let handle = sftp @@ -47,7 +55,13 @@ pub(super) async fn read_dir( .map_err(|e| fs_error(e, dir))? .handle; let result = { - let listing = collect_directory(sftp, dir, &handle); + let listing = async { + let mut entries = collect_directory(sftp, dir, &handle).await?; + if matches!(purpose, ListingPurpose::Browse) { + enrich_links(sftp, dir, &mut entries).await; + } + Ok(entries) + }; tokio::pin!(listing); tokio::select! { biased; @@ -60,36 +74,28 @@ pub(super) async fn read_dir( result } -async fn collect_directory(sftp: &Sftp, dir: &str, handle: &str) -> Result, FsError> { +async fn collect_directory( + sftp: &Sftp, + dir: &str, + handle: &SftpHandle, +) -> Result, FsError> { + let requests = || repeat_with(|| sftp.raw.readdir(handle)); + // One page and EOF can share a round trip on a small directory. Only + // widen the window after both initial replies contained pages. Keep + // replies in request order even when the peer sends them out of order. + let initial = stream::iter(requests().take(INITIAL_PAGE_WINDOW)).buffered(INITIAL_PAGE_WINDOW); + let mut pages = initial.chain(stream::iter(requests()).buffered(PAGE_WINDOW)); let mut entries = Vec::new(); let mut budget = ListingBudget::default(); - loop { - match sftp.raw.readdir(handle).await { + while let Some(page) = pages.next().await { + match page { Ok(names) => { budget.page()?; - for name in &names.files { + for name in names.files { budget.entry(&name.filename)?; - } - // Following a listing link is optional metadata enrichment. - // Pipeline a small window rather than one network roundtrip - // per link; buffered retains the server's listing order. - let enriched = names - .files - .into_iter() - .filter(|name| name.filename != "." && name.filename != "..") - .map(|name| async move { - let mut item = entry(name.filename, &name.attrs); - if item.is_symlink - && let Ok(target) = sftp.raw.stat(path::join(dir, &item.name)).await - { - item.kind = entry_kind(target.attrs.file_type()); - item.size = target.attrs.size; - } - item - }); - let mut enriched = futures::stream::iter(enriched).buffered(8); - while let Some(item) = enriched.next().await { - entries.push(item); + if name.filename != "." && name.filename != ".." { + entries.push(entry(name.filename, &name.attrs)); + } } } Err(SftpError::Status(status)) if status.status_code == StatusCode::Eof => break, @@ -98,3 +104,21 @@ async fn collect_directory(sftp: &Sftp, dir: &str, handle: &str) -> Result u32 { u32::from_be_bytes(packet[1..5].try_into().unwrap()) } -#[test] -fn hostile_directory_listing_is_bounded_and_names_cannot_escape_parent() { - let mut budget = ListingBudget::default(); - assert!(budget.entry("ordinary:file\\name").is_ok()); - for name in ["", "../outside", "/outside", "a\0b"] { - assert!(ListingBudget::default().entry(name).is_err()); - } - assert!( - ListingBudget::default() - .entry(&"a".repeat(MAX_ENTRY_NAME + 1)) - .is_err() - ); - let mut count = ListingBudget { - entries: MAX_DIRECTORY_ENTRIES, - ..Default::default() - }; - assert!(count.entry("next").is_err()); - let mut bytes = ListingBudget { - bytes: MAX_DIRECTORY_BYTES, - ..Default::default() - }; - assert!(bytes.entry("next").is_err()); - let mut pages = ListingBudget { - pages: MAX_DIRECTORY_ENTRIES, - ..Default::default() - }; - assert!(pages.page().is_err()); -} #[tokio::test] async fn upload_admission_never_opens_beyond_the_handle_limit() { let mut registry = HashMap::new(); @@ -75,129 +49,6 @@ async fn upload_admission_never_opens_beyond_the_handle_limit() { assert_eq!(registry.len(), MAX_OPEN_UPLOADS); } -async fn directory_open(peer: &mut DuplexStream) { - assert_eq!(packet(peer).await[0], 1); - send(peer, &[2, 0, 0, 0, 3]).await; - let open = packet(peer).await; - assert_eq!(open[0], 11); - let mut handle = vec![102]; - handle.extend(request_id(&open).to_be_bytes()); - handle.extend(4u32.to_be_bytes()); - handle.extend(b"list"); - send(peer, &handle).await; -} -async fn directory_names(peer: &mut DuplexStream, id: u32, names: &[String], mode: u32) { - let mut bytes = vec![104]; - bytes.extend(id.to_be_bytes()); - bytes.extend((names.len() as u32).to_be_bytes()); - for name in names { - bytes.extend((name.len() as u32).to_be_bytes()); - bytes.extend(name.as_bytes()); - bytes.extend(0u32.to_be_bytes()); - bytes.extend(4u32.to_be_bytes()); - bytes.extend(mode.to_be_bytes()); - } - send(peer, &bytes).await; -} -#[tokio::test] -async fn rejected_directory_page_closes_its_remote_handle() { - for name in ["../outside".into(), "x".repeat(MAX_ENTRY_NAME + 1)] { - let (client, mut peer) = tokio::io::duplex(8192); - let raw = RawSftpSession::new(client); - let fake = tokio::spawn(async move { - directory_open(&mut peer).await; - let read = packet(&mut peer).await; - assert_eq!(read[0], 12); - directory_names(&mut peer, request_id(&read), &[name], 0o100600).await; - let close = packet(&mut peer).await; - assert_eq!(close[0], 4); - status(&mut peer, request_id(&close), StatusCode::Ok).await; - }); - timeout(Duration::from_secs(3), raw.init()) - .await - .unwrap() - .unwrap(); - let sftp = Sftp { - raw, - atomic_replace: false, - }; - assert!( - timeout(Duration::from_secs(3), listing(&sftp, "/root")) - .await - .unwrap() - .is_err() - ); - timeout(Duration::from_secs(3), fake) - .await - .unwrap() - .unwrap(); - } -} -#[tokio::test] -async fn listing_pipelines_eight_link_stats_and_preserves_server_order() { - let (client, mut peer) = tokio::io::duplex(8192); - let raw = RawSftpSession::new(client); - let names: Vec<_> = (0..16).map(|n| format!("link-{n}")).collect(); - let expected = names.clone(); - let fake = tokio::spawn(async move { - directory_open(&mut peer).await; - let read = packet(&mut peer).await; - assert_eq!(read[0], 12); - directory_names(&mut peer, request_id(&read), &names, 0o120777).await; - for _ in 0..2 { - let mut ids = Vec::new(); - // No response until the complete window arrives: sequential - // enrichment would deadlock here and fail the timeout. - for _ in 0..8 { - let stat = packet(&mut peer).await; - assert_eq!(stat[0], 17); - ids.push(request_id(&stat)); - } - for id in ids.into_iter().rev() { - let mut attrs = vec![105]; - attrs.extend(id.to_be_bytes()); - attrs.extend(4u32.to_be_bytes()); - attrs.extend(0o040755u32.to_be_bytes()); - send(&mut peer, &attrs).await; - } - } - let read = packet(&mut peer).await; - assert_eq!(read[0], 12); - status(&mut peer, request_id(&read), StatusCode::Eof).await; - let close = packet(&mut peer).await; - assert_eq!(close[0], 4); - status(&mut peer, request_id(&close), StatusCode::Ok).await; - }); - timeout(Duration::from_secs(3), raw.init()) - .await - .unwrap() - .unwrap(); - let sftp = Sftp { - raw, - atomic_replace: false, - }; - let entries = timeout(Duration::from_secs(3), listing(&sftp, "/root")) - .await - .unwrap() - .unwrap(); - assert_eq!( - entries - .iter() - .map(|entry| entry.name.clone()) - .collect::>(), - expected - ); - assert!( - entries - .iter() - .all(|entry| entry.kind == EntryKind::Directory && entry.is_symlink) - ); - timeout(Duration::from_secs(3), fake) - .await - .unwrap() - .unwrap(); -} - #[tokio::test] async fn download_closes_handle_when_fstat_rejects_object_changed_after_lstat() { let (client, mut peer) = tokio::io::duplex(1024); @@ -217,15 +68,18 @@ async fn download_closes_handle_when_fstat_rejects_object_changed_after_lstat() let mut handle = vec![102]; handle.extend(request_id(&open).to_be_bytes()); handle.extend(6u32.to_be_bytes()); - handle.extend(b"handle"); + let opaque_handle = b"\xff\x00file"; + handle.extend(opaque_handle); send(&mut peer, &handle).await; let fstat = packet(&mut peer).await; assert_eq!(fstat[0], 8); + assert_eq!(&fstat[9..], opaque_handle); attrs[1..5].copy_from_slice(&request_id(&fstat).to_be_bytes()); attrs[9..13].copy_from_slice(&0o040755u32.to_be_bytes()); send(&mut peer, &attrs).await; let close = packet(&mut peer).await; assert_eq!(close[0], 4); + assert_eq!(&close[9..], opaque_handle); status(&mut peer, request_id(&close), StatusCode::Ok).await; }); timeout(Duration::from_secs(3), raw.init()) @@ -687,39 +541,3 @@ async fn read_batch_refuses_oversized_windows_without_touching_the_connection() )); } } - -async fn listing(sftp: &Sftp, path: &str) -> Result, FsError> { - let (mut reply, _result) = oneshot::channel(); - read_dir(sftp, path, &mut reply).await -} - -#[tokio::test] -async fn cancelling_a_listing_closes_its_handle_without_waiting_for_a_page() { - let (client, mut peer) = tokio::io::duplex(8192); - let raw = RawSftpSession::new(client); - let (reading, started) = tokio::sync::oneshot::channel(); - let fake = tokio::spawn(async move { - directory_open(&mut peer).await; - let read = packet(&mut peer).await; - assert_eq!(read[0], 12); - reading.send(()).unwrap(); - let close = packet(&mut peer).await; - assert_eq!(close[0], 4); - status(&mut peer, request_id(&close), StatusCode::Ok).await; - }); - raw.init().await.unwrap(); - let sftp = Sftp { - raw, - atomic_replace: false, - }; - let (mut reply, result) = oneshot::channel(); - let (listing, ()) = tokio::join!(read_dir(&sftp, "/root", &mut reply), async { - started.await.unwrap(); - drop(result); - }); - assert!(listing.is_err()); - timeout(Duration::from_secs(3), fake) - .await - .unwrap() - .unwrap(); -} diff --git a/crates/ssh/src/sftp/tests/directory.rs b/crates/ssh/src/sftp/tests/directory.rs new file mode 100644 index 00000000..d8c14b19 --- /dev/null +++ b/crates/ssh/src/sftp/tests/directory.rs @@ -0,0 +1,285 @@ +use super::*; + +#[test] +fn hostile_directory_listing_is_bounded_and_names_cannot_escape_parent() { + let mut budget = ListingBudget::default(); + assert!(budget.entry("ordinary:file\\name").is_ok()); + for name in ["", "../outside", "/outside", "a\0b"] { + assert!(ListingBudget::default().entry(name).is_err()); + } + assert!( + ListingBudget::default() + .entry(&"a".repeat(MAX_ENTRY_NAME + 1)) + .is_err() + ); + let mut count = ListingBudget { + entries: MAX_DIRECTORY_ENTRIES, + ..Default::default() + }; + assert!(count.entry("next").is_err()); + let mut bytes = ListingBudget { + bytes: MAX_DIRECTORY_BYTES, + ..Default::default() + }; + assert!(bytes.entry("next").is_err()); + let mut pages = ListingBudget { + pages: MAX_DIRECTORY_ENTRIES, + ..Default::default() + }; + assert!(pages.page().is_err()); +} + +async fn directory_open(peer: &mut DuplexStream) { + assert_eq!(packet(peer).await[0], 1); + send(peer, &[2, 0, 0, 0, 3]).await; + let open = packet(peer).await; + assert_eq!(open[0], 11); + let mut handle = vec![102]; + handle.extend(request_id(&open).to_be_bytes()); + handle.extend(4u32.to_be_bytes()); + handle.extend(b"list"); + send(peer, &handle).await; +} +async fn directory_names(peer: &mut DuplexStream, id: u32, names: &[String], mode: u32) { + let mut bytes = vec![104]; + bytes.extend(id.to_be_bytes()); + bytes.extend((names.len() as u32).to_be_bytes()); + for name in names { + bytes.extend((name.len() as u32).to_be_bytes()); + bytes.extend(name.as_bytes()); + bytes.extend(0u32.to_be_bytes()); + bytes.extend(4u32.to_be_bytes()); + bytes.extend(mode.to_be_bytes()); + } + send(peer, &bytes).await; +} + +async fn page_request(peer: &mut DuplexStream) -> u32 { + let read = packet(peer).await; + assert_eq!(read[0], 12); + request_id(&read) +} + +async fn directory_close(peer: &mut DuplexStream) { + let close = packet(peer).await; + assert_eq!(close[0], 4); + status(peer, request_id(&close), StatusCode::Ok).await; +} + +#[tokio::test] +async fn rejected_directory_page_closes_its_remote_handle() { + for name in ["../outside".into(), "x".repeat(MAX_ENTRY_NAME + 1)] { + let (client, mut peer) = tokio::io::duplex(8192); + let raw = RawSftpSession::new(client); + let fake = tokio::spawn(async move { + directory_open(&mut peer).await; + let first = page_request(&mut peer).await; + let _unanswered = page_request(&mut peer).await; + directory_names(&mut peer, first, &[name], 0o100600).await; + directory_close(&mut peer).await; + }); + timeout(Duration::from_secs(3), raw.init()) + .await + .unwrap() + .unwrap(); + let sftp = Sftp { + raw, + atomic_replace: false, + }; + assert!( + timeout(Duration::from_secs(3), listing(&sftp, "/root")) + .await + .unwrap() + .is_err() + ); + timeout(Duration::from_secs(3), fake) + .await + .unwrap() + .unwrap(); + } +} +#[tokio::test] +async fn listing_pipelines_eight_link_stats_and_preserves_server_order() { + let (client, mut peer) = tokio::io::duplex(8192); + let raw = RawSftpSession::new(client); + let names: Vec<_> = (0..16).map(|n| format!("link-{n}")).collect(); + let expected = names.clone(); + let fake = tokio::spawn(async move { + directory_open(&mut peer).await; + let first = page_request(&mut peer).await; + let last = page_request(&mut peer).await; + directory_names(&mut peer, first, &names, 0o120777).await; + status(&mut peer, last, StatusCode::Eof).await; + for _ in 0..2 { + let mut ids = Vec::new(); + // No response until the complete window arrives: sequential + // enrichment would deadlock here and fail the timeout. + for _ in 0..8 { + let stat = packet(&mut peer).await; + assert_eq!(stat[0], 17); + ids.push(request_id(&stat)); + } + for id in ids.into_iter().rev() { + let mut attrs = vec![105]; + attrs.extend(id.to_be_bytes()); + attrs.extend(4u32.to_be_bytes()); + attrs.extend(0o040755u32.to_be_bytes()); + send(&mut peer, &attrs).await; + } + } + directory_close(&mut peer).await; + }); + timeout(Duration::from_secs(3), raw.init()) + .await + .unwrap() + .unwrap(); + let sftp = Sftp { + raw, + atomic_replace: false, + }; + let entries = timeout(Duration::from_secs(3), listing(&sftp, "/root")) + .await + .unwrap() + .unwrap(); + assert_eq!( + entries + .iter() + .map(|entry| entry.name.clone()) + .collect::>(), + expected + ); + assert!( + entries + .iter() + .all(|entry| entry.kind == EntryKind::Directory && entry.is_symlink) + ); + timeout(Duration::from_secs(3), fake) + .await + .unwrap() + .unwrap(); +} + +async fn listing(sftp: &Sftp, path: &str) -> Result, FsError> { + let (mut reply, _result) = oneshot::channel(); + read_dir(sftp, path, ListingPurpose::Browse, &mut reply).await +} + +#[tokio::test] +async fn walking_a_listing_keeps_link_flags_and_closes_without_target_requests() { + let (client, mut peer) = tokio::io::duplex(8192); + let raw = RawSftpSession::new(client); + let fake = tokio::spawn(async move { + directory_open(&mut peer).await; + let first = page_request(&mut peer).await; + let last = page_request(&mut peer).await; + directory_names(&mut peer, first, &["link".into()], 0o120777).await; + status(&mut peer, last, StatusCode::Eof).await; + directory_close(&mut peer).await; + }); + timeout(Duration::from_secs(3), raw.init()) + .await + .unwrap() + .unwrap(); + let sftp = Sftp { + raw, + atomic_replace: false, + }; + let (mut reply, _result) = oneshot::channel(); + let entries = timeout( + Duration::from_secs(3), + read_dir(&sftp, "/root", ListingPurpose::Walk, &mut reply), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].name, "link"); + assert!(entries[0].is_symlink); + timeout(Duration::from_secs(3), fake) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn cancelling_a_listing_closes_its_handle_without_waiting_for_a_page() { + let (client, mut peer) = tokio::io::duplex(8192); + let raw = RawSftpSession::new(client); + let (reading, started) = tokio::sync::oneshot::channel(); + let fake = tokio::spawn(async move { + directory_open(&mut peer).await; + let _first = page_request(&mut peer).await; + let _second = page_request(&mut peer).await; + reading.send(()).unwrap(); + directory_close(&mut peer).await; + }); + raw.init().await.unwrap(); + let sftp = Sftp { + raw, + atomic_replace: false, + }; + let (mut reply, result) = oneshot::channel(); + let (listing, ()) = tokio::join!( + read_dir(&sftp, "/root", ListingPurpose::Browse, &mut reply), + async { + started.await.unwrap(); + drop(result); + } + ); + assert!(listing.is_err()); + timeout(Duration::from_secs(3), fake) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn directory_pages_stay_in_request_order_and_only_the_prefix_before_eof_is_used() { + let (client, mut peer) = tokio::io::duplex(8192); + let raw = RawSftpSession::new(client); + let fake = tokio::spawn(async move { + directory_open(&mut peer).await; + let first = page_request(&mut peer).await; + let second = page_request(&mut peer).await; + directory_names(&mut peer, second, &["b".into()], 0o100600).await; + directory_names(&mut peer, first, &["a".into()], 0o100600).await; + + let mut window = Vec::new(); + for _ in 0..8 { + window.push(page_request(&mut peer).await); + } + status(&mut peer, window[2], StatusCode::PermissionDenied).await; + status(&mut peer, window[1], StatusCode::Eof).await; + directory_names(&mut peer, window[0], &["c".into()], 0o100600).await; + + // Consuming the last page can refill one slot. The rest can remain + // unanswered, including at the time we acknowledge the close. + let next = packet(&mut peer).await; + if next[0] == 12 { + directory_close(&mut peer).await; + } else { + assert_eq!(next[0], 4); + status(&mut peer, request_id(&next), StatusCode::Ok).await; + } + }); + timeout(Duration::from_secs(3), raw.init()) + .await + .unwrap() + .unwrap(); + let sftp = Sftp { + raw, + atomic_replace: false, + }; + let result = timeout(Duration::from_secs(3), listing(&sftp, "/root")) + .await + .unwrap() + .unwrap(); + assert_eq!( + result + .into_iter() + .map(|entry| entry.name) + .collect::>(), + ["a", "b", "c"] + ); + fake.await.unwrap(); +} diff --git a/crates/ssh/tests/cases/host_keys.rs b/crates/ssh/tests/cases/host_keys.rs index 188847bc..d12977aa 100644 --- a/crates/ssh/tests/cases/host_keys.rs +++ b/crates/ssh/tests/cases/host_keys.rs @@ -42,6 +42,87 @@ async fn a_new_host_is_confirmed_once_and_remembered() { assert_eq!(closed(&again, no_prompts).await, CloseReason::ClosedByUser); } +#[tokio::test] +async fn a_known_connection_survives_server_rekey() { + let Some(sshd) = Sshd::start_with("RekeyLimit 32K") else { + return; + }; + let key = fs::read_to_string(sshd.root().join("host_key.pub")).unwrap(); + fs::write( + sshd.root().join("known_hosts"), + format!("{} {key}", sshd.host_label()), + ) + .unwrap(); + let transport = sshd.transport("plain"); + let session = transport.open(sshd.request()); + connect(&session, no_prompts).await; + + let path = sshd.root().join("payload"); + let expected = vec![b'x'; 256 * 1024]; + fs::write(&path, &expected).unwrap(); + let remote = session.fs().unwrap(); + let mut download = remote.download(path.to_str().unwrap()).await.unwrap(); + let mut actual = Vec::new(); + loop { + let chunks = download.read_batch(32 * 1024, 8).await.unwrap(); + if chunks.is_empty() { + break; + } + actual.extend(chunks.into_iter().flatten()); + } + download.close().await.unwrap(); + assert_eq!(actual, expected); + assert!(session.input("printf 'after-%s\\n' rekey\r")); + output_containing(&session, "after-rekey").await; + session.close(); + assert_eq!( + closed(&session, no_prompts).await, + CloseReason::ClosedByUser + ); + let log = fs::read_to_string(sshd.root().join("sshd.log")).unwrap(); + assert!(log.matches("SSH2_MSG_NEWKEYS sent").count() >= 2, "{log}"); +} + +#[tokio::test] +async fn negotiated_ciphers_keep_single_cipher_servers_compatible() { + const AES: &str = "aes256-gcm@openssh.com"; + const CHACHA: &str = "chacha20-poly1305@openssh.com"; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + let accelerated = std::arch::is_x86_feature_detected!("aes") + && std::arch::is_x86_feature_detected!("pclmulqdq"); + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + let accelerated = false; + + for (offered, expected) in [ + ( + format!("{CHACHA},{AES}"), + if accelerated { AES } else { CHACHA }, + ), + (AES.to_owned(), AES), + (CHACHA.to_owned(), CHACHA), + ] { + let Some(sshd) = Sshd::start_with(&format!("Ciphers {offered}")) else { + return; + }; + let transport = sshd.transport("plain"); + let session = transport.open(sshd.request()); + connect(&session, accept).await; + session.close(); + assert_eq!( + closed(&session, no_prompts).await, + CloseReason::ClosedByUser + ); + + let log = fs::read_to_string(sshd.root().join("sshd.log")).unwrap(); + for direction in ["client->server", "server->client"] { + assert!( + log.contains(&format!("kex: {direction} cipher: {expected}")), + "{log}" + ); + } + } +} + #[tokio::test] async fn revoked_host_key_cannot_be_accepted_or_reach_authentication() { let Some(sshd) = Sshd::start() else { return }; @@ -66,17 +147,19 @@ async fn revoked_host_key_cannot_be_accepted_or_reach_authentication() { #[tokio::test] async fn malformed_host_trust_store_never_becomes_an_unknown_host_prompt() { let Some(sshd) = Sshd::start() else { return }; - fs::write( - sshd.root().join("known_hosts"), - format!("{} ssh-ed25519 invalid-key", sshd.host_label()), - ) - .unwrap(); let transport = sshd.transport("plain"); - let session = transport.open(sshd.request()); - let reason = closed(&session, no_prompts).await; - assert!( - matches!(reason, CloseReason::Failed(SessionError::Other(message)) if message.contains("cannot verify host keys")) - ); + for host in [sshd.host_label(), "unrelated.example".into()] { + fs::write( + sshd.root().join("known_hosts"), + format!("# comment\n{host} ssh-ed25519 invalid-key"), + ) + .unwrap(); + let session = transport.open(sshd.request()); + let reason = closed(&session, no_prompts).await; + assert!( + matches!(reason, CloseReason::Failed(SessionError::Other(message)) if message.contains("(line 2): invalid host record")) + ); + } } #[tokio::test] diff --git a/crates/ssh/tests/cases/performance.rs b/crates/ssh/tests/cases/performance.rs new file mode 100644 index 00000000..515928a2 --- /dev/null +++ b/crates/ssh/tests/cases/performance.rs @@ -0,0 +1,409 @@ +use super::*; +use nocterm_session::fs::{RemoteDownload, RemoteFs, UploadMode}; +use std::{ + io::{self, Write as _}, + time::Instant, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}, + net::{TcpListener, TcpStream}, + sync::mpsc, + time::sleep_until, +}; + +/// The two directions each delay the byte stream without imposing a delay +/// after every individual read. Pending data is bounded by the channel. +async fn delayed_copy( + mut input: impl AsyncRead + Unpin, + mut output: impl AsyncWrite + Unpin, + delay: Duration, +) -> io::Result<()> { + let (send, mut receive) = mpsc::channel::<(tokio::time::Instant, Vec)>(32); + let read = async { + loop { + let mut bytes = vec![0; 32 * 1024]; + let count = input.read(&mut bytes).await?; + if count == 0 { + return Ok(()); + } + bytes.truncate(count); + if send + .send((tokio::time::Instant::now() + delay, bytes)) + .await + .is_err() + { + return Ok(()); + } + } + }; + let write = async { + while let Some((deadline, bytes)) = receive.recv().await { + if !delay.is_zero() { + sleep_until(deadline).await; + } + output.write_all(&bytes).await?; + } + output.shutdown().await + }; + let ((), ()) = tokio::try_join!(read, write)?; + Ok(()) +} + +async fn connect_proxy( + sshd: &Sshd, + delay: Duration, +) -> (ConnectRequest, tokio::task::JoinHandle<()>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut request = sshd.request(); + request.target.port = listener.local_addr().unwrap().port(); + let port = sshd.port(); + let proxy = tokio::spawn(async move { + let (mut client, _) = listener.accept().await.unwrap(); + let mut server = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + client.set_nodelay(true).unwrap(); + server.set_nodelay(true).unwrap(); + let (client_read, client_write) = client.split(); + let (server_read, server_write) = server.split(); + let _ = tokio::try_join!( + delayed_copy(client_read, server_write, delay), + delayed_copy(server_read, client_write, delay) + ); + }); + (request, proxy) +} + +async fn read_exactly(mut reader: Box, expected: &[u8], batch: usize) { + let mut offset = 0; + loop { + let chunks = reader.read_batch(32 * 1024, batch).await.unwrap(); + if chunks.is_empty() { + break; + } + for chunk in chunks { + let next = offset + chunk.len(); + assert_eq!(chunk, expected[offset..next]); + offset = next; + } + } + reader.close().await.unwrap(); + assert_eq!(offset, expected.len()); +} + +#[tokio::test] +#[ignore = "manual real loopback SFTP performance fixture"] +async fn sftp_read_and_listing_at_controlled_latency() { + const FILE_BYTES: usize = 4 * 1024 * 1024; + const DIRECTORY_FILES: usize = 2_000; + let sshd = Sshd::start().expect("performance fixture needs local OpenSSH"); + let files = sshd.root().join("entries"); + fs::create_dir(&files).unwrap(); + for index in 0..DIRECTORY_FILES { + fs::write(files.join(format!("{index:05}.data")), []).unwrap(); + } + let source = sshd.root().join("payload"); + let data: Vec<_> = (0..FILE_BYTES).map(|n| (n % 251) as u8).collect(); + fs::write(&source, &data).unwrap(); + + for one_way_ms in [0, 15, 50] { + let delay = Duration::from_millis(one_way_ms); + let (request, proxy) = connect_proxy(&sshd, delay).await; + let transport = sshd.transport("plain"); + let started = Instant::now(); + let session = transport.open(request); + connect(&session, accept).await; + let open_ms = started.elapsed().as_secs_f64() * 1000.; + let remote = session.fs().unwrap(); + // Warm the subsystem before timing the listing or read. + assert!(remote.read_dir(files.to_str().unwrap()).await.is_ok()); + for run in 1..=3 { + let began = Instant::now(); + let listed = remote.read_dir(files.to_str().unwrap()).await.unwrap(); + let listing_ms = began.elapsed().as_secs_f64() * 1000.; + assert_eq!(listed.len(), DIRECTORY_FILES); + writeln!( + io::stdout().lock(), + "one_way={one_way_ms}ms run={run}: connect={open_ms:.2}ms, list={listing_ms:.2}ms" + ) + .unwrap(); + for batch in if run % 2 == 0 { [8, 1] } else { [1, 8] } { + let began = Instant::now(); + let reader = remote.download(source.to_str().unwrap()).await.unwrap(); + read_exactly(reader, &data, batch).await; + writeln!( + io::stdout().lock(), + "one_way={one_way_ms}ms run={run}: read batch {batch}={:.2}ms", + began.elapsed().as_secs_f64() * 1000. + ) + .unwrap(); + } + } + session.close(); + closed(&session, no_prompts).await; + proxy.abort(); + } +} + +#[tokio::test] +#[ignore = "manual real loopback SFTP directory performance fixture"] +async fn sftp_directory_pages_and_links_at_controlled_latency() { + use std::collections::BTreeMap; + use std::os::unix::fs::symlink; + + let sshd = Sshd::start().expect("performance fixture needs local OpenSSH"); + let target = sshd.root().join("target"); + fs::create_dir(&target).unwrap(); + let mut directories = Vec::new(); + + for (label, count, links) in [("small", 32, 0), ("large", 2048, 0), ("links", 512, 64)] { + let path = sshd.root().join(label); + fs::create_dir(&path).unwrap(); + let mut expected = BTreeMap::new(); + for index in 0..count { + let name = format!("{index:05}.data"); + let is_link = index < links; + if is_link { + symlink(&target, path.join(&name)).unwrap(); + } else { + fs::write(path.join(&name), []).unwrap(); + } + let kind = if is_link { + EntryKind::Directory + } else { + EntryKind::File + }; + expected.insert(name, (kind, is_link)); + } + directories.push((label, path, expected)); + } + + for one_way_ms in [0, 15, 50] { + let (request, proxy) = connect_proxy(&sshd, Duration::from_millis(one_way_ms)).await; + let transport = sshd.transport("plain"); + let session = transport.open(request); + connect(&session, accept).await; + let remote = session.fs().unwrap(); + assert_eq!( + remote + .read_dir(directories[0].1.to_str().unwrap()) + .await + .unwrap() + .len(), + 32 + ); + for run in 1..=3 { + for (label, path, expected) in &directories { + for walk in [run % 2 == 0, run % 2 != 0] { + let began = Instant::now(); + let path = path.to_str().unwrap(); + let listed = if walk { + remote.read_dir_for_walk(path).await.unwrap() + } else { + remote.read_dir(path).await.unwrap() + }; + let ms = began.elapsed().as_secs_f64() * 1000.; + assert_eq!(listed.len(), expected.len()); + let mut remaining = expected.clone(); + for entry in listed { + let (kind, is_link) = remaining.remove(&entry.name).unwrap(); + assert_eq!(entry.is_symlink, is_link); + if !walk || !is_link { + assert_eq!(entry.kind, kind); + } + } + assert!(remaining.is_empty()); + writeln!( + io::stdout().lock(), + "one_way={one_way_ms}ms run={run} walk={walk}: {label}={ms:.2}ms" + ) + .unwrap(); + } + } + } + session.close(); + closed(&session, no_prompts).await; + proxy.abort(); + } +} + +async fn echo_samples(session: &Session, phase: &str) -> Vec<(Instant, Duration)> { + let mut samples = Vec::with_capacity(16); + for index in 0..16 { + let token = format!("{phase}-{index:02}"); + let sent = Instant::now(); + assert!(session.input(format!("{token}\r"))); + output_containing(session, &format!("reply:{token}")).await; + samples.push((sent, sent.elapsed())); + tokio::time::sleep(Duration::from_millis(2)).await; + } + samples +} + +async fn upload_exactly(remote: &dyn RemoteFs, destination: &Path, data: &[u8]) { + let path = destination.to_str().unwrap(); + let mut upload = remote.upload(path, UploadMode::Create).await.unwrap(); + for batch in data.chunks(8 * 32 * 1024) { + let chunks = batch.chunks(32 * 1024).map(<[u8]>::to_vec).collect(); + upload.write_batch(chunks).await.unwrap(); + } + upload.finish().await.unwrap(); +} + +fn echo_latency(samples: impl Iterator) -> (usize, f64, f64) { + let mut ms: Vec<_> = samples.map(|sample| sample.as_secs_f64() * 1000.).collect(); + assert!( + ms.len() >= 2, + "need multiple echo samples during the measured phase" + ); + ms.sort_by(f64::total_cmp); + (ms.len(), ms[ms.len() / 2], ms[ms.len() - 1]) +} + +#[tokio::test] +#[ignore = "manual loopback SFTP and terminal performance fixture"] +async fn terminal_echo_during_batched_file_transfers() { + let sshd = Sshd::start().expect("performance fixture needs local OpenSSH"); + let download = sshd.root().join("download"); + for (one_way_ms, mib_per_file, lanes) in [(0, 64, 3), (15, 4, 2), (50, 4, 2)] { + let data: Vec<_> = (0..mib_per_file * 1024 * 1024) + .map(|index| (index % 251) as u8) + .collect(); + fs::write(&download, &data).unwrap(); + let (request, proxy) = if one_way_ms == 0 { + (sshd.request(), None) + } else { + let (request, proxy) = connect_proxy(&sshd, Duration::from_millis(one_way_ms)).await; + (request, Some(proxy)) + }; + let transport = sshd.transport("plain"); + let session = transport.open(request); + connect(&session, accept).await; + let remote = session.fs().unwrap(); + assert!(remote.stat(download.to_str().unwrap()).await.is_ok()); + assert!(session.input( + "stty -echo; printf 'nocterm-%s\\n' ready; while IFS= read -r line; do printf 'reply:%s\\n' \"$line\"; done\r" + )); + output_containing(&session, "nocterm-ready").await; + let (_, idle_median, idle_max) = echo_latency( + echo_samples(&session, "idle") + .await + .into_iter() + .map(|(_, duration)| duration), + ); + let destinations: Vec<_> = (0..lanes) + .map(|index| sshd.root().join(format!("upload-{index}"))) + .collect(); + let traffic = async { + let read = || async { + let reader = remote.download(download.to_str().unwrap()).await.unwrap(); + read_exactly(reader, &data, 8).await; + }; + let uploads = futures::future::join_all( + destinations + .iter() + .map(|path| upload_exactly(remote.as_ref(), path, &data)), + ); + let reads = futures::future::join_all((0..lanes).map(|_| read())); + tokio::join!( + async { + reads.await; + Instant::now() + }, + async { + uploads.await; + Instant::now() + } + ) + }; + let start = Instant::now(); + let ((read_end, write_end), samples) = + tokio::join!(traffic, echo_samples(&session, "loaded")); + let (overlap, loaded_median, loaded_max) = echo_latency( + samples + .into_iter() + .filter(|(sent, _)| *sent < read_end.min(write_end)) + .map(|(_, duration)| duration), + ); + for destination in destinations { + assert_eq!(fs::read(&destination).unwrap(), data); + fs::remove_file(&destination).unwrap(); + } + writeln!( + io::stdout().lock(), + "one_way={one_way_ms}ms {lanes} uploads + {lanes} downloads of {mib_per_file}MiB: idle median/max {idle_median:.2}/{idle_max:.2} ms, loaded {loaded_median:.2}/{loaded_max:.2} ms ({overlap} samples), downloads {:.2} ms, uploads {:.2} ms", + (read_end - start).as_secs_f64() * 1000., + (write_end - start).as_secs_f64() * 1000. + ) + .unwrap(); + session.close(); + closed(&session, no_prompts).await; + if let Some(proxy) = proxy { + proxy.abort(); + } + } +} + +#[tokio::test] +#[ignore = "manual parallel SSH login fixture"] +async fn parallel_ssh_logins_with_a_large_known_hosts_file() { + let sshd = Sshd::start_with("MaxStartups 64:30:128").expect("fixture needs local OpenSSH"); + let transport = sshd.transport("plain"); + let key = fs::read_to_string(sshd.root().join("host_key.pub")).unwrap(); + let known_hosts = sshd.root().join("known_hosts"); + for (shape, count) in [ + ("plain sparse", 32), + ("plain sparse", 12_000), + ("hashed sparse", 12_000), + ("plain dense", 12_000), + ] { + let mut trust = io::BufWriter::new(fs::File::create(&known_hosts).unwrap()); + let target = sshd.host_label(); + for index in 0..count { + if index == 0 || shape == "plain dense" { + writeln!(trust, "{target} {}", key.trim_end()).unwrap(); + } else { + writeln!(trust, "record-{index:05}.example {}", key.trim_end()).unwrap(); + } + } + trust.flush().unwrap(); + drop(trust); + if shape == "hashed sparse" { + assert!( + std::process::Command::new("ssh-keygen") + .args(["-q", "-H", "-f"]) + .arg(&known_hosts) + .output() + .unwrap() + .status + .success() + ); + } + + let start = Instant::now(); + let sessions: Vec<_> = (0..12).map(|_| transport.open(sshd.request())).collect(); + let mut ready = futures::future::join_all(sessions.iter().enumerate().map( + |(index, session)| async move { + connect(session, no_prompts).await; + assert!(session.input(format!("printf 'ready-%s\\n' {index}\r"))); + // The carriage return/newline anchors the end of the response token. + output_containing(session, &format!("ready-{index}\r\n")).await; + start.elapsed() + }, + )) + .await; + ready.sort_unstable(); + writeln!( + io::stdout().lock(), + "{count} {shape} host records, {} ready PTYs, median {:.2} ms, last {:.2} ms", + sessions.len(), + ready[ready.len() / 2].as_secs_f64() * 1000., + ready.last().unwrap().as_secs_f64() * 1000., + ) + .unwrap(); + for session in &sessions { + session.close(); + } + for session in &sessions { + assert_eq!(closed(session, no_prompts).await, CloseReason::ClosedByUser); + } + } +} diff --git a/crates/ssh/tests/cases/recovery.rs b/crates/ssh/tests/cases/recovery.rs new file mode 100644 index 00000000..aba73ebf --- /dev/null +++ b/crates/ssh/tests/cases/recovery.rs @@ -0,0 +1,145 @@ +use super::*; +use futures::future::join_all; +use std::{io::Write as _, time::Instant}; +use tokio::{ + net::{TcpListener, TcpStream}, + sync::watch, + task::{JoinHandle, JoinSet}, +}; + +/// Forwards real SSH sessions and resets only the links accepted before a cut. +async fn faultable_route(upstream_port: u16) -> (u16, watch::Sender, JoinHandle<()>) { + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (cuts, generation) = watch::channel(0); + let proxy = tokio::spawn(async move { + let mut links = JoinSet::new(); + loop { + tokio::select! { + joined = links.join_next(), if !links.is_empty() => { + joined.unwrap().unwrap(); + } + accepted = listener.accept() => { + let (mut client, _) = accepted.unwrap(); + let mut generation = generation.clone(); + generation.borrow_and_update(); + links.spawn(async move { + let mut upstream = TcpStream::connect(("127.0.0.1", upstream_port)).await.unwrap(); + client.set_nodelay(true).unwrap(); + upstream.set_nodelay(true).unwrap(); + tokio::select! { + cut = generation.changed() => { + cut.unwrap(); + client.set_zero_linger().unwrap(); + upstream.set_zero_linger().unwrap(); + } + _ = tokio::io::copy_bidirectional(&mut client, &mut upstream) => {} + } + }); + } + } + } + }); + (port, cuts, proxy) +} + +async fn round_trip(session: &Session, tag: &str) { + // Keep the expected marker out of the input echo. + assert!(session.input(format!("printf '%s%s\\n' 'recovery-' '{tag}'\r"))); + output_containing(session, &format!("recovery-{tag}")).await; +} + +async fn exercise_recovery(width: usize, cycles: usize) { + let Some(sshd) = Sshd::start_with("MaxStartups 64:30:128\nForceCommand /bin/sh -i\n") else { + return; + }; + let (proxy_port, cuts, proxy) = faultable_route(sshd.port()).await; + let host_key = fs::read_to_string(sshd.root().join("host_key.pub")).unwrap(); + fs::write( + sshd.root().join("known_hosts"), + format!( + "[127.0.0.1]:{} {}\n[127.0.0.1]:{proxy_port} {}\n", + sshd.port(), + host_key.trim(), + host_key.trim(), + ), + ) + .unwrap(); + + let transport = sshd.transport("plain"); + let mut routed = sshd.request(); + routed.target.port = proxy_port; + let survivor = transport.open(sshd.request()); + connect(&survivor, no_prompts).await; + let mut active: Vec<_> = (0..width).map(|_| transport.open(routed.clone())).collect(); + join_all( + active + .iter() + .enumerate() + .map(|(index, session)| async move { + connect(session, no_prompts).await; + round_trip(session, &format!("initial-{index}")).await; + }), + ) + .await; + + for cycle in 0..cycles { + let fault = Instant::now(); + cuts.send(cycle + 1).unwrap(); + let lost_times = join_all(active.iter().map(|session| async { + let reason = closed(session, no_prompts).await; + assert!( + matches!(reason, CloseReason::Failed(SessionError::ConnectionLost(_))), + "{reason:?}" + ); + fault.elapsed() + })) + .await; + let reopen = Instant::now(); + active = (0..width).map(|_| transport.open(routed.clone())).collect(); + let first_output = join_all( + active + .iter() + .enumerate() + .map(|(index, session)| async move { + connect(session, no_prompts).await; + round_trip(session, &format!("reopened-{cycle}-{index}")).await; + reopen.elapsed() + }), + ); + let survivor_tag = format!("survivor-{cycle}"); + let (outputs, ()) = tokio::join!(first_output, round_trip(&survivor, &survivor_tag)); + writeln!( + std::io::stdout().lock(), + "{width} links, batch {}: last ConnectionLost {:.3} ms, last fresh shell reply {:.3} ms", + cycle + 1, + lost_times.into_iter().max().unwrap().as_secs_f64() * 1_000., + outputs.into_iter().max().unwrap().as_secs_f64() * 1_000., + ) + .unwrap(); + } + + let sessions = active.iter().chain(std::iter::once(&survivor)); + for session in sessions.clone() { + session.close(); + } + join_all(sessions.map(|session| async { + assert_eq!(closed(session, no_prompts).await, CloseReason::ClosedByUser); + })) + .await; + proxy.abort(); + assert!(proxy.await.unwrap_err().is_cancelled()); +} + +#[tokio::test] +async fn a_reset_ssh_link_can_be_reopened_while_an_unaffected_session_stays_live() { + exercise_recovery(1, 1).await; +} + +#[tokio::test] +#[ignore = "manual loopback SSH recovery latency fixture"] +async fn measure_recovery_after_a_burst_of_ssh_link_resets() { + for width in [1, 8, 16, 16, 8, 1] { + exercise_recovery(width, 4).await; + } +} diff --git a/crates/ssh/tests/sshd.rs b/crates/ssh/tests/sshd.rs index 38030e2b..4feee199 100644 --- a/crates/ssh/tests/sshd.rs +++ b/crates/ssh/tests/sshd.rs @@ -30,9 +30,15 @@ mod file_operations; #[path = "cases/download.rs"] mod download; +#[path = "cases/performance.rs"] +mod performance; + #[path = "cases/proxy.rs"] mod proxy; +#[path = "cases/recovery.rs"] +mod recovery; + #[path = "cases/exec.rs"] mod exec; diff --git a/crates/store/src/append.rs b/crates/store/src/append.rs index 1d9cb153..be224973 100644 --- a/crates/store/src/append.rs +++ b/crates/store/src/append.rs @@ -11,7 +11,7 @@ use futures::{ channel::mpsc::{self, Receiver, Sender}, future::{BoxFuture, poll_fn}, }; -use gpui::{AppContext, Context, Entity}; +use gpui::{AppContext, Context, Entity, EventEmitter}; use nocterm_core::persist::WriteGate; use nocterm_session::recording::{ AppendBlock, AppendOutcome, MAX_APPEND_BYTES, OutputLog, OutputLogFactory, PhysicalPrefix, @@ -24,6 +24,7 @@ use std::{ }; const QUEUE_CAPACITY: usize = 128; +const SHUTDOWN_DRAIN_CONCURRENCY: usize = 4; #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct AppendStatus { @@ -72,6 +73,11 @@ pub struct AppendPersisted { completion: Option>, } +/// The published file path or recording error changed. +pub struct AppendMetadataChanged; + +impl EventEmitter for AppendPersisted {} + pub(crate) enum AppendOpKind { Create, Append, @@ -322,15 +328,31 @@ impl AppendPersisted { fn update_status(&mut self, cx: &mut Context) { let phys = self.physical.lock().unwrap_or_else(|e| e.into_inner()); - self.status.path = phys.path.clone(); - self.status.bytes = phys.prefix.written_bytes(); - self.status.finished = phys.sealed; - self.status.error = self + let error = self .admission .error - .clone() - .or_else(|| phys.first_disk_error.clone()); - *self.shared_status.lock().unwrap_or_else(|e| e.into_inner()) = self.status.clone(); + .as_ref() + .or(phys.first_disk_error.as_ref()); + let path_changed = self.status.path != phys.path; + let error_changed = self.status.error.as_ref() != error; + let mut shared = self.shared_status.lock().unwrap_or_else(|e| e.into_inner()); + if path_changed { + self.status.path.clone_from(&phys.path); + shared.path.clone_from(&phys.path); + } + if error_changed { + self.status.error = error.cloned(); + shared.error.clone_from(&self.status.error); + } + self.status.bytes = phys.prefix.written_bytes(); + self.status.finished = phys.sealed; + shared.bytes = self.status.bytes; + shared.finished = self.status.finished; + drop(shared); + drop(phys); + if path_changed || error_changed { + cx.emit(AppendMetadataChanged); + } cx.notify(); } } @@ -406,7 +428,9 @@ impl NormalOwner for AppendPersisted { self.update_status(cx); - if let (true, Some(completion)) = (self.status.finished, self.completion.take()) { + if self.status.finished + && let Some(completion) = self.completion.take() + { completion(&self.status); } } @@ -604,6 +628,7 @@ impl CapturedPolicy for CapturedAppend { } pub struct RecordingRegistry { + // Keep unfinished recordings alive when their terminal drops its handle. entries: Arc>>>, factory: Arc, } @@ -621,12 +646,22 @@ impl RecordingRegistry { } pub fn open(&self, options: RecordingOptions, cx: &mut gpui::App) -> AppendHandle { - let entries = self.entries.clone(); + let entries = Arc::downgrade(&self.entries); let entity = cx.new(|cx| { - let (persisted, _) = AppendPersisted::new(self.factory.clone(), options, None, cx); + let id = cx.entity_id(); + let retire = Box::new(move |_: &AppendStatus| { + if let Some(entries) = entries.upgrade() { + entries + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|entry| entry.entity_id() != id); + } + }); + let (persisted, _) = + AppendPersisted::new(self.factory.clone(), options, Some(retire), cx); persisted }); - entries + self.entries .lock() .unwrap_or_else(|e| e.into_inner()) .push(entity.clone()); @@ -655,10 +690,18 @@ impl RecordingRegistry { list.push(captured); } entries_guard.clear(); + let executor = cx.background_executor().clone(); Box::pin(async move { - for item in list { - captured::run(item).await; - } + // Each file keeps its own write gate. A blocking sync must allow + // the other files to use the coordinator's remaining deadline. + futures::stream::iter(list) + .for_each_concurrent(SHUTDOWN_DRAIN_CONCURRENCY, |item| { + let task = executor.spawn(captured::run(item)); + async move { + task.await; + } + }) + .await; Ok(()) }) }) diff --git a/crates/store/src/append/tests.rs b/crates/store/src/append/tests.rs index 47497937..04670258 100644 --- a/crates/store/src/append/tests.rs +++ b/crates/store/src/append/tests.rs @@ -330,3 +330,108 @@ async fn recording_registry_handles_publish_held_progress_and_final_error(cx: &m assert!(created.error().is_none()); assert_eq!(created.bytes(), 0); } + +#[gpui::test] +fn finished_recording_releases_its_sink_after_the_last_client_leaves(cx: &mut TestAppContext) { + use nocterm_session::testing::Gate; + + let factory = Arc::new(ScriptedOutputLogFactory::default()); + let registry = RecordingRegistry::new(factory.clone()); + let seal = Gate::pending(); + let sink = Arc::new(ScriptedOutputLog::new(PathBuf::from("/recording.log"))); + let retained = Arc::downgrade(&sink); + sink.enqueue_append( + Gate::open(), + AppendOutcome::new(PhysicalPrefix::new(1, 8, 0, false, false), None), + ); + sink.enqueue_seal( + seal.clone(), + AppendOutcome::new(PhysicalPrefix::new(1, 8, 0, true, true), None), + ); + factory.enqueue(Gate::open(), Ok(sink)); + + let handle = cx.update(|cx| { + let handle = registry.open( + RecordingOptions { + directory: None, + max_file_mib: 10, + }, + cx, + ); + handle.output(b"recorded", cx); + handle.stop(cx); + handle + }); + cx.run_until_parked(); + assert_eq!(handle.status().bytes(), 8); + assert!(!handle.status().finished()); + let recording = handle.entity().downgrade(); + drop(handle); + cx.run_until_parked(); + assert_eq!(retained.upgrade().unwrap().seal_count(), 1); + + seal.release(); + cx.run_until_parked(); + assert!(recording.upgrade().is_none()); + // GPUI drops released entities when it flushes the next application update. + cx.update(|_| {}); + assert!(retained.upgrade().is_none()); +} + +#[gpui::test] +async fn shutdown_drains_recordings_with_bounded_independent_progress(cx: &mut TestAppContext) { + use nocterm_session::testing::Gate; + + let factory = Arc::new(ScriptedOutputLogFactory::default()); + let registry = RecordingRegistry::new(factory.clone()); + let coordinator = crate::ShutdownCoordinator::default(); + registry.register(&coordinator).unwrap(); + + let mut sinks = Vec::new(); + let mut seals = Vec::new(); + for index in 0..6 { + let sink = Arc::new(ScriptedOutputLog::new( + format!("/recording-{index}.log").into(), + )); + let seal = Gate::pending(); + sink.enqueue_seal( + seal.clone(), + AppendOutcome::new(PhysicalPrefix::new(0, 0, 0, true, true), None), + ); + factory.enqueue(Gate::open(), Ok(sink.clone())); + cx.update(|cx| { + registry.open( + RecordingOptions { + directory: None, + max_file_mib: 10, + }, + cx, + ); + }); + sinks.push(sink); + seals.push(seal); + } + cx.run_until_parked(); + + let work = cx.update(|cx| coordinator.capture_all(cx)); + let task = cx.background_executor.spawn(work); + cx.run_until_parked(); + let started = || sinks.iter().filter(|sink| sink.seal_count() != 0).count(); + assert_eq!(started(), 4); + + let started_seal = sinks + .iter() + .position(|sink| sink.seal_count() == 1) + .unwrap(); + seals[started_seal].release(); + cx.run_until_parked(); + assert_eq!(started(), 5); + + for seal in seals { + seal.release(); + } + let report = task.await; + assert!(!report.timed_out()); + assert!(report.failures().is_empty()); + assert!(sinks.iter().all(|sink| sink.seal_count() == 1)); +} diff --git a/crates/store/src/lib.rs b/crates/store/src/lib.rs index 2b8598ba..eb6ddd21 100644 --- a/crates/store/src/lib.rs +++ b/crates/store/src/lib.rs @@ -23,7 +23,10 @@ mod settings; mod shutdown; mod worker; -pub use append::{AppendHandle, AppendPersisted, AppendStatus, CapturedAppend, RecordingRegistry}; +pub use append::{ + AppendHandle, AppendMetadataChanged, AppendPersisted, AppendStatus, CapturedAppend, + RecordingRegistry, +}; pub use captured::{Captured, CapturedFeed, CapturedOutcome, CommitPhase, Committed}; pub use error::StoreError; pub use persisted::{Persisted, Publication, Receipt, Revision, SnapshotWriter}; diff --git a/crates/store/src/settings.rs b/crates/store/src/settings.rs index d803c3be..27fa140d 100644 --- a/crates/store/src/settings.rs +++ b/crates/store/src/settings.rs @@ -107,6 +107,10 @@ impl SettingsHandle { pub fn section_errors(&self, cx: &App) -> Vec { self.document(cx).errors() } + /// A shared immutable diagnostic projection of the visible document. + pub fn section_error_snapshot(&self, cx: &App) -> Arc<[SectionError]> { + self.document(cx).error_snapshot() + } pub fn is_persistent(&self) -> bool { self.persistent } @@ -221,6 +225,30 @@ impl SettingsHandle { }) } + /// Observe published changes to one typed section, not unrelated revisions. + /// Like `observe`, this excludes admission, failures and schema hydration. + pub fn observe_section( + &self, + cx: &mut App, + mut on_change: impl FnMut(&mut App) + 'static, + ) -> Subscription { + let mut seen = self.revision(cx); + let mut previous = self.document(cx).section_snapshot::(); + cx.observe(&self.state, move |entity, cx| { + let snapshot = entity.read(cx).visible(); + if snapshot.revision == seen { + return; + } + seen = snapshot.revision; + let current = snapshot.document.section_snapshot::(); + let changed = !Arc::ptr_eq(&previous, ¤t) && previous != current; + previous = current; + if changed { + on_change(cx); + } + }) + } + pub fn register_shutdown(&self, shutdown: &ShutdownCoordinator) -> Result<(), StoreError> { shutdown.register(&self.state) } diff --git a/crates/store/src/settings/tests.rs b/crates/store/src/settings/tests.rs index a10dffa1..af25a7ca 100644 --- a/crates/store/src/settings/tests.rs +++ b/crates/store/src/settings/tests.rs @@ -399,3 +399,175 @@ async fn checked_section_publishes_sanitized_value_and_counts_sanitized_noop_onc } mod publication; + +#[gpui::test] +#[ignore = "release profile of ordered in-memory settings edits with a large unrelated section"] +async fn measure_unrelated_settings_publication(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + let count = std::env::var("NOCTERM_PROFILE_TYPED_ROWS") + .map_or(Ok(512), |value| value.parse::()) + .unwrap(); + assert!(count <= 4096); + let mut local = LocalShellSettings::default(); + for index in 0..count { + local.env.insert( + format!("PROFILE_ROW_{index:04}"), + format!("{}-{index}", "x".repeat(128)), + ); + } + let settings = cx.update(|cx| { + SettingsConfig::in_memory(SettingsDocument::default()) + .with(local.clone()) + .with(SshSettings::default()) + .install(cx) + }); + let mut samples = Vec::new(); + let mut revision = 0; + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..128 { + let value = 16 + (revision % 2) as u32; + revision += 1; + assert_eq!( + cx.update(|cx| settings.update_checked::(cx, move |ssh| { + ssh.connect_timeout_secs = value; + Ok(()) + })) + .await + .unwrap(), + revision + ); + } + samples.push(start.elapsed()); + } + cx.update(|cx| { + assert_eq!(settings.setting::(cx), &local); + assert_eq!(settings.revision(cx), revision); + }); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "typed_rows={count} publication_p50={:?} publication_max={:?}", + samples[3], + samples[6] + ) + .unwrap(); +} + +#[gpui::test] +async fn retained_settings_snapshots_keep_nested_values_through_accepted_and_rejected_edits( + cx: &mut TestAppContext, +) { + let settings = memory(cx); + cx.update(|cx| { + settings.update::(cx, |local| { + local.env.insert("PROFILE_ROW".into(), "original".into()); + }) + }) + .await + .unwrap(); + let before = cx.update(|cx| settings.document(cx).clone()); + let rejected = cx + .update(|cx| { + settings.update_checked::(cx, |local| { + local.env.insert("PROFILE_ROW".into(), "rejected".into()); + Err(StoreError::PendingWrites) + }) + }) + .await; + assert!(matches!(rejected, Err(StoreError::PendingWrites))); + cx.update(|cx| { + assert_eq!( + settings.setting::(cx).env["PROFILE_ROW"], + "original" + ) + }); + let accepted = cx + .update(|cx| { + settings.update_checked::(cx, |local| { + local.env.insert("PROFILE_ROW".into(), "accepted".into()); + Ok(()) + }) + }) + .await + .unwrap(); + assert_eq!(accepted, 2); + cx.update(|cx| { + assert_eq!( + settings.setting::(cx).env["PROFILE_ROW"], + "accepted" + ) + }); + assert_eq!( + before.get::().env["PROFILE_ROW"], + "original" + ); +} + +#[gpui::test] +async fn section_observation_ignores_unrelated_and_equal_publications(cx: &mut TestAppContext) { + let settings = memory(cx); + let calls = Rc::new(Cell::new(0)); + let observed = calls.clone(); + let subscription = cx.update(|cx| { + settings + .observe_section::(cx, move |_| observed.set(observed.get() + 1)) + }); + cx.update(|cx| { + settings.edit(cx, |document| { + document.update::(|_| {}); + document.update::(|s| s.connect_timeout_secs += 1); + }) + }) + .await + .unwrap(); + assert_eq!(calls.get(), 0); + let retained = cx.update(|cx| { + settings + .document(cx) + .section_snapshot::() + }); + cx.update(|cx| settings.update::(cx, |s| s.program = Some("new".into()))) + .await + .unwrap(); + assert_eq!(calls.get(), 1); + assert!(retained.program.is_none()); + cx.update(|cx| { + settings.update_checked::(cx, |s| { + s.program = None; + Err(StoreError::PendingWrites) + }) + }) + .await + .unwrap_err(); + assert_eq!(calls.get(), 1); + drop(subscription); + cx.update(|cx| settings.update::(cx, |s| s.program = None)) + .await + .unwrap(); + assert_eq!(calls.get(), 1); +} + +#[gpui::test] +async fn section_observation_waits_for_durable_publication(cx: &mut TestAppContext) { + let (writer, release, _) = gated_writer().into_parts(); + let settings = cx.update(|cx| { + SettingsConfig::with_writer(SettingsDocument::default(), writer) + .with(LocalShellSettings::default()) + .install(cx) + }); + let calls = Rc::new(Cell::new(0)); + let observed = calls.clone(); + let _subscription = cx.update(|cx| { + settings + .observe_section::(cx, move |_| observed.set(observed.get() + 1)) + }); + let edit = cx + .update(|cx| settings.update::(cx, |s| s.program = Some("new".into()))); + cx.run_until_parked(); + assert_eq!(calls.get(), 0); + release.send(Ok(())).unwrap(); + cx.run_until_parked(); + assert_eq!(edit.await.unwrap(), 1); + assert_eq!(calls.get(), 1); +} diff --git a/crates/terminal/src/element.rs b/crates/terminal/src/element.rs index be4c20eb..2e968e77 100644 --- a/crates/terminal/src/element.rs +++ b/crates/terminal/src/element.rs @@ -193,7 +193,7 @@ impl TerminalElement { self.view.update(cx, |view, cx| view.sync_cursor_clock(cx)); self.cache.update_highlights( - self.terminal.read(cx).emulator().generation(), + self.terminal.read(cx).emulator().paint_generation(), self.style.semantic_highlighting, ); @@ -231,6 +231,7 @@ impl TerminalElement { { let frame = self.frame(); + let find_highlight = cx.theme().warning.opacity(0.35); for row in 0..frame.size.rows { let cells = frame.row(row); paint_runs(window, &layout.geometry, row, cells, |cell| { @@ -238,7 +239,7 @@ impl TerminalElement { (background != colors.background).then_some(background) }); paint_runs(window, &layout.geometry, row, cells, |cell| { - cell.search_hit.then_some(cx.theme().warning.opacity(0.35)) + cell.search_hit.then_some(find_highlight) }); paint_runs(window, &layout.geometry, row, cells, |cell| { cell.selected.then_some(colors.selection) @@ -248,6 +249,9 @@ impl TerminalElement { self.paint_gutter(&frame, &layout, window, cx); let block = self.paint_cursor(&frame, &layout, window); for row in 0..frame.size.rows { + if frame.occupied_rows.get(usize::from(row)) == Some(&false) { + continue; + } let block_col = block.filter(|at| at.row == row).map(|at| at.col); paint_text( row, @@ -448,7 +452,7 @@ impl TerminalElement { window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { if phase.bubble() { let hovered = move_hitbox.is_hovered(window); - view.update(cx, |view, cx| view.mouse_move(event, hovered, cx)); + view.update(cx, |view, cx| view.mouse_move(event, hovered, window, cx)); } }); diff --git a/crates/terminal/src/element/cache.rs b/crates/terminal/src/element/cache.rs index cbf6b293..42f26919 100644 --- a/crates/terminal/src/element/cache.rs +++ b/crates/terminal/src/element/cache.rs @@ -63,7 +63,7 @@ impl FrameCache { true } pub(crate) fn publish(&self, emulator: &Emulator, revision: u64) -> bool { - let version = (emulator.generation(), revision); + let version = (emulator.paint_generation(), revision); if !self.dirty.get() && self.version.get() == Some(version) && self.frame.borrow().size == emulator.size() diff --git a/crates/terminal/src/element/text.rs b/crates/terminal/src/element/text.rs index fa02d4c0..ddc20a27 100644 --- a/crates/terminal/src/element/text.rs +++ b/crates/terminal/src/element/text.rs @@ -19,6 +19,7 @@ pub(super) fn paint_text( let geometry = &layout.geometry; let mut segment = Segment::default(); let start = usize::from(row) * usize::from(frame.size.cols); + let mut roles = highlights.row_roles(start); let mut combining = frame.combining [frame.combining.partition_point(|(index, _)| *index < start)..] .iter() @@ -33,7 +34,7 @@ pub(super) fn paint_text( } let foreground = layout.colors.text_foreground( cell, - highlights.role_at(start + usize::from(col), cell), + roles.at(start + usize::from(col), cell), block_cursor_col == Some(col), ); let marks = combining.next_if(|(index, _)| *index == start + usize::from(col)); @@ -58,33 +59,31 @@ struct Segment { runs: Vec, /// Holds anything that leaves a mark; blank segments are not shaped. visible: bool, + run_style: Option, } impl Segment { fn push_cell(&mut self, cell: &GridCell, marks: &str, foreground: Hsla, font: &Font) { let hidden = cell.style.hidden || cell.ch.is_control(); let ch = if hidden { ' ' } else { cell.ch }; - self.push(ch, text_run(ch, cell.style, foreground, font)); + let style = RunStyle::new(cell.style, foreground); + let start = self.text.len(); + self.text.push(ch); if !hidden { - for mark in marks.chars() { - self.push(mark, text_run(mark, cell.style, foreground, font)); - } + self.text.push_str(marks); } - } - - fn push(&mut self, ch: char, run: TextRun) { - self.visible |= ch != ' ' || run.underline.is_some() || run.strikethrough.is_some(); - self.text.push(ch); - match self.runs.last_mut() { - Some(last) - if last.font == run.font - && last.color == run.color - && last.underline == run.underline - && last.strikethrough == run.strikethrough => - { - last.len += run.len; - } - _ => self.runs.push(run), + self.visible |= ch != ' ' + || (!hidden && marks.chars().any(|mark| mark != ' ')) + || style.underline + || style.strikeout; + let bytes = self.text.len() - start; + if self.run_style == Some(style) + && let Some(last) = self.runs.last_mut() + { + last.len += bytes; + } else { + self.runs.push(style.text_run(bytes, font)); + self.run_style = Some(style); } } @@ -127,35 +126,58 @@ impl Segment { self.text.clear(); self.runs.clear(); self.visible = false; + self.run_style = None; } } -fn text_run(ch: char, style: Style, color: Hsla, base: &Font) -> TextRun { - let decoration = |on: bool| on.then_some((px(1.0), Some(color))); - TextRun { - len: ch.len_utf8(), - font: Font { - weight: if style.bold { - FontWeight::BOLD - } else { - FontWeight::NORMAL - }, - style: if style.italic { - FontStyle::Italic - } else { - FontStyle::Normal +#[derive(Clone, Copy, PartialEq)] +struct RunStyle { + bold: bool, + italic: bool, + underline: bool, + strikeout: bool, + color: Hsla, +} + +impl RunStyle { + fn new(style: Style, color: Hsla) -> Self { + Self { + bold: style.bold, + italic: style.italic, + underline: style.underline, + strikeout: style.strikeout, + color, + } + } + + fn text_run(self, len: usize, base: &Font) -> TextRun { + let color = self.color; + let decoration = |on: bool| on.then_some((px(1.0), Some(color))); + TextRun { + len, + font: Font { + weight: if self.bold { + FontWeight::BOLD + } else { + FontWeight::NORMAL + }, + style: if self.italic { + FontStyle::Italic + } else { + FontStyle::Normal + }, + ..base.clone() }, - ..base.clone() - }, - color, - background_color: None, - underline: decoration(style.underline).map(|(thickness, color)| UnderlineStyle { - thickness, color, - wavy: false, - }), - strikethrough: decoration(style.strikeout) - .map(|(thickness, color)| StrikethroughStyle { thickness, color }), + background_color: None, + underline: decoration(self.underline).map(|(thickness, color)| UnderlineStyle { + thickness, + color, + wavy: false, + }), + strikethrough: decoration(self.strikeout) + .map(|(thickness, color)| StrikethroughStyle { thickness, color }), + } } } diff --git a/crates/terminal/src/highlighting.rs b/crates/terminal/src/highlighting.rs index 4c4fc1a0..c76508e8 100644 --- a/crates/terminal/src/highlighting.rs +++ b/crates/terminal/src/highlighting.rs @@ -3,7 +3,11 @@ //! The emulator remains the source of truth for ANSI styles, selection, copying //! and recording. This cache holds roles, so changing a palette needs no parsing. use nocterm_vt::{Cell, Color, Frame, Style, TermSize}; +use std::{collections::HashMap, mem}; +use groups::{Budget, Group, GroupKey, Scratch}; + +mod groups; mod rules; #[cfg(test)] mod tests; @@ -11,6 +15,7 @@ mod tests; const GROUP_BYTES: usize = 4096; const FRAME_BYTES: usize = 64 * 1024; const MAX_SPANS: usize = 4096; +const MAX_GROUPS: usize = 512; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Role { @@ -42,13 +47,18 @@ impl Role { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Key { +struct Screen { generation: u64, size: TermSize, - display_offset: usize, alt_screen: bool, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Key { + screen: Screen, + display_offset: usize, +} + // u32 indices bound the retained cache to 48 KiB (4096 twelve-byte spans). #[derive(Clone, Copy, Debug)] struct Span { @@ -61,6 +71,8 @@ struct Span { pub(crate) struct Highlights { key: Option, spans: Vec, + visible_groups: HashMap, + spare_groups: HashMap, #[cfg(test)] scans: usize, } @@ -81,152 +93,98 @@ impl Highlights { pub(crate) fn clear(&mut self) { self.key = None; self.spans = Vec::new(); + self.visible_groups = HashMap::new(); + self.spare_groups = HashMap::new(); } - #[expect( - clippy::cognitive_complexity, - clippy::too_many_lines, - reason = "predates the limit" - )] pub(crate) fn update(&mut self, frame: &Frame, generation: u64, enabled: bool) { if !enabled { self.clear(); return; } let key = Key { - generation, - size: frame.size, + screen: Screen { + generation, + size: frame.size, + alt_screen: frame.alt_screen, + }, display_offset: frame.display_offset, - alt_screen: frame.alt_screen, }; if self.key == Some(key) { return; } + let same_generation = self.key.is_some_and(|old| old.screen == key.screen); + if self.key.is_none_or(|old| { + old.screen.size != key.screen.size || old.screen.alt_screen != key.screen.alt_screen + }) { + self.visible_groups.clear(); + } self.key = Some(key); self.spans.clear(); #[cfg(test)] { self.scans += 1; } - let cols = usize::from(frame.size.cols); - let mut row = 0; - let mut remaining = FRAME_BYTES; - let mut cell_budget = FRAME_BYTES; - while row < frame.size.rows && remaining > 0 && self.spans.len() < MAX_SPANS { - let start_complete = row != 0 || !frame.starts_with_continuation; - let mut end_complete = true; - let mut text = String::new(); - let mut mapping = Vec::new(); - let mut overflow = false; - loop { - let wraps = frame.wraps.get(usize::from(row)).copied().unwrap_or(false); - let cells = frame.row(row); - // Even blank rows consume scan budget; trimming must not walk - // an arbitrarily large viewport that produces no text. - if cells.len() > cell_budget { - return; - } - cell_budget -= cells.len(); - let end = if wraps { - cells.len() - } else { - cells - .iter() - .rposition(|cell| cell.ch != ' ' || cell.spacer) - .map_or(0, |col| col + 1) - }; - for (col, cell) in cells[..end].iter().enumerate() { - if cell.spacer { - continue; - } - let index = usize::from(row) * cols + col; - let marks = frame - .combining - .binary_search_by_key(&index, |(ix, _)| *ix) - .ok() - .map(|ix| frame.combining[ix].1.as_str()) - .unwrap_or(""); - let ch = if cell.style.hidden || cell.ch.is_control() { - '\0' - } else { - cell.ch - }; - let marks = if cell.style.hidden { "" } else { marks }; - let len = ch.len_utf8() + marks.len(); - if len > GROUP_BYTES.saturating_sub(text.len()) || len > remaining { - overflow = true; - break; - } - let start = text.len(); - text.push(ch); - text.push_str(marks); - mapping.push((start, text.len(), index)); - remaining -= len; - } - row += 1; - if !wraps || row == frame.size.rows { - end_complete = !wraps; - break; - } - if overflow { - // Skip the rest of an oversized logical line without scanning its cells. - while row < frame.size.rows { - let wraps = frame.wraps.get(usize::from(row)).copied().unwrap_or(false); - row += 1; - if !wraps { - break; - } - } - break; - } - } - if overflow { - continue; - } - let mut roles = vec![None; text.len()]; - for token in rules::recognize(&text, start_complete, end_complete) { - for slot in &mut roles[token.start..token.end] { - if slot.is_none() { - *slot = Some(token.role); - } - } + self.project_groups(frame, same_generation); + } + + fn project_groups(&mut self, frame: &Frame, same_generation: bool) { + let mut budget = Budget::default(); + let mut scratch = Scratch::default(); + let mut start = 0; + while start < frame.size.rows && budget.has_text_space() && self.spans.len() < MAX_SPANS { + let rows = groups::next_group(frame, start); + let key = GroupKey::for_rows(frame, &rows); + let origin = u32::from(start) * u32::from(frame.size.cols); + start = rows.end; + let previous = self.visible_groups.remove(&key); + let group = match previous { + Some(group) if same_generation && budget.spend(&group) => Some(group), + previous => groups::scan(frame, rows, key, &mut budget, &mut scratch, previous), + }; + let Some(group) = group else { + break; + }; + if !group.project_into(&mut self.spans, origin) { + break; } - for &(start, _end, index) in &mapping { - if index > u32::MAX as usize || !plain(&frame.cells[index]) { - continue; - } - let role = roles[start]; - let Some(role) = role else { - continue; - }; - if let Some(last) = self.spans.last_mut() - && last.end as usize == index - && last.role == role - { - last.end += 1; - } else if self.spans.len() < MAX_SPANS { - self.spans.push(Span { - start: index as u32, - end: index as u32 + 1, - role, - }); - } else { - return; - } + if group.is_reusable() && self.spare_groups.len() < MAX_GROUPS { + self.spare_groups.insert(key, group); } } + self.visible_groups.clear(); + mem::swap(&mut self.visible_groups, &mut self.spare_groups); } - pub(crate) fn role_at(&self, index: usize, cell: &Cell) -> Option { - if cell.selected || cell.search_hit || !plain(cell) { - return None; - } + pub(crate) fn row_roles(&self, start: usize) -> RowRoles<'_> { let next = self .spans - .partition_point(|span| span.end as usize <= index); - self.spans - .get(next) - .filter(|span| span.start as usize <= index) + .partition_point(|span| span.end as usize <= start); + RowRoles(&self.spans[next..]) + } + + #[cfg(test)] + pub(crate) fn role_at(&self, index: usize, cell: &Cell) -> Option { + self.row_roles(index).at(index, cell) + } +} + +pub(crate) struct RowRoles<'a>(&'a [Span]); + +impl RowRoles<'_> { + /// Read cells in increasing order so each span is visited at most once per row. + pub(crate) fn at(&mut self, index: usize, cell: &Cell) -> Option { + while let Some((span, rest)) = self.0.split_first() { + if span.end as usize > index { + break; + } + self.0 = rest; + } + self.0 + .first() + .filter(|span| { + span.start as usize <= index && !cell.selected && !cell.search_hit && plain(cell) + }) .map(|span| span.role) } } diff --git a/crates/terminal/src/highlighting/groups.rs b/crates/terminal/src/highlighting/groups.rs new file mode 100644 index 00000000..9f823a09 --- /dev/null +++ b/crates/terminal/src/highlighting/groups.rs @@ -0,0 +1,236 @@ +//! Preparing one logical line under the same limits as the visible frame. +use super::{FRAME_BYTES, GROUP_BYTES, MAX_SPANS, Role, Span, plain, rules}; +use nocterm_vt::Frame; +use std::ops::Range; + +pub(super) struct Budget { + bytes: usize, + cells: usize, +} + +impl Default for Budget { + fn default() -> Self { + Self { + bytes: FRAME_BYTES, + cells: FRAME_BYTES, + } + } +} + +impl Budget { + pub(super) fn has_text_space(&self) -> bool { + self.bytes != 0 + } + + pub(super) fn spend(&mut self, group: &Group) -> bool { + if self.bytes < group.bytes || self.cells < group.cells { + return false; + } + self.bytes -= group.bytes; + self.cells -= group.cells; + true + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(super) struct GroupKey { + start: i32, + rows: u16, + start_complete: bool, + end_complete: bool, +} + +impl GroupKey { + pub(super) fn for_rows(frame: &Frame, rows: &Range) -> Self { + Self { + start: i32::from(rows.start) - frame.display_offset as i32, + rows: rows.end - rows.start, + start_complete: rows.start != 0 || !frame.starts_with_continuation, + end_complete: !wraps(frame, rows.end - 1), + } + } +} + +pub(super) struct Group { + spans: Vec, + cells: usize, + bytes: usize, + reusable: bool, + recognition: Option, +} + +impl Group { + pub(super) fn project_into(&self, spans: &mut Vec, origin: u32) -> bool { + self.spans + .iter() + .all(|span| push(spans, origin + span.start, origin + span.end, span.role)) + } + + pub(super) fn is_reusable(&self) -> bool { + self.reusable + } +} + +fn wraps(frame: &Frame, row: u16) -> bool { + frame.wraps.get(usize::from(row)).copied().unwrap_or(false) +} + +pub(super) fn next_group(frame: &Frame, start: u16) -> Range { + let mut end = start + 1; + while end < frame.size.rows && wraps(frame, end - 1) { + end += 1; + } + start..end +} + +#[derive(Default)] +pub(super) struct Scratch { + text: String, + positions: Vec<(usize, usize)>, +} + +pub(super) fn scan( + frame: &Frame, + rows: Range, + key: GroupKey, + budget: &mut Budget, + scratch: &mut Scratch, + previous: Option, +) -> Option { + let mut group = Group { + spans: Vec::new(), + cells: 0, + bytes: 0, + reusable: true, + recognition: None, + }; + let Scratch { text, positions } = scratch; + text.clear(); + positions.clear(); + let cols = usize::from(frame.size.cols); + let origin = usize::from(rows.start) * cols; + let mut marks = frame.combining[frame.combining.partition_point(|(i, _)| *i < origin)..] + .iter() + .peekable(); + for row in rows { + let cells = frame.row(row); + budget.cells = budget.cells.checked_sub(cells.len())?; + group.cells += cells.len(); + let end = if wraps(frame, row) { + cells.len() + } else { + if frame.occupied_rows.get(usize::from(row)) == Some(&false) { + continue; + } + cells + .iter() + .rposition(|cell| cell.ch != ' ' || cell.spacer) + .map_or(0, |col| col + 1) + }; + for (col, cell) in cells[..end].iter().enumerate() { + if cell.spacer { + continue; + } + let index = usize::from(row) * cols + col; + while marks.peek().is_some_and(|(i, _)| *i < index) { + marks.next(); + } + let cell_marks = marks.next_if(|(i, _)| *i == index); + let hidden = cell.style.hidden; + let ch = if hidden || cell.ch.is_control() { + '\0' + } else { + cell.ch + }; + let marks = cell_marks + .filter(|_| !hidden) + .map_or("", |(_, marks)| marks.as_str()); + let len = ch.len_utf8() + marks.len(); + if len > GROUP_BYTES - text.len() { + return Some(group); + } + if len > budget.bytes { + group.reusable = false; + return Some(group); + } + if plain(cell) { + positions.push((text.len(), index)); + } + text.push(ch); + text.push_str(marks); + budget.bytes -= len; + group.bytes += len; + } + } + if !positions.is_empty() { + let cached = previous.and_then(|old| { + let recognition = old.recognition?; + (recognition.text.as_ref() == text).then_some((recognition, old.spans)) + }); + let (recognition, mut spans) = + cached.unwrap_or_else(|| (Recognition::new(text, key), Vec::new())); + spans.clear(); + recognition.project(positions, origin, &mut spans); + group.spans = spans; + group.recognition = Some(recognition); + } + Some(group) +} + +struct Recognition { + text: Box, + roles: Box<[Option]>, +} + +impl Recognition { + fn new(text: &str, key: GroupKey) -> Self { + let tokens = rules::recognize(text, key.start_complete, key.end_complete); + let mut roles = Vec::new(); + if !tokens.is_empty() { + roles.resize(text.len(), None); + for token in tokens { + for slot in &mut roles[token.start..token.end] { + if slot.is_none() { + *slot = Some(token.role); + } + } + } + } + Self { + text: text.into(), + roles: roles.into_boxed_slice(), + } + } + + fn project(&self, positions: &[(usize, usize)], origin: usize, spans: &mut Vec) { + if self.roles.is_empty() { + return; + } + for &(start, index) in positions { + if let Some(role) = self.roles[start] + && !push( + spans, + (index - origin) as u32, + (index - origin + 1) as u32, + role, + ) + { + break; + } + } + } +} + +fn push(spans: &mut Vec, start: u32, end: u32, role: Role) -> bool { + if let Some(last) = spans.last_mut() + && last.end == start + && last.role == role + { + last.end = end; + } else if spans.len() < MAX_SPANS { + spans.push(Span { start, end, role }); + } else { + return false; + } + true +} diff --git a/crates/terminal/src/highlighting/rules.rs b/crates/terminal/src/highlighting/rules.rs index 710c1ed4..3971f9a9 100644 --- a/crates/terminal/src/highlighting/rules.rs +++ b/crates/terminal/src/highlighting/rules.rs @@ -1,6 +1,6 @@ //! Ordered field rules: specific messages win over structural tokens. use super::Role; -use regex::Regex; +use regex::{Match, Regex}; use std::{net::IpAddr, sync::LazyLock}; pub(super) struct Token { @@ -51,35 +51,42 @@ fn boundary(text: &str, start: usize, end: usize, address: bool) -> bool { pub(super) fn recognize(text: &str, start_complete: bool, end_complete: bool) -> Vec { let mut tokens = Vec::new(); for rule in RULES.iter() { - for captures in rule.regex.captures_iter(text) { - let whole = captures.get(0).expect("full match"); + let mut accept = |whole: Match<'_>, value: Match<'_>| { if (!start_complete && whole.start() == 0) || (!end_complete && whole.end() == text.len()) + || !boundary( + text, + whole.start(), + whole.end(), + rule.address || rule.role == Role::Version, + ) + || (rule.address && whole.as_str().parse::().is_err()) { - continue; + return false; } - if !boundary( - text, - whole.start(), - whole.end(), - rule.address || rule.role == Role::Version, - ) { - continue; - } - if rule.address && whole.as_str().parse::().is_err() { - continue; - } - let value = captures - .name("value") - .or_else(|| captures.name("number")) - .unwrap_or(whole); tokens.push(Token { start: value.start(), end: value.end(), role: rule.role, }); - if tokens.len() == MAX_TOKENS { - return tokens; + tokens.len() == MAX_TOKENS + }; + if rule.regex.captures_len() == 1 { + for whole in rule.regex.find_iter(text) { + if accept(whole, whole) { + return tokens; + } + } + } else { + for captures in rule.regex.captures_iter(text) { + let whole = captures.get(0).expect("full match"); + let value = captures + .name("value") + .or_else(|| captures.name("number")) + .unwrap_or(whole); + if accept(whole, value) { + return tokens; + } } } } diff --git a/crates/terminal/src/highlighting/tests.rs b/crates/terminal/src/highlighting/tests.rs index 70bb0036..91169c02 100644 --- a/crates/terminal/src/highlighting/tests.rs +++ b/crates/terminal/src/highlighting/tests.rs @@ -11,6 +11,91 @@ fn snapshot(text: &str, cols: u16, rows: u16) -> (Emulator, Frame, Highlights) { (emulator, frame, highlights) } +#[test] +fn scrolling_and_new_output_keep_the_same_highlights_as_a_fresh_viewport() { + let text = (0..50) + .map(|row| { + if row % 3 == 0 { + "WARN request failed while connecting to 192.0.2.20\r\n" + } else { + "INFO request ok\r\n" + } + }) + .collect::(); + let (mut emulator, mut frame, mut retained) = snapshot(&text, 24, 12); + for (scroll, output) in [ + (1, ""), + (4, ""), + (-2, ""), + (0, "ERROR another result\r\n"), + (-9, ""), + ] { + emulator.scroll(Scroll::Lines(scroll)); + emulator.advance(output.as_bytes()); + emulator.snapshot(&mut frame); + retained.update(&frame, emulator.generation(), true); + let mut fresh = Highlights::default(); + fresh.update(&frame, emulator.generation(), true); + for (index, cell) in frame.cells.iter().enumerate() { + assert_eq!(retained.role_at(index, cell), fresh.role_at(index, cell)); + } + } +} + +#[test] +fn restyling_unchanged_text_reprojects_semantic_roles() { + let (mut emulator, mut frame, mut highlights) = snapshot("🌙 ERROR 192.0.2.1", 32, 3); + for (output, expected) in [ + ("", Some(Role::Error)), + ("\x1b[1;5H\x1b[31mR\x1b[0m", None), + ("\x1b[1;5HR", Some(Role::Error)), + ] { + emulator.advance(output.as_bytes()); + emulator.snapshot(&mut frame); + highlights.update(&frame, emulator.paint_generation(), true); + assert_eq!(frame.row_text(0), "🌙 ERROR 192.0.2.1"); + assert_eq!(highlights.role_at(3, &frame.cells[3]), Some(Role::Error)); + assert_eq!(highlights.role_at(4, &frame.cells[4]), expected); + assert_eq!(highlights.role_at(5, &frame.cells[5]), Some(Role::Error)); + assert_eq!(highlights.role_at(9, &frame.cells[9]), Some(Role::Address)); + } +} + +#[test] +#[ignore = "run in release mode on a quiet host"] +fn measure_semantic_highlighting_on_changing_log_viewports() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let initial: String = (1..=75) + .map(|row| { + format!("\x1b[{row};1H2026-12-01T04:20:03 WARN pid={row} connection closed 192.0.2.1") + }) + .collect(); + for updated_rows in [1, 75] { + let (mut emulator, mut frame, mut highlights) = snapshot(&initial, 247, 75); + let mut samples = [0; 240]; + for (index, sample) in samples.iter_mut().enumerate() { + let output: String = (1..=updated_rows) + .map(|row| format!("\x1b[{row};1H2026-12-01T04:21:02 ERROR pid={index:06} connection closed 192.0.2.1")) + .collect(); + emulator.advance(output.as_bytes()); + emulator.snapshot(&mut frame); + let start = Instant::now(); + black_box(&mut highlights).update(black_box(&frame), emulator.paint_generation(), true); + *sample = start.elapsed().as_nanos(); + } + assert_eq!(highlights.role_at(20, &frame.cells[20]), Some(Role::Error)); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{updated_rows} changed rows, highlighting p50/p95 {} / {} ns", + samples[120], + samples[228], + ) + .unwrap(); + } +} + fn role(text: &str, needle: &str) -> Option { let (_, frame, highlights) = snapshot(text, 250, 2); let index = text[..text.find(needle).unwrap()].chars().count(); diff --git a/crates/terminal/src/recording.rs b/crates/terminal/src/recording.rs index 29075e93..ec0d7482 100644 --- a/crates/terminal/src/recording.rs +++ b/crates/terminal/src/recording.rs @@ -1,11 +1,9 @@ //! Output-only session recording presentation state. -use gpui_kit::Context; +use crate::terminal::{Terminal, TerminalEvent}; +use gpui_kit::{Context, Subscription}; use nocterm_session::recording::RecordingOptions; -use nocterm_store::{AppendHandle, RecordingRegistry}; -use std::{ - path::PathBuf, - sync::{Arc, Mutex}, -}; +use nocterm_store::{AppendHandle, AppendMetadataChanged, RecordingRegistry}; +use std::{path::PathBuf, sync::Arc}; #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct RecordingStatus { @@ -30,22 +28,12 @@ impl RecordingStatus { } } +#[derive(Default)] pub(crate) struct OutputRecording { options: nocterm_session::LoggingOptions, registry: Option>, - current: Option, - last_status: Arc>, -} - -impl Default for OutputRecording { - fn default() -> Self { - Self { - options: Default::default(), - registry: None, - current: None, - last_status: Arc::new(Mutex::new(RecordingStatus::default())), - } - } + current: Option<(AppendHandle, Subscription)>, + last_status: RecordingStatus, } impl OutputRecording { @@ -66,21 +54,20 @@ impl OutputRecording { } pub(crate) fn status(&self) -> Option { - let last = self - .last_status - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clone(); - if let Some(current) = &self.current { + let last = &self.last_status; + if let Some((current, _subscription)) = &self.current { let s = current.status(); Some(RecordingStatus { - path: s.path().cloned().or(last.path), - error: s.error().map(|e| e.to_string()).or(last.error), + path: s.path().cloned().or_else(|| last.path.clone()), + error: s + .error() + .map(|e| e.to_string()) + .or_else(|| last.error.clone()), finished: s.finished(), bytes: s.bytes().max(last.bytes), }) } else if last.path.is_some() || last.bytes > 0 || last.finished { - Some(last) + Some(last.clone()) } else { None } @@ -88,7 +75,7 @@ impl OutputRecording { pub(crate) fn start( &mut self, - cx: &mut Context, + cx: &mut Context, ) -> Result<(), nocterm_session::recording::RecordingError> { if self.is_active() { return Ok(()); @@ -103,22 +90,26 @@ impl OutputRecording { }; let handle = registry.open(rec_options, cx); - self.current = Some(handle); + let subscription = cx.subscribe(&handle.entity(), |_, _, _: &AppendMetadataChanged, cx| { + cx.emit(TerminalEvent::RecordingChanged); + }); + self.current = Some((handle, subscription)); cx.notify(); Ok(()) } - pub(crate) fn output(&mut self, bytes: &[u8], cx: &mut Context) { - if let Some(current) = &self.current { + pub(crate) fn output(&mut self, bytes: &[u8], cx: &mut Context) { + if let Some((current, _subscription)) = &self.current { current.output(bytes, cx); } } - pub(crate) fn stop(&mut self, cx: &mut Context) { - if let Some(current) = self.current.take() { + pub(crate) fn stop(&mut self, cx: &mut Context) { + if let Some((current, subscription)) = self.current.take() { + drop(subscription); current.stop(cx); let s = current.status(); - *self.last_status.lock().unwrap_or_else(|e| e.into_inner()) = RecordingStatus { + self.last_status = RecordingStatus { path: s.path().cloned(), error: s.error().map(|e| e.to_string()), finished: true, diff --git a/crates/terminal/src/settings_page/mod.rs b/crates/terminal/src/settings_page/mod.rs index 5a67ae93..16afc33d 100644 --- a/crates/terminal/src/settings_page/mod.rs +++ b/crates/terminal/src/settings_page/mod.rs @@ -81,11 +81,12 @@ impl TerminalSettingsPage { ) -> Self { let weak = cx.weak_entity(); let original_window = window.window_handle(); - let subscription = settings.observe(cx, move |cx| { - let _ = original_window.update(cx, |_, _, cx| { - let _ = weak.update(cx, |_, cx| cx.notify()); + let subscription = + settings.observe_section::(cx, move |cx| { + let _ = original_window.update(cx, |_, _, cx| { + let _ = weak.update(cx, |_, cx| cx.notify()); + }); }); - }); let mut this = Self { settings, fields: BTreeMap::new(), @@ -147,11 +148,12 @@ impl LocalShellSettingsPage { ) -> Self { let weak = cx.weak_entity(); let original_window = window.window_handle(); - let subscription = settings.observe(cx, move |cx| { - let _ = original_window.update(cx, |_, _, cx| { - let _ = weak.update(cx, |_, cx| cx.notify()); + let subscription = + settings.observe_section::(cx, move |cx| { + let _ = original_window.update(cx, |_, _, cx| { + let _ = weak.update(cx, |_, cx| cx.notify()); + }); }); - }); let mut this = Self { settings, fields: BTreeMap::new(), diff --git a/crates/terminal/src/terminal.rs b/crates/terminal/src/terminal.rs index 9dd9a36e..cc545bb7 100644 --- a/crates/terminal/src/terminal.rs +++ b/crates/terminal/src/terminal.rs @@ -20,8 +20,8 @@ use nocterm_session::{Secret, Session}; use nocterm_store::SettingsConfig; use nocterm_ui::{CursorShape, TerminalSettings}; use nocterm_vt::{ - Effect, Emulator, EmulatorOptions, Palette, Scroll, SearchDirection, SearchOptions, - SearchPoint, SearchProgress, SearchResult, TermSize, + Effect, Emulator, EmulatorOptions, Palette, Scroll, SearchAnchor, SearchDirection, + SearchOptions, SearchPoint, SearchProgress, SearchResult, TermSize, }; use nocterm_workspace::SessionSpec; @@ -40,8 +40,12 @@ pub enum Status { pub enum TerminalEvent { /// The status, the pending prompt or the title changed. Changed, - /// The screen changed. + /// Screen presentation needs a repaint. Output, + /// The recording file path or error changed. + RecordingChanged, + /// The negotiated input modes or input admission error changed. + InputChanged, /// The program rang the bell. Bell, /// A program requested a clipboard write; the view applies permission and focus checks. @@ -53,8 +57,10 @@ pub struct FindState { query: String, options: SearchOptions, searching: bool, - /// Counts are final when `searching` is false; active may be an early preview. + confirmed: bool, + /// Count and ordinal from the last completed search. Active may be a current preview. result: SearchResult, + anchor: Option, error: Option, } impl FindState { @@ -67,6 +73,9 @@ impl FindState { pub fn searching(&self) -> bool { self.searching } + pub(crate) fn confirmed(&self) -> bool { + self.confirmed + } pub fn result(&self) -> &SearchResult { &self.result } @@ -176,20 +185,23 @@ impl Terminal { recording: crate::OutputRecording::default(), credentials: crate::credentials::CredentialState::default(), screen: presentation::TerminalScreen::new(options), - _settings: deps.settings().observe(cx, move |cx| { - if let Some(terminal) = weak.upgrade() { - terminal.update(cx, |this, cx| { - let options = emulator_options( - this.deps - .settings() - .setting::(cx), - ); - this.screen.apply_options(options); - this.refresh_find(cx); - this.emit_output(cx); - }); - } - }), + _settings: deps + .settings() + .observe_section::(cx, move |cx| { + if let Some(terminal) = weak.upgrade() { + terminal.update(cx, |this, cx| { + let options = emulator_options( + this.deps + .settings() + .setting::(cx), + ); + if this.screen.apply_options(options) { + this.refresh_find(cx); + this.emit_output(cx); + } + }); + } + }), }; this.connect(cx); this @@ -392,6 +404,7 @@ impl Terminal { } fn close_session(&mut self) { + self.input.cancel_clipboard(); if let Some(session) = self.lifecycle.retire_session() { session.close(); } @@ -430,6 +443,7 @@ impl Terminal { Event::Output(bytes) => self.advance_output(&bytes, cx), Event::Restore(bytes) => self.restore_screen(&bytes, cx), Event::Prompt(prompt) => { + self.input.cancel_clipboard(); // A newer question supersedes an unanswered one, including an // identical retry. Views must discard the previous input state. self.lifecycle.accept_prompt(prompt); @@ -437,6 +451,7 @@ impl Terminal { cx.emit(TerminalEvent::Changed); } Event::Closed(reason) => { + self.input.cancel_clipboard(); let tail = self.input.decode(&[], true); self.recording.output(&tail, cx); self.recording.stop(cx); @@ -495,10 +510,9 @@ impl Terminal { self.screen.schedule_sync(cx); } fn finish_sync(&mut self, cx: &mut Context) { + let before = self.output_state(); if let Some(effects) = self.screen.finish_sync() { - self.apply(effects, cx); - self.refresh_find(cx); - self.emit_output(cx); + self.publish_output(before, effects, cx); } else { self.schedule_sync(cx); } diff --git a/crates/terminal/src/terminal/input.rs b/crates/terminal/src/terminal/input.rs index 43ea1425..a7ea44b4 100644 --- a/crates/terminal/src/terminal/input.rs +++ b/crates/terminal/src/terminal/input.rs @@ -3,9 +3,8 @@ use crate::file_drop::FileDropError; use super::{Terminal, TerminalEvent}; use crate::credentials::answering_credential; -use gpui_kit::{App, Context}; +use gpui_kit::{App, Context, Task}; use nocterm_session::{CredentialStoreError, HostKeyDecision, Prompt, Secret, SecretRequest}; -use nocterm_vt::encode_paste; use nocterm_workspace::{LiveCommandLease, LocalDirectoryError, TerminalError}; use std::{ path::Path, @@ -16,18 +15,28 @@ use std::{ }; use nocterm_session::{Charset, TextEncodingError}; -use nocterm_vt::{Modes, ShellIntegration, TextCodec}; +use nocterm_vt::{Modes, ShellInput, ShellIntegration, TextCodec}; use std::cell::RefCell; +mod clipboard; +use clipboard::{ClipboardQueue, ClipboardRead, clipboard_text, take_ready_read}; + #[derive(Clone, Copy)] enum SubmissionPolicy { User, Agent, Protocol, } +#[derive(Clone, Copy)] +enum InputPresentation { + None, + Edit, + FileDrop, +} struct PreparedInput { bytes: Vec, policy: SubmissionPolicy, + presentation: InputPresentation, } #[derive(Default)] @@ -53,6 +62,7 @@ pub(super) struct TerminalInput { input_error: RefCell>, integration: RefCell, agent: RefCell, + clipboard: RefCell, shell_program: String, shell_syntax: Option, } @@ -64,6 +74,7 @@ impl TerminalInput { input_error: RefCell::default(), integration: RefCell::default(), agent: RefCell::default(), + clipboard: RefCell::default(), shell_program: String::new(), shell_syntax: None, } @@ -90,9 +101,13 @@ impl TerminalInput { self.shell_syntax = syntax; } pub(super) fn revoke(&self) { + self.cancel_clipboard(); self.agent.borrow_mut().revoke(); *self.integration.borrow_mut() = ShellIntegration::default(); } + pub(super) fn cancel_clipboard(&self) { + self.clipboard.borrow_mut().clear(); + } pub(super) fn decode(&mut self, bytes: &[u8], last: bool) -> Vec { self.codec.decode(bytes, last) } @@ -107,9 +122,19 @@ impl TerminalInput { .clone() .or_else(|| self.input_error.borrow().clone()) } + pub(super) fn has_input_error(&self) -> bool { + self.input_error.borrow().is_some() + } pub(super) fn set_text_error(&mut self, error: Option) { self.text_error = error; } + fn record_encoding( + &mut self, + prepared: Result, + ) -> Option { + self.set_text_error(prepared.as_ref().err().map(ToString::to_string)); + prepared.ok() + } fn shell_syntax(&self) -> Option { self.shell_syntax } @@ -151,6 +176,7 @@ impl TerminalInput { Ok(PreparedInput { bytes: self.codec.encode(&format!("{command}\r"))?, policy: SubmissionPolicy::User, + presentation: InputPresentation::None, }) } fn prepare_agent( @@ -186,6 +212,7 @@ impl TerminalInput { Ok(PreparedInput { bytes: self.codec.encode(&text)?, policy: SubmissionPolicy::Agent, + presentation: InputPresentation::None, }) } fn prepare_paste( @@ -193,30 +220,39 @@ impl TerminalInput { text: &str, execute: bool, modes: Modes, - ) -> Result { - let mut paste = encode_paste(text, modes); - if execute { - paste.push(b'\r'); - } - let text = std::str::from_utf8(&paste)?; + presentation: InputPresentation, + ) -> Result { Ok(PreparedInput { - bytes: self.codec.encode(text)?, + bytes: self.codec.encode_paste(text, modes, execute)?, policy: SubmissionPolicy::User, + presentation, }) } - fn prepare_text(&self, text: &str) -> Result { + fn prepare_text( + &self, + text: &str, + presentation: InputPresentation, + ) -> Result { Ok(PreparedInput { bytes: self.codec.encode(text)?, policy: SubmissionPolicy::User, + presentation, }) } - fn commit_submission(&self, prepared: &PreparedInput, accepted: bool) { - if accepted && !matches!(prepared.policy, SubmissionPolicy::Protocol) { - self.integration.borrow_mut().input(&prepared.bytes); + fn submit(&self, session: &nocterm_session::Session, prepared: PreparedInput) -> bool { + let input = (!matches!(prepared.policy, SubmissionPolicy::Protocol)) + .then(|| ShellInput::classify(&prepared.bytes)); + let accepted = session.input(prepared.bytes); + if accepted && let Some(input) = input { + self.integration.borrow_mut().admit_input(input); if matches!(prepared.policy, SubmissionPolicy::User) { self.agent.borrow_mut().revoke(); } } + self.record_admission(accepted); + accepted + } + fn record_admission(&self, accepted: bool) { *self.input_error.borrow_mut() = if accepted { None } else { @@ -235,12 +271,14 @@ impl Terminal { pub fn change_directory( &mut self, path: &Path, - cx: &mut Context, + _cx: &mut Context, ) -> Result<(), LocalDirectoryError> { if !self.is_local() || !self.is_connected() { return Err(LocalDirectoryError::NotConnectedLocal); } - let _ = cx; + if self.input.clipboard.borrow().pending() { + return Err(LocalDirectoryError::QueueFull); + } let prepared = self .input .prepare_directory(path, self.emulator().modes().alt_screen)?; @@ -258,8 +296,6 @@ impl Terminal { self.input.shell_program() } - // ── Input ──────────────────────────────────────────────────────────────── - pub(crate) fn agent_prompt_state(&self) -> (Option, bool) { self.input.prompt_state() } @@ -273,6 +309,9 @@ impl Terminal { if !self.is_connected() || self.prompt().is_some() { return Err(TerminalError::Unavailable); } + if self.input.clipboard.borrow().pending() { + return Err(TerminalError::InputQueueRejected); + } let prepared = self.input .prepare_agent(text, command, self.emulator().modes().alt_screen)?; @@ -314,39 +353,148 @@ impl Terminal { } else { SubmissionPolicy::Protocol }; - self.submit_prepared(PreparedInput { bytes, policy }) + self.submit_prepared(PreparedInput { + bytes, + policy, + presentation: InputPresentation::None, + }) } fn submit_prepared(&self, prepared: PreparedInput) -> bool { if !self.is_connected() { return false; } + if matches!(prepared.policy, SubmissionPolicy::User) + && self.input.clipboard.borrow().pending() + { + let accepted = self.input.clipboard.borrow_mut().enqueue(prepared); + self.input.record_admission(accepted); + return accepted; + } + self.submit_to_session(prepared) + } + + fn submit_to_session(&self, prepared: PreparedInput) -> bool { let Some(session) = self.lifecycle.session() else { return false; }; - let accepted = session.input(prepared.bytes.clone()); - self.input.commit_submission(&prepared, accepted); - accepted + self.input.submit(session, prepared) } /// Encodes only user text. Protocol replies and mouse messages use send unchanged. pub fn send_text(&mut self, text: &str, cx: &mut Context) -> bool { - let previous = self.text_error(); - let accepted = match self.input.prepare_text(text) { - Ok(prepared) => { - self.input.set_text_error(None); - self.submit_prepared(prepared) + self.submit_user_text(self.input.prepare_text(text, InputPresentation::None), cx) + } + + pub(crate) fn edit_text(&mut self, text: &str, cx: &mut Context) -> bool { + self.submit_user_text(self.input.prepare_text(text, InputPresentation::Edit), cx) + } + + pub(crate) fn paste_clipboard( + &mut self, + mut read: Task, + cx: &mut Context, + ) { + if !self.is_connected() || self.prompt().is_some() { + return; + } + let modes = self.emulator().modes(); + if let Some(result) = take_ready_read(&mut read) { + if let Some(item) = result.ok().flatten() + && let Some(text) = clipboard_text(&item) + { + let prepared = + self.input + .prepare_paste(&text, false, modes, InputPresentation::Edit); + self.submit_user_text(prepared, cx); } - Err(error) => { - self.input.set_text_error(Some(error.to_string())); - false + return; + } + if !self.input.clipboard.borrow_mut().begin(|id| { + cx.spawn(async move |this, cx| { + let result = read.await; + let _ = this.update(cx, |terminal, cx| { + terminal.finish_clipboard(id, modes, result, cx) + }); + }) + }) { + self.input.record_admission(false); + cx.emit(TerminalEvent::Changed); + } + } + + fn finish_clipboard( + &mut self, + id: u64, + modes: Modes, + result: ClipboardRead, + cx: &mut Context, + ) { + if !self.input.clipboard.borrow().contains(id) { + return; + } + let previous = self.text_error(); + let prepared = result + .ok() + .flatten() + .as_ref() + .and_then(clipboard_text) + .and_then(|text| { + let prepared = + self.input + .prepare_paste(&text, false, modes, InputPresentation::Edit); + self.input.record_encoding(prepared) + }); + let admitted = self.input.clipboard.borrow_mut().resolve(id, prepared); + loop { + let input = self.input.clipboard.borrow_mut().pop_ready(); + let Some(input) = input else { break }; + let presentation = input.presentation; + if self.submit_to_session(input) { + self.present_input(presentation, cx); } - }; + } + if !admitted { + self.input.record_admission(false); + } + if previous != self.text_error() { + cx.emit(TerminalEvent::Changed); + } + } + + fn submit_user_text( + &mut self, + prepared: Result, + cx: &mut Context, + ) -> bool { + let previous = self.text_error(); + let accepted = self + .input + .record_encoding(prepared) + .is_some_and(|prepared| self.submit_presented(prepared, cx)); if previous != self.text_error() { cx.emit(TerminalEvent::Changed); } accepted } + fn submit_presented(&mut self, prepared: PreparedInput, cx: &mut Context) -> bool { + let presentation = prepared.presentation; + let pending = self.input.clipboard.borrow().pending(); + let accepted = self.submit_prepared(prepared); + if accepted && !pending { + self.present_input(presentation, cx); + } + accepted + } + + fn present_input(&mut self, presentation: InputPresentation, cx: &mut Context) { + match presentation { + InputPresentation::None => {} + InputPresentation::Edit => self.prepare_input(cx), + InputPresentation::FileDrop => self.complete_native_paste(cx), + } + } + /// Paste a user-selected snippet in one transport submission. Shell integration /// is optional: Windows shells and SSH sessions follow the normal paste protocol. pub(crate) fn paste_snippet( @@ -375,7 +523,7 @@ impl Terminal { } else { text }; - self.send_paste(text, execute, cx) + self.send_paste(text, execute, InputPresentation::None, cx) } /// Explorer drops follow native paste, including programs in the alternate screen. @@ -390,7 +538,7 @@ impl Terminal { if text.is_empty() || text.len() > 256 * 1024 || text.chars().any(char::is_control) { return Err(FileDropError::UnsafeSelection); } - self.send_paste(text, false, cx) + self.send_paste(text, false, InputPresentation::FileDrop, cx) .map_err(FileDropError::from) } @@ -398,12 +546,13 @@ impl Terminal { &mut self, text: &str, execute: bool, + presentation: InputPresentation, cx: &mut Context, ) -> Result<(), TerminalError> { - let prepared = self - .input - .prepare_paste(text, execute, self.emulator().modes())?; - if !self.submit_prepared(prepared) { + let prepared = + self.input + .prepare_paste(text, execute, self.emulator().modes(), presentation)?; + if !self.submit_presented(prepared, cx) { return Err(TerminalError::PasteQueueRejected); } cx.emit(TerminalEvent::Changed); diff --git a/crates/terminal/src/terminal/input/clipboard.rs b/crates/terminal/src/terminal/input/clipboard.rs new file mode 100644 index 00000000..02ab2bd8 --- /dev/null +++ b/crates/terminal/src/terminal/input/clipboard.rs @@ -0,0 +1,121 @@ +//! Holds input behind pending clipboard reads for one connection. + +use super::PreparedInput; +use gpui_kit::{ClipboardEntry, ClipboardItem, ClipboardReadError, Task}; +use std::{ + borrow::Cow, + collections::VecDeque, + future::Future as _, + pin::Pin, + task::{Context, Poll, Waker}, +}; + +pub(super) type ClipboardRead = Result, ClipboardReadError>; + +pub(super) fn take_ready_read(read: &mut Task) -> Option { + if read.is_ready() + && let Poll::Ready(result) = Pin::new(read).poll(&mut Context::from_waker(Waker::noop())) + { + return Some(result); + } + None +} + +pub(super) fn clipboard_text(item: &ClipboardItem) -> Option> { + match item.entries() { + [ClipboardEntry::String(entry)] if !entry.text.is_empty() => { + Some(Cow::Borrowed(&entry.text)) + } + _ => item.text().map(Cow::Owned), + } +} + +const MAX_ENTRIES: usize = 64; +const MAX_BYTES: usize = 4 * 1024 * 1024; + +enum Input { + Reading(u64, Task<()>), + Ready(Option), +} + +#[derive(Default)] +pub(super) struct ClipboardQueue { + entries: VecDeque, + bytes: usize, + next_read: u64, +} + +impl ClipboardQueue { + pub(super) fn pending(&self) -> bool { + !self.entries.is_empty() + } + + pub(super) fn clear(&mut self) { + self.entries.clear(); + self.bytes = 0; + } + + pub(super) fn begin(&mut self, spawn: impl FnOnce(u64) -> Task<()>) -> bool { + if self.entries.len() == MAX_ENTRIES { + return false; + } + self.next_read = self.next_read.wrapping_add(1); + self.entries + .push_back(Input::Reading(self.next_read, spawn(self.next_read))); + true + } + + pub(super) fn enqueue(&mut self, input: PreparedInput) -> bool { + if self.entries.len() == MAX_ENTRIES || !self.reserve(input.bytes.len()) { + return false; + } + self.entries.push_back(Input::Ready(Some(input))); + true + } + + pub(super) fn contains(&self, id: u64) -> bool { + self.entries + .iter() + .any(|entry| matches!(entry, Input::Reading(pending, _) if *pending == id)) + } + + pub(super) fn resolve(&mut self, id: u64, mut input: Option) -> bool { + let Some(index) = self + .entries + .iter() + .position(|entry| matches!(entry, Input::Reading(pending, _) if *pending == id)) + else { + return true; + }; + let accepted = input + .as_ref() + .is_none_or(|input| self.reserve(input.bytes.len())); + if !accepted { + input = None; + } + if let Input::Reading(_, task) = + std::mem::replace(&mut self.entries[index], Input::Ready(input)) + { + task.detach(); + } + accepted + } + + pub(super) fn pop_ready(&mut self) -> Option { + while matches!(self.entries.front(), Some(Input::Ready(_))) { + if let Some(Input::Ready(Some(input))) = self.entries.pop_front() { + self.bytes -= input.bytes.len(); + return Some(input); + } + } + None + } + + fn reserve(&mut self, bytes: usize) -> bool { + if bytes > MAX_BYTES - self.bytes { + return false; + } + self.bytes += bytes; + true + } +} diff --git a/crates/terminal/src/terminal/input/tests.rs b/crates/terminal/src/terminal/input/tests.rs index 21221a0f..fdbf1d92 100644 --- a/crates/terminal/src/terminal/input/tests.rs +++ b/crates/terminal/src/terminal/input/tests.rs @@ -6,6 +6,8 @@ use nocterm_session::{ }; use nocterm_workspace::SessionSpec; +mod clipboard; + fn fixture(cx: &mut TestAppContext, local: bool) -> (Entity, SessionDriver) { fixture_with_charset(cx, local, Charset::Utf8) } diff --git a/crates/terminal/src/terminal/input/tests/clipboard.rs b/crates/terminal/src/terminal/input/tests/clipboard.rs new file mode 100644 index 00000000..7ed15e19 --- /dev/null +++ b/crates/terminal/src/terminal/input/tests/clipboard.rs @@ -0,0 +1,109 @@ +use super::*; +use futures::channel::oneshot; +use gpui_kit::ClipboardItem; + +fn start_paste( + terminal: &Entity, + cx: &mut TestAppContext, +) -> oneshot::Sender { + let (send, receive) = oneshot::channel(); + terminal.update(cx, |terminal, cx| { + let read = cx.spawn(async move |_, _| receive.await.unwrap_or(Ok(None))); + terminal.paste_clipboard(read, cx); + }); + cx.run_until_parked(); + send +} + +#[gpui_kit::test] +fn delayed_pastes_and_keyboard_bytes_arrive_in_action_order(cx: &mut TestAppContext) { + let (terminal, driver) = fixture(cx, false); + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Output(b"\x1b[?2004h".to_vec()), cx); + }); + let first = start_paste(&terminal, cx); + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Output(b"\x1b[?2004l".to_vec()), cx); + assert!(terminal.edit_text("b", cx)); + }); + let second = start_paste(&terminal, cx); + terminal.update(cx, |terminal, _| assert!(terminal.send(b"c".to_vec()))); + + second + .send(Ok(Some(ClipboardItem::new_string("second".into())))) + .unwrap(); + cx.run_until_parked(); + assert!(driver.next_command().now_or_never().is_none()); + first + .send(Ok(Some(ClipboardItem::new_string("first".into())))) + .unwrap(); + cx.run_until_parked(); + assert_eq!(sent(&driver), b"\x1b[200~first\x1b[201~"); + assert_eq!(sent(&driver), b"b"); + assert_eq!(sent(&driver), b"second"); + assert_eq!(sent(&driver), b"c"); + assert!(driver.next_command().now_or_never().is_none()); +} + +#[gpui_kit::test] +fn cancelled_selection_read_does_not_block_following_keys(cx: &mut TestAppContext) { + let (terminal, driver) = fixture(cx, false); + let read = start_paste(&terminal, cx); + terminal.update(cx, |terminal, cx| assert!(terminal.edit_text("b", cx))); + read.send(Err(gpui_kit::ClipboardReadError::Unavailable)) + .unwrap(); + cx.run_until_parked(); + assert_eq!(sent(&driver), b"b"); + assert!(driver.next_command().now_or_never().is_none()); +} + +#[gpui_kit::test] +fn disconnect_cancels_delayed_paste_and_queued_keyboard_bytes(cx: &mut TestAppContext) { + let (terminal, driver) = fixture(cx, false); + let read = start_paste(&terminal, cx); + terminal.update(cx, |terminal, cx| { + assert!(terminal.edit_text("b", cx)); + terminal.disconnect(cx); + }); + cx.run_until_parked(); + assert!(read.is_canceled()); + assert!(matches!( + driver.next_command().now_or_never().flatten(), + Some(Command::Close) | None + )); +} + +#[gpui_kit::test] +fn terminal_replies_to_the_program_during_a_pending_clipboard_read(cx: &mut TestAppContext) { + let (terminal, driver) = fixture(cx, false); + let read = start_paste(&terminal, cx); + terminal.update(cx, |terminal, cx| { + assert!(terminal.edit_text("b", cx)); + terminal.handle_event(Event::Output(b"\x1b[5n".to_vec()), cx); + }); + assert_eq!(sent(&driver), b"\x1b[0n"); + read.send(Ok(None)).unwrap(); + cx.run_until_parked(); + assert_eq!(sent(&driver), b"b"); +} + +#[gpui_kit::test] +fn clipboard_wait_bounds_queued_keys_and_keeps_accepted_bytes(cx: &mut TestAppContext) { + let (terminal, driver) = fixture(cx, false); + let read = start_paste(&terminal, cx); + terminal.update(cx, |terminal, cx| { + for _ in 0..63 { + assert!(terminal.edit_text("a", cx)); + } + assert!(!terminal.edit_text("b", cx)); + assert!(terminal.text_error().is_some()); + }); + read.send(Ok(Some(ClipboardItem::new_string("paste".into())))) + .unwrap(); + cx.run_until_parked(); + assert_eq!(sent(&driver), b"paste"); + for _ in 0..63 { + assert_eq!(sent(&driver), b"a"); + } + assert!(driver.next_command().now_or_never().is_none()); +} diff --git a/crates/terminal/src/terminal/local_tests.rs b/crates/terminal/src/terminal/local_tests.rs index fb7f2420..8f73f574 100644 --- a/crates/terminal/src/terminal/local_tests.rs +++ b/crates/terminal/src/terminal/local_tests.rs @@ -487,3 +487,88 @@ fn command_completion_effect_observes_closed_state_and_retired_prompt_authority( ); } } + +#[gpui_kit::test] +#[ignore = "manual release profiling fixture"] +fn measure_unrelated_terminal_settings_fanout(cx: &mut TestAppContext) { + let count: usize = std::env::var("NOCTERM_PROFILE_TERMINALS") + .unwrap_or_else(|_| "128".into()) + .parse() + .unwrap(); + let installed = command_dependencies(cx); + let terminals = cx.update(|cx| { + (0..count) + .map(|_| cx.new(|cx| Terminal::new_local(installed.clone(), cx))) + .collect::>() + }); + cx.run_until_parked(); + let settings = installed.settings(); + for sample in 0..7 { + let start = std::time::Instant::now(); + for step in 0..128 { + cx.update(|cx| { + settings + .update::(cx, move |s| { + s.program = Some( + if step % 2 == 0 { + "/bin/bash" + } else { + "/bin/sh" + } + .into(), + ); + }) + .now_or_never() + .unwrap() + .unwrap(); + }); + } + use std::io::Write as _; + writeln!( + std::io::stdout().lock(), + "sample={sample} terminals={count} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); + } + cx.update(|cx| assert_eq!(settings.revision(cx), 7 * 128)); + assert_eq!(terminals.len(), count); +} + +#[gpui_kit::test] +fn retained_terminal_applies_cursor_settings_after_unrelated_edits(cx: &mut TestAppContext) { + let installed = command_dependencies(cx); + let terminal = cx.update(|cx| cx.new(|cx| Terminal::new_local(installed.clone(), cx))); + cx.run_until_parked(); + let before = cx.update(|cx| terminal.read(cx).emulator().paint_generation()); + cx.update(|cx| { + installed + .settings() + .update::(cx, |s| { + s.program = Some("/bin/sh".into()); + }) + .now_or_never() + .unwrap() + .unwrap(); + }); + cx.update(|cx| { + assert_eq!(terminal.read(cx).emulator().paint_generation(), before); + installed + .settings() + .update::(cx, |s| { + s.cursor_shape = CursorShape::Underline; + }) + .now_or_never() + .unwrap() + .unwrap(); + }); + cx.update(|cx| { + let emulator = terminal.read(cx).emulator(); + let mut frame = nocterm_vt::Frame::default(); + emulator.snapshot(&mut frame); + assert_eq!( + frame.cursor.unwrap().shape, + nocterm_vt::CursorShape::Underline + ); + }); +} diff --git a/crates/terminal/src/terminal/output.rs b/crates/terminal/src/terminal/output.rs index eb26b848..248da892 100644 --- a/crates/terminal/src/terminal/output.rs +++ b/crates/terminal/src/terminal/output.rs @@ -2,6 +2,13 @@ use super::{Terminal, TerminalEvent}; use gpui_kit::Context; +pub(super) struct OutputState { + paint: u64, + search: u64, + modes: nocterm_vt::Modes, + input_error: bool, +} + impl Terminal { pub(super) fn apply_session_batch( &mut self, @@ -24,17 +31,10 @@ impl Terminal { if self.input.advance_integration(&bytes) { cx.emit(TerminalEvent::Changed); } - let alt_screen = self.emulator().modes().alt_screen; + let before = self.output_state(); let effects = self.screen.advance(&bytes); - self.apply(effects, cx); - if self.emulator().modes().alt_screen != alt_screen { - // Panels cache command availability. Screen output by itself is - // visual; entering or leaving a full-screen program changes it. - cx.emit(TerminalEvent::Changed); - } + self.publish_output(before, effects, cx); self.schedule_sync(cx); - self.refresh_find(cx); - self.emit_output(cx); } /// Paints the screen the host holds. The bytes are a picture, not output of /// the program: they are not recorded, and the decoder starts afresh so a @@ -124,4 +124,39 @@ impl Terminal { pub(super) fn refresh_find(&mut self, cx: &mut Context) { self.screen.refresh_find(cx); } + + pub(super) fn output_state(&self) -> OutputState { + let emulator = self.emulator(); + OutputState { + paint: emulator.paint_generation(), + search: emulator.search_generation(), + modes: emulator.modes(), + input_error: self.input.has_input_error(), + } + } + + pub(super) fn publish_output( + &mut self, + before: OutputState, + effects: Vec, + cx: &mut Context, + ) { + self.apply(effects, cx); + let after = self.output_state(); + if before.modes.alt_screen != after.modes.alt_screen { + // Panels cache command availability across full-screen transitions. + cx.emit(TerminalEvent::Changed); + } + let revision = self.display_revision(); + if before.search != after.search { + self.refresh_find(cx); + } + if before.paint != after.paint { + if revision == self.display_revision() { + self.emit_output(cx); + } + } else if before.modes != after.modes || before.input_error != after.input_error { + cx.emit(TerminalEvent::InputChanged); + } + } } diff --git a/crates/terminal/src/terminal/presentation.rs b/crates/terminal/src/terminal/presentation.rs index 14c30194..119fdde6 100644 --- a/crates/terminal/src/terminal/presentation.rs +++ b/crates/terminal/src/terminal/presentation.rs @@ -8,7 +8,7 @@ pub(super) struct TerminalScreen { find_task: Option>, program_title: Option, sync_timer: Option>, - navigation: Option<(u64, Vec)>, + completed_scan: Option, } impl TerminalScreen { pub(super) fn new(options: EmulatorOptions) -> Self { @@ -19,7 +19,7 @@ impl TerminalScreen { find_task: None, program_title: None, sync_timer: None, - navigation: None, + completed_scan: None, } } pub(super) fn emulator(&self) -> &Emulator { @@ -38,8 +38,8 @@ impl TerminalScreen { self.program_title = title; true } - pub(super) fn apply_options(&mut self, options: EmulatorOptions) { - self.emulator.set_options(options); + pub(super) fn apply_options(&mut self, options: EmulatorOptions) -> bool { + self.emulator.set_options(options) } pub(super) fn set_palette(&mut self, palette: Palette) { self.emulator.set_palette(palette); @@ -56,7 +56,11 @@ impl TerminalScreen { pub(super) fn restore(&mut self, bytes: &[u8]) -> Vec { self.emulator.reset(); self.find_task = None; + self.completed_scan = None; self.find.searching = false; + self.find.confirmed = false; + self.find.result = SearchResult::default(); + self.find.anchor = None; self.sync_timer = None; self.program_title = None; self.emulator @@ -124,8 +128,10 @@ impl TerminalScreen { cx: &mut Context, ) -> bool { let scrolled = scroll != 0 && self.emulator.scroll(Scroll::Lines(scroll)); - self.emulator.update_selection(at, side); - self.emit_output(cx); + let selection_changed = self.emulator.update_selection(at, side); + if scrolled || selection_changed { + self.emit_output(cx); + } scrolled } pub(super) fn schedule_sync(&mut self, cx: &mut Context) { @@ -171,7 +177,8 @@ impl TerminalScreen { .collect(), ..Default::default() }; - self.scan_find(direction, anchor, Duration::ZERO, cx); + let anchor = anchor.map(|point| self.emulator.search_anchor(point)); + self.scan_find(direction, anchor, None, Duration::ZERO, cx); } pub(super) fn set_find_options(&mut self, options: SearchOptions, cx: &mut Context) { @@ -179,43 +186,57 @@ impl TerminalScreen { return; } self.find.options = options; - let anchor = self.find.result.active.map(|found| found.start); - self.scan_find(SearchDirection::Stay, anchor, Duration::ZERO, cx); + self.scan_find( + SearchDirection::Stay, + self.find.anchor, + None, + Duration::ZERO, + cx, + ); } pub(super) fn find_next(&mut self, previous: bool, cx: &mut Context) { - if let Some((generation, matches)) = &self.navigation - && *generation == self.emulator.generation() - && !matches.is_empty() - { - let current = self.find.result.ordinal.saturating_sub(1) as usize; - let index = if previous { - (current + matches.len() - 1) % matches.len() + let result = self.find.result; + let target = self.completed_scan.as_ref().and_then(|scan| { + if !scan.is_complete_for(&self.emulator) || result.count == 0 { + return None; + } + let ordinal = if previous { + if result.ordinal == 1 { + result.count + } else { + result.ordinal - 1 + } + } else if result.ordinal == result.count { + 1 } else { - (current + 1) % matches.len() + result.ordinal + 1 }; - let found = matches[index]; + Some((ordinal, scan.navigation_match(&self.emulator, ordinal))) + }); + if let Some((ordinal, Some(found))) = target { self.find.result.active = Some(found); - self.find.result.ordinal = index as u64 + 1; + self.find.result.ordinal = ordinal; + self.find.anchor = Some(self.emulator.search_anchor(found.start)); self.emulator.show_search_match(found); self.emit_output(cx); return; } - let anchor = self.find.result.active.map(|m| m.start); self.scan_find( if previous { SearchDirection::Previous } else { SearchDirection::Next }, - anchor, + self.find.anchor, + target.map(|(ordinal, _)| ordinal), Duration::ZERO, cx, ); } pub(super) fn clear_find(&mut self, cx: &mut Context) { - self.navigation = None; + self.completed_scan = None; self.find_task = None; self.find = FindState { options: self.find.options, @@ -234,43 +255,70 @@ impl TerminalScreen { if self.find.searching { return; } - let anchor = self.find.result.active.map(|m| m.start); self.scan_find( SearchDirection::Stay, - anchor, + self.find.anchor, + None, Duration::from_millis(100), cx, ); } - pub(super) fn scan_find( + fn scan_find( &mut self, direction: SearchDirection, - anchor: Option, + anchor: Option, + ordinal: Option, delay: Duration, cx: &mut Context, ) { self.find_task = None; - self.navigation = None; + let previous = self.completed_scan.take(); + let automatic = !delay.is_zero(); self.find.error = None; - self.find.result = SearchResult::default(); + if !automatic { + self.find.confirmed = false; + self.find.result = SearchResult::default(); + } + self.find.result.active = None; + self.find.anchor = anchor; self.emulator.clear_search(); if self.find.query.is_empty() { self.find.searching = false; - self.find.result = SearchResult::default(); + self.find.anchor = None; self.emit_output(cx); return; } - let scan = match self.emulator.search_with_options( - &self.find.query, - self.find.options, - direction, - anchor, - ) { + let anchor_point = self.resolve_find_anchor(anchor); + let query = &self.find.query; + let options = self.find.options; + let retained = previous + .filter(|_| automatic) + .and_then(|completed| completed.into_refresh(&self.emulator, anchor_point)); + let reused = retained.is_some(); + let scan = if let Some(scan) = retained { + Ok(scan) + } else if let Some(ordinal) = ordinal { + nocterm_vt::SearchScan::navigate( + &self.emulator, + query, + options, + direction, + anchor_point, + ordinal, + ) + } else { + self.emulator + .search_with_options(query, options, direction, anchor_point) + }; + let scan = match scan { Ok(scan) => scan, Err(error) => { self.find.error = Some(error.to_string()); + self.find.confirmed = false; + self.find.result = SearchResult::default(); self.find.searching = false; + self.find.anchor = None; self.emit_output(cx); return; } @@ -279,54 +327,61 @@ impl TerminalScreen { self.emit_output(cx); self.find_task = Some( SearchRun { - scan, - direction, + scan: Some(scan), anchor, - restart: delay != Duration::ZERO, + reuse_prefix: reused, + restart: automatic, previewed: None, } .spawn(delay, cx), ); } + fn resolve_find_anchor(&self, saved: Option) -> Option { + saved.and_then(|anchor| self.emulator.resolve_search_anchor(anchor)) + } + fn step_find(&mut self, run: &mut SearchRun, cx: &mut Context) -> SearchProgress { if run.restart { - let Ok(fresh) = self.emulator.search_with_options( - &self.find.query, - self.find.options, - run.direction, - run.anchor, - ) else { - return SearchProgress::Invalidated; - }; - run.scan = fresh; + let point = self.resolve_find_anchor(run.anchor); + if !(run.reuse_prefix && run.scan().refresh_retained(&self.emulator, point)) { + run.reuse_prefix = false; + run.scan().restart(&self.emulator, point); + } run.restart = false; run.previewed = None; } - let progress = run.scan.step(&self.emulator, 4_096); + let progress = run.scan().step(&self.emulator, 4_096); if matches!(progress, SearchProgress::Searching) - && let Some(found) = run.scan.provisional() + && let Some(found) = run.scan().provisional() && run.previewed != Some(found) { run.previewed = Some(found); self.find.result.active = Some(found); + self.find.anchor = Some(self.emulator.search_anchor(found.start)); self.emulator.show_search_match(found); self.emit_output(cx); } if let SearchProgress::Failed(error) = &progress { self.find.error = Some(error.to_string()); + self.find.confirmed = false; self.find.result = SearchResult::default(); self.find.searching = false; + self.find.anchor = None; self.find_task = None; self.emulator.clear_search(); self.emit_output(cx); } if let SearchProgress::Complete(result) = progress { - self.navigation = run + self.completed_scan = run .scan - .take_navigation_matches() - .map(|matches| (self.emulator.generation(), matches)); + .take() + .and_then(nocterm_vt::SearchScan::into_completed); + self.find.confirmed = true; self.find.result = result; + self.find.anchor = result + .active + .map(|active| self.emulator.search_anchor(active.start)); self.find.searching = false; self.find_task = None; if let Some(active) = result.active @@ -340,13 +395,17 @@ impl TerminalScreen { } } struct SearchRun { - scan: nocterm_vt::SearchScan, - direction: SearchDirection, - anchor: Option, + scan: Option, + reuse_prefix: bool, + anchor: Option, restart: bool, previewed: Option, } impl SearchRun { + fn scan(&mut self) -> &mut nocterm_vt::SearchScan { + self.scan.as_mut().expect("active find task owns its scan") + } + fn spawn(mut self, delay: Duration, cx: &mut Context) -> Task<()> { cx.spawn(async move |this, cx| { cx.background_executor().timer(delay).await; @@ -358,8 +417,9 @@ impl SearchRun { .background_executor() .spawn(async move { work.run() }) .await; - let accepted = this - .update(cx, |this, _| self.scan.accept_work(this.emulator(), result)); + let accepted = this.update(cx, |this, _| { + self.scan().accept_work(this.emulator(), result) + }); if matches!(accepted, Ok(SearchProgress::Invalidated)) { self.restart = true; cx.background_executor() diff --git a/crates/terminal/src/terminal/pump.rs b/crates/terminal/src/terminal/pump.rs index 0308e8ef..91654db8 100644 --- a/crates/terminal/src/terminal/pump.rs +++ b/crates/terminal/src/terminal/pump.rs @@ -68,12 +68,14 @@ fn drain(first: Pending, mut next: impl FnMut() -> Option) -> (Vec break; }; match pending.event { - Event::Output(output) => { + Event::Output(mut output) => { let available = output.len() - pending.offset; let take = available.min(OUTPUT_BATCH_BYTES - bytes); let slice = &output[pending.offset..pending.offset + take]; if let Some(Event::Output(joined)) = batch.last_mut() { joined.extend_from_slice(slice); + } else if take == output.len() { + batch.push(Event::Output(std::mem::take(&mut output))); } else { batch.push(Event::Output(slice.to_vec())); } diff --git a/crates/terminal/src/terminal/pump/tests.rs b/crates/terminal/src/terminal/pump/tests.rs index 5f0364e9..0fce4ae0 100644 --- a/crates/terminal/src/terminal/pump/tests.rs +++ b/crates/terminal/src/terminal/pump/tests.rs @@ -26,6 +26,58 @@ fn joins_adjacent_output_and_keeps_other_events_in_order() { assert!(queue.is_empty()); } +#[test] +fn keeps_complete_output_buffers_on_each_side_of_a_control_event() { + let first = vec![b'a'; 8192]; + let second = vec![b'b'; 8192]; + let allocations = (first.as_ptr(), second.as_ptr()); + let (batch, remainder, queue) = queued(vec![ + Event::Output(first), + Event::Connected, + Event::Output(second), + ]); + let [ + Event::Output(first), + Event::Connected, + Event::Output(second), + ] = batch.as_slice() + else { + panic!("unexpected batch"); + }; + assert!(remainder.is_none() && queue.is_empty()); + assert_eq!((first.len(), second.len()), (8192, 8192)); + assert_eq!((first.as_ptr(), second.as_ptr()), allocations); +} + +#[test] +#[ignore = "manual release-mode performance measurement"] +fn measure_batching_complete_terminal_output_packets() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + const PACKETS: u32 = 1_000; + let mut samples = [0; 31]; + for sample in &mut samples { + let packets: Vec<_> = (0..PACKETS) + .map(|_| Pending::new(Event::Output(vec![b'x'; 8192]))) + .collect(); + let start = Instant::now(); + for packet in packets { + let (batch, remainder) = black_box(drain(black_box(packet), || None)); + assert!(remainder.is_none()); + assert!(matches!(batch.as_slice(), [Event::Output(bytes)] if bytes.len() == 8192)); + } + *sample = start.elapsed().as_nanos() / u128::from(PACKETS); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "8 KiB per batch: p50={} ns, p95={} ns", + samples[15], + samples[29] + ) + .unwrap(); +} + #[test] fn byte_budget_counts_first_and_nonadjacent_outputs() { let (batch, remainder, queue) = queued(vec![ diff --git a/crates/terminal/src/terminal/recording_tests.rs b/crates/terminal/src/terminal/recording_tests.rs index 25ccb3dd..80a8eadf 100644 --- a/crates/terminal/src/terminal/recording_tests.rs +++ b/crates/terminal/src/terminal/recording_tests.rs @@ -1,5 +1,6 @@ use super::*; use gpui_kit::{AppContext as _, TestAppContext}; +use nocterm_session::testing::Gate; use nocterm_session::{Auth, Command, Reply, SecretRequest, Target}; #[gpui_kit::test] fn oversized_bracketed_paste_is_rejected_without_a_partial_protocol_sequence( @@ -64,6 +65,7 @@ fn oversized_bracketed_paste_is_rejected_without_a_partial_protocol_sequence( } fn setup_recording_test( directory: &std::path::Path, + create_gate: Gate, cx: &mut gpui_kit::TestAppContext, ) -> ( gpui_kit::Entity, @@ -90,7 +92,7 @@ fn setup_recording_test( directory.join("session.log"), )); log_factory.enqueue( - nocterm_session::testing::Gate::open(), + create_gate, Ok(log.clone() as std::sync::Arc), ); log.enqueue_append( @@ -143,7 +145,8 @@ fn automatic_logs_exclude_authentication_and_input_and_drain_on_disconnect( cx: &mut TestAppContext, ) { let directory = tempfile::tempdir().unwrap(); - let (terminal, _session, driver, _log) = setup_recording_test(directory.path(), cx); + let (terminal, _session, driver, _log) = + setup_recording_test(directory.path(), Gate::open(), cx); let (reply, answer) = Reply::channel(); cx.update(|cx| { terminal.update(cx, |terminal, cx| { @@ -200,10 +203,136 @@ fn recorded(log: &nocterm_session::testing::recording::ScriptedOutputLog) -> Vec .collect() } +#[gpui_kit::test] +fn recording_device_replies_preserves_bytes_without_repainting_the_grid(cx: &mut TestAppContext) { + use futures::FutureExt as _; + use std::{cell::Cell, rc::Rc}; + + let directory = tempfile::tempdir().unwrap(); + let (terminal, _session, driver, log) = + setup_recording_test(directory.path(), Gate::open(), cx); + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Connected, cx) + }); + cx.run_until_parked(); + let outputs = Rc::new(Cell::new(0)); + let _subscription = cx.update(|cx| { + let outputs = outputs.clone(); + cx.subscribe(&terminal, move |_, event, _| { + if *event == TerminalEvent::Output { + outputs.set(outputs.get() + 1); + } + }) + }); + + let queries = b"\x1b[6n\x1b[6n\x1b[6n\x1b[6n\x1b[6n\x1b[m"; + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Output(queries.to_vec()), cx); + }); + cx.run_until_parked(); + for _ in 0..5 { + assert_eq!( + driver.next_command().now_or_never(), + Some(Some(Command::Input(b"\x1b[1;1R".to_vec()))) + ); + } + assert_eq!(recorded(&log), queries); + assert_eq!( + terminal.read_with(cx, |terminal, _| terminal + .recording_status() + .unwrap() + .bytes()), + 23 + ); + assert_eq!(outputs.get(), 0); +} + +#[gpui_kit::test] +fn recording_publishes_its_path_and_error_while_the_screen_is_idle(cx: &mut TestAppContext) { + use nocterm_session::recording::{AppendOutcome, PhysicalPrefix, RecordingError}; + use std::{cell::RefCell, rc::Rc}; + + let directory = tempfile::tempdir().unwrap(); + let create_gate = Gate::pending(); + let (terminal, _session, _driver, log) = + setup_recording_test(directory.path(), create_gate.clone(), cx); + let path = directory.path().join("session.log"); + let error = RecordingError::append(&path, 23, std::io::ErrorKind::StorageFull.into()); + log.enqueue_append( + Gate::open(), + AppendOutcome::new( + PhysicalPrefix::new(1, 23, 0, false, false), + Some(error.clone()), + ), + ); + let events = Rc::new(RefCell::new(Vec::new())); + let _subscription = cx.update(|cx| { + let events = events.clone(); + cx.subscribe(&terminal, move |terminal, event, cx| { + if *event == TerminalEvent::RecordingChanged { + events + .borrow_mut() + .push(terminal.read(cx).recording_status().unwrap()); + } + }) + }); + + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Connected, cx) + }); + cx.run_until_parked(); + assert!(events.borrow().is_empty()); + create_gate.release(); + cx.run_until_parked(); + + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Output(vec![b' '; 23]), cx) + }); + cx.run_until_parked(); + assert_eq!( + events.borrow().len(), + 1, + "byte progress leaves the metadata unchanged" + ); + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Output(b"\x1b[?1000h".to_vec()), cx); + }); + cx.run_until_parked(); + let statuses = events.borrow(); + assert_eq!(statuses.len(), 2); + assert_eq!(statuses[0].path(), Some(path.clone())); + assert_eq!(statuses[0].error(), None); + assert_eq!(statuses[1].path(), Some(path)); + assert_eq!(statuses[1].error(), Some(error.to_string().as_str())); +} + +#[gpui_kit::test] +fn stopping_recording_retires_pending_file_notifications(cx: &mut TestAppContext) { + let directory = tempfile::tempdir().unwrap(); + let gate = Gate::pending(); + let (terminal, _session, _driver, log) = + setup_recording_test(directory.path(), gate.clone(), cx); + let _subscription = cx.update(|cx| { + cx.subscribe(&terminal, |_, event, _| { + assert_ne!(*event, TerminalEvent::RecordingChanged); + }) + }); + terminal.update(cx, |terminal, cx| { + terminal.handle_event(Event::Connected, cx) + }); + cx.run_until_parked(); + terminal.update(cx, Terminal::stop_recording); + gate.release(); + cx.run_until_parked(); + assert_eq!(log.seal_count(), 1); + assert!(!terminal.read_with(cx, |terminal, _| terminal.is_recording())); +} + #[gpui_kit::test] fn restored_screens_are_not_recorded_as_program_output(cx: &mut TestAppContext) { let directory = tempfile::tempdir().unwrap(); - let (terminal, _session, _driver, log) = setup_recording_test(directory.path(), cx); + let (terminal, _session, _driver, log) = + setup_recording_test(directory.path(), Gate::open(), cx); cx.update(|cx| { terminal.update(cx, |terminal, cx| { terminal.handle_event(Event::Connected, cx); @@ -221,7 +350,8 @@ fn connected_again_after_a_reconnect_does_not_start_another_automatic_recording( cx: &mut TestAppContext, ) { let directory = tempfile::tempdir().unwrap(); - let (terminal, _session, _driver, _log) = setup_recording_test(directory.path(), cx); + let (terminal, _session, _driver, _log) = + setup_recording_test(directory.path(), Gate::open(), cx); cx.update(|cx| { terminal.update(cx, |terminal, cx| { terminal.handle_event(Event::Connected, cx); diff --git a/crates/terminal/src/view.rs b/crates/terminal/src/view.rs index abbb0074..054fb773 100644 --- a/crates/terminal/src/view.rs +++ b/crates/terminal/src/view.rs @@ -23,7 +23,7 @@ use nocterm_session::{CloseReason, ConnectStage, HostKeyDecision, Prompt, Secret use nocterm_ui::{ActiveDesign as _, IconName, TerminalStyle}; use nocterm_vt::{ CellPoint, Frame, KeyPress, Modifiers, MouseEvent, MouseEventKind, Palette, Rgb, Scroll, - SearchDirection, SelectionKind, encode_focus, encode_key, encode_mouse, encode_paste, + SearchDirection, SelectionKind, encode_focus, encode_key, encode_mouse, }; use nocterm_workspace::{Item, ItemEvent, SessionContext, SessionSpec, TabState}; @@ -60,6 +60,7 @@ pub struct TerminalView { pointer: pointer::PointerState, secret: Option, find: Option, + output_had_selection: bool, notice_messages: [Option; 3], _subscriptions: Vec, capabilities: nocterm_workspace::TerminalCapabilities, @@ -132,6 +133,7 @@ impl TerminalView { ) -> Self { let focus_handle = cx.focus_handle(); let settings = terminal.read(cx).installed().settings().clone(); + let observed_settings = settings.clone(); let weak = cx.entity().downgrade(); let origin = if terminal.read(cx).installed().is_container() { crate::access::AccessOrigin::WorkspaceResource @@ -150,18 +152,13 @@ impl TerminalView { let subscriptions = vec![ cx.subscribe_in(&terminal, window, Self::on_terminal_event), - cx.observe_keystrokes(Self::on_keyboard_binding), - settings.observe(cx, move |cx| { + settings.observe_section::(cx, move |cx| { + let semantic_highlighting = observed_settings + .setting::(cx) + .semantic_highlighting; if let Some(view) = weak.upgrade() { view.update(cx, |this, cx| { - if !this - .terminal - .read(cx) - .installed() - .settings() - .setting::(cx) - .semantic_highlighting - { + if !semantic_highlighting { this.cache.clear_highlights(); } cx.notify(); @@ -189,6 +186,7 @@ impl TerminalView { pointer: Default::default(), secret: None, find: None, + output_had_selection: false, notice_messages: Default::default(), _subscriptions: subscriptions, capabilities, @@ -276,11 +274,24 @@ impl TerminalView { cx.emit(ItemEvent::Changed); cx.notify(); } - TerminalEvent::Output => { - self.cache.invalidate(); + TerminalEvent::Output | TerminalEvent::RecordingChanged => { + let paint_only = if *event == TerminalEvent::Output { + self.cache.invalidate(); + self.output_only_changes_paint(cx) + } else { + false + }; self.sync_operational_notices(window, cx); - cx.notify(); + // The tab strip reads this entity even when its grid is absent. + if gpui_kit::is_view_rendered(window, cx.entity_id()) { + if paint_only { + cx.notify_paint(); + } else { + cx.notify(); + } + } } + TerminalEvent::InputChanged => self.sync_operational_notices(window, cx), // A visual or audible bell is a setting still to come. TerminalEvent::Bell => {} TerminalEvent::ClipboardWrite(text) => { @@ -301,6 +312,21 @@ impl TerminalView { } } + fn output_only_changes_paint(&mut self, cx: &App) -> bool { + let terminal = self.terminal.read(cx); + let selected = terminal.emulator().selection_start().is_some(); + let was_selected = std::mem::replace(&mut self.output_had_selection, selected); + // Keep selection commands and the Find, prompt, and session UI in sync + // with the input tree even when a frame cannot be presented. + !selected + && !was_selected + && self.find.is_none() + && self.bar.is_none() + && terminal.is_connected() + && terminal.prompt().is_none() + && terminal.find().query().is_empty() + } + fn sync_operational_notices(&mut self, window: &mut Window, cx: &mut Context) { let terminal = self.terminal.read(cx); let messages = [ @@ -439,10 +465,11 @@ impl TerminalView { &mut self, event: &MouseMoveEvent, hovered: bool, + window: &Window, cx: &mut Context, ) { let host = self.pointer_host(); - self.pointer.mouse_move(event, &host, hovered, cx); + self.pointer.mouse_move(event, &host, hovered, window, cx); } pub(crate) fn mouse_up(&mut self, event: &MouseUpEvent, cx: &mut Context) { let host = self.pointer_host(); @@ -452,28 +479,20 @@ impl TerminalView { let host = self.pointer_host(); self.pointer.scroll_wheel(event, &host, cx); } - fn autoscroll_tick(&mut self, cx: &mut Context) -> bool { + fn autoscroll_tick(&mut self, elapsed: Duration, cx: &mut Context) -> bool { self.sync_pointer(cx); if !self.input.focused() || !self.pointer.dragging() { return false; } let host = self.pointer_host(); - let scrolled = self.pointer.extend_selection(&host, cx); - if !scrolled { - self.pointer.stop_autoscroll(); - } - scrolled + self.pointer.autoscroll(&host, elapsed, cx) } // ── Keyboard ───────────────────────────────────────────────────────────── fn type_text(&mut self, text: &str, cx: &mut Context) -> bool { - let accepted = self.terminal.update(cx, |terminal, cx| { - let accepted = terminal.send_text(text, cx); - if accepted { - terminal.prepare_input(cx); - } - accepted - }); + let accepted = self + .terminal + .update(cx, |terminal, cx| terminal.edit_text(text, cx)); self.wake_cursor(cx); accepted } @@ -522,7 +541,7 @@ impl TerminalView { fn open_find( &mut self, - text: Option, + query: Option, from_selection: bool, window: &mut Window, cx: &mut Context, @@ -560,17 +579,13 @@ impl TerminalView { }); } let input = self.find.as_ref().unwrap().input.clone(); - if let Some(text) = text { - let text: String = text - .chars() - .take(nocterm_vt::MAX_SEARCH_QUERY + 1) - .collect(); - input.update(cx, |input, cx| input.set_value(text.clone(), window, cx)); + if let Some(query) = query { + input.update(cx, |input, cx| input.set_value(query.clone(), window, cx)); let anchor = from_selection .then(|| self.terminal.read(cx).emulator().selection_start()) .flatten(); self.terminal.update(cx, |t, cx| { - t.begin_find(text, SearchDirection::Next, anchor, cx) + t.begin_find(query, SearchDirection::Next, anchor, cx) }); } window.focus(&input.read(cx).focus_handle(cx), cx); diff --git a/crates/terminal/src/view/commands.rs b/crates/terminal/src/view/commands.rs index 5e8943da..b0ca09c9 100644 --- a/crates/terminal/src/view/commands.rs +++ b/crates/terminal/src/view/commands.rs @@ -9,9 +9,8 @@ use nocterm_workspace::{ impl TerminalView { /// Commands for the whole view, so they also reach it from the Find bar. - pub(super) fn on_commands(&self, element: Div, cx: &mut Context) -> Div { + pub(super) fn on_commands(&self, element: Div, selected: bool, cx: &mut Context) -> Div { let terminal = self.terminal.read(cx); - let selected = terminal.emulator().selection_text().is_some(); let selecting = terminal.emulator().selection_start().is_some(); let closed = matches!(terminal.status(), Status::Closed(_)); let command = terminal.is_command(); @@ -46,9 +45,13 @@ impl TerminalView { } /// The edit commands of the screen, which native text fields also answer. - pub(super) fn on_edit_commands(&self, element: Div, cx: &mut Context) -> Div { + pub(super) fn on_edit_commands( + &self, + element: Div, + selected: bool, + cx: &mut Context, + ) -> Div { let terminal = self.terminal.read(cx); - let selected = terminal.emulator().selection_text().is_some(); let connected = terminal.is_connected(); element .on_action(cx.listener(|this, _: &native_input::SelectAll, _, cx| { @@ -84,9 +87,9 @@ impl TerminalView { cx: &mut Context, ) { cx.defer_in(window, |this, window, cx| { - let text = this.terminal.read(cx).emulator().selection_text(); - if text.is_some() { - this.open_find(text, true, window, cx); + let query = this.terminal.read(cx).emulator().selected_search_query(); + if query.is_some() { + this.open_find(query, true, window, cx); } }); } diff --git a/crates/terminal/src/view/find_history_tests.rs b/crates/terminal/src/view/find_history_tests.rs new file mode 100644 index 00000000..0b2f3c14 --- /dev/null +++ b/crates/terminal/src/view/find_history_tests.rs @@ -0,0 +1,180 @@ +use super::*; + +#[gpui_kit::test] +fn find_from_retained_selection_keeps_the_query_overflow_error(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let row = "界é ordinary history"; + emit( + cx, + &transport, + 0, + Event::Output(format!("{row}\r\n").repeat(1_000).into_bytes()), + ); + let max = nocterm_vt::MAX_SEARCH_QUERY; + let expected: String = format!("{row}\n") + .repeat(1_000) + .chars() + .take(max + 1) + .collect(); + cx.update_window(handle, |_, window, cx| { + window.dispatch_action(Box::new(native_input::SelectAll), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.dispatch_action(Box::new(nocterm_workspace::FindNextSelection), cx); + }) + .unwrap(); + complete(cx, &view); + view.read_with(cx, |view, cx| { + let find = view.terminal.read(cx).find(); + assert_eq!(find.query(), expected); + let error = nocterm_vt::SearchError::QueryTooLong { max }.to_string(); + assert_eq!(find.error(), Some(error.as_str())); + }); +} + +#[gpui_kit::test] +fn find_preserves_a_historical_match_after_scrolling_output(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let mut output = b"needle first\r\n".to_vec(); + output.extend(b"padding\r\n".repeat(10)); + output.extend(b"needle second\r\n"); + output.extend(b"padding\r\n".repeat(120)); + emit(cx, &transport, 0, Event::Output(output)); + cx.update_window(handle, |_, window, cx| { + view.update(cx, |v, cx| { + v.open_find(Some("needle".into()), false, window, cx) + }); + }) + .unwrap(); + complete(cx, &view); + let current = |cx: &mut TestAppContext| { + view.read_with(cx, |view, cx| *view.terminal.read(cx).find().result()) + }; + let before = current(cx); + assert_eq!((before.ordinal, before.count), (1, 2)); + assert!(before.active.unwrap().start.line < 0); + + emit(cx, &transport, 0, Event::Output(b"padding\r\n".repeat(5))); + complete(cx, &view); + let after = current(cx); + assert_eq!((after.ordinal, after.count), (1, 2)); + assert_eq!( + after.active.unwrap().start.line, + before.active.unwrap().start.line - 5 + ); + view.read_with(cx, |view, cx| { + let mut frame = Frame::default(); + view.terminal.read(cx).emulator().snapshot(&mut frame); + assert!( + (0..frame.size.rows).any(|row| { + frame.row_text(row) == "needle first" && frame.row(row)[0].search_hit + }) + ); + }); +} + +#[gpui_kit::test] +fn large_find_navigates_nearby_matches_immediately_and_wraps(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let count = nocterm_vt::MAX_NAVIGATION_MATCHES + 12; + emit( + cx, + &transport, + 0, + Event::Output(b"needle\r\n".repeat(count)), + ); + cx.update_window(handle, |_, window, cx| { + view.update(cx, |v, cx| { + v.open_find(Some("needle".into()), false, window, cx) + }); + }) + .unwrap(); + complete(cx, &view); + let terminal = view.read_with(cx, |view, _| view.terminal.clone()); + for (previous, ordinal) in [(false, 2), (true, 1), (true, count), (false, 1)] { + terminal.update(cx, |terminal, cx| { + terminal.find_next(previous, cx); + let find = terminal.find(); + assert!( + !find.searching(), + "a retained match should be shown immediately" + ); + assert_eq!(find.result().ordinal, ordinal as u64); + assert_eq!(find.result().count, count as u64); + }); + } +} + +#[gpui_kit::test] +fn large_find_refills_a_missing_range_and_keeps_a_direction_reversal_local( + cx: &mut TestAppContext, +) { + let (_, view, transport) = fixture(cx); + let count = nocterm_vt::MAX_NAVIGATION_MATCHES as u64 + 12; + emit( + cx, + &transport, + 0, + Event::Output(b"needle\r\n".repeat(count as usize)), + ); + let terminal = view.read_with(cx, |view, _| view.terminal.clone()); + terminal.update(cx, |terminal, cx| { + terminal.begin_find( + "needle".into(), + nocterm_vt::SearchDirection::Previous, + None, + cx, + ) + }); + complete(cx, &view); + terminal.update(cx, |terminal, cx| { + assert_eq!(terminal.find().result().ordinal, count); + terminal.find_next(true, cx); + }); + complete(cx, &view); + terminal.update(cx, |terminal, cx| { + assert_eq!(terminal.find().result().ordinal, count - 1); + terminal.find_next(true, cx); + assert!(!terminal.find().searching()); + assert_eq!(terminal.find().result().ordinal, count - 2); + terminal.find_next(false, cx); + assert!(!terminal.find().searching()); + assert_eq!(terminal.find().result().ordinal, count - 1); + assert_eq!(terminal.find().result().count, count); + }); +} + +#[gpui_kit::test] +fn live_find_keeps_the_last_count_until_the_new_grid_is_searched(cx: &mut TestAppContext) { + let (_, view, transport) = fixture(cx); + emit(cx, &transport, 0, Event::Output(b"needle\r\n".repeat(120))); + let terminal = view.read_with(cx, |view, _| view.terminal.clone()); + terminal.update(cx, |terminal, cx| { + terminal.begin_find("needle".into(), nocterm_vt::SearchDirection::Next, None, cx); + }); + complete(cx, &view); + + emit(cx, &transport, 0, Event::Output(b"needle\r\n".repeat(5))); + terminal.read_with(cx, |terminal, _| { + let find = terminal.find(); + assert!(find.searching()); + assert!(find.confirmed()); + assert_eq!((find.result().ordinal, find.result().count), (1, 120)); + assert!(find.result().active.is_none()); + }); + complete(cx, &view); + terminal.update(cx, |terminal, cx| { + assert_eq!(terminal.find().result().count, 125); + terminal.begin_find( + "different".into(), + nocterm_vt::SearchDirection::Next, + None, + cx, + ); + assert!(!terminal.find().confirmed()); + assert_eq!(terminal.find().result().count, 0); + }); +} diff --git a/crates/terminal/src/view/history_selection_tests.rs b/crates/terminal/src/view/history_selection_tests.rs new file mode 100644 index 00000000..405b842e --- /dev/null +++ b/crates/terminal/src/view/history_selection_tests.rs @@ -0,0 +1,52 @@ +use super::*; +use nocterm_workspace::{ClearSelection, FindNextSelection}; + +#[gpui_kit::test] +fn selecting_retained_history_enables_commands_and_copies_the_whole_text(cx: &mut TestAppContext) { + let (handle, _, transport) = fixture(cx); + let rows = "selected history row á 🌙"; + for _ in 0..10 { + emit( + cx, + &transport, + 0, + Event::Output(format!("{rows}\r\n").repeat(100).into_bytes()), + ); + } + emit(cx, &transport, 0, Event::Output(b"last line".to_vec())); + let expected = format!("{}last line", format!("{rows}\n").repeat(1_000)); + + cx.update_window(handle, |_, window, cx| { + assert!(!window.is_action_available(&FindNextSelection, cx)); + assert!(!window.is_action_available(&ClearSelection, cx)); + window.dispatch_action(Box::new(native_input::SelectAll), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.is_action_available(&native_input::Copy, cx)); + assert!(window.is_action_available(&FindNextSelection, cx)); + assert!(window.is_action_available(&ClearSelection, cx)); + window.dispatch_action(Box::new(native_input::Copy), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert_eq!( + cx.read_from_clipboard().unwrap().text().as_deref(), + Some(expected.as_str()) + ); + }); + cx.update_window(handle, |_, window, cx| { + window.dispatch_action(Box::new(ClearSelection), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(!window.is_action_available(&FindNextSelection, cx)); + assert!(!window.is_action_available(&ClearSelection, cx)); + }) + .unwrap(); +} diff --git a/crates/terminal/src/view/input.rs b/crates/terminal/src/view/input.rs index ea75a3ca..d13cfaf7 100644 --- a/crates/terminal/src/view/input.rs +++ b/crates/terminal/src/view/input.rs @@ -1,7 +1,7 @@ use super::paste::{dropped_paths, quote_paths_with_syntax}; use super::*; use crate::file_drop::FileDropError; -use gpui_kit::KeyUpEvent; +use gpui_kit::{KeyUpEvent, Subscription}; use nocterm_vt::{ KeyEncoding, KeyEvent, KeyEventKind, KeyboardState, encode_key_event, encode_text_commit, }; @@ -11,6 +11,7 @@ use nocterm_workspace::FileDrag; pub(super) struct ViewInput { keyboard: keyboard::KeyboardInput, marked_text: Option, + binding_observer: Option, focused: bool, } impl ViewInput { @@ -20,7 +21,7 @@ impl ViewInput { pub(super) fn focus_changed(&mut self, focused: bool) { self.focused = focused; if !focused { - self.keyboard.clear(); + self.clear_keys(); } } pub(super) fn composing(&self) -> bool { @@ -43,9 +44,13 @@ impl ViewInput { } fn clear_keys(&mut self) { self.keyboard.clear(); + self.binding_observer = None; } fn sync(&mut self, state: KeyboardState, alt_screen: bool, epoch: u64, protocol_epoch: u64) { self.keyboard.sync(state, alt_screen, epoch, protocol_epoch); + if !state.report_event_types { + self.binding_observer = None; + } } fn clear_pending(&mut self) { self.keyboard.clear_pending(); @@ -222,6 +227,13 @@ impl TerminalView { (chars.next().is_none() && !ch.is_control()).then_some(ch) }); let modes = self.terminal.read(cx).emulator().modes(); + if modes.keyboard.report_event_types { + // A later binding may consume the repeat before it reaches this + // handler. Retire that physical key through GPUI's binding observer. + self.input + .binding_observer + .get_or_insert_with(|| cx.observe_keystrokes(Self::on_keyboard_binding)); + } match encode_key_event(&key_event, modes) { KeyEncoding::Encoded(bytes) => { cx.stop_propagation(); @@ -292,7 +304,7 @@ impl TerminalView { } } - pub(super) fn on_keyboard_binding( + fn on_keyboard_binding( &mut self, event: &gpui_kit::KeystrokeEvent, window: &mut Window, @@ -307,18 +319,14 @@ impl TerminalView { impl TerminalView { pub(super) fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context) { - if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - self.paste_text(&text, cx); + let terminal = self.terminal.read(cx); + if !terminal.is_connected() || terminal.prompt().is_some() { + return; } - } - - fn paste_text(&mut self, text: &str, cx: &mut Context) { - let modes = self.terminal.read(cx).emulator().modes(); - self.type_text( - std::str::from_utf8(&encode_paste(text, modes)) - .expect("paste wrapping preserves UTF-8"), - cx, - ); + let read = cx.read_from_clipboard_async(); + self.terminal + .update(cx, |terminal, cx| terminal.paste_clipboard(read, cx)); + self.wake_cursor(cx); } pub(super) fn drop_files( @@ -345,11 +353,9 @@ impl TerminalView { }; match result { Ok(text) => { - let result = self.terminal.update(cx, |terminal, cx| { - terminal.paste_paths(&text, cx)?; - terminal.complete_native_paste(cx); - Ok::<_, FileDropError>(()) - }); + let result = self + .terminal + .update(cx, |terminal, cx| terminal.paste_paths(&text, cx)); if let Err(error) = result { nocterm_ui::notice::warning( window, diff --git a/crates/terminal/src/view/keyboard_transition_tests.rs b/crates/terminal/src/view/keyboard_transition_tests.rs index abf5a4cf..d828256a 100644 --- a/crates/terminal/src/view/keyboard_transition_tests.rs +++ b/crates/terminal/src/view/keyboard_transition_tests.rs @@ -94,3 +94,28 @@ fn ordinary_output_and_protocol_queries_preserve_owned_releases(cx: &mut TestApp .unwrap(); assert_eq!(drain(&driver), [b"\x1b[1;1:3A".to_vec()]); } + +#[gpui_kit::test] +fn a_binding_after_refocus_retires_the_held_key(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let driver = scripted_driver(&transport, 0); + emit(cx, &transport, 0, Event::Output(b"\x1b[>3u".to_vec())); + drain(&driver); + + cx.update_window(handle, |_, window, cx| { + let focus = view.read(cx).focus_handle(cx); + window.blur(cx); + window.render_frame(cx); + window.focus(&focus, cx); + window.render_frame(cx); + press_up(window, cx); + assert_eq!(drain(&driver), [b"\x1b[A".to_vec()]); + + cx.bind_keys([gpui_kit::KeyBinding::new("up", Copy, Some(KEY_CONTEXT))]); + window.render_frame(cx); + press_up(window, cx); + release_up(window, cx); + assert!(drain(&driver).is_empty()); + }) + .unwrap(); +} diff --git a/crates/terminal/src/view/output_visibility_tests.rs b/crates/terminal/src/view/output_visibility_tests.rs new file mode 100644 index 00000000..1efe755c --- /dev/null +++ b/crates/terminal/src/view/output_visibility_tests.rs @@ -0,0 +1,114 @@ +use super::*; + +struct SplitTabs { + first: Entity, + second: Entity, + show_second: bool, +} + +impl Render for SplitTabs { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + // The tab strip reads both views, even when the second grid is absent. + let first = self.first.read(cx).tab_title(cx); + let second = self.second.read(cx).tab_title(cx); + v_flex().child(h_flex().child(first).child(second)).child( + h_flex() + .flex_1() + .child(self.first.clone()) + .when(self.show_second, |row| row.child(self.second.clone())), + ) + } +} + +fn shows(terminal: &TerminalView, character: char) -> bool { + terminal + .painted_frame() + .cells + .iter() + .any(|cell| cell.ch == character) +} + +#[gpui_kit::test] +fn background_output_skips_redraw_until_the_terminal_is_shown(cx: &mut TestAppContext) { + let (handle, first, transport) = fixture(cx); + let (root, second) = cx + .update_window(handle, |_, window, cx| { + let terminal = first.read(cx).terminal().read(cx); + let installed = terminal.installed().clone(); + let spec = terminal.spec().clone(); + let second = cx.new(|cx| TerminalView::new(installed, spec, window, cx)); + let root = window.replace_root(cx, |_, _| SplitTabs { + first: first.clone(), + second: second.clone(), + show_second: false, + }); + window.render_frame(cx); + (root, second) + }) + .unwrap(); + cx.run_until_parked(); + emit(cx, &transport, 1, Event::Connected); + let invalidations = Rc::new(Cell::new(0)); + let _subscription = cx.update(|cx| { + let invalidations = invalidations.clone(); + cx.observe(&second, move |_, _| { + invalidations.set(invalidations.get() + 1) + }) + }); + + for _ in 0..32 { + emit(cx, &transport, 1, Event::Output(b"\r\nZ".to_vec())); + } + assert_eq!(invalidations.get(), 0); + + cx.update_window(handle, |_, window, cx| { + root.update(cx, |root, cx| { + root.show_second = true; + cx.notify(); + }); + window.focus(&first.read(cx).focus_handle(cx), cx); + window.render_frame(cx); + let second = second.read(cx); + assert!(!second.focus_handle(cx).is_focused(window)); + assert!(shows(second, 'Z')); + }) + .unwrap(); + + let before = invalidations.get(); + emit(cx, &transport, 1, Event::Output(b"Y".to_vec())); + assert!( + invalidations.get() > before, + "an unfocused split still updates" + ); + + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(shows(second.read(cx), 'Y')); + root.update(cx, |root, cx| { + root.show_second = false; + cx.notify(); + }); + window.render_frame(cx); + }) + .unwrap(); + let before = invalidations.get(); + emit(cx, &transport, 1, Event::Output(b"X".to_vec())); + assert_eq!(invalidations.get(), before); + + emit( + cx, + &transport, + 1, + Event::Output(b"\x1b]2;background title\x07".to_vec()), + ); + cx.update(|cx| { + assert_eq!( + second.read(cx).terminal().read(cx).program_title(), + Some("background title") + ); + }); + assert!( + invalidations.get() > before, + "the hidden tab still publishes its title" + ); +} diff --git a/crates/terminal/src/view/paste.rs b/crates/terminal/src/view/paste.rs index 8743ebb4..0d226598 100644 --- a/crates/terminal/src/view/paste.rs +++ b/crates/terminal/src/view/paste.rs @@ -3,8 +3,9 @@ use super::*; use crate::file_drop::FileDropError; use nocterm_workspace::FileDrag; +use std::borrow::Cow; -pub(super) fn dropped_paths(files: &FileDrag) -> Result, FileDropError> { +pub(super) fn dropped_paths(files: &FileDrag) -> Result, FileDropError> { match files { FileDrag::Local(paths) => paths .iter() @@ -13,8 +14,9 @@ pub(super) fn dropped_paths(files: &FileDrag) -> Result, FileDropErr .map(str::to_owned) .ok_or(FileDropError::NonUtf8Path) }) - .collect(), - FileDrag::Remote(files) => Ok(files.sources.clone()), + .collect::>() + .map(Cow::Owned), + FileDrag::Remote(files) => Ok(Cow::Borrowed(&files.sources)), } } @@ -117,7 +119,10 @@ mod tests { #[test] fn local_paths_preserve_order_for_any_receiving_terminal() { - let files = FileDrag::Local(vec!["/home/a".into(), "/home/b".into()]); - assert_eq!(dropped_paths(&files).unwrap(), ["/home/a", "/home/b"]); + let files = FileDrag::Local(vec!["/home/a".into(), "/home/b".into()].into()); + assert_eq!( + dropped_paths(&files).unwrap().as_ref(), + ["/home/a", "/home/b"] + ); } } diff --git a/crates/terminal/src/view/paste_tests.rs b/crates/terminal/src/view/paste_tests.rs index cc5767b5..93141832 100644 --- a/crates/terminal/src/view/paste_tests.rs +++ b/crates/terminal/src/view/paste_tests.rs @@ -4,6 +4,26 @@ use super::*; use gpui_kit::{TestAppContext, base::TestSupportExt as _, px, test::TestWindowExt as _}; use nocterm_session::Event; +#[gpui_kit::test] +fn clipboard_paste_preserves_multiple_text_entries_and_keeps_escapes_inside_brackets( + cx: &mut TestAppContext, +) { + let (handle, _, transport) = fixture(cx); + emit(cx, &transport, 0, Event::Output(b"\x1b[?2004h".to_vec())); + let driver = scripted_driver(&transport, 0); + drain(&driver); + cx.update_window(handle, |_, window, cx| { + let mut item = ClipboardItem::new_string_with_metadata("á\n".into(), "ignored".into()); + item.entries + .extend(ClipboardItem::new_string("\x1b[201~🌙".into()).entries); + cx.write_to_clipboard(item); + window.dispatch_action(Box::new(native_input::Paste), cx); + }) + .unwrap(); + cx.run_until_parked(); + assert_eq!(drain(&driver), ["\x1b[200~á\n[201~🌙\x1b[201~".as_bytes()]); +} + struct DropHarness { view: Entity, files: FileDrag, @@ -50,7 +70,7 @@ fn native_file_drop_inserts_literal_paths_once_without_enter(cx: &mut TestAppCon cx.update_window(handle, |_, window, cx| { window.replace_root(cx, |_, _| DropHarness { view: view.clone(), - files: FileDrag::Local(vec!["/tmp/a b".into(), "/tmp/資料's".into()]), + files: FileDrag::Local(vec!["/tmp/a b".into(), "/tmp/資料's".into()].into()), }); window.render_frame(cx); window.drag_to("test-file-source", "terminal-drop-target", cx); @@ -90,7 +110,7 @@ fn remote_shell_launch_override_controls_quote_style_for_local_source(cx: &mut T drain(&driver); cx.update_window(handle, |_, window, cx| { view.update(cx, |view, cx| { - view.drop_files(&FileDrag::Local(vec!["/a'b".into()]), window, cx) + view.drop_files(&FileDrag::Local(vec!["/a'b".into()].into()), window, cx) }); }) .unwrap(); @@ -103,7 +123,7 @@ fn native_remote_source_drop_uses_paths_and_focuses_receiving_terminal(cx: &mut let driver = scripted_driver(&transport, 0); drain(&driver); let files = FileDrag::Remote(nocterm_workspace::RemoteFileDrag { - sources: vec!["/remote/a b".into(), "/remote/資料's".into()], + sources: vec!["/remote/a b".into(), "/remote/資料's".into()].into(), host: nocterm_session::HostAddress::direct(nocterm_session::Target::new( "other-user", "other-host", @@ -141,7 +161,7 @@ fn native_non_utf8_path_rejects_whole_drop_with_notice(cx: &mut TestAppContext) cx.update_window(handle, |_, window, cx| { window.replace_root(cx, |_, _| DropHarness { view: view.clone(), - files: FileDrag::Local(vec!["/tmp/valid-first".into(), invalid]), + files: FileDrag::Local(vec!["/tmp/valid-first".into(), invalid].into()), }); window.render_frame(cx); window.drag_to("test-file-source", "terminal-drop-target", cx); @@ -266,7 +286,7 @@ fn program_fixture_via( cx.update_window(handle, |_, window, cx| { window.replace_root(cx, |_, _| DropHarness { view: view.clone(), - files: FileDrag::Local(vec!["/tmp/a'b 資料".into()]), + files: FileDrag::Local(vec!["/tmp/a'b 資料".into()].into()), }); window.render_frame(cx); }) @@ -309,7 +329,7 @@ fn native_container_wrapper_uses_explicit_receiving_syntax_and_keeps_state_guard ); cx.update_window(handle, |_, window, cx| { view.update(cx, |view, cx| { - view.drop_files(&FileDrag::Local(vec!["/blocked".into()]), window, cx) + view.drop_files(&FileDrag::Local(vec!["/blocked".into()].into()), window, cx) }); }) .unwrap(); @@ -324,7 +344,7 @@ fn native_container_wrapper_uses_explicit_receiving_syntax_and_keeps_state_guard ); cx.update_window(handle, |_, window, cx| { view.update(cx, |view, cx| { - view.drop_files(&FileDrag::Local(vec!["/blocked".into()]), window, cx) + view.drop_files(&FileDrag::Local(vec!["/blocked".into()].into()), window, cx) }); }) .unwrap(); diff --git a/crates/terminal/src/view/pointer.rs b/crates/terminal/src/view/pointer.rs index 286061fa..06548165 100644 --- a/crates/terminal/src/view/pointer.rs +++ b/crates/terminal/src/view/pointer.rs @@ -1,14 +1,16 @@ //! Local selection and bounded program pointer input. use super::*; +use gpui_kit::base::FrameLoop; -const AUTOSCROLL_INTERVAL: Duration = Duration::from_millis(50); +const AUTOSCROLL_STEPS_PER_SECOND: f32 = 20.; const MAX_AUTOSCROLL_LINES: i32 = 8; #[derive(Default)] pub(super) struct PointerState { context: Option, selection: Option>, - auto_scroll: Option>, + auto_scroll: FrameLoop, + edge_remainder: f32, reported_button: Option, last_reported_cell: Option, scroll_remainder: f32, @@ -103,7 +105,7 @@ impl PointerState { MouseButton::Left => { let extend = event.modifiers.shift && event.click_count <= 1 - && host.terminal.read(cx).emulator().selection_text().is_some(); + && host.terminal.read(cx).emulator().has_selection_text(); let kind = match event.click_count { 0 | 1 => SelectionKind::Cells, 2 => SelectionKind::Words, @@ -130,6 +132,7 @@ impl PointerState { event: &MouseMoveEvent, host: &PointerHost, hovered: bool, + window: &Window, cx: &mut Context, ) { self.sync(host.terminal.read(cx), host.geometry); @@ -142,11 +145,13 @@ impl PointerState { return; } self.selection = Some(event.position); - self.extend_selection(host, cx); + self.extend_selection(host, 0, cx); if edge_scroll(geometry, event.position) != 0 { - self.start_autoscroll(cx); + self.auto_scroll.start(window, cx, |view, elapsed, _, cx| { + view.autoscroll_tick(elapsed, cx) + }); } else { - self.auto_scroll = None; + self.stop_autoscroll(); } return; } @@ -206,39 +211,51 @@ impl PointerState { fn stop_selection(&mut self) { self.selection = None; - self.auto_scroll = None; + self.stop_autoscroll(); } /// Scroll and move the endpoint together; the emulator retains the anchor /// in absolute scrollback coordinates. - pub(super) fn extend_selection( + fn extend_selection( &mut self, host: &PointerHost, + lines: i32, cx: &mut Context, ) -> bool { let (Some(position), Some(geometry)) = (self.selection, host.geometry) else { return false; }; - let lines = edge_scroll(geometry, position); let (at, side) = geometry.cell_at(position); host.terminal.update(cx, |terminal, cx| { terminal.extend_selection(at, side, lines, cx) }) } - fn start_autoscroll(&mut self, cx: &mut Context) { - if self.auto_scroll.is_some() { - return; + pub(super) fn autoscroll( + &mut self, + host: &PointerHost, + elapsed: Duration, + cx: &mut Context, + ) -> bool { + let (Some(position), Some(geometry)) = (self.selection, host.geometry) else { + return false; + }; + let speed = edge_scroll(geometry, position) as f32 * AUTOSCROLL_STEPS_PER_SECOND; + if speed == 0. { + return false; + } + if self.edge_remainder.signum() != speed.signum() { + self.edge_remainder = 0.; + } + let progress = self.edge_remainder + speed * elapsed.as_secs_f32().min(0.05); + let lines = progress.trunc() as i32; + self.edge_remainder = progress.fract(); + if lines == 0 || self.extend_selection(host, lines, cx) { + true + } else { + self.edge_remainder = 0.; + false } - self.auto_scroll = Some(cx.spawn(async move |this, cx| { - loop { - cx.background_executor().timer(AUTOSCROLL_INTERVAL).await; - let keep_scrolling = this.update(cx, |this, cx| this.autoscroll_tick(cx)); - if !matches!(keep_scrolling, Ok(true)) { - break; - } - } - })); } pub(super) fn scroll_wheel( @@ -324,8 +341,9 @@ impl PointerState { pub(super) fn dragging(&self) -> bool { self.selection.is_some() } - pub(super) fn stop_autoscroll(&mut self) { - self.auto_scroll = None; + fn stop_autoscroll(&mut self) { + self.auto_scroll.stop(); + self.edge_remainder = 0.; } } diff --git a/crates/terminal/src/view/pointer_edit_tests.rs b/crates/terminal/src/view/pointer_edit_tests.rs index 4822c105..172d7c3e 100644 --- a/crates/terminal/src/view/pointer_edit_tests.rs +++ b/crates/terminal/src/view/pointer_edit_tests.rs @@ -13,7 +13,7 @@ fn edit_during_autoscroll( drain(&driver); down(handle, at(g, 2.2, 5.5), MouseButton::Left, false, 1, cx); motion(handle, at(g, 2.2, -1.0), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); assert!(offset(&view, cx) > 0); assert!(selection(&view, cx).is_some()); cx.update_window(handle, |_, window, cx| edit(window, cx)) @@ -26,7 +26,7 @@ fn edit_during_autoscroll( "accepted input must return to the live screen" ); assert_eq!(selection(&view, cx), None); - tick(cx); + tick(handle, cx); assert_eq!( offset(&view, cx), 0, @@ -73,7 +73,7 @@ fn clear_selection_cancels_edge_autoscroll_without_changing_viewport(cx: &mut Te let g = geometry(handle, &view, cx); down(handle, at(g, 2.2, 5.5), MouseButton::Left, false, 1, cx); motion(handle, at(g, 2.2, -1.0), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); let before = offset(&view, cx); assert!(before > 0); assert!(selection(&view, cx).is_some()); @@ -86,7 +86,7 @@ fn clear_selection_cancels_edge_autoscroll_without_changing_viewport(cx: &mut Te cx.run_until_parked(); assert_eq!(selection(&view, cx), None); assert_eq!(offset(&view, cx), before); - tick(cx); + tick(handle, cx); assert_eq!( offset(&view, cx), before, diff --git a/crates/terminal/src/view/pointer_lifecycle_tests.rs b/crates/terminal/src/view/pointer_lifecycle_tests.rs index 4e0ed90b..686e799f 100644 --- a/crates/terminal/src/view/pointer_lifecycle_tests.rs +++ b/crates/terminal/src/view/pointer_lifecycle_tests.rs @@ -98,7 +98,7 @@ fn disconnect_reconnect_and_screen_switch_cancel_old_selection_drag(cx: &mut Tes emit(cx, &transport, 0, Event::Closed(CloseReason::ClosedByUser)); let before_offset = offset(&view, cx); let before_selection = selection(&view, cx); - tick(cx); + tick(handle, cx); motion(handle, at(g, 6.2, 3.5), Some(MouseButton::Left), false, cx); assert_eq!(offset(&view, cx), before_offset); assert_eq!( @@ -124,7 +124,7 @@ fn disconnect_reconnect_and_screen_switch_cancel_old_selection_drag(cx: &mut Tes emit(cx, &transport, 1, Event::Output(b"\x1b[?1049h".to_vec())); let screen_selection = selection(&view, cx); motion(handle, at(g, 8.2, 3.5), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); assert_eq!(offset(&view, cx), 0); assert_eq!( selection(&view, cx), @@ -221,7 +221,7 @@ fn ordinary_output_keeps_stationary_edge_autoscroll_active(cx: &mut TestAppConte let g = geometry(handle, &view, cx); down(handle, at(g, 2.2, 5.5), MouseButton::Left, false, 1, cx); motion(handle, at(g, 2.2, -1.0), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); assert!(offset(&view, cx) > 0); emit( cx, @@ -231,7 +231,7 @@ fn ordinary_output_keeps_stationary_edge_autoscroll_active(cx: &mut TestAppConte ); let before = offset(&view, cx); let before_selection = selection(&view, cx); - tick(cx); + tick(handle, cx); assert!( offset(&view, cx) > before, "ordinary output cancelled autoscroll" @@ -278,7 +278,7 @@ fn activating_another_window_cancels_autoscroll_despite_retained_terminal_focus( let g = geometry(handle, &view, cx); down(handle, at(g, 2.2, 5.5), MouseButton::Left, false, 1, cx); motion(handle, at(g, 2.2, -1.0), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); assert!( offset(&view, cx) > 0, "fixture must first demonstrate active autoscroll" @@ -297,7 +297,7 @@ fn activating_another_window_cancels_autoscroll_despite_retained_terminal_focus( .unwrap(); let before = offset(&view, cx); let before_selection = selection(&view, cx); - tick(cx); + tick(handle, cx); assert_eq!( offset(&view, cx), before, @@ -308,7 +308,7 @@ fn activating_another_window_cancels_autoscroll_despite_retained_terminal_focus( .unwrap(); cx.run_until_parked(); motion(handle, at(g, 8.2, 3.5), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); assert_eq!( offset(&view, cx), before, diff --git a/crates/terminal/src/view/pointer_tests.rs b/crates/terminal/src/view/pointer_tests.rs index 70f32952..9489fa85 100644 --- a/crates/terminal/src/view/pointer_tests.rs +++ b/crates/terminal/src/view/pointer_tests.rs @@ -120,10 +120,15 @@ fn wheel( .unwrap(); cx.run_until_parked(); } -fn tick(cx: &mut TestAppContext) { - // Advance in steps: a recurring timer must run while the pointer is stationary. - for _ in 0..8 { - cx.executor().advance_clock(Duration::from_millis(25)); +fn tick(handle: AnyWindowHandle, cx: &mut TestAppContext) { + // Feed the frame clock while the pointer is stationary. + for _ in 0..24 { + cx.executor().advance_clock(Duration::from_millis(8)); + cx.update_window(handle, |_, window, cx| { + window.simulate_next_frame(cx); + window.render_frame(cx); + }) + .unwrap(); cx.run_until_parked(); } } @@ -158,7 +163,7 @@ fn stationary_edge_drag_scrolls_history_reverses_and_release_outside_stops( motion(handle, at(g, 2.2, -2.0), Some(MouseButton::Left), false, cx); let initial = offset(&view, cx); let text = selection(&view, cx).unwrap(); - tick(cx); + tick(handle, cx); let scrolled = offset(&view, cx); assert!( scrolled > initial, @@ -176,7 +181,7 @@ fn stationary_edge_drag_scrolls_history_reverses_and_release_outside_stops( false, cx, ); - tick(cx); + tick(handle, cx); assert!( offset(&view, cx) < scrolled, "lower edge must reverse scrolling" @@ -184,7 +189,7 @@ fn stationary_edge_drag_scrolls_history_reverses_and_release_outside_stops( up(handle, at(g, -10.0, -2.0), MouseButton::Left, cx); let ended = offset(&view, cx); let final_text = selection(&view, cx); - tick(cx); + tick(handle, cx); assert_eq!(offset(&view, cx), ended); assert_eq!(selection(&view, cx), final_text); } @@ -209,7 +214,7 @@ fn missing_held_button_and_focus_loss_cancel_selection_drag(cx: &mut TestAppCont let before = selection(&view, cx); let before_offset = offset(&view, cx); motion(handle, at(g, 10.2, 8.5), Some(MouseButton::Left), false, cx); - tick(cx); + tick(handle, cx); assert_eq!( selection(&view, cx), before, diff --git a/crates/terminal/src/view/render.rs b/crates/terminal/src/view/render.rs index 2434012e..07fe07eb 100644 --- a/crates/terminal/src/view/render.rs +++ b/crates/terminal/src/view/render.rs @@ -12,12 +12,25 @@ impl TerminalView { error.to_owned() } else if find.query().is_empty() { "".into() - } else if find.searching() { + } else if find.searching() && !find.confirmed() { "Searching…".into() } else if find.result().count == 0 { - "No matches".into() + if find.searching() { + "No matches · Updating…".into() + } else { + "No matches".into() + } } else { - format!("{} of {}", find.result().ordinal, find.result().count) + let suffix = if find.searching() { + " · Updating…" + } else { + "" + }; + format!( + "{} of {}{suffix}", + find.result().ordinal, + find.result().count + ) }; let disabled = find.query().is_empty() || find.searching() @@ -367,6 +380,7 @@ impl Render for TerminalView { let background = nocterm_ui::hsla(style.background); let element = self.paint_element(cx.entity(), style, self.focus_handle.is_focused(window)); + let selected = self.terminal.read(cx).emulator().has_selection_text(); let grid = div() .id("terminal-drop-target") @@ -391,7 +405,7 @@ impl Render for TerminalView { .on_action(cx.listener(Self::reconnect)) .on_action(cx.listener(Self::toggle_recording)) .child( - self.on_edit_commands(div(), cx) + self.on_edit_commands(div(), selected, cx) .key_context(SCREEN_KEY_CONTEXT) .track_focus(&self.focus_handle) .on_action(cx.listener(Self::copy)) @@ -409,7 +423,7 @@ impl Render for TerminalView { let path = recording .and_then(|recording| recording.path()) .map(|path| path.to_string_lossy().into_owned()); - self.on_commands(v_flex(), cx) + self.on_commands(v_flex(), selected, cx) .size_full() .min_h_0() .children(self.render_find(cx)) diff --git a/crates/terminal/src/view_input_tests.rs b/crates/terminal/src/view_input_tests.rs index fc5c214b..21ff9147 100644 --- a/crates/terminal/src/view_input_tests.rs +++ b/crates/terminal/src/view_input_tests.rs @@ -22,6 +22,101 @@ fn watch( (notifications, outputs, subscriptions) } +#[gpui_kit::test] +fn device_status_queries_reply_without_invalidating_the_visible_grid(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let driver = scripted_driver(&transport, 0); + emit(cx, &transport, 0, Event::Output(b"visible".to_vec())); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + drain(&driver); + let element = cx.update(|cx| element(&view, cx)); + let (notifications, outputs, _subscriptions) = watch(cx, &view); + + for _ in 0..32 { + emit(cx, &transport, 0, Event::Output(b"\x1b[6".to_vec())); + emit(cx, &transport, 0, Event::Output(b"n".to_vec())); + assert_eq!(drain(&driver), [b"\x1b[1;8R".to_vec()]); + cx.update(|cx| assert!(!element.refresh_frame(cx))); + } + assert_eq!(outputs.get(), 0); + assert_eq!(notifications.get(), 0); + + emit(cx, &transport, 0, Event::Output(b"\x1b[H\x1b[6n".to_vec())); + assert_eq!(drain(&driver), [b"\x1b[1;1R".to_vec()]); + assert_eq!(outputs.get(), 1); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + view.read_with(cx, |view, _| { + assert_eq!(view.painted_frame().cursor.unwrap().col, 0); + assert_eq!(view.painted_frame().row_text(0), "visible"); + }); +} + +#[gpui_kit::test] +fn cursor_motion_below_scrollback_replies_without_redrawing(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let driver = scripted_driver(&transport, 0); + emit(cx, &transport, 0, Event::Output(b"history\r\n".repeat(160))); + cx.update_window(handle, |_, window, cx| { + let terminal = view.read(cx).terminal().clone(); + terminal.update(cx, |terminal, cx| terminal.scroll(Scroll::Top, cx)); + window.render_frame(cx); + let frame = view.read(cx).painted_frame(); + assert!(frame.display_offset > usize::from(frame.size.rows)); + assert!(frame.cursor.is_none()); + }) + .unwrap(); + drain(&driver); + let (notifications, outputs, _subscriptions) = watch(cx, &view); + + for (command, reply) in [ + (b"\x1b[1;2H\x1b[6n", b"\x1b[1;2R"), + (b"\x1b[1;4H\x1b[6n", b"\x1b[1;4R"), + ] { + emit(cx, &transport, 0, Event::Output(command.to_vec())); + assert_eq!(drain(&driver), [reply.to_vec()]); + } + assert_eq!(outputs.get(), 0); + assert_eq!(notifications.get(), 0); + + cx.update_window(handle, |_, window, cx| { + let terminal = view.read(cx).terminal().clone(); + terminal.update(cx, |terminal, cx| terminal.scroll(Scroll::Bottom, cx)); + window.render_frame(cx); + assert_eq!(view.read(cx).painted_frame().cursor.unwrap().col, 3); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn device_reply_refusal_publishes_the_input_notice_without_a_grid_change(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let driver = scripted_driver(&transport, 0); + drain(&driver); + let (_, outputs, _subscriptions) = watch(cx, &view); + view.read_with(cx, |view, cx| { + assert!(view.terminal.read(cx).send(vec![b'x'; 4 * 1024 * 1024])); + }); + + emit(cx, &transport, 0, Event::Output(b"\x1b[6n".to_vec())); + assert_eq!(outputs.get(), 0); + cx.update_window(handle, |_, window, cx| { + let terminal = view.read(cx).terminal.read(cx); + assert!(terminal.text_error().unwrap().contains("queue is full")); + assert_eq!(nocterm_ui::notice::count(window, cx), 1); + }) + .unwrap(); + assert_eq!(drain(&driver)[0].len(), 4 * 1024 * 1024); + + emit(cx, &transport, 0, Event::Output(b"\x1b[6n".to_vec())); + assert_eq!(drain(&driver), [b"\x1b[1;1R".to_vec()]); + assert_eq!(outputs.get(), 0); + view.read_with(cx, |view, cx| { + assert!(view.terminal.read(cx).text_error().is_none()); + }); +} + #[gpui_kit::test] fn ordinary_typing_waits_for_delayed_echo_without_redrawing(cx: &mut TestAppContext) { let (handle, view, transport) = fixture(cx); @@ -56,6 +151,64 @@ fn ordinary_typing_waits_for_delayed_echo_without_redrawing(cx: &mut TestAppCont }); } +#[gpui_kit::test] +fn unrelated_settings_leave_the_terminal_screen_and_active_find_unchanged(cx: &mut TestAppContext) { + let (_, view, transport) = fixture(cx); + emit( + cx, + &transport, + 0, + Event::Output(b"needle\r\nneedle".to_vec()), + ); + let terminal = view.read_with(cx, |view, _| view.terminal.clone()); + terminal.update(cx, |terminal, cx| { + terminal.begin_find("needle".into(), SearchDirection::Next, None, cx); + }); + complete(cx, &view); + let settings = terminal.read_with(cx, |terminal, _| terminal.installed().settings().clone()); + let (notifications, outputs, _subscriptions) = watch(cx, &view); + + cx.update(|cx| { + settings + .update::(cx, |settings| { + settings.program = Some("settings-test-shell".into()); + }) + .now_or_never() + .unwrap() + .unwrap(); + }); + cx.run_until_parked(); + assert_eq!(outputs.get(), 0, "unrelated edits must not publish output"); + assert_eq!( + notifications.get(), + 0, + "unrelated edits must not redraw the terminal view" + ); + terminal.read_with(cx, |terminal, _| { + assert_eq!(terminal.find().result().count, 2); + assert!(!terminal.find().searching()); + }); + + cx.update(|cx| { + settings + .update::(cx, |settings| { + settings.cursor_shape = nocterm_ui::CursorShape::Bar; + }) + .now_or_never() + .unwrap() + .unwrap(); + }); + cx.run_until_parked(); + assert!( + outputs.get() > 0, + "emulator option changes still publish output" + ); + assert!( + notifications.get() > 0, + "emulator option changes still redraw the view" + ); +} + #[gpui_kit::test] fn typing_clears_selection_and_returns_scrollback_before_echo(cx: &mut TestAppContext) { let (handle, view, transport) = fixture(cx); diff --git a/crates/terminal/src/view_tests.rs b/crates/terminal/src/view_tests.rs index 6af120fe..32842069 100644 --- a/crates/terminal/src/view_tests.rs +++ b/crates/terminal/src/view_tests.rs @@ -8,6 +8,13 @@ use std::{ sync::{Arc, Mutex}, }; +#[path = "view/find_history_tests.rs"] +mod find_history_tests; +#[path = "view/history_selection_tests.rs"] +mod history_selection_tests; +#[path = "view/output_visibility_tests.rs"] +mod output_visibility_tests; + #[derive(Default)] pub(crate) struct Scripted { drivers: Mutex>>, @@ -643,6 +650,38 @@ fn find_modes_survive_live_output_invalidation_resize_and_throttled_refresh( }); } +#[gpui_kit::test] +fn device_replies_preserve_visible_find_results(cx: &mut TestAppContext) { + let (handle, view, transport) = fixture(cx); + let driver = scripted_driver(&transport, 0); + drain(&driver); + emit(cx, &transport, 0, Event::Output(b"target target".to_vec())); + cx.update_window(handle, |_, window, cx| { + view.update(cx, |v, cx| { + v.open_find(Some("target".into()), false, window, cx) + }); + }) + .unwrap(); + complete(cx, &view); + + emit(cx, &transport, 0, Event::Output(b"\x1b[6n".to_vec())); + assert_eq!(drain(&driver), [b"\x1b[1;14R".to_vec()]); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + let view = view.read(cx); + let find = view.terminal.read(cx).find(); + assert!(!find.searching()); + assert_eq!(find.result().count, 2); + assert!( + view.painted_frame() + .cells + .iter() + .any(|cell| cell.search_hit) + ); + }) + .unwrap(); +} + #[gpui_kit::test] fn semantic_highlighting_updates_open_tabs_without_changing_terminal_text(cx: &mut TestAppContext) { let (handle, view, transport) = fixture(cx); diff --git a/crates/theme-service/src/lib.rs b/crates/theme-service/src/lib.rs index 101f234d..b08e2ae1 100644 --- a/crates/theme-service/src/lib.rs +++ b/crates/theme-service/src/lib.rs @@ -143,7 +143,7 @@ impl ThemesHandle { cx.update(|cx| { handle.0.update(cx, |state, cx| { if let Ok(change) = &result { - state.catalog = Arc::new(change.catalog.clone()); + state.catalog = change.catalog.clone(); state.epoch += 1; } if let Err(error) = &result { diff --git a/crates/theme-service/src/tests.rs b/crates/theme-service/src/tests.rs index aa37db4b..8481f713 100644 --- a/crates/theme-service/src/tests.rs +++ b/crates/theme-service/src/tests.rs @@ -101,3 +101,27 @@ async fn outstanding_mutation_records_have_bounded_admission(cx: &mut TestAppCon )); cx.run_until_parked(); } + +#[gpui::test] +async fn mutation_receipts_share_the_published_catalog(cx: &mut TestAppContext) { + let backend = backend(); + let handle = + cx.update(|cx| ThemesHandle::install(Some(backend.clone()), None, backend.scan(), cx)); + + let installed = cx + .update(|cx| handle.install_pack(info("fake"), cx)) + .await + .unwrap(); + let observed = cx.update(|cx| handle.catalog(cx)); + assert!(Arc::ptr_eq(&installed.catalog, &observed)); + + let removed = cx + .update(|cx| handle.uninstall("fake".into(), cx)) + .await + .unwrap(); + let observed = cx.update(|cx| handle.catalog(cx)); + assert!(observed.entries().is_empty()); + assert!(Arc::ptr_eq(&removed.catalog, &observed)); + assert_eq!(removed.removed, [("Fresh".to_owned(), Appearance::Dark)]); + assert!(installed.catalog.find("Fresh", Appearance::Dark).is_some()); +} diff --git a/crates/themes-registry/src/lib.rs b/crates/themes-registry/src/lib.rs index dc0a5d1d..760df8e2 100644 --- a/crates/themes-registry/src/lib.rs +++ b/crates/themes-registry/src/lib.rs @@ -47,24 +47,22 @@ impl ThemeLibrary for LocalThemeLibrary { archive::install_archive(&self.dirs.installed, extension, &bytes)?; Ok(ThemeChange { operation: ThemeMutation::Install(extension.id.clone()), - catalog: discovery::scan(&self.dirs), + catalog: Arc::new(discovery::scan(&self.dirs)), removed: Vec::new(), }) } fn uninstall(&self, id: &str) -> Result { let _guard = self.mutation.lock().unwrap_or_else(|e| e.into_inner()); - let before = discovery::scan(&self.dirs); - archive::uninstall(&self.dirs.installed, id)?; - let catalog = discovery::scan(&self.dirs); - let removed = before + let removed = discovery::scan(&self.dirs) .entries() .iter() .filter(|e| matches!(&e.source,ThemeSource::Installed{id:pack,..} if pack == id)) .map(|e| (e.name.clone(), e.appearance)) .collect(); + archive::uninstall(&self.dirs.installed, id)?; Ok(ThemeChange { operation: ThemeMutation::Uninstall(id.into()), - catalog, + catalog: Arc::new(discovery::scan(&self.dirs)), removed, }) } diff --git a/crates/themes-registry/src/registry.rs b/crates/themes-registry/src/registry.rs index c5649ec4..f485a21f 100644 --- a/crates/themes-registry/src/registry.rs +++ b/crates/themes-registry/src/registry.rs @@ -179,3 +179,6 @@ mod tests { } } } + +#[cfg(test)] +mod performance; diff --git a/crates/themes-registry/src/registry/performance.rs b/crates/themes-registry/src/registry/performance.rs new file mode 100644 index 00000000..0fd1db46 --- /dev/null +++ b/crates/themes-registry/src/registry/performance.rs @@ -0,0 +1,139 @@ +use super::*; +use flate2::{Compression, write::GzEncoder}; +use nocterm_themes::{Appearance, ThemeDirs, ThemeLibrary}; +use std::{ + fs, + io::{BufRead as _, BufReader, Write as _}, + net::TcpListener, + path::Path, + sync::Arc, + time::Instant, +}; + +fn theme(name: &str, colors: usize) -> Vec { + let style = (0..colors) + .map(|index| (format!("terminal.sample.{index}"), "#102030".into())) + .collect::>(); + serde_json::to_vec(&serde_json::json!({ + "themes": [{"name": name, "appearance": "dark", "style": style}] + })) + .unwrap() +} + +fn archive() -> Vec { + let data = theme("Installed Benchmark", 128); + let mut header = tar::Header::new_gnu(); + header.set_size(data.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::fast())); + archive + .append_data(&mut header, "themes/bench.json", data.as_slice()) + .unwrap(); + archive.into_inner().unwrap().finish().unwrap() +} + +fn seed(directory: &Path, count: usize, colors: usize) { + fs::create_dir(directory).unwrap(); + for index in 0..count { + let name = format!("Local {index:04}"); + fs::write( + directory.join(format!("{index:04}.json")), + theme(&name, colors), + ) + .unwrap(); + } +} + +fn serve_registry(downloads: usize) -> (Arc, std::thread::JoinHandle<()>) { + let archive = archive(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let registry = Arc::new(ZedRegistry { + base: reqwest::Url::parse(&format!("http://{address}/")).unwrap(), + ..ZedRegistry::new().unwrap() + }); + let server = std::thread::spawn(move || { + for _ in 0..downloads { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = String::new(); + let mut reader = BufReader::new(&mut stream); + reader.read_line(&mut request).unwrap(); + assert!( + request.starts_with("GET /extensions/perf/1/download "), + "{request}" + ); + loop { + request.clear(); + assert_ne!(reader.read_line(&mut request).unwrap(), 0); + if request == "\r\n" { + break; + } + } + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + archive.len() + ) + .unwrap(); + stream.write_all(&archive).unwrap(); + } + }); + (registry, server) +} + +#[test] +#[ignore = "release fixture for real theme registry requests, publication and discovery"] +fn measure_install_and_remove_with_large_catalog() { + const REPEATS: usize = 7; + let shapes = [(32, 12), (512, 64), (1_800, 128)]; + let (registry, server) = serve_registry(shapes.len() * REPEATS); + let extension = serde_json::from_str(r#"{"id":"perf","name":"Pack","version":"1"}"#).unwrap(); + for (count, colors) in shapes { + let directory = tempfile::tempdir().unwrap(); + let dirs = ThemeDirs { + user: directory.path().join("user"), + installed: directory.path().join("installed"), + }; + seed(&dirs.user, count, colors); + let manifest = dirs.installed.join("perf/extension.toml"); + let library = crate::LocalThemeLibrary::new(dirs, Some(registry.clone())); + let mut installs = [Duration::ZERO; REPEATS]; + let mut removes = [Duration::ZERO; REPEATS]; + for (install, remove) in installs.iter_mut().zip(&mut removes) { + let start = Instant::now(); + let receipt = library.install(&extension).unwrap(); + *install = start.elapsed(); + assert_eq!(receipt.catalog.entries().len(), count + 1); + assert!( + receipt + .catalog + .find("Installed Benchmark", Appearance::Dark) + .is_some() + ); + assert!(manifest.is_file()); + let start = Instant::now(); + let receipt = library.uninstall("perf").unwrap(); + *remove = start.elapsed(); + assert_eq!( + receipt.removed, + [("Installed Benchmark".to_owned(), Appearance::Dark)] + ); + assert_eq!(receipt.catalog.entries().len(), count); + assert!(!manifest.exists()); + } + installs.sort_unstable(); + removes.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "variants={count} colors={colors} install_median={:?} remove_median={:?}", + installs[REPEATS / 2], + removes[REPEATS / 2] + ) + .unwrap(); + } + server.join().unwrap(); +} diff --git a/crates/themes/src/contracts.rs b/crates/themes/src/contracts.rs index fa0a31e9..43e31048 100644 --- a/crates/themes/src/contracts.rs +++ b/crates/themes/src/contracts.rs @@ -1,7 +1,7 @@ //! Blocking library ports. Callers dispatch them on their executor. use crate::{Appearance, ThemeCatalog, ThemeOperationError}; use serde::{Deserialize, Serialize}; -use std::path::PathBuf; +use std::{path::PathBuf, sync::Arc}; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ExtensionInfo { pub id: String, @@ -33,6 +33,7 @@ pub enum ThemeMutation { #[derive(Debug, Clone)] pub struct ThemeChange { pub operation: ThemeMutation, - pub catalog: ThemeCatalog, + /// The committed catalog shared by the receipt and its observers. + pub catalog: Arc, pub removed: Vec<(String, Appearance)>, } diff --git a/crates/themes/src/test_support.rs b/crates/themes/src/test_support.rs index 25007f88..2e87a1b5 100644 --- a/crates/themes/src/test_support.rs +++ b/crates/themes/src/test_support.rs @@ -7,7 +7,7 @@ use std::{ collections::BTreeMap, path::PathBuf, sync::{ - Mutex, + Arc, Mutex, atomic::{AtomicUsize, Ordering}, }, }; @@ -109,7 +109,7 @@ impl ThemeLibrary for InMemoryThemes { .insert(info.id.clone(), (info.clone(), bytes)); Ok(ThemeChange { operation: ThemeMutation::Install(info.id.clone()), - catalog: catalog(&state), + catalog: Arc::new(catalog(&state)), removed: Vec::new(), }) } @@ -125,7 +125,7 @@ impl ThemeLibrary for InMemoryThemes { .collect(); Ok(ThemeChange { operation: ThemeMutation::Uninstall(id.into()), - catalog: catalog(&state), + catalog: Arc::new(catalog(&state)), removed, }) } diff --git a/crates/themes/src/zed.rs b/crates/themes/src/zed.rs index 3fdaa668..a800f195 100644 --- a/crates/themes/src/zed.rs +++ b/crates/themes/src/zed.rs @@ -75,7 +75,7 @@ pub fn parse_family(bytes: &[u8]) -> Result { return Err(ThemeError::FileLimit); } let bytes = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(bytes); - let value: Value = serde_json_lenient::from_slice(bytes)?; + let mut value: Value = serde_json_lenient::from_slice(bytes)?; let mut family = ThemeFamily { name: value["name"] .as_str() @@ -84,7 +84,8 @@ pub fn parse_family(bytes: &[u8]) -> Result { author: value["author"].as_str().unwrap_or_default().to_owned(), themes: Vec::new(), }; - for theme in value["themes"].as_array().into_iter().flatten() { + let themes = value.get_mut("themes").and_then(Value::as_array_mut); + for theme in themes.into_iter().flatten() { let Some(name) = theme["name"].as_str().filter(|n| !n.trim().is_empty()) else { continue; }; @@ -93,12 +94,24 @@ pub fn parse_family(bytes: &[u8]) -> Result { Some("dark") => Appearance::Dark, _ => continue, }; - let Some(style) = theme["style"].as_object() else { + let name = name.trim().to_owned(); + let Some(Value::Object(style)) = theme.get_mut("style").map(Value::take) else { continue; }; + let players = style + .get("players") + .and_then(Value::as_array) + .into_iter() + .flatten() + .take(1) + .map(|v| Player { + cursor: color(&v["cursor"]), + selection: color(&v["selection"]), + }) + .collect(); let mut colors: BTreeMap<_, _> = style - .iter() - .filter_map(|(k, v)| color(v).map(|c| (k.clone(), c))) + .into_iter() + .filter_map(|(key, value)| color(&value).map(|c| (key, c))) .collect(); for (alias, canonical) in [ ("scrollbar_thumb.background", "scrollbar.thumb.background"), @@ -111,19 +124,8 @@ pub fn parse_family(bytes: &[u8]) -> Result { colors.entry(canonical.into()).or_insert(c); } } - let players = style - .get("players") - .and_then(Value::as_array) - .into_iter() - .flatten() - .take(1) - .map(|v| Player { - cursor: color(&v["cursor"]), - selection: color(&v["selection"]), - }) - .collect(); family.themes.push(ZedTheme { - name: name.trim().into(), + name, appearance, colors, players, diff --git a/crates/themes/src/zed/tests.rs b/crates/themes/src/zed/tests.rs index ba5f58b9..c111b399 100644 --- a/crates/themes/src/zed/tests.rs +++ b/crates/themes/src/zed/tests.rs @@ -245,3 +245,37 @@ fn alternate_sources_and_player_priority_refine_the_palette() { assert_eq!(ui["selection.background"], parse_color("#2348").unwrap()); assert_eq!(palette.terminal.foreground.unwrap().a, 255); } + +#[test] +fn style_parsing_preserves_unknown_colors_and_explicit_alias_targets() { + let family = parse_family( + br##"{ + "themes": [ + null, + {"name":"ignored", "appearance":"dark", "style":false}, + {"name":" Trimmed ", "appearance":"dark", "style":{ + "custom.color":"#123", "scrollbar_thumb.background":"#456", + "scrollbar.thumb.background":"#abc", "players":"#fed", "ignored":{"a":"#789"} + }}, + {"name":"Light", "appearance":"light", "style":{ + "players":[{"cursor":"#444"}, {"cursor":"#555"}] + }} + ] + }"##, + ) + .unwrap(); + let [dark, light] = family.themes.as_slice() else { + panic!("two usable variants"); + }; + assert_eq!(dark.name, "Trimmed"); + assert_eq!(dark.colors.len(), 4); + assert_eq!(dark.colors["custom.color"], parse_color("#123").unwrap()); + assert_eq!( + dark.colors["scrollbar.thumb.background"], + parse_color("#abc").unwrap() + ); + assert_eq!(dark.colors["players"], parse_color("#fed").unwrap()); + assert!(dark.players.is_empty()); + assert_eq!(light.players.len(), 1); + assert_eq!(light.players[0].cursor, parse_color("#444")); +} diff --git a/crates/transfer-runtime/src/batch.rs b/crates/transfer-runtime/src/batch.rs index 1500d6c6..68e901d8 100644 --- a/crates/transfer-runtime/src/batch.rs +++ b/crates/transfer-runtime/src/batch.rs @@ -6,6 +6,7 @@ use nocterm_transfers::{ }; use parking_lot::Mutex; use std::sync::Arc; +use tokio::sync::Notify; pub(crate) struct Batch { sequence: u64, @@ -13,6 +14,7 @@ pub(crate) struct Batch { request: Request, tracker: Mutex, cancellation: CancelFlag, + cancel_waiters: Notify, reservations: Arc, } impl Batch { @@ -29,6 +31,7 @@ impl Batch { tracker: Mutex::new(ProgressTracker::new(id, &request, limits)), request, cancellation: CancelFlag::default(), + cancel_waiters: Notify::new(), reservations: Arc::new(ReservationBook::default()), } } @@ -54,9 +57,18 @@ impl Batch { pub(crate) fn cancelled(&self) -> bool { self.cancellation.is_cancelled() } + pub(crate) async fn wait_cancelled(&self) { + let notified = self.cancel_waiters.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if !self.cancelled() { + notified.await; + } + } pub(crate) fn cancel(&self) { self.cancellation.cancel(); self.event(TransferEvent::CancelRequested); + self.cancel_waiters.notify_waiters(); } pub(crate) fn reservations(&self) -> &Arc { &self.reservations diff --git a/crates/transfer-runtime/src/discovery.rs b/crates/transfer-runtime/src/discovery.rs index 67990b43..3fa354ce 100644 --- a/crates/transfer-runtime/src/discovery.rs +++ b/crates/transfer-runtime/src/discovery.rs @@ -3,9 +3,9 @@ use crate::{ scheduler::{FileJob, QueuedJob, UploadJob, Work}, }; use nocterm_session::{ - EntryKind, FileMetadata, + EntryKind, fs::path, - local_fs::{LocalCursor, LocalDirectory, LocalFsError}, + local_fs::{LocalCursor, LocalDirectory, LocalFsError, LocalSource}, }; use nocterm_transfers::{ DiscoveryBudget, Request, TransferCause, TransferEvent, TransferIssue, TransferOperation, @@ -84,6 +84,11 @@ struct LocalNode { remote: String, depth: usize, } +enum LocalEntry { + File(Box, Option), + Directory, + Skip, +} struct UploadDiscovery { work: Work, sender: mpsc::Sender, @@ -120,16 +125,15 @@ impl UploadDiscovery { .await?; let name_text = name.to_str().ok_or(TransferCause::InvalidName)?; let remote = path::join(&destination, name_text); - self.node(LocalNode { + self.node(&mut LocalNode { directory, name, remote, depth: 0, }) .await?; - while let Some(node) = self.next().await? { - let display = node.directory.location().join(&node.name); - if let Err(cause) = self.node(node).await { + while let Some(mut node) = self.next().await? { + if let Err(cause) = self.node(&mut node).await { if matches!( cause, TransferCause::Limit(nocterm_transfers::LimitKind::Visited) @@ -138,7 +142,9 @@ impl UploadDiscovery { return Err(cause); } self.work.fail( - Some(TransferPath::Local(display)), + Some(TransferPath::Local( + node.directory.location().join(&node.name), + )), TransferOperation::Discover, cause, ); @@ -146,7 +152,7 @@ impl UploadDiscovery { } Ok(()) } - async fn node(&mut self, node: LocalNode) -> Result<(), TransferCause> { + async fn node(&mut self, node: &mut LocalNode) -> Result<(), TransferCause> { self.work.check()?; self.budget.visit(node.depth)?; let text = node.name.to_str().ok_or(TransferCause::InvalidName)?; @@ -155,72 +161,78 @@ impl UploadDiscovery { } let parent = node.directory.clone(); let name = node.name.clone(); - let metadata = self + let cancel = self.work.cancel(); + let entry = self .work .state() .blocking() - .call(self.work.cancel(), move || parent.metadata(&name)) - .await? - .ok_or_else(|| { - TransferCause::Local(LocalFsError::NotFound( + .call(cancel.clone(), move || { + let metadata = parent + .metadata(&name)? + .ok_or_else(|| LocalFsError::NotFound(parent.location().join(&name)))?; + match (metadata.kind, metadata.is_symlink) { + (_, true) | (EntryKind::Other, false) => Ok(LocalEntry::Skip), + (EntryKind::Directory, false) => Ok(LocalEntry::Directory), + (EntryKind::File, false) => { + cancel.check()?; + Ok(LocalEntry::File(parent.open_source(&name)?, metadata.size)) + } + } + }) + .await?; + match entry { + LocalEntry::Skip => { + self.skip(TransferPath::Local( node.directory.location().join(&node.name), - )) - })?; - if special(&metadata) { - self.skip(TransferPath::Local( - node.directory.location().join(&node.name), - )); - return Ok(()); - } - match metadata.kind { - EntryKind::File => self.file(node, metadata).await, - EntryKind::Directory => self.directory(node).await, - EntryKind::Other => Ok(()), + )); + Ok(()) + } + LocalEntry::Directory => self.directory(node).await, + LocalEntry::File(source, expected) => { + self.file(std::mem::take(&mut node.remote), source, expected) + .await + } } } - async fn file(&mut self, node: LocalNode, metadata: FileMetadata) -> Result<(), TransferCause> { - let directory = node.directory; - let name = node.name; - let source = self - .work - .state() - .blocking() - .call(self.work.cancel(), move || directory.open_source(&name)) - .await?; + async fn file( + &mut self, + remote: String, + source: Box, + expected: Option, + ) -> Result<(), TransferCause> { self.work.batch().event(TransferEvent::DiscoveredFile { - bytes: metadata.size.unwrap_or(0), + bytes: expected.unwrap_or(0), }); send( &self.work, &self.sender, - FileJob::Upload(UploadJob::new(source, node.remote, metadata.size)), + FileJob::Upload(UploadJob::new(source, remote, expected)), ) .await } - async fn directory(&mut self, node: LocalNode) -> Result<(), TransferCause> { + async fn directory(&mut self, node: &mut LocalNode) -> Result<(), TransferCause> { self.work .remote(self.work.batch().request().fs().create_dir(&node.remote)) .await?; self.work.batch().event(TransferEvent::DirectoryPrepared); - let parent = node.directory; - let name = node.name; - let directory = self - .work - .state() - .blocking() - .call(self.work.cancel(), move || parent.child(&name)) - .await?; - let for_cursor = directory.clone(); - let cursor = self + let parent = node.directory.clone(); + let name = node.name.clone(); + let cancel = self.work.cancel(); + let (directory, cursor) = self .work .state() .blocking() - .call(self.work.cancel(), move || for_cursor.entries()) + .call(cancel.clone(), move || { + let directory = parent.child(&name)?; + cancel.check()?; + let cursor = directory.entries()?; + Ok((directory, cursor)) + }) .await?; self.stack.push(LocalFrame { directory, cursor, - remote: node.remote, + remote: std::mem::take(&mut node.remote), depth: node.depth + 1, }); Ok(()) @@ -273,9 +285,6 @@ impl UploadDiscovery { skip(&self.work, path); } } -fn special(metadata: &FileMetadata) -> bool { - metadata.is_symlink || metadata.kind == EntryKind::Other -} pub(crate) fn skip(work: &Work, path: TransferPath) { work.batch() .event(TransferEvent::FileSkipped(Some(TransferIssue::new( diff --git a/crates/transfer-runtime/src/download.rs b/crates/transfer-runtime/src/download.rs index a9fba4c2..c01131b9 100644 --- a/crates/transfer-runtime/src/download.rs +++ b/crates/transfer-runtime/src/download.rs @@ -4,7 +4,7 @@ use crate::{ }; use nocterm_session::{ fs::UploadMode, - local_fs::{LocalFsError, LocalStage, PublicationOutcome}, + local_fs::{LocalFsError, LocalResult, LocalStage, PublicationOutcome}, }; use nocterm_transfers::{ CollisionPolicy, LimitKind, TransferCause, TransferEvent, TransferIssue, TransferOperation, @@ -43,35 +43,30 @@ impl StageWriter { self.stage = Some(stage); result.map_err(Into::into) } - async fn sync(&mut self, work: &Work) -> Result<(), TransferCause> { - let mut stage = self.take()?; - let (stage, result) = work - .state() - .blocking() - .call(work.cancel(), move || { - let result = stage.sync(); - Ok((stage, result)) - }) - .await?; - self.stage = Some(stage); - result.map_err(Into::into) - } async fn publish( &mut self, work: &Work, name: OsString, - ) -> Result { + needs_sync: bool, + ) -> Result, TransferCause> { let mut stage = self.take()?; let mode = if work.batch().request().collisions() == CollisionPolicy::Replace { UploadMode::Replace } else { UploadMode::Create }; + let cancel = work.cancel(); let (stage, result) = work .state() .blocking() - .call(work.cancel(), move || { - let result = stage.publish(&name, mode); + .call(cancel.clone(), move || { + let ready = if needs_sync { + stage.sync().and_then(|()| cancel.check()) + } else { + Ok(()) + }; + // Only errors from publication can select a collision retry. + let result = ready.map(|()| stage.publish(&name, mode)); Ok((stage, result)) }) .await?; @@ -133,10 +128,7 @@ async fn receive( .map_err(|(_, cause)| cause); let closed = reader.close().await.map_err(TransferCause::from); match result { - Ok(()) => { - closed?; - stage.sync(work).await - } + Ok(()) => closed, Err(cause) => { if let Err(cleanup) = closed { work.batch().event(TransferEvent::Notice(issue( @@ -167,8 +159,12 @@ async fn publish( mut _reservation: reservations::Reservation, mut number: u32, ) -> Result { + let mut needs_sync = true; loop { - match stage.publish(work, name.clone()).await { + match stage + .publish(work, name.clone(), std::mem::take(&mut needs_sync)) + .await? + { Ok(PublicationOutcome::Published) => return Ok(FileOutcome::Completed), Ok(PublicationOutcome::PublishedWithWarning(warning)) => { work.batch().event(TransferEvent::Notice(issue( @@ -178,12 +174,12 @@ async fn publish( ))); return Ok(FileOutcome::Completed); } - Err(TransferCause::Local(LocalFsError::AlreadyExists(_))) + Err(LocalFsError::AlreadyExists(_)) if work.batch().request().collisions() == CollisionPolicy::Skip => { return Ok(FileOutcome::Skipped(None)); } - Err(TransferCause::Local(LocalFsError::AlreadyExists(_))) + Err(LocalFsError::AlreadyExists(_)) if work.batch().request().collisions() == CollisionPolicy::Rename => { let next = number @@ -201,7 +197,7 @@ async fn publish( _reservation = next_reservation; number = used; } - Err(cause) => return Err(cause), + Err(cause) => return Err(cause.into()), } } // The named reservation is held until publication or failure exits this scope. diff --git a/crates/transfer-runtime/src/remote_discovery.rs b/crates/transfer-runtime/src/remote_discovery.rs index 405d7b57..022b886c 100644 --- a/crates/transfer-runtime/src/remote_discovery.rs +++ b/crates/transfer-runtime/src/remote_discovery.rs @@ -183,7 +183,7 @@ impl RemoteDiscovery { self.work.batch().event(TransferEvent::DirectoryPrepared); let entries = self .work - .remote(self.source_fs.read_dir(&node.source)) + .remote(self.source_fs.read_dir_for_walk(&node.source)) .await?; let bytes = entries.iter().fold(0usize, |total, entry| { total.saturating_add(entry.name.len()) diff --git a/crates/transfer-runtime/src/reservations.rs b/crates/transfer-runtime/src/reservations.rs index a7a12771..313a1aea 100644 --- a/crates/transfer-runtime/src/reservations.rs +++ b/crates/transfer-runtime/src/reservations.rs @@ -1,4 +1,7 @@ -use crate::scheduler::{DownloadJob, Work}; +use crate::{ + changes::Changes, + scheduler::{DownloadJob, Work}, +}; use nocterm_session::{fs::path, local_fs::DirectoryIdentity}; use nocterm_transfers::{CollisionDecision, LimitKind, TransferCause, collision_decision, renamed}; use parking_lot::Mutex; @@ -8,6 +11,7 @@ use std::{collections::HashSet, ffi::OsString, sync::Arc}; pub(crate) struct ReservationBook { remote: Mutex>, local: Mutex>, + released: Changes, } enum Key { Remote(String), @@ -30,9 +34,17 @@ impl Drop for Reservation { .remove(&(identity.clone(), name.clone())); } } + self.book.released.advance(); } } impl ReservationBook { + async fn wait_for_release(&self, revision: u64, work: &Work) -> Result<(), TransferCause> { + tokio::select! { + () = self.released.since(revision) => Ok(()), + () = work.cancelled() => Err(TransferCause::Cancelled), + } + } + fn remote_reserved(&self, path: &str) -> bool { self.remote.lock().contains(path) } @@ -73,6 +85,7 @@ pub(crate) async fn remote( let mut number = start; loop { work.check()?; + let revision = book.released.revision(); let candidate = if number == 0 { original.to_owned() } else { @@ -94,9 +107,7 @@ pub(crate) async fn remote( } } CollisionDecision::Rename => number = next_number(work, number)?, - CollisionDecision::Wait => { - tokio::select! {()=work.cancelled()=>return Err(TransferCause::Cancelled),()=tokio::time::sleep(std::time::Duration::from_millis(10))=>{}} - } + CollisionDecision::Wait => book.wait_for_release(revision, work).await?, } } } @@ -110,6 +121,7 @@ pub(crate) async fn local( let mut number = start; loop { work.check()?; + let revision = book.released.revision(); let original = job.name().to_str().ok_or(TransferCause::InvalidName)?; let name: OsString = if number == 0 { original.to_owned() @@ -137,9 +149,7 @@ pub(crate) async fn local( } } CollisionDecision::Rename => number = next_number(work, number)?, - CollisionDecision::Wait => { - tokio::select! {()=work.cancelled()=>return Err(TransferCause::Cancelled),()=tokio::time::sleep(std::time::Duration::from_millis(10))=>{}} - } + CollisionDecision::Wait => book.wait_for_release(revision, work).await?, } } } diff --git a/crates/transfer-runtime/src/runtime.rs b/crates/transfer-runtime/src/runtime.rs index c4f6d1a9..d9c4d27e 100644 --- a/crates/transfer-runtime/src/runtime.rs +++ b/crates/transfer-runtime/src/runtime.rs @@ -122,13 +122,16 @@ impl TransferRuntime { .build() .map_err(TransferRuntimeError::Executor)?; let (sender, receiver) = mpsc::channel(deps.limits.queue().queued()); + let parallel_files = deps.limits.queue().parallel(); let state = Arc::new(RuntimeState { batches: Mutex::new(BTreeMap::new()), revision: Arc::default(), local: deps.local, limits: deps.limits, - blocking: BlockingDispatcher::new(deps.limits.queue().parallel()), - file_slots: Arc::new(tokio::sync::Semaphore::new(deps.limits.queue().parallel())), + // Each file worker can occupy one blocking slot. Leave room for discovery + // when all file workers are waiting for native I/O. + blocking: BlockingDispatcher::new(parallel_files + 1), + file_slots: Arc::new(tokio::sync::Semaphore::new(parallel_files)), backlog_slots: Arc::new(tokio::sync::Semaphore::new(deps.limits.queue().backlog())), completion: Completion { done: AtomicBool::new(false), diff --git a/crates/transfer-runtime/src/scheduler.rs b/crates/transfer-runtime/src/scheduler.rs index aa3d5cc9..82e4cccd 100644 --- a/crates/transfer-runtime/src/scheduler.rs +++ b/crates/transfer-runtime/src/scheduler.rs @@ -7,7 +7,7 @@ use nocterm_session::{ use nocterm_transfers::{ TransferCause, TransferEvent, TransferIssue, TransferOperation, TransferPath, }; -use std::{ffi::OsString, sync::Arc, time::Duration}; +use std::{ffi::OsString, sync::Arc}; use tokio::sync::mpsc; pub(crate) enum FileJob { @@ -146,9 +146,7 @@ impl Work { Ok(QueuedJob { job, pending }) } pub(crate) async fn cancelled(&self) { - while !self.batch.cancelled() { - tokio::time::sleep(Duration::from_millis(10)).await; - } + self.batch.wait_cancelled().await; } pub(crate) fn fail( &self, diff --git a/crates/transfer-runtime/tests/cases/downloads.rs b/crates/transfer-runtime/tests/cases/downloads.rs index 4239a64f..18fb38b9 100644 --- a/crates/transfer-runtime/tests/cases/downloads.rs +++ b/crates/transfer-runtime/tests/cases/downloads.rs @@ -10,7 +10,11 @@ use nocterm_transfers::{ }; use std::{ ffi::OsStr, - sync::{Arc, Mutex, mpsc}, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + mpsc, + }, time::Duration, }; @@ -78,6 +82,15 @@ fn local_publication_is_invisible_until_complete_and_collision_choices_keep_old_ #[test] fn late_local_collision_renames_the_same_synced_stage_without_reopening_the_reader() { let fixture = Fixture::new(); + let syncs = Arc::new(AtomicUsize::new(0)); + let observed_syncs = syncs.clone(); + fixture + .local + .observe_local(Arc::new(move |operation, _: &std::path::Path| { + if operation == FsOperation::Sync { + observed_syncs.fetch_add(1, Ordering::Relaxed); + } + })); fixture.remote.seed_file("/file.txt", b"incoming").unwrap(); let gate = Gate::pending(); fixture @@ -105,6 +118,7 @@ fn late_local_collision_renames_the_same_synced_stage_without_reopening_the_read assert_eq!(fixture.local_bytes("file.txt"), b"external"); assert_eq!(fixture.local_bytes("file (1).txt"), b"incoming"); assert_eq!(fixture.remote.activity().closed_downloads, 1); + assert_eq!(syncs.load(Ordering::Relaxed), 1); } #[test] fn cancelled_or_failed_reads_discard_private_output_and_release_both_handles() { @@ -226,6 +240,56 @@ fn aliased_held_destination_identity_serializes_same_basename_replace() { assert!(bytes == b"first" || bytes == b"second"); assert_eq!(fixture.local.activity().live_uploads, 0); } +#[test] +fn replace_waits_for_the_reserved_local_name_without_repeated_metadata() { + let fixture = Fixture::new(); + fixture.remote.seed_file("/a/same", b"first").unwrap(); + fixture.remote.seed_file("/b/same", b"second").unwrap(); + let hold = Gate::pending(); + for path in ["/a/same", "/b/same"] { + fixture + .remote + .suspend_next(FsOperation::Read, path, hold.clone()); + } + let probes = Arc::new(AtomicUsize::new(0)); + let observed = probes.clone(); + let path = native("output/same"); + fixture + .local + .observe_local(Arc::new(move |operation, name: &std::path::Path| { + if operation == FsOperation::Metadata && name == path { + observed.fetch_add(1, Ordering::Relaxed); + } + })); + let id = fixture.download( + vec!["/a/same".into(), "/b/same".into()], + CollisionPolicy::Replace, + ); + + wait(|| { + nocterm_transfers::TransferRequests::progress(fixture.runtime.as_ref(), id) + .unwrap() + .discovery_complete + && fixture.remote.activity().live_downloads == 1 + }); + std::thread::sleep(Duration::from_millis(120)); + let metadata_requests = probes.load(Ordering::Relaxed); + let held = fixture.remote.activity(); + hold.release(); + + let progress = fixture.finished(id); + assert_eq!(progress.state, TransferState::Completed); + assert_eq!(progress.completed_files, 2); + assert_eq!(held.live_downloads, 1); + assert_eq!(held.closed_downloads, 0); + assert!( + metadata_requests <= 2, + "expected at most one metadata probe per source while reserved, saw {metadata_requests}" + ); + let contents = fixture.local_bytes("same"); + assert!(contents == b"first" || contents == b"second"); +} + #[test] fn empty_directories_links_special_files_and_hostile_names_are_accounted_without_escape() { let fixture = Fixture::new(); @@ -358,21 +422,61 @@ fn failed_reader_close_or_local_sync_never_authorizes_publication() { fixture.local.fail_next_local( FsOperation::Sync, native("output"), - nocterm_session::local_fs::LocalFsError::from_io( - native("output"), - std::io::Error::other("sync"), - ), + LocalFsError::AlreadyExists(native("output")), ); } let progress = - fixture.finished(fixture.download(vec!["/file".into()], CollisionPolicy::Skip)); + fixture.finished(fixture.download(vec!["/file".into()], CollisionPolicy::Rename)); assert_eq!(progress.state, TransferState::Failed); assert!(LocalFs::open_source(fixture.local.as_ref(), &native("output/file")).is_err()); assert_eq!(fixture.local.activity().live_uploads, 0); + assert_eq!(fixture.local.activity().canceled_uploads, 1); assert_eq!(fixture.remote.activity().live_downloads, 0); } } +#[test] +fn cancellation_waits_for_local_io_and_only_keeps_an_admitted_publication() { + for blocked in [FsOperation::Sync, FsOperation::Finish] { + let fixture = Fixture::new(); + fixture.remote.seed_file("/file", b"incoming").unwrap(); + let (started, operation_started) = mpsc::channel(); + let (release, released) = mpsc::channel::<()>(); + let released = Mutex::new(released); + fixture + .local + .observe_local(Arc::new(move |operation, _: &std::path::Path| { + if operation == blocked { + let _ = started.send(()); + let _ = released.lock().unwrap().recv(); + } + })); + + let id = fixture.download(vec!["/file".into()], CollisionPolicy::Skip); + operation_started + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + assert_eq!(fixture.remote.activity().live_downloads, 0); + fixture.runtime.cancel(id).unwrap(); + let progress = + nocterm_transfers::TransferRequests::progress(fixture.runtime.as_ref(), id).unwrap(); + assert!(!progress.state.finished()); + release.send(()).unwrap(); + + let progress = fixture.finished(id); + assert_eq!(progress.state, TransferState::Cancelled); + let activity = fixture.local.activity(); + assert_eq!(activity.abandoned_uploads, 0); + if blocked == FsOperation::Finish { + assert_eq!(progress.completed_files, 1); + assert_eq!(fixture.local_bytes("file"), b"incoming"); + } else { + assert_eq!(activity.canceled_uploads, 1); + assert!(LocalFs::open_source(fixture.local.as_ref(), &native("output/file")).is_err()); + } + } +} + #[test] fn exhausted_download_walk_stops_instead_of_reporting_every_remaining_name() { let discovery = nocterm_transfers::DiscoveryLimits::with_walk_bounds(4, 2, 100, 4096).unwrap(); diff --git a/crates/transfer-runtime/tests/cases/mixed_storage.rs b/crates/transfer-runtime/tests/cases/mixed_storage.rs new file mode 100644 index 00000000..ca72fc82 --- /dev/null +++ b/crates/transfer-runtime/tests/cases/mixed_storage.rs @@ -0,0 +1,139 @@ +use std::{ + io::Write as _, + path::Path, + sync::{Arc, mpsc}, + thread, + time::{Duration, Instant}, +}; + +use nocterm_session::{ + RemoteFs as _, + testing::{FsOperation, Gate}, +}; +use nocterm_transfers::{ + CollisionPolicy, TransferId, TransferLimits, TransferRequests as _, TransferState, +}; + +use super::{Fixture, native}; + +fn downloads_waiting_for_sync(fixture: &Fixture) -> (TransferId, Gate) { + let gate = Gate::pending(); + let hold = gate.clone(); + let (at_sync, syncs) = mpsc::channel(); + fixture + .local + .observe_local(Arc::new(move |operation, _: &Path| { + if operation == FsOperation::Sync { + let _ = at_sync.send(()); + futures::executor::block_on(hold.wait()); + } + })); + let parallel = TransferLimits::default().queue().parallel(); + let sources = (0..parallel) + .map(|file| { + let name = format!("/incoming-{file}"); + fixture.remote.seed_file(&name, b"incoming").unwrap(); + name + }) + .collect(); + let id = fixture.download(sources, CollisionPolicy::Skip); + for _ in 0..parallel { + if let Err(error) = syncs.recv_timeout(Duration::from_secs(5)) { + gate.release(); + panic!("a download did not start syncing: {error}"); + } + } + (id, gate) +} + +fn check_downloads(fixture: &Fixture, download: TransferId) { + let done = fixture.finished(download); + assert_eq!(done.state, TransferState::Completed); + let parallel = TransferLimits::default().queue().parallel(); + assert_eq!(done.completed_files, parallel as u64); + for file in 0..parallel { + assert_eq!( + fixture.local_bytes(&format!("incoming-{file}")), + b"incoming" + ); + } +} + +#[test] +fn an_empty_directory_upload_finishes_while_download_syncs_are_held() { + let fixture = Fixture::new(); + let source = native("input/empty"); + fixture.local.seed_native_directory(&source).unwrap(); + let (download, gate) = downloads_waiting_for_sync(&fixture); + let upload = fixture.upload(vec![source], CollisionPolicy::Skip); + let deadline = Instant::now() + Duration::from_secs(3); + let observed = loop { + let progress = fixture.runtime.progress(upload).unwrap(); + if progress.state.finished() || Instant::now() >= deadline { + break progress; + } + thread::sleep(Duration::from_millis(1)); + }; + let still_waiting = fixture.runtime.progress(download).unwrap(); + gate.release(); + check_downloads(&fixture, download); + + assert!(!still_waiting.state.finished()); + assert_eq!(observed.state, TransferState::Completed); + assert_eq!(observed.prepared_directories, 1); + assert!( + futures::executor::block_on(fixture.remote.stat("/dest/empty")) + .unwrap() + .is_some() + ); +} + +#[test] +#[ignore = "manual release timing fixture for simultaneous uploads and local syncs"] +fn measure_upload_discovery_during_held_download_syncs() { + for hold in [Duration::ZERO, Duration::from_millis(120)] { + let mut samples = Vec::new(); + for _ in 0..8 { + let fixture = Fixture::new(); + let source = native("input/outgoing"); + fixture + .local + .seed_native_file(&source, b"outgoing") + .unwrap(); + let (download, gate) = downloads_waiting_for_sync(&fixture); + let started = Instant::now(); + let upload = fixture.upload(vec![source], CollisionPolicy::Skip); + let mut first_file = None; + loop { + let progress = fixture.runtime.progress(upload).unwrap(); + let elapsed = started.elapsed(); + if progress.discovered_files == 1 { + first_file.get_or_insert(elapsed); + } + if elapsed >= hold { + gate.release(); + } + if progress.state.finished() { + assert_eq!(progress.sent_bytes, 8); + samples.push(( + first_file.unwrap().as_secs_f64() * 1_000., + elapsed.as_secs_f64() * 1_000., + )); + break; + } + if elapsed >= Duration::from_secs(5) { + panic!("upload stalled"); + } + thread::sleep(Duration::from_micros(250)); + } + assert_eq!(fixture.remote.bytes("/dest/outgoing").unwrap(), b"outgoing"); + check_downloads(&fixture, download); + } + writeln!( + std::io::stdout().lock(), + "hold_ms={} discovery_and_finish_ms={samples:?}", + hold.as_millis() + ) + .unwrap(); + } +} diff --git a/crates/transfer-runtime/tests/cases/progress.rs b/crates/transfer-runtime/tests/cases/progress.rs new file mode 100644 index 00000000..dc7821e0 --- /dev/null +++ b/crates/transfer-runtime/tests/cases/progress.rs @@ -0,0 +1,72 @@ +use std::{hint::black_box, io::Write as _, time::Instant}; + +use nocterm_session::{ + FsError, + testing::{FsOperation, Gate}, +}; +use nocterm_transfers::{CollisionPolicy, TransferCause, TransferService as _}; + +use super::{Fixture, wait}; + +#[test] +#[ignore = "manual release timing fixture for published transfer progress"] +fn measure_snapshots_with_retained_transfer_diagnostics() { + for (history, issues) in [(0, 0), (64, 0), (64, 100)] { + let fixture = Fixture::new(); + let mut ids = Vec::new(); + for index in 0..history { + let source = format!("/completed-{index}"); + fixture + .remote + .seed_file(&source, b"complete".to_vec()) + .unwrap(); + let mut sources = vec![source]; + sources.extend((0..issues).map(|issue| format!("/missing-{index}-{issue}"))); + let id = fixture.download(sources, CollisionPolicy::Skip); + let done = fixture.finished(id); + assert_eq!(done.sent_bytes, 8); + assert_eq!(done.errors.len(), issues); + assert!(done.errors.iter().all(|issue| matches!( + issue.cause(), + TransferCause::Remote(FsError::NotFound { .. }) + ))); + ids.push(id); + } + + let payload = vec![0x5a; 256 * 1024]; + fixture + .remote + .seed_file("/active", payload.clone()) + .unwrap(); + let gate = Gate::pending(); + fixture + .remote + .suspend_next(FsOperation::Read, "/active", gate.clone()); + let active = fixture.download(vec!["/active".into()], CollisionPolicy::Skip); + wait(|| fixture.remote.activity().live_downloads == 1); + ids.push(active); + let snapshot = fixture.runtime.snapshot(); + assert!(snapshot.iter().map(|row| row.id).eq(ids.into_iter().rev())); + assert!(!snapshot[0].state.finished()); + + let mut samples = Vec::with_capacity(2_000); + for _ in 0..2_000 { + let start = Instant::now(); + drop(black_box(fixture.runtime.snapshot())); + samples.push(start.elapsed().as_nanos()); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "history={history}, issues={issues}, snapshot median/p95 ns: {}/{}", + samples[1_000], + samples[1_900] + ) + .unwrap(); + + gate.release(); + assert_eq!(fixture.finished(active).sent_bytes, payload.len() as u64); + assert_eq!(fixture.local_bytes("active"), payload); + assert!(!snapshot[0].state.finished()); + } +} diff --git a/crates/transfer-runtime/tests/cases/uploads.rs b/crates/transfer-runtime/tests/cases/uploads.rs index 202a128d..99bcb89b 100644 --- a/crates/transfer-runtime/tests/cases/uploads.rs +++ b/crates/transfer-runtime/tests/cases/uploads.rs @@ -7,7 +7,7 @@ use nocterm_transfers::{ CollisionPolicy, TransferCause, TransferError, TransferOperation, TransferPath, TransferService, TransferState, UploadRequest, }; -use std::sync::Arc; +use std::{sync::Arc, time::Duration}; #[test] fn many_files_stream_with_four_writers_and_bounded_acknowledgement_batches() { @@ -253,6 +253,51 @@ fn same_basename_sources_reserve_distinct_rename_destinations() { bytes.sort(); assert_eq!(bytes, [b"first".to_vec(), b"second".to_vec()]); } +#[test] +fn replace_waits_for_the_reserved_remote_name_without_repeated_requests() { + let fixture = Fixture::new(); + let first = native("input/a/same.txt"); + let second = native("input/b/same.txt"); + fixture + .local + .seed_native_file(&first, b"first".to_vec()) + .unwrap(); + fixture + .local + .seed_native_file(&second, b"second".to_vec()) + .unwrap(); + let hold = Gate::pending(); + fixture + .remote + .suspend_next(FsOperation::Write, "/dest/same.txt", hold.clone()); + let before = fixture.remote.activity().requests; + let id = fixture.upload(vec![first, second], CollisionPolicy::Replace); + + wait(|| { + nocterm_transfers::TransferRequests::progress(fixture.runtime.as_ref(), id) + .unwrap() + .discovery_complete + && fixture.remote.activity().live_uploads == 1 + }); + // Keep the writer alive long enough for a polling waiter to re-probe repeatedly. + std::thread::sleep(Duration::from_millis(120)); + let held = fixture.remote.activity(); + hold.release(); + + let progress = fixture.finished(id); + assert_eq!(progress.state, TransferState::Completed); + assert_eq!(progress.completed_files, 2); + assert_eq!(held.completed_uploads, 0); + assert_eq!(held.live_uploads, 1); + assert!( + held.requests - before <= 4, + "expected at most a stat for each source and one open/write while reserved, saw {}", + held.requests - before + ); + let contents = fixture.remote.bytes("/dest/same.txt").unwrap(); + assert!(contents == b"first" || contents == b"second"); +} + #[test] fn strict_upload_discovery_skips_links_special_entries_and_preserves_empty_directories() { let fixture = Fixture::new(); @@ -466,6 +511,57 @@ fn acknowledged_upload_directory_survives_later_source_listing_failure() { .is_some() ); } +#[test] +fn inaccessible_upload_descendants_report_their_paths_and_do_not_stop_the_walk() { + use nocterm_session::local_fs::LocalFsError; + + let fixture = Fixture::new(); + let source = native("input/tree"); + let blocked = source.join("blocked"); + let unreadable = source.join("unreadable"); + fixture.local.seed_native_directory(&source).unwrap(); + fixture.local.seed_native_directory(&blocked).unwrap(); + fixture + .local + .seed_native_file(&unreadable, b"hidden") + .unwrap(); + fixture + .local + .seed_native_file(&source.join("visible"), b"data") + .unwrap(); + for (operation, path) in [ + (FsOperation::List, &blocked), + (FsOperation::Metadata, &unreadable), + ] { + fixture.local.fail_next_local( + operation, + path.clone(), + LocalFsError::PermissionDenied(path.clone()), + ); + } + + let progress = fixture.finished(fixture.upload(vec![source], CollisionPolicy::Skip)); + assert_eq!(progress.state, TransferState::Failed); + assert_eq!(progress.prepared_directories, 2); + assert_eq!(progress.failed_files, 2); + assert_eq!(progress.completed_files, 1); + assert_eq!(progress.sent_bytes, 4); + assert_eq!(fixture.remote.bytes("/dest/tree/visible").unwrap(), b"data"); + assert_eq!(progress.errors.len(), 2); + for path in [blocked, unreadable] { + let expected = TransferPath::Local(path.clone()); + let issue = progress + .errors + .iter() + .find(|issue| issue.path() == Some(&expected)) + .unwrap(); + assert_eq!(issue.operation(), TransferOperation::Discover); + assert!( + matches!(issue.cause(), TransferCause::Local(LocalFsError::PermissionDenied(actual)) if actual == &path) + ); + } +} + #[test] fn acknowledged_upload_directory_survives_cancellation_before_file_completion() { let fixture = Fixture::new(); diff --git a/crates/transfer-runtime/tests/transfers.rs b/crates/transfer-runtime/tests/transfers.rs index 37db302c..d62aad20 100644 --- a/crates/transfer-runtime/tests/transfers.rs +++ b/crates/transfer-runtime/tests/transfers.rs @@ -3,6 +3,10 @@ mod support; use support::*; #[path = "cases/downloads.rs"] mod downloads; +#[path = "cases/mixed_storage.rs"] +mod mixed_storage; +#[path = "cases/progress.rs"] +mod progress; #[path = "cases/relays.rs"] mod relays; #[path = "cases/uploads.rs"] diff --git a/crates/transfers/src/lib.rs b/crates/transfers/src/lib.rs index 42fd258b..344a9e80 100644 --- a/crates/transfers/src/lib.rs +++ b/crates/transfers/src/lib.rs @@ -27,7 +27,7 @@ pub use limits::{ pub use owned::{OwnedLimits, OwnedTransferError, OwnedTransfers}; pub use progress::{ Progress, ProgressTracker, TransferCause, TransferDirection, TransferEvent, TransferIssue, - TransferOperation, TransferPath, TransferState, + TransferIssues, TransferOperation, TransferPath, TransferState, }; pub use request::{DownloadRequest, RelayRequest, Request, UploadRequest, valid_relay_source}; pub use service::{TransferError, TransferId, TransferRequests, TransferService}; diff --git a/crates/transfers/src/progress.rs b/crates/transfers/src/progress.rs index d23a5392..8662c476 100644 --- a/crates/transfers/src/progress.rs +++ b/crates/transfers/src/progress.rs @@ -4,7 +4,7 @@ use nocterm_session::{ FsError, HostAddress, local_fs::{DurabilityWarning, LocalFsError}, }; -use std::{error::Error, fmt, path::PathBuf, sync::Arc}; +use std::{error::Error, fmt, ops::Deref, path::PathBuf, sync::Arc}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TransferState { Queued, @@ -43,8 +43,33 @@ pub struct Progress { pub total_bytes: u64, pub sent_bytes: u64, pub discovery_complete: bool, - pub errors: Vec, + pub errors: TransferIssues, } + +/// A read-only diagnostic list shared by progress snapshots until a new issue arrives. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TransferIssues(Option>>); + +impl Deref for TransferIssues { + type Target = [TransferIssue]; + + fn deref(&self) -> &Self::Target { + self.0.as_deref().map_or(&[], Vec::as_slice) + } +} + +impl From> for TransferIssues { + fn from(issues: Vec) -> Self { + Self((!issues.is_empty()).then(|| Arc::new(issues))) + } +} + +impl TransferIssues { + fn push(&mut self, issue: TransferIssue) { + Arc::make_mut(self.0.get_or_insert_with(Default::default)).push(issue); + } +} + #[derive(Clone, Debug, PartialEq, Eq)] pub enum TransferPath { Local(PathBuf), @@ -216,7 +241,7 @@ impl ProgressTracker { total_bytes: 0, sent_bytes: 0, discovery_complete: false, - errors: Vec::new(), + errors: TransferIssues::default(), }, workers_done: false, detail_limit: limits.details(), diff --git a/crates/transfers/tests/progress.rs b/crates/transfers/tests/progress.rs index 75f9e455..3291e75f 100644 --- a/crates/transfers/tests/progress.rs +++ b/crates/transfers/tests/progress.rs @@ -80,6 +80,26 @@ fn diagnostic_details_are_bounded_and_failures_survive_truncation() { assert_eq!(snapshot.state, TransferState::Failed); } #[test] +fn published_progress_keeps_its_diagnostics_as_the_transfer_changes() { + let mut tracker = tracker(); + let first = TransferIssue::new(None, TransferOperation::Read, TransferCause::InvalidName); + let second = TransferIssue::new(None, TransferOperation::Write, TransferCause::Cancelled); + let empty = tracker.snapshot(); + tracker.apply(TransferEvent::FileFailed(first.clone())); + let initial = tracker.snapshot(); + tracker.apply(TransferEvent::FileFailed(second.clone())); + tracker.apply(TransferEvent::DiscoveryComplete); + tracker.apply(TransferEvent::WorkersDrained); + let final_progress = tracker.snapshot(); + + assert!(empty.errors.is_empty()); + assert_eq!(initial.failed_files, 1); + assert_eq!(&*initial.errors, std::slice::from_ref(&first)); + assert_eq!(final_progress.state, TransferState::Failed); + assert_eq!(final_progress.failed_files, 2); + assert_eq!(&*final_progress.errors, &[first, second]); +} +#[test] fn notices_do_not_turn_a_committed_file_into_failure() { let mut tracker = tracker(); tracker.apply(TransferEvent::Notice(TransferIssue::new( diff --git a/crates/ui/src/appearance_page/commands.rs b/crates/ui/src/appearance_page/commands.rs index cee69e0e..99983612 100644 --- a/crates/ui/src/appearance_page/commands.rs +++ b/crates/ui/src/appearance_page/commands.rs @@ -3,7 +3,7 @@ use crate::notice; use crate::{AppearanceMode, PickerOption, open_choice_picker}; use gpui_kit::{App, Window, component::ActiveTheme as _}; -use super::{choices, selection}; +use super::{DEFAULT_THEME, available_theme, choices, requested_theme}; #[derive(Clone)] enum Choice { @@ -25,8 +25,13 @@ pub fn open_theme_picker( } else { nocterm_themes::Appearance::Light }; - let selected = selection(themes, settings, appearance, cx); - let options = choices(themes, appearance, cx) + let catalog = themes.themes().catalog(cx); + let current = requested_theme( + settings.setting::(cx), + appearance, + ); + let selected = available_theme(current, &catalog, appearance).unwrap_or(DEFAULT_THEME); + let options = choices(&catalog, appearance) .into_iter() .map(|name| { let checked = name == selected; @@ -83,7 +88,7 @@ fn save( ) { let task = settings.update::(cx, move |settings| match choice { Choice::Theme { dark, name } => { - let name = (name != "Nocterm Default").then_some(name); + let name = (name != DEFAULT_THEME).then_some(name); if dark { settings.dark_theme = name; } else { diff --git a/crates/ui/src/appearance_page/installed.rs b/crates/ui/src/appearance_page/installed.rs index e0ff19a7..85f734da 100644 --- a/crates/ui/src/appearance_page/installed.rs +++ b/crates/ui/src/appearance_page/installed.rs @@ -10,8 +10,7 @@ use gpui_kit::{ }, prelude::*, }; -use nocterm_themes::{Appearance, ThemeSource}; -use std::collections::BTreeSet; +use nocterm_themes::Appearance; pub(super) fn remove( view: &mut AppearanceSettingsPage, @@ -149,32 +148,7 @@ pub(super) fn render( rows.push(form::error_text(error.clone(), cx)); } } - append_diagnostics(&catalog, &mut rows, cx); - form::section("Installed themes", rows, cx) -} - -fn append_diagnostics( - catalog: &nocterm_themes::ThemeCatalog, - rows: &mut Vec, - cx: &mut Context, -) { - let files: BTreeSet<_> = catalog - .entries() - .iter() - .filter_map(|e| match &e.source { - ThemeSource::User(p) => Some(p.clone()), - _ => None, - }) - .collect(); - for file in files { - rows.push(form::note( - format!( - "User file: {}", - file.file_name().unwrap_or_default().to_string_lossy() - ), - cx, - )); - } + rows.extend(view.user_files.element()); if catalog.packs().is_empty() && catalog.entries().is_empty() { rows.push(form::note( "No themes installed. Browse Zed below or add a JSON file to the themes folder.", @@ -187,4 +161,5 @@ fn append_diagnostics( cx, )); } + form::section("Installed themes", rows, cx) } diff --git a/crates/ui/src/appearance_page/mod.rs b/crates/ui/src/appearance_page/mod.rs index 6c6f6c5e..d8171770 100644 --- a/crates/ui/src/appearance_page/mod.rs +++ b/crates/ui/src/appearance_page/mod.rs @@ -10,25 +10,71 @@ use gpui_kit::{ }, prelude::*, }; -use nocterm_themes::Appearance; -use std::collections::BTreeMap; +use nocterm_themes::{Appearance, ThemeCatalog}; +use std::{ + collections::BTreeMap, + sync::{Arc, Weak}, +}; mod browser; pub(crate) mod commands; mod controls; mod installed; #[cfg(test)] mod tests; +mod user_files; use browser::ThemeBrowser; type Picker = Entity>>; +const DEFAULT_THEME: &str = "Nocterm Default"; + +struct ThemePicker { + widget: Picker, + available: bool, +} + +impl ThemePicker { + fn new( + current: Option<&str>, + catalog: &ThemeCatalog, + appearance: Appearance, + window: &mut Window, + cx: &mut App, + ) -> Self { + let available = available_theme(current, catalog, appearance); + let items = choices(catalog, appearance); + let selected = available.unwrap_or(DEFAULT_THEME); + let index = items.iter().position(|name| name == selected).unwrap_or(0); + let widget = cx.new(|cx| { + SelectState::new( + SearchableVec::new(items), + Some(IndexPath::new(index)), + window, + cx, + ) + .searchable(true) + }); + Self { + widget, + available: available.is_some(), + } + } +} + +struct ThemePickers { + catalog: Weak, + published: AppearanceSettings, + light: ThemePicker, + dark: ThemePicker, +} + struct AppearanceSettingsPage { themes: ThemeUi, settings: nocterm_store::SettingsHandle, - light: Picker, - dark: Picker, + pickers: ThemePickers, browser: Entity, errors: BTreeMap, folder_error: Option, + user_files: user_files::UserFiles, _subscriptions: Vec, fields: std::collections::BTreeMap, focus: gpui_kit::FocusHandle, @@ -42,29 +88,36 @@ impl AppearanceSettingsPage { cx: &mut Context, ) -> Self { let settings = context.settings().clone(); - let picker = |appearance, window: &mut Window, cx: &mut Context| { - let items = choices(&themes, appearance, cx); - let selected = selection(&themes, &settings, appearance, cx); - let index = items.iter().position(|name| name == &selected).unwrap_or(0); - cx.new(|cx| { - SelectState::new( - SearchableVec::new(items), - Some(IndexPath::new(index)), - window, - cx, - ) - .searchable(true) - }) + let catalog = themes.themes().catalog(cx); + let published = settings.setting::(cx).clone(); + let pickers = ThemePickers { + catalog: Arc::downgrade(&catalog), + light: ThemePicker::new( + published.light_theme.as_deref(), + &catalog, + Appearance::Light, + window, + cx, + ), + dark: ThemePicker::new( + published.dark_theme.as_deref(), + &catalog, + Appearance::Dark, + window, + cx, + ), + published, }; - let light = picker(Appearance::Light, window, cx); - let dark = picker(Appearance::Dark, window, cx); let mut subscriptions = Vec::new(); - for (picker, appearance) in [(&light, Appearance::Light), (&dark, Appearance::Dark)] { + for (picker, appearance) in [ + (&pickers.light.widget, Appearance::Light), + (&pickers.dark.widget, Appearance::Dark), + ] { let subscription = cx.subscribe( picker, move |this, _, event: &SelectEvent>, cx| { let SelectEvent::Confirm(name) = event; - let name = name.clone().filter(|s| s != "Nocterm Default"); + let name = name.clone().filter(|s| s != DEFAULT_THEME); this.save( move |s: &mut crate::AppearanceSettings| match appearance { Appearance::Light => s.light_theme = name, @@ -86,19 +139,20 @@ impl AppearanceSettingsPage { subscriptions.push(settings.observe(cx, move |cx| { let _ = original_window.update(cx, |_, window, cx| { let _ = weak.update(cx, |this, cx| { - this.sync(window, cx); - cx.notify(); + if this.sync(window, cx) { + cx.notify(); + } }); }); })); let mut this = Self { themes, settings, - light, - dark, + pickers, browser, errors: BTreeMap::new(), folder_error: None, + user_files: user_files::UserFiles::default(), _subscriptions: subscriptions, fields: BTreeMap::new(), focus: cx.focus_handle(), @@ -107,49 +161,70 @@ impl AppearanceSettingsPage { appearance_fields(&mut this, window, cx); this } - pub(crate) fn sync(&mut self, window: &mut Window, cx: &mut Context) { - for (picker, appearance) in [ - (&self.light, Appearance::Light), - (&self.dark, Appearance::Dark), + fn sync(&mut self, window: &mut Window, cx: &mut Context) -> bool { + let catalog = self.themes.themes().catalog(cx); + let catalog_changed = !std::ptr::eq(self.pickers.catalog.as_ptr(), Arc::as_ptr(&catalog)); + let current = self.settings.setting::(cx); + let appearance_changed = self.pickers.published != *current; + let light_changed = self.pickers.published.light_theme != current.light_theme; + let dark_changed = self.pickers.published.dark_theme != current.dark_theme; + if appearance_changed { + self.pickers.published.clone_from(current); + } + for (picker, appearance, selection_changed) in [ + (&mut self.pickers.light, Appearance::Light, light_changed), + (&mut self.pickers.dark, Appearance::Dark, dark_changed), ] { - let items = choices(&self.themes, appearance, cx); - let selected = selection(&self.themes, &self.settings, appearance, cx); - picker.update(cx, |state, cx| { - state.set_items(SearchableVec::new(items), window, cx); - state.set_selected_value(&selected, window, cx); - }); + let name = requested_theme(&self.pickers.published, appearance); + if catalog_changed || selection_changed { + picker.available = available_theme(name, &catalog, appearance).is_some(); + } + let selected = name.filter(|_| picker.available).unwrap_or(DEFAULT_THEME); + let committed = picker.widget.read(cx).selected_value().map(String::as_str); + // Setting the same value would also clear the active query. + if catalog_changed || committed != Some(selected) { + picker.widget.update(cx, |state, cx| { + if catalog_changed { + state.set_items( + SearchableVec::new(choices(&catalog, appearance)), + window, + cx, + ); + } + state.set_selected_value(&selected.to_owned(), window, cx); + }); + } } + if catalog_changed { + self.pickers.catalog = Arc::downgrade(&catalog); + } + appearance_changed + } +} + +fn requested_theme(settings: &AppearanceSettings, appearance: Appearance) -> Option<&str> { + match appearance { + Appearance::Light => settings.light_theme.as_deref(), + Appearance::Dark => settings.dark_theme.as_deref(), } } -fn selection( - themes: &ThemeUi, - settings: &nocterm_store::SettingsHandle, + +fn available_theme<'a>( + name: Option<&'a str>, + catalog: &ThemeCatalog, appearance: Appearance, - cx: &App, -) -> String { - let name = match appearance { - Appearance::Light => { - &settings - .setting::(cx) - .light_theme - } - Appearance::Dark => &settings.setting::(cx).dark_theme, - }; - name.as_ref() - .filter(|name| themes.themes().catalog(cx).find(name, appearance).is_some()) - .cloned() - .unwrap_or("Nocterm Default".into()) +) -> Option<&'a str> { + name.filter(|name| catalog.find(name, appearance).is_some()) } -fn choices(themes: &ThemeUi, appearance: Appearance, cx: &App) -> Vec { - std::iter::once("Nocterm Default".into()) + +fn choices(catalog: &ThemeCatalog, appearance: Appearance) -> Vec { + std::iter::once(DEFAULT_THEME.into()) .chain( - themes - .themes() - .catalog(cx) + catalog .entries() .iter() - .filter(|e| e.appearance == appearance) - .map(|e| e.name.clone()), + .filter(|entry| entry.appearance == appearance) + .map(|entry| entry.name.clone()), ) .collect() } @@ -223,14 +298,16 @@ fn render( form::stacked_row( "Light theme", "Used in Light mode and when the system uses light appearance.", - Select::new(&view.light).small(), + Select::new(&view.pickers.light.widget).small(), None, cx, ), form::stacked_row( "Dark theme", "Used in Dark mode and when the system uses dark appearance.", - Select::new(&view.dark).small(), + Select::new(&view.pickers.dark.widget) + .id("dark-theme-picker") + .small(), None, cx, ), @@ -338,6 +415,7 @@ impl crate::SettingsPage for AppearanceSettingsPage { } impl gpui_kit::Render for AppearanceSettingsPage { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl gpui_kit::IntoElement { + self.user_files.prepare(&self.themes.themes().catalog(cx)); let sections = render(self, cx); gpui_kit::component::v_flex() .w_full() diff --git a/crates/ui/src/appearance_page/tests.rs b/crates/ui/src/appearance_page/tests.rs index d72dfe89..5eabc52c 100644 --- a/crates/ui/src/appearance_page/tests.rs +++ b/crates/ui/src/appearance_page/tests.rs @@ -1,7 +1,13 @@ //! Appearance behavior through rendered controls and explicit shared ports. use super::AppearanceSettingsPage; use crate::{AppearanceSettings, ThemeUi}; -use gpui_kit::{AppContext as _, Entity, TestAppContext, WindowOptions, test::TestWindowExt as _}; +use gpui_kit::{ + AppContext as _, Entity, Pixels, ScrollDelta, ScrollHandle, TestAppContext, WindowOptions, div, + point, + prelude::*, + px, + test::{TestSupportExt as _, TestWindowExt as _}, +}; use nocterm_themes::{Appearance, ExtensionInfo, ThemeLibrary, test_support::InMemoryThemes}; use std::sync::Arc; fn info(id: &str) -> ExtensionInfo { @@ -23,6 +29,40 @@ fn setup( gpui_kit::AnyWindowHandle, Entity, ThemeUi, +) { + setup_scroll(cx, backend, px(2000.), ScrollHandle::new()) +} + +struct AppearanceScroll { + view: Entity, + scroll: ScrollHandle, +} + +impl gpui_kit::Render for AppearanceScroll { + fn render( + &mut self, + _: &mut gpui_kit::Window, + _: &mut gpui_kit::Context, + ) -> impl gpui_kit::IntoElement { + div() + .id("appearance-scroll") + .test_support() + .size_full() + .overflow_y_scroll() + .track_scroll(&self.scroll) + .child(self.view.clone()) + } +} + +fn setup_scroll( + cx: &mut TestAppContext, + backend: Arc, + height: Pixels, + scroll: ScrollHandle, +) -> ( + gpui_kit::AnyWindowHandle, + Entity, + ThemeUi, ) { cx.update(|cx| { gpui_kit::init(cx); @@ -51,13 +91,13 @@ fn setup( WindowOptions { window_bounds: Some(gpui_kit::WindowBounds::Windowed(gpui_kit::Bounds::new( gpui_kit::point(gpui_kit::px(0.), gpui_kit::px(0.)), - gpui_kit::size(gpui_kit::px(1100.), gpui_kit::px(2000.)), + gpui_kit::size(gpui_kit::px(1100.), height), ))), ..WindowOptions::default() }, cx, |window, cx| { - cx.new(|cx| { + let view = cx.new(|cx| { AppearanceSettingsPage::new( supplied, crate::SettingsPageContext::new( @@ -67,11 +107,12 @@ fn setup( window, cx, ) - }) + }); + cx.new(|_| AppearanceScroll { view, scroll }) }, ) .unwrap(); - (handle, view, themes) + (handle, view.read(cx).view.clone(), themes) }) } fn click(handle: gpui_kit::AnyWindowHandle, id: &'static str, cx: &mut TestAppContext) { @@ -198,3 +239,326 @@ fn shared_status_and_admitted_install_survive_the_originating_page(cx: &mut Test }); assert_eq!(backend.installs(), 1); } + +fn user_files(backend: &InMemoryThemes, start: usize, end: usize) { + for index in start..end { + let path = if index.is_multiple_of(5) { + format!("Theme-{index:04} {}.json", "界 ".repeat(58)) + } else { + format!("Theme-{index:04}.json") + }; + let bytes = serde_json::to_vec(&serde_json::json!({ + "themes": [{ + "name": format!("User Theme {index:04}"), + "appearance": "dark", + "style": { "background": "#234" } + }] + })) + .unwrap(); + backend.user_document(path.into(), bytes); + } +} + +fn search_dark_themes(handle: gpui_kit::AnyWindowHandle, query: &str, cx: &mut TestAppContext) { + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.within("dark-theme-picker").click("input", cx); + window.input(query, cx); + }) + .unwrap(); + cx.executor() + .advance_clock(std::time::Duration::from_millis(250)); + cx.run_until_parked(); +} + +fn confirm_dark_theme( + handle: gpui_kit::AnyWindowHandle, + themes: &ThemeUi, + expected: &str, + cx: &mut TestAppContext, +) { + cx.update_window(handle, |_, window, cx| window.press("enter", cx)) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert_eq!( + themes + .settings() + .setting::(cx) + .dark_theme + .as_deref(), + Some(expected) + ); + }); +} + +#[gpui_kit::test] +fn searching_the_dark_picker_commits_the_filtered_theme(cx: &mut TestAppContext) { + let backend = backend(); + user_files(&backend, 0, 32); + let (handle, _, themes) = setup(cx, backend); + search_dark_themes(handle, "User Theme 0017", cx); + confirm_dark_theme(handle, &themes, "User Theme 0017", cx); +} + +#[gpui_kit::test] +async fn another_settings_section_does_not_clear_the_theme_search(cx: &mut TestAppContext) { + let backend = backend(); + user_files(&backend, 0, 32); + let (handle, _, themes) = setup(cx, backend); + search_dark_themes(handle, "User Theme 0017", cx); + cx.update(|cx| { + themes + .settings() + .update::(cx, |settings| { + settings.copy_on_select = !settings.copy_on_select; + }) + }) + .await + .unwrap(); + cx.run_until_parked(); + confirm_dark_theme(handle, &themes, "User Theme 0017", cx); +} + +#[gpui_kit::test] +async fn changing_the_light_theme_preserves_the_dark_theme_search(cx: &mut TestAppContext) { + let backend = backend(); + backend.install(&info("fake")).unwrap(); + user_files(&backend, 0, 32); + let (handle, _, themes) = setup(cx, backend); + search_dark_themes(handle, "User Theme 0017", cx); + cx.update(|cx| { + themes + .settings() + .update::(cx, |settings| { + settings.light_theme = Some("Fake Light".into()); + }) + }) + .await + .unwrap(); + cx.run_until_parked(); + confirm_dark_theme(handle, &themes, "User Theme 0017", cx); +} + +#[gpui_kit::test] +async fn a_failed_theme_install_preserves_an_active_search(cx: &mut TestAppContext) { + let backend = backend(); + user_files(&backend, 0, 32); + let (handle, _, themes) = setup(cx, backend); + search_dark_themes(handle, "User Theme 0017", cx); + assert!( + cx.update(|cx| themes.themes().install_pack(info("failure"), cx)) + .await + .is_err() + ); + cx.run_until_parked(); + confirm_dark_theme(handle, &themes, "User Theme 0017", cx); +} + +#[gpui_kit::test] +fn a_reloaded_catalog_offers_the_newly_discovered_theme(cx: &mut TestAppContext) { + let backend = backend(); + user_files(&backend, 0, 32); + let (handle, _, themes) = setup(cx, backend.clone()); + user_files(&backend, 32, 50); + cx.update(|cx| themes.themes().reload(cx)); + cx.run_until_parked(); + search_dark_themes(handle, "User Theme 0049", cx); + confirm_dark_theme(handle, &themes, "User Theme 0049", cx); +} + +#[gpui_kit::test] +#[ignore = "release measurement of Appearance reacting to settings publications"] +async fn measure_appearance_picker_settings_publications(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + for count in [32, 1_800] { + let backend = backend(); + user_files(&backend, 0, count); + let (handle, _, themes) = setup(cx, backend); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + let mut samples = [std::time::Duration::ZERO; 256]; + for sample in &mut samples { + let start = Instant::now(); + cx.update(|cx| { + themes + .settings() + .update::(cx, |settings| { + settings.copy_on_select = !settings.copy_on_select; + }) + }) + .await + .unwrap(); + *sample = start.elapsed(); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "themes={count} publications={} median={:?} p95={:?}", + samples.len(), + samples[samples.len() / 2], + samples[samples.len() * 95 / 100] + ) + .unwrap(); + } +} + +#[gpui_kit::test] +fn browser_stays_reachable_through_the_same_scroll_after_theme_reload(cx: &mut TestAppContext) { + let backend = backend(); + user_files(&backend, 0, 48); + let scroll = ScrollHandle::new(); + let (handle, _, themes) = setup_scroll(cx, backend.clone(), px(700.), scroll.clone()); + let initial_extent = cx + .update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(!window.find("browse-zed-themes").visible()); + scroll.max_offset().y + }) + .unwrap(); + assert!(initial_extent > px(1000.)); + + user_files(&backend, 48, 96); + cx.update(|cx| themes.themes().reload(cx)); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(scroll.max_offset().y > initial_extent + px(1000.)); + scroll.scroll_to_bottom(); + window.render_frame(cx); + assert!(window.find("browse-zed-themes").visible()); + window.click("browse-zed-themes", cx); + }) + .unwrap(); + cx.run_until_parked(); + assert_eq!(backend.searches(), 1); +} + +#[gpui_kit::test] +#[ignore = "release measurement of the Appearance file list with real GPUI scroll events"] +fn measure_appearance_scroll_with_large_theme_catalog(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + for count in [32, 1_800] { + let backend = backend(); + user_files(&backend, 0, count); + let scroll = ScrollHandle::new(); + let (handle, _, _) = setup_scroll(cx, backend, px(700.), scroll.clone()); + let opening = cx + .update_window(handle, |_, window, cx| { + let start = Instant::now(); + window.render_frame(cx); + start.elapsed() + }) + .unwrap(); + let scrolling = cx + .update_window(handle, |_, window, cx| { + let start = Instant::now(); + for _ in 0..32 { + window.scroll( + "appearance-scroll", + ScrollDelta::Pixels(point(px(0.), px(-32.))), + cx, + ); + window.render_frame(cx); + } + start.elapsed() + }) + .unwrap(); + assert!(scroll.offset().y < px(-600.)); + writeln!( + std::io::stdout().lock(), + "files={count} opening={opening:?} scroll_32={scrolling:?}" + ) + .unwrap(); + } +} + +struct ThemeFileRows { + virtual_rows: Option, + labels: Arc<[gpui_kit::SharedString]>, + scroll: ScrollHandle, +} + +impl gpui_kit::Render for ThemeFileRows { + fn render( + &mut self, + _: &mut gpui_kit::Window, + cx: &mut gpui_kit::Context, + ) -> impl gpui_kit::IntoElement { + let mut rows = vec![crate::form::note("Intro", cx)]; + if let Some(virtual_rows) = &self.virtual_rows { + rows.extend(virtual_rows.element()); + } else { + rows.extend( + self.labels + .iter() + .map(|label| crate::form::note(label.clone(), cx)), + ); + } + rows.push(crate::form::note("After all files", cx)); + div() + .id("theme-file-test-scroll") + .size_full() + .overflow_y_scroll() + .track_scroll(&self.scroll) + .child(crate::form::section("Installed themes", rows, cx)) + } +} + +#[gpui_kit::test] +fn theme_file_rows_keep_the_same_scroll_extent_after_width_and_text_scale_changes( + cx: &mut TestAppContext, +) { + let backend = backend(); + user_files(&backend, 0, 96); + let catalog = Arc::new(backend.scan()); + let labels: Arc<[gpui_kit::SharedString]> = catalog + .entries() + .iter() + .map(|entry| { + let nocterm_themes::ThemeSource::User(path) = &entry.source else { + panic!("expected a user file"); + }; + format!("User file: {}", path.file_name().unwrap().to_string_lossy()).into() + }) + .collect(); + let windows = cx.update(|cx| { + gpui_kit::init(cx); + [false, true].map(|virtualized| { + let scroll = ScrollHandle::new(); + let mut virtual_rows = super::user_files::UserFiles::default(); + virtual_rows.prepare(&catalog); + let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |_, cx| { + cx.new(|_| ThemeFileRows { + virtual_rows: virtualized.then_some(virtual_rows), + labels: labels.clone(), + scroll: scroll.clone(), + }) + }) + .unwrap(); + (handle, scroll) + }) + }); + for (scale, width, rem) in [(1., 1000., 16.), (1.25, 480., 16.), (1.3, 720., 20.)] { + let [eager, visible] = windows.each_ref().map(|(handle, scroll)| { + cx.simulate_window_scale_factor_change(*handle, scale); + cx.update_window(*handle, |_, window, _| { + window.resize(gpui_kit::size(px(width), px(500.))); + window.set_rem_size(px(rem)); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(*handle, |_, window, cx| { + window.render_frame(cx); + scroll.max_offset().y + }) + .unwrap() + }); + assert!( + (eager - visible).abs() < px(1. / scale), + "scale={scale} width={width} eager={eager:?} visible={visible:?}" + ); + } +} diff --git a/crates/ui/src/appearance_page/user_files.rs b/crates/ui/src/appearance_page/user_files.rs new file mode 100644 index 00000000..b5cb5e3b --- /dev/null +++ b/crates/ui/src/appearance_page/user_files.rs @@ -0,0 +1,259 @@ +//! User-file notes inside the existing Appearance scroll. +use crate::form; +use gpui_kit::{ + AnyElement, App, AvailableSpace, Bounds, Element, ElementId, Font, GlobalElementId, + InspectorElementId, LayoutId, Pixels, SharedString, Style, TextStyle, WhiteSpace, Window, + point, prelude::*, px, size, +}; +use nocterm_themes::{ThemeCatalog, ThemeSource}; +use std::{ + cell::RefCell, + collections::BTreeSet, + rc::Rc, + sync::{Arc, Weak}, +}; + +#[derive(Default)] +pub(super) struct UserFiles { + catalog: Weak, + rows: Rc, +} + +#[derive(Default)] +struct Rows { + labels: Vec, + geometry: RefCell>, +} + +impl UserFiles { + pub(super) fn prepare(&mut self, catalog: &Arc) { + let source = Arc::downgrade(catalog); + if self.catalog.ptr_eq(&source) { + return; + } + let paths = catalog + .entries() + .iter() + .filter_map(|entry| match &entry.source { + ThemeSource::User(path) => Some(path), + _ => None, + }) + .collect::>(); + self.rows = Rc::new(Rows { + labels: paths + .into_iter() + .map(|path| { + format!( + "User file: {}", + path.file_name().unwrap_or_default().to_string_lossy() + ) + .into() + }) + .collect(), + geometry: RefCell::default(), + }); + self.catalog = source; + } + + pub(super) fn element(&self) -> Option { + (!self.rows.labels.is_empty()) + .then(|| VisibleUserFiles(self.rows.clone()).into_any_element()) + } +} + +#[derive(PartialEq)] +struct Metrics { + width: Pixels, + scale: f32, + font: Font, + font_size: Pixels, + line_height: Pixels, + pad: Pixels, + border: Pixels, + wrap: bool, + line_clamp: Option, +} + +struct Geometry { + metrics: Metrics, + // The normal layout snaps each note's text, padding and border separately. + // Accumulate the same device-pixel lengths to keep the last row aligned. + offsets: Vec, +} + +impl Geometry { + fn height(&self) -> Pixels { + let device_height = *self.offsets.last().unwrap(); + let scale = self.metrics.scale; + let logical = device_height / scale; + // A leaf's measured height is ceiled to device pixels by GPUI. + // Division can round to a value whose round trip is just above the edge. + px(if logical * scale > device_height { + logical.next_down() + } else { + logical + }) + } +} + +impl Rows { + fn measure(&self, width: Pixels, style: &TextStyle, window: &mut Window) { + let rem = window.rem_size(); + let font_size = style.font_size.to_pixels(rem); + let metrics = Metrics { + width, + scale: window.scale_factor(), + font: style.font(), + font_size, + line_height: window.pixel_snap(style.line_height.to_pixels(font_size.into(), rem)), + pad: window.pixel_snap(form::NOTE_PADDING.to_pixels(rem)) * 2., + border: window + .pixel_snap(form::SECTION_DIVIDER) + .max(px(1. / window.scale_factor())), + wrap: style.white_space == WhiteSpace::Normal, + line_clamp: style.line_clamp, + }; + let mut geometry = self.geometry.borrow_mut(); + if geometry + .as_ref() + .is_some_and(|previous| previous.metrics == metrics) + { + return; + } + let mut offsets = Vec::with_capacity(self.labels.len() + 1); + offsets.push(0.); + let wrap_width = metrics.wrap.then_some(width); + let scale = metrics.scale; + let padding = (f32::from(metrics.pad) * scale).round(); + let border = (f32::from(metrics.border) * scale).round(); + let mut bottom = 0.; + for (index, label) in self.labels.iter().enumerate() { + let text_height: Pixels = window + .text_system() + .shape_text( + label.clone(), + font_size, + &[style.to_run(label.len())], + wrap_width, + metrics.line_clamp, + ) + .iter() + .flatten() + .map(|line| line.size(metrics.line_height).height) + .sum(); + bottom += padding + (f32::from(text_height) * scale).ceil(); + if index > 0 { + bottom += border; + } + offsets.push(bottom); + } + *geometry = Some(Geometry { metrics, offsets }); + } +} + +struct VisibleUserFiles(Rc); +impl IntoElement for VisibleUserFiles { + type Element = Self; + + fn into_element(self) -> Self { + self + } +} + +impl Element for VisibleUserFiles { + type RequestLayoutState = TextStyle; + type PrepaintState = Vec; + + fn id(&self) -> Option { + None + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + window: &mut Window, + _: &mut App, + ) -> (LayoutId, TextStyle) { + let rows = self.0.clone(); + let mut style = window.text_style(); + style.font_size = form::NOTE_FONT_SIZE.into(); + let text_style = style.clone(); + let layout = + window.request_measured_layout(Style::default(), move |known, available, window, _| { + let width = known + .width + .or(match available.width { + AvailableSpace::Definite(width) => Some(width), + _ => None, + }) + .unwrap_or_else(|| window.viewport_size().width); + rows.measure(width, &text_style, window); + let geometry = rows.geometry.borrow(); + size(width, geometry.as_ref().unwrap().height()) + }); + (layout, style) + } + + fn prepaint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + bounds: Bounds, + style: &mut TextStyle, + window: &mut Window, + cx: &mut App, + ) -> Vec { + let visible = bounds + .intersect(&window.content_mask().bounds) + .intersect(&Bounds::new(Default::default(), window.viewport_size())); + if visible.size.height <= Pixels::ZERO || visible.size.width <= Pixels::ZERO { + return Vec::new(); + } + self.0.measure(bounds.size.width, style, window); + let geometry = self.0.geometry.borrow(); + let geometry = geometry.as_ref().unwrap(); + let offsets = &geometry.offsets; + let scale = geometry.metrics.scale; + let top = f32::from(visible.top() - bounds.top()) * scale; + let bottom = f32::from(visible.bottom() - bounds.top()) * scale; + let start = offsets[1..].partition_point(|end| *end <= top); + let end = offsets[..self.0.labels.len()].partition_point(|start| *start < bottom); + (start..end) + .map(|index| { + let mut row = + form::section_row(form::note(self.0.labels[index].clone(), cx), index > 0, cx); + let origin = point(bounds.left(), bounds.top() + px(offsets[index] / scale)); + row.prepaint_as_root( + origin, + size( + AvailableSpace::Definite(bounds.size.width), + AvailableSpace::MinContent, + ), + window, + cx, + ); + row + }) + .collect() + } + + fn paint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut TextStyle, + rows: &mut Vec, + window: &mut Window, + cx: &mut App, + ) { + for row in rows { + row.paint(window, cx); + } + } +} diff --git a/crates/ui/src/choice_picker.rs b/crates/ui/src/choice_picker.rs index 9151b0d4..d7d5b972 100644 --- a/crates/ui/src/choice_picker.rs +++ b/crates/ui/src/choice_picker.rs @@ -1,8 +1,6 @@ //! A searchable dialog that asks the user to pick one value from a short list. -use std::rc::Rc; - use gpui_kit::{ - App, AppContext as _, Window, + App, AppContext as _, SharedString, Window, component::{ WindowExt as _, command::{Command, CommandItem, CommandState}, @@ -15,7 +13,7 @@ use gpui_kit::{ /// stands for. #[derive(Clone)] pub struct PickerOption { - label: String, + label: SharedString, checked: bool, value: T, } @@ -23,7 +21,7 @@ pub struct PickerOption { impl PickerOption { pub fn new(label: impl Into, checked: bool, value: T) -> Self { Self { - label: label.into(), + label: label.into().into(), checked, value, } @@ -40,41 +38,35 @@ pub fn open_choice_picker( cx: &mut App, ) { let origin = window.focused(cx); - let options = Rc::new(options); - let on_choose = Rc::new(on_choose); - let state = cx.new(|cx| CommandState::new(window, cx)); + let state = cx.new(|cx| CommandState::new_for_plain_choices(window, cx)); + let state = Command::new(&state) + .items(options.iter().map(|option| { + CommandItem::new() + .label(option.label.clone()) + .checked(option.checked) + })) + .placeholder(placeholder) + .bordered(false) + .max_h(px(420.)) + .on_confirm(move |index, window, cx| { + let Some(option) = options.get(index.row) else { + return; + }; + let value = option.value.clone(); + window.close_dialog(cx); + if let Some(origin) = &origin { + window.focus(origin, cx); + } + on_choose(value, window, cx); + }) + .install(cx); let field = state.clone(); window.open_dialog(cx, move |dialog, _, _| { - let confirm = options.clone(); - let on_choose = on_choose.clone(); - let origin = origin.clone(); - dialog.w(px(560.)).p_0().close_button(false).child( - Command::new(&state) - .items( - options - .iter() - .map(|option| { - CommandItem::new() - .label(option.label.clone()) - .checked(option.checked) - }) - .collect::>(), - ) - .placeholder(placeholder) - .bordered(false) - .max_h(px(420.)) - .on_confirm(move |index, window, cx| { - let Some(option) = confirm.get(index.row) else { - return; - }; - let value = option.value.clone(); - window.close_dialog(cx); - if let Some(origin) = &origin { - window.focus(origin, cx); - } - on_choose(value, window, cx); - }), - ) + dialog + .w(px(560.)) + .p_0() + .close_button(false) + .child(state.clone()) }); field.update(cx, |state, cx| state.focus(window, cx)); } @@ -97,6 +89,21 @@ mod tests { fn open( picked: &Rc>>, cx: &mut TestAppContext, + ) -> gpui_kit::AnyWindowHandle { + open_options( + vec![ + PickerOption::new("First", true, "first"), + PickerOption::new("Second", false, "second"), + ], + picked, + cx, + ) + } + + fn open_options( + options: Vec>, + picked: &Rc>>, + cx: &mut TestAppContext, ) -> gpui_kit::AnyWindowHandle { let picked = picked.clone(); cx.update(|cx| { @@ -116,10 +123,7 @@ mod tests { .update(cx, move |_, window, cx| { open_choice_picker( "Pick one", - vec![ - PickerOption::new("First", true, "first"), - PickerOption::new("Second", false, "second"), - ], + options, move |value, _, _| picked.borrow_mut().push(value), window, cx, @@ -130,6 +134,109 @@ mod tests { }) } + #[gpui_kit::test] + fn query_edits_keep_the_filtered_choices_actionable(cx: &mut TestAppContext) { + let picked = Rc::new(RefCell::new(Vec::new())); + let handle = open(&picked, cx); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + for segment in ["s", "e", "c"] { + cx.simulate_input(handle, segment); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + cx.update_window(handle, |_, window, cx| window.press("enter", cx)) + .unwrap(); + cx.run_until_parked(); + assert_eq!(*picked.borrow(), ["second"]); + } + + #[gpui_kit::test] + fn keyboard_wrap_reveals_the_multiline_last_choice(cx: &mut TestAppContext) { + let mut options = (0..180) + .map(|index| PickerOption::new(format!("Choice {index}"), index == 0, index)) + .collect::>(); + options.push(PickerOption::new( + "First line\nSecond line\nThird line\nFourth line", + false, + 180, + )); + let picked = Rc::new(RefCell::new(Vec::new())); + let handle = open_options(options, &picked, cx); + cx.run_until_parked(); + + let first_height = cx + .update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("index-path(0,180,0)").is_none()); + let first = window.find("index-path(0,0,0)").bounds(); + window.press("up", cx); + first.size.height + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + let viewport = window.find("command-list-container").bounds(); + let last = window.find("index-path(0,180,0)"); + assert_eq!(last.selected(), Some(true)); + let last = last.bounds(); + assert!(last.size.height > first_height); + assert!(last.top() >= viewport.top() && last.bottom() <= viewport.bottom()); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + assert_eq!(*picked.borrow(), [180]); + } + + #[gpui_kit::test] + #[ignore = "large choice picker performance fixture; run in isolation"] + fn measure_choice_picker_filtering(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + for _ in 0..3 { + let options = (0..1800) + .map(|index| PickerOption::new(format!("Audit theme {index:04}"), false, index)) + .collect(); + let picked = Rc::new(RefCell::new(Vec::new())); + let start = Instant::now(); + let handle = open_options(options, &picked, cx); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + let opened = start.elapsed(); + + let start = Instant::now(); + for letter in "audit theme 1732".chars() { + cx.simulate_input(handle, letter.encode_utf8(&mut [0; 4])); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + let filtered = start.elapsed(); + let start = Instant::now(); + for _ in 0..24 { + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + let redrawn = start.elapsed(); + cx.update_window(handle, |_, window, cx| window.press("enter", cx)) + .unwrap(); + cx.run_until_parked(); + assert_eq!(*picked.borrow(), [1732]); + writeln!( + std::io::stdout().lock(), + "1,800 choices: open {:.3} ms, filter {:.3} ms, 24 redraws {:.3} ms", + opened.as_secs_f64() * 1_000.0, + filtered.as_secs_f64() * 1_000.0, + redrawn.as_secs_f64() * 1_000.0, + ) + .unwrap(); + } + } + #[gpui_kit::test] fn confirming_a_row_closes_the_dialog_and_reports_its_value(cx: &mut TestAppContext) { let picked = Rc::new(RefCell::new(Vec::new())); diff --git a/crates/ui/src/form.rs b/crates/ui/src/form.rs index ee340469..c225746c 100644 --- a/crates/ui/src/form.rs +++ b/crates/ui/src/form.rs @@ -1,7 +1,7 @@ //! The look shared by settings pages: titled sections of rows on the //! terminal's background, without cards or outlines. use gpui_kit::{ - AnyElement, App, SharedString, + AnyElement, App, Pixels, Rems, SharedString, component::{ActiveTheme as _, Sizable as _, StyledExt as _, h_flex, v_flex}, div, prelude::*, @@ -16,6 +16,35 @@ pub use controls::choices; pub use fields::{short_field, text_field}; pub use fold::{fade, fold_button, fold_list}; +/// Wheel behavior for a bounded virtual form: preserve ordinary overflow +/// line height and horizontal fallback, leaving precise vertical input to List. +pub fn list_wheel_overlay(scroll: gpui_kit::ListState) -> impl IntoElement { + use gpui_kit::{DispatchPhase, HitboxBehavior, IsZero, ScrollWheelEvent, canvas}; + canvas( + |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal), + move |_, hitbox, window, _| { + let line_height = window.line_height(); + let view = window.current_view(); + window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || !hitbox.should_handle_scroll(window) { + return; + } + let delta = event.delta.pixel_delta(line_height); + if event.delta.precise() && !delta.y.is_zero() { + return; + } + let vertical = if delta.y.is_zero() { delta.x } else { delta.y }; + if scroll.scroll_wheel_pixels(vertical) { + cx.notify(view); + cx.stop_propagation(); + } + }); + }, + ) + .absolute() + .inset_0() +} + /// The width a settings form keeps to on wide windows. pub fn page_width(cx: &App) -> gpui_kit::Rems { rems(cx.design().layout.settings_width) @@ -72,22 +101,32 @@ pub fn page_header( .into_any_element() } +pub(crate) const SECTION_DIVIDER: Pixels = px(1.); +pub(crate) const NOTE_FONT_SIZE: Rems = rems(0.875); +pub(crate) const NOTE_PADDING: Rems = rems(0.5); + +pub(crate) fn section_row(row: AnyElement, divided: bool, cx: &App) -> AnyElement { + div() + .w_full() + .when(divided, |row| { + row.border_t_1() + .border_color(cx.theme().border.opacity(0.5)) + }) + .child(row) + .into_any_element() +} + /// A group of rows under a heading; rows are separated by hairlines. pub fn section( title: impl Into, rows: impl IntoIterator, cx: &App, ) -> AnyElement { - let divider = cx.theme().border.opacity(0.5); - let mut list = v_flex().w_full(); - for (index, row) in rows.into_iter().enumerate() { - list = list.child( - div() - .w_full() - .when(index > 0, |row| row.border_t_1().border_color(divider)) - .child(row), - ); - } + let list = v_flex().w_full().children( + rows.into_iter() + .enumerate() + .map(|(index, row)| section_row(row, index > 0, cx)), + ); v_flex() .w_full() .pt_4() @@ -151,8 +190,8 @@ pub fn error_text(error: impl Into, cx: &App) -> AnyElement { /// A muted note, for status lines and empty states. pub fn note(text: impl Into, cx: &App) -> AnyElement { div() - .py_2() - .text_sm() + .py(NOTE_PADDING) + .text_size(NOTE_FONT_SIZE) .text_color(cx.theme().muted_foreground) .child(text.into()) .into_any_element() diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index ca289249..a5c430ad 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -62,7 +62,7 @@ pub use plugin_source::{PluginSetHandle, PluginSource, StaticPluginSource}; pub use sections::{ AppearanceMode, AppearanceSettings, CARD_GAP_RANGE, CARD_RADIUS_RANGE, UiLayout, }; -pub use terminal_style::{TerminalStyle, hsla}; +pub use terminal_style::{TerminalStyle, hsla, terminal_background}; pub use theme::unknown_color_names; pub use themes::ThemeUi; diff --git a/crates/ui/src/settings_page.rs b/crates/ui/src/settings_page.rs index 2fc21ac6..d2c89b11 100644 --- a/crates/ui/src/settings_page.rs +++ b/crates/ui/src/settings_page.rs @@ -5,7 +5,9 @@ use gpui_kit::{ }; use std::rc::Rc; -/// An independent settings page. Hidden and closing pages can clear sensitive drafts. +/// An independent settings page. Observe its own settings and other inputs; the host +/// follows shared diagnostics, not the contents of individual pages. Hidden and closing +/// pages can clear sensitive drafts. pub trait SettingsPage: Render + Focusable { fn flush(&mut self, _window: &mut Window, _cx: &mut Context) {} fn on_deactivate(&mut self, _window: &mut Window, _cx: &mut Context) {} @@ -61,6 +63,7 @@ pub struct SettingsPageSpec { /// Shown beside the title in the page list. pub icon: crate::IconName, factory: Rc, + viewport: bool, } impl SettingsPageSpec { @@ -73,6 +76,7 @@ impl SettingsPageSpec { id, title: title.into(), icon: crate::IconName::Wrench, + viewport: false, factory: Rc::new(move |_, window, cx| Box::new(factory(window, cx))), } } @@ -87,6 +91,7 @@ impl SettingsPageSpec { id, title: title.into(), icon: crate::IconName::Wrench, + viewport: false, factory: Rc::new(move |context, window, cx| Box::new(factory(context, window, cx))), } } @@ -103,6 +108,16 @@ impl SettingsPageSpec { self } + /// Give the page the remaining height so it can scroll its own content. + pub fn with_viewport(mut self) -> Self { + self.viewport = true; + self + } + + pub fn uses_viewport(&self) -> bool { + self.viewport + } + /// Shows the page first and each section below it in the host's scroll. A section is /// created when the page first renders it; the page passes flush, hide and close on to the /// sections it created. `reveal("")` scrolls to and focuses a section, and diff --git a/crates/ui/src/terminal_style.rs b/crates/ui/src/terminal_style.rs index 5fc17e19..8bad1453 100644 --- a/crates/ui/src/terminal_style.rs +++ b/crates/ui/src/terminal_style.rs @@ -51,7 +51,7 @@ impl TerminalStyle { semantic_highlighting: settings.semantic_highlighting, gutter_foreground: color(theme.muted_foreground), foreground, - background: colors.background.unwrap_or_else(|| color(theme.background)), + background: background_color(colors.background, theme.background), cursor: colors.cursor.unwrap_or(foreground), selection: colors.selection.unwrap_or_else(|| color(theme.selection)), ansi: colors.ansi(), @@ -59,6 +59,18 @@ impl TerminalStyle { } } +/// The terminal background without resolving fonts, foreground or ANSI colours. +/// It depends on the active palette and component theme, not terminal preferences. +pub fn terminal_background(cx: &App) -> Color { + let theme = cx.theme(); + let colors = &cx.design().palette(theme.is_dark()).terminal; + background_color(colors.background, theme.background) +} + +fn background_color(token: Option, fallback: Hsla) -> Color { + token.unwrap_or_else(|| color(fallback)) +} + /// A token colour as GPUI paints it. pub fn hsla(color: Color) -> Hsla { Rgba { @@ -111,6 +123,49 @@ mod tests { }); } + #[gpui_kit::test] + fn direct_background_matches_terminal_style_in_both_palettes_and_fallback( + cx: &mut gpui_kit::TestAppContext, + ) { + cx.update(|cx| { + gpui_kit::init(cx); + crate::init( + crate::DesignTokens::builtin(), + nocterm_store::SettingsConfig::in_memory(Default::default()).install(cx), + cx, + ); + for mode in [crate::AppearanceMode::Light, crate::AppearanceMode::Dark] { + for background in [None, Some(Color::rgb(17, 31, 47))] { + let mut tokens = crate::DesignTokens::builtin(); + tokens.light.terminal.background = background; + tokens.dark.terminal.background = background; + cx.set_global(crate::Design::new(tokens)); + crate::theme::apply_theme_for( + &crate::AppearanceSettings { + mode, + ..Default::default() + }, + cx, + ); + let settings = crate::TerminalSettings { + font_family: Some("Non-default font".into()), + font_size: Some(21.), + ..Default::default() + }; + let direct = terminal_background(cx); + assert_eq!( + direct, + TerminalStyle::with_settings(&settings, cx).background + ); + assert_eq!( + direct, + background.unwrap_or_else(|| color(cx.theme().background)) + ); + } + } + }); + } + #[test] fn colours_survive_the_round_trip_through_gpui() { for value in [ diff --git a/crates/ui/src/themes.rs b/crates/ui/src/themes.rs index 863005e5..d6820721 100644 --- a/crates/ui/src/themes.rs +++ b/crates/ui/src/themes.rs @@ -32,8 +32,21 @@ impl ThemeUi { }); let theme_projection = themes.clone(); let settings_projection = settings.clone(); + let mut applied = settings.setting::(cx).clone(); let setting_observer = settings.observe(cx, move |cx| { - if !resolve(&theme_projection, &settings_projection, &base, cx) { + let current = settings_projection.setting::(cx); + let resolve_selection = applied.light_theme != current.light_theme + || applied.dark_theme != current.dark_theme; + let repaint = resolve_selection + || applied.mode != current.mode + || applied.layout != current.layout + || applied.card_gap != current.card_gap + || applied.card_radius != current.card_radius; + if !repaint { + return; + } + applied = current.clone(); + if !resolve_selection || !resolve(&theme_projection, &settings_projection, &base, cx) { apply(&settings_projection, cx); } }); diff --git a/crates/ui/src/themes/tests/projection_authority.rs b/crates/ui/src/themes/tests/projection_authority.rs index f3f3b883..c248aca5 100644 --- a/crates/ui/src/themes/tests/projection_authority.rs +++ b/crates/ui/src/themes/tests/projection_authority.rs @@ -23,6 +23,24 @@ fn install_projection(cx: &mut gpui_kit::App) -> ThemeUi { ThemeUi::install(ready.settings().clone(), service, base, cx) } +#[gpui_kit::test] +async fn terminal_settings_leave_the_published_application_theme_in_place(cx: &mut TestAppContext) { + let projection = cx.update(install_projection); + let before = cx.update(|cx| Theme::global(cx).dark_theme.clone()); + + cx.update(|cx| { + projection + .settings() + .update::(cx, |settings| settings.show_line_numbers = true) + }) + .await + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert!(Rc::ptr_eq(&Theme::global(cx).dark_theme, &before)); + }); +} + fn unrelated_projection_window(cx: &mut App) -> (nocterm_store::SettingsHandle, AnyWindowHandle) { let other = nocterm_store::SettingsConfig::in_memory(Default::default()) .with(AppearanceSettings { diff --git a/crates/vault-broker/src/service.rs b/crates/vault-broker/src/service.rs index b8d23fff..59b6e23b 100644 --- a/crates/vault-broker/src/service.rs +++ b/crates/vault-broker/src/service.rs @@ -7,19 +7,14 @@ use self::fprintd::FPRINT; use self::fprintd::FprintdBackend; use crate::store::{Owner, Store}; use futures::StreamExt as _; -use std::{ - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, - time::Duration, -}; -use tokio::sync::Mutex; +use std::{sync::Arc, time::Duration}; +use tokio::sync::{Mutex, watch}; use zbus::{ Connection, - fdo::{self, DBusProxy}, + fdo::{self, DBusProxy, NameOwnerChangedStream}, message::Header, names::BusName, + object_server::SignalEmitter, }; const NAME: &str = "dev.nocterm.VaultBroker1"; const PATH: &str = "/dev/nocterm/VaultBroker1"; @@ -32,6 +27,23 @@ struct Broker { #[cfg(test)] scan_timeout: Duration, } +/// Progress belongs to one release and is addressed to its original caller. +struct Progress<'a> { + emitter: SignalEmitter<'a>, + request: u64, +} + +impl Progress<'_> { + async fn send(&self, remaining: u8) { + // Bound best-effort delivery so a slow bus cannot stall the scanner. + let _ = tokio::time::timeout( + Duration::from_millis(50), + Broker::release_progress(&self.emitter, self.request, remaining), + ) + .await; + } +} + fn denied(error: impl std::fmt::Display) -> fdo::Error { fdo::Error::AccessDenied(error.to_string()) } @@ -117,7 +129,8 @@ impl Broker { owner: &Owner, binding: &str, token: &str, - cancel: Arc, + cancel: &watch::Receiver, + progress: Option<&Progress<'_>>, ) -> fdo::Result<()> { let backend = FprintdBackend::new(&self.connection, self.fingerprint_uid()).await?; let request = verify::Request { @@ -128,11 +141,69 @@ impl Broker { token, }, scanner: &self.scanner, - cancel: &cancel, + cancel, scan_timeout: self.scan_timeout(), + progress, }; verify::verify(&backend, &request).await } + + async fn verify_connected( + &self, + owner: &Owner, + binding: &str, + token: &str, + cancel: &watch::Receiver, + progress: Option<&Progress<'_>>, + remaining: u8, + ) -> fdo::Result<()> { + // The observer sees losses after admission. This one check covers a + // loss processed between reading the caller's credentials and admission. + let dbus = DBusProxy::new(&self.connection).await.map_err(denied)?; + let name = BusName::try_from(owner.connection.as_str()).map_err(denied)?; + if !dbus.name_has_owner(name).await.map_err(denied)? { + return Err(denied("Client disconnected")); + } + if let Some(progress) = progress { + progress.send(remaining).await; + } + self.verify(owner, binding, token, cancel, progress).await + } + + async fn release_key( + &self, + owner: Owner, + binding: &str, + token: &str, + progress: Option<&Progress<'_>>, + ) -> Result, ReleaseError> { + let (cancel, remaining) = { + let mut store = self.store.lock().await; + let entry = store.entry(&owner, binding, token).map_err(denied)?; + if entry.attempts_remaining == 0 { + return Err(locked()); + } + let cancelled = entry + .start_release(&owner) + .ok_or_else(|| denied("Authentication is already in progress"))?; + (cancelled, entry.attempts_remaining) + }; + let result = self + .verify_connected(&owner, binding, token, &cancel, progress, remaining) + .await; + let mut store = self.store.lock().await; + let entry = store.entry(&owner, binding, token).map_err(denied)?; + entry.finish_release(); + if result.is_err() && entry.attempts_remaining == 0 { + return Err(locked()); + } + result?; + if *cancel.borrow() { + return Err(denied("Authentication cancelled").into()); + } + entry.touched = std::time::Instant::now(); + Ok(entry.key.to_vec()) + } } #[zbus::interface(name = "dev.nocterm.VaultBroker1")] impl Broker { @@ -191,35 +262,34 @@ impl Broker { #[zbus(header)] header: Header<'_>, ) -> Result, ReleaseError> { let owner = self.owner(&header).await?; - let cancel = { - let mut store = self.store.lock().await; - let entry = store.entry(&owner, &binding, &token).map_err(denied)?; - if entry.attempts_remaining == 0 { - return Err(locked()); - } - if entry.busy { - return Err(denied("Authentication is already in progress").into()); - } - entry.busy = true; - // A disconnecting caller cancels only its own authentication. - entry.owner = owner.clone(); - entry.cancel = Arc::new(AtomicBool::new(false)); - entry.cancel.clone() + self.release_key(owner, &binding, &token, None).await + } + + async fn release_with_progress( + &self, + binding: String, + token: String, + request: u64, + #[zbus(header)] header: Header<'_>, + #[zbus(signal_emitter)] emitter: SignalEmitter<'_>, + ) -> Result, ReleaseError> { + let owner = self.owner(&header).await?; + let sender = header.sender().ok_or_else(|| denied("Missing sender"))?; + let progress = Progress { + emitter: emitter.set_destination(BusName::from(sender.clone())), + request, }; - let result = self.verify(&owner, &binding, &token, cancel.clone()).await; - let mut store = self.store.lock().await; - let entry = store.entry(&owner, &binding, &token).map_err(denied)?; - entry.busy = false; - if result.is_err() && entry.attempts_remaining == 0 { - return Err(locked()); - } - result?; - if cancel.load(Ordering::SeqCst) { - return Err(denied("Authentication cancelled").into()); - } - entry.touched = std::time::Instant::now(); - Ok(entry.key.to_vec()) + self.release_key(owner, &binding, &token, Some(&progress)) + .await } + + #[zbus(signal)] + async fn release_progress( + emitter: &SignalEmitter<'_>, + request: u64, + remaining: u8, + ) -> zbus::Result<()>; + async fn cancel( &self, binding: String, @@ -232,8 +302,7 @@ impl Broker { .await .entry(&owner, &binding, &token) .map_err(denied)? - .cancel - .store(true, Ordering::SeqCst); + .cancel_release(); Ok(()) } async fn remove( @@ -258,6 +327,7 @@ pub(crate) async fn run() -> Result<(), Box> { .method_timeout(Duration::from_secs(5)) .build() .await?; + let changes = connection_losses(&connection).await?; let store = Arc::new(Mutex::new(Store::default())); connection .object_server() @@ -275,15 +345,19 @@ pub(crate) async fn run() -> Result<(), Box> { ) .await?; connection.request_name(NAME).await?; - observe_connections(connection, store, Duration::from_secs(30)).await + observe_connections(changes, store, Duration::from_secs(30)).await } + +async fn connection_losses(connection: &Connection) -> zbus::Result { + let dbus = DBusProxy::new(connection).await?; + dbus.receive_name_owner_changed_with_args(&[(2, "")]).await +} + async fn observe_connections( - connection: Connection, + mut changes: NameOwnerChangedStream, store: Arc>, expiry_period: Duration, ) -> Result<(), Box> { - let dbus = DBusProxy::new(&connection).await?; - let mut changes = dbus.receive_name_owner_changed().await?; let mut expiry = tokio::time::interval(expiry_period); expiry.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { @@ -291,8 +365,8 @@ async fn observe_connections( change = changes.next() => { let Some(change) = change else { break; }; let args = change.args()?; - if args.new_owner().is_none() { - store.lock().await.disconnected(args.name().as_str()); + if let BusName::Unique(name) = args.name() { + store.lock().await.disconnected(name.as_str()); } } _ = expiry.tick() => store.lock().await.expire(), diff --git a/crates/vault-broker/src/service/fingerprint.rs b/crates/vault-broker/src/service/fingerprint.rs index f48434a2..4873d891 100644 --- a/crates/vault-broker/src/service/fingerprint.rs +++ b/crates/vault-broker/src/service/fingerprint.rs @@ -6,13 +6,11 @@ use super::denied; use crate::store::Owner; use zbus::fdo; -/// Finds readers for a desktop user and watches the client that asked. +/// Finds readers for a desktop user. pub(super) trait FingerprintBackend: Send + Sync { type Device: FingerprintDevice; /// A trusted reader with fingers enrolled for `owner`, not yet claimed. fn device(&self, owner: &Owner) -> impl Future> + Send; - /// Whether the client that asked for the scan is still connected. - fn client_present(&self, owner: &Owner) -> impl Future + Send; } /// One reader. Claim separates owners; each scan subscribes afresh. diff --git a/crates/vault-broker/src/service/fprintd.rs b/crates/vault-broker/src/service/fprintd.rs index a6e7b1bb..96cdc4c2 100644 --- a/crates/vault-broker/src/service/fprintd.rs +++ b/crates/vault-broker/src/service/fprintd.rs @@ -97,13 +97,6 @@ impl FingerprintBackend for FprintdBackend { } Err(denied("No enrolled fingerprint reader")) } - - async fn client_present(&self, owner: &Owner) -> bool { - let Ok(client) = BusName::try_from(owner.connection.as_str()) else { - return false; - }; - self.dbus.get_connection_unix_user(client).await.is_ok() - } } pub(super) struct FprintdDevice { diff --git a/crates/vault-broker/src/service/tests.rs b/crates/vault-broker/src/service/tests.rs index 4f9d6312..dc6d2cfe 100644 --- a/crates/vault-broker/src/service/tests.rs +++ b/crates/vault-broker/src/service/tests.rs @@ -2,7 +2,7 @@ use super::*; use std::{ io::{BufRead as _, BufReader}, process::{Child, Command, Stdio}, - sync::atomic::AtomicUsize, + sync::atomic::{AtomicUsize, Ordering}, }; use zbus::{Proxy, connection::Builder, object_server::SignalEmitter, zvariant::OwnedObjectPath}; struct Bus { @@ -60,7 +60,7 @@ struct Device { mode: Arc, scripts: Arc>>, events: Arc>>, - cancel: Arc, + cancel: watch::Sender, } #[zbus::interface(name = "net.reactivated.Fprint.Device")] impl Device { @@ -99,7 +99,7 @@ impl Device { )); } if self.mode.load(Ordering::SeqCst) == 7 { - self.cancel.store(true, Ordering::SeqCst); + self.cancel.send_replace(true); } // Stale success emitted during stop must not authorize the next scan. Self::verify_status(&emitter, "verify-match", true) @@ -173,8 +173,9 @@ async fn key_expiry_runs_while_unrelated_name_ownership_keeps_changing() { ) .unwrap(); let observe_store = store.clone(); + let changes = connection_losses(&service).await.unwrap(); let observer = tokio::spawn(async move { - observe_connections(service, observe_store, Duration::from_millis(30)) + observe_connections(changes, observe_store, Duration::from_millis(30)) .await .unwrap(); }); @@ -207,10 +208,10 @@ async fn key_expiry_runs_while_unrelated_name_ownership_keeps_changing() { let mut store = store.lock().await; let entry = store.entry(&owner, &binding, &token).unwrap(); entry.touched -= Duration::from_secs(9 * 60 * 60); - entry.cancel.clone() + entry.start_release(&owner).unwrap() }; let expired = tokio::time::timeout(Duration::from_millis(750), async { - while !cancelled.load(Ordering::SeqCst) || events.load(Ordering::SeqCst) <= 5 { + while !*cancelled.borrow() || events.load(Ordering::SeqCst) <= 5 { tokio::time::sleep(Duration::from_millis(1)).await; } }) diff --git a/crates/vault-broker/src/service/tests/retries.rs b/crates/vault-broker/src/service/tests/retries.rs index c5f08523..1717c599 100644 --- a/crates/vault-broker/src/service/tests/retries.rs +++ b/crates/vault-broker/src/service/tests/retries.rs @@ -8,7 +8,7 @@ struct Fixture { owner: Owner, calls: Arc, events: Arc>>, - cancel: Arc, + cancel: watch::Sender, binding: String, token: String, } @@ -20,7 +20,7 @@ impl Fixture { let client = connect(&bus).await; let calls = Arc::new(AtomicUsize::new(0)); let events = Arc::new(std::sync::Mutex::new(Vec::new())); - let cancel = Arc::new(AtomicBool::new(false)); + let cancel = watch::Sender::new(false); fake.object_server() .at("/net/reactivated/Fprint/Manager", Manager) .await @@ -83,7 +83,13 @@ impl Fixture { } async fn verify(&self) -> fdo::Result<()> { self.broker - .verify(&self.owner, &self.binding, &self.token, self.cancel.clone()) + .verify( + &self.owner, + &self.binding, + &self.token, + &self.cancel.subscribe(), + None, + ) .await } } @@ -305,7 +311,7 @@ async fn failures_survive_cancellation_faults_and_timeout_but_match_resets() { .attempts_remaining, 2 ); - fixture.cancel.store(false, Ordering::SeqCst); + fixture.cancel.send_replace(false); let interface = fixture ._fake .object_server() @@ -328,3 +334,203 @@ async fn failures_survive_cancellation_faults_and_timeout_but_match_resets() { ); } } + +async fn publish(broker: Broker) -> (Connection, tokio::task::JoinHandle<()>) { + let service = broker.connection.clone(); + let changes = connection_losses(&service).await.unwrap(); + let store = broker.store.clone(); + service.object_server().at(PATH, broker).await.unwrap(); + service.request_name(NAME).await.unwrap(); + let observer = tokio::spawn(async move { + observe_connections(changes, store, Duration::from_secs(30)) + .await + .unwrap(); + }); + (service, observer) +} + +async fn wait_for_scan(calls: &AtomicUsize) { + tokio::time::timeout(Duration::from_secs(2), async { + while calls.load(Ordering::SeqCst) == 0 { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn disconnect_releases_the_scanner_and_preserves_the_registration() { + let fixture = Fixture::new( + vec![vec![], vec![("verify-match", true)]], + 2, + Duration::from_secs(15), + ) + .await; + let (_, observer) = publish(fixture.broker).await; + let caller = Proxy::new(&fixture._client, NAME, PATH, NAME) + .await + .unwrap(); + let args = (fixture.binding.as_str(), fixture.token.as_str()); + let pending = caller.call::<_, _, Vec>("Release", &args); + tokio::pin!(pending); + tokio::select! { + () = wait_for_scan(&fixture.calls) => {} + result = &mut pending => panic!("scan finished before disconnect: {result:?}"), + } + let restarted = connect(&fixture._bus).await; + let replacement = Proxy::new(&restarted, NAME, PATH, NAME).await.unwrap(); + fixture._client.clone().close().await.unwrap(); + let result = tokio::time::timeout(Duration::from_secs(2), pending) + .await + .unwrap(); + assert!(result.is_err()); + tokio::time::timeout(Duration::from_secs(2), async { + while !fixture.events.lock().unwrap().contains(&"release".into()) { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + + // Cleanup completes before the second release can claim the same reader. + let key: Vec = tokio::time::timeout(Duration::from_secs(2), async { + loop { + match replacement.call("Release", &args).await { + Err(zbus::Error::MethodError(_, Some(ref text), _)) + if text == "Authentication is already in progress" => + { + tokio::time::sleep(Duration::from_millis(1)).await; + } + result => break result.unwrap(), + } + } + }) + .await + .unwrap(); + assert_eq!(key, [42; 32]); + assert_eq!( + *fixture.events.lock().unwrap(), + ["start", "stop", "release", "start", "stop", "release"] + ); + observer.abort(); +} + +async fn monitor_caller_credentials( + bus: &Bus, + service: &Connection, + client: &Connection, +) -> zbus::MessageStream { + let monitor = connect(bus).await; + let rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::MethodCall) + .sender(service.unique_name().unwrap().as_str()) + .unwrap() + .interface("org.freedesktop.DBus") + .unwrap() + .member("GetConnectionUnixUser") + .unwrap() + .arg(0, client.unique_name().unwrap().as_str()) + .unwrap() + .build(); + fdo::MonitoringProxy::new(&monitor) + .await + .unwrap() + .become_monitor(&[rule], 0) + .await + .unwrap(); + zbus::MessageStream::from(monitor) +} + +#[tokio::test] +async fn a_waiting_scan_does_not_poll_caller_credentials_or_cancel_for_another_peer() { + let fixture = Fixture::new(vec![], 2, Duration::from_secs(15)).await; + let (service, observer) = publish(fixture.broker).await; + let caller = Proxy::new(&fixture._client, NAME, PATH, NAME) + .await + .unwrap(); + let mut monitor = monitor_caller_credentials(&fixture._bus, &service, &fixture._client).await; + let args = (fixture.binding.as_str(), fixture.token.as_str()); + let pending = caller.call::<_, _, Vec>("Release", &args); + tokio::pin!(pending); + tokio::select! { + () = wait_for_scan(&fixture.calls) => {} + result = &mut pending => panic!("scan finished before cancellation: {result:?}"), + } + let initial = tokio::time::timeout(Duration::from_secs(1), monitor.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + initial.header().member().unwrap().as_str(), + "GetConnectionUnixUser" + ); + + connect(&fixture._bus).await.close().await.unwrap(); + tokio::select! { + result = &mut pending => panic!("another peer ended the scan: {result:?}"), + message = monitor.next() => panic!("the broker polled caller credentials: {message:?}"), + () = tokio::time::sleep(Duration::from_millis(250)) => {} + } + let _: () = caller.call("Cancel", &args).await.unwrap(); + let error = tokio::time::timeout(Duration::from_secs(2), pending) + .await + .unwrap() + .unwrap_err(); + assert!( + matches!(error, zbus::Error::MethodError(_, Some(text), _) if text == "Authentication cancelled") + ); + assert_eq!( + *fixture.events.lock().unwrap(), + ["start", "stop", "release"] + ); + observer.abort(); +} + +#[tokio::test] +async fn progress_goes_only_to_the_release_caller_and_reports_each_failed_scan() { + let fixture = Fixture::new(vec![], 1, Duration::from_secs(5)).await; + let service = fixture.broker.connection.clone(); + let other = connect(&fixture._bus).await; + service + .object_server() + .at(PATH, fixture.broker) + .await + .unwrap(); + service.request_name(NAME).await.unwrap(); + // Mirror the desktop, which sends to the broker's authenticated unique name. + let destination = service.unique_name().unwrap().to_owned(); + let caller = Proxy::new(&fixture._client, destination.clone(), PATH, NAME) + .await + .unwrap(); + let observer = Proxy::new(&other, destination, PATH, NAME).await.unwrap(); + let mut reports = caller.receive_signal("ReleaseProgress").await.unwrap(); + let mut unrelated = observer.receive_signal("ReleaseProgress").await.unwrap(); + + let invalid = (fixture.binding.as_str(), "b".repeat(64), 8u64); + let denied: Result, _> = caller.call("ReleaseWithProgress", &invalid).await; + assert!(denied.is_err()); + assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); + + let args = (fixture.binding.as_str(), fixture.token.as_str(), 9u64); + let result: Result, _> = caller.call("ReleaseWithProgress", &args).await; + assert!(matches!(result, Err(zbus::Error::MethodError(name, _, _)) + if name.as_str() == "dev.nocterm.VaultBroker1.Error.Locked")); + for remaining in [3, 2, 1, 0] { + let message = tokio::time::timeout(Duration::from_secs(1), reports.next()) + .await + .unwrap() + .unwrap(); + assert_eq!( + message.body().deserialize::<(u64, u8)>().unwrap(), + (9, remaining) + ); + } + assert!( + tokio::time::timeout(Duration::from_millis(50), unrelated.next()) + .await + .is_err() + ); + assert_eq!(fixture.calls.load(Ordering::SeqCst), 3); +} diff --git a/crates/vault-broker/src/service/verify.rs b/crates/vault-broker/src/service/verify.rs index d7bcc5b6..7545949f 100644 --- a/crates/vault-broker/src/service/verify.rs +++ b/crates/vault-broker/src/service/verify.rs @@ -2,25 +2,23 @@ //! attempt accounting, scanner exclusivity, claim with bounded cleanup and //! the scan loop under one deadline. use super::{ - denied, + Progress, denied, fingerprint::{ FingerprintBackend, FingerprintDevice, ScanStatus, VerifyStatuses, verification_status, }, }; use crate::store::{MAX_ATTEMPTS, Owner, Store}; -use std::{ - sync::atomic::{AtomicBool, Ordering}, - time::Duration, +use std::time::Duration; +use tokio::{ + sync::{Mutex, watch}, + time::Instant, }; -use tokio::{sync::Mutex, time::Instant}; use zbus::fdo; /// Bounds discovery, claim and scanning together, whatever the scan deadline. const SERVICE_LIMIT: Duration = Duration::from_secs(35); /// Bounds each cleanup call, so a hung reader cannot keep the broker waiting. pub(super) const CLEANUP_LIMIT: Duration = Duration::from_secs(1); -/// How often a scan checks for cancellation and a departed client. -const WATCHDOG: Duration = Duration::from_millis(50); const LOCKED: &str = "Fingerprint unlock is locked after 3 failed attempts"; /// The registration whose attempts a verification spends. @@ -44,14 +42,14 @@ impl Attempts<'_> { } /// Persists the outcome of a completed scan before anything else happens. - async fn record(&self, matched: bool) -> fdo::Result { + async fn record(&self, matched: bool) -> fdo::Result<(u8, Next)> { let mut store = self.store.lock().await; let entry = store .entry(self.owner, self.binding, self.token) .map_err(denied)?; let (remaining, next) = after_scan(entry.attempts_remaining, matched); entry.attempts_remaining = remaining; - Ok(next) + Ok((remaining, next)) } } @@ -78,14 +76,15 @@ pub(super) struct Request<'a> { pub attempts: Attempts<'a>, /// Held for the whole verification: one reader serves one request. pub scanner: &'a Mutex<()>, - pub cancel: &'a AtomicBool, + pub cancel: &'a watch::Receiver, /// Covers every scan and the setup between them. pub scan_timeout: Duration, + pub progress: Option<&'a Progress<'a>>, } impl Request<'_> { fn ensure_active(&self) -> fdo::Result<()> { - if self.cancel.load(Ordering::SeqCst) { + if *self.cancel.borrow() { return Err(denied("Authentication cancelled")); } Ok(()) @@ -97,6 +96,7 @@ pub(super) async fn verify( backend: &B, request: &Request<'_>, ) -> fdo::Result<()> { + request.ensure_active()?; request.attempts.ensure_unlocked().await?; let _scanner = request .scanner @@ -104,7 +104,7 @@ pub(super) async fn verify( .map_err(|_| fdo::Error::Failed("Fingerprint reader is busy".into()))?; let service = Instant::now() + SERVICE_LIMIT; let device = within(service, backend.device(request.attempts.owner)).await?; - with_claim(&device, service, scan(backend, &device, request)).await + with_claim(&device, service, scan(&device, request)).await } async fn within( @@ -145,13 +145,9 @@ pub(super) async fn with_claim( claimed.result } -async fn scan( - backend: &B, - device: &B::Device, - request: &Request<'_>, -) -> Claimed { +async fn scan(device: &D, request: &Request<'_>) -> Claimed { let mut reader_gone = false; - let result = scan_until_decided(backend, device, request, &mut reader_gone).await; + let result = scan_until_decided(device, request, &mut reader_gone).await; Claimed { result, reader_gone, @@ -159,9 +155,8 @@ async fn scan( } /// Scans until a match, lockout, fault or the deadline. -async fn scan_until_decided( - backend: &B, - device: &B::Device, +async fn scan_until_decided( + device: &D, request: &Request<'_>, reader_gone: &mut bool, ) -> fdo::Result<()> { @@ -173,9 +168,13 @@ async fn scan_until_decided( loop { let matched = tokio::select! { () = &mut deadline => return Err(timed_out()), - result = scan_once(backend, device, request, reader_gone) => result?, + result = scan_once(device, request, reader_gone) => result?, }; - match request.attempts.record(matched).await? { + let (remaining, next) = request.attempts.record(matched).await?; + if !matched && let Some(progress) = request.progress { + progress.send(remaining).await; + } + match next { Next::Accept => return Ok(()), Next::Locked => return Err(denied(LOCKED)), Next::Retry => {} @@ -190,21 +189,18 @@ async fn scan_until_decided( } /// One scan: whether the finger matched. -async fn scan_once( - backend: &B, - device: &B::Device, +async fn scan_once( + device: &D, request: &Request<'_>, reader_gone: &mut bool, ) -> fdo::Result { request.ensure_active()?; let mut statuses = device.verify_start().await?; + let mut cancel = request.cancel.clone(); loop { tokio::select! { - () = tokio::time::sleep(WATCHDOG) => { - request.ensure_active()?; - if !backend.client_present(request.attempts.owner).await { - return Err(denied("Client disconnected")); - } + _ = cancel.wait_for(|cancelled| *cancelled) => { + return Err(denied("Authentication cancelled")); } status = statuses.next() => { let (status, done) = status?; diff --git a/crates/vault-broker/src/service/verify/tests.rs b/crates/vault-broker/src/service/verify/tests.rs index 8f56affb..b0d7e917 100644 --- a/crates/vault-broker/src/service/verify/tests.rs +++ b/crates/vault-broker/src/service/verify/tests.rs @@ -46,14 +46,12 @@ impl Reader { struct ScriptedBackend { reader: Reader, - client_present: AtomicBool, } impl ScriptedBackend { fn new(reader: &Reader) -> Self { Self { reader: reader.clone(), - client_present: AtomicBool::new(true), } } } @@ -64,10 +62,6 @@ impl FingerprintBackend for ScriptedBackend { async fn device(&self, _owner: &Owner) -> fdo::Result { Ok(self.reader.clone()) } - - async fn client_present(&self, _owner: &Owner) -> bool { - self.client_present.load(Ordering::SeqCst) - } } impl FingerprintDevice for Reader { @@ -118,7 +112,7 @@ impl VerifyStatuses for VecDeque<(&'static str, bool)> { struct Fixture { store: Mutex, scanner: Mutex<()>, - cancel: AtomicBool, + cancel: watch::Sender, owner: Owner, binding: String, token: String, @@ -143,7 +137,7 @@ impl Fixture { Self { store: Mutex::new(store), scanner: Mutex::new(()), - cancel: AtomicBool::new(false), + cancel: watch::Sender::new(false), owner, binding, token, @@ -151,7 +145,7 @@ impl Fixture { } } - fn request(&self) -> Request<'_> { + fn request<'a>(&'a self, cancel: &'a watch::Receiver) -> Request<'a> { Request { attempts: Attempts { store: &self.store, @@ -160,13 +154,14 @@ impl Fixture { token: &self.token, }, scanner: &self.scanner, - cancel: &self.cancel, + cancel, scan_timeout: self.scan_timeout, + progress: None, } } async fn verify(&self, backend: &ScriptedBackend) -> fdo::Result<()> { - verify(backend, &self.request()).await + verify(backend, &self.request(&self.cancel.subscribe())).await } async fn remaining(&self) -> u8 { @@ -272,23 +267,13 @@ async fn cancelling_during_a_scan_ends_it() { let backend = ScriptedBackend::new(&reader); let cancel = async { tokio::time::sleep(Duration::from_millis(20)).await; - fixture.cancel.store(true, Ordering::SeqCst); + fixture.cancel.send_replace(true); }; let (result, ()) = tokio::join!(fixture.verify(&backend), cancel); assert!(message(result).contains("Authentication cancelled")); assert_eq!(reader.log(), ["claim", "start", "stop", "release"]); } -#[tokio::test] -async fn a_departed_client_ends_the_scan() { - let reader = Reader::new(vec![vec![]]); - let fixture = Fixture::new(); - let backend = ScriptedBackend::new(&reader); - backend.client_present.store(false, Ordering::SeqCst); - assert!(message(fixture.verify(&backend).await).contains("Client disconnected")); - assert_eq!(reader.log(), ["claim", "start", "stop", "release"]); -} - #[tokio::test] async fn a_hung_release_is_bounded_by_the_cleanup_limit() { let reader = Reader::new(vec![vec![("verify-match", true)]]).with(Fault::ReleaseHangs); @@ -321,7 +306,7 @@ async fn a_second_verification_finds_the_reader_busy() { let second = async { tokio::time::sleep(Duration::from_millis(20)).await; let result = fixture.verify(&backend).await; - fixture.cancel.store(true, Ordering::SeqCst); + fixture.cancel.send_replace(true); result }; let (first, second) = tokio::join!(fixture.verify(&backend), second); diff --git a/crates/vault-broker/src/store.rs b/crates/vault-broker/src/store.rs index 38da9c8b..cc5c5183 100644 --- a/crates/vault-broker/src/store.rs +++ b/crates/vault-broker/src/store.rs @@ -2,12 +2,9 @@ //! restarts, but disappear with the broker (reboot) or after their lifetime. use std::{ collections::HashMap, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, time::{Duration, Instant}, }; +use tokio::sync::watch; use zeroize::Zeroizing; pub(crate) const MAX_ATTEMPTS: u8 = 3; const MAX_ENTRIES: usize = 64; @@ -42,10 +39,32 @@ pub(crate) struct Entry { pub binding: String, pub key: Zeroizing<[u8; 32]>, pub touched: Instant, - pub cancel: Arc, - pub busy: bool, + active_release: Option>, pub attempts_remaining: u8, } +impl Entry { + pub(crate) fn start_release(&mut self, caller: &Owner) -> Option> { + if self.active_release.is_some() { + return None; + } + let (cancel, cancelled) = watch::channel(false); + // A disconnecting caller cancels only its own authentication. + self.owner.connection.clone_from(&caller.connection); + self.active_release = Some(cancel); + Some(cancelled) + } + + pub(crate) fn cancel_release(&self) { + if let Some(cancel) = &self.active_release { + cancel.send_replace(true); + } + } + + pub(crate) fn finish_release(&mut self) { + self.active_release = None; + } +} + #[derive(Default)] pub(crate) struct Store { entries: HashMap, @@ -83,7 +102,7 @@ impl Store { self.entries.retain(|_, e| { let replaced = e.owner.uid == owner.uid && e.binding == binding; if replaced { - e.cancel.store(true, Ordering::SeqCst); + e.cancel_release(); } !replaced }); @@ -107,8 +126,7 @@ impl Store { binding, key, touched: Instant::now(), - cancel: Arc::new(AtomicBool::new(false)), - busy: false, + active_release: None, attempts_remaining: MAX_ATTEMPTS, }, ); @@ -138,9 +156,7 @@ impl Store { if !self.entries.contains_key(token) { return Ok(()); } - self.entry(owner, binding, token)? - .cancel - .store(true, Ordering::SeqCst); + self.entry(owner, binding, token)?.cancel_release(); self.entries.remove(token); Ok(()) } @@ -149,14 +165,14 @@ impl Store { pub(crate) fn disconnected(&mut self, name: &str) { for entry in self.entries.values_mut() { if entry.owner.connection == name { - entry.cancel.store(true, Ordering::SeqCst); + entry.cancel_release(); } } } pub(crate) fn expire(&mut self) { self.entries.retain(|_, e| { if e.touched.elapsed() > LIFETIME { - e.cancel.store(true, Ordering::SeqCst); + e.cancel_release(); false } else { true @@ -228,9 +244,13 @@ mod tests { let token = store .enroll(a.clone(), id.clone(), Zeroizing::new([42; 32])) .unwrap(); - let cancel = store.entry(&a, &id, &token).unwrap().cancel.clone(); + let cancel = store + .entry(&a, &id, &token) + .unwrap() + .start_release(&a) + .unwrap(); store.disconnected(":1.1"); - assert!(cancel.load(Ordering::SeqCst)); + assert!(*cancel.borrow()); assert!(store.entry(&a, &id, &token).is_ok()); let token = store .enroll(a.clone(), id.clone(), Zeroizing::new([42; 32])) @@ -286,13 +306,12 @@ mod tests { )); let (first, token) = oldest.unwrap(); let entry = store.entry(&first, &id, &token).unwrap(); - let cancel = entry.cancel.clone(); - entry.busy = true; + let cancel = entry.start_release(&first).unwrap(); entry.touched = Instant::now() - LIFETIME - Duration::from_secs(1); let admitted = store .enroll(newcomer.clone(), id.clone(), Zeroizing::new([0; 32])) .unwrap(); - assert!(cancel.load(Ordering::SeqCst)); + assert!(*cancel.borrow()); assert!(matches!( store.entry(&first, &id, &token), Err(RegistrationError::Unavailable) @@ -300,10 +319,10 @@ mod tests { let cancel = store .entry(&newcomer, &id, &admitted) .unwrap() - .cancel - .clone(); + .start_release(&newcomer) + .unwrap(); store.disconnected(&newcomer.connection); - assert!(cancel.load(Ordering::SeqCst)); + assert!(*cancel.borrow()); assert!(store.entry(&newcomer, &id, &admitted).is_ok()); assert!( store @@ -347,9 +366,13 @@ mod tests { let token = store .enroll(a.clone(), binding.clone(), Zeroizing::new([42; 32])) .unwrap(); - let cancel = store.entry(&a, &binding, &token).unwrap().cancel.clone(); + let cancel = store + .entry(&a, &binding, &token) + .unwrap() + .start_release(&a) + .unwrap(); store.remove(&a, &binding, &token).unwrap(); - assert!(cancel.load(Ordering::SeqCst)); + assert!(*cancel.borrow()); assert!(matches!( store.entry(&a, &binding, &token), Err(RegistrationError::Unavailable) @@ -369,7 +392,11 @@ mod tests { let token = store .enroll(a.clone(), binding.clone(), Zeroizing::new([42; 32])) .unwrap(); - let cancel = store.entry(&a, &binding, &token).unwrap().cancel.clone(); + let cancel = store + .entry(&a, &binding, &token) + .unwrap() + .start_release(&a) + .unwrap(); let error = store .enroll_with_entropy(a.clone(), binding.clone(), Zeroizing::new([7; 32]), |_| { Err(getrandom::Error::UNSUPPORTED) @@ -386,7 +413,7 @@ mod tests { assert_eq!(error.to_string(), "Randomness unavailable"); assert!(!format!("{error:?}").contains(&token)); assert!(!format!("{error:?}").contains(&binding)); - assert!(cancel.load(Ordering::SeqCst)); + assert!(*cancel.borrow()); assert!(matches!( store.entry(&a, &binding, &token), Err(RegistrationError::Unavailable) diff --git a/crates/vault-store/src/tests/status.rs b/crates/vault-store/src/tests/status.rs index 9ada51f5..99ad6ef0 100644 --- a/crates/vault-store/src/tests/status.rs +++ b/crates/vault-store/src/tests/status.rs @@ -4,12 +4,13 @@ use futures::{ task::{ArcWake, waker}, }; use nocterm_session::Secret; -use nocterm_vault::VaultStatus; +use nocterm_vault::{VaultError, VaultStatus}; use std::task::{Context, Poll}; use std::{ sync::{ Arc, atomic::{AtomicBool, Ordering}, + mpsc, }, time::Duration, }; @@ -24,6 +25,14 @@ impl ArcWake for Woken { } } +struct Signal(mpsc::SyncSender<()>); + +impl ArcWake for Signal { + fn wake_by_ref(this: &Arc) { + let _ = this.0.try_send(()); + } +} + fn locked_vault(directory: &tempfile::TempDir) -> VaultService { let service = VaultService::new(directory.path().join("vault"), Duration::from_secs(60)).unwrap(); @@ -67,6 +76,32 @@ fn locking_publishes_a_change() { assert_eq!(service.status(), VaultStatus::Locked); } +#[test] +fn changing_the_timeout_reapplies_it_to_idle_time_without_new_vault_activity() { + let directory = tempfile::tempdir().unwrap(); + let service = + VaultService::new(directory.path().join("vault"), Duration::from_secs(1)).unwrap(); + block_on(service.create(Secret::new(MASTER))).unwrap(); + let mut changed = service.changed(service.revision()); + let (sender, receiver) = mpsc::sync_channel(1); + let waker = waker(Arc::new(Signal(sender))); + let mut cx = Context::from_waker(&waker); + assert!(changed.as_mut().poll(&mut cx).is_pending()); + + service.set_auto_lock(Duration::from_secs(60)); + assert_eq!( + receiver.recv_timeout(Duration::from_millis(1350)), + Err(mpsc::RecvTimeoutError::Timeout) + ); + assert_eq!(service.status(), VaultStatus::Unlocked); + + service.set_auto_lock(Duration::from_secs(1)); + receiver.recv_timeout(Duration::from_secs(5)).unwrap(); + assert!(changed.as_mut().poll(&mut cx).is_ready()); + assert_eq!(service.status(), VaultStatus::Locked); + assert!(matches!(block_on(service.list()), Err(VaultError::Locked))); +} + #[test] fn a_missing_vault_reports_missing() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/vault-store/src/worker.rs b/crates/vault-store/src/worker.rs index 44f0d205..3af2c357 100644 --- a/crates/vault-store/src/worker.rs +++ b/crates/vault-store/src/worker.rs @@ -15,7 +15,7 @@ use std::{ sync::{ Arc, atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}, - mpsc::{self, RecvTimeoutError, SyncSender}, + mpsc::{self, Receiver, RecvTimeoutError, SyncSender}, }, thread, time::{Duration, Instant}, @@ -26,6 +26,11 @@ struct Job { epoch: u64, operation: Operation, } +enum Command { + Run(Job), + Wake, +} + struct State { epoch: Arc, unlocked: AtomicBool, @@ -73,12 +78,68 @@ impl State { } } +fn run_worker(mut vault: Vault, state: &State, commands: Receiver) { + let mut epoch = 0; + let mut touched = Instant::now(); + let mut command = Command::Wake; + loop { + let current = state.epoch.load(Ordering::SeqCst); + if epoch != current { + vault.lock(); + epoch = current; + } + let timeout = Duration::from_secs(state.auto_lock_secs.load(Ordering::Relaxed)); + if vault.is_unlocked() && touched.elapsed() >= timeout { + vault.lock(); + let next = epoch.wrapping_add(1); + epoch = + match state + .epoch + .compare_exchange(epoch, next, Ordering::SeqCst, Ordering::SeqCst) + { + Ok(_) => next, + Err(current) => current, + }; + state.unlocked.store(false, Ordering::SeqCst); + state.publish(); + } + if let Command::Run(job) = command + && job.epoch == state.epoch.load(Ordering::SeqCst) + { + vault.set_cancellation(DeviceCancellation::for_epoch( + state.epoch.clone(), + job.epoch, + )); + (job.operation)(&mut vault); + vault.set_cancellation(DeviceCancellation::never()); + if job.epoch != state.epoch.load(Ordering::SeqCst) { + vault.lock(); + } + state.published_epoch.store(job.epoch, Ordering::SeqCst); + state.unlocked.store(vault.is_unlocked(), Ordering::SeqCst); + state.exists.store(vault.exists(), Ordering::SeqCst); + state.publish(); + touched = Instant::now(); + } + let received = if vault.is_unlocked() { + commands.recv_timeout(timeout.saturating_sub(touched.elapsed())) + } else { + commands.recv().map_err(|_| RecvTimeoutError::Disconnected) + }; + command = match received { + Ok(command) => command, + Err(RecvTimeoutError::Timeout) => Command::Wake, + Err(RecvTimeoutError::Disconnected) => break, + }; + } +} + /// Thread-safe provider. No method waits for a KDF or file I/O on the caller. /// At most eight operations are queued behind a single worker. Lock invalidates /// queued and in-flight results; intermediate secrets are zeroized when dropped. #[derive(Clone)] pub struct VaultService { - jobs: SyncSender, + jobs: SyncSender, state: Arc, } impl VaultService { @@ -102,59 +163,11 @@ impl VaultService { changed: event_listener::Event::new(), }); state.publish(); - let (sender, receiver) = mpsc::sync_channel::(8); + let (sender, receiver) = mpsc::sync_channel(8); let worker_state = state.clone(); thread::Builder::new() .name("nocterm-vault".into()) - .spawn(move || { - let mut vault = Vault::with_device(path, device); - let mut epoch = 0; - let mut touched = Instant::now(); - loop { - let now_epoch = worker_state.epoch.load(Ordering::SeqCst); - if epoch != now_epoch { - vault.lock(); - epoch = now_epoch; - } - if vault.is_unlocked() - && touched.elapsed().as_secs() - >= worker_state.auto_lock_secs.load(Ordering::Relaxed) - { - vault.lock(); - epoch = worker_state.epoch.fetch_add(1, Ordering::SeqCst) + 1; - worker_state.unlocked.store(false, Ordering::SeqCst); - worker_state.publish(); - } - match receiver.recv_timeout(Duration::from_millis(250)) { - Ok(job) => { - if job.epoch != worker_state.epoch.load(Ordering::SeqCst) { - drop(job); - continue; - } - vault.set_cancellation(DeviceCancellation::for_epoch( - worker_state.epoch.clone(), - job.epoch, - )); - (job.operation)(&mut vault); - vault.set_cancellation(DeviceCancellation::never()); - if job.epoch != worker_state.epoch.load(Ordering::SeqCst) { - vault.lock(); - } - worker_state - .published_epoch - .store(job.epoch, Ordering::SeqCst); - worker_state - .unlocked - .store(vault.is_unlocked(), Ordering::SeqCst); - worker_state.exists.store(vault.exists(), Ordering::SeqCst); - worker_state.publish(); - touched = Instant::now(); - } - Err(RecvTimeoutError::Timeout) => {} - Err(RecvTimeoutError::Disconnected) => break, - } - } - })?; + .spawn(move || run_worker(Vault::with_device(path, device), &worker_state, receiver))?; Ok(Self { jobs: sender, state, @@ -194,20 +207,21 @@ impl VaultService { .boxed() } pub fn set_auto_lock(&self, duration: Duration) { - self.state - .auto_lock_secs - .store(duration.as_secs().max(1), Ordering::Relaxed); + let seconds = duration.as_secs().max(1); + if self.state.auto_lock_secs.swap(seconds, Ordering::Relaxed) != seconds { + self.wake_worker(); + } } pub fn lock(&self) { self.state.epoch.fetch_add(1, Ordering::SeqCst); self.state.unlocked.store(false, Ordering::SeqCst); self.state.publish(); - // Wake the worker. If its bounded queue is full, the next job already - // wakes it and will observe the changed epoch before accessing secrets. - let _ = self.jobs.try_send(Job { - epoch: self.state.epoch.load(Ordering::SeqCst), - operation: Box::new(|vault| vault.lock()), - }); + self.wake_worker(); + } + fn wake_worker(&self) { + // A full queue already guarantees a wake. The loop reads the latest + // epoch and timeout before dispatch, regardless of the command type. + let _ = self.jobs.try_send(Command::Wake); } fn request( &self, @@ -232,7 +246,7 @@ impl VaultService { let _ = sender.send(result); }), }; - let sent = self.jobs.try_send(job).is_ok(); + let sent = self.jobs.try_send(Command::Run(job)).is_ok(); async move { if !sent { return Err(VaultError::Busy); diff --git a/crates/vault-store/tests/worker_idle.rs b/crates/vault-store/tests/worker_idle.rs new file mode 100644 index 00000000..04cb0bad --- /dev/null +++ b/crates/vault-store/tests/worker_idle.rs @@ -0,0 +1,81 @@ +//! Linux scheduler counters for the native worker. +#![cfg(target_os = "linux")] + +use futures::executor::block_on; +use nocterm_session::Secret; +use nocterm_vault::VaultStatus; +use nocterm_vault_store::VaultService; +use std::{ + fs, + io::{self, Write as _}, + path::{Path, PathBuf}, + thread, + time::{Duration, Instant}, +}; + +#[test] +#[ignore = "manual release benchmark; requires Linux /proc scheduler counters"] +fn measure_idle_vault_worker() { + let directory = tempfile::tempdir().unwrap(); + let service = + VaultService::new(directory.path().join("vault"), Duration::from_secs(60)).unwrap(); + let password = || Secret::new("synthetic benchmark master passphrase"); + block_on(service.create(password())).unwrap(); + let worker = vault_thread(); + service.lock(); + assert!(block_on(service.list()).is_err()); + measure_phase(&service, &worker, VaultStatus::Locked); + + block_on(service.unlock(password())).unwrap(); + assert!(block_on(service.list()).unwrap().is_empty()); + measure_phase(&service, &worker, VaultStatus::Unlocked); +} + +fn vault_thread() -> PathBuf { + fs::read_dir("/proc/self/task") + .unwrap() + .filter_map(Result::ok) + .map(|entry| entry.path()) + .find(|path| { + fs::read_to_string(path.join("comm")).is_ok_and(|name| name.trim() == "nocterm-vault") + }) + .expect("vault worker thread") +} + +fn measure_phase(service: &VaultService, worker: &Path, status: VaultStatus) { + // The operation receipts can be sent just before the worker finishes admission. + thread::sleep(Duration::from_millis(50)); + assert_eq!(service.status(), status); + let (cpu_before, switches_before) = scheduler_counters(worker); + let start = Instant::now(); + thread::sleep(Duration::from_secs(2)); + let (cpu, switches) = scheduler_counters(worker); + assert_eq!(service.status(), status); + writeln!( + io::stdout().lock(), + "status={status:?} elapsed_us={} worker_cpu_ns={} voluntary_switches={}", + start.elapsed().as_micros(), + cpu - cpu_before, + switches - switches_before + ) + .unwrap(); +} + +fn scheduler_counters(worker: &Path) -> (u64, u64) { + let schedstat = fs::read_to_string(worker.join("schedstat")).unwrap(); + let status = fs::read_to_string(worker.join("status")).unwrap(); + let cpu = schedstat + .split_whitespace() + .next() + .unwrap() + .parse() + .unwrap(); + let switches = status + .lines() + .find_map(|line| line.strip_prefix("voluntary_ctxt_switches:")) + .unwrap() + .trim() + .parse() + .unwrap(); + (cpu, switches) +} diff --git a/crates/vault-ui/src/credentials_tab.rs b/crates/vault-ui/src/credentials_tab.rs index dd3f0903..fc1477a8 100644 --- a/crates/vault-ui/src/credentials_tab.rs +++ b/crates/vault-ui/src/credentials_tab.rs @@ -2,9 +2,10 @@ //! server. A password can be added under a name of its own (in a dialog) and then sign in to //! several servers, which are listed under it; any credential can be renamed or deleted, and a //! password detached from a server. +use gpui_kit::base::TestSupportExt as _; use gpui_kit::{ - AnyElement, AppContext as _, ClipboardItem, Context, Entity, SharedString, Subscription, - Window, + AnyElement, AppContext as _, ClipboardItem, Context, Entity, Focusable as _, SharedString, + Subscription, Window, component::{ ActiveTheme as _, Disableable as _, Sizable as _, button::{Button, ButtonVariants as _}, @@ -12,7 +13,7 @@ use gpui_kit::{ input::{Input, InputEvent, InputState}, v_flex, }, - div, + div, list, prelude::*, rems, }; @@ -21,9 +22,12 @@ use nocterm_ui::{IconName, form}; use nocterm_vault::{CredentialBinding, CredentialInfo, VaultAccess, VaultFuture}; use std::sync::Arc; +mod catalog; +use catalog::{Catalog, RenameFocus}; + pub(crate) struct CredentialsTab { service: Arc, - records: Vec, + catalog: Catalog, /// Bumped when the vault locks or the page closes, so that a late answer is dropped. generation: u64, busy: bool, @@ -49,14 +53,17 @@ impl CredentialsTab { ) -> Self { let query = cx.new(|cx| InputState::new(window, cx).placeholder("Search by name or server")); - let subscriptions = vec![cx.subscribe(&query, |_, _, event: &InputEvent, cx| { + let subscriptions = vec![cx.subscribe(&query, |this, input, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { - cx.notify(); + let rename = this.rename_focus(cx); + if this.catalog.search(&input.read(cx).value(), rename) { + cx.notify(); + } } })]; Self { service, - records: Vec::new(), + catalog: Catalog::default(), generation: 0, busy: false, message: None, @@ -77,7 +84,10 @@ impl CredentialsTab { return; } match result { - Ok(records) => this.records = records, + Ok(records) => { + let rename = this.rename_focus(cx); + this.catalog.replace(records, rename); + } Err(error) => this.message = Some((error.to_string().into(), true)), } cx.notify(); @@ -89,7 +99,7 @@ impl CredentialsTab { /// Forgets what the vault showed and every draft: it locked or the page closed. pub(crate) fn clear(&mut self, window: &mut Window, cx: &mut Context) { self.generation = self.generation.wrapping_add(1); - self.records.clear(); + self.catalog.clear(); self.busy = false; self.message = None; self.renaming = None; @@ -98,26 +108,14 @@ impl CredentialsTab { cx.notify(); } - /// The records whose name or server has the searched text. - fn matching(&self, cx: &gpui_kit::App) -> Vec { - let query = self.query.read(cx).value().trim().to_lowercase(); - self.records - .iter() - .filter(|record| { - query.is_empty() - || record.label.to_lowercase().contains(&query) - || record - .binding - .targets() - .iter() - .any(|target| target.to_string().to_lowercase().contains(&query)) - }) - .cloned() - .collect() + fn rename_focus(&self, cx: &gpui_kit::App) -> Option { + self.renaming + .as_ref() + .map(|rename| (rename.id, rename.input.read(cx).focus_handle(cx))) } fn start_rename(&mut self, id: CredentialId, window: &mut Window, cx: &mut Context) { - let Some(record) = self.records.iter().find(|record| record.id == id) else { + let Some(record) = self.catalog.record(id) else { return; }; let label = record.label.clone(); @@ -127,6 +125,8 @@ impl CredentialsTab { InputEvent::PressEnter { .. } | InputEvent::Blur => this.finish_rename(cx), _ => {} }); + self.catalog + .rename_focus(id, Some(input.read(cx).focus_handle(cx))); self.renaming = Some(Renaming { id, input, @@ -139,8 +139,9 @@ impl CredentialsTab { let Some(Renaming { id, input, .. }) = self.renaming.take() else { return; }; + self.catalog.rename_focus(id, None); let label = input.read(cx).value().trim().to_owned(); - let Some(record) = self.records.iter().find(|record| record.id == id) else { + let Some(record) = self.catalog.record(id) else { return; }; if label.is_empty() || label == record.label { @@ -153,7 +154,7 @@ impl CredentialsTab { /// Stops the password `id` signing in to its server at `index`. fn detach(&mut self, id: CredentialId, index: usize, cx: &mut Context) { - let Some(record) = self.records.iter().find(|record| record.id == id) else { + let Some(record) = self.catalog.record(id) else { return; }; let mut targets = record.binding.targets().to_vec(); @@ -228,6 +229,9 @@ impl CredentialsTab { .w_full() .py_3() .gap_2() + .when(index > 0, |row| { + row.border_t_1().border_color(theme.border.opacity(0.5)) + }) .items_start() .child( v_flex() @@ -335,25 +339,44 @@ impl Render for CredentialsTab { cx, ); } - let records = self.matching(cx); - let mut rows: Vec = records - .iter() - .enumerate() - .map(|(index, record)| self.row(index, record, cx)) - .collect(); - if rows.is_empty() { - let empty = if self.records.is_empty() { - "Nothing saved yet. Add a password, or choose Remember when you sign in to a \ - server." + let rows = if self.catalog.has_matches() { + v_flex() + .flex_1() + .min_h_0() + .child(form::section("Saved credentials", [], cx)) + .child( + div() + .id("vault-credential-results") + .test_support() + .flex_1() + .min_h_0() + .child( + list( + self.catalog.scroll(), + cx.processor(|this, index, _, cx| { + this.catalog.row(index).map_or_else( + || gpui_kit::Empty.into_any_element(), + |record| this.row(index, record, cx), + ) + }), + ) + .size_full(), + ), + ) + .into_any_element() + } else { + let empty = if self.catalog.is_empty() { + "Nothing saved yet. Add a password, or choose Remember when you sign in to a server." } else { "No saved credential has this name or server." }; - rows.push(form::note(empty, cx)); - } + form::section("Saved credentials", [form::note(empty, cx)], cx) + }; v_flex() - .w_full() + .size_full() + .min_h_0() .child(self.toolbar(cx)) - .child(form::section("Saved credentials", rows, cx)) + .child(rows) .child( h_flex().pt_2().child( Button::new("vault-refresh") diff --git a/crates/vault-ui/src/credentials_tab/catalog.rs b/crates/vault-ui/src/credentials_tab/catalog.rs new file mode 100644 index 00000000..5ffaab90 --- /dev/null +++ b/crates/vault-ui/src/credentials_tab/catalog.rs @@ -0,0 +1,153 @@ +//! The credentials tab's presentation snapshot and its filtered scroll order. +use gpui_kit::{FocusHandle, ListAlignment, ListState, px}; +use nocterm_session::CredentialId; +use nocterm_vault::CredentialInfo; + +pub(super) type RenameFocus = (CredentialId, FocusHandle); + +struct Record { + info: CredentialInfo, + label: String, + servers: Vec, +} + +impl Record { + fn new(info: CredentialInfo) -> Self { + let label = info.label.to_lowercase(); + let servers = info + .binding + .targets() + .iter() + .map(|target| target.to_string().to_lowercase()) + .collect(); + Self { + info, + label, + servers, + } + } + + fn matches(&self, query: &str) -> bool { + query.is_empty() + || self.label.contains(query) + || self.servers.iter().any(|server| server.contains(query)) + } +} + +pub(super) struct Catalog { + records: Vec, + matches: Vec, + query: String, + scroll: ListState, +} + +impl Default for Catalog { + fn default() -> Self { + Self { + records: Vec::new(), + matches: Vec::new(), + query: String::new(), + scroll: ListState::new(0, ListAlignment::Top, px(96.)), + } + } +} + +impl Catalog { + pub(super) fn replace(&mut self, records: Vec, rename: Option) { + let mut top = self.scroll.logical_scroll_top(); + let anchor = self.row(top.item_ix).map(|record| record.id); + self.records = records.into_iter().map(Record::new).collect(); + self.matches.clear(); + self.matches + .extend(matching_indices(&self.records, &self.query)); + self.reset_scroll(rename); + if let Some(anchor) = anchor { + top.item_ix = self.position(anchor).unwrap_or(top.item_ix); + self.scroll.scroll_to(top); + } + } + + pub(super) fn search(&mut self, query: &str, rename: Option) -> bool { + let query = query.trim().to_lowercase(); + if self.query == query { + return false; + } + self.query = query; + let matches = matching_indices(&self.records, &self.query); + if matches.clone().eq(self.matches.iter().copied()) { + return false; + } + self.matches.clear(); + self.matches.extend(matches); + self.reset_scroll(rename); + true + } + + pub(super) fn clear(&mut self) { + self.records = Vec::new(); + self.matches = Vec::new(); + self.query = String::new(); + self.scroll.reset(0); + } + + pub(super) fn record(&self, id: CredentialId) -> Option<&CredentialInfo> { + self.records + .iter() + .map(|record| &record.info) + .find(|info| info.id == id) + } + + pub(super) fn row(&self, index: usize) -> Option<&CredentialInfo> { + self.matches + .get(index) + .map(|&index| &self.records[index].info) + } + + pub(super) fn is_empty(&self) -> bool { + self.records.is_empty() + } + + pub(super) fn has_matches(&self) -> bool { + !self.matches.is_empty() + } + + pub(super) fn scroll(&self) -> ListState { + self.scroll.clone() + } + + pub(super) fn rename_focus(&self, id: CredentialId, focus: Option) { + if let Some(index) = self.position(id) { + let top = self.scroll.logical_scroll_top(); + self.scroll.splice_focusable(index..index + 1, [focus]); + if index == top.item_ix { + self.scroll.scroll_to(top); + } + } + } + + fn position(&self, id: CredentialId) -> Option { + self.matches + .iter() + .position(|&index| self.records[index].info.id == id) + } + + fn reset_scroll(&self, rename: Option) { + // Height hints keep offscreen rows reachable by scrolling. GPUI measures + // actual heights as rows appear, including wrapped server buttons. + self.scroll + .reset_with_uniform_height(self.matches.len(), px(56.)); + if let Some((id, focus)) = rename { + self.rename_focus(id, Some(focus)); + } + } +} + +fn matching_indices<'a>( + records: &'a [Record], + query: &'a str, +) -> impl Iterator + Clone + 'a { + records + .iter() + .enumerate() + .filter_map(move |(index, record)| record.matches(query).then_some(index)) +} diff --git a/crates/vault-ui/src/lib.rs b/crates/vault-ui/src/lib.rs index 3bc53d1e..5d0fab0b 100644 --- a/crates/vault-ui/src/lib.rs +++ b/crates/vault-ui/src/lib.rs @@ -120,6 +120,7 @@ pub fn settings_page(installed: &Installed) -> SettingsPageSpec { }) }) .with_icon(nocterm_ui::IconName::Lock) + .with_viewport() } #[cfg(test)] mod tests; diff --git a/crates/vault-ui/src/render.rs b/crates/vault-ui/src/render.rs index b80c7a78..8d447310 100644 --- a/crates/vault-ui/src/render.rs +++ b/crates/vault-ui/src/render.rs @@ -40,8 +40,12 @@ impl Render for VaultView { Tab::Security => self.security(cx), Tab::Options => self.options(cx), }; + let credentials_viewport = self.tab == Tab::Credentials && self.service.is_unlocked(); v_flex() - .w_full() + .id("vault-page") + .size_full() + .min_h_0() + .when(!credentials_viewport, |page| page.overflow_y_scroll()) .track_focus(&self.focus) .child(form::page_header( "Vault", @@ -49,7 +53,7 @@ impl Render for VaultView { cx, )) .child(tabs) - .child(body) + .child(div().w_full().when(credentials_viewport, |body| body.flex_1().min_h_0()).child(body)) .when_some(self.message.clone(), |page, (message, error)| { page.child(div().id("vault-message").role(gpui_kit::Role::Alert).aria_label(message.clone()).test_support().child(if error { form::error_text(message,cx) diff --git a/crates/vault-ui/src/tests/credentials_tab.rs b/crates/vault-ui/src/tests/credentials_tab.rs index ae5b3252..85d0b053 100644 --- a/crates/vault-ui/src/tests/credentials_tab.rs +++ b/crates/vault-ui/src/tests/credentials_tab.rs @@ -118,3 +118,139 @@ fn a_credential_is_renamed_and_a_shared_password_detached_from_one_server(cx: &m ); assert!(block_on(service.get(id, CredentialBinding::password([a]))).is_err()); } + +fn seed_credentials(service: &ScriptedVaultAccess, count: usize) -> nocterm_session::CredentialId { + let mut last = None; + for index in 0..count { + let host = format!("lab-{index:04}.example"); + last = Some( + block_on(service.put( + None, + format!("Synthetic credential {index:04}"), + CredentialBinding::password([Target::new("ops", host, 2222)]), + Secret::new("synthetic test password"), + )) + .unwrap(), + ); + } + last.unwrap() +} + +#[gpui_kit::test] +fn finding_a_server_after_scrolling_renames_its_credential(cx: &mut TestAppContext) { + use gpui_kit::{ScrollDelta, point, px}; + + let (handle, service) = unlocked_on_credentials(cx); + let last = seed_credentials(&service, 96); + click(handle, "vault-refresh", cx); + drain(cx); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + let search_bounds = window.find("vault-search").bounds(); + assert!(window.try_find(("vault-rename", 0usize)).is_some()); + assert!(window.try_find(("vault-rename", 95usize)).is_none()); + for _ in 0..12 { + window.scroll( + "vault-credential-results", + ScrollDelta::Pixels(point(px(0.), px(-100.))), + cx, + ); + } + assert!(window.try_find(("vault-rename", 0usize)).is_none()); + assert_eq!(window.find("vault-search").bounds(), search_bounds); + }) + .unwrap(); + + type_field(handle, "vault-search", "OPS@LAB-0095.EXAMPLE:2222", cx); + drain(cx); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find(("vault-rename", 1usize)).is_none()); + window.click(("vault-rename", 0usize), cx); + window.render_frame(cx); + window.press("ctrl-a", cx); + window.input("Selected by server", cx); + window.press("enter", cx); + }) + .unwrap(); + drain(cx); + let renamed = listed(&service) + .into_iter() + .find(|record| record.id == last) + .unwrap(); + assert_eq!(renamed.label, "Selected by server"); +} + +#[gpui_kit::test] +fn scrolling_a_rename_editor_out_of_view_preserves_its_keyboard_focus(cx: &mut TestAppContext) { + use gpui_kit::{ScrollDelta, point, px, size}; + + let (handle, service) = unlocked_on_credentials(cx); + cx.simulate_window_resize(handle, size(px(700.), px(390.))); + let first = seed_credentials(&service, 1); + seed_credentials(&service, 64); + click(handle, "vault-refresh", cx); + drain(cx); + + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.click(("vault-rename", 0usize), cx); + window.render_frame(cx); + assert!(window.try_find(("vault-rename", 12usize)).is_none()); + window.press("ctrl-a", cx); + window.input("Still editing", cx); + for _ in 0..12 { + window.scroll( + "vault-credential-results", + ScrollDelta::Pixels(point(px(0.), px(-110.))), + cx, + ); + } + assert!((12usize..65).any(|index| window.try_find(("vault-rename", index)).is_some())); + window.input(" after scrolling", cx); + window.press("enter", cx); + }) + .unwrap(); + drain(cx); + let renamed = listed(&service) + .into_iter() + .find(|record| record.id == first) + .unwrap(); + assert_eq!(renamed.label, "Still editing after scrolling"); +} + +#[gpui_kit::test] +#[ignore = "manual large credentials performance measurement"] +fn measure_search_in_large_credentials_tab(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let (handle, service) = unlocked_on_credentials(cx); + seed_credentials(&service, 512); + click(handle, "vault-refresh", cx); + drain(cx); + click(handle, "vault-search", cx); + let start = Instant::now(); + for letter in "synthetic".chars() { + cx.simulate_input(handle, letter.encode_utf8(&mut [0; 4])); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + } + let elapsed = start.elapsed(); + cx.update_window(handle, |_, window, _| { + assert!(window.try_find(("vault-rename", 1usize)).is_some()); + }) + .unwrap(); + type_field(handle, "vault-search", "ops@lab-0511.example:2222", cx); + drain(cx); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find(("vault-rename", 0usize)).is_some()); + assert!(window.try_find(("vault-rename", 1usize)).is_none()); + }) + .unwrap(); + writeln!( + std::io::stdout().lock(), + "512 credentials, 9 rendered query edits: {elapsed:.2?}" + ) + .unwrap(); +} diff --git a/crates/vt/Cargo.toml b/crates/vt/Cargo.toml index c5d35e1f..8196432d 100644 --- a/crates/vt/Cargo.toml +++ b/crates/vt/Cargo.toml @@ -11,6 +11,7 @@ layer = "domain" [dependencies] encoding_rs.workspace = true +memchr.workspace = true nocterm-session.workspace = true alacritty_terminal.workspace = true regex.workspace = true diff --git a/crates/vt/src/emulator.rs b/crates/vt/src/emulator.rs index 2c853fd8..bbb4d897 100644 --- a/crates/vt/src/emulator.rs +++ b/crates/vt/src/emulator.rs @@ -9,9 +9,9 @@ use alacritty_terminal::{ Term, event::{Event, EventListener, WindowSize}, grid::{Dimensions, Scroll as GridScroll}, - index::{Column, Line, Point, Side as GridSide}, - selection::{Selection, SelectionType}, - term::{Config, TermMode, cell::Flags, color::COUNT as COLOR_SLOTS, viewport_to_point}, + index::{Column, Line, Point}, + selection::Selection, + term::{Config, TermMode, cell::Flags, color::COUNT as COLOR_SLOTS}, vte::ansi::{ Color as AnsiColor, CursorShape as AnsiCursorShape, CursorStyle, NamedColor, Processor, Rgb as AnsiRgb, @@ -300,6 +300,9 @@ pub struct Frame { pub alt_screen: bool, /// Whether a visible physical row soft-wraps into the next row, on either screen. pub wraps: Vec, + /// Which visible rows contain cells modified since initialization or reset. + /// Untouched rows carry only blank cells and may still have background colors. + pub occupied_rows: Vec, /// The first visible row continues a soft-wrapped row above the viewport. pub starts_with_continuation: bool, /// Combining characters stacked on a cell, as `(cell index, characters)` @@ -357,6 +360,9 @@ pub struct Emulator { palette: Palette, options: EmulatorOptions, generation: u64, + paint_generation: u64, + search_generation: u64, + history_layout: u64, mouse_tracking_epoch: u64, search_match: Option<(u64, crate::SearchMatch)>, } @@ -383,6 +389,9 @@ impl Emulator { palette: Palette::default(), options, generation: 0, + paint_generation: 0, + search_generation: 0, + history_layout: 0, mouse_tracking_epoch: 0, search_match: None, } @@ -405,6 +414,9 @@ impl Emulator { self.osc_guard = crate::osc_guard::OscGuard::default(); self.events = events; self.generation = self.generation.wrapping_add(1); + self.paint_generation = self.paint_generation.wrapping_add(1); + self.search_generation = self.search_generation.wrapping_add(1); + self.history_layout = self.history_layout.wrapping_add(1); self.mouse_tracking_epoch = self.mouse_tracking_epoch.wrapping_add(1); self.search_match = None; } @@ -425,9 +437,11 @@ impl Emulator { self.generation = self.generation.wrapping_add(1); } let queued_events = self.queued_events(); + let paint = self.paint_state(); self.term.set_output_timestamp_ms(timestamp_ms); self.osc_guard .advance(bytes, |bytes| self.parser.advance(&mut self.term, bytes)); + self.observe_paint_change(paint); self.take_effects(queued_events) } @@ -444,10 +458,20 @@ impl Emulator { pub fn finish_sync(&mut self) -> Vec { self.generation = self.generation.wrapping_add(1); let queued_events = self.queued_events(); + let paint = self.paint_state(); self.parser.stop_sync(&mut self.term); + self.observe_paint_change(paint); self.take_effects(queued_events) } + fn observe_grid_change(&mut self) -> bool { + let changed = self.term.take_grid_changed(); + if changed { + self.search_generation = self.search_generation.wrapping_add(1); + } + changed + } + /// Highest allocated logical output line, independent of scrollback trimming. pub fn output_line_number(&self) -> u64 { self.term.output_line_number() @@ -460,18 +484,27 @@ impl Emulator { pub fn resize(&mut self, size: TermSize) { if size != self.size { self.generation = self.generation.wrapping_add(1); + self.paint_generation = self.paint_generation.wrapping_add(1); + if (size.cols, size.rows) != (self.size.cols, self.size.rows) { + self.history_layout = self.history_layout.wrapping_add(1); + } self.size = size; self.term.resize(size); + self.observe_grid_change(); } } - pub fn set_options(&mut self, options: EmulatorOptions) { + /// Returns whether the accepted options changed. + pub fn set_options(&mut self, options: EmulatorOptions) -> bool { if self.options == options { - return; + return false; } self.options = options; self.generation = self.generation.wrapping_add(1); + self.paint_generation = self.paint_generation.wrapping_add(1); self.term.set_options(options.to_config()); + self.observe_grid_change(); + true } /// Tells the emulator which colours the host draws with. @@ -479,42 +512,37 @@ impl Emulator { self.palette = palette; } - /// Begins a selection at a cell of the viewport, replacing any other. - pub fn start_selection(&mut self, kind: SelectionKind, at: CellPoint, side: Side) { - let kind = match kind { - SelectionKind::Cells => SelectionType::Simple, - SelectionKind::Words => SelectionType::Semantic, - SelectionKind::Lines => SelectionType::Lines, - }; - let point = self.grid_point(at); - self.term.selection = Some(Selection::new(kind, point, grid_side(side))); + /// Output activity stamp used to detect an idle session. + pub fn generation(&self) -> u64 { + self.generation + } + + /// Version of the searchable grid and match positions. + pub fn search_generation(&self) -> u64 { + self.search_generation } - /// Extends the selection to a cell of the viewport. - pub fn update_selection(&mut self, at: CellPoint, side: Side) { - let point = self.grid_point(at); - if let Some(selection) = &mut self.term.selection { - selection.update(point, grid_side(side)); - } + /// Remembers a search position on this emulator across retained-history scrolling. + pub fn search_anchor(&self, point: crate::SearchPoint) -> crate::SearchAnchor { + crate::SearchAnchor::new( + point, + self.history_layout, + self.term.grid().history_scroll(), + ) } - /// Selects retained history and the screen without touching search state. - pub fn select_all(&mut self) { + /// Maps a saved position to current coordinates. Evicted or reflowed history expires. + pub fn resolve_search_anchor(&self, anchor: crate::SearchAnchor) -> Option { let grid = self.term.grid(); - let mut selection = Selection::new( - SelectionType::Simple, - Point::new(grid.topmost_line(), Column(0)), - GridSide::Left, - ); - selection.update( - Point::new(grid.bottommost_line(), Column(grid.columns() - 1)), - GridSide::Right, - ); - self.term.selection = Some(selection); + anchor.resolve( + self.history_layout, + grid.history_scroll(), + grid.topmost_line().0, + ) } - pub fn generation(&self) -> u64 { - self.generation + pub(crate) fn search_history_epoch(&self) -> Option { + (!self.term.mode().contains(TermMode::ALT_SCREEN)).then_some(self.history_layout) } pub(crate) fn search_grid( @@ -539,7 +567,7 @@ impl Emulator { direction: crate::SearchDirection, anchor: Option, ) -> Result { - crate::SearchScan::new(self, query, options, direction, anchor) + crate::SearchScan::new(self, query, options, direction, anchor, None) } pub fn selection_start(&self) -> Option { @@ -566,7 +594,7 @@ impl Emulator { { return; } - self.search_match = Some((self.generation, result)); + self.search_match = Some((self.search_generation, result)); let row = result.start.line + self.term.grid().display_offset() as i32; if row < 0 || row >= i32::from(self.size.rows) { let offset = (-result.start.line).max(0) as usize; @@ -575,6 +603,18 @@ impl Emulator { } } + /// Whether the active selection can provide nonempty clipboard text. + pub fn has_selection_text(&self) -> bool { + self.term.selection_has_text() + } + + /// A query from the active selection, including one scalar for overflow detection. + pub fn selected_search_query(&self) -> Option { + self.term + .selection_text_prefix(crate::MAX_SEARCH_QUERY + 1) + .filter(|text| !text.is_empty()) + } + /// The selected text, if anything is selected. pub fn selection_text(&self) -> Option { self.term @@ -582,52 +622,6 @@ impl Emulator { .filter(|text| !text.is_empty()) } - fn grid_point(&self, at: CellPoint) -> Point { - let row = at.row.min(self.size.rows - 1); - let col = at.col.min(self.size.cols - 1); - viewport_to_point( - self.term.grid().display_offset(), - Point::new(usize::from(row), Column(usize::from(col))), - ) - } - - /// Maps a cell colour to the palette slot or the exact colour to draw. - fn resolve(&self, color: AnsiColor) -> Color { - match color { - AnsiColor::Spec(rgb) => Color::Rgb(from_ansi_rgb(rgb)), - AnsiColor::Indexed(index) => self.resolve_indexed(usize::from(index)), - AnsiColor::Named(named) => match named { - NamedColor::Background => self.resolve_indexed(NamedColor::Background as usize), - NamedColor::Foreground - | NamedColor::BrightForeground - | NamedColor::DimForeground - | NamedColor::Cursor => self.resolve_indexed(NamedColor::Foreground as usize), - NamedColor::DimBlack => Color::Ansi(0), - NamedColor::DimRed => Color::Ansi(1), - NamedColor::DimGreen => Color::Ansi(2), - NamedColor::DimYellow => Color::Ansi(3), - NamedColor::DimBlue => Color::Ansi(4), - NamedColor::DimMagenta => Color::Ansi(5), - NamedColor::DimCyan => Color::Ansi(6), - NamedColor::DimWhite => Color::Ansi(7), - ansi => self.resolve_indexed(ansi as usize), - }, - } - } - - fn resolve_indexed(&self, index: usize) -> Color { - // A program may have redefined the slot (`OSC 4`, `OSC 10`, `OSC 11`). - if let Some(rgb) = self.term.colors()[index] { - return Color::Rgb(from_ansi_rgb(rgb)); - } - match index { - 0..=15 => Color::Ansi(index as u8), - 16..=255 => Color::Rgb(indexed_color(index as u8)), - index if index == NamedColor::Background as usize => Color::Background, - _ => Color::Foreground, - } - } - /// The colour a program is told a slot has when it asks. fn reported_color(&self, index: usize) -> Option { if index >= COLOR_SLOTS { @@ -704,13 +698,6 @@ impl Emulator { } } -fn grid_side(side: Side) -> GridSide { - match side { - Side::Left => GridSide::Left, - Side::Right => GridSide::Right, - } -} - fn from_ansi_rgb(rgb: AnsiRgb) -> Rgb { Rgb::new(rgb.r, rgb.g, rgb.b) } @@ -752,6 +739,8 @@ fn indexed_color(index: u8) -> Rgb { #[cfg(test)] mod pointer_tests; +#[cfg(test)] +mod reflow_tests; mod snapshot; #[cfg(test)] mod tests; diff --git a/crates/vt/src/emulator/input.rs b/crates/vt/src/emulator/input.rs index ae3d1041..f22ecaf9 100644 --- a/crates/vt/src/emulator/input.rs +++ b/crates/vt/src/emulator/input.rs @@ -1,4 +1,7 @@ use super::*; +use alacritty_terminal::{ + index::Side as GridSide, selection::SelectionType, term::viewport_to_point, +}; impl Emulator { /// Moves the viewport through the scrollback, returning whether its display changed. @@ -44,6 +47,44 @@ impl Emulator { self.term.selection.is_some() } + /// Begins a selection at a cell of the viewport, replacing any other. + pub fn start_selection(&mut self, kind: SelectionKind, at: CellPoint, side: Side) { + let kind = match kind { + SelectionKind::Cells => SelectionType::Simple, + SelectionKind::Words => SelectionType::Semantic, + SelectionKind::Lines => SelectionType::Lines, + }; + let point = self.grid_point(at); + self.term.selection = Some(Selection::new(kind, point, grid_side(side))); + } + + /// Extends the selection to a cell of the viewport, returning whether + /// the endpoint changed in the grid's coordinates. + pub fn update_selection(&mut self, at: CellPoint, side: Side) -> bool { + let point = self.grid_point(at); + let Some(selection) = &mut self.term.selection else { + return false; + }; + let previous = selection.clone(); + selection.update(point, grid_side(side)); + *selection != previous + } + + /// Selects retained history and the screen without touching search state. + pub fn select_all(&mut self) { + let grid = self.term.grid(); + let mut selection = Selection::new( + SelectionType::Simple, + Point::new(grid.topmost_line(), Column(0)), + GridSide::Left, + ); + selection.update( + Point::new(grid.bottommost_line(), Column(grid.columns() - 1)), + GridSide::Right, + ); + self.term.selection = Some(selection); + } + pub fn clear_selection(&mut self) { self.term.selection = None; } @@ -57,6 +98,21 @@ impl Emulator { } changed } + fn grid_point(&self, at: CellPoint) -> Point { + let row = at.row.min(self.size.rows - 1); + let col = at.col.min(self.size.cols - 1); + viewport_to_point( + self.term.grid().display_offset(), + Point::new(usize::from(row), Column(usize::from(col))), + ) + } +} + +fn grid_side(side: Side) -> GridSide { + match side { + Side::Left => GridSide::Left, + Side::Right => GridSide::Right, + } } #[cfg(test)] diff --git a/crates/vt/src/emulator/reflow_tests.rs b/crates/vt/src/emulator/reflow_tests.rs new file mode 100644 index 00000000..dbd6de34 --- /dev/null +++ b/crates/vt/src/emulator/reflow_tests.rs @@ -0,0 +1,67 @@ +use super::*; + +const QUERY: crate::TextQuery = crate::TextQuery { + max_lines: 32, + max_bytes: 32 * 1024, + since_line: None, +}; + +#[test] +fn narrowing_full_scrollback_keeps_the_newest_logical_lines() { + let wide = TermSize::new(64, 4, 8, 16); + let mut emulator = Emulator::new( + wide, + EmulatorOptions { + scrollback_lines: 8, + ..EmulatorOptions::default() + }, + ); + for index in 0..24 { + // At 24 columns the wide character starts on the last column. + let line = format!("row-{index:02} qqqqqqqqqqqqqqqq界e\u{301} end\r\n"); + emulator.advance_at(line.as_bytes(), index * 100); + } + + let before = emulator.text(QUERY); + assert!(before.text.contains("row-16 ")); + let last = "row-23 qqqqqqqqqqqqqqqq界e\u{301} end"; + + emulator.resize(TermSize::new(24, 4, 16, 32)); + let narrowed = emulator.text(QUERY); + assert!(narrowed.text.lines().any(|line| line == last)); + assert!(!narrowed.text.contains("row-16 ")); + assert!(narrowed.first_line > before.first_line); + assert_eq!(narrowed.next_line, before.next_line); + + emulator.resize(wide); + let widened = emulator.text(QUERY); + assert!(widened.text.lines().any(|line| line == last)); + assert!(!widened.text.contains("row-16 ")); + assert_eq!(widened.next_line, before.next_line); +} + +#[test] +#[ignore = "full scrollback font-size performance fixture; run in isolation"] +fn measure_narrowing_a_full_scrollback_for_font_change() { + use std::io::Write as _; + use std::time::Instant; + + let lines = (0..9_000) + .map(|index| format!("{index:05} {} 界e\u{301}\r\n", "wrap test ".repeat(7))) + .collect::(); + for _ in 0..7 { + let mut emulator = Emulator::new(TermSize::new(119, 9, 8, 16), EmulatorOptions::default()); + emulator.advance(lines.as_bytes()); + let expected = emulator.text(QUERY); + let start = Instant::now(); + emulator.resize(TermSize::new(59, 4, 16, 32)); + let elapsed = start.elapsed(); + assert_eq!(emulator.text(QUERY), expected); + writeln!( + std::io::stdout().lock(), + "119 to 59 columns with 9,000 lines {:.3} ms", + elapsed.as_secs_f64() * 1_000., + ) + .unwrap(); + } +} diff --git a/crates/vt/src/emulator/snapshot.rs b/crates/vt/src/emulator/snapshot.rs index 1159520b..96e0a829 100644 --- a/crates/vt/src/emulator/snapshot.rs +++ b/crates/vt/src/emulator/snapshot.rs @@ -1,8 +1,98 @@ use super::*; +use alacritty_terminal::selection::SelectionRange; + +/// The parser can change these paint inputs without writing to the grid. +#[derive(PartialEq, Eq)] +pub(super) struct PaintState { + cursor: Option<(Point, CursorStyle)>, + selection: Option, + display_offset: usize, + palette_revision: u64, +} + +fn visible_cell(point: Point, display_offset: usize, size: TermSize) -> Option { + let row = point.line.0 + display_offset as i32; + let col = point.column.0; + ((0..i32::from(size.rows)).contains(&row) && col < usize::from(size.cols)).then_some( + CellPoint { + row: row as u16, + col: col as u16, + }, + ) +} impl Emulator { + pub(super) fn paint_state(&self) -> PaintState { + let mode = *self.term.mode(); + let grid = self.term.grid(); + let cursor = if mode.contains(TermMode::VI) { + Some(self.term.vi_mode_cursor.point) + } else { + mode.contains(TermMode::SHOW_CURSOR) + .then_some(grid.cursor.point) + }; + let display_offset = grid.display_offset(); + PaintState { + cursor: cursor + .filter(|&point| visible_cell(point, display_offset, self.size).is_some()) + .map(|point| (point, self.term.cursor_style())) + .filter(|(_, style)| style.shape != AnsiCursorShape::Hidden), + selection: self.term.selection.clone(), + display_offset, + palette_revision: self.term.palette_revision(), + } + } + + /// Version of the viewport inputs that can change during parsing, reflow or reset. + /// Host selection, scrolling and theme setters are tracked by the caller. + pub fn paint_generation(&self) -> u64 { + self.paint_generation + } + + pub(super) fn observe_paint_change(&mut self, before: PaintState) { + if self.observe_grid_change() || before != self.paint_state() { + self.paint_generation = self.paint_generation.wrapping_add(1); + } + } + + /// Maps a cell colour to the palette slot or the exact colour to draw. + fn resolve(&self, color: AnsiColor) -> Color { + match color { + AnsiColor::Spec(rgb) => Color::Rgb(from_ansi_rgb(rgb)), + AnsiColor::Indexed(index) => self.resolve_indexed(usize::from(index)), + AnsiColor::Named(named) => match named { + NamedColor::Background => self.resolve_indexed(NamedColor::Background as usize), + NamedColor::Foreground + | NamedColor::BrightForeground + | NamedColor::DimForeground + | NamedColor::Cursor => self.resolve_indexed(NamedColor::Foreground as usize), + NamedColor::DimBlack => Color::Ansi(0), + NamedColor::DimRed => Color::Ansi(1), + NamedColor::DimGreen => Color::Ansi(2), + NamedColor::DimYellow => Color::Ansi(3), + NamedColor::DimBlue => Color::Ansi(4), + NamedColor::DimMagenta => Color::Ansi(5), + NamedColor::DimCyan => Color::Ansi(6), + NamedColor::DimWhite => Color::Ansi(7), + ansi => self.resolve_indexed(ansi as usize), + }, + } + } + + fn resolve_indexed(&self, index: usize) -> Color { + // A program may have redefined the slot (`OSC 4`, `OSC 10`, `OSC 11`). + if let Some(rgb) = self.term.colors()[index] { + return Color::Rgb(from_ansi_rgb(rgb)); + } + match index { + 0..=15 => Color::Ansi(index as u8), + 16..=255 => Color::Rgb(indexed_color(index as u8)), + index if index == NamedColor::Background as usize => Color::Background, + _ => Color::Foreground, + } + } + /// Writes the current viewport into `frame`. - #[expect(clippy::too_many_lines, reason = "predates the limit")] pub fn snapshot(&self, frame: &mut Frame) { let content = self.term.renderable_content(); let cols = usize::from(self.size.cols); @@ -18,19 +108,28 @@ impl Emulator { && self.term.grid()[first_line - 1i32][Column(cols - 1)] .flags .contains(Flags::WRAPLINE); + let grid = self.term.grid(); frame.wraps.clear(); - frame.wraps.extend((0..rows).map(|row| { - self.term.grid()[Line(row as i32 - display_offset)][Column(cols - 1)] - .flags - .contains(Flags::WRAPLINE) - })); + frame.wraps.reserve(rows); + frame.occupied_rows.clear(); + frame.occupied_rows.reserve(rows); + for line in first_line.0..first_line.0 + rows as i32 { + let row = &grid[Line(line)]; + frame + .wraps + .push(row[Column(cols - 1)].flags.contains(Flags::WRAPLINE)); + frame.occupied_rows.push(row.occupied_end() != 0); + } frame.lines.clear(); frame.lines.resize(rows, None); if !frame.alt_screen { - let grid = self.term.grid(); for (row, metadata) in frame.lines.iter_mut().enumerate() { - let line = alacritty_terminal::index::Line(row as i32 - display_offset); - if let Some(mark) = grid[line][..].iter().find_map(|cell| cell.logical_line()) { + let line = first_line + row as i32; + let cells = &grid[line]; + if let Some(mark) = cells[..Column(cells.occupied_end())] + .iter() + .find_map(|cell| cell.logical_line()) + { let continuation = line > grid.topmost_line() && grid[line - 1i32][alacritty_terminal::index::Column(cols - 1)] .flags @@ -43,58 +142,8 @@ impl Emulator { } } } - frame.combining.clear(); - frame.cells.clear(); - frame.cells.resize(cols * rows, Cell::default()); - - for indexed in content.display_iter { - let row = indexed.point.line.0 + display_offset; - let col = indexed.point.column.0; - if row < 0 || row as usize >= rows || col >= cols { - continue; - } - let ix = row as usize * cols + col; - let cell = indexed.cell; - let flags = cell.flags; - - frame.cells[ix] = Cell { - ch: cell.c, - fg: self.resolve(cell.fg), - bg: self.resolve(cell.bg), - style: Style { - bold: flags.contains(Flags::BOLD), - italic: flags.contains(Flags::ITALIC), - dim: flags.contains(Flags::DIM), - underline: flags.intersects(Flags::ALL_UNDERLINES), - strikeout: flags.contains(Flags::STRIKEOUT), - inverse: flags.contains(Flags::INVERSE), - hidden: flags.contains(Flags::HIDDEN), - }, - wide: flags.contains(Flags::WIDE_CHAR), - spacer: flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER), - selected: content - .selection - .is_some_and(|selection| selection.contains(indexed.point)), - search_hit: self.search_match.is_some_and(|(generation, range)| { - if generation != self.generation { - return false; - } - let point = (indexed.point.line.0, col); - let end_cell = &self.term.grid() - [Point::new(Line(range.end.line), Column(usize::from(range.end.column)))]; - let end_col = usize::from(range.end.column) - + usize::from(end_cell.flags.contains(Flags::WIDE_CHAR)); - point >= (range.start.line, usize::from(range.start.column)) - && point <= (range.end.line, end_col) - }), - }; - if let Some(combining) = cell.zerowidth().filter(|chars| !chars.is_empty()) { - frame.combining.push((ix, combining.iter().collect())); - } - } + self.snapshot_cells(first_line, content.selection, frame); - let cursor_row = content.cursor.point.line.0 + display_offset; - let cursor_col = content.cursor.point.column.0; let shape = match content.cursor.shape { AnsiCursorShape::Hidden => None, AnsiCursorShape::Block => Some(CursorShape::Block), @@ -102,14 +151,301 @@ impl Emulator { AnsiCursorShape::Underline => Some(CursorShape::Underline), AnsiCursorShape::HollowBlock => Some(CursorShape::Hollow), }; - frame.cursor = shape - .filter(|_| cursor_row >= 0 && (cursor_row as usize) < rows && cursor_col < cols) - .map(|shape| Cursor { - row: cursor_row as u16, - col: cursor_col as u16, + frame.cursor = shape.and_then(|shape| { + let CellPoint { row, col } = + visible_cell(content.cursor.point, content.display_offset, self.size)?; + Some(Cursor { + row, + col, shape, blinking: self.term.cursor_style().blinking, - wide: frame.cells[cursor_row as usize * cols + cursor_col].wide, - }); + wide: frame.cells[usize::from(row) * cols + usize::from(col)].wide, + }) + }); + } + + fn snapshot_cells(&self, top: Line, selection: Option, frame: &mut Frame) { + frame.combining.clear(); + frame.cells.clear(); + let cols = usize::from(frame.size.cols); + frame.cells.reserve(cols * usize::from(frame.size.rows)); + + let search = self.search_match.and_then(|(generation, range)| { + if generation != self.search_generation { + return None; + } + let end = Point::new(Line(range.end.line), Column(usize::from(range.end.column))); + let end_wide = self.term.grid()[end].flags.contains(Flags::WIDE_CHAR); + Some(( + (range.start.line, usize::from(range.start.column)), + (range.end.line, end.column.0 + usize::from(end_wide)), + )) + }); + + let grid = self.term.grid(); + let blank = Cell { + fg: self.resolve_indexed(NamedColor::Foreground as usize), + bg: self.resolve_indexed(NamedColor::Background as usize), + ..Cell::default() + }; + // Project each visible row directly into the reused row-major buffer. + for index in top.0..top.0 + i32::from(frame.size.rows) { + let line = Line(index); + let row = &grid[line]; + let selection = + selection.filter(|range| range.start.line <= line && line <= range.end.line); + let search = search.filter(|(start, end)| start.0 <= index && index <= end.0); + let end = if selection.is_none() && search.is_none() { + row.occupied_end() + } else { + cols + }; + for (col, cell) in row[..Column(end)].iter().enumerate() { + let flags = cell.flags; + + frame.cells.push(Cell { + ch: cell.c, + fg: self.resolve(cell.fg), + bg: self.resolve(cell.bg), + style: Style { + bold: flags.contains(Flags::BOLD), + italic: flags.contains(Flags::ITALIC), + dim: flags.contains(Flags::DIM), + underline: flags.intersects(Flags::ALL_UNDERLINES), + strikeout: flags.contains(Flags::STRIKEOUT), + inverse: flags.contains(Flags::INVERSE), + hidden: flags.contains(Flags::HIDDEN), + }, + wide: flags.contains(Flags::WIDE_CHAR), + spacer: flags + .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER), + selected: selection + .is_some_and(|selection| selection.contains(Point::new(line, Column(col)))), + search_hit: search.is_some_and(|(start, end)| { + let point = (line.0, col); + start <= point && point <= end + }), + }); + if let Some(combining) = cell.zerowidth().filter(|chars| !chars.is_empty()) { + frame + .combining + .push((frame.cells.len() - 1, combining.iter().collect())); + } + } + // Reset cells retain their background. A subsequent width increase + // can append cells with the default background to that same row. + if end < cols { + frame + .cells + .extend( + row[Column(end)..Column(cols)] + .iter() + .map(|cell| match cell.bg { + AnsiColor::Named(NamedColor::Background) => blank, + bg => Cell { + bg: self.resolve(bg), + ..blank + }, + }), + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn emulator() -> Emulator { + Emulator::new(TermSize::new(20, 4, 8, 16), EmulatorOptions::default()) + } + + #[test] + fn a_partially_scrolled_view_repaints_when_the_cursor_crosses_its_edge() { + let mut emulator = emulator(); + emulator.advance(b"first\r\nsecond\r\nthird\r\nfourth\r\nfifth"); + assert!(emulator.scroll(Scroll::Lines(1))); + assert!(frame(&emulator).cursor.is_none()); + + let paint = emulator.paint_generation(); + emulator.advance(b"\x1b[4;2H"); + assert_eq!(emulator.paint_generation(), paint); + emulator.advance(b"\x1b[3;2H"); + assert_ne!(emulator.paint_generation(), paint); + let cursor = frame(&emulator).cursor.unwrap(); + assert_eq!((cursor.row, cursor.col), (3, 1)); + + let paint = emulator.paint_generation(); + emulator.advance(b"\x1b[4;3H"); + assert_ne!(emulator.paint_generation(), paint); + assert!(frame(&emulator).cursor.is_none()); + } + + fn frame(emulator: &Emulator) -> Frame { + let mut frame = Frame::default(); + emulator.snapshot(&mut frame); + frame + } + + #[test] + fn snapshot_empty_rows_keep_background_and_occupied_rows_keep_text_marks() { + let mut emulator = emulator(); + let mut frame = Frame::default(); + emulator.snapshot(&mut frame); + assert_eq!(frame.occupied_rows, [false; 4]); + assert!(frame.cursor.is_some()); + + emulator.advance(b"\x1b[44m\x1b[2J\x1b[0m"); + emulator.snapshot(&mut frame); + assert!(frame.row(2).iter().all(|cell| cell.bg == Color::Ansi(4))); + + emulator.advance( + "\x1b[1;20Hx\x1b[2;1H\x1b[4m \x1b[0m\x1b[3;1H \u{301}\x1b[4;1H\x1b[9m \x1b[0m" + .as_bytes(), + ); + emulator.snapshot(&mut frame); + assert_eq!(frame.occupied_rows, [true; 4]); + assert_eq!(frame.row(0)[19].ch, 'x'); + assert!(frame.row(1)[0].style.underline); + assert_eq!(frame.combining, [(40, "\u{301}".to_owned())]); + assert!(frame.row(3)[0].style.strikeout); + + emulator.advance(b"\x1b[?1049h"); + emulator.snapshot(&mut frame); + assert!(frame.alt_screen); + assert_eq!(frame.occupied_rows, [false; 4]); + emulator.advance(b"\x1b[?1049l"); + emulator.snapshot(&mut frame); + assert!(!frame.alt_screen); + assert_eq!(frame.occupied_rows, [true; 4]); + } + + #[test] + fn snapshot_reports_occupied_rows_in_viewport_order_after_scroll_and_reflow() { + let mut emulator = emulator(); + emulator.advance(b"first\r\n\r\nsecond\r\n\r\nthird"); + assert!(emulator.scroll(Scroll::Lines(1))); + let mut frame = Frame::default(); + emulator.snapshot(&mut frame); + assert_eq!(frame.row_text(0), "first"); + assert_eq!(frame.row_text(2), "second"); + assert!(frame.occupied_rows[0] && frame.occupied_rows[2]); + + emulator.resize(TermSize::new(4, 6, 8, 16)); + emulator.snapshot(&mut frame); + assert_eq!(frame.occupied_rows.len(), 6); + for row in 0..frame.size.rows { + if !frame.row_text(row).is_empty() { + assert!(frame.occupied_rows[usize::from(row)]); + } + } + } + + #[test] + fn snapshot_keeps_resolved_colors_in_a_reset_row_after_growing() { + let mut emulator = emulator(); + emulator.advance(b"\x1b[44m\x1b[2J\x1b[0m\x1b]10;#ab12cd\x07\x1b]11;#fe9021\x07"); + emulator.resize(TermSize::new(30, 4, 8, 16)); + let frame = frame(&emulator); + + assert!( + frame.row(2)[..20] + .iter() + .all(|cell| cell.bg == Color::Ansi(4)) + ); + assert!( + frame.row(2)[20..] + .iter() + .all(|cell| cell.bg == Color::Rgb(Rgb::new(0xfe, 0x90, 0x21))) + ); + assert!( + frame + .row(2) + .iter() + .all(|cell| cell.ch == ' ' && cell.fg == Color::Rgb(Rgb::new(0xab, 0x12, 0xcd))) + ); + } + + #[test] + fn snapshot_keeps_selection_in_blank_suffixes_and_search_on_wide_cells() { + use crate::{SearchDirection, SearchProgress}; + + let mut emulator = emulator(); + emulator.advance("🌙\r\n\r\na".as_bytes()); + emulator.start_selection( + SelectionKind::Cells, + CellPoint { row: 0, col: 7 }, + Side::Left, + ); + assert!(emulator.update_selection(CellPoint { row: 2, col: 9 }, Side::Right)); + let mut scan = emulator.search("🌙", SearchDirection::Next, None).unwrap(); + let SearchProgress::Complete(result) = scan.step(&emulator, 1000) else { + panic!("a visible wide glyph should fit the scan budget"); + }; + emulator.show_search_match(result.active.unwrap()); + + let frame = frame(&emulator); + assert!(frame.row(0)[0].wide && frame.row(0)[0].search_hit); + assert!(frame.row(0)[1].spacer && frame.row(0)[1].search_hit); + assert!(frame.row(0)[2..].iter().all(|cell| !cell.search_hit)); + assert!(!frame.row(0)[6].selected && frame.row(0)[7].selected); + assert!( + frame + .row(1) + .iter() + .all(|cell| cell.ch == ' ' && cell.selected) + ); + assert!(frame.row(2)[9].selected && !frame.row(2)[10].selected); + } + + #[test] + fn paint_generation_tracks_cursor_and_palette_while_queries_only_count_as_activity() { + let mut emulator = emulator(); + emulator.advance(b"color"); + let paint = emulator.paint_generation(); + let activity = emulator.generation(); + let snapshot = frame(&emulator); + emulator.advance(b"\x1b[6n\x1b]10;?\x07\x1b[?1004h"); + assert_eq!(emulator.paint_generation(), paint); + assert!(emulator.generation() > activity); + assert_eq!(frame(&emulator).cursor, snapshot.cursor); + + emulator.advance(b"\x1b[H"); + assert_ne!(emulator.paint_generation(), paint); + assert_eq!(frame(&emulator).cursor.unwrap().col, 0); + let paint = emulator.paint_generation(); + emulator.advance(b"\x1b]10;#ff0000\x07"); + assert_ne!(emulator.paint_generation(), paint); + assert_eq!( + frame(&emulator).cells[0].fg, + Color::Rgb(Rgb::new(255, 0, 0)) + ); + let paint = emulator.paint_generation(); + emulator.advance(b"\x1b]10;#ff0000\x07"); + assert_eq!(emulator.paint_generation(), paint); + emulator.advance(b"\x1b]110\x07"); + assert_ne!(emulator.paint_generation(), paint); + assert_eq!(frame(&emulator).cells[0].fg, Color::Foreground); + } + + #[test] + fn held_updates_invalidate_paint_only_when_applied() { + let mut emulator = emulator(); + emulator.advance(b"before"); + for end in [Some(b"\x1b[?2026l".as_slice()), None] { + let paint = emulator.paint_generation(); + emulator.advance(b"\x1b[?2026h\x1b[H\x1b[?25l"); + assert_eq!(emulator.paint_generation(), paint); + assert!(frame(&emulator).cursor.is_some()); + if let Some(bytes) = end { + emulator.advance(bytes); + } else { + emulator.finish_sync(); + } + assert_ne!(emulator.paint_generation(), paint); + assert!(frame(&emulator).cursor.is_none()); + emulator.advance(b"\x1b[?25h"); + } } } diff --git a/crates/vt/src/emulator/tests.rs b/crates/vt/src/emulator/tests.rs index 9a74c13c..b2d28edd 100644 --- a/crates/vt/src/emulator/tests.rs +++ b/crates/vt/src/emulator/tests.rs @@ -14,6 +14,21 @@ mod screen { frame } + #[test] + fn identical_selection_coordinates_are_unchanged_until_the_viewport_scrolls() { + let mut terminal = emulator(16, 2); + terminal.advance(b"first\r\nsecond\r\nthird\r\nfourth"); + let start = CellPoint { row: 1, col: 0 }; + let end = CellPoint { row: 0, col: 2 }; + terminal.start_selection(SelectionKind::Cells, start, Side::Left); + assert!(terminal.update_selection(end, Side::Right)); + let selected = terminal.selection_text().unwrap(); + assert!(!terminal.update_selection(end, Side::Right)); + assert!(terminal.scroll(Scroll::Lines(1))); + assert!(terminal.update_selection(end, Side::Right)); + assert_ne!(terminal.selection_text().unwrap(), selected); + } + #[test] fn unchanged_options_preserve_generation_and_changes_update_the_cursor() { let mut terminal = emulator(20, 2); @@ -264,6 +279,7 @@ mod screen { Side::Left, ); emulator.update_selection(CellPoint { row: 0, col: 3 }, Side::Right); + assert!(emulator.has_selection_text()); assert_eq!(emulator.selection_text().as_deref(), Some("lph")); let selected: Vec = frame(&emulator).row(0)[..5] .iter() @@ -276,6 +292,7 @@ mod screen { CellPoint { row: 0, col: 7 }, Side::Left, ); + assert!(emulator.has_selection_text()); assert_eq!(emulator.selection_text().as_deref(), Some("beta")); emulator.start_selection( @@ -283,12 +300,29 @@ mod screen { CellPoint { row: 1, col: 2 }, Side::Left, ); + assert!(emulator.has_selection_text()); assert_eq!(emulator.selection_text().as_deref(), Some("gamma\n")); emulator.clear_selection(); + assert!(!emulator.has_selection_text()); assert_eq!(emulator.selection_text(), None); } + #[test] + fn selection_availability_distinguishes_empty_text_from_a_selected_line_break() { + let mut terminal = emulator(4, 3); + let blank = CellPoint { row: 0, col: 0 }; + terminal.start_selection(SelectionKind::Cells, blank, Side::Left); + terminal.update_selection(blank, Side::Right); + assert!(terminal.selection_start().is_some()); + assert!(!terminal.has_selection_text()); + assert_eq!(terminal.selection_text(), None); + + terminal.start_selection(SelectionKind::Lines, blank, Side::Left); + assert!(terminal.has_selection_text()); + assert_eq!(terminal.selection_text().as_deref(), Some("\n")); + } + #[test] fn resizing_reflows_and_clamps_to_a_minimum() { let mut emulator = emulator(10, 3); @@ -301,6 +335,129 @@ mod screen { assert_eq!(frame(&emulator).row_text(0), "0123456789abc"); } + #[test] + fn column_reflow_preserves_wide_combining_and_blank_lines_in_scrollback() { + let mut terminal = emulator(9, 3); + terminal.advance("abcde界e\u{301}fg\r\n\r\n123界4567\r\nlast".as_bytes()); + let query = crate::TextQuery { + max_lines: 8, + max_bytes: 1_024, + since_line: None, + }; + let before = terminal.text(query); + assert_eq!(before.text, "abcde界e\u{301}fg\n\n123界4567\nlast"); + for cols in [6, 7, 5, 12, 9] { + terminal.resize(TermSize::new(cols, 3, 8, 16)); + assert_eq!(terminal.text(query), before, "width {cols}"); + } + } + + #[test] + fn a_full_history_keeps_the_newest_rows_through_resize_and_clear() { + use std::fmt::Write as _; + + let options = EmulatorOptions { + scrollback_lines: 100, + ..Default::default() + }; + let mut terminal = Emulator::new(TermSize::new(260, 48, 8, 16), options); + let mut output = String::new(); + for row in 0..180 { + writeln!(output, "row {row:03} 界e\u{301}\r").unwrap(); + } + terminal.advance(output.as_bytes()); + let query = crate::TextQuery { + max_lines: 200, + max_bytes: 8 * 1024, + since_line: None, + }; + let before = terminal.text(query); + assert_eq!(before.text.lines().count(), 147); + assert!(before.text.starts_with("row 033")); + assert!(before.text.ends_with("row 179 界e\u{301}")); + assert!(terminal.scroll(Scroll::Top)); + assert_eq!(frame(&terminal).row_text(0), "row 033 界e"); + + terminal.resize(TermSize::new(32, 48, 8, 16)); + assert_eq!(terminal.text(query), before); + terminal.advance(b"\x1b[3J"); + let after = terminal.text(query); + assert_eq!(after.text.lines().count(), 47); + assert!(after.text.starts_with("row 133")); + assert!(after.text.ends_with("row 179 界e\u{301}")); + } + + #[test] + #[ignore = "first scrollback allocation performance fixture; run in release"] + fn measure_first_scrollback_growth() { + use std::io::Write as _; + + let fill = "initial row\r\n".repeat(47); + for columns in [120, 260] { + for scrollback_lines in [0, 100, 10_000] { + let mut elapsed = Vec::with_capacity(31); + for _ in 0..31 { + let mut terminal = Emulator::new( + TermSize::new(columns, 48, 8, 16), + EmulatorOptions { + scrollback_lines, + ..Default::default() + }, + ); + terminal.advance(fill.as_bytes()); + let start = std::time::Instant::now(); + std::hint::black_box(terminal.advance(b"new row\r\n")); + elapsed.push(start.elapsed().as_nanos()); + assert_eq!(frame(&terminal).row_text(46), "new row"); + assert_eq!(terminal.scroll(Scroll::Top), scrollback_lines > 0); + } + elapsed.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{columns} columns, {scrollback_lines} lines: median {} ns, p95 {} ns", + elapsed[elapsed.len() / 2], + elapsed[elapsed.len() * 95 / 100], + ) + .unwrap(); + } + } + } + + #[test] + #[ignore = "terminal reflow performance fixture; run alone in both builds"] + fn measure_column_reflow_with_scrollback() { + use std::io::Write as _; + + let mut terminal = emulator(247, 32); + for index in 0..10_000 { + let line = format!( + "row {index:05} {}界e\u{301}\r\n", + "wrapped content ".repeat(22) + ); + terminal.advance(line.as_bytes()); + } + let query = crate::TextQuery { + max_lines: 32, + max_bytes: 32 * 1024, + since_line: None, + }; + let before = terminal.text(query); + assert!(before.text.contains("row 09999")); + for _ in 0..3 { + for cols in (248..=263).chain((247..263).rev()) { + let start = std::time::Instant::now(); + terminal.resize(TermSize::new(cols, 32, 8, 16)); + writeln!( + std::io::stdout().lock(), + "{cols} {:.3}", + start.elapsed().as_secs_f64() * 1_000.0 + ) + .unwrap(); + } + assert_eq!(terminal.text(query), before); + } + } + #[test] fn default_cursor_follows_the_options() { let mut emulator = Emulator::new( @@ -417,6 +574,59 @@ mod line_metadata_tests { assert_eq!(frame(&terminal).lines[0].unwrap().number, 2); assert_eq!(frame(&terminal).lines[0].unwrap().timestamp_ms, 3000); } + #[test] + fn a_sparse_row_keeps_its_lineage_when_widened_and_extended() { + let mut terminal = emulator(260, 5); + terminal.advance_at(b"\x1b[121Gfirst", 1000); + let lineage = frame(&terminal).lines[0].unwrap(); + terminal.resize(TermSize::new(480, 5, 0, 0)); + terminal.advance_at(b"-tail\r\n\r\nnew", 2000); + + let frame = frame(&terminal); + assert!(frame.row_text(0).ends_with("first-tail")); + assert_eq!(frame.lines[0], Some(lineage)); + assert_eq!(lineage.timestamp_ms, 1000); + assert_eq!(frame.lines[1].unwrap().number, lineage.number + 1); + assert_eq!(frame.lines[2].unwrap().number, lineage.number + 2); + assert_eq!(frame.lines[2].unwrap().timestamp_ms, 2000); + } + + #[test] + #[ignore = "manual release-mode terminal output performance measurement"] + fn measure_line_metadata_during_continuous_output() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let row = "shipping 192.0.2.42 progress [ready]"; + let packet = format!("{row}\r\n").repeat(50); + for width in [120, 260, 480] { + let mut samples = [0; 31]; + for sample in &mut samples { + let mut terminal = Emulator::new( + TermSize::new(width, 48, 8, 16), + EmulatorOptions { + scrollback_lines: 512, + ..Default::default() + }, + ); + let start = Instant::now(); + for _ in 0..120 { + black_box(terminal.advance_at(black_box(packet.as_bytes()), 1000)); + } + *sample = start.elapsed().as_micros(); + assert_eq!(terminal.output_line_number(), 6000); + assert_eq!(frame(&terminal).row_text(46), row); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{width} columns, 6000 lines: p50={} us, p95={} us", + samples[15], + samples[29] + ) + .unwrap(); + } + } + #[test] fn trimming_history_never_renumbers_remaining_lines() { let options = EmulatorOptions { diff --git a/crates/vt/src/lib.rs b/crates/vt/src/lib.rs index 428eff50..07603560 100644 --- a/crates/vt/src/lib.rs +++ b/crates/vt/src/lib.rs @@ -32,9 +32,9 @@ mod text; mod text_codec; pub use search::{ - MAX_NAVIGATION_MATCHES, MAX_REGEX_LINE_BYTES, MAX_SEARCH_QUERY, RegexWork, SearchBatch, - SearchDirection, SearchError, SearchMatch, SearchOptions, SearchPoint, SearchProgress, - SearchResult, SearchScan, + CompletedSearch, MAX_NAVIGATION_MATCHES, MAX_REGEX_LINE_BYTES, MAX_SEARCH_QUERY, RegexWork, + SearchAnchor, SearchBatch, SearchDirection, SearchError, SearchMatch, SearchNavigation, + SearchOptions, SearchPoint, SearchProgress, SearchResult, SearchScan, }; pub use emulator::{ @@ -49,5 +49,5 @@ pub use mouse::{MouseButton, MouseEvent, MouseEventKind, encode_mouse}; pub use paste::{encode_focus, encode_paste}; pub use text::{TextQuery, TextTail}; -pub use shell_integration::ShellIntegration; +pub use shell_integration::{ShellInput, ShellIntegration}; pub use text_codec::TextCodec; diff --git a/crates/vt/src/osc_guard.rs b/crates/vt/src/osc_guard.rs index b218ca18..d7f409f3 100644 --- a/crates/vt/src/osc_guard.rs +++ b/crates/vt/src/osc_guard.rs @@ -22,7 +22,7 @@ impl OscGuard { State::Pass => { // ESC itself reaches VTE. The OSC introducer `]` stays // withheld until the bounded sequence can safely dispatch. - if let Some(index) = bytes.iter().position(|byte| *byte == 0x1b) { + if let Some(index) = memchr::memchr(0x1b, bytes) { feed(&bytes[..=index]); bytes = &bytes[index + 1..]; self.state = State::Escape; diff --git a/crates/vt/src/paste.rs b/crates/vt/src/paste.rs index 42673362..955f77a3 100644 --- a/crates/vt/src/paste.rs +++ b/crates/vt/src/paste.rs @@ -4,19 +4,35 @@ use crate::Modes; /// The bytes to send when the user pastes `text`. pub fn encode_paste(text: &str, modes: Modes) -> Vec { - if modes.bracketed_paste { + encode_paste_with_enter(text, modes, false) +} + +pub(crate) fn encode_paste_with_enter(text: &str, modes: Modes, execute: bool) -> Vec { + let mut bytes = if modes.bracketed_paste { // Brackets tell the program this is a paste, not typing, so it will // not run it line by line. Escape characters are dropped: a clipboard // holding the closing bracket could otherwise end the paste early and // have the rest executed. - let mut bytes = b"\x1b[200~".to_vec(); - bytes.extend(text.bytes().filter(|byte| *byte != 0x1b)); + let mut bytes = if memchr::memchr(0x1b, text.as_bytes()).is_none() { + let mut bytes = Vec::with_capacity(text.len() + 12 + usize::from(execute)); + bytes.extend_from_slice(b"\x1b[200~"); + bytes.extend_from_slice(text.as_bytes()); + bytes + } else { + let mut bytes = b"\x1b[200~".to_vec(); + bytes.extend(text.bytes().filter(|byte| *byte != 0x1b)); + bytes + }; bytes.extend_from_slice(b"\x1b[201~"); bytes } else { // A terminal's Enter is a carriage return. text.replace("\r\n", "\r").replace('\n', "\r").into_bytes() + }; + if execute { + bytes.push(b'\r'); } + bytes } /// The bytes to send when the terminal gains or loses focus, if the program diff --git a/crates/vt/src/search.rs b/crates/vt/src/search.rs index 7bf4d887..3df53d1a 100644 --- a/crates/vt/src/search.rs +++ b/crates/vt/src/search.rs @@ -6,7 +6,6 @@ use alacritty_terminal::{ term::cell::Flags, }; use std::{ - collections::{HashMap, VecDeque}, sync::{ Arc, atomic::{AtomicBool, Ordering}, @@ -14,12 +13,25 @@ use std::{ time::{Duration, Instant}, }; +mod literal; +mod navigation; +mod regex_line; +mod retained; +use literal::Literal; +pub use navigation::SearchNavigation; +use navigation::Summary; +use regex_line::LogicalLine; +pub use retained::CompletedSearch; +use retained::HistoryPrefix; + /// Maximum query length in Unicode scalar values. pub const MAX_SEARCH_QUERY: usize = 2_048; /// Regexes operate on complete logical lines, joining soft wraps only. pub const MAX_REGEX_LINE_BYTES: usize = 64 * 1024; -/// Matches retained for instant navigation of an unchanged completed search. -pub const MAX_NAVIGATION_MATCHES: usize = 4_096; +/// Maximum entries in the 128 KiB navigation span, excluding the saved endpoints. +pub const MAX_NAVIGATION_MATCHES: usize = 8_192; +// Live cells keep at most 64 combining scalars. A hard break sorts after them. +const HARD_BREAK_PART: u16 = u16::MAX; const MAX_REGEX_BATCH_BYTES: usize = 64 * 1024; const MAX_REGEX_COMPILED_BYTES: usize = 256 * 1024; const MAX_REGEX_WORK_TIME: Duration = Duration::from_millis(250); @@ -65,7 +77,33 @@ impl Default for SearchOptions { pub struct SearchPoint { pub line: i32, pub column: u16, - pub(crate) part: usize, + pub(crate) part: u16, +} +/// Search origin remembered on the emulator that produced it. +#[derive(Clone, Copy, Debug)] +pub struct SearchAnchor { + point: SearchPoint, + history: Option<(u64, u64)>, +} +impl SearchAnchor { + pub(crate) fn new(point: SearchPoint, layout: u64, scroll: u64) -> Self { + Self { + point, + history: (point.line < 0).then_some((layout, scroll)), + } + } + + pub(crate) fn resolve(self, layout: u64, scroll: u64, top: i32) -> Option { + let Some((saved_layout, saved_scroll)) = self.history else { + return Some(self.point); + }; + if layout != saved_layout { + return None; + } + let rows = i32::try_from(scroll.wrapping_sub(saved_scroll)).ok()?; + let line = self.point.line.checked_sub(rows)?; + (line >= top).then_some(SearchPoint { line, ..self.point }) + } } /// Inclusive cell range; search never replaces the user selection. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -73,6 +111,18 @@ pub struct SearchMatch { pub start: SearchPoint, pub end: SearchPoint, } +impl SearchMatch { + fn translated(self, shift: i32) -> Self { + let translate = |point: SearchPoint| SearchPoint { + line: point.line - shift, + ..point + }; + Self { + start: translate(self.start), + end: translate(self.end), + } + } +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SearchDirection { Next, @@ -95,88 +145,6 @@ pub enum SearchProgress { Work(RegexWork), } #[derive(Debug)] -struct Summary { - first: Option, - last: Option, - best: Option<(SearchMatch, u64)>, - count: u64, - matches: Option>, -} -impl Default for Summary { - fn default() -> Self { - Self { - first: None, - last: None, - best: None, - count: 0, - matches: Some(Vec::new()), - } - } -} -impl Summary { - fn record( - &mut self, - found: SearchMatch, - direction: SearchDirection, - anchor: Option, - ) { - self.count = self.count.saturating_add(1); - if let Some(matches) = &mut self.matches { - if matches.len() == MAX_NAVIGATION_MATCHES { - self.matches = None; - } else { - matches.push(found); - } - } - self.first.get_or_insert(found); - self.last = Some(found); - let eligible = anchor.is_none_or(|a| match direction { - SearchDirection::Next => found.start > a, - SearchDirection::Previous => found.start < a, - SearchDirection::Stay => found.start >= a, - }); - if eligible && (self.best.is_none() || direction == SearchDirection::Previous) { - self.best = Some((found, self.count)); - } - } - fn append(&mut self, batch: Self, direction: SearchDirection) { - match (&mut self.matches, batch.matches) { - (Some(current), Some(next)) if current.len() + next.len() <= MAX_NAVIGATION_MATCHES => { - current.extend(next) - } - _ => self.matches = None, - } - if let Some((found, ordinal)) = batch.best - && (self.best.is_none() || direction == SearchDirection::Previous) - { - self.best = Some((found, self.count.saturating_add(ordinal))); - } - if self.first.is_none() { - self.first = batch.first; - } - if batch.last.is_some() { - self.last = batch.last; - } - self.count = self.count.saturating_add(batch.count); - } - fn finish(&self, direction: SearchDirection) -> SearchResult { - let chosen = self.best.or_else(|| match direction { - SearchDirection::Previous => self.last.map(|m| (m, self.count)), - _ => self.first.map(|m| (m, 1)), - }); - SearchResult { - active: chosen.map(|(m, _)| m), - ordinal: chosen.map_or(0, |(_, n)| n), - count: self.count, - } - } -} -#[derive(Debug, Default, PartialEq, Eq)] -struct LogicalLine { - text: String, - points: Vec<(usize, SearchPoint)>, -} -#[derive(Debug)] pub struct RegexWork { regex: Arc, lines: Vec, @@ -184,6 +152,7 @@ pub struct RegexWork { direction: SearchDirection, anchor: Option, cancelled: Arc, + summary: Summary, } impl PartialEq for RegexWork { fn eq(&self, other: &Self) -> bool { @@ -192,12 +161,14 @@ impl PartialEq for RegexWork { && self.generation == other.generation && self.direction == other.direction && self.anchor == other.anchor + && self.summary == other.summary } } impl Eq for RegexWork {} #[derive(Debug)] pub struct SearchBatch { generation: u64, + cancelled: Arc, summary: Summary, } impl RegexWork { @@ -211,47 +182,34 @@ impl RegexWork { Ok(()) } /// No terminal state is accessed here. Only a bounded navigation list may be retained. - pub fn run(self) -> Result { + pub fn run(mut self) -> Result { let started = Instant::now(); - let mut summary = Summary::default(); + let mut summary = std::mem::take(&mut self.summary); + // The check after each line also guards entry to the next line. + self.check_budget(started)?; for line in &self.lines { - self.check_budget(started)?; - for found in self.regex.find_iter(&line.text) { + for found in self.regex.find_iter(line.text()) { self.check_budget(started)?; - if found.is_empty() { - continue; - } - let start = line - .points - .partition_point(|(byte, _)| *byte < found.start()); - let end = line.points.partition_point(|(byte, _)| *byte < found.end()); - if let (Some((_, start)), Some((_, end))) = ( - line.points.get(start), - end.checked_sub(1).and_then(|end| line.points.get(end)), - ) { - summary.record( - SearchMatch { - start: *start, - end: *end, - }, - self.direction, - self.anchor, - ); + if let Some(found) = line.range(found.range()) { + summary.record(found, self.direction, self.anchor); } } self.check_budget(started)?; } Ok(SearchBatch { generation: self.generation, + cancelled: self.cancelled, summary, }) } } +#[derive(Clone, Copy)] struct Cursor { + shift: i32, line: i32, end_line: i32, column: usize, - part: usize, + part: u16, trim: Option, end_column: usize, wrapped: bool, @@ -259,11 +217,13 @@ struct Cursor { enum Tick { Inspection, Scalar(char, SearchPoint), + HardBreak(SearchPoint), End, } impl Cursor { fn new(e: &Emulator) -> Self { Self { + shift: 0, line: e.search_grid().topmost_line().0, end_line: e.search_grid().bottommost_line().0, column: 0, @@ -278,16 +238,21 @@ impl Cursor { return Tick::End; } let grid = e.search_grid(); + let row = &grid[Line(self.line - self.shift)]; if self.trim.is_none() { - self.wrapped = grid[Line(self.line)][Column(grid.columns() - 1)] + self.wrapped = row[Column(grid.columns() - 1)] .flags .contains(Flags::WRAPLINE); - self.trim = Some(grid.columns()); + self.trim = Some(if self.wrapped { + grid.columns() + } else { + row.occupied_end() + }); } if self.column == 0 && self.part == 0 { let trim = self.trim.unwrap(); if !self.wrapped && trim > 0 { - let cell = &grid[Line(self.line)][Column(trim - 1)]; + let cell = &row[Column(trim - 1)]; if cell.c == ' ' && cell.zerowidth().is_none_or(|s| s.is_empty()) { self.trim = Some(trim - 1); return Tick::Inspection; @@ -299,7 +264,7 @@ impl Cursor { let point = SearchPoint { line: self.line, column: self.end_column.min(grid.columns() - 1) as u16, - part: usize::MAX, + part: HARD_BREAK_PART, }; let wrapped = self.wrapped; self.line += 1; @@ -309,10 +274,10 @@ impl Cursor { return if wrapped { Tick::Inspection } else { - Tick::Scalar('\n', point) + Tick::HardBreak(point) }; } - let cell = &grid[Line(self.line)][Column(self.column)]; + let cell = &row[Column(self.column)]; if cell .flags .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) @@ -321,57 +286,27 @@ impl Cursor { self.part = 0; return Tick::Inspection; } + let marks = cell.zerowidth().unwrap_or_default(); + debug_assert!(marks.len() < usize::from(HARD_BREAK_PART)); let scalar = if self.part == 0 { Some(cell.c) } else { - cell.zerowidth().and_then(|s| s.get(self.part - 1)).copied() + marks.get(usize::from(self.part) - 1).copied() }; - if let Some(scalar) = scalar { - let point = SearchPoint { - line: self.line, - column: self.column as u16, - part: self.part, - }; - self.part += 1; - Tick::Scalar(scalar, point) - } else { + let point = SearchPoint { + line: self.line, + column: self.column as u16, + part: self.part, + }; + if usize::from(self.part) >= marks.len() { self.column += 1; self.part = 0; - Tick::Inspection + } else { + self.part += 1; } + scalar.map_or(Tick::Inspection, |scalar| Tick::Scalar(scalar, point)) } } -#[derive(Default)] -struct Fold { - cache: HashMap, -} -impl Fold { - fn scalar(&mut self, c: char) -> char { - if let Some(folded) = self.cache.get(&c) { - return *folded; - } - let mut class = - regex_syntax::hir::ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new(c, c)]); - class - .try_case_fold_simple() - .expect("Unicode case tables are enabled"); - let folded = class.iter().next().map_or(c, |range| range.start()); - if self.cache.len() >= 4096 { - self.cache.clear(); - } - self.cache.insert(c, folded); - folded - } -} -struct Literal { - query: Vec, - prefix: Vec, - ring: VecDeque<(SearchPoint, bool, bool)>, - matched: usize, - fold: Fold, - previous_word: bool, - pending: Option<(SearchMatch, bool)>, -} struct RegexState { regex: Arc, line: LogicalLine, @@ -379,6 +314,15 @@ struct RegexState { bytes: usize, waiting: bool, } +impl RegexState { + fn finish_line(&mut self) { + // Regex results with empty ranges are never selectable. + if !self.line.text().is_empty() { + self.bytes += self.line.text().len(); + self.lines.push(std::mem::take(&mut self.line)); + } + } +} enum Matcher { Literal(Literal), Regex(RegexState), @@ -388,10 +332,12 @@ pub struct SearchScan { generation: u64, options: SearchOptions, cursor: Cursor, + prefix: HistoryPrefix, matcher: Matcher, anchor: Option, direction: SearchDirection, summary: Summary, + target: Option, complete: Option, error: Option, cancelled: Arc, @@ -402,27 +348,155 @@ impl Drop for SearchScan { } } impl SearchScan { - /// Moves out the bounded navigation list only after the complete result was produced. - /// An oversized match set retains no list and callers can fall back to a fresh scan. - pub fn take_navigation_matches(&mut self) -> Option> { + /// Restarts an invalidated scan with the same compiled query and direction. + /// The caller must have awaited or discarded any outstanding regex work. + pub fn restart(&mut self, e: &Emulator, anchor: Option) { + let generation = e.search_generation(); + if self.generation == generation { + return; + } + self.generation = generation; + self.anchor = anchor; + self.cursor = Cursor::new(e); + self.prefix = HistoryPrefix::start(self.cursor.line, false); + self.summary = Summary::default(); + self.target = None; + self.complete = None; + self.error = None; + self.reset_matcher(); + } + + fn reset_matcher(&mut self) { + match &mut self.matcher { + Matcher::Literal(state) => state.reset(), + Matcher::Regex(state) => { + state.line = LogicalLine::default(); + state.lines.clear(); + state.bytes = 0; + if std::mem::take(&mut state.waiting) { + self.cancelled.store(true, Ordering::Relaxed); + self.cancelled = Arc::new(AtomicBool::new(false)); + } + } + } + } + + /// Starts a refresh from a retained primary-history prefix for the same query. + /// Pass the selected position resolved in the current grid, if still available. + /// Returns false when the surviving prefix or selection requires a new scan. + pub fn refresh_retained(&mut self, e: &Emulator, anchor: Option) -> bool { + if self.error.is_some() || matches!(&self.matcher, Matcher::Regex(state) if state.waiting) { + return false; + } + let HistoryPrefix::Saved(prefix) = &mut self.prefix else { + return false; + }; + let Some((cursor, selected)) = prefix.resume(e, &mut self.summary.navigation, anchor) + else { + return false; + }; + self.summary.best = selected; + self.cursor = cursor; + self.generation = e.search_generation(); + self.direction = SearchDirection::Stay; + self.anchor = anchor.map(|point| SearchPoint { + line: point.line + cursor.shift, + ..point + }); + self.complete = None; + self.reset_matcher(); + true + } + + fn checkpoint(&mut self, e: &Emulator) -> Option { + if !self.prefix.can_checkpoint(self.cursor) || self.cursor.wrapped { + return None; + } + match &self.matcher { + Matcher::Literal(state) if !state.at_boundary() => return None, + Matcher::Regex(state) if !state.line.text().is_empty() => return None, + _ => (), + } + if let Some(work) = self.work() { + return Some(work); + } + let without_hard_breaks = match &self.matcher { + Matcher::Literal(state) => !state.crosses_hard_breaks(), + Matcher::Regex(_) => true, + }; + self.prefix.checkpoint( + e, + self.cursor, + self.summary.navigation.checkpoint(), + without_hard_breaks, + ); + None + } + + /// A complete result belongs to the current grid version. + pub fn is_complete_for(&self, e: &Emulator) -> bool { + self.complete.is_some() && self.generation == e.search_generation() + } + + /// Looks up a cached ordinal in the current completed grid version. + pub fn navigation_match(&self, e: &Emulator, ordinal: u64) -> Option { + if !self.is_complete_for(e) { + return None; + } + self.summary + .navigation + .get(ordinal) + .map(|found| found.translated(self.cursor.shift)) + } + + /// Preserves navigation after completion and retains the matcher only with a history checkpoint. + pub fn into_completed(self) -> Option { + CompletedSearch::capture(self) + } + + /// Moves out the retained span and endpoints of a finished search with matches. + pub fn take_navigation(&mut self) -> Option { self.complete?; - self.summary.matches.take() + self.prefix = HistoryPrefix::Unavailable; + (self.summary.navigation.count() > 0).then(|| { + let mut navigation = std::mem::take(&mut self.summary.navigation); + navigation.translate(self.cursor.shift); + navigation + }) } + pub fn provisional(&self) -> Option { - if self.direction == SearchDirection::Previous { + if self.direction == SearchDirection::Previous || self.target.is_some() { None } else { - self.summary.best.map(|(found, _)| found) + self.summary + .best + .map(|(found, _)| found.translated(self.cursor.shift)) } } + /// Rebuilds the navigation span around a known one-based match ordinal. + /// Use an ordinal from the current search and grid version. The anchor applies + /// if the grid changes before completion. + pub fn navigate( + e: &Emulator, + query: &str, + options: SearchOptions, + direction: SearchDirection, + anchor: Option, + ordinal: u64, + ) -> Result { + Self::new(e, query, options, direction, anchor, Some(ordinal)) + } + pub(crate) fn new( e: &Emulator, query: &str, options: SearchOptions, direction: SearchDirection, anchor: Option, + target: Option, ) -> Result { - let mut chars: Vec<_> = query.chars().take(MAX_SEARCH_QUERY + 1).collect(); + let chars: Vec<_> = query.chars().take(MAX_SEARCH_QUERY + 1).collect(); if chars.len() > MAX_SEARCH_QUERY { return Err(SearchError::QueryTooLong { max: MAX_SEARCH_QUERY, @@ -451,41 +525,22 @@ impl SearchScan { waiting: false, }) } else { - let mut fold = Fold::default(); - if !options.case_sensitive { - for c in &mut chars { - *c = fold.scalar(*c); - } - } - let mut prefix = vec![0; chars.len()]; - for i in 1..chars.len() { - let mut j = prefix[i - 1]; - while j > 0 && chars[i] != chars[j] { - j = prefix[j - 1]; - } - if chars[i] == chars[j] { - j += 1; - } - prefix[i] = j; - } - Matcher::Literal(Literal { - query: chars, - prefix, - ring: VecDeque::new(), - matched: 0, - fold, - previous_word: false, - pending: None, - }) + Matcher::Literal(Literal::new(chars, options.case_sensitive)) }; + let cursor = Cursor::new(e); Ok(Self { - generation: e.generation(), + generation: e.search_generation(), options, - cursor: Cursor::new(e), + cursor, + prefix: HistoryPrefix::start(cursor.line, target.is_some()), matcher, anchor, direction, - summary: Summary::default(), + summary: Summary { + navigation: SearchNavigation::around(target.unwrap_or(1)), + best: None, + }, + target, complete: None, error: None, cancelled: Arc::new(AtomicBool::new(false)), @@ -507,6 +562,7 @@ impl SearchScan { direction: self.direction, anchor: self.anchor, cancelled: self.cancelled.clone(), + summary: self.summary.take_for_work(), })) } pub fn accept_work( @@ -514,18 +570,36 @@ impl SearchScan { e: &Emulator, result: Result, ) -> SearchProgress { - if e.generation() != self.generation { + if e.search_generation() != self.generation { + if self.prefix.has_saved() + && let Matcher::Regex(state) = &mut self.matcher + && state.waiting + && let Ok(batch) = result + && batch.generation == self.generation + && Arc::ptr_eq(&batch.cancelled, &self.cancelled) + { + self.summary = batch.summary; + state.waiting = false; + } return SearchProgress::Invalidated; } let Matcher::Regex(state) = &mut self.matcher else { return SearchProgress::Failed(SearchError::UnexpectedRegexWork); }; + if let Ok(batch) = &result { + if batch.generation != self.generation { + return SearchProgress::Invalidated; + } + if !Arc::ptr_eq(&batch.cancelled, &self.cancelled) { + return SearchProgress::Failed(SearchError::UnexpectedRegexWork); + } + } + if !state.waiting { + return SearchProgress::Failed(SearchError::UnexpectedRegexWork); + } state.waiting = false; match result { - Ok(batch) if batch.generation == self.generation => { - self.summary.append(batch.summary, self.direction) - } - Ok(_) => return SearchProgress::Invalidated, + Ok(batch) => self.summary = batch.summary, Err(error) => { self.error = Some(error.clone()); return SearchProgress::Failed(error); @@ -534,13 +608,8 @@ impl SearchScan { SearchProgress::Searching } /// Visits at most budget grid inspections or Unicode scalars on this thread. - #[expect( - clippy::cognitive_complexity, - clippy::too_many_lines, - reason = "predates the limit" - )] pub fn step(&mut self, e: &Emulator, budget: usize) -> SearchProgress { - if e.generation() != self.generation { + if e.search_generation() != self.generation { return SearchProgress::Invalidated; } if let Some(error) = &self.error { @@ -553,83 +622,64 @@ impl SearchScan { return SearchProgress::Searching; } for _ in 0..budget { - if matches!(&self.matcher,Matcher::Regex(state) if !state.lines.is_empty() && state.bytes+state.line.text.len()>=MAX_REGEX_BATCH_BYTES) + if self.cursor.line == self.cursor.shift + && self.cursor.trim.is_none() + && let Some(work) = self.checkpoint(e) + { + return work; + } + if matches!(&self.matcher,Matcher::Regex(state) if !state.lines.is_empty() && state.bytes+state.line.text().len()>=MAX_REGEX_BATCH_BYTES) && let Some(work) = self.work() { return work; } - match self.cursor.tick(e) { - Tick::Inspection => {} + let (scalar, point) = match self.cursor.tick(e) { + Tick::Inspection => continue, Tick::End => { - if let Matcher::Regex(state) = &mut self.matcher - && !state.line.text.is_empty() - { - state.lines.push(std::mem::take(&mut state.line)); + if let Matcher::Regex(state) = &mut self.matcher { + state.finish_line(); } if let Some(work) = self.work() { return work; } if let Matcher::Literal(state) = &mut self.matcher - && let Some((found, true)) = state.pending.take() + && let Some(found) = state.finish() { self.summary.record(found, self.direction, self.anchor); } - let result = self.summary.finish(self.direction); + let mut result = self.summary.finish(self.direction, self.target); + result.active = result + .active + .map(|found| found.translated(self.cursor.shift)); self.complete = Some(result); return SearchProgress::Complete(result); } - Tick::Scalar(scalar, point) => match &mut self.matcher { - Matcher::Literal(state) => { - let word = regex_syntax::is_word_character(scalar); - if let Some((found, end_word)) = state.pending.take() - && end_word != word - { - self.summary.record(found, self.direction, self.anchor); - } - state.ring.push_back((point, state.previous_word, word)); - state.previous_word = word; - if state.ring.len() > state.query.len() { - state.ring.pop_front(); - } - let scalar = if self.options.case_sensitive { - scalar - } else { - state.fold.scalar(scalar) - }; - while state.matched > 0 && scalar != state.query[state.matched] { - state.matched = state.prefix[state.matched - 1]; - } - if scalar == state.query[state.matched] { - state.matched += 1; - } - if state.matched == state.query.len() { - let (start, previous_word, start_word) = *state.ring.front().unwrap(); - let found = SearchMatch { start, end: point }; - if !self.options.whole_word { - self.summary.record(found, self.direction, self.anchor); - } else if previous_word != start_word { - state.pending = Some((found, word)); - } - state.matched = state.prefix[state.matched - 1]; - } + Tick::HardBreak(point) => { + self.prefix.hard_break(point.line); + ('\n', point) + } + Tick::Scalar(scalar, point) => (scalar, point), + }; + match &mut self.matcher { + Matcher::Literal(state) => { + if let Some(found) = state.advance(scalar, point, self.options) { + self.summary.record(found, self.direction, self.anchor); } - Matcher::Regex(state) => { - if scalar == '\n' && point.part == usize::MAX { - state.bytes += state.line.text.len(); - state.lines.push(std::mem::take(&mut state.line)); - } else { - if state.line.text.len() + scalar.len_utf8() > MAX_REGEX_LINE_BYTES { - let error = SearchError::LogicalLineTooLong { - max: MAX_REGEX_LINE_BYTES, - }; - self.error = Some(error.clone()); - return SearchProgress::Failed(error); - } - state.line.points.push((state.line.text.len(), point)); - state.line.text.push(scalar); + } + Matcher::Regex(state) => { + if point.part == HARD_BREAK_PART { + state.finish_line(); + } else { + if state.line.text().len() + scalar.len_utf8() > MAX_REGEX_LINE_BYTES { + let error = SearchError::LogicalLineTooLong { + max: MAX_REGEX_LINE_BYTES, + }; + self.error = Some(error.clone()); + return SearchProgress::Failed(error); } + state.line.push(scalar, point); } - }, + } } } self.work().unwrap_or(SearchProgress::Searching) diff --git a/crates/vt/src/search/literal.rs b/crates/vt/src/search/literal.rs new file mode 100644 index 00000000..8d37a869 --- /dev/null +++ b/crates/vt/src/search/literal.rs @@ -0,0 +1,139 @@ +//! Streaming literal matching across grid scalars and line boundaries. +use super::{SearchMatch, SearchOptions, SearchPoint}; +use std::collections::{HashMap, VecDeque}; + +pub(super) struct Literal { + query: Vec, + prefix: Vec, + positions: VecDeque<(SearchPoint, bool, bool)>, + matched: usize, + fold: Fold, + previous_word: bool, + pending: Option<(SearchMatch, bool)>, +} + +impl Literal { + pub(super) fn new(mut query: Vec, case_sensitive: bool) -> Self { + let mut fold = Fold::default(); + if !case_sensitive { + for scalar in &mut query { + *scalar = fold.scalar(*scalar); + } + } + let mut prefix = vec![0; query.len()]; + for i in 1..query.len() { + let mut j = prefix[i - 1]; + while j > 0 && query[i] != query[j] { + j = prefix[j - 1]; + } + if query[i] == query[j] { + j += 1; + } + prefix[i] = j; + } + Self { + query, + prefix, + positions: VecDeque::new(), + matched: 0, + fold, + previous_word: false, + pending: None, + } + } + + pub(super) fn reset(&mut self) { + self.positions.clear(); + self.matched = 0; + self.previous_word = false; + self.pending = None; + } + + pub(super) fn crosses_hard_breaks(&self) -> bool { + self.query.contains(&'\n') + } + + pub(super) fn at_boundary(&self) -> bool { + self.matched == 0 && self.pending.is_none() + } + + pub(super) fn finish(&mut self) -> Option { + self.pending + .take() + .and_then(|(found, word)| word.then_some(found)) + } + + pub(super) fn advance( + &mut self, + scalar: char, + point: SearchPoint, + options: SearchOptions, + ) -> Option { + let word = options.whole_word && regex_syntax::is_word_character(scalar); + let confirmed = self + .pending + .take() + .and_then(|(found, end_word)| (end_word != word).then_some(found)); + let previous_word = std::mem::replace(&mut self.previous_word, word); + let scalar = if options.case_sensitive { + scalar + } else { + self.fold.scalar(scalar) + }; + while self.matched > 0 && scalar != self.query[self.matched] { + self.matched = self.prefix[self.matched - 1]; + } + if scalar != self.query[self.matched] { + return confirmed; + } + self.matched += 1; + + // Every scalar in a complete match extended a prefix when it arrived. + // Saving only those positions still puts the entire match in the deque. + if self.positions.len() == self.query.len() { + self.positions.pop_front(); + } + self.positions.push_back((point, previous_word, word)); + if self.matched != self.query.len() { + return confirmed; + } + self.matched = self.prefix[self.matched - 1]; + let (start, preceding, first_word) = *self.positions.front().unwrap(); + let found = SearchMatch { start, end: point }; + if !options.whole_word { + return Some(found); + } + if preceding != first_word { + self.pending = Some((found, word)); + } + confirmed + } +} + +#[derive(Default)] +struct Fold { + cache: HashMap, +} + +impl Fold { + fn scalar(&mut self, c: char) -> char { + // The least scalar in an ASCII letter's simple fold class is its uppercase form. + if c.is_ascii() { + return c.to_ascii_uppercase(); + } + if let Some(folded) = self.cache.get(&c) { + return *folded; + } + let mut class = + regex_syntax::hir::ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new(c, c)]); + class + .try_case_fold_simple() + .expect("Unicode case tables are enabled"); + let folded = class.iter().next().map_or(c, |range| range.start()); + if self.cache.len() >= 4096 { + self.cache.clear(); + } + self.cache.insert(c, folded); + folded + } +} diff --git a/crates/vt/src/search/navigation.rs b/crates/vt/src/search/navigation.rs new file mode 100644 index 00000000..6c003bc2 --- /dev/null +++ b/crates/vt/src/search/navigation.rs @@ -0,0 +1,185 @@ +use std::collections::VecDeque; + +use super::{MAX_NAVIGATION_MATCHES, SearchDirection, SearchMatch, SearchPoint, SearchResult}; + +/// A bounded span of a completed search, with its first and last matches for wraparound. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct SearchNavigation { + skipped: u64, + matches: VecDeque, + first: Option, + last: Option, + count: u64, +} + +#[derive(Clone, Copy)] +pub(super) struct NavigationCheckpoint { + len: usize, + count: u64, + last: Option, +} + +impl SearchNavigation { + pub(super) fn checkpoint(&self) -> NavigationCheckpoint { + NavigationCheckpoint { + len: self.matches.len(), + count: self.count, + last: self.last, + } + } + + /// Rewinds the mutable tail and drops the matches before the surviving history. + /// A sparse navigation window may be insufficient to prove either cutoff. + pub(super) fn resume_prefix( + &mut self, + checkpoint: NavigationCheckpoint, + top: i32, + anchor: Option, + ) -> Option> { + if self.skipped != 0 { + return None; + } + let removed = self + .matches + .partition_point(|found| found.start.line < top) + .min(checkpoint.len); + let remaining = checkpoint.count.checked_sub(removed as u64)?; + // A nonempty suffix needs a cached match on the surviving side of the cut. + if remaining != 0 && removed == checkpoint.len { + return None; + } + let first = (remaining != 0).then(|| self.matches[removed]); + let selected = match anchor { + None => first.map(|found| (found, 1)), + Some(anchor) => self.select_in_prefix(checkpoint, removed, anchor)?, + }; + self.matches.truncate(checkpoint.len); + self.matches.drain(..removed); + self.count = remaining; + self.first = first; + self.last = checkpoint.last.filter(|_| remaining != 0); + Some(selected) + } + + fn select_in_prefix( + &self, + checkpoint: NavigationCheckpoint, + removed: usize, + anchor: SearchPoint, + ) -> Option> { + let Some(last) = checkpoint.last.filter(|found| found.start >= anchor) else { + return Some(None); + }; + let index = self + .matches + .partition_point(|found| found.start < anchor) + .max(removed); + if index < checkpoint.len { + return Some(Some((self.matches[index], (index - removed) as u64 + 1))); + } + // The middle of a large prefix may have no cached coordinates. + (last.start == anchor).then_some(Some((last, checkpoint.count - removed as u64))) + } + + pub(super) fn translate(&mut self, shift: i32) { + if shift != 0 { + self.first = self.first.map(|found| found.translated(shift)); + self.last = self.last.map(|found| found.translated(shift)); + for found in &mut self.matches { + *found = found.translated(shift); + } + } + } + + pub(super) fn around(ordinal: u64) -> Self { + Self { + skipped: ordinal.saturating_sub(MAX_NAVIGATION_MATCHES as u64 / 2 + 1), + ..Self::default() + } + } + + pub(super) fn record(&mut self, found: SearchMatch) -> u64 { + let index = self.count; + self.count = index.saturating_add(1); + self.first.get_or_insert(found); + self.last = Some(found); + if index.checked_sub(self.skipped) == Some(self.matches.len() as u64) + && self.matches.len() < MAX_NAVIGATION_MATCHES + { + self.matches.push_back(found); + } + self.count + } + + pub(super) fn take_for_work(&mut self) -> Self { + Self { + matches: std::mem::take(&mut self.matches), + ..*self + } + } + + pub(super) fn count(&self) -> u64 { + self.count + } + + /// Looks up a one-based ordinal. A miss can still be within the exact match count. + pub fn get(&self, ordinal: u64) -> Option { + if ordinal == 1 { + return self.first; + } + if ordinal == self.count { + return self.last; + } + let index = ordinal.checked_sub(1)?.checked_sub(self.skipped)?; + self.matches.get(usize::try_from(index).ok()?).copied() + } +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub(super) struct Summary { + pub(super) best: Option<(SearchMatch, u64)>, + pub(super) navigation: SearchNavigation, +} +impl Summary { + pub(super) fn record( + &mut self, + found: SearchMatch, + direction: SearchDirection, + anchor: Option, + ) { + let ordinal = self.navigation.record(found); + let eligible = anchor.is_none_or(|a| match direction { + SearchDirection::Next => found.start > a, + SearchDirection::Previous => found.start < a, + SearchDirection::Stay => found.start >= a, + }); + if eligible && (self.best.is_none() || direction == SearchDirection::Previous) { + self.best = Some((found, ordinal)); + } + } + + pub(super) fn take_for_work(&mut self) -> Self { + Self { + best: self.best, + navigation: self.navigation.take_for_work(), + } + } + + pub(super) fn finish(&self, direction: SearchDirection, target: Option) -> SearchResult { + let count = self.navigation.count(); + let endpoint = if direction == SearchDirection::Previous { + count + } else { + 1 + }; + let chosen = target + .and_then(|ordinal| self.navigation.get(ordinal).map(|found| (found, ordinal))) + .or(self.best) + .or_else(|| self.navigation.get(endpoint).map(|found| (found, endpoint))); + SearchResult { + active: chosen.map(|(m, _)| m), + ordinal: chosen.map_or(0, |(_, n)| n), + count, + } + } +} diff --git a/crates/vt/src/search/regex_line.rs b/crates/vt/src/search/regex_line.rs new file mode 100644 index 00000000..ca85560d --- /dev/null +++ b/crates/vt/src/search/regex_line.rs @@ -0,0 +1,57 @@ +use super::{SearchMatch, SearchPoint}; +use std::ops::Range; + +/// One logical line and the starts of runs where byte offsets track grid columns. +#[derive(Debug, Default, PartialEq, Eq)] +pub(super) struct LogicalLine { + text: String, + origin: Option, + runs: Vec<(usize, SearchPoint)>, +} + +impl LogicalLine { + pub(super) fn text(&self) -> &str { + &self.text + } + + pub(super) fn push(&mut self, scalar: char, point: SearchPoint) { + let byte = self.text.len(); + // A run may cross a multibyte scalar only if its next scalar still has + // the same byte-to-column offset. Combining positions need their own point. + let Some(first) = self.origin else { + self.origin = Some(point); + self.text.push(scalar); + return; + }; + let (start, origin) = self.runs.last().copied().unwrap_or((0, first)); + let extends = origin.part == 0 + && point.part == 0 + && origin.line == point.line + && usize::from(origin.column) + (byte - start) == usize::from(point.column); + if !extends { + self.runs.push((byte, point)); + } + self.text.push(scalar); + } + + pub(super) fn range(&self, bytes: Range) -> Option { + if bytes.is_empty() { + return None; + } + let last = self.text.floor_char_boundary(bytes.end - 1); + Some(SearchMatch { + start: self.point_at(bytes.start)?, + end: self.point_at(last)?, + }) + } + + fn point_at(&self, byte: usize) -> Option { + let after = self.runs.partition_point(|&(start, _)| start <= byte); + let (start, mut point) = match after.checked_sub(1) { + Some(index) => self.runs[index], + None => (0, self.origin?), + }; + point.column = u16::try_from(usize::from(point.column) + (byte - start)).ok()?; + Some(point) + } +} diff --git a/crates/vt/src/search/retained.rs b/crates/vt/src/search/retained.rs new file mode 100644 index 00000000..6c58cbd3 --- /dev/null +++ b/crates/vt/src/search/retained.rs @@ -0,0 +1,230 @@ +//! The completed primary-history prefix and its position in later grids. +use super::{ + Cursor, SearchMatch, SearchNavigation, SearchPoint, SearchScan, + navigation::NavigationCheckpoint, +}; +use crate::Emulator; +use alacritty_terminal::grid::Dimensions as _; + +// Track a bounded leading slice of the old history. A longer eviction can +// establish a fresh checkpoint with a complete scan. +const BOUNDARY_WORDS: usize = 16; +const BITS_PER_WORD: usize = u64::BITS as usize; + +pub(super) enum HistoryPrefix { + Unavailable, + Scanning(HardCuts), + Saved(RetainedPrefix), +} + +impl HistoryPrefix { + pub(super) fn start(top: i32, navigating: bool) -> Self { + if top < 0 && !navigating { + Self::Scanning(HardCuts::new(top)) + } else { + Self::Unavailable + } + } + + pub(super) fn hard_break(&mut self, line: i32) { + if let Self::Scanning(cuts) = self { + cuts.record(line); + } + } + + pub(super) fn can_checkpoint(&self, cursor: Cursor) -> bool { + match self { + Self::Unavailable => false, + Self::Scanning(_) => true, + Self::Saved(prefix) => prefix.cursor.line < cursor.line, + } + } + + pub(super) fn checkpoint( + &mut self, + emulator: &Emulator, + cursor: Cursor, + navigation: NavigationCheckpoint, + independent_lines: bool, + ) { + if let Self::Saved(prefix) = self { + // Its positions and eviction cuts still use the original scroll origin. + prefix.cursor = cursor; + prefix.navigation = navigation; + } else if let Self::Scanning(cuts) = std::mem::replace(self, Self::Unavailable) + && let Some(prefix) = + RetainedPrefix::capture(emulator, cursor, navigation, cuts, independent_lines) + { + *self = Self::Saved(prefix); + } + } + + pub(super) fn has_saved(&self) -> bool { + matches!(self, Self::Saved(_)) + } +} + +pub(super) struct HardCuts { + top: i32, + words: [u64; BOUNDARY_WORDS], +} + +impl HardCuts { + fn new(top: i32) -> Self { + Self { + top, + words: [0; BOUNDARY_WORDS], + } + } + + fn record(&mut self, line: i32) { + if !(self.top..0).contains(&line) { + return; + } + let offset = (i64::from(line) - i64::from(self.top)) as usize; + if let Some(word) = self.words.get_mut(offset / BITS_PER_WORD) { + *word |= 1 << (offset % BITS_PER_WORD); + } + } + + fn accepts(&self, top: i32) -> bool { + if top == self.top { + return true; + } + // Boundary bit n describes the end of row n, immediately before the cut. + let offset = i64::from(top) - i64::from(self.top) - 1; + let Ok(offset) = usize::try_from(offset) else { + return false; + }; + self.words + .get(offset / BITS_PER_WORD) + .is_some_and(|word| word & (1 << (offset % BITS_PER_WORD)) != 0) + } +} + +pub(super) struct RetainedPrefix { + cursor: Cursor, + origin: HistoryOrigin, + navigation: NavigationCheckpoint, + cuts: HardCuts, +} + +struct HistoryOrigin { + layout: u64, + scroll: u64, +} + +impl RetainedPrefix { + fn capture( + emulator: &Emulator, + cursor: Cursor, + navigation: NavigationCheckpoint, + cuts: HardCuts, + independent_lines: bool, + ) -> Option { + let grid = emulator.search_grid(); + Some(Self { + cursor, + origin: HistoryOrigin { + layout: emulator.search_history_epoch()?, + scroll: grid.history_scroll(), + }, + navigation, + cuts: if independent_lines { + cuts + } else { + HardCuts::new(cuts.top) + }, + }) + } + + pub(super) fn resume( + &mut self, + emulator: &Emulator, + navigation: &mut SearchNavigation, + mut anchor: Option, + ) -> Option<(Cursor, Option<(SearchMatch, u64)>)> { + if Some(self.origin.layout) != emulator.search_history_epoch() { + return None; + } + let grid = emulator.search_grid(); + let shift = i32::try_from(grid.history_scroll().wrapping_sub(self.origin.scroll)).ok()?; + let top = grid.topmost_line().0.checked_add(shift)?; + let end_line = grid.bottommost_line().0.checked_add(shift)?; + if end_line == i32::MAX || top >= self.cursor.line || !self.cuts.accepts(top) { + return None; + } + if let Some(point) = &mut anchor { + point.line = point.line.checked_add(shift)?; + } + let selected = navigation.resume_prefix(self.navigation, top, anchor)?; + self.navigation = navigation.checkpoint(); + Some(( + Cursor { + end_line, + shift, + ..self.cursor + }, + selected, + )) + } +} + +/// A completed navigation span and, when available, the scan that can refresh it. +pub struct CompletedSearch(Completion); + +enum Completion { + Navigation { + generation: u64, + matches: SearchNavigation, + }, + Retained(Box), +} + +impl CompletedSearch { + pub(super) fn capture(mut scan: SearchScan) -> Option { + scan.complete?; + Some(Self(if scan.prefix.has_saved() { + Completion::Retained(Box::new(scan)) + } else { + Completion::Navigation { + generation: scan.generation, + matches: scan.take_navigation()?, + } + })) + } + + /// Whether the completed search covers this version of its original emulator. + pub fn is_complete_for(&self, emulator: &Emulator) -> bool { + match &self.0 { + Completion::Navigation { generation, .. } => { + *generation == emulator.search_generation() + } + Completion::Retained(scan) => scan.is_complete_for(emulator), + } + } + + /// Looks up a cached ordinal in the current grid version. + pub fn navigation_match(&self, emulator: &Emulator, ordinal: u64) -> Option { + match &self.0 { + Completion::Navigation { + generation, + matches, + } if *generation == emulator.search_generation() => matches.get(ordinal), + Completion::Navigation { .. } => None, + Completion::Retained(scan) => scan.navigation_match(emulator, ordinal), + } + } + + /// Restarts a completed search from its retained primary history, when usable. + pub fn into_refresh( + self, + emulator: &Emulator, + anchor: Option, + ) -> Option { + let Completion::Retained(mut scan) = self.0 else { + return None; + }; + scan.refresh_retained(emulator, anchor).then_some(*scan) + } +} diff --git a/crates/vt/src/search/tests.rs b/crates/vt/src/search/tests.rs index 95369379..a449961e 100644 --- a/crates/vt/src/search/tests.rs +++ b/crates/vt/src/search/tests.rs @@ -21,6 +21,10 @@ fn finish_options( anchor: Option, ) -> Result { let mut scan = e.search_with_options(query, options, direction, anchor)?; + finish_scan(e, &mut scan) +} + +fn finish_scan(e: &Emulator, scan: &mut SearchScan) -> Result { loop { match scan.step(e, 4096) { SearchProgress::Complete(result) => return Ok(result), @@ -35,54 +39,149 @@ fn finish_options( } #[test] -fn completed_search_retains_only_a_bounded_navigation_list() { - let mut e = Emulator::new(TermSize::new(80, 3, 0, 0), EmulatorOptions::default()); - e.advance(b"target target"); - let mut scan = e.search("target", SearchDirection::Next, None).unwrap(); - assert!(scan.take_navigation_matches().is_none()); - while !matches!(scan.step(&e, 4096), SearchProgress::Complete(_)) {} - let matches = scan.take_navigation_matches().unwrap(); - assert_eq!(matches.len(), 2); - assert!(matches[0].start < matches[1].start); - e.advance(&b" target".repeat(MAX_NAVIGATION_MATCHES + 1)); - let mut scan = e.search("target", SearchDirection::Next, None).unwrap(); - while !matches!(scan.step(&e, 4096), SearchProgress::Complete(_)) {} - assert!(scan.take_navigation_matches().is_none()); +fn history_anchor_tracks_grid_rotation_and_expires_when_history_is_lost() { + let size = TermSize::new(40, 4, 0, 0); + let options = EmulatorOptions { + scrollback_lines: 6, + ..Default::default() + }; + let mut e = Emulator::new(size, options); + e.advance(b"find this\r\n\r\n\r\n\r\n"); + let point = finish(&e, "this", SearchDirection::Next, None) + .active + .unwrap() + .start; + assert_eq!((point.line, point.column), (-1, 5)); + let anchor = e.search_anchor(point); + e.scroll(crate::Scroll::Top); + + // A top-origin scroll region moves history, even with fixed rows below it. + e.advance(b"\x1b[1;3r\x1b[2S"); + let moved = e.resolve_search_anchor(anchor).unwrap(); + assert_eq!((moved.line, moved.column), (-3, 5)); + let found = finish(&e, "this", SearchDirection::Stay, Some(moved)); + assert_eq!(found.active.unwrap().start, moved); + + e.advance(b"\x1b[?1049h"); + assert_eq!(e.resolve_search_anchor(anchor), None); + e.advance(b"\x1b[?1049l"); + assert_eq!(e.resolve_search_anchor(anchor), Some(moved)); + + e.advance(b"\x1b[3S"); + assert_eq!(e.resolve_search_anchor(anchor).unwrap().line, -6); + e.advance(b"\x1b[1S"); + assert_eq!(e.resolve_search_anchor(anchor), None); + e.advance(b"another\r\n\r\n\r\n\r\n"); + let recent = finish(&e, "another", SearchDirection::Next, None) + .active + .unwrap() + .start; + assert!(recent.line < 0); + let saved_recent = e.search_anchor(recent); + e.advance(b"\x1b[3J\x1b[2S"); + assert_eq!(e.resolve_search_anchor(saved_recent), None); } #[test] -fn unicode_case_folding_keeps_overlap_and_cell_positions() { - let mut e = Emulator::new(TermSize::new(80, 3, 0, 0), EmulatorOptions::default()); - e.advance("Кот кОт КОТ Σσς KkK aAa".as_bytes()); - let options = SearchOptions { - case_sensitive: false, - ..Default::default() - }; - assert_eq!( - finish_options(&e, "кот", options, SearchDirection::Next, None) - .unwrap() - .count, - 3 - ); - assert_eq!( - finish_options(&e, "Σ", options, SearchDirection::Next, None) - .unwrap() - .count, - 3 - ); - assert_eq!( - finish_options(&e, "k", options, SearchDirection::Next, None) +fn history_anchor_survives_pixel_resize_but_not_reflow_or_reset() { + let size = TermSize::new(40, 4, 0, 0); + let mut e = Emulator::new(size, EmulatorOptions::default()); + let output = b"needle\r\n\r\n\r\n\r\n"; + e.advance(output); + let point = finish(&e, "needle", SearchDirection::Next, None) + .active + .unwrap() + .start; + let anchor = e.search_anchor(point); + e.resize(TermSize::new(40, 4, 9, 18)); + assert_eq!(e.resolve_search_anchor(anchor), Some(point)); + e.resize(TermSize::new(38, 4, 9, 18)); + assert_eq!(e.resolve_search_anchor(anchor), None); + + let anchor = e.search_anchor( + finish(&e, "needle", SearchDirection::Next, None) + .active .unwrap() - .count, - 3 + .start, ); + e.reset(); + e.advance(output); + assert_eq!(e.resolve_search_anchor(anchor), None); +} + +#[test] +fn restarted_search_discards_old_matches_and_keeps_the_query_and_direction() { + let mut e = Emulator::new(TermSize::new(20, 2, 0, 0), EmulatorOptions::default()); + e.advance(b"Needle needle"); + for regex in [false, true] { + let options = SearchOptions { + regex, + case_sensitive: false, + whole_word: true, + }; + let mut scan = e + .search_with_options("Needle", options, SearchDirection::Previous, None) + .unwrap(); + let result = finish_scan(&e, &mut scan).unwrap(); + assert_eq!(result.count, 2); + + e.advance(b"\x1b[2K\r needleX NEEDLE needle"); + assert_eq!(scan.step(&e, 4096), SearchProgress::Invalidated); + let anchor = Some(result.active.unwrap().start); + scan.restart(&e, anchor); + let expected = + finish_options(&e, "Needle", options, SearchDirection::Previous, anchor).unwrap(); + assert_eq!(finish_scan(&e, &mut scan).unwrap(), expected); + e.advance(b"\x1b[2K\rNeedle needle"); + } +} + +#[test] +fn a_full_ascii_row_scans_with_one_step_per_scalar() { + let mut e = Emulator::new(TermSize::new(8, 1, 0, 0), EmulatorOptions::default()); + e.advance(b"abcdefgh"); + let mut scan = e.search("h", SearchDirection::Next, None).unwrap(); + // Eight printed scalars, one hard line ending and one end-of-grid check. + let SearchProgress::Complete(result) = scan.step(&e, 10) else { + panic!("a complete row should fit the budget"); + }; + assert_eq!(result.count, 1); + assert_eq!(result.active.unwrap().start.column, 7); +} + +#[test] +fn a_short_line_in_a_wide_grid_finishes_without_inspecting_the_unused_tail() { + let mut e = Emulator::new(TermSize::new(480, 1, 0, 0), EmulatorOptions::default()); + e.advance(b"\x1b[10Ghit"); + let mut scan = e.search("hit", SearchDirection::Next, None).unwrap(); + let SearchProgress::Complete(result) = scan.step(&e, 14) else { + panic!("twelve cells, a line break and the end of the grid should fit"); + }; + assert_eq!(result.count, 1); + let found = result.active.unwrap(); + assert_eq!((found.start.column, found.end.column), (9, 11)); +} + +#[test] +fn empty_logical_lines_require_no_regex_worker() { + let mut e = Emulator::new(TermSize::new(120, 8, 0, 0), EmulatorOptions::default()); + e.advance(&b"\r\n".repeat(100)); + let mut scan = e + .search_with_options( + "^$", + SearchOptions { + regex: true, + ..Default::default() + }, + SearchDirection::Next, + None, + ) + .unwrap(); assert_eq!( - finish_options(&e, "aa", options, SearchDirection::Next, None) - .unwrap() - .count, - 2 + scan.step(&e, 20_000), + SearchProgress::Complete(SearchResult::default()) ); - assert_eq!(finish(&e, "КОТ", SearchDirection::Next, None).count, 1); + assert!(finish(&e, "\n\n", SearchDirection::Next, None).count > 0); } #[test] @@ -134,7 +233,7 @@ fn regex_anchors_join_soft_wraps_and_map_utf8_combining_bytes_to_cells() { } #[test] -fn regex_navigation_wraps_without_retaining_a_match_list_or_selecting_empty_matches() { +fn regex_navigation_wraps_and_never_selects_empty_matches() { let mut e = Emulator::new(TermSize::new(80, 3, 0, 0), EmulatorOptions::default()); e.advance(b"id1 id22 id333"); let options = SearchOptions { @@ -237,7 +336,10 @@ fn regex_batches_many_short_rows_and_counts_every_match() { jobs += 1; assert!(work.lines.len() > 1); assert!( - work.lines.iter().map(|line| line.text.len()).sum::() + work.lines + .iter() + .map(|line| line.text().len()) + .sum::() <= MAX_REGEX_BATCH_BYTES ); scan.accept_work(&e, work.run()); @@ -338,6 +440,94 @@ fn bounded_steps_invalidation_empty_and_query_limit() { assert_eq!(scan.step(&e, 1), SearchProgress::Invalidated); } +#[test] +fn cursor_queries_preserve_search_work_and_highlights() { + let mut e = Emulator::new(TermSize::new(40, 4, 0, 0), EmulatorOptions::default()); + e.advance(b"target\r\nsecond target"); + let mut literal = e.search("target", SearchDirection::Next, None).unwrap(); + assert_eq!(literal.step(&e, 2), SearchProgress::Searching); + let mut regex = e + .search_with_options( + "target", + SearchOptions { + regex: true, + ..Default::default() + }, + SearchDirection::Next, + None, + ) + .unwrap(); + let SearchProgress::Work(work) = regex.step(&e, 4096) else { + panic!("expected work"); + }; + + assert!(e.advance(b"\x1b[6").is_empty()); + assert_eq!( + e.advance(b"n"), + [crate::Effect::Reply(b"\x1b[2;14R".to_vec())] + ); + e.advance(b"\x1b[H\x1b[?25l\x1b]2;renamed\x07"); + assert_ne!( + regex.accept_work(&e, work.run()), + SearchProgress::Invalidated + ); + let SearchProgress::Complete(regex) = regex.step(&e, 4096) else { + panic!("expected complete regex search"); + }; + let SearchProgress::Complete(literal) = literal.step(&e, 4096) else { + panic!("expected complete literal search"); + }; + assert_eq!(literal, regex); + assert_eq!(literal.count, 2); + + e.show_search_match(literal.active.unwrap()); + e.advance(b"\x1b[6n"); + let mut frame = crate::Frame::default(); + e.snapshot(&mut frame); + assert_eq!(frame.cells.iter().filter(|cell| cell.search_hit).count(), 6); +} + +#[test] +fn search_invalidates_on_committed_grid_mutations() { + for operation in [ + "\u{301}", + "\x1b[2J", + "\x1b[3J", + "\x1b[S", + "\x1b[T", + "\x1b[?1049h", + "\x1bc", + ] { + let mut e = Emulator::new(TermSize::new(20, 2, 0, 0), EmulatorOptions::default()); + e.advance(b"target\r\nsecond\r\nthird"); + let mut scan = e.search("target", SearchDirection::Next, None).unwrap(); + e.advance(operation.as_bytes()); + assert_eq!( + scan.step(&e, 1), + SearchProgress::Invalidated, + "{operation:?}", + ); + } +} + +#[test] +fn synchronized_search_keeps_scanning_until_buffered_text_is_applied() { + let mut e = Emulator::new(TermSize::new(40, 4, 0, 0), EmulatorOptions::default()); + e.advance(b"target"); + for end in [Some(b"\x1b[?2026l".as_slice()), None] { + let mut scan = e.search("target", SearchDirection::Next, None).unwrap(); + e.advance(b"\x1b[?2026h target"); + assert_eq!(scan.step(&e, 1), SearchProgress::Searching); + if let Some(bytes) = end { + e.advance(bytes); + } else { + e.finish_sync(); + } + assert_eq!(scan.step(&e, 1), SearchProgress::Invalidated); + } + assert_eq!(finish(&e, "target", SearchDirection::Next, None).count, 3); +} + #[test] fn search_highlight_never_changes_selection_and_history_eviction_invalidates() { use crate::{CellPoint, Frame, SelectionKind, Side}; @@ -373,6 +563,44 @@ fn search_highlight_never_changes_selection_and_history_eviction_invalidates() { assert_eq!(finish(&e, "needle", SearchDirection::Next, None).count, 0); } +#[test] +fn a_scrolled_frame_keeps_wide_matches_and_combining_cells_in_row_order() { + use crate::{CellPoint, Frame, SelectionKind, Side}; + let mut e = Emulator::new(TermSize::new(12, 2, 0, 0), EmulatorOptions::default()); + e.advance("zero\r\n\x1b[1mAe\u{301}界\x1b[0m\r\nlast".as_bytes()); + let found = finish(&e, "界", SearchDirection::Next, None) + .active + .unwrap(); + e.show_search_match(found); + assert!(e.scroll(crate::Scroll::Top)); + let first = CellPoint { row: 1, col: 0 }; + e.start_selection(SelectionKind::Cells, first, Side::Left); + e.update_selection(first, Side::Right); + + let mut frame = Frame::default(); + e.snapshot(&mut frame); + assert_eq!(frame.cells.len(), 24); + assert_eq!(frame.row_text(0), "zero"); + assert_eq!(frame.row_text(1), "Ae界"); + assert_eq!(frame.combining, [(13, "\u{301}".into())]); + assert!(frame.row(1)[0].style.bold && frame.row(1)[0].selected); + assert!(frame.row(1)[2].wide && frame.row(1)[3].spacer); + assert_eq!( + frame + .cells + .iter() + .enumerate() + .filter_map(|(index, cell)| cell.search_hit.then_some(index)) + .collect::>(), + [14, 15], + ); + + e.advance(b" changed"); + e.snapshot(&mut frame); + assert_eq!(frame.cells.len(), 24); + assert!(!frame.cells.iter().any(|cell| cell.search_hit)); +} + #[test] fn resize_reflow_and_alternate_screen_do_not_keep_stale_matches() { use crate::Frame; @@ -400,9 +628,8 @@ fn resize_reflow_and_alternate_screen_do_not_keep_stale_matches() { #[test] fn many_combining_scalars_use_bounded_steps_and_distinct_overlap_anchors() { let mut e = Emulator::new(TermSize::new(100, 2, 0, 0), EmulatorOptions::default()); - // Keep thousands of scalars under tiny scheduler budgets while respecting - // the engine's 64-mark cap per cell. - let cluster = format!("a{}", "\u{301}".repeat(50)); + // Keep thousands of scalars under tiny budgets and exercise the cell's mark cap. + let cluster = format!("a{}", "\u{301}".repeat(70)); e.advance(cluster.repeat(100).as_bytes()); let mut scan = e .search("\u{301}\u{301}", SearchDirection::Next, None) @@ -411,7 +638,7 @@ fn many_combining_scalars_use_bounded_steps_and_distinct_overlap_anchors() { assert_eq!(scan.step(&e, 1), SearchProgress::Searching); } let first = finish(&e, "\u{301}\u{301}", SearchDirection::Next, None); - assert_eq!(first.count, 100 * 49); + assert_eq!(first.count, 100 * 63); let second = finish( &e, "\u{301}\u{301}", @@ -519,3 +746,13 @@ fn failed_worker_is_sticky_without_fallback_and_stale_failures_are_discarded() { let current = finish_options(&e, "target", options, SearchDirection::Next, None).unwrap(); assert_eq!(current.count, 1); } + +mod performance; + +mod navigation; + +mod regex_coordinates; + +mod retained; + +mod case_folding; diff --git a/crates/vt/src/search/tests/case_folding.rs b/crates/vt/src/search/tests/case_folding.rs new file mode 100644 index 00000000..c7049bf4 --- /dev/null +++ b/crates/vt/src/search/tests/case_folding.rs @@ -0,0 +1,113 @@ +use super::*; +use std::{hint::black_box, io::Write as _, time::Instant}; + +#[test] +fn unicode_case_folding_keeps_overlap_and_cell_positions() { + let mut e = Emulator::new(TermSize::new(80, 3, 0, 0), EmulatorOptions::default()); + e.advance("Кот кОт КОТ Σσς KkK aAa".as_bytes()); + let options = SearchOptions { + case_sensitive: false, + ..Default::default() + }; + assert_eq!( + finish_options(&e, "кот", options, SearchDirection::Next, None) + .unwrap() + .count, + 3 + ); + assert_eq!( + finish_options(&e, "Σ", options, SearchDirection::Next, None) + .unwrap() + .count, + 3 + ); + assert_eq!( + finish_options(&e, "k", options, SearchDirection::Next, None) + .unwrap() + .count, + 3 + ); + assert_eq!( + finish_options(&e, "aa", options, SearchDirection::Next, None) + .unwrap() + .count, + 2 + ); + assert_eq!(finish(&e, "КОТ", SearchDirection::Next, None).count, 1); +} + +#[test] +fn case_insensitive_literal_and_regex_agree_across_ascii_and_unicode() { + let mut emulator = Emulator::new(TermSize::new(160, 4, 0, 0), EmulatorOptions::default()); + let text: String = (b' '..=b'~').map(char::from).collect(); + emulator.advance(format!("{text} ßẞ KKk ſSs Σσς\r\n{text}\r\n").as_bytes()); + + let literal = SearchOptions { + case_sensitive: false, + ..Default::default() + }; + let regex = SearchOptions { + regex: true, + ..literal + }; + for scalar in (b' '..=b'~').map(char::from).chain(['K', 'ſ', 'ß', 'ς']) { + let query = scalar.to_string(); + let plain = + finish_options(&emulator, &query, literal, SearchDirection::Next, None).unwrap(); + let pattern = regex::escape(&query); + let folded = + finish_options(&emulator, &pattern, regex, SearchDirection::Next, None).unwrap(); + assert_eq!(plain, folded, "{scalar:?}"); + } +} + +#[test] +#[ignore = "release fixture for case-insensitive public VT search"] +fn measure_case_insensitive_scrollback() { + let options = SearchOptions { + case_sensitive: false, + ..Default::default() + }; + for (shape, row, query, expected) in [ + ( + "ascii", + "Logs for NEEDLE and NEedle. ".repeat(7), + "needle", + 126_000, + ), + ( + "mixed", + "Кот ſhared-King and SHARED-KING. ".repeat(6), + "shared-king", + 108_000, + ), + ] { + let mut emulator = Emulator::new(TermSize::new(245, 40, 0, 0), EmulatorOptions::default()); + emulator.advance(format!("{row}\r\n").repeat(9_000).as_bytes()); + let reference = + finish_options(&emulator, query, options, SearchDirection::Next, None).unwrap(); + assert_eq!(reference.count, expected); + let mut samples = Vec::new(); + for _ in 0..15 { + let start = Instant::now(); + let found = finish_options( + black_box(&emulator), + black_box(query), + options, + SearchDirection::Next, + None, + ) + .unwrap(); + samples.push(start.elapsed()); + assert_eq!(found, reference); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{shape} count={expected} p50={:?} p95={:?}", + samples[7], + samples[14], + ) + .unwrap(); + } +} diff --git a/crates/vt/src/search/tests/navigation.rs b/crates/vt/src/search/tests/navigation.rs new file mode 100644 index 00000000..76191206 --- /dev/null +++ b/crates/vt/src/search/tests/navigation.rs @@ -0,0 +1,119 @@ +use super::*; + +#[test] +fn large_searches_retain_a_bounded_span_and_exact_endpoints() { + let cap = MAX_NAVIGATION_MATCHES as u64; + let count = cap * 2 + 100; + for regex in [false, true] { + let mut e = Emulator::new( + TermSize::new(80, 3, 0, 0), + EmulatorOptions { + scrollback_lines: count as usize, + ..Default::default() + }, + ); + e.advance(&b"target\r\n".repeat(count as usize)); + let options = SearchOptions { + regex, + ..Default::default() + }; + let mut scan = e + .search_with_options("target", options, SearchDirection::Stay, None) + .unwrap(); + assert!(scan.take_navigation().is_none()); + let result = finish_scan(&e, &mut scan).unwrap(); + let initial = scan.take_navigation().unwrap(); + assert!(scan.take_navigation().is_none()); + assert_eq!(result.ordinal, 1); + assert_eq!(result.count, count); + assert_eq!(initial.get(1), result.active); + assert!(initial.get(cap).is_some()); + assert!(initial.get(cap + 1).is_none()); + + let wanted = cap + 1; + let mut scan = SearchScan::navigate( + &e, + "target", + options, + SearchDirection::Next, + initial.get(cap).map(|m| m.start), + wanted, + ) + .unwrap(); + let result = finish_scan(&e, &mut scan).unwrap(); + let span = scan.take_navigation().unwrap(); + assert_eq!((result.ordinal, result.count), (wanted, count)); + assert_eq!(span.get(wanted), result.active); + assert_eq!(span.get(cap), initial.get(cap)); + assert_eq!(span.get(1), initial.get(1)); + assert_eq!(span.get(count), initial.get(count)); + assert_eq!( + span.get(wanted + 1).unwrap().start.line, + result.active.unwrap().start.line + 1 + ); + assert!(span.get(wanted - cap / 2 - 1).is_none()); + assert!(span.get(wanted + cap / 2).is_none()); + assert!(span.get(0).is_none()); + assert!(span.get(count + 1).is_none()); + } +} + +#[test] +fn restarting_navigation_uses_the_anchor_and_rejects_the_old_batch() { + let mut e = Emulator::new(TermSize::new(80, 3, 0, 0), EmulatorOptions::default()); + e.advance(b"target target target"); + let options = SearchOptions { + regex: true, + ..Default::default() + }; + let anchor = finish(&e, "target", SearchDirection::Stay, None) + .active + .map(|m| m.start); + let mut scan = + SearchScan::navigate(&e, "target", options, SearchDirection::Next, anchor, 2).unwrap(); + let SearchProgress::Work(old) = scan.step(&e, 4096) else { + panic!("expected original work"); + }; + let completed = old.run(); + e.advance(b"\r......"); + scan.restart(&e, anchor); + let SearchProgress::Work(current) = scan.step(&e, 4096) else { + panic!("expected restarted work"); + }; + assert_eq!(scan.accept_work(&e, completed), SearchProgress::Invalidated); + assert_eq!( + scan.accept_work(&e, current.run()), + SearchProgress::Searching + ); + let result = finish_scan(&e, &mut scan).unwrap(); + assert_eq!((result.ordinal, result.count), (1, 2)); + assert_eq!(result.active.unwrap().start.column, 7); +} + +#[test] +fn literal_fallback_and_overlapping_prefixes_keep_the_exact_columns() { + let mut emulator = Emulator::new(TermSize::new(80, 4, 0, 0), EmulatorOptions::default()); + emulator.advance(b"aaaa x aabaabaabaab aaabaab aabaab aabaaab\r\n"); + for (whole_word, columns) in [(false, &[7, 10, 13, 21, 28][..]), (true, &[28][..])] { + let options = SearchOptions { + whole_word, + ..Default::default() + }; + let mut scan = emulator + .search_with_options("aabaab", options, SearchDirection::Next, None) + .unwrap(); + let result = loop { + match scan.step(&emulator, 1) { + SearchProgress::Complete(result) => break result, + SearchProgress::Searching => continue, + other => panic!("unexpected literal search progress: {other:?}"), + } + }; + assert_eq!(result.count as usize, columns.len()); + for (index, &column) in columns.iter().enumerate() { + let found = scan.navigation_match(&emulator, index as u64 + 1).unwrap(); + assert_eq!((found.start.line, found.start.column), (0, column)); + assert_eq!((found.end.line, found.end.column), (0, column + 5)); + } + } +} diff --git a/crates/vt/src/search/tests/performance.rs b/crates/vt/src/search/tests/performance.rs new file mode 100644 index 00000000..05655571 --- /dev/null +++ b/crates/vt/src/search/tests/performance.rs @@ -0,0 +1,369 @@ +use super::*; +use std::{ + io::Write as _, + time::{Duration, Instant}, +}; + +#[test] +#[ignore = "release performance fixture for terminal frame projection"] +fn search_highlight_frame_profile() { + use crate::Frame; + for (cols, rows, density) in [(122, 35, 17), (240, 55, 17), (240, 55, 236), (480, 90, 17)] { + let mut e = Emulator::new(TermSize::new(cols, rows, 8, 16), EmulatorOptions::default()); + for row in 0..rows - 1 { + let mut text = String::new(); + if row == 4 || density > 17 || row % 8 == 4 { + text.push_str(&"x".repeat(density)); + text.push(if row == 4 { '界' } else { 'x' }); + } + text.push_str("\r\n"); + e.advance_at(text.as_bytes(), u64::from(row)); + } + let mut frame = Frame::default(); + for highlight in [false, true] { + if highlight { + let found = finish(&e, "界", SearchDirection::Next, None) + .active + .unwrap(); + e.show_search_match(found); + } + let mut samples = [Duration::ZERO; 21]; + for sample in &mut samples { + let start = Instant::now(); + for _ in 0..64 { + e.snapshot(std::hint::black_box(&mut frame)); + } + *sample = start.elapsed() / 64; + } + assert_eq!(frame.cells.len(), usize::from(cols) * usize::from(rows)); + assert_eq!( + frame.cells.iter().filter(|cell| cell.search_hit).count(), + if highlight { 2 } else { 0 } + ); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "cols={cols} rows={rows} prefix={density} highlight={highlight} p50={:?} p95={:?}", + samples[10], + samples[19] + ) + .unwrap(); + } + } +} + +#[test] +#[ignore = "release performance fixture for sparse and dense search"] +fn find_sparse_history_profile() { + for (width, prefix) in [(260, 32), (260, 235), (480, 32)] { + let mut e = Emulator::new( + TermSize::new(width, 48, 8, 16), + EmulatorOptions { + scrollback_lines: 10_000, + ..Default::default() + }, + ); + let rows = format!("{} needle\r\n", "x".repeat(prefix)).repeat(100); + for _ in 0..100 { + e.advance_at(rows.as_bytes(), 1_000); + } + for regex in [false, true] { + let options = SearchOptions { + regex, + ..Default::default() + }; + let mut samples = Vec::with_capacity(21); + for _ in 0..21 { + let start = Instant::now(); + let found = + finish_options(&e, "needle", options, SearchDirection::Next, None).unwrap(); + samples.push(start.elapsed()); + assert_eq!(found.count, 10_000); + assert_eq!(found.active.unwrap().start.column as usize, prefix + 1); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "cols={width} prefix={prefix} regex={regex} p50={:?} p95={:?}", + samples[10], + samples[19] + ) + .unwrap(); + } + } +} + +#[test] +#[ignore = "release performance fixture; prints real timings"] +fn search_device_queries_profile() { + let mut e = Emulator::new( + TermSize::new(260, 48, 8, 16), + EmulatorOptions { + scrollback_lines: 10_000, + ..Default::default() + }, + ); + let rows = format!("{} needle\r\n", "x".repeat(235)).repeat(100); + for _ in 0..100 { + e.advance_at(rows.as_bytes(), 1000); + } + for regex in [false, true] { + let options = SearchOptions { + regex, + ..Default::default() + }; + for query_between_steps in [false, true] { + let mut completions = 0; + let mut durations = Vec::new(); + for _ in 0..20 { + let mut scan = e + .search_with_options("needle", options, SearchDirection::Next, None) + .unwrap(); + let start = Instant::now(); + let mut progress = scan.step(&e, 4096); + let mut next_query = Duration::from_millis(1); + loop { + if query_between_steps && start.elapsed() >= next_query { + assert!(matches!( + e.advance_at(b"\x1b[6n", 2000).as_slice(), + [crate::Effect::Reply(_)] + )); + next_query = start.elapsed() + Duration::from_millis(1); + } + progress = match progress { + SearchProgress::Searching => scan.step(&e, 4096), + SearchProgress::Work(work) => scan.accept_work(&e, work.run()), + SearchProgress::Complete(result) => { + assert_eq!(result.count, 10_000); + completions += 1; + break; + } + SearchProgress::Invalidated => break, + SearchProgress::Failed(error) => panic!("{error}"), + }; + } + durations.push(start.elapsed()); + } + durations.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "regex={regex} cursor_queries={query_between_steps} p50={:?} p95={:?} completions={completions}", + durations[10], durations[18], + ) + .unwrap(); + assert_eq!(completions, 20, "device queries interrupted a search"); + } + } +} + +#[test] +#[ignore = "release performance fixture; compares repeated preparation and scan restart"] +fn search_restarts_profile() { + let mut e = Emulator::new(TermSize::new(80, 2, 0, 0), EmulatorOptions::default()); + let options = SearchOptions { + regex: true, + case_sensitive: false, + whole_word: true, + }; + let direction = SearchDirection::Next; + for query in [ + "needle", + "(?:needle|error|warn(?:ing)?|debug|trace|status|finished|started|success|failed|[A-Z]{2}-[0-9]+)", + ] { + for reuse in [false, true] { + let mut scan = e + .search_with_options(query, options, direction, None) + .unwrap(); + let mut samples = Vec::with_capacity(301); + for i in 0..301 { + let output: &[u8] = if i % 2 == 0 { + b"\rNeedle unused" + } else { + b"\rneedle unused" + }; + e.advance(output); + assert_eq!(scan.step(&e, 1), SearchProgress::Invalidated); + let start = Instant::now(); + if reuse { + scan.restart(&e, None); + } else { + scan = e + .search_with_options(query, options, direction, None) + .unwrap(); + } + samples.push(start.elapsed()); + let result = finish_scan(&e, &mut scan).unwrap(); + assert_eq!(result.count, 1); + assert_eq!(result.active.unwrap().start.column, 0); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "regex_bytes={} reuse={reuse} p50={:?} p95={:?}", + query.len(), + samples[150], + samples[285] + ) + .unwrap(); + } + } +} + +#[test] +#[ignore = "release performance fixture for repeated navigation through large scrollback"] +fn large_history_navigation_profile() { + use std::hint::black_box; + + let mut e = Emulator::new(TermSize::new(260, 40, 8, 16), EmulatorOptions::default()); + e.advance(&b"012345678 needle\r\n".repeat(9_000)); + for regex in [false, true] { + let options = SearchOptions { + regex, + ..Default::default() + }; + let mut scan = e + .search_with_options("needle", options, SearchDirection::Next, None) + .unwrap(); + let first = finish_scan(&e, &mut scan).unwrap(); + let retained = scan.take_navigation().unwrap(); + let first_match = first.active.unwrap(); + for reuse in [false, true] { + let mut samples = [Duration::ZERO; 15]; + for sample in &mut samples { + let mut current = first_match; + let start = Instant::now(); + for ordinal in 2..=25 { + current = if reuse { + retained.get(black_box(ordinal)).unwrap() + } else { + let result = finish_options( + &e, + "needle", + options, + SearchDirection::Next, + Some(current.start), + ) + .unwrap(); + assert_eq!((result.ordinal, result.count), (ordinal, 9_000)); + result.active.unwrap() + }; + assert_eq!( + current.start.line, + first_match.start.line + ordinal as i32 - 1 + ); + } + *sample = start.elapsed(); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "regex={regex} retained={reuse} actions=24 p50={:?} p95={:?}", + samples[7], + samples[14], + ) + .unwrap(); + } + } +} + +#[test] +#[ignore = "release performance fixture for regex coordinate mapping"] +fn regex_coordinate_scan_profile() { + let options = SearchOptions { + regex: true, + ..Default::default() + }; + for (name, prefix, pattern) in [ + ("short_ascii", "x".repeat(32), "needle$"), + ("dense_ascii", "x".repeat(235), "needle$"), + ("mixed", "abc界é_e\u{301}_123😀".repeat(8), "needle$"), + ("wide_combining", "界路é\u{301}😀".repeat(32), "needle$"), + ] { + let mut e = Emulator::new(TermSize::new(260, 48, 8, 16), EmulatorOptions::default()); + let packet = format!("{prefix} needle\r\n").repeat(100); + for _ in 0..100 { + e.advance_at(packet.as_bytes(), 1_000); + } + + let mut samples = [Duration::ZERO; 21]; + for sample in &mut samples { + let start = Instant::now(); + let result = finish_options(&e, pattern, options, SearchDirection::Next, None).unwrap(); + *sample = start.elapsed(); + assert_eq!(result.count, 10_000); + assert_eq!( + result.active.unwrap().end.column - result.active.unwrap().start.column, + 5 + ); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "regex_coordinates={name} p50={:?} p95={:?}", + samples[10], + samples[19] + ) + .unwrap(); + } +} + +#[test] +#[ignore = "release fixture for sustained search refresh as the oldest scrollback rows rotate"] +fn measure_search_refresh_at_scrollback_capacity() { + let log = b"2026-12-01T04:20:03 INFO connected pid=1000 prefix needle suffix for audit log\r\n"; + let dense = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n"; + for (name, regex, query, line, matches_per_row) in [ + ("literal", false, "needle", log.as_slice(), 1), + ("overlap", false, "aaaaa", dense.as_slice(), 69), + ("regex", true, r"\bneedl[e]\b", log.as_slice(), 1), + ] { + for capacity in [500, 10_000] { + let mut emulator = Emulator::new( + TermSize::new(240, 75, 8, 16), + EmulatorOptions { + scrollback_lines: capacity, + ..Default::default() + }, + ); + let retained_rows = capacity + 74; + emulator.advance(&line.repeat(retained_rows)); + let options = SearchOptions { + regex, + ..Default::default() + }; + let mut scan = emulator + .search_with_options(query, options, SearchDirection::Stay, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!(initial.count as usize, retained_rows * matches_per_row); + let mut fallbacks = Vec::new(); + let mut durations = [Duration::ZERO; 1_350]; + for duration in &mut durations { + emulator.advance(std::hint::black_box(line)); + let start = Instant::now(); + let refreshed = scan.refresh_retained(&emulator, None); + if !refreshed { + scan.restart(&emulator, None); + } + let result = finish_scan(&emulator, &mut scan).unwrap(); + *duration = start.elapsed(); + if !refreshed { + fallbacks.push(*duration); + } + assert_eq!(result, initial); + } + durations.sort_unstable(); + fallbacks.sort_unstable(); + let fallback_median = fallbacks.get(fallbacks.len() / 2); + writeln!( + std::io::stdout().lock(), + "history={capacity} pattern={name} restarts={} fallback_p50={fallback_median:?} p50={:?} p95={:?} p99={:?}", + fallbacks.len(), + durations[675], + durations[1_282], + durations[1_336] + ) + .unwrap(); + } + } +} diff --git a/crates/vt/src/search/tests/regex_coordinates.rs b/crates/vt/src/search/tests/regex_coordinates.rs new file mode 100644 index 00000000..8f38c1f8 --- /dev/null +++ b/crates/vt/src/search/tests/regex_coordinates.rs @@ -0,0 +1,107 @@ +use super::*; + +fn matches(e: &Emulator, query: &str, regex: bool) -> Vec { + let options = SearchOptions { + regex, + ..Default::default() + }; + let mut scan = e + .search_with_options(query, options, SearchDirection::Next, None) + .unwrap(); + let result = finish_scan(e, &mut scan).unwrap(); + if result.count == 0 { + return Vec::new(); + } + let navigation = scan.take_navigation().unwrap(); + (1..=result.count) + .map(|ordinal| navigation.get(ordinal).unwrap()) + .collect() +} + +#[test] +fn regex_ranges_preserve_multibyte_ends_and_combining_positions() { + let mut e = Emulator::new(TermSize::new(32, 4, 0, 0), EmulatorOptions::default()); + e.advance("abé界😀e\u{301}z é界😀e\u{301}z".as_bytes()); + + for needle in ["bé", "é界", "界😀", "😀e\u{301}", "\u{301}", "\u{301}z"] { + let expected = matches(&e, needle, false); + assert!(!expected.is_empty(), "{needle:?}"); + assert_eq!( + matches(&e, ®ex::escape(needle), true), + expected, + "{needle:?}" + ); + } + let endings = matches(&e, "e\\p{M}", true); + assert_eq!(endings.len(), 2); + assert_eq!(endings, matches(&e, "e\u{301}", false)); + assert_eq!(endings[0].start.column, 7); + assert_eq!(endings[0].end.column, 7); + assert_ne!(endings[0].start, endings[0].end); +} + +#[test] +fn regex_coordinates_follow_soft_wraps_and_skip_wide_spacers_after_reflow() { + let mut e = Emulator::new(TermSize::new(6, 6, 0, 0), EmulatorOptions::default()); + e.advance("abcde界aé\u{301}b\r\nnext".as_bytes()); + let needle = "e界aé\u{301}"; + let initial = matches(&e, needle, true); + assert_eq!(initial.len(), 1); + assert_eq!(initial, matches(&e, needle, false)); + assert_eq!((initial[0].start.column, initial[0].end.column), (4, 3)); + assert!(initial[0].start.line < initial[0].end.line); + assert!(matches(&e, "bnext", true).is_empty()); + + for width in [4, 10] { + e.resize(TermSize::new(width, 6, 0, 0)); + let expected = matches(&e, needle, false); + assert_eq!(expected.len(), 1); + assert_eq!(matches(&e, needle, true), expected); + assert!(matches(&e, "bnext", true).is_empty()); + } +} + +#[test] +fn regex_keeps_the_final_wrapped_line_at_the_batch_byte_boundary() { + let mut emulator = Emulator::new(TermSize::new(256, 1, 0, 0), EmulatorOptions::default()); + let mut output = format!("{}tail\r\n", "x".repeat(4096 - 4)).repeat(12); + output.push_str(&"x".repeat(16384 - 4)); + output.push_str("tail"); + assert_eq!(output.len() - 12 * 2, MAX_REGEX_BATCH_BYTES); + emulator.advance(output.as_bytes()); + let expected = matches(&emulator, "tail", false); + assert_eq!(expected.len(), 13); + assert_eq!(expected.last().unwrap().end.column, 255); + + for budget in [3, 67, 4096, usize::MAX] { + let mut scan = emulator + .search_with_options( + "tail$", + SearchOptions { + regex: true, + ..Default::default() + }, + SearchDirection::Previous, + None, + ) + .unwrap(); + let result = loop { + match scan.step(&emulator, budget) { + SearchProgress::Complete(result) => break result, + SearchProgress::Searching => continue, + SearchProgress::Work(work) => { + assert_eq!( + scan.accept_work(&emulator, work.run()), + SearchProgress::Searching + ); + } + progress => panic!("unexpected search progress: {progress:?}"), + } + }; + assert_eq!(result.count as usize, expected.len()); + assert_eq!(result.active, expected.last().copied()); + let found = + (1..=result.count).map(|ordinal| scan.navigation_match(&emulator, ordinal).unwrap()); + assert!(found.eq(expected.iter().copied()), "budget {budget}"); + } +} diff --git a/crates/vt/src/search/tests/retained.rs b/crates/vt/src/search/tests/retained.rs new file mode 100644 index 00000000..848317b3 --- /dev/null +++ b/crates/vt/src/search/tests/retained.rs @@ -0,0 +1,475 @@ +use super::*; +use std::hint::black_box; +use std::io::Write as _; +use std::time::Instant; + +fn scripted_history(rows: usize, capacity: usize) -> Emulator { + let mut emulator = Emulator::new( + TermSize::new(80, 24, 0, 0), + EmulatorOptions { + scrollback_lines: capacity, + ..Default::default() + }, + ); + emulator.advance(b"prefix needle suffix\r\n".repeat(rows).as_slice()); + emulator +} + +#[test] +fn live_refresh_keeps_the_selected_ordinal_and_updates_exact_coordinates() { + for regex in [false, true] { + let mut emulator = scripted_history(500, 1_000); + let pattern = if regex { "n[e]+dle" } else { "needle" }; + let options = SearchOptions { + regex, + whole_word: true, + ..Default::default() + }; + let mut scan = emulator + .search_with_options(pattern, options, SearchDirection::Next, None) + .unwrap(); + finish_scan(&emulator, &mut scan).unwrap(); + let historical = scan.navigation_match(&emulator, 13).unwrap(); + let anchor = emulator.search_anchor(historical.start); + for rows in 1..=12 { + emulator.advance(b"prefix needle suffix\r\n".repeat(rows).as_slice()); + assert!(scan.navigation_match(&emulator, 13).is_none()); + assert!(scan.refresh_retained(&emulator, emulator.resolve_search_anchor(anchor))); + let result = finish_scan(&emulator, &mut scan).unwrap(); + let reference = finish_options( + &emulator, + pattern, + options, + SearchDirection::Stay, + emulator.resolve_search_anchor(anchor), + ) + .unwrap(); + assert_eq!(result, reference); + assert_eq!(result.ordinal, 13); + assert_eq!(scan.navigation_match(&emulator, 13), result.active); + } + } +} + +#[test] +fn invalidated_regex_worker_leaves_the_same_completed_history_usable() { + let mut emulator = scripted_history(550, 1_000); + let options = SearchOptions { + regex: true, + ..Default::default() + }; + let mut scan = emulator + .search_with_options("needl[e]", options, SearchDirection::Next, None) + .unwrap(); + finish_scan(&emulator, &mut scan).unwrap(); + emulator.advance(b"needle\r\n"); + assert!(scan.refresh_retained(&emulator, None)); + let SearchProgress::Work(work) = scan.step(&emulator, 4_096) else { + panic!("the changed tail has regex work"); + }; + emulator.advance(b"needle\r\n"); + assert_eq!( + scan.accept_work(&emulator, work.run()), + SearchProgress::Invalidated + ); + assert!(scan.navigation_match(&emulator, 1).is_none()); + assert!(scan.refresh_retained(&emulator, None)); + let result = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!((result.ordinal, result.count), (1, 552)); +} + +#[test] +fn live_refresh_rejects_cleared_reflowed_replaced_and_alternate_history() { + for changed in [b"\x1b[3J".as_slice(), b"\x1bc", b"\x1b[?1049h"] { + let mut emulator = scripted_history(250, 230); + let mut scan = emulator + .search("needle", SearchDirection::Next, None) + .unwrap(); + finish_scan(&emulator, &mut scan).unwrap(); + emulator.advance(changed); + assert!(!scan.refresh_retained(&emulator, None), "{changed:?}"); + scan.restart(&emulator, None); + assert_eq!( + finish_scan(&emulator, &mut scan).unwrap(), + finish(&emulator, "needle", SearchDirection::Next, None) + ); + } + let mut emulator = scripted_history(250, 1_000); + let mut scan = emulator + .search("needle", SearchDirection::Next, None) + .unwrap(); + finish_scan(&emulator, &mut scan).unwrap(); + emulator.resize(TermSize::new(36, 24, 0, 0)); + assert!(!scan.refresh_retained(&emulator, None)); + emulator.reset(); + emulator.advance(b"needle\r\n".repeat(255).as_slice()); + assert!(!scan.refresh_retained(&emulator, None)); +} + +#[test] +fn live_refresh_preserves_multiline_matches_across_the_history_boundary() { + let mut emulator = Emulator::new(TermSize::new(20, 4, 0, 0), EmulatorOptions::default()); + emulator.advance(b"needle\r\nsecond\r\nneedle\r\nsecond\r\nlast\r\npadding\r\nend"); + let mut scan = emulator + .search("needle\nsecond", SearchDirection::Next, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!(initial.count, 2); + assert!(initial.active.unwrap().start.line < 0); + emulator.advance(b" updated"); + assert!(!scan.refresh_retained(&emulator, None)); + scan.restart(&emulator, None); + assert_eq!(finish_scan(&emulator, &mut scan).unwrap(), initial); +} + +#[test] +#[ignore = "release fixture for completed history followed by live appends"] +fn measure_completed_history_refresh() { + for regex in [false, true] { + let options = SearchOptions { + regex, + ..Default::default() + }; + let pattern = if regex { "n[e]+dle" } else { "needle" }; + for reused in [false, true, true, false] { + let mut emulator = scripted_history(9_000, 12_000); + let mut scan = emulator + .search_with_options(pattern, options, SearchDirection::Stay, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + let anchor = emulator.search_anchor(initial.active.unwrap().start); + let mut elapsed = std::time::Duration::ZERO; + for expected in 9_001..=9_060 { + emulator.advance(black_box(b"prefix needle suffix\r\n")); + let start = Instant::now(); + if reused { + assert!( + scan.refresh_retained(&emulator, emulator.resolve_search_anchor(anchor)) + ); + } else { + scan.restart(&emulator, emulator.resolve_search_anchor(anchor)); + } + let found = finish_scan(&emulator, &mut scan).unwrap(); + elapsed += start.elapsed(); + assert_eq!((found.count, found.ordinal), (expected, 1)); + assert_eq!( + found.active.unwrap().start, + emulator.resolve_search_anchor(anchor).unwrap() + ); + } + writeln!( + std::io::stdout().lock(), + "regex={regex} reused={reused} total_ms={:.3}", + elapsed.as_secs_f64() * 1_000. + ) + .unwrap(); + } + } +} + +#[test] +fn completed_search_without_history_keeps_current_navigation() { + let mut emulator = scripted_history(4, 1000); + let options = SearchOptions { + regex: true, + ..Default::default() + }; + let mut scan = emulator + .search_with_options("needl[e]", options, SearchDirection::Next, None) + .unwrap(); + let exact = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!(exact.count, 4); + let completed = scan.into_completed().unwrap(); + assert_eq!(completed.navigation_match(&emulator, 1), exact.active); + emulator.advance(b"needle\r\n"); + assert!(!completed.is_complete_for(&emulator)); + assert!(completed.navigation_match(&emulator, 1).is_none()); + assert!(completed.into_refresh(&emulator, None).is_none()); +} + +#[test] +fn full_history_refresh_preserves_the_surviving_match_and_rebases_its_ordinal() { + for regex in [false, true] { + let mut emulator = scripted_history(700, 500); + let options = SearchOptions { + regex, + ..Default::default() + }; + let mut scan = emulator + .search_with_options("needle", options, SearchDirection::Next, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + let active = scan.navigation_match(&emulator, 7).unwrap(); + let anchor = emulator.search_anchor(active.start); + for (index, output) in [b"only noise\r\n".as_slice(), b"needle\r\n", b"noise\r\n"] + .into_iter() + .enumerate() + { + emulator.advance(output); + let anchor = emulator.resolve_search_anchor(anchor); + assert!(scan.refresh_retained(&emulator, anchor)); + let found = finish_scan(&emulator, &mut scan).unwrap(); + let fresh = finish_options(&emulator, "needle", options, SearchDirection::Stay, anchor) + .unwrap(); + assert_eq!(found, fresh); + assert_eq!(found.ordinal, 6 - index as u64); + assert_eq!(found.count, initial.count - if index < 2 { 1 } else { 2 }); + assert_eq!( + scan.navigation_match(&emulator, found.ordinal), + found.active + ); + } + emulator.advance(b"noise\r\n".repeat(10).as_slice()); + assert!(emulator.resolve_search_anchor(anchor).is_none()); + assert!(scan.refresh_retained(&emulator, None)); + let found = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!( + found, + finish_options(&emulator, "needle", options, SearchDirection::Stay, None).unwrap() + ); + assert_eq!(found.ordinal, 1); + } +} + +#[test] +fn dense_history_reuses_exact_matches_after_a_large_eviction() { + let mut emulator = Emulator::new( + TermSize::new(80, 5, 0, 0), + EmulatorOptions { + scrollback_lines: 150, + ..Default::default() + }, + ); + let row = format!("{}\r\n", "a".repeat(73)); + emulator.advance(row.repeat(154).as_bytes()); + let mut scan = emulator + .search("aaaaa", SearchDirection::Next, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!(initial.count, 154 * 69); + + // Sixty rows at 69 matches each exhaust the former 4,096-match span. + emulator.advance(&b"noise\r\n".repeat(60)); + assert!(scan.refresh_retained(&emulator, None)); + let found = finish_scan(&emulator, &mut scan).unwrap(); + let reference = finish(&emulator, "aaaaa", SearchDirection::Next, None); + assert_eq!(found, reference); + assert_eq!((found.ordinal, found.count), (1, 94 * 69)); + assert_eq!(scan.navigation_match(&emulator, 1), reference.active); + let next = finish( + &emulator, + "aaaaa", + SearchDirection::Next, + reference.active.map(|found| found.start), + ); + assert_eq!(scan.navigation_match(&emulator, 2), next.active); +} + +#[test] +fn refresh_does_not_invent_coordinates_in_a_truncated_navigation_span() { + let cap = MAX_NAVIGATION_MATCHES; + let mut emulator = scripted_history(cap + 1_000, cap + 500); + let mut scan = emulator + .search("needle", SearchDirection::Next, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + assert!(scan.navigation_match(&emulator, cap as u64).is_some()); + emulator.advance(b"noise\r\n".repeat(5).as_slice()); + assert!(scan.refresh_retained(&emulator, None)); + let found = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!(found.count, initial.count - 5); + assert!(scan.navigation_match(&emulator, cap as u64 - 5).is_some()); + assert!(scan.navigation_match(&emulator, cap as u64 - 4).is_none()); + assert!(scan.navigation_match(&emulator, found.count).is_some()); +} + +#[test] +fn refresh_rejects_an_eviction_cut_inside_an_old_soft_wrap() { + let mut emulator = Emulator::new( + TermSize::new(8, 5, 0, 0), + EmulatorOptions { + scrollback_lines: 20, + ..Default::default() + }, + ); + emulator.advance(b"abcdefghneedle\r\n".repeat(30).as_slice()); + let options = SearchOptions { + regex: true, + ..Default::default() + }; + let mut scan = emulator + .search_with_options("^needle", options, SearchDirection::Stay, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + assert!(scan.refresh_retained(&emulator, None)); + assert_eq!(finish_scan(&emulator, &mut scan).unwrap(), initial); + emulator.advance(b"noise\r\n"); + let fresh = finish_options(&emulator, "^needle", options, SearchDirection::Stay, None).unwrap(); + assert_ne!(fresh.count, initial.count); + assert!(!scan.refresh_retained(&emulator, None)); + scan.restart(&emulator, None); + assert_eq!(finish_scan(&emulator, &mut scan).unwrap(), fresh); +} + +#[test] +fn live_eviction_can_rewind_a_regex_batch_against_the_same_selected_anchor() { + let mut emulator = scripted_history(650, 500); + let options = SearchOptions { + regex: true, + ..Default::default() + }; + let mut scan = emulator + .search_with_options("needl[e]", options, SearchDirection::Next, None) + .unwrap(); + finish_scan(&emulator, &mut scan).unwrap(); + let anchor = emulator.search_anchor(scan.navigation_match(&emulator, 7).unwrap().start); + emulator.advance(b"noise\r\n"); + assert!(scan.refresh_retained(&emulator, emulator.resolve_search_anchor(anchor))); + let SearchProgress::Work(work) = scan.step(&emulator, 4_096) else { + panic!("the refreshed tail must have regex work"); + }; + emulator.advance(b"needle\r\n"); + assert_eq!( + scan.accept_work(&emulator, work.run()), + SearchProgress::Invalidated + ); + let position = emulator.resolve_search_anchor(anchor); + assert!(scan.refresh_retained(&emulator, position)); + let result = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!( + result, + finish_options( + &emulator, + "needl[e]", + options, + SearchDirection::Stay, + position + ) + .unwrap() + ); + assert_eq!(result.ordinal, 5); +} + +#[test] +fn eviction_rejects_literal_queries_that_consume_hard_line_breaks() { + let mut emulator = scripted_history(80, 60); + emulator.advance(b"noise\r\n".repeat(30).as_slice()); + let mut scan = emulator + .search("needle suffix\nprefix", SearchDirection::Stay, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + assert!(initial.count > 0); + assert!(scan.refresh_retained(&emulator, None)); + assert_eq!(finish_scan(&emulator, &mut scan).unwrap(), initial); + emulator.advance(b"another line\r\n"); + assert!(!scan.refresh_retained(&emulator, None)); +} + +#[test] +fn refresh_falls_back_after_the_old_boundary_window_is_exhausted() { + let mut emulator = scripted_history(4_000, 3_000); + let mut scan = emulator + .search("needle", SearchDirection::Stay, None) + .unwrap(); + let first = finish_scan(&emulator, &mut scan).unwrap(); + emulator.advance(&b"noise\r\n".repeat(1_024)); + assert!(scan.refresh_retained(&emulator, None)); + assert_eq!( + finish_scan(&emulator, &mut scan).unwrap().count, + first.count - 1_024 + ); + emulator.advance(b"noise\r\n"); + assert!(!scan.refresh_retained(&emulator, None)); + scan.restart(&emulator, None); + assert_eq!( + finish_scan(&emulator, &mut scan).unwrap().count, + first.count - 1_025 + ); +} + +#[test] +fn refresh_counts_new_history_and_rechecks_edits_in_the_visible_rows() { + for regex in [false, true] { + let mut emulator = scripted_history(700, 500); + let options = SearchOptions { + regex, + ..Default::default() + }; + let query = if regex { "needl[e]" } else { "needle" }; + let mut scan = emulator + .search_with_options(query, options, SearchDirection::Stay, None) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + let anchor = emulator.search_anchor(scan.navigation_match(&emulator, 20).unwrap().start); + for (index, output) in [ + b"no match\r\n".as_slice(), + b"\x1b[1;1H\x1b[2Kneedle\x1b[24;1H", + b"needle\r\nnoise\r\n", + b"\x1b[2;1H\x1b[2Knone\x1b[24;1H", + ] + .into_iter() + .enumerate() + { + emulator.advance(output); + let position = emulator.resolve_search_anchor(anchor); + assert!(scan.refresh_retained(&emulator, position)); + let found = finish_scan(&emulator, &mut scan).unwrap(); + assert_eq!( + found, + finish_options(&emulator, query, options, SearchDirection::Stay, position).unwrap() + ); + assert_eq!(found.count, initial.count - [1, 1, 2, 3][index]); + } + } +} + +#[test] +fn sustained_regex_refresh_bounds_worker_batches_after_the_tail_enters_history() { + let mut emulator = Emulator::new( + TermSize::new(120, 25, 0, 0), + EmulatorOptions { + scrollback_lines: 500, + ..Default::default() + }, + ); + let row = b"2026-12-01T04:20:03 INFO connected pid=1000 prefix needle suffix for audit log\r\n"; + emulator.advance(&row.repeat(524)); + let mut scan = emulator + .search_with_options( + "needl[e]", + SearchOptions { + regex: true, + ..Default::default() + }, + SearchDirection::Stay, + None, + ) + .unwrap(); + let initial = finish_scan(&emulator, &mut scan).unwrap(); + for _ in 0..160 { + emulator.advance(row); + assert!(scan.refresh_retained(&emulator, None)); + assert_eq!(finish_scan(&emulator, &mut scan).unwrap(), initial); + } + emulator.advance(row); + assert!(scan.refresh_retained(&emulator, None)); + let mut batches = 0; + loop { + match scan.step(&emulator, 4_096) { + SearchProgress::Work(work) => { + batches += 1; + scan.accept_work(&emulator, work.run()); + } + SearchProgress::Searching => continue, + SearchProgress::Complete(result) => { + assert_eq!(result, initial); + break; + } + progress => panic!("unexpected search progress: {progress:?}"), + } + } + assert!( + batches <= 2, + "mutable viewport required {batches} regex batches" + ); +} diff --git a/crates/vt/src/shell_integration.rs b/crates/vt/src/shell_integration.rs index 04be00e1..7ce970b6 100644 --- a/crates/vt/src/shell_integration.rs +++ b/crates/vt/src/shell_integration.rs @@ -2,6 +2,27 @@ use std::path::PathBuf; +/// The shell-observation effect of a prepared submission, independent of its storage. +#[derive(Clone, Copy)] +pub enum ShellInput { + Empty, + Text, + LineBreak, +} + +impl ShellInput { + /// Classify before moving the bytes to the transport. Apply only after admission. + pub fn classify(bytes: &[u8]) -> Self { + match bytes { + [] => Self::Empty, + [b'\r' | b'\n'] => Self::LineBreak, + [_] => Self::Text, + _ if memchr::memchr2(b'\r', b'\n', bytes).is_some() => Self::LineBreak, + _ => Self::Text, + } + } +} + /// Observes bounded OSC 7 directory reports and OSC 133 shell prompt markers. /// /// Markers are observations of the byte stream, not authenticated authority to @@ -39,18 +60,36 @@ impl ShellIntegration { } /// Consumes output fragments; returns whether the reported directory changed. - pub fn advance(&mut self, bytes: &[u8]) -> bool { - let old = self.cwd.clone(); - for &byte in bytes { + pub fn advance(&mut self, mut bytes: &[u8]) -> bool { + let mut previous_cwd = None; + while let Some((&byte, rest)) = bytes.split_first() { + bytes = rest; match (self.state, byte) { (0, 0x1b) => self.state = 1, + (0, _) => { + // Dense ANSI output often has only a few bytes between escapes. + let (prefix, tail) = bytes.split_at(bytes.len().min(8)); + let escape = prefix + .iter() + .position(|byte| *byte == 0x1b) + .or_else(|| memchr::memchr(0x1b, tail).map(|index| prefix.len() + index)); + let Some(escape) = escape else { + break; + }; + bytes = &bytes[escape + 1..]; + self.state = 1; + } (1, b']') => { self.state = 2; self.payload.clear(); } (1, _) => self.state = 0, (2, 7) | (3, b'\\') => { - self.finish(); + if let Some(path) = self.finish() { + // Keep the directory from before this fragment for the final comparison. + let old = self.cwd.replace(path); + previous_cwd.get_or_insert(old); + } self.state = 0; } (2, 0x1b) => self.state = 3, @@ -70,13 +109,11 @@ impl ShellIntegration { _ => {} } } - self.cwd != old + previous_cwd.is_some_and(|old| self.cwd != old) } - fn finish(&mut self) { - let Ok(text) = std::str::from_utf8(&self.payload) else { - return; - }; + fn finish(&mut self) -> Option { + let text = std::str::from_utf8(&self.payload).ok()?; if matches!(text, "133;A" | "133;B" | "133;C" | "133;D") { self.known = true; } @@ -91,29 +128,29 @@ impl ShellIntegration { self.dirty_input = false; } _ => { - if let Some(uri) = text.strip_prefix("7;") { - let Some(rest) = uri.strip_prefix("file://") else { - return; - }; - let Some(slash) = rest.find('/') else { return }; - let host = &rest[..slash]; - if !host.is_empty() && host != "localhost" { - return; - } - if let Some(path) = decode(&rest[slash..]) { - self.cwd = Some(PathBuf::from(path)); - } + let rest = text.strip_prefix("7;file://")?; + let slash = rest.find('/')?; + let host = &rest[..slash]; + if !host.is_empty() && host != "localhost" { + return None; } + return decode(&rest[slash..]).map(PathBuf::from); } } + None } /// Records bytes only after the caller admits them to the original session. pub fn input(&mut self, bytes: &[u8]) { - if bytes.contains(&b'\r') || bytes.contains(&b'\n') { - self.at_prompt = false; - } else if !bytes.is_empty() { - self.dirty_input = true; + self.admit_input(ShellInput::classify(bytes)); + } + + /// Records a previously classified submission after admission. + pub fn admit_input(&mut self, input: ShellInput) { + match input { + ShellInput::Empty => {} + ShellInput::Text => self.dirty_input = true, + ShellInput::LineBreak => self.at_prompt = false, } } } @@ -202,6 +239,110 @@ mod tests { } } + #[test] + fn cwd_notification_reports_only_the_net_change_in_a_fragment() { + let mut shell = ShellIntegration::default(); + assert!(shell.advance(b"output\x1b]7;file:///home/a\x07")); + let mut output = vec![b'x'; 8192]; + output.extend_from_slice(b"\x1b[32m\x1b]7;file:///home/b\x07\x1b]7;file:///home/a\x1b\\"); + assert!(!shell.advance(&output)); + assert_eq!(shell.cwd(), Some(std::path::Path::new("/home/a"))); + assert!(!shell.advance(b"\x1b]7;file:///home//a\x07")); + assert_eq!(shell.cwd().unwrap().as_os_str(), "/home//a"); + assert!(!shell.advance(b"\x1b[0m more output\x1b")); + assert!(shell.advance(b"]7;file:///home/c\x07")); + assert_eq!(shell.cwd(), Some(std::path::Path::new("/home/c"))); + } + + #[test] + #[ignore = "manual release-mode performance measurement"] + fn measure_shell_observation_during_output() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + const PACKETS: u32 = 1_000; + let plain = vec![b'x'; 8192]; + let mut sparse_sgr = [b'x'; 128]; + sparse_sgr[..5].copy_from_slice(b"\x1b[32m"); + for (label, output) in [ + ("plain", plain), + ("sparse SGR", sparse_sgr.repeat(64)), + ("dense SGR", b"\x1b[32mx\x1b[0mabcdef".repeat(512)), + ] { + let mut shell = ShellIntegration::default(); + assert!(shell.advance(b"\x1b]7;file:///home/terminal\x07")); + let mut samples = [0; 31]; + for sample in &mut samples { + let start = Instant::now(); + for _ in 0..PACKETS { + assert!(!black_box(&mut shell).advance(black_box(&output))); + } + *sample = start.elapsed().as_nanos() / u128::from(PACKETS); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{label} ({} bytes): p50={} ns, p95={} ns per packet", + output.len(), + samples[15], + samples[29] + ) + .unwrap(); + assert_eq!(shell.cwd(), Some(std::path::Path::new("/home/terminal"))); + } + } + + #[test] + fn admitted_input_with_a_line_break_leaves_the_prompt_without_marking_it_dirty() { + let mut shell = ShellIntegration::default(); + shell.advance(b"\x1b]133;A\x07"); + shell.admit_input(ShellInput::classify(b"")); + assert_eq!(shell.prompt_state(), (Some(true), false)); + + let mut paste = vec![b'x'; 4096]; + for line_break in *b"\n\r" { + paste[4095] = line_break; + shell.admit_input(ShellInput::classify(&paste)); + assert_eq!(shell.prompt_state(), (Some(false), false)); + shell.advance(b"\x1b]133;A\x07"); + } + } + + #[test] + #[ignore = "manual release-mode performance measurement"] + fn measure_shell_input_observation() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let text = vec![b'x'; 3_300_000]; + let mut multiline = text.clone(); + multiline[3_299_999] = b'\n'; + for (bytes, iterations) in [ + (b"x".as_slice(), 100_000_u32), + (b"\r".as_slice(), 100_000), + (text.as_slice(), 100), + (multiline.as_slice(), 100), + ] { + let mut shell = ShellIntegration::default(); + let mut samples = [0; 31]; + for sample in &mut samples { + let start = Instant::now(); + for _ in 0..iterations { + black_box(&mut shell).input(black_box(bytes)); + } + *sample = start.elapsed().as_nanos(); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{} bytes, last byte {:#04x}: p50={:.2} ns, p95={:.2} ns per observation", + bytes.len(), + bytes[bytes.len() - 1], + samples[15] as f64 / f64::from(iterations), + samples[29] as f64 / f64::from(iterations), + ) + .unwrap(); + } + } + #[test] fn oversized_osc_cannot_smuggle_a_prompt_and_recovers_at_both_terminators() { for terminator in [b"\x07".as_slice(), b"\x1b\\".as_slice()] { diff --git a/crates/vt/src/text.rs b/crates/vt/src/text.rs index aa304eb9..2919c927 100644 --- a/crates/vt/src/text.rs +++ b/crates/vt/src/text.rs @@ -2,12 +2,12 @@ //! is not the user, such as an AI agent. use alacritty_terminal::{ - grid::Dimensions as _, + grid::{Dimensions as _, Grid}, index::{Column, Line}, - term::cell::Flags, + term::cell::{Cell, Flags}, }; -use alacritty_terminal::{grid::Grid, term::cell::Cell}; +const WIDE_SPACERS: Flags = Flags::WIDE_CHAR_SPACER.union(Flags::LEADING_WIDE_CHAR_SPACER); /// Borrowed terminal history and its exact lineage for one bounded read. pub(crate) struct TextReader<'a> { @@ -90,7 +90,8 @@ impl<'a> TextReader<'a> { } let number = (start.0..=end.0) .find_map(|row| { - grid[Line(row)][..] + let line = &grid[Line(row)]; + line[..Column(line.occupied_end())] .iter() .find_map(|cell| cell.logical_line()) }) @@ -151,12 +152,24 @@ impl<'a> TextReader<'a> { } fn rows_blank(&self, start: Line, end: Line) -> bool { - (start.0..=end.0).all(|row| self.row_text(Line(row), true).is_empty()) + (start.0..=end.0).all(|row| { + let line = &self.grid[Line(row)]; + line[..Column(line.occupied_end())].iter().all(|cell| { + cell.flags.intersects(WIDE_SPACERS | Flags::HIDDEN) + || (cell.c.is_whitespace() + && cell + .zerowidth() + .is_none_or(|marks| marks.iter().all(|mark| mark.is_whitespace()))) + }) + }) } /// The rows `start..=end` as one line, built from the end until it is /// longer than `room` bytes (the caller keeps only the end). fn join_rows(&self, start: Line, end: Line, room: usize) -> String { + if start == end { + return self.row_text(end, true); + } let mut parts = Vec::new(); let mut length = 0; let mut row = end; @@ -176,11 +189,14 @@ impl<'a> TextReader<'a> { /// earlier rows end where the line wrapped. fn row_text(&self, line: Line, last_row: bool) -> String { let mut text = String::new(); - for cell in &self.grid[line][..] { - if cell - .flags - .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) - { + let row = &self.grid[line]; + let end = if last_row { + row.occupied_end() + } else { + row.len() + }; + for cell in &row[..Column(end)] { + if cell.flags.intersects(WIDE_SPACERS) { continue; } if cell.flags.contains(Flags::HIDDEN) { @@ -235,6 +251,52 @@ mod tests { assert!(!tail.alt_screen); } + #[test] + fn trailing_hidden_and_unicode_blank_rows_are_omitted_but_combining_text_is_kept() { + let mut terminal = emulator(480, 6, 100); + terminal.advance("visible\r\n\u{a0}\x1b[8mhidden\x1b[28m\r\n".as_bytes()); + assert_eq!(terminal.text(query(100, 1024)).text, "visible"); + terminal.advance(" \u{301}\r\n".as_bytes()); + assert_eq!(terminal.text(query(100, 1024)).text, "visible\n\n \u{301}"); + } + + #[test] + #[ignore = "release performance fixture for bounded history reads"] + fn text_tail_sparse_history_profile() { + use std::{io::Write as _, time::Instant}; + + let mut terminal = emulator(260, 48, 10_000); + let line = "short synthetic terminal output"; + let packet = format!("{line}\r\n").repeat(100); + for _ in 0..100 { + terminal.advance_at(packet.as_bytes(), 1000); + } + for limit in [50, 500, 2_000, 9_000] { + let max_bytes = if limit <= 2_000 { + 64 * 1024 + } else { + 1024 * 1024 + }; + let expected = format!("{line}\n").repeat(limit - 1) + line; + let mut samples = Vec::with_capacity(31); + for _ in 0..31 { + let start = Instant::now(); + let tail = terminal.text(query(limit, max_bytes)); + samples.push(start.elapsed()); + assert_eq!(tail.text, expected); + assert!(tail.truncated); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "lines={limit} p50={:?} p95={:?}", + samples[15], + samples[29] + ) + .unwrap(); + } + } + #[test] fn spans_history_and_screen_and_drops_trailing_blanks() { let mut terminal = emulator(10, 2, 100); diff --git a/crates/vt/src/text_codec.rs b/crates/vt/src/text_codec.rs index db9a7be9..6974118b 100644 --- a/crates/vt/src/text_codec.rs +++ b/crates/vt/src/text_codec.rs @@ -1,4 +1,5 @@ //! Converts session text; transport and terminal protocol messages stay bytes. +use crate::{Modes, paste::encode_paste_with_enter}; use encoding_rs::{CoderResult, Decoder, Encoding}; use nocterm_session::{Charset, TextEncodingError}; @@ -39,6 +40,21 @@ impl TextCodec { } Ok(bytes.into_owned()) } + + /// Normalizes a paste using negotiated modes, then encodes it for the session. + pub fn encode_paste( + &self, + text: &str, + modes: Modes, + execute: bool, + ) -> Result, TextEncodingError> { + let bytes = encode_paste_with_enter(text, modes, execute); + if self.charset == Charset::Utf8 { + return Ok(bytes); + } + let text = std::str::from_utf8(&bytes).expect("paste wrapping preserves UTF-8"); + self.encode(text) + } } fn encoding(charset: Charset) -> &'static Encoding { @@ -67,6 +83,26 @@ mod tests { assert_eq!(codec.encode("plain text").unwrap(), b"plain text"); } + #[test] + fn paste_keeps_protocol_markers_and_encodes_text_for_the_session_charset() { + let codec = TextCodec::new(Charset::Windows1251); + let modes = Modes { + bracketed_paste: true, + ..Modes::default() + }; + assert_eq!( + codec.encode_paste("Привет\x1b[201~", modes, true).unwrap(), + b"\x1b[200~\xcf\xf0\xe8\xe2\xe5\xf2[201~\x1b[201~\r" + ); + assert_eq!( + codec + .encode_paste("🌙", modes, false) + .unwrap_err() + .charset(), + Charset::Windows1251 + ); + } + #[test] fn incomplete_utf8_is_buffered_and_replaced_only_when_finalized() { let mut codec = TextCodec::new(Charset::Utf8); diff --git a/crates/vt/tests/paste_cost.rs b/crates/vt/tests/paste_cost.rs new file mode 100644 index 00000000..7a1dc813 --- /dev/null +++ b/crates/vt/tests/paste_cost.rs @@ -0,0 +1,56 @@ +use nocterm_session::Charset; +use nocterm_vt::{Modes, TextCodec}; +use std::{hint::black_box, io::Write as _, time::Instant}; + +#[test] +fn large_utf8_paste_returns_one_exactly_sized_transport_buffer() { + let line = "á 🌙 selected history\r\n"; + let text = line.repeat(120_000); + let modes = Modes { + bracketed_paste: true, + ..Modes::default() + }; + let codec = TextCodec::new(Charset::Utf8); + let bytes = codec.encode_paste(&text, modes, true).unwrap(); + assert_eq!(&bytes[..6], b"\x1b[200~"); + assert_eq!(&bytes[6..6 + text.len()], text.as_bytes()); + assert_eq!(&bytes[6 + text.len()..], b"\x1b[201~\r"); + assert_eq!(bytes.capacity(), bytes.len()); +} + +#[test] +#[ignore = "run in release mode on a quiet host"] +fn measure_utf8_paste_across_sizes_modes_and_escape_density() { + let codec = TextCodec::new(Charset::Utf8); + for size in [1_024, 65_536, 3_300_017] { + for (label, line) in [ + ("multiline", "á 🌙 selected history\r\nline\n"), + ("ESC-dense", "\x1b[201~a\x1b\x1b!"), + ] { + let text = line.repeat(size / line.len()); + for bracketed_paste in [false, true] { + let modes = Modes { + bracketed_paste, + ..Modes::default() + }; + let mut times = [0; 41]; + for duration in &mut times { + let start = Instant::now(); + let bytes = + black_box(codec.encode_paste(black_box(&text), modes, false).unwrap()); + *duration = start.elapsed().as_nanos(); + assert!(!bytes.is_empty()); + } + times.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{} bytes, {label}, bracketed={bracketed_paste}, p50/p95 {} / {} ns", + text.len(), + times[20], + times[38] + ) + .unwrap(); + } + } + } +} diff --git a/crates/vt/tests/selection_cost.rs b/crates/vt/tests/selection_cost.rs new file mode 100644 index 00000000..694e4c64 --- /dev/null +++ b/crates/vt/tests/selection_cost.rs @@ -0,0 +1,128 @@ +use nocterm_vt::{Emulator, EmulatorOptions, MAX_SEARCH_QUERY, TermSize}; +use std::{hint::black_box, time::Instant}; + +fn select_history(rows: usize, columns: u16) -> (Emulator, String) { + let options = EmulatorOptions { + scrollback_lines: rows, + ..Default::default() + }; + let mut terminal = Emulator::new(TermSize::new(columns, 25, 8, 16), options); + let row = "á 🌙 selected history"; + let history = format!("{row}\r\n").repeat(rows); + terminal.advance(history.as_bytes()); + terminal.advance(b"last row"); + terminal.select_all(); + let expected = format!("{}last row", format!("{row}\n").repeat(rows)); + (terminal, expected) +} + +#[test] +fn selected_history_stays_available_and_copies_every_line() { + let (mut terminal, expected) = select_history(10_000, 120); + assert!(terminal.has_selection_text()); + assert_eq!( + terminal.selection_text().as_deref(), + Some(expected.as_str()) + ); + let query: String = expected.chars().take(MAX_SEARCH_QUERY + 1).collect(); + assert_eq!( + terminal.selected_search_query().as_deref(), + Some(query.as_str()) + ); + terminal.clear_selection(); + assert!(!terminal.has_selection_text()); + assert!(terminal.selected_search_query().is_none()); +} + +#[test] +fn widening_and_narrowing_preserve_selected_text_with_blank_columns() { + let (mut terminal, expected) = select_history(1_000, 500); + for columns in [32, 500, 96] { + terminal.resize(TermSize::new(columns, 25, 8, 16)); + terminal.select_all(); + assert_eq!( + terminal.selection_text().as_deref(), + Some(expected.as_str()) + ); + } +} + +#[test] +#[ignore = "run in release mode on a quiet host"] +fn measure_selection_availability_and_copy_across_history_sizes() { + use std::io::Write as _; + + for rows in [1_000, 10_000, 50_000] { + let (terminal, expected) = select_history(rows, 120); + assert!(terminal.has_selection_text()); + assert_eq!( + terminal.selection_text().as_deref(), + Some(expected.as_str()) + ); + let mut availability_ns = [0.0; 21]; + let mut copy_us = [0; 21]; + let mut query_ns = [0.0; 21]; + let expected_query: String = expected.chars().take(MAX_SEARCH_QUERY + 1).collect(); + for query in &mut query_ns { + let start = Instant::now(); + for _ in 0..1_000 { + black_box(black_box(&terminal).selected_search_query()); + } + *query = start.elapsed().as_nanos() as f64 / 1_000.; + } + assert_eq!( + terminal.selected_search_query().as_deref(), + Some(expected_query.as_str()), + ); + for (availability, copy) in availability_ns.iter_mut().zip(&mut copy_us) { + let start = Instant::now(); + for _ in 0..100_000 { + black_box(black_box(&terminal).has_selection_text()); + } + *availability = start.elapsed().as_nanos() as f64 / 100_000.; + let start = Instant::now(); + let copied = black_box(terminal.selection_text()).unwrap(); + *copy = start.elapsed().as_micros(); + assert_eq!(copied, expected); + } + availability_ns.sort_by(f64::total_cmp); + query_ns.sort_by(f64::total_cmp); + copy_us.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{rows} lines: availability p50/p95 {:.1}/{:.1} ns, query {:.1}/{:.1} ns, copy {}/{} µs", + availability_ns[10], + availability_ns[19], + query_ns[10], + query_ns[19], + copy_us[10], + copy_us[19], + ) + .unwrap(); + } +} + +#[test] +#[ignore = "run in release mode on a quiet host"] +fn measure_copy_of_short_rows_across_terminal_widths() { + use std::io::Write as _; + + for columns in [120, 300, 500] { + let (terminal, expected) = select_history(50_000, columns); + let mut copy_us = [0; 21]; + for copy in &mut copy_us { + let start = Instant::now(); + let copied = black_box(terminal.selection_text()).unwrap(); + *copy = start.elapsed().as_micros(); + assert_eq!(copied, expected); + } + copy_us.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{columns} columns, 50000 short rows, copy p50/p95 {}/{} µs", + copy_us[10], + copy_us[19], + ) + .unwrap(); + } +} diff --git a/crates/vt/tests/snapshot_cost.rs b/crates/vt/tests/snapshot_cost.rs new file mode 100644 index 00000000..c7e5714d --- /dev/null +++ b/crates/vt/tests/snapshot_cost.rs @@ -0,0 +1,81 @@ +use nocterm_vt::{ + CellPoint, Emulator, EmulatorOptions, Frame, SearchDirection, SearchProgress, SelectionKind, + Side, TermSize, +}; +use std::{hint::black_box, time::Instant}; + +#[test] +#[ignore = "run in release mode on a quiet host"] +fn measure_snapshots_of_sparse_and_dense_screens() { + use std::io::Write as _; + + for (columns, rows) in [(210, 80), (480, 90)] { + let sparse = format!("prompt\r\n\x1b[3;{columns}Hx"); + let dense = + format!("{}\r\n", "x".repeat(usize::from(columns) - 1)).repeat(usize::from(rows) - 1); + let alternate = format!("\x1b[?1049h\x1b[4m \x1b[0m{dense}"); + for (scenario, input) in [ + ("blank", ""), + ("sparse", sparse.as_str()), + ("dense", dense.as_str()), + ("colored erase", "\x1b[44m\x1b[2J"), + ("grown erase", "\x1b[44m\x1b[2J"), + ("search and selection", sparse.as_str()), + ("alternate screen", alternate.as_str()), + ] { + let initial_columns = if scenario == "grown erase" { + columns / 2 + } else { + columns + }; + let mut terminal = Emulator::new( + TermSize::new(initial_columns, rows, 8, 16), + EmulatorOptions::default(), + ); + terminal.advance(input.as_bytes()); + if initial_columns != columns { + terminal.resize(TermSize::new(columns, rows, 8, 16)); + } + if scenario == "search and selection" { + terminal.start_selection( + SelectionKind::Cells, + CellPoint { row: 1, col: 2 }, + Side::Left, + ); + assert!(terminal.update_selection( + CellPoint { + row: 4, + col: columns - 5 + }, + Side::Right, + )); + let mut scan = terminal + .search("prompt", SearchDirection::Next, None) + .unwrap(); + let SearchProgress::Complete(result) = scan.step(&terminal, 100_000) else { + panic!("the sparse viewport should fit the scan budget"); + }; + terminal.show_search_match(result.active.unwrap()); + } + let mut frame = Frame::default(); + for _ in 0..100 { + terminal.snapshot(black_box(&mut frame)); + } + + let mut samples = [0; 1024]; + for sample in &mut samples { + let start = Instant::now(); + black_box(&terminal).snapshot(black_box(&mut frame)); + *sample = start.elapsed().as_nanos(); + } + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{columns}x{rows} {scenario}, snapshot p50/p95 {} / {} ns", + samples[512], + samples[972], + ) + .unwrap(); + } + } +} diff --git a/crates/workspace-ports/src/connections.rs b/crates/workspace-ports/src/connections.rs index 1a40f30c..98b163cc 100644 --- a/crates/workspace-ports/src/connections.rs +++ b/crates/workspace-ports/src/connections.rs @@ -1,9 +1,8 @@ //! Only user-facing connection metadata crosses this boundary. -use gpui::{Image, SharedString}; +use gpui::{ImageSource, SharedString}; use nocterm_session::Target; -use std::sync::Arc; -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct ConnectionSummary { pub id: SharedString, pub name: SharedString, @@ -11,7 +10,21 @@ pub struct ConnectionSummary { pub description: SharedString, pub target: Target, /// The server's system icon, in its colour; none shows a generic server. - pub icon: Option>, + pub icon: Option, /// The flag of the server's country, once loaded. - pub flag: Option>, + pub flag: Option, +} + +impl std::fmt::Debug for ConnectionSummary { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ConnectionSummary") + .field("id", &self.id) + .field("name", &self.name) + .field("group", &self.group) + .field("description", &self.description) + .field("target", &self.target) + .field("has_icon", &self.icon.is_some()) + .field("has_flag", &self.flag.is_some()) + .finish() + } } diff --git a/crates/workspace/src/clock/settings.rs b/crates/workspace/src/clock/settings.rs index c43bcc48..0ad21980 100644 --- a/crates/workspace/src/clock/settings.rs +++ b/crates/workspace/src/clock/settings.rs @@ -1,6 +1,6 @@ //! The `[clock]` settings section: how the Clock widget writes the time. -use std::time::Duration; +use std::{fmt::Write as _, time::Duration}; use nocterm_core::clock::WallTime; use nocterm_settings::SettingsSection; @@ -61,26 +61,22 @@ const MONTHS: [&str; 12] = [ impl ClockSettings { /// The text for `time`: `09:05` by default, `Oct 24 9:05:07 PM` with every option on. pub fn render(&self, time: WallTime) -> String { + self.reading(time).render() + } + + /// Only the values that affect the displayed text, including the formatting options. + pub(super) fn reading(&self, time: WallTime) -> ClockReading { let (hour, minute, second) = time.local_hour_minute_second(); - let mut text = String::new(); - if self.date { - let (_, month, day) = time.local_date(); - text.push_str(&format!( - "{} {day} ", - MONTHS[usize::from(month.clamp(1, 12)) - 1] - )); - } - match self.format { - ClockFormat::Hour24 => text.push_str(&format!("{hour:02}:{minute:02}")), - ClockFormat::Hour12 => text.push_str(&format!("{}:{minute:02}", hour_on_dial(hour))), - } - if self.seconds { - text.push_str(&format!(":{second:02}")); + ClockReading { + format: self.format, + hour, + minute, + second: self.seconds.then_some(second), + date: self.date.then(|| { + let (_, month, day) = time.local_date(); + (month, day) + }), } - if self.format == ClockFormat::Hour12 { - text.push_str(if hour < 12 { " AM" } else { " PM" }); - } - text } /// How long the text of `time` stays right: to the next second with seconds on, else to the @@ -100,6 +96,48 @@ impl ClockSettings { } } +/// The complete display value. A clock step, zone change or format change is visible whenever +/// it changes any of these components; unchanged polls need not allocate or format text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ClockReading { + format: ClockFormat, + hour: u8, + minute: u8, + second: Option, + date: Option<(u8, u8)>, +} + +impl ClockReading { + pub(super) fn render(self) -> String { + let capacity = 5 + + 7 * usize::from(self.date.is_some()) + + 3 * usize::from(self.second.is_some()) + + 3 * usize::from(self.format == ClockFormat::Hour12); + let mut text = String::with_capacity(capacity); + let Self { hour, minute, .. } = self; + if let Some((month, day)) = self.date { + write!( + text, + "{} {day} ", + MONTHS[usize::from(month.clamp(1, 12)) - 1] + ) + .expect("writing to a String cannot fail"); + } + match self.format { + ClockFormat::Hour24 => write!(text, "{hour:02}:{minute:02}"), + ClockFormat::Hour12 => write!(text, "{}:{minute:02}", hour_on_dial(hour)), + } + .expect("writing to a String cannot fail"); + if let Some(second) = self.second { + write!(text, ":{second:02}").expect("writing to a String cannot fail"); + } + if self.format == ClockFormat::Hour12 { + text.push_str(if hour < 12 { " AM" } else { " PM" }); + } + text + } +} + /// The hour on a 12-hour dial: midnight and noon are 12. fn hour_on_dial(hour: u8) -> u8 { match hour % 12 { diff --git a/crates/workspace/src/clock/tests.rs b/crates/workspace/src/clock/tests.rs index ed2f7b32..081ca3ea 100644 --- a/crates/workspace/src/clock/tests.rs +++ b/crates/workspace/src/clock/tests.rs @@ -334,3 +334,102 @@ fn a_hand_edited_unknown_format_is_shown_as_the_default(cx: &mut TestAppContext) assert!(!settings.section_errors(cx).is_empty()); }); } + +#[gpui_kit::test] +#[ignore = "manual release profile of retained clock widgets and timer callbacks"] +fn measure_clock_view_polling(cx: &mut TestAppContext) { + use nocterm_core::clock::WallClock as _; + use nocterm_session::LocalShellSettings; + use std::{io::Write as _, time::Instant}; + + let count = std::env::var("NOCTERM_PROFILE_CLOCKS") + .map_or(Ok(64), |count| count.parse::()) + .unwrap(); + let clock = clock_at(NINE_FIVE, 0); + let settings = settings(cx); + cx.update(|cx| settings.register::(cx)); + let views: Vec<_> = (0..count) + .map(|_| view_over(&clock, &settings, cx)) + .collect(); + cx.run_until_parked(); + for mode in ["unrelated", "minute", "second"] { + restyle( + &settings, + ClockSettings { + format: ClockFormat::Hour12, + seconds: mode == "second", + date: true, + }, + cx, + ); + for sample in 0..7 { + let reads = clock.reads(); + let start = Instant::now(); + for i in 1..=120 { + if mode == "unrelated" { + let receipt = cx.update(|cx| { + settings.update::(cx, move |settings| { + settings.program = Some(format!("shell-{}", i % 2)); + }) + }); + cx.foreground_executor().block_test(receipt).unwrap(); + } else { + clock.set(WallTime { + unix_seconds: NINE_FIVE + i64::from(sample * 120 + i), + utc_offset_seconds: 0, + }); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + } + } + let elapsed = start.elapsed(); + let expected = + cx.update(|cx| settings.setting::(cx).render(clock.now())); + for view in &views { + assert_eq!(text(view, cx), expected); + } + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} clocks={count} reads={} elapsed_ns={}", + clock.reads() - reads, + elapsed.as_nanos(), + ) + .unwrap(); + } + } +} + +#[gpui_kit::test] +fn date_and_timezone_steps_change_the_shown_time_even_within_the_same_minute( + cx: &mut TestAppContext, +) { + let clock = clock_at(NINE_FIVE, 0); + let settings = settings(cx); + let view = view_over(&clock, &settings, cx); + restyle( + &settings, + ClockSettings { + date: true, + ..Default::default() + }, + cx, + ); + assert_eq!(text(&view, cx), "Jan 1 09:05"); + + clock.set(WallTime { + unix_seconds: NINE_FIVE + 86_400, + utc_offset_seconds: 0, + }); + cx.executor().advance_clock(Duration::from_secs(5)); + cx.run_until_parked(); + assert_eq!(text(&view, cx), "Jan 2 09:05"); + + // A zone change can step backwards across midnight without changing UTC. + clock.set(WallTime { + unix_seconds: NINE_FIVE + 86_400, + utc_offset_seconds: -10 * 3600, + }); + cx.executor().advance_clock(Duration::from_secs(5)); + cx.run_until_parked(); + assert_eq!(text(&view, cx), "Jan 1 23:05"); +} diff --git a/crates/workspace/src/clock/view.rs b/crates/workspace/src/clock/view.rs index 840fa58a..c8a2f64b 100644 --- a/crates/workspace/src/clock/view.rs +++ b/crates/workspace/src/clock/view.rs @@ -2,13 +2,13 @@ use std::{sync::Arc, time::Duration}; use gpui_kit::{ - Context, IntoElement, Render, Subscription, Task, TestSupportExt as _, Window, + Context, IntoElement, Render, SharedString, Subscription, Task, TestSupportExt as _, Window, component::ActiveTheme as _, div, prelude::*, }; use nocterm_core::clock::WallClock; use nocterm_store::SettingsHandle; -use super::settings::ClockSettings; +use super::settings::{ClockReading, ClockSettings}; /// The local time, written as `[clock]` says. It re-reads the clock when the text can change /// (each second with seconds on, else each minute boundary, never later than five seconds) for @@ -18,7 +18,8 @@ pub(crate) struct ClockView { clock: Arc, settings: SettingsHandle, style: ClockSettings, - shown: String, + reading: ClockReading, + shown: SharedString, timer: Task<()>, _follow: Subscription, } @@ -31,12 +32,14 @@ impl ClockView { cx: &mut Context, ) -> Self { let style = settings.setting::(cx).clone(); - let shown = style.render(clock.now()); + let reading = style.reading(clock.now()); + let shown = reading.render().into(); let this = cx.weak_entity(); - let follow = settings.observe(cx, move |cx| { + let follow = settings.observe_section::(cx, move |cx| { let _ = this.update(cx, |view, cx| view.restyle(cx)); }); Self { + reading, shown, timer: Self::arm(cx), clock, @@ -60,9 +63,10 @@ impl ClockView { /// Reads the clock, shows the time, and says how long until the text can change. fn read_clock(&mut self, cx: &mut Context) -> Duration { let time = self.clock.now(); - let shown = self.style.render(time); - if self.shown != shown { - self.shown = shown; + let reading = self.style.reading(time); + if self.reading != reading { + self.reading = reading; + self.shown = reading.render().into(); cx.notify(); } self.style.wait(time) @@ -83,7 +87,7 @@ impl ClockView { /// What the view shows. #[cfg(test)] pub(crate) fn text(&self) -> String { - self.shown.clone() + self.shown.to_string() } } diff --git a/crates/workspace/src/command_palette.rs b/crates/workspace/src/command_palette.rs index fad6f745..c43ab5e9 100644 --- a/crates/workspace/src/command_palette.rs +++ b/crates/workspace/src/command_palette.rs @@ -6,11 +6,10 @@ //! nocterm's own namespaces and runs the chosen one from the focus the //! palette was opened over, exactly as its shortcut would. use gpui_kit::{ - Action, App, AppContext as _, FocusHandle, ParentElement as _, SharedString, Styled as _, - Window, + Action, App, FocusHandle, ParentElement as _, SharedString, Styled as _, Window, component::{ ActiveTheme as _, WindowExt as _, - command::{Command, CommandItem, CommandState}, + command::{Command, CommandItem}, h_flex, kbd::Kbd, }, @@ -19,7 +18,6 @@ use gpui_kit::{ px, }; use nocterm_keymap::{humanize, offered}; -use std::rc::Rc; struct Entry { label: SharedString, @@ -58,53 +56,58 @@ pub fn init(cx: &mut App) { /// Opens the palette over the focused view. pub fn open(window: &mut Window, cx: &mut App) { let origin = window.focused(cx); - let entries = Rc::new(entries(window, cx)); - let state = cx.new(|cx| CommandState::new(window, cx)); - let width = px(560.); + let entries = entries(window, cx); + let command = Command::new_with_lazy_row_measurement(window, cx); + let docs = cx.action_documentation(); + let items = entries.iter().map(|entry| { + let label = entry.label.clone(); + let binding = entry.binding.clone(); + let name = entry.action.name(); + let description = docs.get(name).copied(); + let display_description = + description.map(|text| SharedString::from(text.trim_end_matches('.'))); + CommandItem::new() + .label(label.clone()) + .keywords([SharedString::from(name)]) + .keywords(description.map(SharedString::from)) + .child(move |_, cx| { + h_flex() + .w_full() + .gap_3() + .child(div().flex_1().min_w_0().truncate().child(label.clone())) + .when_some(display_description.clone(), |row, description| { + row.child( + div() + .max_w(px(220.)) + .truncate() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(description), + ) + }) + .children(binding.clone()) + }) + }); + let command = command + .items(items) + .placeholder("Run a command…") + .bordered(false) + .max_h(px(420.)); + let state = command + .on_confirm(move |index, window, cx| { + let Some(entry) = entries.get(index.row) else { + return; + }; + run(entry.action.boxed_clone(), origin.clone(), window, cx); + }) + .install(cx); let field = state.clone(); - window.open_dialog(cx, move |dialog, _, cx| { - let docs = cx.action_documentation(); - let items = entries.iter().map(|entry| { - let label = entry.label.clone(); - let binding = entry.binding.clone(); - let description = docs.get(entry.action.name()).copied(); - CommandItem::new() - .label(label.clone()) - .keywords([SharedString::from(entry.action.name())]) - .keywords(description.map(SharedString::from)) - .child(move |_, cx| { - h_flex() - .w_full() - .gap_3() - .child(div().flex_1().min_w_0().truncate().child(label.clone())) - .when_some(description, |row, description| { - row.child( - div() - .max_w(px(220.)) - .truncate() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(description.trim_end_matches('.').to_owned()), - ) - }) - .children(binding.clone()) - }) - }); - let confirm = entries.clone(); - let origin = origin.clone(); - dialog.w(width).p_0().close_button(false).child( - Command::new(&state) - .items(items.collect::>()) - .placeholder("Run a command…") - .bordered(false) - .max_h(px(420.)) - .on_confirm(move |index, window, cx| { - let Some(entry) = confirm.get(index.row) else { - return; - }; - run(entry.action.boxed_clone(), origin.clone(), window, cx); - }), - ) + window.open_dialog(cx, move |dialog, _, _| { + dialog + .w(px(560.)) + .p_0() + .close_button(false) + .child(state.clone()) }); // The dialog focuses itself as it opens; move focus into the search // field after that. diff --git a/crates/workspace/src/file_drag.rs b/crates/workspace/src/file_drag.rs index ffe883bc..2e6dd67d 100644 --- a/crates/workspace/src/file_drag.rs +++ b/crates/workspace/src/file_drag.rs @@ -3,17 +3,18 @@ use nocterm_session::{HostAddress, RemoteFs}; use std::{path::PathBuf, sync::Arc}; /// An internal file drag. Remote payloads retain their original connection so -/// switching tabs during a drag cannot redirect a transfer. +/// switching tabs during a drag cannot redirect a transfer. Rows can share +/// the immutable selection without copying the file paths during paint. #[derive(Clone)] pub enum FileDrag { - Local(Vec), + Local(Arc<[PathBuf]>), Remote(RemoteFileDrag), } /// Remote paths and the filesystem on which they exist. #[derive(Clone)] pub struct RemoteFileDrag { - pub sources: Vec, + pub sources: Arc<[String]>, pub host: HostAddress, pub fs: Arc, } diff --git a/crates/workspace/src/tab_groups.rs b/crates/workspace/src/tab_groups.rs index ed73d093..17a5737a 100644 --- a/crates/workspace/src/tab_groups.rs +++ b/crates/workspace/src/tab_groups.rs @@ -41,6 +41,8 @@ pub(crate) struct TabGroups { /// Where each member was when the groups were last gathered. A member /// without a place has just joined, so it follows rather than leads. last: HashMap, + /// The saved positions cover every member and all groups are contiguous. + settled: bool, } impl Default for TabGroups { @@ -50,11 +52,16 @@ impl Default for TabGroups { colors: BTreeMap::new(), member: HashMap::new(), last: HashMap::new(), + settled: true, } } } impl TabGroups { + pub(crate) fn is_empty(&self) -> bool { + self.member.is_empty() + } + pub(crate) fn group_of(&self, panel: P) -> Option { self.member.get(&panel).copied() } @@ -97,6 +104,7 @@ impl TabGroups { self.leave(panel); self.member.insert(panel, group); self.last.remove(&panel); + self.settled = false; } /// Takes `panel` out of its group. A group left with a single tab is @@ -106,6 +114,7 @@ impl TabGroups { return; }; self.last.remove(&panel); + self.settled = false; if self.members(group).count() < 2 { self.dissolve(group); } @@ -123,8 +132,10 @@ impl TabGroups { /// The moves that bring every group back together in `bars`, the dock's /// tab bars as they are now. Members no longer in any bar have closed /// and leave their group. - pub(crate) fn gather(&mut self, bars: &[(N, Vec

)]) -> Vec> { - let mut bars: Bars = bars.to_vec(); + pub(crate) fn gather(&mut self, mut bars: Bars) -> Vec> { + if self.same_positions(&bars) { + return Vec::new(); + } let gone: Vec

= self .member .keys() @@ -139,25 +150,53 @@ impl TabGroups { let groups: Vec = self.groups().collect(); // Gathering one group can split another it lands in; each pass // settles at least one, so as many passes as groups always suffice. + self.settled = false; for _ in 0..=groups.len() { let before = moves.len(); for group in &groups { self.gather_group(*group, &mut bars, &mut moves); } if moves.len() == before { + self.settled = true; break; } } - self.last = self - .member - .keys() - .filter_map(|panel| Some((*panel, locate(&bars, *panel)?))) - .map(|(panel, (bar, ix))| (panel, (bars[bar].0, ix))) + self.last = bars + .iter() + .flat_map(|(node, panels)| { + panels.iter().enumerate().filter_map(|(ix, panel)| { + self.member + .contains_key(panel) + .then_some((*panel, (*node, ix))) + }) + }) .collect(); moves } + fn same_positions(&self, bars: &[(N, Vec

)]) -> bool { + if !self.settled { + return false; + } + if self.last.is_empty() { + return true; + } + let mut found = 0; + for (node, panels) in bars { + for (ix, panel) in panels.iter().enumerate() { + if let Some(position) = self.last.get(panel) { + if *position != (*node, ix) { + return false; + } + found += 1; + } + } + } + // The dock places each panel at most once. Missing members must leave. + found == self.last.len() + } + fn gather_group(&self, group: GroupId, bars: &mut Bars, moves: &mut Vec>) { // Members where they are now, in display order. let mut spots: Vec<(P, usize, usize)> = self @@ -182,7 +221,7 @@ impl TabGroups { // The member that was moved leads: one that changed bars, else the // one displaced the furthest, else the leftmost. A newcomer never // leads, so joining brings a tab to its group, not the other way. - let (anchor, ..) = spots + let (anchor, bar, _) = spots .iter() .enumerate() .max_by_key(|(at, (panel, bar, ix))| { @@ -195,7 +234,7 @@ impl TabGroups { }) .map(|(_, spot)| *spot) .expect("a group of two has a member"); - let node = bars[locate(bars, anchor).expect("the anchor is in a bar").0].0; + let node = bars[bar].0; let lead = order .iter() .position(|panel| *panel == anchor) diff --git a/crates/workspace/src/tab_groups/tests.rs b/crates/workspace/src/tab_groups/tests.rs index 08c6b547..99e22f52 100644 --- a/crates/workspace/src/tab_groups/tests.rs +++ b/crates/workspace/src/tab_groups/tests.rs @@ -39,7 +39,7 @@ fn grouped(layout: &[(u8, &str)], members: &str) -> (TabGroups, Bars (TabGroups, Bars, layout: &[(u8, &str)]) -> Vec { let mut layout = bars(layout); - let moves = groups.gather(&layout); + let moves = groups.gather(layout.clone()); apply(&mut layout, &moves); assert!( - groups.gather(&layout).is_empty(), + groups.gather(layout.clone()).is_empty(), "a gathered layout is left alone" ); shown(&layout) @@ -109,7 +109,7 @@ fn a_group_gathered_into_another_pushes_that_one_aside() { let second = groups.create('x', PALETTE); groups.join('y', second); let mut layout = bars(&[(1, "abxy")]); - let moves = groups.gather(&layout); + let moves = groups.gather(layout.clone()); apply(&mut layout, &moves); // `b` dragged between `x` and `y`. let result = after(&mut groups, &[(1, "axby")]); @@ -123,7 +123,7 @@ fn a_group_gathered_into_another_pushes_that_one_aside() { fn closing_down_to_one_tab_ends_the_group() { let (mut groups, _) = grouped(&[(1, "abc")], "ab"); let group = groups.group_of('a').unwrap(); - groups.gather(&bars(&[(1, "ac")])); + groups.gather(bars(&[(1, "ac")])); assert_eq!(groups.group_of('a'), None); assert_eq!(groups.color(group), None); } diff --git a/crates/workspace/src/test_support.rs b/crates/workspace/src/test_support.rs index d47d3c45..f3656bf4 100644 --- a/crates/workspace/src/test_support.rs +++ b/crates/workspace/src/test_support.rs @@ -16,6 +16,7 @@ pub struct SessionProbe { focus: FocusHandle, spec: SessionSpec, connected: bool, + local: bool, fs: Option>, exec: Option>, generation: u64, @@ -48,6 +49,7 @@ impl SessionProbe { focus: cx.focus_handle(), spec, connected, + local: false, fs, exec: None, generation: 0, @@ -59,6 +61,13 @@ impl SessionProbe { pub fn title_reads(&self) -> usize { self.title_reads.get() } + /// Supplies the same terminal capability with local command identity. + pub fn set_local(&mut self, local: bool, cx: &mut Context) { + if self.local != local { + self.local = local; + cx.emit(ItemEvent::Changed); + } + } /// Supply structured execution without a native session in feature tests. pub fn set_executor( &mut self, @@ -249,7 +258,7 @@ impl TerminalState for ProbeState { source: None, source_current: true, title: probe.spec.title.clone(), - local: false, + local: probe.local, target: Some(probe.spec.target.clone()), profile: probe.spec.profile.clone(), status: if probe.connected { diff --git a/crates/workspace/src/tests.rs b/crates/workspace/src/tests.rs index e527661a..dc4691e2 100644 --- a/crates/workspace/src/tests.rs +++ b/crates/workspace/src/tests.rs @@ -20,6 +20,10 @@ mod local_directory; mod project_tabs; #[path = "tests/provider_resolution.rs"] mod provider_resolution; +#[path = "tests/tab_groups.rs"] +mod tab_groups; +#[path = "tests/tab_projection.rs"] +mod tab_projection; #[path = "tests/test_plugin.rs"] pub(super) mod test_plugin; diff --git a/crates/workspace/src/tests/close_scopes.rs b/crates/workspace/src/tests/close_scopes.rs index 6e956f1c..36340d5c 100644 --- a/crates/workspace/src/tests/close_scopes.rs +++ b/crates/workspace/src/tests/close_scopes.rs @@ -1,5 +1,6 @@ //! Close scopes follow the clicked native pane and visual order. use super::*; +use std::io::Write as _; #[gpui_kit::test] fn close_scopes_follow_reordered_pane_tabs_and_do_not_close_other_panes(cx: &mut TestAppContext) { @@ -57,3 +58,81 @@ fn close_scopes_follow_reordered_pane_tabs_and_do_not_close_other_panes(cx: &mut "native deferred removal must not close twice" ); } + +#[gpui_kit::test] +fn closing_other_tabs_preserves_the_neighboring_pane_and_focused_tab(cx: &mut TestAppContext) { + close_other_tabs_in_split(cx, 4); +} + +#[gpui_kit::test] +#[ignore = "release profile for Close Others beside a second populated pane"] +fn measure_close_others_in_two_dense_panes(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(96), |count| count.parse::()) + .unwrap(); + assert!(count >= 2); + let mut samples = std::array::from_fn::<_, 5, _>(|_| close_other_tabs_in_split(cx, count)); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "tabs_per_pane={count} close_others_p50={:?} close_others_max={:?}", + samples[2], + samples[4], + ) + .unwrap(); +} + +fn close_other_tabs_in_split(cx: &mut TestAppContext, count: usize) -> std::time::Duration { + let (window, workspace) = fixture(cx); + let closes = Rc::new(Cell::new(0)); + let (keep, neighbor_ids) = cx + .update_window(window, |_, window, cx| { + let left: Vec<_> = (0..count).map(|_| probe(cx, closes.clone())).collect(); + let right: Vec<_> = (0..count).map(|_| probe(cx, closes.clone())).collect(); + let keep = left[0].clone(); + let neighbor_ids: Vec<_> = right.iter().map(Entity::entity_id).collect(); + workspace.update(cx, |workspace, cx| { + for tab in left.into_iter().chain(right) { + let split = tab.entity_id() == neighbor_ids[0]; + workspace.add_item(tab, window, cx); + if split { + workspace.split_active(Placement::Right, window, cx); + } + } + assert!(workspace.activate_item_by_id(keep.entity_id(), window, cx)); + }); + window.render_frame(cx); + (keep, neighbor_ids) + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(window, |_, window, cx| { + let panes = workspace.read(cx).tab_panes(DockPlacement::Center, cx); + assert_eq!(panes[0].items().len(), count); + assert_eq!(panes[1].items(), neighbor_ids); + assert!(keep.read(cx).focus_handle(cx).is_focused(window)); + }) + .unwrap(); + + let started = std::time::Instant::now(); + cx.update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + workspace.close_tabs(keep.entity_id(), crate::TabCloseScope::Others, window, cx); + }); + }) + .unwrap(); + let elapsed = started.elapsed(); + cx.run_until_parked(); + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + let panes = workspace.read(cx).tab_panes(DockPlacement::Center, cx); + assert_eq!(panes.len(), 2); + assert_eq!(panes[0].items(), [keep.entity_id()]); + assert_eq!(panes[1].items(), neighbor_ids); + assert!(keep.read(cx).focus_handle(cx).is_focused(window)); + window.remove_window(); + }) + .unwrap(); + assert_eq!(closes.get(), count - 1); + elapsed +} diff --git a/crates/workspace/src/tests/tab_groups.rs b/crates/workspace/src/tests/tab_groups.rs new file mode 100644 index 00000000..c9238c58 --- /dev/null +++ b/crates/workspace/src/tests/tab_groups.rs @@ -0,0 +1,279 @@ +use super::*; +use std::io::Write as _; +use std::time::{Duration, Instant}; + +fn populate( + workspace: &Entity, + count: usize, + grouped: bool, + window: &mut Window, + cx: &mut App, +) -> Vec> { + let tabs: Vec<_> = (0..count) + .map(|_| { + let tab = probe(cx, Rc::default()); + workspace.update(cx, |workspace, cx| { + workspace.add_item(tab.clone(), window, cx); + }); + tab + }) + .collect(); + if grouped { + workspace.update(cx, |workspace, cx| { + for group in tabs.as_chunks::<4>().0 { + let first = group[0].entity_id(); + workspace.new_tab_group(first, window, cx); + for tab in &group[1..] { + workspace.group_tab_with(tab.entity_id(), first, window, cx); + } + } + }); + } + tabs +} + +fn activate(workspace: &Entity, tab: &Entity, window: &mut Window, cx: &mut App) { + workspace.update(cx, |workspace, cx| { + assert!(workspace.activate_item_by_id(tab.entity_id(), window, cx)); + }); +} + +#[gpui_kit::test] +fn activating_then_ungrouping_a_tab_preserves_focus_order_and_colors(cx: &mut TestAppContext) { + let (window, workspace) = fixture(cx); + let tabs = cx + .update_window(window, |_, window, cx| { + populate(&workspace, 8, true, window, cx) + }) + .unwrap(); + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + window.click(("tab-title", tabs[1].entity_id().as_u64()), cx); + }) + .unwrap(); + cx.update_window(window, |_, window, cx| { + let current = workspace.read(cx); + assert_eq!( + current.active_item(cx).unwrap().item_id(), + tabs[1].entity_id() + ); + assert!(tabs[1].read(cx).focus_handle(cx).is_focused(window)); + let colors: Vec<_> = current + .tabs(cx) + .iter() + .map(crate::TabSnapshot::group_color) + .collect(); + assert!(colors[0].is_some()); + assert!(colors[4].is_some()); + assert_ne!(colors[0], colors[4]); + assert_eq!( + colors, + [colors[0]; 4] + .into_iter() + .chain([colors[4]; 4]) + .collect::>() + ); + workspace.update(cx, |workspace, cx| { + workspace.ungroup_tab(tabs[1].entity_id(), window, cx) + }); + let current = workspace.read(cx); + let pane = ¤t.tab_panes(DockPlacement::Center, cx)[0]; + let ids = [0, 2, 3, 1, 4, 5, 6, 7].map(|index| tabs[index].entity_id()); + assert_eq!(pane.items(), ids); + assert_eq!( + current.active_item(cx).unwrap().item_id(), + tabs[1].entity_id() + ); + assert!(tabs[1].read(cx).focus_handle(cx).is_focused(window)); + let snapshots = current.tabs(cx); + assert_eq!(snapshots[1].group_color(), None); + assert_eq!(snapshots[2].group_color(), colors[0]); + assert_eq!(snapshots[4].group_color(), colors[4]); + }) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "release profile for tab activation with ordinary and densely grouped docks"] +fn measure_activation_and_draw_in_large_tab_bars(cx: &mut TestAppContext) { + let (window, workspace) = fixture(cx); + let grouped = std::env::var_os("NOCTERM_PROFILE_GROUPED_TABS").is_some(); + let size = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(96), |count| count.parse()) + .unwrap(); + let tabs = cx + .update_window(window, |_, window, cx| { + let tabs = populate(&workspace, size, grouped, window, cx); + window.render_frame(cx); + tabs + }) + .unwrap(); + let mut activation = [Duration::ZERO; 301]; + let mut draw = [Duration::ZERO; 301]; + for (index, (activate_time, draw_time)) in activation.iter_mut().zip(&mut draw).enumerate() { + let tab = &tabs[index % tabs.len()]; + let started = Instant::now(); + cx.update_window(window, |_, window, cx| { + activate(&workspace, tab, window, cx) + }) + .unwrap(); + *activate_time = started.elapsed(); + cx.update_window(window, |_, window, cx| { + let started = Instant::now(); + window.render_frame(cx); + *draw_time = started.elapsed(); + assert_eq!( + workspace.read(cx).active_item(cx).unwrap().item_id(), + tab.entity_id() + ); + assert!(tab.read(cx).focus_handle(cx).is_focused(window)); + }) + .unwrap(); + } + activation.sort_unstable(); + draw.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "tabs={size} grouped={grouped} activation_p50={:?} activation_p95={:?} draw_p50={:?} draw_p95={:?}", + activation[150], activation[285], draw[150], draw[285], + ) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "release profile for closing a grouped dock while checking focus-handle teardown"] +fn measure_closing_tab_batches_and_releasing_focus(cx: &mut TestAppContext) { + const BATCH_SIZE: usize = 4; + let (window, workspace) = fixture(cx); + let count = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(96), |count| count.parse::()) + .unwrap(); + assert!(count >= BATCH_SIZE * 2 && count.is_multiple_of(BATCH_SIZE)); + let (mut tabs, weak_handles) = cx + .update_window(window, |_, window, cx| { + let tabs = populate(&workspace, count, true, window, cx); + window.render_frame(cx); + let weak_handles: Vec<_> = tabs + .iter() + .map(|tab| tab.read(cx).focus_handle(cx).downgrade()) + .collect(); + (tabs, weak_handles) + }) + .unwrap(); + let mut close_samples = Vec::with_capacity(count / BATCH_SIZE); + + while !tabs.is_empty() { + let end = tabs.len(); + let start = end - BATCH_SIZE; + let started = Instant::now(); + tabs.truncate(start); + cx.update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + for index in (start..end).rev() { + workspace.close_item(index, window, cx); + } + }); + }) + .unwrap(); + close_samples.push(started.elapsed()); + cx.update_window(window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + assert_closed_tab_batch(cx, &workspace, &weak_handles[start..end], start); + } + + close_samples.sort_unstable(); + let median = close_samples[close_samples.len() / 2]; + let tail = close_samples[(close_samples.len() * 95).div_ceil(100) - 1]; + writeln!( + std::io::stdout().lock(), + "tabs={count} batch_size={BATCH_SIZE} close_batch_p50={median:?} close_batch_p95={tail:?}" + ) + .unwrap(); +} + +fn assert_closed_tab_batch( + cx: &mut TestAppContext, + workspace: &Entity, + closed: &[gpui_kit::WeakFocusHandle], + remaining: usize, +) { + cx.update(|cx| { + assert_eq!(workspace.read(cx).tabs(cx).len(), remaining); + assert!(closed.iter().all(|handle| handle.upgrade().is_none())); + }); +} + +#[gpui_kit::test] +fn closing_the_focused_tab_group_releases_its_members_and_focuses_the_survivor( + cx: &mut TestAppContext, +) { + close_focused_tab_group(cx, 4); +} + +#[gpui_kit::test] +#[ignore = "release profile for the native dock's Close Group command"] +fn measure_closing_a_large_tab_group(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(96), |count| count.parse::()) + .unwrap(); + assert!(count >= 2); + let mut samples = std::array::from_fn::<_, 9, _>(|_| close_focused_tab_group(cx, count)); + samples.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "grouped_tabs={count} close_group_p50={:?} close_group_p95={:?}", + samples[4], + samples[8], + ) + .unwrap(); +} + +fn close_focused_tab_group(cx: &mut TestAppContext, count: usize) -> Duration { + let (window, workspace) = fixture(cx); + let (survivor, group, weak_handles) = cx + .update_window(window, |_, window, cx| { + let mut tabs = populate(&workspace, count + 1, false, window, cx); + let survivor = tabs.remove(0); + let group = tabs[0].entity_id(); + workspace.update(cx, |workspace, cx| { + workspace.new_tab_group(group, window, cx); + for tab in &tabs[1..] { + workspace.group_tab_with(tab.entity_id(), group, window, cx); + } + }); + activate(&workspace, &tabs[count - 1], window, cx); + window.render_frame(cx); + assert!(tabs[count - 1].read(cx).focus_handle(cx).is_focused(window)); + let weak_handles: Vec<_> = tabs + .iter() + .map(|tab| tab.read(cx).focus_handle(cx).downgrade()) + .collect(); + (survivor, group, weak_handles) + }) + .unwrap(); + cx.run_until_parked(); + + let started = Instant::now(); + cx.update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + workspace.close_tab_group(group, window, cx) + }); + }) + .unwrap(); + let elapsed = started.elapsed(); + cx.update_window(window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + assert_closed_tab_batch(cx, &workspace, &weak_handles, 1); + cx.update_window(window, |_, window, cx| { + assert_eq!( + workspace.read(cx).active_item(cx).unwrap().item_id(), + survivor.entity_id() + ); + assert!(survivor.read(cx).focus_handle(cx).is_focused(window)); + window.remove_window(); + }) + .unwrap(); + elapsed +} diff --git a/crates/workspace/src/tests/tab_projection.rs b/crates/workspace/src/tests/tab_projection.rs new file mode 100644 index 00000000..4911c53c --- /dev/null +++ b/crates/workspace/src/tests/tab_projection.rs @@ -0,0 +1,191 @@ +use super::*; +use crate::{SessionSpec, test_support::SessionProbe}; +use std::io::Write as _; + +fn spec(index: usize) -> SessionSpec { + SessionSpec { + options: Default::default(), + title: format!("Terminal {index}").into(), + profile: None, + target: nocterm_session::Target::parse("user@example.test", None).unwrap(), + auth: Default::default(), + launch: None, + credential: None, + jumps: Vec::new(), + } +} + +fn populate( + workspace: &Entity, + count: usize, + window: &mut Window, + cx: &mut App, +) -> Vec> { + workspace.update(cx, |workspace, cx| { + let items: Vec<_> = (0..count) + .map(|index| { + let item = SessionProbe::new(spec(index), true, cx); + if index % 8 == 7 { + item.update(cx, |item, cx| item.set_local(true, cx)); + workspace.add_local_terminal(item.clone(), window, cx); + } else { + workspace.add_item(item.clone(), window, cx); + } + item + }) + .collect(); + for index in [4, 12, 24, 48] { + if let Some(item) = items.get(index) { + workspace.split_item(item.entity_id(), Placement::Right, window, cx); + } + } + assert!(workspace.activate_item_by_id(items[0].entity_id(), window, cx)); + items + }) +} + +#[gpui_kit::test] +#[ignore = "manual release profile of full tab and terminal projections"] +fn measure_workspace_tab_projections(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(128), |count| count.parse::()) + .unwrap(); + let (window, workspace) = fixture(cx); + let items = cx + .update_window(window, |_, window, cx| { + populate(&workspace, count, window, cx) + }) + .unwrap(); + cx.run_until_parked(); + for mode in ["terminals", "snapshots", "panes", "active"] { + for sample in 0..7 { + let start = std::time::Instant::now(); + cx.update(|cx| { + for _ in 0..128 { + let workspace = workspace.read(cx); + match mode { + "terminals" => { + assert_eq!(std::hint::black_box(workspace.terminals(cx)).len(), count) + } + "snapshots" => { + assert_eq!(std::hint::black_box(workspace.tabs(cx)).len(), count) + } + "panes" => assert_eq!( + std::hint::black_box(workspace.tab_panes(DockPlacement::Center, cx)) + .iter() + .map(|pane| pane.items().len()) + .sum::() + + workspace + .tab_panes(DockPlacement::Bottom, cx) + .iter() + .map(|pane| pane.items().len()) + .sum::(), + count + ), + _ => assert_eq!( + std::hint::black_box(workspace.active_terminal(cx)), + Some(items[0].entity_id()) + ), + } + } + }); + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} tabs={count} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); + } + } +} + +#[gpui_kit::test] +fn projections_keep_native_pane_membership_alias_and_background_identity(cx: &mut TestAppContext) { + let (window, workspace) = fixture(cx); + let items = cx + .update_window(window, |_, window, cx| populate(&workspace, 16, window, cx)) + .unwrap(); + let background = cx + .update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + let item = SessionProbe::new(spec(16), true, cx); + workspace.add_background_item(item.clone(), window, cx); + workspace.rename_active_tab(window, cx); + item + }) + }) + .unwrap(); + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + window.press("ctrl-a", cx); + window.input("Renamed", cx); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + let ws = workspace.read(cx); + let terminals = ws.terminals(cx); + assert_eq!(terminals.len(), 17); + assert_eq!(terminals[0].item, items[0].entity_id()); + assert_eq!(terminals[0].title.as_ref(), "Renamed"); + assert!(terminals[0].active); + assert_eq!(ws.active_terminal(cx), Some(items[0].entity_id())); + assert!( + terminals + .iter() + .find(|entry| entry.item == items[7].entity_id()) + .unwrap() + .bottom + ); + assert!(terminals.last().unwrap().background); + assert_eq!(terminals.last().unwrap().item, background.entity_id()); + let tabs = ws.tabs(cx); + assert_eq!(tabs[0].alias(), Some("Renamed")); + assert_pane_locations(ws, &tabs, cx); + }); + cx.update_window(window, |_, window, cx| { + workspace.update(cx, |workspace, cx| { + assert!(workspace.show_background_session(background.entity_id(), window, cx)); + workspace.toggle_local_terminal(window, cx); + }) + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + let ws = workspace.read(cx); + let terminals = ws.terminals(cx); + let promoted = terminals + .iter() + .find(|entry| entry.item == background.entity_id()) + .unwrap(); + assert!(!promoted.background); + assert!(promoted.active); + assert_eq!(ws.active_terminal(cx), Some(background.entity_id())); + assert!( + terminals + .iter() + .find(|entry| entry.item == items[7].entity_id()) + .unwrap() + .bottom + ); + assert!( + !ws.tabs(cx) + .iter() + .find(|tab| tab.id() == items[7].entity_id()) + .unwrap() + .is_visible() + ); + }); +} + +fn assert_pane_locations(ws: &Workspace, tabs: &[crate::TabSnapshot], cx: &App) { + for placement in [DockPlacement::Center, DockPlacement::Bottom] { + for pane in ws.tab_panes(placement, cx) { + for item in pane.items() { + let tab = tabs.iter().find(|tab| tab.id() == *item).unwrap(); + assert_eq!(tab.location(), Some((placement, pane.node()))); + } + } + } +} diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index add871af..83d23919 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -119,6 +119,8 @@ pub enum WorkspaceEvent { ConnectionsChanged, /// A panel group was shown or hidden. PanelVisibilityChanged, + /// Selection or layout changed which panel a shown group presents. + PanelSelectionChanged, /// A toolbar was shown, hidden or moved to another edge; [`Workspace::toolbar_edge`] tells /// where each is now. ToolbarsChanged, diff --git a/crates/workspace/src/workspace/chrome/empty_state/tests.rs b/crates/workspace/src/workspace/chrome/empty_state/tests.rs index 0ff5638b..c56beb23 100644 --- a/crates/workspace/src/workspace/chrome/empty_state/tests.rs +++ b/crates/workspace/src/workspace/chrome/empty_state/tests.rs @@ -58,7 +58,7 @@ fn connection(index: usize) -> ConnectionSummary { flag: Some(Arc::new(Image::from_bytes( ImageFormat::Svg, b"".to_vec(), - ))), + )).into()), } } diff --git a/crates/workspace/src/workspace/composition.rs b/crates/workspace/src/workspace/composition.rs index d6df0a37..e06ceae0 100644 --- a/crates/workspace/src/workspace/composition.rs +++ b/crates/workspace/src/workspace/composition.rs @@ -282,9 +282,8 @@ impl Workspace { } if self.shell.claim_open(&opened) && let Some(transition) = self.panels.reveal_panel(&opened) - && transition.visibility_changed().is_some() { - cx.emit(WorkspaceEvent::PanelVisibilityChanged); + Self::emit_panel_changes(&transition, cx); } self.sync_panel_sides(cx); cx.notify(); diff --git a/crates/workspace/src/workspace/interaction.rs b/crates/workspace/src/workspace/interaction.rs index 2425039c..78a60376 100644 --- a/crates/workspace/src/workspace/interaction.rs +++ b/crates/workspace/src/workspace/interaction.rs @@ -312,9 +312,7 @@ impl Workspace { window: &mut Window, cx: &mut Context, ) { - if transition.visibility_changed().is_some() { - cx.emit(WorkspaceEvent::PanelVisibilityChanged); - } + Self::emit_panel_changes(&transition, cx); match transition.into_focus() { PanelFocus::Preserve => {} PanelFocus::Panel(focus) => window.focus(&focus, cx), @@ -333,6 +331,14 @@ impl Workspace { } cx.notify(); } + pub(super) fn emit_panel_changes(transition: &PanelTransition, cx: &mut Context) { + if transition.visibility_changed().is_some() { + cx.emit(WorkspaceEvent::PanelVisibilityChanged); + } + if transition.selection_changed() { + cx.emit(WorkspaceEvent::PanelSelectionChanged); + } + } pub(super) fn widen_group( &mut self, group: GroupKey, diff --git a/crates/workspace/src/workspace/layout_switch_tests.rs b/crates/workspace/src/workspace/layout_switch_tests.rs index 7d9bfce9..f2512f68 100644 --- a/crates/workspace/src/workspace/layout_switch_tests.rs +++ b/crates/workspace/src/workspace/layout_switch_tests.rs @@ -585,3 +585,112 @@ fn an_edit_made_before_any_switch_reaches_both_windows(cx: &mut TestAppContext) assert!(!is_open(cx, window, PANEL_A)); } } + +#[gpui_kit::test] +#[ignore = "manual release profile of shared layout publication across windows"] +fn measure_window_layout_publications(cx: &mut TestAppContext) { + use nocterm_session::LocalShellSettings; + use std::io::Write as _; + + let count = std::env::var("NOCTERM_PROFILE_WINDOWS") + .map_or(Ok(16), |count| count.parse::()) + .unwrap(); + let presets = std::env::var("NOCTERM_PROFILE_PRESETS") + .map_or(Ok(32), |count| count.parse::()) + .unwrap(); + let layouts = layouts_of( + (1..=presets) + .map(|i| { + preset( + &format!("p{i}"), + &format!("Layout {i}"), + &["test.panel-a"], + &["test.panel-a", "test.panel-b"], + &["test.expandable"], + ) + }) + .collect(), + ); + let mut document = SettingsDocument::default(); + document.register::(); + let Windows { + handle, + workspace, + settings, + } = windows_over(cx, document, Some(layouts), false); + let mut windows = vec![(handle, workspace)]; + windows.extend((1..count).map(|_| another_window(cx, &settings))); + for (handle, workspace) in &windows { + register_all(cx, *handle, workspace); + } + cx.run_until_parked(); + for mode in ["unrelated", "selection"] { + for sample in 0..7 { + let start = std::time::Instant::now(); + for i in 0..32 { + let receipt = cx.update(|cx| { + if mode == "unrelated" { + settings.update::(cx, move |settings| { + settings.program = Some(format!("shell-{}", i % 2)); + }) + } else { + settings.update::(cx, move |layouts| { + layouts.active = + Some(pid(if i % 2 == 0 { "swapped" } else { "default" })); + }) + } + }); + cx.foreground_executor().block_test(receipt).unwrap(); + } + writeln!( + std::io::stdout().lock(), + "mode={mode} sample={sample} windows={count} presets={presets} elapsed_ns={}", + start.elapsed().as_nanos() + ) + .unwrap(); + } + for (_, workspace) in &windows { + assert_eq!(selected(cx, workspace), "default"); + } + } +} + +#[gpui_kit::test] +fn atomic_layout_and_enablement_publication_reaches_every_window(cx: &mut TestAppContext) { + use nocterm_plugin_enablement::PluginEnablement; + + let Windows { + handle, + workspace, + settings, + } = windows(cx); + let (other_handle, other) = another_window(cx, &settings); + register_all(cx, handle, &workspace); + register_all(cx, other_handle, &other); + switch(cx, handle, &workspace, "p1").unwrap(); + let receipt = cx.update(|cx| { + settings.edit(cx, |document| { + document.update::(|layouts| layouts.active = Some(pid("p2"))); + document.update::(|plugins| { + plugins.disabled.push(TEST_PLUGIN.id.clone()) + }); + }) + }); + cx.foreground_executor().block_test(receipt).unwrap(); + for window in [&workspace, &other] { + assert_eq!(selected(cx, window), "p2"); + assert!(open_panels(cx, window).is_empty()); + cx.update(|cx| assert!(!window.read(cx).panel_is_enabled(&PANEL_B.id))); + } + let receipt = cx.update(|cx| { + settings.edit(cx, |document| { + document.update::(|layouts| layouts.active = Some(pid("p1"))); + document.update::(|plugins| plugins.disabled.clear()); + }) + }); + cx.foreground_executor().block_test(receipt).unwrap(); + for window in [&workspace, &other] { + assert_eq!(selected(cx, window), "p1"); + assert_eq!(open_panels(cx, window), [PANEL_A.title]); + } +} diff --git a/crates/workspace/src/workspace/panel_groups.rs b/crates/workspace/src/workspace/panel_groups.rs index 69338fc6..250c3f56 100644 --- a/crates/workspace/src/workspace/panel_groups.rs +++ b/crates/workspace/src/workspace/panel_groups.rs @@ -354,11 +354,18 @@ impl PanelGroups { let member = *self.group(key).members().get(ix)?; let slot = self.slot(Some(member)).filter(|slot| slot.offered())?; let focus = slot.panel.as_ref()?.focus_handle(cx); - let revealed = self.group_mut(key).select(member); - Some(PanelTransition::new( - revealed.then_some(key), - PanelFocus::Panel(focus), - )) + Some(self.select(key, member, PanelFocus::Panel(focus))) + } + + fn select(&mut self, key: GroupKey, member: PanelKey, focus: PanelFocus) -> PanelTransition { + let group = self.group_mut(key); + let previous = group.shown_member(); + let revealed = group.select(member); + if !revealed && previous != Some(member) { + PanelTransition::new_selection(focus) + } else { + PanelTransition::new(revealed.then_some(key), focus) + } } /// Shows a hidden group or hides a shown one. @@ -571,11 +578,7 @@ impl PanelGroups { Some(ix) if self.group(key).showing(ix) => {} Some(ix) => { if let Some(member) = self.group(key).members().get(ix).copied() { - let revealed = self.group_mut(key).select(member); - transitions.push(PanelTransition::new( - revealed.then_some(key), - PanelFocus::Preserve, - )); + transitions.push(self.select(key, member, PanelFocus::Preserve)); } } None if self.group(key).is_shown() => { @@ -596,6 +599,7 @@ impl PanelGroups { window: &Window, cx: &mut App, ) -> Vec { + let shown_before: Vec<_> = self.groups.iter().map(PanelGroup::shown_member).collect(); self.adopt(layout); let mut transitions = open .map(|open| self.set_open(open, window, cx)) @@ -608,17 +612,23 @@ impl PanelGroups { for id in stray { transitions.extend(self.toggle_panel(&id, window, cx)); } + // Adoption can implicitly replace a group member without a focus transition. + if !transitions + .iter() + .any(|change| change.visibility_changed().is_some() || change.selection_changed()) + && self.groups.iter().any(|group| { + shown_before.get(group.key().index()).copied().flatten() != group.shown_member() + }) + { + transitions.push(PanelTransition::new_selection(PanelFocus::Preserve)); + } transitions } /// Shows one panel without taking focus; used while a window composes its panels. pub(super) fn reveal_panel(&mut self, id: &ContributionId) -> Option { let (key, panel, _) = self.position_of(id)?; self.slot(Some(panel)).filter(|slot| slot.offered())?; - let revealed = self.group_mut(key).select(panel); - Some(PanelTransition::new( - revealed.then_some(key), - PanelFocus::Preserve, - )) + Some(self.select(key, panel, PanelFocus::Preserve)) } pub(super) fn set_panel_available( &mut self, diff --git a/crates/workspace/src/workspace/panel_groups/group.rs b/crates/workspace/src/workspace/panel_groups/group.rs index 2633298f..28af543e 100644 --- a/crates/workspace/src/workspace/panel_groups/group.rs +++ b/crates/workspace/src/workspace/panel_groups/group.rs @@ -46,6 +46,9 @@ impl PanelGroup { pub(super) fn is_shown(&self) -> bool { self.shown } + pub(super) fn shown_member(&self) -> Option { + if self.shown { self.selected } else { None } + } pub(super) fn is_expanded(&self) -> bool { self.expanded } diff --git a/crates/workspace/src/workspace/panel_groups/tests.rs b/crates/workspace/src/workspace/panel_groups/tests.rs index 110882d7..48221b3d 100644 --- a/crates/workspace/src/workspace/panel_groups/tests.rs +++ b/crates/workspace/src/workspace/panel_groups/tests.rs @@ -270,6 +270,7 @@ mod owner { assert!(!groups.panel_is_open(&id(PANEL_B))); let transition = groups.activate(GroupKey::NAVIGATION, 1, cx).unwrap(); assert_eq!(transition.visibility_changed(), None); + assert!(transition.selection_changed()); assert_eq!(focused_panel(transition), second.focus_handle(cx)); assert!(!groups.panel_is_open(&id(PANEL_A))); assert!(groups.panel_is_open(&id(PANEL_B))); @@ -561,8 +562,16 @@ mod owner { with_window(cx, |window, cx| { let (mut groups, [_, second, _]) = shell(window, cx); groups.set_panel_available(&assistant_id(), true, window, cx); + groups.open_panel(&id(PANEL_B), cx).unwrap(); let moved = LayoutPreset { bar: Bar { + left: vec![BarItem::Group { + id: GroupId::new("navigation"), + name: None, + side: None, + primary: true, + members: vec![GroupEntry::Panel(id(PANEL_A))], + }], right: vec![BarItem::Group { id: GroupId::new("assistant"), name: None, @@ -580,7 +589,15 @@ mod owner { let catalog = nocterm_plugin_model::PluginSet::from( crate::plugin::catalog(&[TEST_CORE], &[&TEST_PLUGIN]).expect("valid"), ); - groups.adopt(&resolve(&moved, &catalog, &BTreeSet::new())); + let changes = groups.follow( + &resolve(&moved, &catalog, &BTreeSet::new()), + None, + window, + cx, + ); + assert!(changes.iter().any(PanelTransition::selection_changed)); + assert!(groups.panel_is_open(&id(PANEL_A))); + assert!(!groups.panel_is_open(&id(PANEL_B))); let (host, ix, _) = groups.offered(&id(PANEL_B)).expect("offered"); assert_eq!((host, ix), (GroupKey::ASSISTANT, 0)); let (host, ix, _) = groups.offered(&assistant_id()).expect("offered"); diff --git a/crates/workspace/src/workspace/panel_groups/transition.rs b/crates/workspace/src/workspace/panel_groups/transition.rs index 6e75756a..a11ea080 100644 --- a/crates/workspace/src/workspace/panel_groups/transition.rs +++ b/crates/workspace/src/workspace/panel_groups/transition.rs @@ -16,21 +16,36 @@ pub(in crate::workspace) enum PanelFocus { ActiveItem, } -/// The effect of one group transition: which group became visible or hidden, and -/// where focus goes. The workspace applies it after the owner has committed. +/// The effect of one group transition: visibility, the presented member, and focus. +/// The workspace applies it after the owner has committed. pub(in crate::workspace) struct PanelTransition { visibility: Option, + selection_changed: bool, focus: PanelFocus, } impl PanelTransition { pub(super) fn new(visibility: Option, focus: PanelFocus) -> Self { - Self { visibility, focus } + Self { + visibility, + selection_changed: false, + focus, + } + } + pub(super) fn new_selection(focus: PanelFocus) -> Self { + Self { + selection_changed: true, + ..Self::new(None, focus) + } } /// The group that was shown or hidden, if one was. pub(in crate::workspace) fn visibility_changed(&self) -> Option { self.visibility } + /// A change in which panel is shown while applying a selection or layout. + pub(in crate::workspace) fn selection_changed(&self) -> bool { + self.selection_changed + } pub(in crate::workspace) fn into_focus(self) -> PanelFocus { self.focus } diff --git a/crates/workspace/src/workspace/queries.rs b/crates/workspace/src/workspace/queries.rs index 351c9217..61f1412f 100644 --- a/crates/workspace/src/workspace/queries.rs +++ b/crates/workspace/src/workspace/queries.rs @@ -14,23 +14,21 @@ impl Workspace { let session = inner.tabs().active_session(); let local = inner .content() - .terminals(cx) - .into_iter() - .find(|entry| entry.active) - .and_then(|entry| entry.capabilities.state().info(cx)) + .active_terminal(cx) + .and_then(|(_, capabilities)| capabilities.state().info(cx)) .is_some_and(|info| info.local); let general = source.context() == nocterm_project_model::ContextId::General; let local = local || general && session.is_none() && inner.tabs().active_handle().is_none(); - let target = self - .surfaces - .outer() - .read(cx) - .tabs() - .active_project() - .and_then(|project| project.monitor_target(cx)); if general { crate::MonitorSource::general(source.surface_id(), session, local) } else { + let target = self + .surfaces + .outer() + .read(cx) + .tabs() + .active_project() + .and_then(|project| project.monitor_target(cx)); crate::MonitorSource::project(source.surface_id(), target, session, local) } } @@ -41,10 +39,8 @@ impl Workspace { let inner = surface.read(cx); let local = inner .content() - .terminals(cx) - .into_iter() - .find(|entry| entry.active) - .and_then(|entry| entry.capabilities.state().info(cx)) + .active_terminal(cx) + .and_then(|(_, capabilities)| capabilities.state().info(cx)) .is_some_and(|info| info.local); return Some(match (inner.root(), inner.tabs().active_session()) { (Some(root), _) if local => crate::ExplorerSource::local_folder(id, root), @@ -118,12 +114,7 @@ impl Workspace { } pub fn items(&self, cx: &App) -> impl Iterator> { - self.surfaces - .outer() - .read(cx) - .tabs() - .central_handles() - .into_iter() + self.surfaces.outer().read(cx).tabs().central_handles() } pub fn active_item(&self, cx: &App) -> Option> { self.surfaces.outer().read(cx).tabs().active_handle() @@ -320,10 +311,14 @@ impl Workspace { .title(self.command_item(window, cx)?.item_id(), cx) } pub fn active_terminal(&self, cx: &App) -> Option { - self.terminals(cx) - .into_iter() - .find(|entry| entry.active) - .map(|entry| entry.item) + self.surfaces + .window() + .resolve(self.context_source(cx), cx) + .ok()? + .read(cx) + .content() + .active_terminal(cx) + .map(|(id, _)| id) } pub fn terminals(&self, cx: &App) -> Vec { self.context_terminals(self.context_source(cx), cx) diff --git a/crates/workspace/src/workspace/shell_layout.rs b/crates/workspace/src/workspace/shell_layout.rs index c0886ab3..24f5a2ac 100644 --- a/crates/workspace/src/workspace/shell_layout.rs +++ b/crates/workspace/src/workspace/shell_layout.rs @@ -8,6 +8,7 @@ //! chose a layout. use std::{ + cell::Cell, collections::{BTreeSet, HashSet}, rc::Rc, sync::Arc, @@ -74,7 +75,7 @@ pub(super) struct ShellLayout { /// The plugins in force when the arrangement was last resolved. set: Arc, legacy_swapped: bool, - seen: LayoutSettings, + seen: Arc, /// The plugins the arrangement leaves out: the stored ones the catalog allows to be off. disabled: BTreeSet, selected: PresetId, @@ -94,7 +95,7 @@ impl ShellLayout { settings.register::(cx); settings.register::(cx); let legacy_swapped = super::layout_edit::legacy_layout_swapped(flags, cx); - let seen = settings.setting::(cx).clone(); + let seen = settings.document(cx).section_snapshot::(); let set = source.current(cx); let disabled = disabled_in(&settings, &set, cx); let selected = select(&seen, legacy_swapped); @@ -118,8 +119,25 @@ impl ShellLayout { /// as the window lives. pub(super) fn follow(&mut self, cx: &mut App, on_change: impl Fn(&mut App) + Clone + 'static) { let plugins = self.source.observe(Box::new(on_change.clone()), cx); - let settings = self.settings.observe(cx, on_change); - self.subscription = Some(Subscription::join(settings, plugins)); + // Two sections can change in the same publication. Apply the complete document once. + let seen_revision = Rc::new(Cell::new(self.settings.revision(cx))); + let settings = self.settings.clone(); + let published = move |cx: &mut App| { + let revision = settings.revision(cx); + if seen_revision.replace(revision) != revision { + on_change(cx); + } + }; + let layouts = self + .settings + .observe_section::(cx, published.clone()); + let enablement = self + .settings + .observe_section::(cx, published); + self.subscription = Some(Subscription::join( + Subscription::join(layouts, enablement), + plugins, + )); } /// Reads the settings again and tells how the change affects the window. @@ -128,23 +146,31 @@ impl ShellLayout { /// the arrangement, never a switch: panels that stay keep their state and no `open` set /// applies. pub(super) fn refresh(&mut self, cx: &App) -> LayoutChange { - let next = self.settings.setting::(cx); + let next = self + .settings + .document(cx) + .section_snapshot::(); let set = self.source.current(cx); let disabled = disabled_in(&self.settings, &set, cx); - let layouts_changed = *next != self.seen; + let layouts_changed = !Arc::ptr_eq(&next, &self.seen) && next != self.seen; let enablement_changed = disabled != self.disabled || !Arc::ptr_eq(&set, &self.set); if !layouts_changed && !enablement_changed { return LayoutChange::Unchanged; } self.set = set; let change = if layouts_changed { - transition(&self.seen, next, self.legacy_swapped) + transition(&self.seen, &next, self.legacy_swapped) } else { LayoutTransition::None }; if layouts_changed { - report_ignored_primary(next, Some(&self.seen), &self.set); - self.seen = next.clone(); + report_ignored_primary(&next, Some(&self.seen), &self.set); + } + self.seen = next; + if change == LayoutTransition::None && !enablement_changed { + // Renaming a preset or editing an unselected one changes the menu, not the + // window arrangement. Retain the current resolution. + return LayoutChange::Unchanged; } self.disabled = disabled; self.selected = select(&self.seen, self.legacy_swapped); diff --git a/crates/workspace/src/workspace/surface/membership.rs b/crates/workspace/src/workspace/surface/membership.rs index c1ff4d74..6dc0f63a 100644 --- a/crates/workspace/src/workspace/surface/membership.rs +++ b/crates/workspace/src/workspace/surface/membership.rs @@ -15,15 +15,11 @@ impl SurfaceContent { } } pub(super) fn frame(&self, view: AnyView, cx: &App) -> SurfaceFrame { - let centre = self.tabs.panes(DockPlacement::Center, cx); SurfaceFrame { view, visible: self.tabs.has_visible_tabs(cx), local_visible: self.tabs.local_visible(cx), - only_group: match centre.as_slice() { - [only] => Some(only.node()), - _ => None, - }, + only_group: self.tabs.only_group(DockPlacement::Center, cx), } } pub(super) fn presentation(&self, cx: &App) -> (Option, bool) { @@ -46,6 +42,26 @@ impl SurfaceContent { pub(in crate::workspace) fn background_contains(&self, id: EntityId) -> bool { self.background.contains(id) } + /// Same selected terminal as the full terminal projection, without + /// constructing titles, placement or capabilities for unrelated Items. + pub(in crate::workspace) fn active_terminal( + &self, + cx: &App, + ) -> Option<(EntityId, crate::TerminalCapabilities)> { + self.tabs + .last_command() + .and_then(|id| { + let capabilities = self + .tabs + .foreground_capabilities(id, cx) + .or_else(|| self.background.item_handle(id)?.terminal_capabilities(cx))?; + Some((id, capabilities)) + }) + .or_else(|| { + let id = self.tabs.active_item()?.item_id(); + Some((id, self.tabs.foreground_capabilities(id, cx)?)) + }) + } pub(in crate::workspace) fn terminals(&self, cx: &App) -> Vec { let mut entries = self.tabs.foreground_terminals(cx); entries.extend(self.background.terminals(cx)); diff --git a/crates/workspace/src/workspace/tabs.rs b/crates/workspace/src/workspace/tabs.rs index d10b07db..76df512f 100644 --- a/crates/workspace/src/workspace/tabs.rs +++ b/crates/workspace/src/workspace/tabs.rs @@ -2,6 +2,7 @@ use super::docking::{DockPane, TAB_PLACEMENTS}; use super::*; use gpui_kit::component::dock::{DockAreaState, NodeId}; +use std::collections::HashMap; mod groups; mod lifecycle; mod local; @@ -61,6 +62,13 @@ impl TabEntry { pub(super) fn close(self, window: &mut Window, cx: &mut App) { self.detach().handle.close(window, cx); } + fn title(&self, cx: &App) -> SharedString { + self.dock_item + .read(cx) + .alias + .clone() + .unwrap_or_else(|| self.handle.tab_title(cx)) + } fn panel(&self) -> PanelId { PanelId::from(self.dock_item.entity_id()) } @@ -168,12 +176,11 @@ impl Tabs { .find(|entry| entry.handle.item_id() == id) .map(|entry| entry.handle.clone()) } - pub(super) fn central_handles(&self) -> Vec> { + pub(super) fn central_handles(&self) -> impl Iterator> + '_ { self.entries .iter() .filter(|entry| entry.local.is_none()) .map(|entry| entry.handle.clone()) - .collect() } pub(super) fn active_handle(&self) -> Option> { self.active_entry().map(|entry| entry.handle.clone()) @@ -248,21 +255,42 @@ impl Tabs { self.topology.pane(placement, node, cx) } pub(super) fn snapshots(&self, cx: &App) -> Vec { + let locations = + (self.entries.len() > 8).then(|| self.topology.locations(self.entries.len(), cx)); self.entries .iter() - .map(|entry| TabSnapshot { - id: entry.id(), - alias: entry.dock_item.read(cx).alias.clone(), - local: entry.local.is_some(), - location: self.item_location(entry.id(), cx), - group_color: entry.dock_item.read(cx).group_color(), - visible: self.item_visible(entry.id(), cx), + .map(|entry| { + let dock_item = entry.dock_item.read(cx); + let location = match &locations { + Some(locations) => locations.get(&entry.panel()).copied(), + None => self.topology.location(entry.panel(), cx), + }; + TabSnapshot { + id: entry.id(), + alias: dock_item.alias.clone(), + local: entry.local.is_some(), + location, + group_color: dock_item.group_color(), + visible: location.is_some_and(|(placement, _)| { + placement == DockPlacement::Center + || self.topology.region_open(placement, cx) + }), + } }) .collect() } pub(super) fn panes(&self, placement: DockPlacement, cx: &App) -> Vec { - self.topology - .panes(placement, cx) + let panes = self.topology.panes(placement, cx); + if panes.is_empty() { + return Vec::new(); + } + let items = (panes.iter().map(|pane| pane.panels.len()).sum::() > 32).then(|| { + self.entries + .iter() + .map(|entry| (entry.panel(), entry.id())) + .collect::>() + }); + panes .into_iter() .map(|pane| TabPane { placement: pane.placement, @@ -270,11 +298,17 @@ impl Tabs { items: pane .panels .into_iter() - .filter_map(|panel| self.item_for_panel(panel).map(TabEntry::id)) + .filter_map(|panel| match &items { + Some(items) => items.get(&panel).copied(), + None => self.item_for_panel(panel).map(TabEntry::id), + }) .collect(), }) .collect() } + pub(super) fn only_group(&self, placement: DockPlacement, cx: &App) -> Option { + self.topology.only_group(placement, cx) + } pub(super) fn region_present(&self, placement: DockPlacement, cx: &App) -> bool { self.topology.region_present(placement, cx) } @@ -379,21 +413,27 @@ impl Tabs { self.last_command_id } pub(super) fn title(&self, id: EntityId, cx: &App) -> Option { - let entry = self.entry(id)?; - Some( - entry - .dock_item - .read(cx) - .alias - .clone() - .unwrap_or_else(|| entry.handle.tab_title(cx)), - ) + self.entry(id).map(|entry| entry.title(cx)) } pub(super) fn terminal(&self, id: EntityId, cx: &App) -> bool { self.entry(id) .is_some_and(|entry| entry.handle.terminal_capabilities(cx).is_some()) } + /// Reads only the selected foreground capability; project Items own inner + /// terminals and must not be read from this outer membership. + pub(super) fn foreground_capabilities( + &self, + id: EntityId, + cx: &App, + ) -> Option { + let entry = self.entry(id)?; + if entry.project.is_some() { + return None; + } + entry.handle.terminal_capabilities(cx) + } pub(super) fn foreground_terminals(&self, cx: &App) -> Vec { + let bottom = self.topology.bottom_panels(cx); self.entries .iter() // Registered project Items own inner terminals and advertise no @@ -404,11 +444,9 @@ impl Tabs { Some(crate::TerminalEntry { item: entry.id(), capabilities: entry.handle.terminal_capabilities(cx)?, - title: self.title(entry.id(), cx)?, + title: entry.title(cx), active: false, - bottom: self - .item_location(entry.id(), cx) - .is_some_and(|(placement, _)| placement == DockPlacement::Bottom), + bottom: bottom.contains(&entry.panel()), background: false, }) }) diff --git a/crates/workspace/src/workspace/tabs/groups.rs b/crates/workspace/src/workspace/tabs/groups.rs index 34129ab8..b2bf8cb7 100644 --- a/crates/workspace/src/workspace/tabs/groups.rs +++ b/crates/workspace/src/workspace/tabs/groups.rs @@ -150,9 +150,9 @@ impl Tabs { /// Brings every group back together after the dock changed, and marks /// each tab with its group's color. pub(in crate::workspace) fn regroup(&mut self, window: &mut Window, cx: &mut App) { - let moves = self.groups.gather(&self.tab_bars(cx)); - if !moves.is_empty() { - for step in moves { + if !self.groups.is_empty() { + let bars = self.tab_bars(cx); + for step in self.groups.gather(bars) { self.topology.move_panel( step.panel, InsertTarget::Tabs { @@ -170,8 +170,10 @@ impl Tabs { .groups .group_of(panel(open)) .and_then(|group| self.groups.color(group)); - open.dock_item - .update(cx, |item, cx| item.set_group_color(color, cx)); + if open.dock_item.read(cx).group_color() != color { + open.dock_item + .update(cx, |item, cx| item.set_group_color(color, cx)); + } } } diff --git a/crates/workspace/src/workspace/tabs/lifecycle.rs b/crates/workspace/src/workspace/tabs/lifecycle.rs index fe870569..449a93e2 100644 --- a/crates/workspace/src/workspace/tabs/lifecycle.rs +++ b/crates/workspace/src/workspace/tabs/lifecycle.rs @@ -57,10 +57,15 @@ impl Tabs { ) -> Option { let index = self.entries.iter().position(|entry| entry.id() == id)?; let previous = self.active_central_id; - let location = self.item_location(id, cx); + let selected_local = self.local.selected() == Some(id); + let panel = self.entries[index].panel(); + let location = if focused || previous == Some(id) || selected_local { + self.topology.location(panel, cx) + } else { + None + }; let closed = self.entries.remove(index).detach(); - self.groups - .leave(PanelId::from(closed.dock_item.entity_id())); + self.groups.leave(panel); self.topology.remove(closed.dock_item, window, cx); self.reconcile_empty_regions(window, cx); closed.handle.close(window, cx); @@ -69,7 +74,7 @@ impl Tabs { .and_then(|pane| pane.active_panel()) .and_then(|panel| self.item_for_panel(panel)) .map(TabEntry::id); - if self.local.selected() == Some(id) { + if selected_local { let selected = replacement .filter(|id| self.local_entry(*id).is_some()) .or_else(|| { diff --git a/crates/workspace/src/workspace/tabs/topology.rs b/crates/workspace/src/workspace/tabs/topology.rs index 2e64dcf7..83f49db8 100644 --- a/crates/workspace/src/workspace/tabs/topology.rs +++ b/crates/workspace/src/workspace/tabs/topology.rs @@ -2,6 +2,7 @@ use super::super::docking::{DockPane, TAB_PLACEMENTS}; use super::super::*; use gpui_kit::component::dock::{DockAreaState, InsertTarget, NodeId}; +use std::collections::{HashMap, HashSet}; pub(in crate::workspace) struct DockTopology { dock: Entity, @@ -47,6 +48,52 @@ impl DockTopology { Some((placement, dock.layout(placement)?.find_panel_node(panel)?)) }) } + /// One transient native placement projection; never retained or used as an + /// authority after this synchronous observation. + pub(super) fn locations( + &self, + capacity: usize, + cx: &App, + ) -> HashMap { + let mut locations = HashMap::with_capacity(capacity); + let dock = self.dock.read(cx); + for placement in TAB_PLACEMENTS.into_iter().rev() { + if let Some(tree) = dock.layout(placement) { + tree.root().walk(&mut |node| { + if let PaneRef::Tabs { panels, .. } = node.kind() { + locations + .extend(panels.iter().map(|panel| (*panel, (placement, node.id())))); + } + }); + } + } + locations + } + + pub(super) fn bottom_panels(&self, cx: &App) -> HashSet { + let mut bottom = HashSet::new(); + if let Some(tree) = self.dock.read(cx).layout(DockPlacement::Bottom) { + tree.root().walk(&mut |node| { + if let PaneRef::Tabs { panels, .. } = node.kind() { + bottom.extend(panels.iter().copied()); + } + }); + } + bottom + } + + pub(super) fn only_group(&self, placement: DockPlacement, cx: &App) -> Option { + let tree = self.dock.read(cx).layout(placement)?; + let mut only = None; + let mut multiple = false; + tree.root().walk(&mut |node| { + if matches!(node.kind(), PaneRef::Tabs { .. }) { + multiple |= only.replace(node.id()).is_some(); + } + }); + if multiple { None } else { only } + } + pub(super) fn pane( &self, placement: DockPlacement, @@ -65,15 +112,18 @@ impl DockTopology { let Some(tree) = dock.layout(placement) else { return vec![]; }; - tree.node_ids() - .into_iter() - .filter_map(|node| { - let PaneRef::Tabs { panels, active_ix } = tree.find_node(node)?.kind() else { - return None; - }; - Some(DockPane::new(placement, node, panels.to_vec(), active_ix)) - }) - .collect() + let mut panes = Vec::new(); + tree.root().walk(&mut |node| { + if let PaneRef::Tabs { panels, active_ix } = node.kind() { + panes.push(DockPane::new( + placement, + node.id(), + panels.to_vec(), + active_ix, + )); + } + }); + panes } pub(super) fn add( &self, diff --git a/docs/DEVICE_UNLOCK.md b/docs/DEVICE_UNLOCK.md index 226d2195..eed36155 100644 --- a/docs/DEVICE_UNLOCK.md +++ b/docs/DEVICE_UNLOCK.md @@ -77,6 +77,10 @@ After three non-matches, fingerprint unlock is locked until a successful master password unlock re-registers the key. Closing the dialog, cancelling a scan, or restarting Nocterm does not reset failed attempts. A successful fingerprint match resets a partial count. Reader faults and timeouts preserve earlier failed attempts. +Current Linux clients receive changes directed to their own D-Bus release call. +If that client connection closes during a scan, the broker stops the scan +and releases the reader. The existing registration can be used on restart. +Clients fall back to periodic queries with brokers that expose the previous progress API. Older brokers without attempt reporting still support scans; update the installed broker to get persistent lockout and remaining-attempt display. diff --git a/docs/adr/0162-windows-holds-directory-handles-for-strict-local-capabilities.md b/docs/adr/0162-windows-holds-directory-handles-for-strict-local-capabilities.md new file mode 100644 index 00000000..241d4caf --- /dev/null +++ b/docs/adr/0162-windows-holds-directory-handles-for-strict-local-capabilities.md @@ -0,0 +1,46 @@ +# 0162. Windows holds directory handles for strict local filesystem capabilities + +Status: accepted. +- Amends [0110](0110-local-history-environment-partitions.md): Windows now supplies the held + directory capabilities that new v3 chat namespaces require. + +## Context + +New chats are environment-scoped v3 documents ([0110](0110-local-history-environment-partitions.md)). +Their partitions require held directory capabilities, so that one account's or project's +history cannot be redirected into another through a swapped directory or link. + +`nocterm-localfs` implemented held capabilities only on Unix, with directory descriptors and +`*at` calls. Windows used the portable fallback, whose identities are locations rather than +held directories. Every save of a new chat on Windows was refused with +`EnvironmentUnsupported`, the queue paused, and the notice advised checking disk space. + +## Decision + +- On Windows a strict `DirectoryCapability` holds an open handle to every directory from the + volume root down to itself. Each handle is opened with list access, without + `FILE_SHARE_DELETE` and with `FILE_FLAG_OPEN_REPARSE_POINT`. While the capability lives, + no held directory can be renamed, removed or replaced by a junction, so path operations + below it resolve through the same directories that were checked. +- Every component is opened as itself; a reparse point (symbolic link, junction, mount + point) or a non-directory is refused as `LinkRefused`. +- The identity is the volume serial number and file index read from the held handle, and + is reported as native, so `is_held` is true because the handles are actually held. +- A child capability is opened below its parent's held chain. A child of a browse + capability, which followed links and holds nothing, first re-establishes a strict chain. +- Staged publication, sources, listings and removal keep their existing Windows code. They + run below a held chain, and publication still replaces the target atomically. +- Other non-Unix targets keep the portable fallback and the typed refusal of 0110. +- A failed save names its class: unsupported storage, a full volume, refused access or + another failure. Only a full volume suggests freeing disk space. + +## Consequences + +- New chats save on Windows in every environment and context, with the same partition and + owner checks as on Unix. +- While a capability is held, other programs cannot rename or delete the held directories; + capabilities are short-lived, so this lasts for one operation. +- A directory another program holds open with delete access cannot be opened strictly until + that program closes it. +- On ReFS the 64-bit file index is the lower part of the 128-bit file ID; identities are only + compared within one operation. diff --git a/docs/adr/0162-windows-held-directory-capabilities.md b/docs/adr/0165-windows-ancestry-publication-guards.md similarity index 93% rename from docs/adr/0162-windows-held-directory-capabilities.md rename to docs/adr/0165-windows-ancestry-publication-guards.md index 8ad92995..34bf75e4 100644 --- a/docs/adr/0162-windows-held-directory-capabilities.md +++ b/docs/adr/0165-windows-ancestry-publication-guards.md @@ -1,6 +1,8 @@ -# 0162. Windows holds directory ancestry and guards atomic publication +# 0165. Windows holds directory ancestry and guards atomic publication -Status: accepted. Extends the Windows implementation of [ADR 0017](0017-local-filesystem-capabilities.md). +Status: accepted. Supersedes the Windows acquisition and publication guarantees in +[ADR 0162](0162-windows-holds-directory-handles-for-strict-local-capabilities.md) +and extends [ADR 0017](0017-local-filesystem-capabilities.md). ## Context diff --git a/docs/adr/0166-settings-pages-can-own-a-bounded-scroll-viewport.md b/docs/adr/0166-settings-pages-can-own-a-bounded-scroll-viewport.md new file mode 100644 index 00000000..f938ac80 --- /dev/null +++ b/docs/adr/0166-settings-pages-can-own-a-bounded-scroll-viewport.md @@ -0,0 +1,35 @@ +# 0166. Settings pages can own a bounded scroll viewport + +Status: accepted + +## Context + +Settings normally scrolls each page as a document. Keymap renders a long table +of editable bindings, and constructing all matching rows on every input event +can delay the next keystroke. A virtual list needs a definite viewport height. + +## Decision + +A complete native page factory can request a viewport through +`SettingsPageSpec::with_viewport`. Settings supplies the remaining height after +its navigation and diagnostics. The requested page owns its scroll position and +focusable controls. Ordinary pages continue to use the host's per-page scroll +handle for document scrolling and anchors. + +Keymap keeps its search and column headings above the virtualized rows. It owns +the prepared row projection and invalidates it on keymap revision or query +changes. Rebinding, persistence, save errors and page lifetime still use the +supplied installation and lifecycle in [ADR 0051](0051-retained-keymap-installation.md). + +## Alternatives + +Putting a fixed-height list inside the host scroll would add a second scrolling +region and leave unused space on larger windows. Reimplementing the host scroll +in each page would duplicate focus, diagnostics and anchor handling across +ordinary settings forms. + +## Consequences + +The host can drive either layout through the existing SettingsPageSpec. +Pages requesting a viewport are responsible for keeping their contents +reachable at the height supplied by the host. diff --git a/docs/adr/0167-local-listings-project-observed-entry-types.md b/docs/adr/0167-local-listings-project-observed-entry-types.md new file mode 100644 index 00000000..cd70c78c --- /dev/null +++ b/docs/adr/0167-local-listings-project-observed-entry-types.md @@ -0,0 +1,34 @@ +# 0167. Local listings project the entry types each caller needs + +Status: accepted + +## Context + +Explorer uses names, entry kinds and link flags for its rows. Path completion filters +the same enumeration to directories and links to directories. Both previously paid +to read complete metadata for every name. Actions such as opening or transferring a +file acquire and validate their own filesystem capabilities. + +## Decision + +Keep full metadata browsing and add a projected listing to the existing +`nocterm-session::local_fs::LocalFs` browsing boundary. Its purpose distinguishes +file rows from directory completion. Both preserve native names and ordering and +charge each observed leaf to the entry and display-name budgets. Adapters can +project their full listing by default. The same injected filesystem serves both +callers and keeps the typed errors and cancellation flag. + +On Linux, `nocterm-localfs` reads type information from held-directory enumeration, +checks directory search access and uses descriptor-relative metadata for unknown +types. Directory completion probes link targets when needed. Enumeration supplies +an observation whose names or types can change before the next filesystem action. +This operation grants no strict or mutation capability. + +## Consequences + +The Explorer keeps only the projected fields. The shared directory reader can skip +full metadata, file rows and their sorting keys during completion. Other platforms +continue through the full-metadata implementation. Strict traversal, source +streaming and mutation retain the capability rules from [ADR 0017](0017-local-filesystem-capabilities.md). +The shared completion input and captured source still follow +[ADR 0072](0072-shared-directory-selection.md). diff --git a/docs/adr/0168-plugin-views-carry-validation-to-the-renderer.md b/docs/adr/0168-plugin-views-carry-validation-to-the-renderer.md new file mode 100644 index 00000000..48d8bee6 --- /dev/null +++ b/docs/adr/0168-plugin-views-carry-validation-to-the-renderer.md @@ -0,0 +1,25 @@ +# 0168. Plugin views carry validation to the renderer + +Status: accepted + +## Context + +The plugin host accepts a serializable view from a guest. Its nodes and refresh request are +public data. The host sanitizes strings and validates the complete arena before accepting the +reply. Previously the application kept an additional copy of the view for equality checks and +the renderer repeated validation on each changed reply. + +## Decision + +`nocterm-plugin-api` issues an opaque `ValidatedView` after sanitizing and validating a raw view. +It exposes read-only data and can be consumed back into an editable view, which must be checked +to regain the validated type. The guest protocol still uses the raw view. Guest validation +failures continue through the host's existing refused-reply policy, and callers that supply raw +views directly to the renderer still go through the same validation. + +## Consequences + +The renderer owns the displayed nodes and compares subsequent accepted replies to them. A changed +reply transfers its nodes into the renderer. Equal nodes keep the existing layout and fold state. +The shell reads the requested refresh independently of that comparison. Following a fault, the +next successful reply replaces the fault display even if it contains the earlier nodes. diff --git a/docs/adr/0169-single-image-previews-reuse-the-inspection-decode.md b/docs/adr/0169-single-image-previews-reuse-the-inspection-decode.md new file mode 100644 index 00000000..c36adf3b --- /dev/null +++ b/docs/adr/0169-single-image-previews-reuse-the-inspection-decode.md @@ -0,0 +1,36 @@ +# 0169. Single image previews reuse the inspection decode + +Status: accepted + +## Context + +[ADR 0035](0035-injected-image-codecs.md) assigns physical inspection and thumbnail +encoding to the native image adapter. [ADR 0142](0142-live-transcript-and-image-admission.md) +bounds physical work across windows and shares preview identity across the composer and +transcript. Pasting or selecting a single image still decodes it during inspection and +again for its first preview. + +## Decision + +The existing inspector can return a single-use decoded preview source with the inspected +original. Only in-flight work holds that source. The composer admits the original as soon +as inspection and prompt encoding finish. It hands the source and the same physical work +permit to the existing preview request after the original chat and composer accept the +attachment. The preview cache admits and delivers its result using the existing source key, +byte budget and request generation. + +A stale attachment, rejected cache request or cancelled task releases the source and +permit. Inspectors with no decoded source and multi-image selections use the existing +lazy preview path. The prompt and history retain the same original encoded data. + +## Alternatives + +Keeping the full decoded buffer with the prompt would extend its lifetime through the +composer and transcript. Building the thumbnail before admitting the original would +hold Send until resize and PNG encoding completed. + +## Consequences + +Single-image previews can reuse their inspected pixels without another physical decode. +The preparation and preview tasks share one existing slot during the handoff. The +decoder, attachment and preview limits continue to apply independently. diff --git a/docs/adr/0170-code-plugins-can-borrow-storage-for-keyed-reads.md b/docs/adr/0170-code-plugins-can-borrow-storage-for-keyed-reads.md new file mode 100644 index 00000000..af305165 --- /dev/null +++ b/docs/adr/0170-code-plugins-can-borrow-storage-for-keyed-reads.md @@ -0,0 +1,36 @@ +# 0170. Code plugins can borrow storage for keyed reads + +Status: accepted + +## Context + +[ADR 0091](0091-user-plugin-code-runs-in-process-on-wasmi.md) sets the ABI and the execution +budget. [ADR 0092](0092-plugin-sdk-and-developer-sessions.md) puts guest decoding in the SDK. +A guest with hundreds of stored entries can spend most of its budget constructing the +owned storage map before it reads any key. The additional first-call translation can +then use up the remaining fuel. + +## Decision + +The ABI decoder can keep storage strings borrowed from the input for one call. It still +checks the original byte limit, wire encoding and string validity. Lookup preserves the +last value for a repeated key. The SDK exposes this path through `TypedPlugin`, +`TypedCx` and the `typed` form of `export!`. The test host can run either dispatch. + +The typed context serves individual keys and the existing typed observation and setting +reads. The ordinary `Plugin` and `Cx` keep the owned snapshot for guests that need to +enumerate it or use fields outside the typed reads. The Focus Timer uses the typed path. +The encoded calls, exports, permissions and Wasmi budgets are shared by both paths. + +## Alternatives + +Materializing the whole map on the first call to `snapshot()` added enough fuel to make +a previously successful warm call fail near the storage limit. Raising the call budget +would apply the extra fuel to every guest. Eager translation made large modules with +unused code more expensive to load. + +## Consequences + +A plugin that reads a few stored keys can avoid constructing a map on each call. +Each lookup scans the bounded list of stored keys, which suits a small number of reads. +A guest needs to be rebuilt to adopt the typed SDK path. diff --git a/docs/adr/0171-container-watches-recover-once-without-waiting.md b/docs/adr/0171-container-watches-recover-once-without-waiting.md new file mode 100644 index 00000000..05f952d5 --- /dev/null +++ b/docs/adr/0171-container-watches-recover-once-without-waiting.md @@ -0,0 +1,31 @@ +# 0171. Container watches recover once without waiting + +Status: accepted + +## Context + +[ADR 0131](0131-one-container-watch-per-host-connection.md) shares one subscription +and both listings per host connection. An ended event stream waited ten seconds before +the service subscribed again and refreshed the lists. During that interval the panel +could still show the last successful listing. + +## Decision + +The watch may immediately reacquire a subscription after a stream ends. Reacquisition +subscribes before it reads the containers and images, so the full listing catches up +with changes missed while disconnected. After using this immediate retry, the watch +must publish the first listing and stay with that stream for one retry interval before +another immediate retry becomes available. A shorter stream or a failed listing uses +the ordinary retry delay. An explicit refresh can still end the wait. + +## Alternatives + +Reopening on every stream end can continuously run new processes and listings when +an engine cannot deliver events. Shortening the general delay would also make failed +listings more expensive on hosts that remain unavailable. + +## Consequences + +An isolated interruption can recover without an idle wait. Repeated short-lived +streams resume the existing ten-second cadence after the immediate attempt. All +windows sharing the host still share its subscription and lists. diff --git a/docs/adr/0172-runtime-calls-borrow-host-snapshot-data.md b/docs/adr/0172-runtime-calls-borrow-host-snapshot-data.md new file mode 100644 index 00000000..bc25a365 --- /dev/null +++ b/docs/adr/0172-runtime-calls-borrow-host-snapshot-data.md @@ -0,0 +1,42 @@ +# 0172. Runtime calls can borrow the host's snapshot data + +Status: accepted + +## Context + +The plugin host assembles observations, settings, storage and previous effect outcomes for each +call. Copying the entire stored map before the adapter serializes it allocates strings and map +nodes for every invocation, including renders that yield the same view. The installed data already +lives through the synchronous call. + +## Decision + +The runtime port accepts a call-scoped `SnapshotRef` for rendering and events. The plugin host +keeps the installed data in its registry and lends storage from the same entry that supplies the +runtime instance. Observations and outcomes are still prepared for each call. The guest-visible +settings are resolved from stored fields using the shared schema validator. The projection skips +secret fields before reading their stored values. + +The declarative runtime reads the borrowed input and the WASM adapter encodes it in the existing +ABI v1 order. Rust runtimes that use the owned snapshot methods can rely on the port defaults to +materialize the scoped input. The guest SDK continues to read its decoded input from WASM memory. + +The grant, observation cadence, request admission, execution budget and effect settlement follow +[ADR 0090](0090-user-plugin-host-and-passive-providers.md) and +[ADR 0091](0091-user-plugin-code-runs-in-process-on-wasmi.md). +[ADR 0170](0170-code-plugins-can-borrow-storage-for-keyed-reads.md) governs borrowing on the guest +side. + +## Alternatives + +A shared pointer to a stored map would let a runtime retain it beyond the call and would change the +shape of a snapshot for existing consumers. A per-package cache of encoded bytes would need keys and +invalidation for changing storage, observations, settings, outcomes and terminal context. A scoped +borrow uses the existing owner and requires no invalidation. + +## Consequences + +Built-in runtimes can use the same data through the end of each synchronous call. The host performs +setting validation against the current stored values on every call, including after a package or +data change. Tests can compare the exact serialized bytes for both runtime entry points and keep +the owned guest API and version unchanged. diff --git a/docs/adr/0173-fingerprint-progress-is-addressed-to-the-release-caller.md b/docs/adr/0173-fingerprint-progress-is-addressed-to-the-release-caller.md new file mode 100644 index 00000000..b6d5f4b7 --- /dev/null +++ b/docs/adr/0173-fingerprint-progress-is-addressed-to-the-release-caller.md @@ -0,0 +1,38 @@ +# 0173. Fingerprint progress is addressed to the release caller + +Status: accepted + +## Context + +The Linux fingerprint client queried the privileged broker every 50 ms during a scan. +Even with no completed scan, each query reached the system bus and repeated broker +caller identification and registration lookup. The application and the installed +broker can be updated independently. + +## Decision + +The broker offers `ReleaseWithProgress(binding, token, request)` alongside the +existing release methods. It authenticates and admits the request through the same +path as `Release`. It sends `ReleaseProgress(request, remaining)` to the original +caller's unique D-Bus name after admission and after each completed non-match. +Progress contains no registration token or key material. Only the authenticated +method reply can carry a released key. Progress delivery is best effort and bounded. + +The Linux client pins the broker's authenticated unique name for the release, subscribes +before invoking it, and accepts progress for its own request only. The existing +cancellation and late-key checks still apply. On an `UnknownMethod` reply to the new call, +the client tries the legacy `Release` and `AttemptsRemaining` path. Other errors are +reported without repeating the scan. The original calls remain available for older clients. + +## Alternatives + +Broadcast progress would make one user's authentication activity visible to unrelated bus +clients. Slower periodic queries would keep broker work running during silence and delay +attempt feedback. Keeping the authenticated reply and adding addressed notifications +avoids both costs without changing who authorizes release. + +## Consequences + +Compatible versions exchange no periodic progress requests. Fingerprint recognition, +attempt accounting, lockout and key lifetime remain with the broker. Older package +combinations retain their existing progress behavior. diff --git a/docs/adr/0174-terminal-paste-waits-without-blocking-the-window.md b/docs/adr/0174-terminal-paste-waits-without-blocking-the-window.md new file mode 100644 index 00000000..a17d3125 --- /dev/null +++ b/docs/adr/0174-terminal-paste-waits-without-blocking-the-window.md @@ -0,0 +1,45 @@ +# 0174 — Terminal paste waits without blocking the window + +Status: accepted. Extends the input contract in [0038](0038-private-terminal-state-owners.md). + +## Context + +A Wayland clipboard request asks another client to write into a pipe. That +client can take time to respond. The terminal used to read the pipe during the +paste action, so unrelated window input and drawing waited for the clipboard. +Moving the read out of the action creates a new ordering dependency between +the paste and later input to the same program. + +## Decision + +The Wayland adapter snapshots the selected offer when GPUI's asynchronous +clipboard API is called. It transfers pipe bytes and decodes them on the +background executor. Cached and locally owned contents are immediately +available. A late result may be used by its original caller, and only the +current offer can populate its cache. The adapter bounds concurrent reads, +bytes and waiting time. Dropping a read closes its pipe. + +The terminal's input owner reserves the paste's place in the connection's +input order, capturing the negotiated paste modes from the action. It buffers +later user input while the read is pending, with a 64-entry and 4 MiB cap. +Completed reads and queued keys are admitted to the session in order, and +actual admission still precedes shell integration, live lease revocation and +viewport changes. An empty or failed read releases later input. Disconnect, +replacement, an authentication prompt and terminal disposal cancel the queue. + +Program protocol replies can proceed during clipboard transfer. A new agent +command or directory change waits for a clear input order, using the existing +queue rejection contract while a clipboard read is pending. + +## Alternatives + +Moving a terminal action onto a worker without recording its position would +let typing overtake a paste. Keeping the order in the platform would couple +the platform clipboard to session and terminal mode state. Holding program +replies behind a paste could prevent the running program from making progress. + +## Consequences + +Other window actions can run while the Wayland source is preparing data. +Later input to the receiving terminal still depends on the paste's outcome. +Applications using synchronous clipboard reads keep their existing contract. diff --git a/docs/adr/0175-remote-walks-skip-link-target-metadata.md b/docs/adr/0175-remote-walks-skip-link-target-metadata.md new file mode 100644 index 00000000..285237c1 --- /dev/null +++ b/docs/adr/0175-remote-walks-skip-link-target-metadata.md @@ -0,0 +1,38 @@ +# 0175. Remote walks skip link target metadata + +Status: accepted + +## Context + +The Explorer uses directory rows for browsing and for recursive statistics. +Download and relay discovery also traverse remote directories. Browsing needs +the target kind of a symbolic link to offer directory navigation. Walks skip +symbolic links, so resolving every link in those listings adds network work +whose result the walk discards. + +## Decision + +The session contract provides `RemoteFs::read_dir_for_walk` for recursive +consumers. It preserves the entries and link flags. Link target kinds and sizes +can be unresolved. An implementation can delegate to the existing browse +listing. The SFTP adapter shares the directory open, page, validation and +close path with browsing and omits the target lookups for the walk projection. + +Explorer counts its accepted root listing in server order and uses the walk +projection for descendants. Download and relay discovery use the walk +projection for their directory listings. Each consumer still decides whether +it can enter an entry. Activity remains tied to the original session +capability and the existing request cancellation rules. + +## Alternatives + +Resolving links in both projections keeps one response policy but makes a +walker wait for targets it will skip. Adding a separate traversal port would +duplicate session capability wiring for the same read authority. + +## Consequences + +Browsing still resolves links for navigation. Recursive listing work is bounded +by directory pages and the existing validation limits, without another +request per link. The adapter closes each directory handle after completion, +failure or cancellation. diff --git a/docs/adr/0176-agent-previews-use-bounded-pixels.md b/docs/adr/0176-agent-previews-use-bounded-pixels.md new file mode 100644 index 00000000..9eec7f58 --- /dev/null +++ b/docs/adr/0176-agent-previews-use-bounded-pixels.md @@ -0,0 +1,36 @@ +# 0176. Agent previews use bounded pixels + +Status: accepted + +## Context + +The native adapter scales pixels, then PNG-encodes them for the display workflow +introduced by [0035](0035-injected-image-codecs.md). Agent copies and decodes that +PNG to display the preview. [0169](0169-single-image-previews-reuse-the-inspection-decode.md) +already allows the first preview to share the source decode with inspection. + +## Decision + +The existing thumbnailer and single-use decoded source expose a display projection. +Its pure result carries either a checked PNG or tightly packed owned RGBA8 pixels. +The domain checks nonzero dimensions, request bounds, exact byte length and bounded +buffer capacity. Implementations of the encoded operation can use the default +projection. The native adapter moves the resized pixels directly when serving it. + +Agent converts RGBA8 to BGRA in place and moves the allocation into its GPUI frame. +The existing preview cache compares frame dimensions and exact BGRA bytes before +sharing a ready image. It charges the allocation and its atlas estimate. Its existing +generation, working reservation, cancellation and last-reference eviction rules apply. +Prompt and transcript payloads retain the original encoded source. + +## Alternatives + +Transporting PNG for display preserves a single result shape and spends CPU and +allocations on compression and decompression. Passing a GPUI frame across the +port would couple the native adapter and AI domain to the renderer. A separate +port would duplicate capability wiring for the same bounded decode. + +## Consequences + +The native display path avoids a PNG round trip. Other implementations can keep +returning a checked PNG. Image cache identity follows actual presentation bytes. diff --git a/docs/adr/0177-attachment-batches-reuse-one-inspection-decode.md b/docs/adr/0177-attachment-batches-reuse-one-inspection-decode.md new file mode 100644 index 00000000..a48250e3 --- /dev/null +++ b/docs/adr/0177-attachment-batches-reuse-one-inspection-decode.md @@ -0,0 +1,36 @@ +# 0177. Attachment batches reuse one inspection decode + +Status: accepted + +## Context + +[ADR 0169](0169-single-image-previews-reuse-the-inspection-decode.md) +lets the first preview of a single attachment use the original's inspection +decode. A selection of several files validates every original and later decodes +each original again for its first preview. Admitting the originals before +scaling allows the composer to send them while previews are still loading. + +## Decision + +The Agent feature validates the files in their selected order under its existing +count and size limits. It asks for a transient preview source when inspecting the +last file. The whole selection must pass validation before the composer accepts it. +After acceptance, the existing handoff carries that source and the preparation's +physical work permit to the preview task. Earlier files and inspectors without a +transient source use lazy previews. + +The cache continues to bind delivery to the original chat and request generation. +A stale or rejected handoff releases the source and its permit. The original +payloads retain their bytes and order. + +## Alternatives + +Scaling each preview during inspection delays acceptance of the originals. +Retaining several full-resolution decodes for one selection increases the memory +charge per admitted physical job. + +## Consequences + +Each selection can avoid one repeat decode while keeping at most one transient +inspection result under the preparation's permit. Each sibling preview acquires +its own permit. The existing per-image and shared preview budgets still apply. diff --git a/docs/adr/0178-acp-budgets-inbound-and-outbound-lines-separately.md b/docs/adr/0178-acp-budgets-inbound-and-outbound-lines-separately.md new file mode 100644 index 00000000..cc371088 --- /dev/null +++ b/docs/adr/0178-acp-budgets-inbound-and-outbound-lines-separately.md @@ -0,0 +1,41 @@ +# 0178. ACP budgets inbound and outbound lines separately + +Status: accepted + +## Context + +Agent image admission allows a collection of 20 MiB of originals under +[ADR 0142](0142-live-transcript-and-image-admission.md). The same limit used to +bound both directions of the local ACP transport at 16 MiB of JSON per line. +Base64 expands a full selection to around 26.7 MiB before request framing. The +composer could therefore accept every original and lose the connection when +the transport rejected the prompt. Mapping each shared encoded image to an +owned SDK string also created an extra full copy before JSON serialization. + +## Decision + +The ACP adapter caps each inbound line at 16 MiB. Its outbound cap includes +that budget plus the maximum Base64 expansion of the domain's image collection +with room for separately padded blocks. Outbound lines still have a finite +length and exclude literal line breaks. + +The adapter constructs the SDK prompt envelope around the neutral content +blocks. The blocks serialize in the existing content shape and retain the +shared image bytes through request preparation. The SDK owns the request +lifecycle and the adapter maps the typed response under +[ADR 0058](0058-neutral-agent-protocol-boundary.md). + +## Alternatives + +Using the same larger limit in both directions increases the cost of a line +from an external process. Lowering the raw attachment limit reduces the set of +originals users can send. Splitting one prompt across multiple requests changes +the user's turn and provider behavior. The directional budgets let the +existing prompt carry the admitted originals in order. + +## Consequences + +The transport can carry a full attachment collection alongside ordinary prompt +text and context. The larger outbound line can hold more application-owned +bytes during a send. Envelope equivalence and subprocess tests protect the +protocol shape. History and cloud transport have separate owners and limits. diff --git a/docs/adr/README.md b/docs/adr/README.md index 6953c764..ea0a8671 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -22,7 +22,7 @@ acceptance; a later record supersedes an earlier one. | [0014](0014-vendor-source-replay.md) | Vendored sources replay from authenticated archives and ordered patches | | [0015](0015-private-file-publication.md) | Private file publication shares one staged, atomic mechanism | | [0016](0016-vault-storage-boundary.md) | Vault format and rules are independent of storage and lifecycle | -| [0017](0017-local-filesystem-capabilities.md) | Native filesystem capabilities are injected through pure session ports (Windows support extended by 0162) | +| [0017](0017-local-filesystem-capabilities.md) | Native filesystem capabilities are injected through pure session ports | | [0018](0018-transfer-runtime-capabilities.md) | Transfer execution is an adapter over held filesystem and retryable publication ports | | [0022](0022-agent-storage-owners.md) | Agent storage adapters and private lifecycle owners share persistence execution (numeric history ceilings superseded by 0164) | | [0025](0025-native-program-opener.md) | External local programs have an explicit bounded native owner | @@ -34,7 +34,7 @@ acceptance; a later record supersedes an earlier one. | [0032](0032-narrow-terminal-ports.md) | Separate terminal ports bind approvals and secret answers to original Item/session/prompt epochs | | [0033](0033-native-agent-sandbox-capabilities.md) | Inject native workspace preparation and fail-closed sandbox launch capabilities | | [0034](0034-chat-config-composer-owners.md) | Per-chat configuration and composer transitions have private feature owners | -| [0035](0035-injected-image-codecs.md) | Inject bounded native image codecs and bind preview delivery to request generations | +| [0035](0035-injected-image-codecs.md) | Inject bounded native image codecs and bind preview delivery to request generations. Display representation amended by [0176](0176-agent-previews-use-bounded-pixels.md) | | [0036](0036-connection-profile-native-boundary.md) | Connection documents and native values use explicit domain ports | | [0037](0037-chat-document-semantic-revisions.md) | Durable chat revisions, pending candidates and capture have separate ownership | | [0038](0038-private-terminal-state-owners.md) | Private terminal state owners commit input and presentation after captured session admission | @@ -157,6 +157,20 @@ acceptance; a later record supersedes an earlier one. | [0159](0159-plugin-charts-toolbar-axis-and-toolbar-moves.md) | Plugin views draw charts of recent values (`chart`, ABI stays 1), a toolbar's calls name its axis in the zone (`cx.is_column()`), toolbars use the status bar's small text, and moving a toolbar is a layout edit | | [0160](0160-ci-compiles-each-kind-once-and-tests-the-plugin-feature-where-it-changes-code.md) | CI compiles each kind of build once (lint checks, build and tests), tests `user-plugins` only in the packages that declare it, saves caches from `dev` and `master`, and builds installers only for releases | | [0161](0161-user-plugins-ship-in-every-build.md) | User plugins ship in every build: the `user-plugins` cargo feature and the compile-out rule are gone, the `[plugins] user_plugins` switch and `--safe-mode` still decide whether a run loads them (supersedes the compile-out part of 0093) | -| [0162](0162-windows-held-directory-capabilities.md) | Windows holds directory ancestry and guards atomic publication against reparse conversion | -| [0163](0163-windows-agents-start-hidden-with-the-systems-search-path.md) | Windows agents start hidden and use the system search path and usual Node.js locations | +| [0162](0162-windows-holds-directory-handles-for-strict-local-capabilities.md) | Windows strict local filesystem capabilities hold every ancestor's handle without delete sharing and refuse reparse points, so new v3 chats save on Windows; a failed save names its class (amends 0110; acquisition/publication guarantees superseded by 0165) | +| [0163](0163-windows-agents-start-hidden-with-the-systems-search-path.md) | Windows agents start without a console window, the agent environment matches Windows names without case, and bare commands such as `npx` are also looked for in the usual Node.js locations | | [0164](0164-chat-history-capacity.md) | Installation history capacity is separate from a single document; larger byte and row ceilings supersede numeric limits in 0022, 0031 and 0142 | +| [0165](0165-windows-ancestry-publication-guards.md) | Windows pins native ancestry, preserves full file identity and guards publication against reparse conversion (supersedes the guarantees in 0162) | +| [0166](0166-settings-pages-can-own-a-bounded-scroll-viewport.md) | Settings pages can request a bounded viewport and own their scrolling | +| [0167](0167-local-listings-project-observed-entry-types.md) | Local listings project the native entry types needed for file rows or directory completion | +| [0168](0168-plugin-views-carry-validation-to-the-renderer.md) | The plugin host hands the renderer an immutable validated view | +| [0169](0169-single-image-previews-reuse-the-inspection-decode.md) | Single image previews reuse the inspection decode under the existing work permit. Display representation amended by [0176](0176-agent-previews-use-bounded-pixels.md). Selection scope amended by [0177](0177-attachment-batches-reuse-one-inspection-decode.md) | +| [0170](0170-code-plugins-can-borrow-storage-for-keyed-reads.md) | Code plugins can borrow storage for keyed reads during one call | +| [0171](0171-container-watches-recover-once-without-waiting.md) | Container watches can immediately recover after a stream break and wait between repeated short streams | +| [0172](0172-runtime-calls-borrow-host-snapshot-data.md) | Runtime calls can borrow the host’s snapshot data | +| [0173](0173-fingerprint-progress-is-addressed-to-the-release-caller.md) | Linux fingerprint progress goes only to the original D-Bus release caller | +| [0174](0174-terminal-paste-waits-without-blocking-the-window.md) | Terminal paste preserves the session's input order while the window remains responsive | +| [0175](0175-remote-walks-skip-link-target-metadata.md) | Remote walks skip link target metadata and preserve browsing resolution | +| [0176](0176-agent-previews-use-bounded-pixels.md) | Agent previews transport bounded pixels across the native display path, amending [0035](0035-injected-image-codecs.md) and [0169](0169-single-image-previews-reuse-the-inspection-decode.md) | +| [0177](0177-attachment-batches-reuse-one-inspection-decode.md) | Attachment batches may reuse the final inspection decode, amending the selection scope of [0169](0169-single-image-previews-reuse-the-inspection-decode.md) | +| [0178](0178-acp-budgets-inbound-and-outbound-lines-separately.md) | ACP reserves outbound line space for the Base64 expansion of an admitted image collection | diff --git a/docs/architecture/adapter.md b/docs/architecture/adapter.md index 0cafccc9..5ef6f085 100644 --- a/docs/architecture/adapter.md +++ b/docs/architecture/adapter.md @@ -79,14 +79,25 @@ for a missing remote source `nocterm-ssh` implements that contract using russh and lazily opened SFTP channels on a dedicated Tokio -runtime. Authentication with a vault key reads the record through the credential store, +runtime. A directory listing starts with two SFTP page requests and keeps up to +eight requests in flight once the two initial replies contain pages. It consumes +replies in request order, stops at the first EOF and closes the handle after +completion, failure or cancellation. Browse listings resolve symlink targets in +a bounded window. Recursive walks retain link flags and skip target lookup +([ADR 0175](../adr/0175-remote-walks-skip-link-target-metadata.md)). +Authentication with a vault key +reads the record through the credential store, checks its public half against the profile and signs without SHA-1 for RSA ([ADR 0102](../adr/0102-ssh-keys-are-kept-in-the-vault.md)). `nocterm-local` adapts portable-pty to the same session events and launch contract. Integration supplies bounded OSC 7 -cwd and prompt markers without parsing rendered prompt text. It also implements the +cwd and prompt markers without parsing rendered prompt text. On Linux, reads and +backpressured writes wait for PTY readiness, session close or leader exit. Waits for +restricted writes also recheck source authority periodically. It also implements the foundation `WallClock` as `SystemClock`, which reads the system time and the local time zone -in effect at that instant ([ADR 0088](../adr/0088-wall-clock-contract-and-the-clock-plugin.md)). +in effect at that instant using Jiff ([ADR 0088](../adr/0088-wall-clock-contract-and-the-clock-plugin.md)). +The shared adapter refreshes Jiff’s system-zone cache once per observed wall-clock second +when read, including after clock steps; it starts no background timer. ## User plugin packages @@ -107,10 +118,14 @@ ever created. See [ADR0141](../adr/0141-versioned-plugin-publication.md). `nocterm-plugin-wasm` implements the `PluginRuntime` port on wasmi for code packages. It reads no file: the bytes come from the package port. It validates and compiles a module when a plugin is -instantiated, caches at most 16 compiled modules, runs each call under a fuel budget and a memory -limit, allows at most 16 live instances, bounds every read of guest memory, and maps a trap, a +instantiated and caches at most 16 compiled modules. Each module owns its engine, so an evicted +module releases its compiled code when its last live instance is gone. The runtime runs each call +under a fuel budget and a memory limit, allows at most 16 live instances, bounds every read of guest +memory, and maps a trap, a missed deadline or a memory fault to a `RuntimeError` that the host counts. Guests import nothing; their log lines go to an injected `GuestLog`. The crate has no thread and no global. +An HTTP response whose body and snapshot exceed the ABI call limit arrives with status 0 and +the original request key. A successful binary response is sent whole. `nocterm-plugin-net` implements the `PluginNet` port for the `net.request` capability. The host builds each call from the plugin's settings: the origin the user typed and, from a secret setting, @@ -138,6 +153,14 @@ async stream the handshake needs, so a relay that stops reading stalls the write instead of growing a buffer. Closing either side ends both directions. The relay carries bytes only: the host key checked and the sign-in are the destination's. +Each SSH link reads and validates the whole host-key store afresh. Its protocol +handler shares the parsed records matching that link for verification and +rekeying. The initial trust decision owns the source file bytes and identity +needed to revalidate a pending confirmation and releases them when that decision +completes. On x86 with +hardware AES and carry-less multiply, the adapter gives the already-supported +AES-256-GCM cipher first preference. It preserves the provider's fallback order. + The adapter also establishes jump-host routes ([ADR 0060](../adr/0060-ssh-jump-host-routes.md)). `ConnectRequest.jumps` lists resolved hops; each is reached through a `direct-tcpip` forward opened on the previous connection, and the configured proxy carries only the @@ -153,7 +176,12 @@ the shell's lifetime. Unix exit observation leaves the leader unreaped until its process group is stopped, preventing reuse of the group ID; deliberately detached process groups are outside that ownership. Windows commands start suspended and are attached to a Job Object before execution. Dropping the -output or startup future cancels the owned command. +output or startup future cancels the owned command. On Linux, a shared close +notification wakes the command's stdin, stdout and stderr workers on shutdown. +When that notification cannot be allocated, workers use the bounded pipe wait. +The leader wait uses a pidfd and the existing output-close notification for +unrestricted Linux commands. Restricted sources and systems without pidfd +readiness keep bounded process-status checks. ## External local programs @@ -174,7 +202,9 @@ binding and cancellation rules. The composition root injects `nocterm-device-unlock` into `nocterm-vault-store`; native adapters remain outside the pure vault and its UI. An optional `nocterm-vault-broker` Linux system service enforces fingerprint -verification for user-bound memory-only keys. See [device unlock](../DEVICE_UNLOCK.md) +verification for user-bound memory-only keys. It sends attempt progress only to the +authenticated caller ([ADR 0173](../adr/0173-fingerprint-progress-is-addressed-to-the-release-caller.md)). +See [device unlock](../DEVICE_UNLOCK.md) for the platform boundaries and explicit installation. ## Vault storage @@ -186,13 +216,19 @@ uses `nocterm_core::fs::AtomicPublication`; the lock remains held through rename and pure state is accepted only after success. Device registration is checked against the current envelope and cancellation epoch before publication or key installation. Only the app composes this adapter with native authentication. +The worker sleeps until a command or the current auto-lock deadline. Changing +the timeout recomputes that deadline from the latest vault activity. ## Native filesystem capabilities `nocterm-localfs` implements session's synchronous `LocalFs` and `LocalMutations` ports. Application composition supplies them to Explorer; feature code dispatches blocking calls on the background executor. Native names remain `OsString`/`PathBuf` -through operations; lossy strings are presentation only. +through operations; lossy strings are presentation only. File rows and directory +completion request separate projections of the same bounded traversal. On Linux, +the projected read uses observed directory record types with descriptor-relative +lookup for unknown entries and directory-link completion +([ADR 0167](../adr/0167-local-listings-project-observed-entry-types.md)). Read-only browsing may follow directory links and accepts linked parent navigation. Strict traversal, source streams and mutations reject linked ancestors. Unix uses @@ -202,7 +238,7 @@ enumerates through independent native handles. During atomic publication, a lock guard file keeps the leaf nonempty and prevents reparse conversion. It is removed after candidate cleanup or committed publication. Windows identities preserve full 128-bit file IDs, with a distinct native fallback identity for shorter file IDs. -See [ADR 0162](../adr/0162-windows-held-directory-capabilities.md). +See [ADR 0165](../adr/0165-windows-ancestry-publication-guards.md). Directory pins and cursors reopen the captured object through native relative `NtCreateFile`; they avoid Win32 `ReOpenFile`, which can reject directory handles on Windows despite backup semantics. A shared acquisition module keeps native @@ -229,8 +265,10 @@ committed warning, never permission to repeat the publication. See `nocterm-transfer-runtime` implements `TransferService` over injected `LocalFs` and `RemoteFs` ports. It schedules bounded discovery and four workers, uses 32-KiB chunks with at most eight acknowledged upload chunks per batch, and owns entropy, -cancellable reservations and cleanup. Local operations run through bounded blocking -slots; the adapter imports no concrete filesystem adapter or GPUI. +cancellable reservations and cleanup. Local operations share a bounded blocking +dispatcher with one more slot than the file worker limit. This lets discovery +make progress while all file workers wait for native I/O. The adapter imports +no concrete filesystem adapter or GPUI. Downloads and relays walk remote sources through one bounded DFS. Its destination retains either a held `LocalDirectory` or the admitted remote filesystem and parent @@ -300,6 +338,17 @@ See [ADR0022](../adr/0022-agent-storage-owners.md). ## Agent usage boundary +Native ACP reads at most 16 MiB per inbound JSON-RPC line. The outbound line +budget adds the Base64 expansion of a full accepted image collection, with +rounding for each attachment. Large image prompts use a per-connection handoff +between command preparation and the outgoing line writer. The SDK assigns the +request ID and correlates the response as usual. The line writer consumes the +internal ticket, checks the full escaped JSON size, and writes the envelope and +image segments from the original shared bytes. The handoff can hold one queued +prompt and releases it on writer teardown. Other prompts use the ordinary SDK +serialization path. The adapter owns the envelope and response mapping. +See [ADR 0178](../adr/0178-acp-budgets-inbound-and-outbound-lines-separately.md). + The authenticated MCP relay belongs to `nocterm-acp`. Accepted sockets use blocking reads. Its five-second authentication deadline is cleared on the retained buffered reader itself; pipelined MCP bytes survive authentication and established sessions @@ -309,20 +358,15 @@ authentication, EOF, registration revocation and bridge shutdown without recordi tokens or protocol contents. The ACP adapter maps the connected agent's context usage, token totals and usage -metadata into AI's neutral records. No adapter in Nocterm reads provider sign-in -tokens or session logs, or requests private provider account endpoints. The agent -owns its authentication, requests and state files +metadata into AI's neutral records. The Codex ACP session-info extension +`_meta.codex.threadStatus` is mapped to an optional typed active/idle observation; +other metadata and unknown status values do not decide activity. No adapter in +Nocterm reads provider sign-in tokens or session logs, or requests private +provider account endpoints. The agent owns its authentication, requests and state files ([ADR 0105](../adr/0105-provider-usage-through-acp-only.md)). ## Agent workspace and sandbox -On Windows the launcher uses case-insensitive environment names, preserves the -system search path and starts agents and `taskkill` without a console window. -Bare commands missing from `PATH` are also searched in the usual Node.js install -locations; a matching directory is prepended for child scripts. Resolved Windows -paths use the ordinary drive form accepted by `cmd.exe` -([ADR0163](../adr/0163-windows-agents-start-hidden-with-the-systems-search-path.md)). - `nocterm-acp::NativeWorkdirResolver` creates the explicit private default workspace through the shared foundation helper and canonicalizes user-selected roots. One private path resolver supplies facts to AI's pure policy and revalidates them before @@ -366,9 +410,19 @@ worker until actual return, isolating optional country acquisition from other fa `nocterm-image-codec::NativeImageCodec` implements AI's image inspector and thumbnailer without filesystem access, GPUI or its own workers. PNG, JPEG, GIF and WebP decoding applies shared pure preflight before bounded decoder allocation: -4096 pixels per axis and 64 MiB. It validates full decode against header facts. -Previews preserve aspect and alpha, fit requested bounds up to 640 pixels, and -encode PNG through a sink capped at 4 MiB. Native errors retain typed causes. +4096 pixels per axis and 64 MiB. It validates decoded data against header facts. +Non-interlaced RGB8 and RGBA8 PNGs can validate the first frame and shrink it +for a standalone preview using a reusable output row. Shrinking keeps only +the current output band sums, the previous row sums and the bounded preview. +Both row paths check the full-frame size limit before reading the pixels. +When the first frame covers the canvas and its unexpanded raster exceeds the +4 MiB preview byte budget, attachment inspection validates these PNGs by row +and lets the preview task shrink the source on demand after admission. +Previews preserve aspect and alpha and fit requested bounds up to 640 pixels. +The display projection moves the scaled pixels as owned RGBA8, and callers of +the encoded operation get a PNG through a sink capped at 4 MiB. Native errors +retain typed causes. Single-image preparation can hand the same bounded decode +to either preview operation through the inspector's transient source. Remote OS acquisition belongs to `nocterm-connections-io::NativeOsDetector`. Its 16-KiB release reads use bounded chunks and explicit best-effort close on every @@ -425,7 +479,10 @@ Already admitted remote A operations retain their existing cancellation limits. Personal-vault refresh snapshots publish monotonically within a collection: an older cursor cannot replace a newer cached deletion. Identical refreshes leave the cache file -untouched, and reading one credential copies only its encrypted object and envelope. +untouched. Credential reads borrow ciphertext from the captured immutable snapshot. +A list opens the collection key once and decodes only the metadata it returns. +At most two vault lists take operation permits at once, and their record batches +yield cooperatively so other tasks on the Hub runtime can run. Account-cache encoding and acquisition share a 32 MiB file limit; a refused oversized publication preserves the previous readable file. @@ -471,9 +528,13 @@ attachments, sends the message and resolves at the end of the first run that sta it, cancel stops the run, approvals answer the chat's pending approval, and the model option sets the chat's model. Runs started from another device become neutral turn notices. A `Watch` per open chat is the only stream; nothing polls. `HubChatRepository` decorates the -local `ChatRepository`: in a hub environment it lists, renames, pins and deletes the hub's chats -and keeps only which local documents started which hub chats in a private file; a hub chat's -transcript is never written locally. +local `ChatRepository`: in a hub environment it lists, renames, pins and deletes the hub's chats. +Each account has a private cache of chat metadata and local document IDs. The adapter runs one +`ListChats` at a time for that account, with at most one follow-up. It checks the captured login +before publishing results. Publications signal the matching hub's history to read the cached rows +without scheduling another `ListChats`. The address-only cache from older releases supplies local document +IDs only after the hub lists their chat IDs for the current account. Hub transcripts stay on +the hub. ## Agent command execution diff --git a/docs/architecture/dependencies.md b/docs/architecture/dependencies.md index 0eb28d52..80259595 100644 --- a/docs/architecture/dependencies.md +++ b/docs/architecture/dependencies.md @@ -67,7 +67,7 @@ Derived from Cargo manifests. Check boundaries with `cargo xtask architecture`. | `nocterm-projects` | feature | `nocterm-containers`, `nocterm-explorer`, `nocterm-plugin-model`, `nocterm-project-model`, `nocterm-project-providers`, `nocterm-project-service`, `nocterm-session`, `nocterm-store`, `nocterm-ui`, `nocterm-workspace`, `nocterm-workspace-ports` | Connection-bound workspace library, creation and nested terminal presentation. | | `nocterm-session` | domain | `nocterm-core`, `nocterm-settings` | Transport-agnostic session contract: commands, events, prompts and the remote file system. | | `nocterm-settings` | foundation | `nocterm-core` | User settings: typed sections and the file that holds them. | -| `nocterm-settings-ui` | feature | `nocterm-store`, `nocterm-ui`, `nocterm-workspace` | Settings tab. | +| `nocterm-settings-ui` | feature | `nocterm-settings`, `nocterm-store`, `nocterm-ui`, `nocterm-workspace` | Settings tab. | | `nocterm-snippets` | domain | | Snippet library, validation and connection matching. | | `nocterm-snippets-io` | adapter | `nocterm-core`, `nocterm-snippets` | Native snippet document acquisition, publication and draft identities. | | `nocterm-snippets-store` | service | `nocterm-core`, `nocterm-snippets`, `nocterm-store` | Checked snippet publication over shared persistence. | @@ -407,6 +407,7 @@ graph TD nocterm_session --> nocterm_core nocterm_session --> nocterm_settings nocterm_settings --> nocterm_core + nocterm_settings_ui --> nocterm_settings nocterm_settings_ui --> nocterm_store nocterm_settings_ui --> nocterm_ui nocterm_settings_ui --> nocterm_workspace diff --git a/docs/architecture/domain.md b/docs/architecture/domain.md index ba3a9364..55296d7d 100644 --- a/docs/architecture/domain.md +++ b/docs/architecture/domain.md @@ -61,13 +61,18 @@ preserves typed credential, JSON, launch and session-option causes. Profile encoding errors retain original typed TOML serializer causes through foundation `SharedError`; clones share the native diagnostic. Checked conflict classification and both 64 KiB mutation/profile limits remain domain rules. +Profile document snapshots share immutable rows until those rows are edited, +while retaining the same serialized document. An owned checked profile can be +prepared independently of a snapshot; insertion still checks live absence. `ConnectionRepository` describes blocking document calls without naming a file implementation; GPUI publication and observation scheduling stay outside the domain. `RecentUse` supplies semantic session-use inputs without workspace types or timestamps. `ObservationEpochs` tracks only live profile IDs. Supplied generations advance incarnation, exact target and manual icon/country stamps at each candidate transition; equal final payloads retain intermediate history. `ProfilePublication` projects immutable -live authority without serialized stamps or full document copies. +live authority without serialized stamps or full document copies. Readers share each +publication's immutable lookup table. Epoch transitions use temporary ID lookups and +retain the first matching profile for comparison with existing documents. Checked `OsId` and release aliases/marker eligibility are pure rules. `RemoteOsDetector` supplies typed acquisition results over a held session capability; legacy detected-fact strings retain their serialized representation. @@ -85,6 +90,8 @@ native typed causes and an actionable kind without protocol types in this domain commands, events, prompts and the `RemoteFs` contract. Launch and session-override validation returns typed field/constraint errors without filesystem access or value expansion; native transports reject invalid launches before starting I/O. +The directory projection for recursive walks retains link flags and permits +unresolved link targets ([ADR 0175](../adr/0175-remote-walks-skip-link-target-metadata.md)). `TextEncodingError` carries the configured `Charset` without retaining input text. `ExecOutput::collect_bounded` reports typed output overflow separately from an unknown command exit; the existing `collect` retains its bounded-prefix behavior. @@ -133,7 +140,16 @@ alacritty_terminal and encodes keyboard, mouse and paste input. It also owns `TextCodec`, the incremental charset decoder/encoder, and `ShellIntegration`, the bounded OSC directory and prompt observer. Shell observations grant no session or input authority; the caller still validates its captured session and admits -input before recording it with the observer. These domain crates do not know +input before recording it with the observer. An emulator search is keyed by the +searchable grid version. Cell edits, reflow, history eviction and screen switches +invalidate positions. A completed search can provide a bounded ordinal span +plus its endpoints for navigation. A new span can be centered on an ordinal +from the same grid version. Regex work maps byte offsets to cells using runs +within each logical line, with separate positions for column jumps and combining +scalars. Protocol replies and pending synchronized text preserve +the current search until a grid mutation is applied. The paint generation +tracks changes to rendered data independently of the output activity stamp used +for session idle detection. These domain crates do not know the workspace or GPUI. Recording diagnostics preserve native I/O through immutable foundation `SharedError`. @@ -175,15 +191,30 @@ VT's literal Unicode search uses bounded KMP scan steps over grid cells and thei combining characters, with memory proportional to the query rather than the number of matches or history size. It supports case sensitivity and Unicode whole-word boundaries, preserves soft wraps and can match an explicit hard line -break. Regex mode joins soft wraps but matches only within each complete logical +break. Search and bounded history reads use the grid's existing occupied-cell +bound to skip untouched blank suffixes on rows that end a logical line. +Regex mode joins soft wraps but matches only within each complete logical line. It limits each line to 64 KiB, caps compiled regex size and returns an explicit typed `SearchError` when a limit is exceeded. Regex compilation retains -its native cause; cancellation and obsolete generations cannot publish matches. -Regex batches run off the UI thread; -Terminal schedules scan slices and invalidates matches when output, geometry or -screen changes. A rapidly changing buffer can defer a complete result, but -stale highlights are cleared and input remains responsive. Search highlights -and clipboard selection are independent. +its native cause and the compiled query is reused when a scan restarts. Regex +batches run off the UI thread. Terminal schedules scan slices and clears stale +highlights when output, geometry or screen changes. A historical search anchor +moves with its retained row and expires on eviction, grid resize or reset. +A completed scan can retain one checkpoint at a hard line boundary before +the mutable rows. Without a reusable checkpoint, a completed search keeps +only navigation. A refresh of the same query can restore the bounded +navigation span and revisit the tail while primary history and layout agree. +As rows enter history, a refresh can advance its checkpoint at the next +safe logical-line boundary before the visible rows. +After eviction, reuse requires a known logical-line boundary and cached matches +that prove the exact remaining count and selection. Literal queries containing +a hard line break require a full scan after eviction. The retained navigation +span covers a bounded range, and missing ordinals can be searched on demand. +The grid version must still match when the result is published. A rapidly changing buffer can defer a complete result, so Find +labels the last confirmed count as updating while it checks the new grid. +Search highlights and clipboard selection are independent. The viewport resolves the current match's +highlight range once per snapshot and writes each visible row directly into the +reused frame buffer. ## Line metadata @@ -195,11 +226,13 @@ outside PTY columns/selection and hides it in alternate screen. See the ## Themes -`nocterm-themes` is a GUI-independent domain crate. It parses original Zed JSON, -loads user files and installed extension manifests, maps palettes, and provides a -bounded registry client and archive installer. The installer accepts only direct -regular `themes/*.json` files and publishes a validated pack through a staged -rename. `nocterm-ui` resolves light/dark selections from its supplied SettingsHandle and the +`nocterm-themes` is a GUI-independent domain crate that parses supplied Zed +documents, maps palettes, and defines the library and registry ports. +`nocterm-themes-registry` loads user files and installed manifests and implements +bounded HTTP and archive installation. The installer accepts direct regular +`themes/*.json` files and publishes a validated pack through a staged rename. +A mutation receipt and the theme service share the same immutable catalog. +`nocterm-ui` resolves light/dark selections from its supplied SettingsHandle and the catalogue into effective Design tokens, retaining the base tokens for Nocterm Default. Imported component palettes start from empty configuration so the component fallback chain derives unmapped colors. The UI Appearance page retains the theme @@ -215,7 +248,9 @@ exec channel of the live connection and `nocterm-local` as a child process. `sh` reading `/proc` and `/sys` on Linux, PowerShell with CIM on Windows), splits its output into frames, parses them into raw counters and turns successive readings into loads, rates and bounded histories. It knows neither -GPUI nor the workspace. +GPUI nor the workspace. Linux reads only the aggregate CPU row when the +watch requests CPU without per-core data. The frame reader lends reusable text +to the platform parser and releases large buffers between frames. The Linux container platform instead builds own-cgroup v1/v2 CPU/memory recipes. It resolves process membership and controller mounts, parses bounded facts and derives CPU as percent of one CPU. Memory retains an optional observed limit; @@ -241,6 +276,8 @@ execution and retention behavior belong to the adapter's conformance tests. Podman command lines over `HostExec` — detection (exit 127 or `ExecError::NotFound` means not installed), listings parsed from either JSON dialect, the event stream and actions — and knows nothing of GPUI. +Listings decode one JSON row at a time and retain the typed container or image +data. Both dialects validate the complete input before returning a listing. `EventReader` turns the event stream into `Changes`: which of the two listings an event made stale. Commands run inside a container (health checks), attached terminals and copies change neither, an unchanged health status changes nothing, and an unreadable line @@ -262,8 +299,9 @@ batches. The optional dev-only `test-support` feature exposes an explicitly driv port fake, without scheduling or streaming. Execution belongs to the transfer adapter ([ADR 0018](../adr/0018-transfer-runtime-capabilities.md)). Runtime errors use core shared cause ownership through domain constructors, so standard source -traversal retains their original concrete classification. Snapshot clones retain -the same diagnostic identity; adapter code gains no core dependency for construction. +traversal retains their original concrete classification. Snapshot clones share the +diagnostic list and retain the same issue identities. A subsequent diagnostic can +change the tracker's list while an earlier snapshot keeps its original entries. A request is an upload, a download or a relay between two remote hosts (`Request::Relay`, `TransferDirection::Relay`). `Request::between` pairs two @@ -397,8 +435,11 @@ the history wire format and protocol-backed records retain their current represe AI owns pure image header preflight, checked format/dimension facts, exact prompt encoding and collection limits. ImageInspector supplies validated original bytes; prompt admission checks their Arc identity and facts against its own preflight. -ImageThumbnailer supplies bounded PNG previews, with pure checked dimensions and -output-size contracts. Native decoding and PNG encoding belong to an adapter. +ImageThumbnailer supplies bounded previews, with pure checked dimensions and +output-size contracts. Its display projection accepts owned RGBA8 pixels or +the existing checked PNG, as does the inspector's single-use decoded source. +Native decoding, resizing and PNG encoding belong to an adapter. +See [ADR 0176](../adr/0176-agent-previews-use-bounded-pixels.md). ## Display and Explorer settings @@ -485,8 +526,9 @@ declarative interpreter or the injected code runtime by the manifest's `runtime` resource limits, the call and reply wire types and their bounded postcard encoding. It is `no_std`, reads no file and runs no code, so the SDK can use it on the guest side. Its wire types embed the public types of `nocterm-plugin-api` (views, effects, events, errors, capability -values) and mirror only observations and setting values, so the golden file is what pins their -bytes. +values) and mirror only observations and setting values, so the golden file pins their +bytes. The runtime encodes directly from the snapshot's ordered entries. Byte-equivalence tests +cover the borrowed encoding and the owned call types, including terminal bars. `crates/plugin-abi/abi-golden.json` records its exports and canonical encodings and is kept fresh by `cargo xtask docs` ([ADR 0091](../adr/0091-user-plugin-code-runs-in-process-on-wasmi.md)). @@ -501,6 +543,11 @@ as guest-only, and it must stay out of the closure of `nocterm` plugin built on it, in a workspace of its own ([ADR 0092](../adr/0092-plugin-sdk-and-developer-sessions.md)). +The SDK's `TypedPlugin` and `TypedCx` opt in to borrowing the storage strings from the +encoded input for one call. The ABI reads the same bytes and the SDK looks up individual +keys without building a storage map. `Plugin` and `Cx` provide the owned snapshot for +guests that need it ([ADR 0170](../adr/0170-code-plugins-can-borrow-storage-for-keyed-reads.md)). + `nocterm-window-layout` owns the shell's layout as plain data and pure rules: the three zones of the status bar, panel groups with their members and separators (the catalog's, groups the user made and named, and panels that stand alone as groups of one), the tray of diff --git a/docs/architecture/feature.md b/docs/architecture/feature.md index 2fbd04dd..2dcf70b4 100644 --- a/docs/architecture/feature.md +++ b/docs/architecture/feature.md @@ -76,11 +76,15 @@ retain the original source; account equality in AI workspace capabilities applie to program tabs as well. A program whose host has no session stays ThisComputer. `nocterm-terminal` owns the terminal model/view and observes session -and settings changes. Private model owners separate session/prompt lifecycle, +and typed terminal settings changes (unrelated published settings revisions do not reapply emulator options). Private model owners separate session/prompt lifecycle, transport input and live leases, screen/search presentation, credential candidates and output recording. The view keeps independent frame-cache, keyboard/composition, cursor-clock and pointer owners. Selection and scrolling use named model actions; consumers only receive immutable emulator and painted-frame projections. See [ADR 0038](../adr/0038-private-terminal-state-owners.md). +The input owner holds a bounded order of pending clipboard reads and later user +input for the same connection. Program replies proceed independently. Prompt +and connection transitions cancel pending clipboard input +([ADR 0174](../adr/0174-terminal-paste-waits-without-blocking-the-window.md)). `open_attached` opens a tab on an `AttachedSession`, a session reached through its own transport (no feature uses it at present): `Event::Restore` repaints a fresh emulator without recording the picture, a repeated `Connected` @@ -90,21 +94,37 @@ output with semantic roles for timestamps, validated IP addresses, versions, process/user identifiers and important messages. ANSI colors and program styles, selection, search results and block cursors take precedence. This presentation never enters clipboard text, recordings or terminal transport. A per-view cache -uses output generation, viewport size, scroll offset and screen identity; blink -and selection repaint reuse roles, while palette colors resolve at paint time. +uses the emulator's paint generation, viewport size, scroll offset and screen +identity. Protocol traffic updates input state and sends replies independently of +screen invalidation. Recording publishes file path and error changes separately +from the grid, while the append handle exposes physical write progress. Scrolls +reuse decorated logical lines that overlap the previous viewport, identified by +their absolute grid row and visible wrap boundaries. Blink and selection repaint +reuse roles, and palette colors resolve at paint time. Only visible rows are examined, joining soft wraps on either screen. Matches touching a clipped soft-wrap boundary are skipped without reading off-screen text; complete fields elsewhere in that visible group still receive decoration. Work is bounded to 64 KiB of text and 65536 examined cells per frame, 4 KiB per logical group, 512 field matches per group and 4096 retained compact spans. Oversized -groups are left undecorated. Disabling `terminal.semantic_highlighting` releases -the cache and skips parsing; the Terminal settings switch is enabled by default. +groups are left undecorated. The overlap cache holds at most 512 visible groups. +After output changes, a group's exact visible text and wrap boundaries can reuse +the recognized roles. The view projects those roles against the current cell +positions and styles. Retained text and byte roles together use up to 128 KiB +per viewport. The cache drops groups that leave the viewport and clears on resize +or screen switch. Disabling `terminal.semantic_highlighting` releases the cache +and skips parsing. The Terminal settings switch is enabled by default. Theme ANSI colors are used only when their normal or bright variant meets 4.5:1 contrast against the terminal background, otherwise the original foreground is kept. Built-in field captures follow the bounded line decoration approach used by [iTerm2 triggers](https://iterm2.com/triggers.html) and the semantic log fields in [lnav formats](https://docs.lnav.org/en/latest/formats.html). +The pointer owns selection and accumulates fractional lines for edge scrolling +on GPUI's window frame clock. The edge speed depends on pointer position and +elapsed time. Releasing, changing input ownership or reaching a scroll boundary +ends the frame loop. Dragging within the same selection endpoint asks for no +new terminal snapshot. + Typed session options inherit global TERM, charset, proxy and output-recording defaults, with explicit profile/quick-connect overrides. A shared options form in `nocterm-ui` keeps settings and connection features independent. Terminal owns @@ -165,15 +185,19 @@ and checked transitions belong to `nocterm-connections-model`; the app supplies preloaded documents and repository writers. Editor, reload and quick-connect use injected identifiers/defaults retained by `Installed`; recent-use intents receive their timestamp from the service's injected clock. `Installed` retains the -actual `FactsService` entity. `FactsPresentation` projects immutable bounded flag -bytes to one cached GPUI image per country, with embedded fallback after a terminal -negative result. Raw fact persistence, detection admission and native job reservations +actual `FactsService` entity. `FactsPresentation` projects immutable flag bytes to +one cached thumbnail per country, with embedded fallback after a terminal negative +result. The largest side of a flag raster is capped at 128 device pixels. +Raw fact persistence, detection admission and native job reservations belong to the GPUI-only service. `ObservationDeps` arrives explicitly from bootstrap; no view performs native acquisition. Weak rotating source projections supply original Item/session receipts and retry refused work by re-reading live capabilities after -capacity events, without retaining a waiting request/FS payload. Icons and flags -reach other features only as images in `ConnectionSummary`. The empty workspace -projects its six most recent saved profiles through +capacity events, without retaining a waiting request/FS payload. Workspace event bursts share a deferred projection, retaining their admission opportunities until the sources settle. `FactsPresentation` +shares generated system icons between the sidebar, editor and connection summaries. +The last reference to a source releases its decoded raster and atlas entries. +Icons and flags reach other features as renderable metadata in `ConnectionSummary`. +The Agent attachment menu requests system icons and flags within its visible scroll region. +The empty workspace projects its six most recent saved profiles through `ConnectionDirectory`, using current names and the same icon and country policy as the sidebar. Quick destinations and deleted profiles are excluded. Selecting a recent server defers opening through the normal authentication path until the @@ -202,7 +226,8 @@ and comments on retained keys round-trip through the existing atomic writer. `nocterm-settings-ui` contributes a single settings Item with a page list. The app supplies a checked ordered catalog with explicit eager/lazy registration and a required default; validation invokes no factories. Each Item -constructs eager pages in order, reuses lazy pages and closes only constructed pages. The ordinary +constructs eager pages in order, reuses lazy pages and closes only constructed pages. The host follows +shared document diagnostics and save feedback; independent pages observe their own inputs. The ordinary and startup catalogs retain separate application policies ([ADR0057](../adr/0057-checked-settings-catalog.md)). Every control saves itself: switches and choices at once, text when typing pauses, on Enter and on blur. @@ -240,9 +265,22 @@ composition retains `Installed` and supplies it to each workspace. Transfers and its status widget retain the supplied TransferService port, so Show Transfers also works before Explorer is opened. The coordinator handles transfer intents and queue snapshots; pane entities own their views and emit typed intents without mutating siblings. +The workspace's panel visibility gates automatic home discovery, new directory +listings and deferred refreshes. Hidden panes track the current source and +finished transfers. First presentation loads the current source, and reopening +refreshes an affected directory once. Navigation already in progress can finish +while the panel is hidden. Local home discovery, listing, completion, statistics and mutations run through `LocalFs`/`LocalMutations` on background executors. `ListingState` exposes the presentation of navigation through a public query, rather than exposing pane state. +The local pane requests names, kinds and link flags and retains the accepted listing's +native directory and leaf names. +Visible rows derive display names and action paths from that listing, and +actions retain the owned paths when accepted. +The remote pane shares its accepted root listing with recursive statistics. +Display order comes from a compact index, and the walk counts entries in server +order. Descendant listings use the traversal projection described in +[ADR 0175](../adr/0175-remote-walks-skip-link-target-metadata.md). Configured local program dispatch uses the injected `ProgramOpener`; the local adapter owns process spawning and child reaping. @@ -323,7 +361,7 @@ and control ownership from [ADR0050](../adr/0050-retained-snippet-installation.m ## Monitor `nocterm-monitor-ui` consumes the workspace's dedicated `MonitorSource` projection. -The selected inner workspace session takes precedence; missing or unsupported +Selected-source queries read only the focused command capability (or the active central terminal), not all tab titles and locations. Full tab snapshots and large pane projections build transient address maps from the native tree; full terminal lists read only bottom placement and each original title. The shell frame reads the single-group identity directly, without projecting all tab IDs. Burst workspace events share one deferred selected-source refresh; settings observation follows the monitor section. The selected inner workspace session takes precedence; missing or unsupported workspace authority never falls back to the unrelated outer session or local runner. Ordinary local contexts retain the injected local policy. Cache identity includes the original surface and checked resource; watch generations reject stale detection @@ -375,8 +413,15 @@ disconnected or stale remote terminals refuse creation instead of falling back t local capabilities. Container rows preserve full engine/ID selection independently of truncated names, image labels and status summaries. An independent `ContainerPicker` owns captured inventory discovery, filtering and -exact selection. Search matches names, full IDs, images and engine without I/O or -changing a filtered-out selection. The fixed shared header retains the original +exact selection. Discovery starts when the Connection step shows Existing +container or the Custom image's Local images tab. Its task is canceled when +neither view needs it or the dialog closes. A completed discovery is shared by +both views for the lifetime of the wizard, with explicit Refresh in Existing +container. Search matches names, full IDs, images and engine without I/O or +changing a filtered-out selection. A successful host discovery prepares the image +index once. The container picker lays out only rows near the scroll viewport. +The local image picker shares the discovered snapshot and retains up to 25 +matches for its current query. The fixed shared header retains the original server. Image sources use a single full-width bounded result viewport. Projects retains Workspace for outer ProjectView admission, Panel/action @@ -432,6 +477,9 @@ every window on one host connection shares one watch through `Workspace::open_program`; the terminal runs them with `ProgramTransport` over `HostExec::terminal`, so no feature opens a connection of its own and the tab follows as the same host. +The panel prepares ordered rows when the host model or a fold changes. The list +measures and paints only its viewport and overdraw, retaining the top row by +identity where possible. Destructive confirmation captures the host executor, engine, object IDs and connection epoch when the dialog opens. Switching hosts or reconnecting invalidates that confirmation; completion asks only its original context's watch to @@ -455,6 +503,13 @@ vault in a small dialog without opening Settings and without depending on the vault feature. The credential list describes a key record by its fingerprint and never shows or saves the secret. +The Credentials tab owns the most recent credential metadata and prepares name +and server search terms when the service supplies a list. It uses a bounded +Settings viewport ([ADR 0166](../adr/0166-settings-pages-can-own-a-bounded-scroll-viewport.md)) +to build rows near the scroll position. Search and actions operate on the +current records, with edits addressed by credential ID. Closing the page or +locking the vault clears the metadata, search terms, and drafts. + In a hub window the connection editor also shows Agent access of a saved server, through the `ServerAgentAccess` port the application supplies with `EditorInputs::with_agent_access`; the switch acts at once, and a refusal is shown under it. Without an open session it first opens @@ -638,22 +693,50 @@ shows as a neutral turn notice and keeps the composer waiting until it ends ([ADR 0148](../adr/0148-hub-chats-run-on-the-hub-and-use-the-agent-chat-ui.md)). MessageList reuses one ImagePipeline for preview cache generations and remeasures rows only for accepted delivery. Its 32-entry, -64 MiB preview budget retains full immutable source identities and charges image/source -allocations; one installation shares four physical image jobs across attachments and previews. +64 MiB preview cache reserves each identity with a weak reference to the source allocation. +Loading accounts for the bytes held by the task and reserves bounded display output. +Ready entries retain their display pixels and the small allocation identity. When a pending +decode is using the space needed by another, admission waits for completion before evicting +a ready preview. One installation shares four physical image slots across attachments, queue edits +and previews. Waiting selections and queue edits receive newly available slots before +queued previews. At most four new selections wait per installation, with one preparation +per composer. Closing or switching composers cancels their pending preparation. An active +decoder retains its slot until the physical work finishes. +Preview jobs move native RGBA8 pixels into a GPUI frame after converting them to +BGRA in place. Encoded projections still use the bounded PNG decoder. The preview +cache owns the render image and releases its atlas entry after its last preview is +evicted or on clear. Workers reuse an image with the same dimensions and BGRA bytes. +The composer, queue and transcript reuse a preview when they share the same encoded +image allocation. Raw source bytes are charged during composer preview work. A loading +preview records which chat regions are waiting and remeasures only its waiting transcript +rows on delivery. Attachment preparation refreshes the footer. Preview delivery refreshes +the regions that requested it, that must retry after the loading limit clears, or that may +still display an evicted preview. Counts and remaining bytes are admitted before file acquisition or base64/decoder allocation. +When inspection supplies decoded pixels for the final file of a selection or a single +pasted image, the composer admits the originals first and transfers that decoder result +with its existing work permit to the preview task. The source lives only for in-flight work +([ADR 0177](../adr/0177-attachment-batches-reuse-one-inspection-decode.md)). Literal tool input and output keep their scroll offset in GPUI's keyed element state. Their axis masks consume wheel input before the transcript's mask; vertical input chains to the transcript at a text boundary or when the text fits, and horizontal input stays in the text viewport. MessageList keeps each agent message's and expanded reasoning's parsed Markdown per row, so a row -scrolled back into view keeps its parse and streamed text parses only what was -appended. PanelLayout keeps the panel's regions as cached views: the transcript, the +scrolled back into view keeps its parse. The chat document's transcript generation +marks replacements. Within one generation, stream updates and reveal ticks let the +row sanitize and parse just the appended text, unless an image marker crosses the +chunk boundary. PanelLayout keeps the panel's regions as cached views: the transcript, the history and the footer (approvals, status, queue, commands and composer), which is cached to its content and keeps its last height while reused. Any panel notify redraws every region; a change of the open chat redraws the transcript only when its rows or what they show changed, typing redraws the footer, and the coalesced redraw of other chats redraws the history only -when a listed row changed. Attachment +when a listed row changed. The history view retains filtered chat order and a +GPUI virtual list. Scrolling builds the rows in view, while the search field and +side selector stay in place. The viewport keeps a focused rename field alive and +anchors scrolled history to the same chat across reorderings. Transcript selection +uses the shared window frame loop for edge scrolling in its ancestor viewport. +Attachment preparation preserves chat/lifecycle/composer revision checks and admits a complete validated candidate collection atomically. The feature never decodes image data. Live ACP transcript admission checks its 20,000-row and 64 MiB resident budgets before mutation, including mixed text/tool/control updates. @@ -712,6 +795,8 @@ unsubscribe during callback destruction. UI owners retain the installation itsel The keymap page receives its actual KeymapHandle from the root's lazy page factory. +It retains the current revision's search terms and matching row indices. Its search +and column headings stay above the virtualized table inside a page-owned viewport. Its private search, recording and per-view message remain window-local; a retained weak observation subscription refreshes shared desired bindings and typed native save errors across windows. Deactivating a page releases interception; closing also releases @@ -744,7 +829,7 @@ behavior. Settings consumers retain their supplied service handles. See [ADR0053](../adr/0053-retained-settings-ui-installation.md) and [ADR0054](../adr/0054-checked-settings-text-receipts.md). Explorer panes and its settings page retain their original installation's settings -owner. Indexing reads policy at the existing scan request phase, and a local pane +owner. The settings page uses a bounded variable-height viewport over rule indices, retains its input owners and measures visible rows; it reads shared typed settings snapshots and observes only the Explorer section. Indexing reads policy at the existing scan request phase, and a local pane captures initial configured cwd before resolving home while retaining the original navigation guard. Opening a context menu snapshots its label; selecting its file open action reads the latest published policy from that same installation during diff --git a/docs/architecture/foundation.md b/docs/architecture/foundation.md index 298b0f65..6c0e9b07 100644 --- a/docs/architecture/foundation.md +++ b/docs/architecture/foundation.md @@ -24,7 +24,8 @@ See [private file publication](../adr/0015-private-file-publication.md). `persist::RevisionedFile` retains observed top-level table fingerprints and coordinates configuration publication with a persistent sibling OS lock. Settings compare owned tables; profiles compare the whole document. External changes return a typed conflict and preserve -the newer file. Unknown settings tables retain their current formatting and values. This +the newer file. Unknown settings tables retain their current formatting and values. Saving +leaves those parsed tables untouched and retains their freshly checked fingerprints. This coordinates Nocterm writers; a non-cooperating editor can still race the final rename. See [ADR0137](../adr/0137-observed-configuration-publication.md). `AtomicPublication::publish_new` instead refuses every existing destination and @@ -52,6 +53,11 @@ the crate that uses it: `[ssh]`, `[local]` and `[logging]` in `nocterm-session`, `[vault]` in `nocterm-vault-ui`. Owners register their sections at startup and read them with `cx.setting::()`; `cargo xtask architecture` fails if the settings reference does not list a section. +Document copies share immutable original tables and registered section values; +an edit copies only its own typed section before sanitizing and replacing it. +Semantic comparison and broken-table ownership remain value-based. Immutable +diagnostic projections are shared by value-only edits and rebuilt after section +registration or repair of a broken table. `nocterm-core::bounded_io` supplies in-memory counting and byte-buffer writers with caller-supplied caps. Refused writes preserve the accepted prefix; consumers own diff --git a/docs/architecture/service.md b/docs/architecture/service.md index 4e616793..87087642 100644 --- a/docs/architecture/service.md +++ b/docs/architecture/service.md @@ -44,9 +44,14 @@ and keeps its agent transfers in a private `OwnedTransfers` book bound to the or `nocterm-containers-service` owns `ContainerHosts`, the one watch of each host connection's containers and images, shared by every window. Each watch is keyed by its -`HostExec`. It follows one engine event stream, lists only what `EventReader` reports -changed (once per burst), and stops its programs when the last holder lets it go -([ADR 0131](../adr/0131-one-container-watch-per-host-connection.md)). +`HostExec`. It follows one engine event stream in the background and publishes completed +listings to the host entity. The first relevant event or refresh request starts a fixed +settle window. The watch lists only what changed and stops its programs when the last +holder lets it go. +A broken event stream can reopen immediately and refresh both lists. Repeated short +streams use the ordinary retry interval until a subscription stays open for that interval +([ADR 0131](../adr/0131-one-container-watch-per-host-connection.md), +[ADR 0171](../adr/0171-container-watches-recover-once-without-waiting.md)). `nocterm-project-service` owns the durable workspace catalog and the open-window registry used to focus an already opened workspace. It uses @@ -98,6 +103,13 @@ and the footer, without changing remembered docked widths. `ConnectionDirectory` methods take the workspace as a weak handle and are called outside workspace updates, because opening a connection updates the workspace. +A session's explicit activity observation can start or end an autonomous turn +without inserting a user prompt or granting a tool scope. A client-owned prompt +still settles on its own response; the latest observed activity is reconciled +before dispatching the next queued message. Repeated activity observations +without a phase change do not trigger a redraw. Session replacement clears the +observation. + Saved history starts as a catalogue of at most 200 metadata rows, with transcript files as the source of truth. Obsolete metadata sidecars are ignored. Opening or editing a row loads its document in the background. A shared loading permit @@ -236,6 +248,17 @@ feed the later one stands ([ADR 0149](../adr/0149-agent-access-connects-with-sav Feed acquisition runs off the foreground before planning, capped at 256 pages, 16,384 changes, 16 MiB of encoded payload plus metadata and a two-minute deadline. Non-progress, repeated or oversized cursors fail without advancing the agreed cursor or applying a partial plan. +Planning borrows the local document and agreed snapshot in one foreground turn. +The in-memory Hub mirror applies a pass of new profiles in groups of up to 64. +The round prepares one group at a time on the background executor using the +domain profile size check, then checks expected absence at publication. A group +publishes its accepted entries together and records their agreement before the +next foreground turn. Rejected entries remain ahead of the cursor. +Agreed snapshots share their profile map until it changes. An unchanged cursor +skips persistence admission when the document is clean, while dirty state can retry. +Detaching clears the mirror in one checked publication, preserving remembered +folders and applying the usual recent-destination effects. The next attachment +starts its watch and feed only after successful clearing and agreement reset. See [ADR 0101](../adr/0101-profiles-synchronize-through-a-replica-beside-the-local-document.md). ## Raw connection facts @@ -256,8 +279,10 @@ and alternating raw flag/probe lanes. There is no native cancellation guarantee, production pool, hidden runtime/global lookup or waiting filesystem request queue. Raw CountryCode flag requests are independent of live sessions and detection policy: -persisted startup keys, manual saved choices and editor drafts keep their previous -behavior. DNS/GeoIP and OS require an original connected matching session. A terminal +startup batches distinct persisted keys and reads manual choices once. Subsequent +manual choices are admitted when the committed profile projection advances. +Editor drafts can request a country directly. DNS/GeoIP and OS require an original +connected matching session. A terminal flag negative result is cached; image decoding/presentation stays in the feature. Known capture reuses Persisted/ShutdownCoordinator; closing blocks admissions and late completions from mutating captured data. See [ADR0048](../adr/0048-guarded-connection-facts.md). @@ -328,7 +353,7 @@ physical write. Typed section edits register/read their section, apply the callb to a clone and insert its sanitized value only on success. Memory edits publish synchronously; durable receipts retain the existing queue/backend timing and return semantic settings revisions, including unchanged revisions for successful no-ops. -The original infallible edits and their consumers retain their behavior. Dev-only +The original infallible edits and their consumers retain their behavior. Typed section observers retain one immutable section snapshot and skip unrelated published revisions; global revision observers remain available for receipts and multi-section consumers. Dev-only store test-support supplies the shared first-write gate and snapshot recording used by service and UI persistence fixtures. @@ -358,8 +383,16 @@ queue with gesture tokens, rate limits and the apply-time re-check, fault counti installed/enabled plugins and renders, and the `PluginRecords` and `PluginData` ports with their documents. Production receives prepared native packages/runtime instances; accepted management results await actual persistence receipts. Destructive data changes hold affected -host mutations through physical completion. See +host mutations through physical completion. A successful render hands off the checked view +to the renderer ([ADR 0168](../adr/0168-plugin-views-carry-validation-to-the-renderer.md)). See [ADR0141](../adr/0141-versioned-plugin-publication.md). +Built-in runtimes borrow the installed plugin's storage during the synchronous call. The host +assembles the other snapshot fields and resolves guest-visible settings directly from the stored +fields ([ADR 0172](../adr/0172-runtime-calls-borrow-host-snapshot-data.md)). +Host-originated events invalidate the views of the guest that handled them. The window driver +coalesces these refresh requests, and the installed-plugin catalog follows management changes. +Completed HTTP answers retain their existing in-flight slot until delivery. The host drains +them in completion order and yields to platform input between slices of slow guest calls. Neither does I/O; the application implements the two storage ports over the shared persistence service. For a developer session (`nocterm plugin dev`) the host also offers `SessionRecords` and `SessionData`, in-memory implementations of the same two ports: composing them leaves the host no @@ -382,7 +415,7 @@ crates are in the [guardrails](guardrails.md#isolation-of-the-plugin-crates). reaches a hub only through the `HubTrust`, `HubSignIn`, `AccountDevices` and `AccountKeyLock` ports of `nocterm-hubs-model`, passed in `Deps` by the composition, and reads and edits the `[hubs]` section through `SettingsHandle`. `install` registers the section and returns an `Installed` -with the one `Hubs` entity every window shares ([ADR 0099](../adr/0099-windows-have-no-environments.md)). +with the one `Hubs` entity every window shares ([ADR 0099](../adr/0099-windows-have-no-environments.md)). The registry subscribes to the hubs section only; metadata edits keep existing entries in place, and membership changes reconcile by canonical address while retaining current status and attempts. - `Hubs` lists the known servers in the order of the settings with a `HubStatus` for each: `SignedOut`, `Connecting`, `Online`, `Offline` with the time of the next attempt, `Revoked`, @@ -432,7 +465,10 @@ agents and agent servers as last listed (a failed listing keeps the last lists a problem), the follow of the hub's chat list (re-subscribed with growing delays, ending when the hub is untracked) and the launches of its agents as ordinary `AgentLaunch`es, which the agent installation offers in that hub's windows only. It emits `Changed` when a hub's lists change and -`ChatsChanged` on every chat hint, so a history of that hub reads its chats again. Agent access +`ChatsChanged` on server hints, so history requests a fresh catalog for that hub. It emits +`ChatCatalogPublished` when that hub's local cache is updated, so history can read the published +rows directly. A pending server hint retains its captured login and takes precedence over cache +publications while that login is current. Agent access of a saved server is a transition of the same entity: `session_open` says whether a session to it is open, `grant_access` writes the agent key's line through that session (`AgentHosts` of `nocterm-ssh-keys`) and only then records the @@ -447,4 +483,7 @@ scope. Consumer subscriptions contribute metrics and cadence; the union and fast select one generation-bound watch. One latest raw reading is shared, while feature models retain their own histories and samplers. The last subscriber cancels native work and the installation registry retains weak references. Descriptive host names cannot merge authority. +A collector that produced spaced readings gets a retry after one second when it ends. +Short-lived collectors use the ten-second interval after that attempt. +A collector can earn another early retry by reporting data over ten seconds. See [ADR0138](../adr/0138-shared-captured-monitor-collection.md). diff --git a/docs/architecture/ui.md b/docs/architecture/ui.md index 4eada698..0361dd84 100644 --- a/docs/architecture/ui.md +++ b/docs/architecture/ui.md @@ -16,8 +16,8 @@ presenting a form error; malformed numeric text never becomes a saved override. `nocterm-ui` projects tokens/settings into the standard GPUI Kit theme and accepts an explicitly installed SettingsHandle and returns its retained UiReady witness; it provides shared icons, terminal styling, standalone drag previews and operational notices. One retained ThemeUi owns catalog, settings and Design paint subscriptions. -Catalog changes resolve effective tokens; published settings resolve and paint directly -when tokens remain unchanged. Design observation paints only, preserving the one-way +Catalog and theme selection changes resolve effective tokens. Published changes to +appearance mode or card geometry repaint directly. Design observation paints only, preserving the one-way projection. Appearance callbacks apply the same supplied settings owner. UI initialization paints initial supplied policy; live changes require retaining ThemeUi. Terminal styling and form surfaces use supplied TerminalSettings plus the current paint tokens/theme. Optional toolkit button metrics are projected from design tokens once; @@ -115,6 +115,9 @@ comparison. Snapshots rotate only after successful submission with an unchanged atlas revision, and invalidation releases their storage. The [WGPU patch notes](../../vendor/gpui-pre-wgpu/NOCTERM_PATCH.md) record the Linux scope, provenance and tests. Linux scroll-copy is not enabled. +The [Wayland platform patch](../../vendor/gpui-pre-linux/NOCTERM_PATCH.md) +keeps clipboard and drag transfers in the platform event loop with bounded +nonblocking writes so a slow reader cannot delay unrelated input. Measured retained scrolling still increased CPU per event by about 3.3–3.8% on the tested Radeon/Vulkan system, so it is not enabled by default. The shared GPUI Div scroll handler uses the same snapped and rounded bounds as @@ -415,6 +418,9 @@ agent resolution and credential policy remain in the AI domain and Agent page. `SettingsPageSpec` supports the same plain lazy guest factories and contextual builtin factories. The latter receive only their original SettingsHandle and per-Item save feedback. The additive flush operation leaves existing guest lifecycle contracts intact. +The complete factory can request the host's available height with +`SettingsPageSpec::with_viewport` and scroll its own contents +([ADR 0166](../adr/0166-settings-pages-can-own-a-bounded-scroll-viewport.md)). `SettingsPage::reveal(anchor, window, cx)` lets a page bring forward the part an anchor names (a plugin id on the Plugins page, `layout/` for an item in the editor of Appearance); the default returns `false` and the host `SettingsPageHandle::reveal` forwards it to a constructed page diff --git a/docs/plugins/guide.md b/docs/plugins/guide.md index 88448e4c..779d03e7 100644 --- a/docs/plugins/guide.md +++ b/docs/plugins/guide.md @@ -232,6 +232,12 @@ nocterm_plugin_sdk::export!(Hello, concat!(env!("CARGO_MANIFEST_DIR"), "/plugin. in the manifest. A reply with more than eight effects is refused as a whole, none of them applies, and the refusal counts as a fault of the plugin. +A plugin that reads a few stored keys per call can implement `TypedPlugin` with `TypedCx` +and export it with `export!(MyPlugin, manifest, typed)`. It uses the same typed read and +log methods, and `stored` reads from the input without building a storage map. Use `Plugin` +and the `snapshot()` method on `Cx` to enumerate storage or access the whole snapshot. The Focus Timer +uses the typed dispatch. Its native tests use `Host::render_typed` and `Host::event_typed`. + The crate type is `cdylib`, and the module is built for `wasm32-unknown-unknown`. `export!` puts `plugin.toml` into the module as the custom section `nocterm.manifest`, so the `.wasm` file is the whole package, and writes the exports of the ABI. Write `runtime = "wasm"` in that manifest. diff --git a/examples/plugins/focus-timer/src/lib.rs b/examples/plugins/focus-timer/src/lib.rs index a4ac793e..85562590 100644 --- a/examples/plugins/focus-timer/src/lib.rs +++ b/examples/plugins/focus-timer/src/lib.rs @@ -5,7 +5,7 @@ //! snapshot, so an instance the host restarts after a fault carries on where it was. use nocterm_plugin_sdk::{ - Cx, Plugin, ViewBuilder, + TypedCx, TypedPlugin, ViewBuilder, api::{Effects, Event, LocalId, Refresh, Tone, View}, effect, observe::Clock, @@ -21,27 +21,27 @@ const DEFAULT_GOAL: i64 = 25; pub struct FocusTimer; /// Minutes since the stored start, when the clock is readable and a round has started. -fn elapsed(cx: &Cx<'_>) -> Option { +fn elapsed(cx: &TypedCx<'_>) -> Option { let now = cx.observe::().ok()?.unix_minutes; let start = cx.stored(START)?.parse::().ok()?; Some((now - start).max(0)) } -fn goal(cx: &Cx<'_>) -> i64 { +fn goal(cx: &TypedCx<'_>) -> i64 { cx.setting("goal") .and_then(|value| value.as_number()) .map_or(DEFAULT_GOAL, i64::from) .max(1) } -fn rounds(cx: &Cx<'_>) -> u16 { +fn rounds(cx: &TypedCx<'_>) -> u16 { cx.stored(ROUNDS) .and_then(|text| text.parse().ok()) .unwrap_or(0) } impl FocusTimer { - fn bar(cx: &Cx<'_>) -> View { + fn bar(cx: &TypedCx<'_>) -> View { let mut view = ViewBuilder::new(); let row = view.row(None); let label = match elapsed(cx) { @@ -53,7 +53,7 @@ impl FocusTimer { view.build() } - fn panel(cx: &Cx<'_>) -> View { + fn panel(cx: &TypedCx<'_>) -> View { let mut view = ViewBuilder::new(); let column = view.column(None); let goal = goal(cx); @@ -78,7 +78,7 @@ impl FocusTimer { view.build() } - fn open(cx: &Cx<'_>) -> Effects { + fn open(cx: &TypedCx<'_>) -> Effects { let mut requests = Vec::new(); if cx.stored(START).is_none() && let Ok(now) = cx.observe::() @@ -99,7 +99,7 @@ impl FocusTimer { effect::effects(requests) } - fn reset(cx: &Cx<'_>) -> Effects { + fn reset(cx: &TypedCx<'_>) -> Effects { let Ok(now) = cx.observe::() else { return Effects::default(); }; @@ -122,8 +122,8 @@ impl FocusTimer { } } -impl Plugin for FocusTimer { - fn render(&mut self, cx: &mut Cx<'_>) -> View { +impl TypedPlugin for FocusTimer { + fn render(&mut self, cx: &mut TypedCx<'_>) -> View { if cx.local().as_str() == PANEL { Self::panel(cx) } else { @@ -131,7 +131,7 @@ impl Plugin for FocusTimer { } } - fn on_event(&mut self, cx: &mut Cx<'_>, event: &Event) -> Effects { + fn on_event(&mut self, cx: &mut TypedCx<'_>, event: &Event) -> Effects { let Event::Activated { key } = event else { return Effects::default(); }; @@ -146,5 +146,6 @@ impl Plugin for FocusTimer { nocterm_plugin_sdk::export!( FocusTimer, - concat!(env!("CARGO_MANIFEST_DIR"), "/plugin.toml") + concat!(env!("CARGO_MANIFEST_DIR"), "/plugin.toml"), + typed, ); diff --git a/examples/plugins/focus-timer/tests/plugin.rs b/examples/plugins/focus-timer/tests/plugin.rs index 553ff7c6..4826e0ba 100644 --- a/examples/plugins/focus-timer/tests/plugin.rs +++ b/examples/plugins/focus-timer/tests/plugin.rs @@ -22,7 +22,7 @@ fn host() -> Host { fn press(host: &mut Host, local: &str, key: &str) -> Vec { let effects = host - .event(&mut FocusTimer, local, Event::Activated { key: key.into() }) + .event_typed(&mut FocusTimer, local, Event::Activated { key: key.into() }) .expect("the event is answered"); effects .0 @@ -46,11 +46,11 @@ fn texts(view: &nocterm_plugin_sdk::api::View) -> Vec { fn the_bar_shows_the_minutes_since_the_stored_start() { let mut host = host(); host.observe::(clock(1_000)); - let idle = host.render(&mut FocusTimer, "bar").unwrap(); + let idle = host.render_typed(&mut FocusTimer, "bar").unwrap(); assert_eq!(texts(&idle), ["Focus"]); host.store("start", "988"); - let running = host.render(&mut FocusTimer, "bar").unwrap(); + let running = host.render_typed(&mut FocusTimer, "bar").unwrap(); assert_eq!(texts(&running), ["Focus 12m"]); } @@ -102,7 +102,7 @@ fn the_panel_meter_follows_the_goal_setting() { let mut host = host(); host.observe::(clock(1_010)).store("start", "1000"); - let view = host.render(&mut FocusTimer, "panel").unwrap(); + let view = host.render_typed(&mut FocusTimer, "panel").unwrap(); assert_eq!(texts(&view)[0], "10 of 25 min"); assert!(view.nodes.iter().any(|n| n.kind == NodeKind::Meter(40))); @@ -152,6 +152,6 @@ fn closing_the_panel_asks_the_host_to_close_it() { fn a_plugin_without_the_clock_still_draws() { let mut host = host(); host.observe_error::(HostError::Unavailable); - let view = host.render(&mut FocusTimer, "panel").unwrap(); + let view = host.render_typed(&mut FocusTimer, "panel").unwrap(); assert!(texts(&view)[0].starts_with("No round yet")); } diff --git a/licensing/sources.json b/licensing/sources.json index 4112f193..69e70593 100644 --- a/licensing/sources.json +++ b/licensing/sources.json @@ -472,10 +472,10 @@ }, { "packages": [ - "russh@0.63.3" + "russh@0.65.1" ], "path": "upstream/brendanzab-gl-rs-license-cfc7749b96f6.txt", - "url": "https://raw.githubusercontent.com/warp-tech/russh/f33baf439be8c59c49cb6cb2ae5976c579495bdf/LICENSE.txt", + "url": "https://raw.githubusercontent.com/warp-tech/russh/b33092aad1e51c66258a12e8b83fc473a68d9d34/LICENSE.txt", "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" }, { diff --git a/scripts/perf/README.md b/scripts/perf/README.md index 0471da00..ee516521 100644 --- a/scripts/perf/README.md +++ b/scripts/perf/README.md @@ -51,3 +51,407 @@ For an explicitly authorized remote scenario, add `--ssh user@host --ssh-key connected session, and sends the same bounded key sequence. It creates shell sessions and uses the existing host-key policy; it does not approve unknown keys. Increasing `--ssh-tabs` creates additional remote terminal tabs. + +## Marked Wayland traces + +`analyze.py` correlates activity in an isolated compositor trace with optional +userspace CPU samples. It reports new buffer commits and their gaps, input +cadence, the most recent callback-to-commit delay and foreground leaf symbols. +These metrics describe the application and compositor protocol. + +```sh +python3 scripts/perf/analyze.py /tmp/run.frames --pid "$app_pid" \ + --samples /tmp/run.samples +``` + +Trace lines contain monotonic seconds, an event name and two integer fields. +Use `mark WORKLOAD_ID 1` and `mark WORKLOAD_ID 0` for workload boundaries, +`buffer SURFACE_ID PID` for a commit with a newly attached buffer, and +`callback SURFACE_ID CALLBACK_ID` for a frame callback. The callback metric +assumes a single measured client on the compositor during each workload. +The optional samples are collected on the same clock and should be symbolized +with `perf script -F comm,pid,tid,time,event,ip,sym,dso`. Record userspace +`cpu-clock:u` with `--clockid mono`, and use a binary with symbols. +`--surface` overrides the default choice of the process's most active surface. + +## GPU stage timings + +Launch an isolated native wgpu build with `NOCTERM_GPU_TIMING=1` and INFO +logging to collect sampled timestamps from the app's GPU command encoder. +The `nocterm_gpu_timing` lines include the scene interval and, when +`present_copy=true`, the retained image copy interval. Direct and retained +frames that render the scene can be sampled. Copy-only presentations and +atlas uploads preceding the scene encoder are outside those intervals. + +The diagnostic samples one in eight scene frames when its single readback +slot is available. It polls the GPU without waiting for completion. The +readback age includes time until the app polls again and is unsuitable as a +GPU latency measurement. Collect CPU and frame pacing data in separate runs +with this diagnostic disabled. The adapter must support timestamp queries in +command encoders. Pass `--gpu-log /tmp/gpu-run.app` to the trace analyzer to +append a summary of that entire GPU timing log. Use a short log for a single +workload when comparing stage distributions. + +## Native operation benchmarks + +Run these on an otherwise quiet host. The local command benchmark samples the +CPU time and scheduling slices of the three command workers per live process +through Linux procfs. The OpenSSH benchmark starts its own loopback server and +uses a bounded TCP proxy to add delay in each direction. It times connection, +directory listing and reads at batch sizes one and eight, and compares every +received byte with the fixture. Its timings include the proxy and server. +The directory-only OpenSSH benchmark measures three inventory shapes at each +delay and verifies every name, kind and symlink flag. It uses the same proxy. +The Explorer projection benchmark times conversion of native listing data into +rows, then derives paths and display names for 32 visible entries. +The PTY benchmark measures from input submission to acknowledgement after a +raw Unix terminal consumes 1 MiB and verifies the byte count and contents. +The release VT benchmark times column reflow over 10,000 input lines and +checks the logical text and line identities after each width sweep. +The selection benchmark measures availability, the bounded Find query and +clipboard extraction separately for three history sizes. It verifies the +query prefix and the copied text. It also measures copying 50,000 short rows +at 120, 300 and 500 columns and checks the entire clipboard payload. +The paste encoding benchmark reports p50 and p95 for UTF-8 payloads from 1 KiB +to 3.3 MB, with and without brackets, for multiline and ESC-heavy text. A +separate test verifies the large bracketed payload and its transport buffer size. +The Wayland clipboard regression fills an unread socket, then verifies that +the platform event loop delivers independent input before the receiver reads. +It also checks all bytes received after reading resumes. +The OSC observer benchmark measures plain text and sparse and dense ANSI +color updates with a known working directory. The terminal batching benchmark +measures delivery of prepared 8 KiB packets, excluding producer allocation. +Both report p50 and p95 across groups of 1,000 packets. +The line metadata benchmark feeds 6,000 lines at each of three terminal widths +and checks the terminal contents and logical line number after each run. +The VT search benchmark scans 10,000 retained matches with literal and regex +queries, both in isolation and with cursor-position requests injected between +steps. It verifies every completed count and runs regex work inline to isolate +the scan from executor scheduling. +The completed-history search fixture accumulates scan time over 60 one-row +appends to 9,000 matching lines. It alternates full scans and retained-prefix +refreshes for literal and regex queries. Each refresh checks the exact count +and the selected historical position against the current grid. The timer +excludes PTY intake, GUI work and executor scheduling. +The case-insensitive search fixture verifies match counts and positions on +ASCII and mixed-Unicode scrollback and reports the median and p95 scan time. +The theme mutation fixture serves a packaged theme over loopback HTTP, installs +and removes it in a private library, and checks the pack manifest, removed +variants and catalog size. It measures seven install/remove pairs at each +catalog size and reports the median wall time. +The settings snapshot benchmark times 500 copies of a loaded document at +each of three sizes, excluding TOML parsing and file writes. +The settings publication benchmark reports twelve durable saves at each size +for both unknown values and comment-heavy files. It verifies the original +unowned text and reloads the final edited section. Set `TMPDIR` to a directory +on the filesystem you want to measure. +The choice picker benchmark types a query one character at a time through the +GUI test window, renders each result, and confirms a value from 1,800 choices. +The agent benchmark drives 120 updates into a visible Markdown row and checks +the final transcript bytes. It uses a local test provider and the GUI test +window. +The monitor benchmark measures batches of Linux frames with aggregate CPU and +memory, then with 12, 128 and 512 additional per-core rows. It verifies the +parsed counters through the watch and reports the median time per frame. +The full Linux report benchmark times network counters and duplicate mount +rows at two sizes and checks the resulting counters and retained mount count. +The native Linux collection benchmark compares 256 CPU and memory samples +with and without network counters and verifies the returned metrics. +The native thermal benchmark measures 32 temperature-only reports and counts +decoded readings from the available Linux sensors. +The Monitor details benchmark fills 600 history samples in a GPUI test window +and times 40 detail frames for each of the 12- and 512-core fixtures. +The monitor recovery fixture measures collector launches during three minutes of +virtual time for an outage from startup and for one after successful collection. +The Snippets benchmark filters 1,500 entries with title, body and Unicode +queries and verifies the resulting counts and the unique match. +The Workspaces benchmark uses 256 saved entries in the GUI test window. It +times 30 wheel events and 11 search edits separately, then verifies the unique +directory match. +The workspace tab benchmark reports median and p95 latency for 301 tab +activations and explicit draws in a GPUI test window. It checks the active item +and focus after each activation. Run at 16, 96 and 256 tabs with and without +`NOCTERM_PROFILE_GROUPED_TABS`. The test window has no GPU presentation path. +The Keymap benchmark types a query through the GUI test window with 260 +additional bindings and verifies the resulting editable shortcut rows. +The separate Keymap merge benchmark measures defaults and user overrides at +64, 260 and 1,024 effective bindings and checks the resulting precedence. +The Vault benchmark drives a broad nine-character search through the rendered +Credentials tab with 512 synthetic records, then finds one record by server. +The image codec benchmark times native validation and PNG preview generation +for three RGBA source sizes and verifies original bytes, preview size and alpha. +The connections benchmark uses 4,096 synthetic saved profiles and times grouped +search, retaining a committed publication and updating endpoint authority. +The replication service benchmark times an empty reconciliation and a single +incoming edit with 32, 512 and 4,096 already agreed profiles. Its local replica +and persistence writer are in memory. The live feed benchmark uses a dedicated +Hub account with two devices and 512 synthetic profiles. It checks pagination, +empty reads and an incoming edit over pinned TLS, then removes the profiles. +The first-replication benchmark imports 32, 256 and 512 profiles. It uses an +in-memory mirror and a file-backed control with the revisioned TOML writer. +Set `TMPDIR` to a directory on the filesystem you want to measure. +The detach benchmark starts with 32, 512 and 4,096 agreed profiles. It measures +the in-memory clear and checks that it removes the agreement and sends no writes. +The large-fields benchmark imports 32, 128 and 256 new profiles with 48 KiB +descriptions and verifies the accepted local contents. + +```sh +cargo test --locked -p nocterm-local --lib idle_native_commands_benchmark \ + -- --ignored --nocapture +cargo test --locked -p nocterm-local --lib measure_native_command_exit_with_inherited_pipes \ + -- --ignored --nocapture +cargo test --locked -p nocterm-local --lib measure_large_input_delivery_to_a_native_pty \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-vt --lib measure_column_reflow_with_scrollback \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-vt --test selection_cost \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-vt --test paste_cost \ + -- --ignored --nocapture --test-threads=1 +cargo test --locked -p gpui-pre-linux --lib input_dispatches_before_the_clipboard_reader_resumes +cargo test --release --locked -p nocterm-vt --lib measure_first_scrollback_growth \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-vt --lib measure_shell_observation_during_output \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-vt --lib measure_line_metadata_during_continuous_output \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-vt --lib search_device_queries_profile \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-vt --lib measure_completed_history_refresh \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-vt --lib measure_case_insensitive_scrollback \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-themes-registry --lib measure_install_and_remove_with_large_catalog \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-ui --lib measure_appearance_scroll_with_large_theme_catalog \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-ui --lib measure_appearance_picker_settings_publications \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-plugin-net --lib measure_plugin_http_body_reads \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-plugin-abi --lib measure_encoding_http_response_limits \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-terminal --lib measure_batching_complete_terminal_output_packets \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-settings --lib measure_settings_snapshot_clones \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-settings --lib measure_settings_publication_with_unowned_tables \ + -- --ignored --nocapture +cargo test --locked -p nocterm-ui --lib measure_choice_picker_filtering \ + -- --ignored --nocapture +cargo test --locked -p nocterm-agent --lib measure_visible_markdown_stream \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-monitor --lib host_frame_decoding_benchmark \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-monitor --lib full_linux_report_benchmark \ + -- --ignored --nocapture +cargo test --locked -p nocterm-monitor --lib measure_linux_monitor_collecting_frames \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-monitor --lib measure_linux_monitor_collecting_temperatures \ + -- --ignored --nocapture +cargo test --locked -p nocterm-monitor-ui --lib measure_dense_monitor_details \ + -- --ignored --nocapture +cargo test --locked -p nocterm-monitor-service --lib measure_monitor_retry_attempts \ + -- --ignored --nocapture +cargo test --locked -p nocterm-containers-ui --lib measure_scrolling_a_large_container_list \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-containers --test listing_performance \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-snippets --lib search_large_library_benchmark \ + -- --ignored --nocapture +cargo test --locked -p nocterm-projects --lib measure_workspace_catalog_scroll_and_search \ + -- --ignored --nocapture +NOCTERM_PROFILE_TAB_COUNT=96 NOCTERM_PROFILE_GROUPED_TABS=1 \ + cargo test --release --locked -p nocterm-workspace --lib measure_activation_and_draw_in_large_tab_bars \ + -- --ignored --nocapture --test-threads=1 +NOCTERM_PROFILE_TAB_COUNT=96 \ + cargo test --release --locked -p nocterm-workspace --lib measure_closing_tab_batches_and_releasing_focus \ + -- --ignored --nocapture --test-threads=1 +NOCTERM_PROFILE_TAB_COUNT=96 \ + cargo test --release --locked -p nocterm-workspace --lib measure_closing_a_large_tab_group \ + -- --ignored --nocapture --test-threads=1 +NOCTERM_PROFILE_TAB_COUNT=96 \ + cargo test --release --locked -p nocterm-workspace --lib measure_close_others_in_two_dense_panes \ + -- --ignored --nocapture --test-threads=1 +NOCTERM_PROFILE_CATALOG_COUNT=4096 NOCTERM_PROFILE_SESSION_COUNT=16 \ + cargo test --release --locked -p nocterm-connections --lib measure_saved_session_reprojection \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-projects --lib measure_filtering_and_scrolling_a_large_container_inventory \ + -- --ignored --nocapture --test-threads=1 +cargo test --locked -p nocterm-keymap-ui --lib measure_expanded_keymap_filtering \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-keymap --lib measure_large_keymap_merge \ + -- --ignored --nocapture +cargo test --locked -p nocterm-vault-ui --lib measure_search_in_large_credentials_tab \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-hub-io --lib measure_hub_vault_credential_reads \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-hub-io --lib measure_hub_latency_during_parallel_vault_reads \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-vault-store --test worker_idle \ + -- --ignored --nocapture --test-threads=1 +cargo test --release --locked -p nocterm-image-codec --lib measure_native_image_validation_and_preview \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-connections-model --lib measure_large_connection_catalog_operations \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-connections-model --lib measure_cloning_a_catalog_with_large_profile_fields \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-connections-store --lib measure_steady_profile_replication_rounds \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-connections-store --lib measure_first_profile_replication \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-connections-store --lib measure_profile_replication_detach \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-connections-store --lib measure_replication_with_large_profile_fields \ + -- --ignored --nocapture +NOCTERM_REQUIRE_HUB=1 cargo test --release --locked -p nocterm-hub-io --test hub \ + measure_live_profile_feed -- --ignored --nocapture +NOCTERM_REQUIRE_SSHD=1 cargo test --locked -p nocterm-ssh --test sshd \ + sftp_read_and_listing_at_controlled_latency -- --ignored --nocapture +NOCTERM_REQUIRE_SSHD=1 cargo test --release --locked -p nocterm-ssh --test sshd \ + sftp_directory_pages_and_links_at_controlled_latency -- --ignored --nocapture +NOCTERM_REQUIRE_SSHD=1 cargo test --release --locked -p nocterm-ssh --test sshd \ + terminal_echo_during_batched_file_transfers -- --ignored --nocapture +NOCTERM_REQUIRE_SSHD=1 cargo test --release --locked -p nocterm-ssh --test sshd \ + parallel_ssh_logins_with_a_large_known_hosts_file -- --ignored --nocapture +cargo test --release --locked -p nocterm-files --lib measure_dense_local_listing_projection \ + -- --ignored --nocapture +cargo test --release --locked -p nocterm-plugin-view --lib \ + measure_changed_and_equal_plugin_view_handoffs -- --ignored --nocapture +cargo test --release --locked -p nocterm-plugin-api --lib \ + measure_guest_text_validation -- --ignored --nocapture +cargo test --release --locked -p nocterm-plugin-wasm --lib \ + measure_decoding_guest_render_replies -- --ignored --nocapture +cargo test --release --locked -p nocterm-plugin-abi --lib \ + measure_encoding_with_host_owned_or_borrowed_storage -- --ignored --nocapture +cargo test --locked -p nocterm --bin nocterm \ + measure_guest_refreshes_per_foreground_turn -- --ignored --nocapture +``` + +The dock close fixture measures batches of four grouped tabs and reports median +and p95 close latency. After each batch it draws the shell and checks that every +closed tab's weak focus handle has expired. Use 16, 96 or 256 tabs to compare +sizes. This test window measures CPU-side close operations. +The Close Group fixture times one command against a single group at each +size. Nine fresh windows verify the final active item and focus, and verify +that the closed focus handles expire. Setup runs outside the command timer. + +The host storage fixture compares a per-call storage copy with borrowing the +installed map, followed by ABI encoding in both cases. It checks identical +encoded bytes and reports medians and p95 for 0, 128 and 512 stored entries. + +The Hub vault fixture seeds 32 and 1,024 encrypted credentials through the real +codec, warms the cache, and reports separate list and get latencies through the +vault port with its test server offline. It verifies metadata and escaped key text. +The parallel fixture uses 4,096 encrypted records and a two-worker runtime. It +reports list, single-record read, and worker dispatch latency with up to four +overlapping lists and verifies every result. Its online control uses the same +in-memory server. + +The widget refresh fixture counts how many of 16 simultaneously due guest calls +run per foreground turn and verifies delivery of every refresh. It uses a +scripted runtime and a virtual clock. Measure native input and GPU costs separately. + +The plugin view fixture reports median and p95 handoff latency for changed and equal +trees of 8, 64 and 256 nodes. It starts after host validation and includes the +renderer accepting the tree. WASM execution and frame rendering need a native run. + +The guest text fixture measures the consuming validation of printable ASCII, +mixed Unicode, control-heavy text and multiline code. It checks the accepted +nodes against the full sanitization and truncation result outside the timer. + +The SSH mixed workload drives terminal round trips during concurrent uploads +and downloads on a single connection, with direct loopback and added network +latency. It verifies each transferred byte and includes only echo requests +sent while both transfer groups are outstanding in the loaded report. + +The WASM guest reply fixture reports warm render call latency for small and +dense synthetic replies, including memory access, decoding and reply ownership. + +The container filesystem fixture measures NUL-delimited directory listing +through the public RemoteFs adapter and its actor, with a scripted command +transport. It verifies entry order and metadata outside the operation timer. +Use 32, 4096 or 100000 entries; real engine execution and GPU costs are not +included. + +```sh +NOCTERM_PROFILE_DIRECTORY_COUNT=4096 cargo test --release --locked -p nocterm-project-container-fs --lib \ + measure_container_directory_listing -- --ignored --nocapture --test-threads=1 +``` + +The container download fixture transfers seven 8 MiB payloads through the +public RemoteFs adapter, including its producer and actor. It checks the exact +bytes, read bounds and EOF. Use 16384/32768 for typical local output/reads or +262144/777 for partial-read stress. The scripted transport excludes real engine +and network cost. + +```sh +NOCTERM_PROFILE_OUTPUT_SIZE=16384 NOCTERM_PROFILE_READ_SIZE=32768 \ + cargo test --release --locked -p nocterm-project-container-fs --lib \ + measure_container_download -- --ignored --nocapture --test-threads=1 +``` + +The installed plugin package fixture measures 51 warm private-file loads of +an inert code package with a manifest and padding. Each load verifies that +the returned bytes and computed hash match the installed package. Use 1024, +262144 or 2097152 bytes. The fixture does not execute a guest. + +```sh +NOCTERM_PROFILE_PACKAGE_BYTES=2097152 cargo test --release --locked -p nocterm-plugin-packages --lib \ + measure_installed_package_load -- --ignored --nocapture --test-threads=1 +``` + +The agent directory fixture measures batches of 64 profile and 64 direct +agent lookups through the current settings service. Configure 0, 32 or 512 +local overrides and optionally 128 synthetic hub launches; no agent launches. +It checks the returned built-in profile and source. GPU rendering is excluded. + +```sh +NOCTERM_PROFILE_AGENT_COUNT=512 NOCTERM_PROFILE_HUB_AGENT_COUNT=0 \ + cargo test --release --locked -p nocterm-agent-directory --lib \ + measure_agent_directory_lookup -- --ignored --nocapture --test-threads=1 +``` + +The composed Settings fixture measures construction and AI-page selection in +seven fresh GPUI test windows with 0, 32 or 512 configured agents. It verifies +that the AI page and agent headers are reachable without opening details. This +isolates CPU-side layout and state work; it does not measure GPU execution. + +```sh +NOCTERM_PROFILE_AGENT_COUNT=512 cargo test --release --locked -p nocterm --bin nocterm \ + measure_ai_settings_page -- --ignored --nocapture --test-threads=1 +``` + +The dense default-agent picker fixture opens the real Settings selector and +searches for the last of 512 custom agents seven times. It verifies the selected +ID after each search. Its opening and search timings include the composed page +and dialog rendering, not physical presentation or GPU activity. + +```sh +cargo test --release --locked -p nocterm --bin nocterm \ + measure_default_agent_picker -- --ignored --nocapture --test-threads=1 +``` + +The dense agent settings scrolling fixture uses 64 wheel events in a 1100×1100 +GPUI test window with 512 custom agents. It verifies that the first row leaves +the viewport and that the last row and add form remain reachable. It measures +CPU-side interaction and layout, not hardware presentation. + +```sh +cargo test --release --locked -p nocterm --bin nocterm \ + measure_dense_agent_scrolling -- --ignored --nocapture --test-threads=1 +``` + +The registered-settings fixture builds a typed collection of 0, 32 or 512 +synthetic agent settings, measuring seven batches of 128 document clones and +128 clone/edit/compare operations on an unrelated section. The service fixture +uses actual in-memory checked settings receipts with a large local-shell +environment and verifies all revisions and the unchanged environment. These +isolate CPU and memory work; neither fixture measures filesystem writes. + +```sh +NOCTERM_PROFILE_TYPED_ROWS=512 cargo test --release --locked -p nocterm-settings --lib \ + measure_registered_settings_snapshots -- --ignored --nocapture --test-threads=1 +NOCTERM_PROFILE_TYPED_ROWS=512 cargo test --release --locked -p nocterm-store --lib \ + measure_unrelated_settings_publication -- --ignored --nocapture --test-threads=1 +``` diff --git a/scripts/perf/analyze.py b/scripts/perf/analyze.py new file mode 100644 index 00000000..a0e2b309 --- /dev/null +++ b/scripts/perf/analyze.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Summarize marked Wayland runs with optional userspace perf samples.""" + +import argparse +from collections import Counter +from dataclasses import dataclass +from math import ceil +from pathlib import Path +import re +from statistics import median + + +SAMPLE = re.compile( + r"^\s*\S+\s+(\d+)/(\d+)\s+(\d+\.\d+): cpu-clock:u:" + r"\s+\S+\s+(.+) \([^()]*\)$" +) +GPU_SAMPLE = re.compile( + r"\bnocterm_gpu_timing:\s+mode=(\w+) scene_ns=(\d+) " + r"present_copy=(true|false) copy_ns=(\d+)\b" +) +ANSI_STYLE = re.compile(r"\x1b\[[0-9;]*m") + + +@dataclass(frozen=True) +class Event: + time: float + kind: str + key: int + value: int + + +def read_events(lines): + for line in lines: + time, kind, key, value, *_ = line.split() + yield Event(float(time), kind, int(key), int(value)) + + +def mark_windows(events, warmup, cooldown): + starts = {} + for event in events: + if event.kind != "mark": + continue + if event.value == 1: + if event.key in starts: + raise ValueError(f"overlapping starts for workload {event.key}") + starts[event.key] = event.time + elif event.value == 0 and event.key in starts: + start = starts.pop(event.key) + warmup + end = event.time - cooldown + if start >= end: + raise ValueError(f"workload {event.key} is shorter than the excluded time") + yield event.key, start, end + if starts: + raise ValueError(f"unclosed workload markers: {sorted(starts)}") + + +def foreground_samples(lines, pid): + for line in lines: + match = SAMPLE.match(line) + if match: + process, thread, time, symbol = match.groups() + if int(process) == pid and process == thread: + yield float(time), symbol + + +def gpu_intervals(lines): + scenes = {} + copies = {} + for line in lines: + if match := GPU_SAMPLE.search(ANSI_STYLE.sub("", line)): + mode, scene, did_copy, copy = match.groups() + scenes.setdefault(mode, []).append(int(scene) / 1_000_000) + if did_copy == "true": + copies.setdefault(mode, []).append(int(copy) / 1_000_000) + return scenes, copies + + +def p95(values): + return sorted(values)[ceil(0.95 * len(values)) - 1] if values else None + + +def callback_delays(events, pid, surface): + pending = None + for event in events: + if event.key != surface: + continue + if event.kind == "callback": + pending = event.time + elif event.kind == "buffer" and event.value == pid and pending is not None: + yield (event.time - pending) * 1000 + pending = None + + +def summarize(events, samples, pid, warmup, cooldown, surface=None): + windows = list(mark_windows(events, warmup, cooldown)) + if not windows: + raise ValueError("no completed workloads") + surfaces = Counter(event.key for event in events if event.kind == "buffer" and event.value == pid) + if not surfaces: + raise ValueError(f"no buffer commits for PID {pid}") + if surface is None: + # The main surface normally presents more often than decoration or popup surfaces. + surface, _ = surfaces.most_common(1)[0] + elif surface not in surfaces: + raise ValueError(f"surface {surface} has no buffer commits for PID {pid}") + for key, start, end in windows: + section = [event for event in events if start <= event.time <= end] + commits = [ + event.time for event in section + if event.kind == "buffer" and event.key == surface and event.value == pid + ] + gaps = [(b - a) * 1000 for a, b in zip(commits, commits[1:])] + input_count = sum(event.kind in {"move", "scroll", "key", "button"} for event in section) + counts = Counter(symbol for time, symbol in samples if start <= time <= end) + yield { + "workload": key, + "surface": surface, + "input_per_second": input_count / (end - start), + "commits_per_second": len(commits) / (end - start), + "p50_gap_ms": median(gaps) if gaps else None, + "p95_gap_ms": p95(gaps), + "p95_callback_ms": p95(list(callback_delays(section, pid, surface))), + "foreground_samples": counts, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("trace", type=Path, help="monotonic Weston marker and buffer log") + parser.add_argument("--pid", required=True, type=int, help="isolated Nocterm PID from the run") + parser.add_argument("--surface", type=int, help="select a surface with this object ID") + parser.add_argument("--samples", type=Path, help="userspace cpu-clock perf script output") + parser.add_argument("--gpu-log", type=Path, help="summarize separate GPU timing log") + parser.add_argument("--warmup", type=float, default=0.18, help="seconds skipped after each mark") + parser.add_argument("--cooldown", type=float, default=0.08, help="seconds skipped before each end") + args = parser.parse_args() + if args.warmup < 0 or args.cooldown < 0: + parser.error("excluded times must be nonnegative") + try: + with args.trace.open() as trace: + events = list(read_events(trace)) + samples = [] + if args.samples: + with args.samples.open() as profile: + samples = list(foreground_samples(profile, args.pid)) + for result in summarize(events, samples, args.pid, args.warmup, args.cooldown, args.surface): + counts = result["foreground_samples"] + print( + f"{result['workload']} surface={result['surface']} " + f"input={result['input_per_second']:.1f}/s " + f"commits={result['commits_per_second']:.1f}/s " + f"p50 gap={milliseconds(result['p50_gap_ms'])} " + f"p95 gap={milliseconds(result['p95_gap_ms'])} " + f"p95 callback-to-commit={milliseconds(result['p95_callback_ms'])} " + f"foreground samples={counts.total()}" + ) + for symbol, count in counts.most_common(10): + print(f" {count:4d} {symbol}") + if args.gpu_log: + with args.gpu_log.open() as gpu_log: + scenes, copies = gpu_intervals(gpu_log) + if not scenes: + raise ValueError("no GPU timing samples") + for stage, groups in (("scene", scenes), ("present copy", copies)): + for mode, times in sorted(groups.items()): + print( + f"GPU {stage} {mode} samples={len(times)} " + f"p50={milliseconds(median(times))} p95={milliseconds(p95(times))}" + ) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + + +def milliseconds(value): + return f"{value:.2f} ms" if value is not None else "unavailable" + + +if __name__ == "__main__": + main() diff --git a/scripts/perf/test_analyze.py b/scripts/perf/test_analyze.py new file mode 100644 index 00000000..f5285001 --- /dev/null +++ b/scripts/perf/test_analyze.py @@ -0,0 +1,71 @@ +import unittest + +from analyze import foreground_samples, gpu_intervals, read_events, summarize + + +class TraceAnalysisTests(unittest.TestCase): + def test_only_marked_frames_on_the_requested_process_count(self): + events = list(read_events("""\ +0.90 buffer 15 521 +1.00 mark 9 1 +1.05 buffer 15 521 +1.100 scroll 99 0 +1.200 callback 15 20 +1.203 buffer 15 521 +1.205 buffer 15 999 +1.206 buffer 11 521 +1.209 callback 15 21 +1.212 buffer 15 521 +1.230 buffer 15 521 +1.95 buffer 15 521 +2.00 mark 9 0 +""".splitlines())) + samples = list(foreground_samples("""\ + baseline 521/521 1.201000: cpu-clock:u: abc first (/tmp/bin) + baseline 521/888 1.218000: cpu-clock:u: abc worker (/tmp/bin) + baseline 999/999 1.219000: cpu-clock:u: abc other (/tmp/bin) + baseline 521/521 1.250000: cpu-clock:u: def first (/tmp/bin) + baseline 521/521 2.100000: cpu-clock:u: abc unmarked (/tmp/bin) +""".splitlines(), 521)) + result, = summarize(events, samples, 521, 0.09, 0.09) + self.assertEqual(result["surface"], 15) + self.assertAlmostEqual(result["commits_per_second"], 3 / 0.82) + self.assertAlmostEqual(result["input_per_second"], 1 / 0.82) + self.assertAlmostEqual(result["p50_gap_ms"], 13.5) + self.assertAlmostEqual(result["p95_gap_ms"], 18) + self.assertAlmostEqual(result["p95_callback_ms"], 3) + self.assertEqual(result["foreground_samples"], {"first": 2}) + auxiliary, = summarize(events, samples, 521, 0, 0, surface=11) + self.assertIsNone(auxiliary["p95_gap_ms"]) + self.assertIsNone(auxiliary["p95_callback_ms"]) + + def test_unclosed_workload_cannot_produce_a_summary(self): + events = list(read_events(["0.90 buffer 15 521", "1.00 mark 9 1"])) + with self.assertRaisesRegex(ValueError, "unclosed workload"): + list(summarize(events, [], 521, 0, 0)) + + def test_gpu_scene_and_real_copy_intervals_are_aggregated_by_mode(self): + samples = [ + "INFO nocterm_gpu_timing: mode=full scene_ns=1650000 present_copy=false " + "copy_ns=18010 readback_age_us=6400", + "INFO nocterm_gpu_timing: mode=partial scene_ns=380000 present_copy=true " + "copy_ns=222000 readback_age_us=6800", + "INFO nocterm_gpu_timing: mode=partial scene_ns=720000 present_copy=true " + "copy_ns=320000 readback_age_us=7700", + "WARN wgpu: Could not read back GPU timestamps", + ] + scenes, copies = gpu_intervals(samples) + self.assertEqual(scenes, {"full": [1.65], "partial": [0.38, 0.72]}) + self.assertEqual(copies, {"partial": [0.222, 0.32]}) + + def test_gpu_intervals_accept_default_colorized_application_logs(self): + log = ( + "\x1b[2m2026-11-27T11:49:00Z\x1b[0m \x1b[32m INFO\x1b[0m " + "\x1b[2mnocterm_gpu_timing\x1b[0m\x1b[2m:\x1b[0m " + "mode=full scene_ns=1878028 present_copy=false copy_ns=7494 readback_age_us=6915" + ) + self.assertEqual(gpu_intervals([log]), ({"full": [1.878028]}, {})) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/bootstrap.rs b/src/bootstrap.rs index 439a5ffe..033c2271 100644 --- a/src/bootstrap.rs +++ b/src/bootstrap.rs @@ -372,7 +372,7 @@ pub(crate) fn bootstrap(services: Services, cx: &mut App) -> Result = Arc::new(nocterm_local::SystemClock); + let clock: Arc = Arc::new(nocterm_local::SystemClock::default()); let plugins = Plugins::install(&paths, &shutdown, clock.clone(), mode, ui.settings(), cx)?; let monitor = nocterm_monitor_ui::install(local_host.clone(), &ui, cx); let inputs = GuestInputs::new(&monitor, &ui, keymap.clone(), &files, &layout) diff --git a/src/gui_tests/settings_pages.rs b/src/gui_tests/settings_pages.rs index 5908fb1b..2398db04 100644 --- a/src/gui_tests/settings_pages.rs +++ b/src/gui_tests/settings_pages.rs @@ -506,6 +506,7 @@ fn sandbox_controls_use_the_injected_probe_on_every_platform(cx: &mut TestAppCon } } +mod agent_performance; mod appearance; mod dependencies; mod layout_editor; diff --git a/src/gui_tests/settings_pages/agent_performance.rs b/src/gui_tests/settings_pages/agent_performance.rs new file mode 100644 index 00000000..83fdd588 --- /dev/null +++ b/src/gui_tests/settings_pages/agent_performance.rs @@ -0,0 +1,580 @@ +//! Composed AI settings page performance and retained field behavior. +use super::*; +use nocterm_ai::AgentServerSettings; +use std::{io::Write as _, time::Instant}; + +fn configured_agents(count: usize) -> SettingsDocument { + let mut document = SettingsDocument::default(); + document.register::(); + let mut ai = AiSettings::default(); + for index in 0..count { + ai.agents.insert( + format!("custom-{index:04}"), + AgentServerSettings { + name: Some(format!("Custom agent {index}")), + command: Some("/opt/example/agent".into()), + args: Some(vec!["acp".into()]), + ..Default::default() + }, + ); + } + document.set(ai); + document +} + +fn open_fixture( + fixture: &SettingsFixture, + cx: &mut TestAppContext, +) -> (gpui_kit::AnyWindowHandle, Entity) { + cx.update(|cx| { + gpui_kit::open_window(test_window_options(), cx, |window, cx| { + cx.new(|cx| { + SettingsView::with_pages( + fixture.pages.clone(), + fixture.settings.clone(), + window, + cx, + ) + }) + }) + .unwrap() + }) +} + +#[gpui_kit::test] +#[ignore = "release profile of configured AI settings page construction and draw"] +fn measure_ai_settings_page(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_AGENT_COUNT") + .map_or(Ok(32), |count| count.parse::()) + .unwrap(); + assert!(count <= 512); + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(count)), cx)); + let mut creation = Vec::new(); + let mut selection = Vec::new(); + for _ in 0..7 { + let start = Instant::now(); + let (handle, view) = open_fixture(&fixture, cx); + creation.push(start.elapsed()); + cx.run_until_parked(); + let start = Instant::now(); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx); + assert_eq!(view.read(cx).selected_page_id(), "ai"); + }) + .unwrap(); + selection.push(start.elapsed()); + cx.update_window(handle, |_, window, _| { + assert!(window.try_find("ai-agent-claude").is_some()); + if count > 0 { + assert!(window.try_find("ai-agent-custom-0000").is_some()); + } + assert!( + window + .try_find("settings-field-agent.claude.command") + .is_none() + ); + }) + .unwrap(); + cx.update_window(handle, |_, window, _| window.remove_window()) + .unwrap(); + drop(view); + cx.run_until_parked(); + } + creation.sort_unstable(); + selection.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "agents={count} creation_p50={:?} creation_max={:?} selection_p50={:?} selection_max={:?}", + creation[3], + creation[6], + selection[3], + selection[6] + ) + .unwrap(); +} + +fn args_row_height(window: &Window) -> gpui_kit::Pixels { + window + .find("settings-field-agent.custom-0000.args") + .bounds() + .size + .height +} + +#[gpui_kit::test] +fn agent_details_follow_current_settings_and_keep_an_invalid_draft_when_collapsed( + cx: &mut TestAppContext, +) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(1)), cx)); + let (handle, view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx); + assert!( + window + .try_find("settings-field-agent.custom-0000.command") + .is_none() + ); + fixture + .settings + .update::(cx, |settings| { + settings.agents.get_mut("custom-0000").unwrap().command = + Some("/opt/new-agent".into()); + }) + .detach(); + }) + .unwrap(); + cx.run_until_parked(); + let clean_height = cx + .update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.click("ai-agent-custom-0000", cx); + window.render_frame(cx); + assert_eq!( + window.find("agent.custom-0000.command").value(), + Some("/opt/new-agent") + ); + args_row_height(window) + }) + .unwrap(); + type_and_leave(cx, handle, &view, "agent.custom-0000.args", "not JSON"); + let invalid_height = cx + .update_window(handle, |_, window, cx| { + window.render_frame(cx); + let height = args_row_height(window); + assert!( + height > clean_height, + "the stacked field shows its diagnostic" + ); + window.click("ai-agent-custom-0000", cx); + window.render_frame(cx); + assert!( + window + .try_find("settings-field-agent.custom-0000.args") + .is_none() + ); + height + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.click("ai-agent-custom-0000", cx); + window.render_frame(cx); + assert_eq!( + window.find("agent.custom-0000.args").value(), + Some("not JSON") + ); + assert_eq!(args_row_height(window), invalid_height); + assert_eq!( + fixture.settings.setting::(cx).agents["custom-0000"].args, + Some(vec!["acp".into()]) + ); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn removing_an_agent_retires_its_opened_fields_before_the_id_returns(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(1)), cx)); + let (handle, view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx); + window.click("ai-agent-custom-0000", cx); + window.render_frame(cx); + }) + .unwrap(); + type_and_leave(cx, handle, &view, "agent.custom-0000.args", "not JSON"); + cx.update_window(handle, |_, window, cx| { + window.click("ai-agent-custom-0000", cx); + fixture + .settings + .update::(cx, |settings| { + settings.agents.remove("custom-0000"); + }) + .detach(); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("ai-agent-custom-0000").is_none()); + fixture + .settings + .update::(cx, |settings| { + settings.agents.insert( + "custom-0000".into(), + AgentServerSettings { + command: Some("/opt/another-agent".into()), + ..Default::default() + }, + ); + }) + .detach(); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent.custom-0000.args").is_none()); + window.click("ai-agent-custom-0000", cx); + window.render_frame(cx); + assert_eq!(window.find("agent.custom-0000.args").value(), Some("")); + assert_eq!( + window.find("agent.custom-0000.command").value(), + Some("/opt/another-agent") + ); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn many_default_agent_choices_are_searchable_and_can_return_to_ask(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(32)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx); + window.click("ai-default-agent-choose", cx); + window.render_frame(cx); + }) + .unwrap(); + cx.simulate_input(handle, "Custom agent 31"); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + assert_eq!( + fixture + .settings + .setting::(cx) + .default_agent + .as_deref(), + Some("custom-0031") + ); + window.render_frame(cx); + window.click("ai-default-agent-choose", cx); + window.render_frame(cx); + }) + .unwrap(); + cx.simulate_input(handle, "Ask"); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert_eq!( + fixture.settings.setting::(cx).default_agent, + None + ) + }); +} + +#[gpui_kit::test] +fn default_agent_picker_rechecks_availability_when_a_choice_disappears(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(8)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx); + window.click("ai-default-agent-choose", cx); + window.render_frame(cx); + }) + .unwrap(); + cx.simulate_input(handle, "Custom agent 7"); + cx.update(|cx| { + fixture + .settings + .update::(cx, |settings| { + settings.agents.remove("custom-0007"); + }) + .detach(); + }); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert_eq!( + fixture.settings.setting::(cx).default_agent, + None + ) + }); +} + +#[gpui_kit::test] +fn the_builtin_default_agent_choices_remain_inline(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(0)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx); + assert!(window.try_find("ai-default-agent-choose").is_none()); + window.click(("ai-default-agent", 1usize), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + assert_eq!( + fixture + .settings + .setting::(cx) + .default_agent + .as_deref(), + Some("claude") + ); + window.render_frame(cx); + window.click(("ai-default-agent", 0usize), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert_eq!( + fixture.settings.setting::(cx).default_agent, + None + ) + }); +} + +#[gpui_kit::test] +#[ignore = "release profile of opening and searching the dense default-agent picker"] +fn measure_default_agent_picker(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(512)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + select_field_page("ai.enabled", window, cx) + }) + .unwrap(); + let mut opened = Vec::new(); + let mut searched = Vec::new(); + for _ in 0..7 { + let start = Instant::now(); + cx.update_window(handle, |_, window, cx| { + window.click("ai-default-agent-choose", cx); + window.render_frame(cx); + }) + .unwrap(); + opened.push(start.elapsed()); + let start = Instant::now(); + cx.simulate_input(handle, "Custom agent 511"); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .unwrap(); + searched.push(start.elapsed()); + cx.update_window(handle, |_, window, cx| window.press("enter", cx)) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + assert_eq!( + fixture + .settings + .setting::(cx) + .default_agent + .as_deref(), + Some("custom-0511") + ); + window.render_frame(cx); + }) + .unwrap(); + } + opened.sort_unstable(); + searched.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "512 agents picker opening_p50={:?} opening_max={:?} search_p50={:?} search_max={:?}", + opened[3], + opened[6], + searched[3], + searched[6] + ) + .unwrap(); +} + +fn scroll_to_agent_control(target: &'static str, delta: f32, window: &mut Window, cx: &mut App) { + for _ in 0..160 { + window.render_frame(cx); + if window + .try_find(target) + .is_some_and(|element| element.visible()) + { + return; + } + window.scroll( + "ai-settings-list", + gpui_kit::ScrollDelta::Pixels(gpui_kit::point(gpui_kit::px(0.), gpui_kit::px(delta))), + cx, + ); + } + panic!("could not scroll to {target}"); +} + +#[gpui_kit::test] +fn the_dense_agent_list_scrolls_to_the_last_agent_and_retains_focused_input( + cx: &mut TestAppContext, +) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(128)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + window.resize(gpui_kit::size(gpui_kit::px(1100.), gpui_kit::px(1100.))); + select_field_page("ai.enabled", window, cx); + assert!(window.try_find("ai-agent-custom-0127").is_none()); + scroll_to_agent_control("ai-agent-custom-0127", -380., window, cx); + assert!(window.try_find("ai-agent-custom-0000").is_none()); + window.click("ai-agent-custom-0127", cx); + scroll_to_agent_control("agent.custom-0127.args", -250., window, cx); + window.click("agent.custom-0127.args", cx); + window.press("ctrl-a", cx); + scroll_to_agent_control("ai-enabled", 380., window, cx); + window.input("not JSON", cx); + scroll_to_agent_control("agent.custom-0127.args", -380., window, cx); + assert_eq!( + window.find("agent.custom-0127.args").value(), + Some("not JSON") + ); + scroll_to_agent_control("ai-agent-custom-0127", 250., window, cx); + window.click("ai-agent-custom-0127", cx); + window.render_frame(cx); + assert!(window.try_find("agent.custom-0127.args").is_none()); + }) + .unwrap(); + cx.run_until_parked(); + cx.update(|cx| { + assert_eq!( + fixture.settings.setting::(cx).agents["custom-0127"].args, + Some(vec!["acp".into()]) + ) + }); +} + +#[gpui_kit::test] +fn adding_and_removing_earlier_agents_does_not_shift_a_visible_tail_row(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(128)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + window.resize(gpui_kit::size(gpui_kit::px(1100.), gpui_kit::px(1100.))); + select_field_page("ai.enabled", window, cx); + scroll_to_agent_control("ai-agent-custom-0127", -380., window, cx); + fixture + .settings + .update::(cx, |settings| { + settings.agents.remove("custom-0000"); + for index in 0..6 { + settings.agents.insert( + format!("aaa-{index}"), + AgentServerSettings { + command: Some("/opt/example/agent".into()), + ..Default::default() + }, + ); + } + }) + .detach(); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.find("ai-agent-custom-0127").visible()); + window.click("ai-agent-custom-0127", cx); + scroll_to_agent_control("agent.custom-0127.command", -250., window, cx); + assert_eq!( + window.find("agent.custom-0127.command").value(), + Some("/opt/example/agent") + ); + }) + .unwrap(); +} + +#[gpui_kit::test] +#[ignore = "release profile of actual wheel events through dense agent settings"] +fn measure_dense_agent_scrolling(cx: &mut TestAppContext) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(512)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + let elapsed = cx + .update_window(handle, |_, window, cx| { + window.resize(gpui_kit::size(gpui_kit::px(1100.), gpui_kit::px(1100.))); + select_field_page("ai.enabled", window, cx); + let start = Instant::now(); + for _ in 0..64 { + window.scroll( + "ai-settings-list", + gpui_kit::ScrollDelta::Pixels(gpui_kit::point( + gpui_kit::px(0.), + gpui_kit::px(-220.), + )), + cx, + ); + window.render_frame(cx); + } + let elapsed = start.elapsed(); + assert!(window.try_find("ai-agent-custom-0000").is_none()); + scroll_to_agent_control("ai-agent-custom-0511", -380., window, cx); + scroll_to_agent_control("ai-add-agent", -380., window, cx); + elapsed + }) + .unwrap(); + writeln!( + std::io::stdout().lock(), + "512 agents wheel_events=64 elapsed={elapsed:?}" + ) + .unwrap(); +} + +#[gpui_kit::test] +fn membership_changes_on_both_sides_preserve_the_current_agent_scroll_anchor( + cx: &mut TestAppContext, +) { + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(128)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + window.resize(gpui_kit::size(gpui_kit::px(1100.), gpui_kit::px(1100.))); + select_field_page("ai.enabled", window, cx); + scroll_to_agent_control("ai-agent-custom-0060", -380., window, cx); + fixture + .settings + .update::(cx, |settings| { + settings.agents.remove("custom-0000"); + settings.agents.remove("custom-0127"); + }) + .detach(); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.find("ai-agent-custom-0060").visible()); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn either_wheel_axis_moves_the_agent_list_by_the_same_distance(cx: &mut TestAppContext) { + use gpui_kit::{ScrollDelta, point}; + let fixture = + cx.update(|cx| init_with_settings(SettingsConfig::in_memory(configured_agents(128)), cx)); + let (handle, _view) = open_fixture(&fixture, cx); + cx.update_window(handle, |_, window, cx| { + window.resize(gpui_kit::size(gpui_kit::px(1100.), gpui_kit::px(1100.))); + select_field_page("ai.enabled", window, cx); + let top = window.find("ai-enabled").bounds().top(); + window.scroll("ai-settings-list", ScrollDelta::Lines(point(0., -3.)), cx); + assert!(window.find("ai-enabled").bounds().top() < top); + window.scroll("ai-settings-list", ScrollDelta::Lines(point(3., 0.)), cx); + assert_eq!(window.find("ai-enabled").bounds().top(), top); + }) + .unwrap(); +} diff --git a/src/gui_tests/shortcuts.rs b/src/gui_tests/shortcuts.rs index e5581d5e..bee79907 100644 --- a/src/gui_tests/shortcuts.rs +++ b/src/gui_tests/shortcuts.rs @@ -1,5 +1,8 @@ //! Shortcuts pressed in a connected terminal reach the workspace. -use gpui_kit::{AppContext as _, Focusable as _, TestAppContext, test::TestWindowExt as _}; +use gpui_kit::{ + AppContext as _, Focusable as _, TestAppContext, component::WindowExt as _, + test::TestWindowExt as _, +}; use super::fixture; @@ -98,6 +101,175 @@ fn command_palette_takes_typing_and_runs_the_command_from_the_terminal(cx: &mut .unwrap(); } +#[gpui_kit::test] +fn command_palette_reopens_with_a_fresh_query_on_the_original_terminal(cx: &mut TestAppContext) { + let (handle, _, terminal, _) = fixture(cx); + cx.update_window(handle, |_, window, cx| { + nocterm_workspace::command_palette::open(window, cx); + window.render_frame(cx); + }) + .unwrap(); + cx.simulate_input(handle, "there is no command with this name"); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("index-path(0,0,0)").is_none()); + window.close_dialog(cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(terminal.read(cx).focus_handle(cx).is_focused(window)); + nocterm_workspace::command_palette::open(window, cx); + window.render_frame(cx); + assert!(window.find("index-path(0,0,0)").visible()); + }) + .unwrap(); + cx.simulate_input(handle, "workspace::find"); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.find("find-previous").visible()); + assert!(terminal.read(cx).focus_handle(cx).is_focused(window)); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn command_palette_reveals_offscreen_results_during_keyboard_navigation(cx: &mut TestAppContext) { + let (handle, _, _, _) = fixture(cx); + cx.update_window(handle, |_, window, cx| { + nocterm_workspace::command_palette::open(window, cx); + window.render_frame(cx); + assert!( + !window + .try_find("index-path(0,20,0)") + .is_some_and(|row| row.visible()) + ); + for _ in 0..20 { + window.press("down", cx); + window.render_frame(cx); + } + assert!(window.find("index-path(0,20,0)").visible()); + }) + .unwrap(); + cx.simulate_input(handle, "workspace::find"); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.press("enter", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.find("find-previous").visible()); + }) + .unwrap(); +} + +#[gpui_kit::test] +fn command_palette_bounds_row_builds_after_a_broad_query(cx: &mut TestAppContext) { + use gpui_kit::{ + ParentElement as _, + component::command::{Command, CommandItem}, + div, px, + }; + use std::{cell::Cell, rc::Rc}; + + const MATCHES: usize = 256; + let (handle, _, _, _) = fixture(cx); + let builds = Rc::new(Cell::new(0)); + cx.update_window(handle, |_, window, cx| { + let items = (0..MATCHES * 2).map(|index| { + let name = if index % 2 == 0 { "Zoom" } else { "Apply" }; + let label = format!("{name} action {index}"); + let builds = builds.clone(); + CommandItem::new().label(label.clone()).child(move |_, _| { + builds.set(builds.get() + 1); + div().child(label.clone()) + }) + }); + let command = Command::new_with_lazy_row_measurement(window, cx) + .items(items) + .max_h(px(420.)) + .install(cx); + let field = command.clone(); + window.open_dialog(cx, move |dialog, _, _| dialog.child(command.clone())); + field.update(cx, |state, cx| state.focus(window, cx)); + window.render_frame(cx); + }) + .unwrap(); + cx.run_until_parked(); + builds.set(0); + cx.simulate_input(handle, "z"); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.find("index-path(0,0,0)").visible()); + assert!(window.try_find("index-path(0,1,0)").is_none()); + }) + .unwrap(); + assert!( + (1..MATCHES / 2).contains(&builds.get()), + "built {} rows for {MATCHES} matches", + builds.get() + ); +} + +#[gpui_kit::test] +#[ignore = "manual command palette render cost measurement"] +fn measure_command_palette_render_cost(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + const FRAMES: usize = 30; + let (handle, _, _, _) = fixture(cx); + for (label, query) in [ + ("closed", None), + ("open", Some("")), + ("filtered", Some("open")), + ] { + if let Some(query) = query { + cx.update_window(handle, |_, window, cx| { + nocterm_workspace::command_palette::open(window, cx); + window.render_frame(cx); + }) + .unwrap(); + cx.simulate_input(handle, query); + } + cx.run_until_parked(); + let mut elapsed = [0; FRAMES]; + for sample in &mut elapsed { + *sample = cx + .update_window(handle, |_, window, cx| { + let start = Instant::now(); + window.render_frame(cx); + start.elapsed().as_micros() + }) + .unwrap(); + cx.run_until_parked(); + } + elapsed.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{label}: p50={} µs, p95={} µs", + elapsed[FRAMES / 2], + elapsed[28] + ) + .unwrap(); + if query.is_some() { + cx.update_window(handle, |_, window, cx| window.close_dialog(cx)) + .unwrap(); + } + } +} + #[gpui_kit::test] fn close_shortcut_from_connected_terminal_closes_tab(cx: &mut TestAppContext) { let (handle, workspace, _, _) = fixture(cx); diff --git a/src/project_setup/tests/environment.rs b/src/project_setup/tests/environment.rs index d94ce53c..bfec526d 100644 --- a/src/project_setup/tests/environment.rs +++ b/src/project_setup/tests/environment.rs @@ -43,6 +43,11 @@ fn host_and_already_scoped_sources_route_exactly_once_and_probe_actual_container .replace("ID=ubuntu", "ID=alpine") .replace("glibc 2.39", "musl libc"), ); + response( + &exec, + "podman inspect", + serde_json::json!([{"Id": "a".repeat(64), "Name": "/alpine-workspace"}]).to_string(), + ); let location = ContainerLocation::new( HostLocator::Local, Engine::Podman, @@ -66,9 +71,15 @@ fn host_and_already_scoped_sources_route_exactly_once_and_probe_actual_container .unwrap(); assert_eq!(snapshot.os.id, "alpine"); assert_eq!(snapshot.os.libc, LibcFamily::Musl); - assert_eq!(snapshot.container.unwrap().id, "a".repeat(64)); + let facts = snapshot.container.unwrap(); + assert_eq!(facts.id, "a".repeat(64)); + assert_eq!( + facts.name.as_deref(), + (!scoped).then_some("alpine-workspace") + ); let requests = exec.requests(); assert_eq!(requests[0].program, if scoped { "sh" } else { "podman" }); + assert_eq!(requests.len(), if scoped { 1 } else { 2 }); assert_eq!( requests .iter() @@ -78,6 +89,72 @@ fn host_and_already_scoped_sources_route_exactly_once_and_probe_actual_container ); } } + +#[test] +fn container_install_checks_the_environment_before_fetching_metadata_for_its_result() { + let id = super::id(); + let location = ContainerLocation::new( + HostLocator::Local, + Engine::Podman, + id.clone(), + RootPath::parse("/workspace").unwrap(), + ContainerOrigin::Attached, + ) + .unwrap(); + let target = location.to_target().unwrap(); + let environment = NativeWorkspaceEnvironment::new(Arc::new( + nocterm_project_runtime::NativeEnvironmentCommands, + )); + let exec = FakeExec::default(); + let exec_prefix = format!("podman exec --interactive {id}"); + response(&exec, &format!("{exec_prefix} sh -c"), probe_fixture()); + response(&exec, &exec_prefix, String::new()); + response( + &exec, + "podman inspect", + serde_json::json!([{"Id": id, "Name": "/workspace", "Config": {"Image": "test:base"}}]) + .to_string(), + ); + let snapshot = block_on(environment.install( + EnvironmentSource::host(target.clone(), Arc::new(exec.clone())).unwrap(), + vec![LanguageSelection::default_for(ProgrammingLanguage::Node)], + CancelFlag::default(), + Arc::new(|_| {}), + )) + .unwrap(); + let facts = snapshot.container.unwrap(); + assert_eq!(facts.id, id); + assert_eq!(facts.name.as_deref(), Some("workspace")); + assert_eq!(facts.image.as_deref(), Some("test:base")); + let requests = exec.requests(); + let (metadata, scoped) = requests.split_last().unwrap(); + assert_eq!(metadata.program, "podman"); + assert_eq!(metadata.args, ["inspect", "--type", "container", &id]); + assert!(scoped.iter().all(|request| request.args[0] == "exec")); + assert_eq!(scoped.first().unwrap().args, scoped.last().unwrap().args); + assert!( + scoped[1..scoped.len() - 1] + .iter() + .any(|request| { request.args.iter().any(|arg| arg == "apt-get") }) + ); + + let exec = FakeExec::default(); + response( + &exec, + &format!("{exec_prefix} sh -c"), + probe_fixture().replace("writable\x00yes", "writable\x00no"), + ); + let error = block_on(environment.install( + EnvironmentSource::host(target, Arc::new(exec.clone())).unwrap(), + vec![LanguageSelection::default_for(ProgrammingLanguage::Node)], + CancelFlag::default(), + Arc::new(|_| {}), + )) + .unwrap_err(); + assert!(matches!(error, EnvironmentError::ReadOnlyHome)); + assert_eq!(exec.requests().len(), 1); + assert_eq!(exec.requests()[0].args[0], "exec"); +} #[test] fn unsupported_versions_read_only_home_and_missing_prerequisites_refuse_before_mutation() { for (fixture, expected) in [ @@ -237,4 +314,7 @@ fn freshly_owned_arch_can_initialize_package_databases_without_upgrading_an_exis .iter() .all(|request| request.program != "pacman") ); + assert!(exec.requests().iter().all(|request| { + request.program != "podman" || request.args.first().is_none_or(|arg| arg != "inspect") + })); } diff --git a/src/settings_pages/tests.rs b/src/settings_pages/tests.rs index 9c4e0480..32719a72 100644 --- a/src/settings_pages/tests.rs +++ b/src/settings_pages/tests.rs @@ -203,6 +203,16 @@ fn catalog_keeps_the_real_keymap_page_alive_without_a_booted_fixture_handle( window.try_find(("keymap-row", 0usize)).is_some(), "the actual retained keymap supplies commands after composition inputs leave scope" ); + let search = window.find("keymap-search").bounds(); + let results = window.find("keymap-results").bounds(); + assert!(results.bottom() <= window.find("settings-view").bounds().bottom()); + window.scroll( + "keymap-results", + gpui_kit::ScrollDelta::Pixels(gpui_kit::point(gpui_kit::px(0.), gpui_kit::px(-420.))), + cx, + ); + assert!(window.try_find(("keymap-row", 0usize)).is_none()); + assert_eq!(window.find("keymap-search").bounds(), search); }) .unwrap(); } diff --git a/src/shell_setup/user_plugin_panel.rs b/src/shell_setup/user_plugin_panel.rs index 55fbf80d..239f8f28 100644 --- a/src/shell_setup/user_plugin_panel.rs +++ b/src/shell_setup/user_plugin_panel.rs @@ -50,6 +50,7 @@ pub(super) fn attach( if matches!( event, nocterm_workspace::WorkspaceEvent::PanelVisibilityChanged + | nocterm_workspace::WorkspaceEvent::PanelSelectionChanged | nocterm_workspace::WorkspaceEvent::ContextChanged ) { let driver = deferred.clone(); diff --git a/src/shell_setup/user_plugin_panel/content.rs b/src/shell_setup/user_plugin_panel/content.rs index dcff4c47..38fe45fc 100644 --- a/src/shell_setup/user_plugin_panel/content.rs +++ b/src/shell_setup/user_plugin_panel/content.rs @@ -11,9 +11,9 @@ use gpui_kit::{ App, AppContext as _, Entity, FocusHandle, IntoElement as _, WeakEntity, component::{ActiveTheme as _, Icon, tooltip::Tooltip}, }; -use nocterm_plugin_api::{Event, Refresh, View}; +use nocterm_plugin_api::{Event, Refresh}; use nocterm_plugin_host::{Call, CallError, Input, PluginHost}; -use nocterm_plugin_model::ContributionId; +use nocterm_plugin_model::{ContributionId, PluginId}; use nocterm_plugin_ports::PluginProviders; use nocterm_plugin_view::{FrameKind, Hooks, Interaction, Origin, PluginView, ViewStyle}; use nocterm_workspace::Workspace; @@ -40,7 +40,6 @@ pub(super) struct Content { visible: bool, /// The visibility the plugin was last told, by a `visibility-changed` event. told: Option, - last: Option, appearance: ViewStyle, panel: Option<(WeakEntity, ContributionId)>, driver: WeakEntity, @@ -84,7 +83,6 @@ impl Content { next: now, visible: false, told: None, - last: None, appearance, panel: None, driver: driver.downgrade(), @@ -144,7 +142,15 @@ impl Content { }); } } - pub(super) fn tick(&mut self, now: Instant, cx: &mut App) -> Option { + pub(super) fn is_of(&self, plugin: &PluginId) -> bool { + &self.call.plugin == plugin + } + + pub(super) fn invalidate(&mut self, now: Instant) { + self.next = now; + } + + pub(super) fn deadline(&mut self, now: Instant, cx: &mut App) -> Option { if let Some((workspace, id)) = &self.panel { self.visible = workspace .read_with(cx, |workspace, _| workspace.panel_is_open(id)) @@ -154,35 +160,30 @@ impl Content { if !self.visible { return None; } - if now >= self.next || self.host.read(cx).revision() != self.revision { - self.refresh(now, cx); - } - Some(self.next) + let next = if self.next > now && self.host.read(cx).revision() != self.revision { + now + } else { + self.next + }; + Some(next) } /// Asks the host for the view and shows it. A plugin that failed shows the fault chip; one /// over the render budget keeps its last view and is asked again soon. - fn refresh(&mut self, now: Instant, cx: &mut App) { - let answer = self - .host - .update(cx, |host, cx| host.render(&self.call, &self.providers, cx)); + pub(super) fn refresh(&mut self, now: Instant, cx: &mut App) -> Instant { + let answer = self.host.update(cx, |host, cx| { + host.render_validated(&self.call, &self.providers, cx) + }); self.revision = self.host.read(cx).revision(); self.restyle(cx); match answer { Ok(view) => { - self.next = now + wait_of(view.refresh); - let changed = self - .last - .as_ref() - .is_none_or(|last| last.nodes != view.nodes); - if changed { - let shown = view.clone(); - self.view.update(cx, |plugin_view, cx| { - if let Err(error) = plugin_view.show(shown) { tracing::warn!(%error, plugin = %self.call.plugin, "a plugin view was refused"); } + self.next = now + wait_of(view.refresh()); + self.view.update(cx, |plugin_view, cx| { + if plugin_view.show_validated(view) { cx.notify(); - }); - } - self.last = Some(view); + } + }); } Err(CallError::Throttled { retry_after_ms }) => { self.next = now + Duration::from_millis(u64::from(retry_after_ms)).max(MIN_WAIT); @@ -199,7 +200,6 @@ impl Content { Err(error) => { tracing::debug!(%error, plugin = %self.call.plugin, "a plugin view is not drawn"); self.next = now + IDLE; - self.last = None; self.view.update(cx, |plugin_view, cx| { if !plugin_view.is_fault() { plugin_view.fault(); @@ -208,6 +208,7 @@ impl Content { }); } } + self.next } } diff --git a/src/shell_setup/user_plugin_panel/driver.rs b/src/shell_setup/user_plugin_panel/driver.rs index d20f187c..35e53bcd 100644 --- a/src/shell_setup/user_plugin_panel/driver.rs +++ b/src/shell_setup/user_plugin_panel/driver.rs @@ -1,18 +1,25 @@ //! One nearest-deadline timer for the visible contributions of one physical window. use super::content::Content; use gpui_kit::{App, AppContext as _, Context, Entity, Subscription, Task, WeakEntity, WindowId}; -use nocterm_plugin_host::PluginHost; -use std::time::Instant; +use nocterm_plugin_host::{GuestChanged, PluginHost}; +use nocterm_plugin_model::PluginId; +use std::time::{Duration, Instant}; + +// An admitted WASM call can occupy several milliseconds. Give input and paint +// a turn between batches of simultaneously due contributions. +const MAX_REFRESHES_PER_PASS: usize = 2; +const REFRESH_YIELD: Duration = Duration::from_millis(1); pub(in crate::shell_setup) struct RefreshDriver { contents: Vec>, timer: Option>, + resume_at: Option, host: Entity, window: WindowId, visible: bool, closed: bool, scheduled: bool, - _subscription: Subscription, + _subscriptions: [Subscription; 2], } impl RefreshDriver { pub(in crate::shell_setup) fn new( @@ -21,17 +28,21 @@ impl RefreshDriver { cx: &mut App, ) -> Entity { cx.new(|cx| { - let subscription = cx.observe(&host, |this: &mut Self, _, cx| this.wake(cx)); + let managed = cx.observe(&host, |this: &mut Self, _, cx| this.wake(cx)); + let guest = cx.subscribe(&host, |this: &mut Self, _, event: &GuestChanged, cx| { + this.invalidate(event.plugin(), cx); + }); cx.on_release(|this: &mut Self, cx| this.close(cx)).detach(); Self { contents: Vec::new(), timer: None, + resume_at: None, host, window, visible: true, closed: false, scheduled: false, - _subscription: subscription, + _subscriptions: [managed, guest], } }) } @@ -39,6 +50,19 @@ impl RefreshDriver { self.contents.push(content); self.defer_wake(cx); } + fn invalidate(&mut self, plugin: &PluginId, cx: &mut Context) { + let now = cx.background_executor().now(); + let mut refresh = false; + for content in self.contents.iter().filter_map(WeakEntity::upgrade) { + if content.read(cx).is_of(plugin) { + content.update(cx, |content, _| content.invalidate(now)); + refresh = true; + } + } + if refresh && self.visible { + self.defer_wake(cx); + } + } pub(super) fn defer_wake(&mut self, cx: &mut Context) { if self.scheduled || self.closed { return; @@ -64,29 +88,57 @@ impl RefreshDriver { } self.closed = true; self.timer.take(); + self.resume_at = None; self.contents.clear(); self.host .update(cx, |host, _| host.release_window(self.window)); } - pub(super) fn wake(&mut self, cx: &mut Context) { - self.timer.take(); + fn wake(&mut self, cx: &mut Context) { if self.closed || !self.visible { + self.timer.take(); + self.resume_at = None; return; } let now = cx.background_executor().now(); + if self.resume_at.is_some_and(|resume| now < resume) { + return; + } + self.timer.take(); + self.resume_at = None; let mut deadline: Option = None; + let mut remaining = MAX_REFRESHES_PER_PASS; + let mut deferred = false; self.contents.retain(|content| { let Some(content) = content.upgrade() else { return false; }; - let next = content.update(cx, |content, cx| content.tick(now, cx)); + let next = content.update(cx, |content, cx| { + let next = content.deadline(now, cx)?; + if next > now { + return Some(next); + } + if remaining == 0 { + deferred = true; + return None; + } + remaining -= 1; + Some(content.refresh(now, cx)) + }); if let Some(next) = next { deadline = Some(deadline.map_or(next, |current| current.min(next))); } true }); - if let Some(deadline) = deadline { - let wait = deadline.saturating_duration_since(cx.background_executor().now()); + let now = cx.background_executor().now(); + let wake_at = if deferred { + let resume = now + REFRESH_YIELD; + self.resume_at = Some(resume); + Some(resume) + } else { + deadline + }; + if let Some(wake_at) = wake_at { + let wait = wake_at.saturating_duration_since(now); self.timer = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(wait).await; let _ = this.update(cx, |this, cx| this.wake(cx)); diff --git a/src/shell_setup/user_plugin_panel/tests.rs b/src/shell_setup/user_plugin_panel/tests.rs index 89af1a72..2e90bb1f 100644 --- a/src/shell_setup/user_plugin_panel/tests.rs +++ b/src/shell_setup/user_plugin_panel/tests.rs @@ -1,4 +1,4 @@ -//! A status bar widget asks its plugin for a view only while the bar draws it. +//! Refresh and event delivery for user contributions as their visibility changes. use std::{cell::Cell, rc::Rc, sync::Arc, time::Duration}; use gpui_kit::test::TestWindowExt as _; @@ -24,6 +24,9 @@ use super::{ }; use crate::shell_setup::{UserPluginMode, UserShell, plugin_catalog}; +mod panel_visibility; +mod refresh_burst; + struct Noon; impl WallClock for Noon { fn now(&self) -> WallTime { diff --git a/src/shell_setup/user_plugin_panel/tests/panel_visibility.rs b/src/shell_setup/user_plugin_panel/tests/panel_visibility.rs new file mode 100644 index 00000000..5e60925b --- /dev/null +++ b/src/shell_setup/user_plugin_panel/tests/panel_visibility.rs @@ -0,0 +1,240 @@ +use std::{rc::Rc, sync::Arc, time::Duration}; + +use gpui_kit::{AppContext as _, TestAppContext, WindowHandle, test::TestWindowExt as _}; +use nocterm_plugin_api::{Event, Kind, Refresh, View}; +use nocterm_plugin_host::{ + HostPorts, PluginHost, + test_support::{ + MemoryData, MemoryPackages, MemoryRecords, Script, ScriptedRuntime, package_with, + }, +}; +use nocterm_plugin_model::{ContributionId, GroupId, PluginSet}; +use nocterm_plugin_ports::PluginProviders; +use nocterm_snippets_ui::plugin::LIBRARY; +use nocterm_store::SettingsConfig; +use nocterm_ui::{LayoutHandle, PluginSetHandle}; +use nocterm_window_layout::{Bar, BarItem, GroupEntry, LayoutPreset, LayoutSettings, PresetId}; +use nocterm_workspace::{Deps, PanelRegistration, Workspace, test_support::TestPanel}; + +use super::super::{Badges, RefreshDriver, WindowSync, attach}; +use crate::shell_setup::plugin_catalog; + +const BOARD: ContributionId = ContributionId::new("user-acme-clock.board"); +const CLOCK_FACE: ContributionId = ContributionId::new("user-acme-clock.face"); +const OTHER_FACE: ContributionId = ContributionId::new("user-acme-other.face"); + +fn settings(widget: Option<&ContributionId>) -> SettingsConfig { + let id = PresetId::new("p1"); + SettingsConfig::in_memory(Default::default()).with(LayoutSettings { + active: Some(id.clone()), + presets: vec![LayoutPreset { + id, + name: "Plugin panel test".into(), + bar: Bar { + left: vec![BarItem::Group { + id: GroupId::new("navigation"), + name: None, + side: None, + primary: true, + members: vec![ + GroupEntry::Panel(LIBRARY.id.clone()), + GroupEntry::Panel(BOARD.clone()), + ], + }], + right: widget + .map(|id| BarItem::Item { id: id.clone() }) + .into_iter() + .collect(), + ..Bar::default() + }, + tray: [CLOCK_FACE, OTHER_FACE] + .into_iter() + .filter(|id| Some(id) != widget) + .collect(), + open: vec![LIBRARY.id.clone()], + ..LayoutPreset::default() + }], + }) +} + +fn workspace( + script: &Script, + widget: Option<&ContributionId>, + cx: &mut TestAppContext, +) -> WindowHandle { + let (host, settings, source) = cx.update(|cx| { + gpui_kit::init(cx); + let settings = settings(widget).install(cx); + nocterm_ui::init(nocterm_ui::DesignTokens::builtin(), settings.clone(), cx); + let host = cx.new(|_| { + PluginHost::new(HostPorts { + records: MemoryRecords::new(), + data: MemoryData::new(), + packages: MemoryPackages::new(), + runtime: ScriptedRuntime::new(script), + net: None, + }) + }); + let set = host.update(cx, |host, cx| { + let id = host + .install(package_with("clock", 1, &[]), &[], cx) + .unwrap(); + host.set_placeable(&id, true, cx).unwrap(); + if widget == Some(&OTHER_FACE) { + let id = host + .install(package_with("other", 2, &[]), &[], cx) + .unwrap(); + host.set_placeable(&id, true, cx).unwrap(); + } + PluginSet::system(Arc::new(plugin_catalog().unwrap())) + .with_users(host.entries(), host.revision()) + .unwrap() + }); + (host, settings, PluginSetHandle::new(set, cx)) + }); + cx.add_window(move |window, cx| { + let deps = Deps::new(LayoutHandle::in_memory(cx)) + .with_settings(settings) + .with_plugin_source(Rc::new(source.clone())); + let mut workspace = Workspace::new(deps, window, cx); + workspace + .register_panel( + PanelRegistration::new(&LIBRARY, |_, _, cx| { + TestPanel::builder("snippets").build(cx) + }), + window, + cx, + ) + .unwrap(); + let id = window.window_handle().window_id(); + let driver = RefreshDriver::new(host.clone(), id, cx); + let sync = WindowSync::new( + host, + driver.clone(), + source, + PluginProviders::new(), + Badges::default(), + false, + id, + ); + attach(sync, driver, &mut workspace, window, cx); + workspace + }) +} + +fn open(window: WindowHandle, id: &ContributionId, cx: &mut TestAppContext) { + window + .update(cx, |workspace, window, cx| { + workspace.open_panel(id, window, cx) + }) + .unwrap(); + cx.update_window(*window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); +} + +fn visibility(script: &Script) -> Vec { + script + .events() + .iter() + .filter_map(|event| match event { + Event::VisibilityChanged { visible } => Some(*visible), + _ => None, + }) + .collect() +} + +#[gpui_kit::test] +fn selecting_a_builtin_sibling_stops_the_guest_before_its_refresh_deadline( + cx: &mut TestAppContext, +) { + let script = Script::new(); + script.render_with(Ok(View { + refresh: Some(Refresh::NextMinute), + ..View::default() + })); + let window = workspace(&script, None, cx); + open(window, &BOARD, cx); + assert_eq!(visibility(&script), [true]); + let calls = script.snapshots().len(); + + open(window, &LIBRARY.id, cx); + assert_eq!(visibility(&script), [true, false]); + assert_eq!(script.snapshots().len(), calls + 1, "only the hide event"); + open(window, &BOARD, cx); + assert_eq!(visibility(&script), [true, false, true]); + assert!( + script.snapshots().len() > calls + 2, + "the panel refreshes on return" + ); + + open(window, &LIBRARY.id, cx); + assert_eq!(visibility(&script), [true, false, true, false]); + let calls = script.snapshots().len(); + cx.executor().advance_clock(Duration::from_secs(65)); + cx.run_until_parked(); + assert_eq!( + script.snapshots().len(), + calls, + "the hidden guest stays idle" + ); +} + +fn widget_calls(script: &Script) -> usize { + script + .snapshots() + .iter() + .filter(|snapshot| snapshot.context.kind == Kind::Widget) + .count() +} + +fn minute_view() -> Script { + let script = Script::new(); + script.render_with(Ok(View { + nodes: vec![nocterm_plugin_api::Node::new( + nocterm_plugin_api::NodeKind::Text("Ready".into()), + )], + refresh: Some(Refresh::NextMinute), + })); + script +} + +#[gpui_kit::test] +fn hiding_a_panel_does_not_render_an_unrelated_widget_before_its_deadline(cx: &mut TestAppContext) { + let script = minute_view(); + let window = workspace(&script, Some(&OTHER_FACE), cx); + open(window, &BOARD, cx); + let visible = widget_calls(&script); + assert!( + visible > 1, + "the widget has received a view and a visibility event" + ); + + open(window, &LIBRARY.id, cx); + assert_eq!(visibility(&script).last(), Some(&false)); + assert_eq!(widget_calls(&script), visible); + + cx.executor().advance_clock(Duration::from_secs(65)); + cx.run_until_parked(); + assert_eq!( + widget_calls(&script), + visible + 1, + "the widget keeps its timer" + ); +} + +#[gpui_kit::test] +fn hiding_a_panel_refreshes_a_widget_of_the_same_guest(cx: &mut TestAppContext) { + let script = minute_view(); + let window = workspace(&script, Some(&CLOCK_FACE), cx); + open(window, &BOARD, cx); + let visible = widget_calls(&script); + assert!( + visible > 1, + "the widget has received a view and a visibility event" + ); + + open(window, &LIBRARY.id, cx); + assert_eq!(visibility(&script).last(), Some(&false)); + assert_eq!(widget_calls(&script), visible + 1); +} diff --git a/src/shell_setup/user_plugin_panel/tests/refresh_burst.rs b/src/shell_setup/user_plugin_panel/tests/refresh_burst.rs new file mode 100644 index 00000000..5555ba0b --- /dev/null +++ b/src/shell_setup/user_plugin_panel/tests/refresh_burst.rs @@ -0,0 +1,182 @@ +use std::{io::Write as _, time::Duration}; + +use gpui_kit::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, TestAppContext, + Window, WindowHandle, div, test::TestWindowExt as _, +}; +use nocterm_plugin_api::{ContributionContext, Kind, LocalId, Refresh, View, Zone}; +use nocterm_plugin_host::{ + Call, HostPorts, PluginHost, + test_support::{ + MemoryData, MemoryPackages, MemoryRecords, Script, ScriptedRuntime, package_with, + }, +}; +use nocterm_plugin_model::PluginId; +use nocterm_plugin_ports::PluginProviders; +use nocterm_plugin_view::FrameKind; +use nocterm_store::SettingsConfig; + +use super::{Content, FrameSpec, RefreshDriver}; + +struct Widgets { + contents: Vec>, + _driver: Entity, +} + +impl Render for Widgets { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + for content in &self.contents { + content.update(cx, |content, cx| content.visible(true, false, cx)); + } + div().children( + self.contents + .iter() + .map(|content| content.read(cx).view().clone()), + ) + } +} + +fn window( + script: &Script, + guests: u8, + cx: &mut TestAppContext, +) -> (WindowHandle, Entity) { + let host = cx.update(|cx| { + gpui_kit::init(cx); + let settings = SettingsConfig::in_memory(Default::default()).install(cx); + nocterm_ui::init(nocterm_ui::DesignTokens::builtin(), settings, cx); + cx.new(|_| { + PluginHost::new(HostPorts { + records: MemoryRecords::new(), + data: MemoryData::new(), + packages: MemoryPackages::new(), + runtime: ScriptedRuntime::new(script), + net: None, + }) + }) + }); + let host_in_window = host.clone(); + let window = cx.add_window(move |window, cx| { + let host = host_in_window; + let window_id = window.window_handle().window_id(); + let driver = RefreshDriver::new(host.clone(), window_id, cx); + let contents = (0..guests) + .map(|index| { + let name = format!("widget{index}"); + let plugin = host.update(cx, |host, cx| { + host.install(package_with(&name, index, &[]), &[], cx) + .unwrap() + }); + Content::new( + host.clone(), + driver.clone(), + Call { + window: window_id, + plugin, + local: LocalId::parse("face").unwrap(), + context: ContributionContext { + kind: Kind::Widget, + zone: Zone::Right, + }, + in_focus: false, + terminal: None, + }, + FrameSpec { + name: &name, + kind: FrameKind::Bar, + dev: false, + }, + PluginProviders::new(), + cx, + ) + }) + .collect(); + Widgets { + contents, + _driver: driver, + } + }); + (window, host) +} + +fn start_refresh_burst( + guests: u8, + cx: &mut TestAppContext, +) -> (WindowHandle, Script, usize) { + let script = Script::new(); + script.render_with(Ok(View { + refresh: Some(Refresh::NextMinute), + ..View::default() + })); + let (window, host) = window(&script, guests, cx); + cx.update_window(*window, |_, window, cx| window.render_frame(cx)) + .unwrap(); + cx.run_until_parked(); + for _ in 0..guests { + advance(cx); + } + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + let before = script.snapshots().len(); + assert!(before >= usize::from(guests) * 2); + + host.update(cx, |host, cx| { + host.set_placeable(&PluginId::new("user-acme-widget0"), true, cx) + .unwrap(); + }); + cx.run_until_parked(); + (window, script, before) +} + +fn advance(cx: &mut TestAppContext) { + cx.executor().advance_clock(Duration::from_millis(10)); + cx.run_until_parked(); +} + +#[gpui_kit::test] +fn a_refresh_burst_leaves_work_for_a_later_turn(cx: &mut TestAppContext) { + let (_window, script, before) = start_refresh_burst(3, cx); + assert_eq!(script.snapshots().len() - before, 2); + + advance(cx); + assert_eq!(script.snapshots().len() - before, 3); +} + +#[gpui_kit::test] +fn closing_the_window_cancels_the_rest_of_the_refresh_burst(cx: &mut TestAppContext) { + let (window, script, before) = start_refresh_burst(3, cx); + assert_eq!(script.snapshots().len() - before, 2); + cx.update_window(*window, |_, window, _| window.remove_window()) + .unwrap(); + advance(cx); + assert_eq!(script.snapshots().len() - before, 2); +} + +#[gpui_kit::test] +#[ignore = "manual work-per-turn profile for 16 simultaneously due widgets"] +fn measure_guest_refreshes_per_foreground_turn(cx: &mut TestAppContext) { + let (_window, script, before) = start_refresh_burst(16, cx); + let mut previous = before; + let mut passes = Vec::new(); + loop { + let total = script.snapshots().len(); + let processed = total - previous; + assert!( + (1..=2).contains(&processed), + "calls in one turn: {processed}" + ); + passes.push(processed); + if total - before >= 16 { + assert_eq!(total - before, 16); + break; + } + previous = total; + cx.executor().advance_clock(Duration::from_millis(1)); + cx.run_until_parked(); + } + writeln!( + std::io::stdout().lock(), + "guest refreshes per turn: {passes:?}" + ) + .unwrap(); +} diff --git a/src/shell_setup/user_plugins/rust_guest.rs b/src/shell_setup/user_plugins/rust_guest.rs index b79d95ac..0f62b8a5 100644 --- a/src/shell_setup/user_plugins/rust_guest.rs +++ b/src/shell_setup/user_plugins/rust_guest.rs @@ -69,15 +69,26 @@ fn a_rust_guest_passes_the_check_and_answers_events_through_the_runtime() { utc_offset_seconds: 0, })), ); + for index in 0..511 { + running + .storage + .insert(format!("sample-{index:04}"), "x".repeat(110)); + } running.storage.insert("start".into(), "1000".into()); - let view = instance.render(&bar, &running).expect("the bar renders"); + let view = instance + .render_borrowed(&bar, (&running).into()) + .expect("the cold bar renders near the storage limit"); assert!( format!("{view:?}").contains("Focus 12m"), "the guest read the clock and its stored start: {view:?}" ); let effects = instance - .on_event(&bar, Event::Activated { key: "open".into() }, &running) + .on_event_borrowed( + &bar, + Event::Activated { key: "open".into() }, + (&running).into(), + ) .expect("the guest answers the event"); assert!( effects diff --git a/src/shell_setup/user_plugins/terminals.rs b/src/shell_setup/user_plugins/terminals.rs index 5c8bbb62..a7b8d02c 100644 --- a/src/shell_setup/user_plugins/terminals.rs +++ b/src/shell_setup/user_plugins/terminals.rs @@ -22,13 +22,9 @@ use std::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, }, - time::Duration, }; -use futures::{ - FutureExt as _, SinkExt as _, StreamExt as _, - channel::{mpsc, oneshot}, -}; +use futures::{FutureExt as _, SinkExt as _, StreamExt as _, channel::mpsc}; use gpui_kit::{ AnyWindowHandle, App, AppContext as _, BackgroundExecutor, Context, Subscription, WeakEntity, Window, @@ -36,12 +32,10 @@ use gpui_kit::{ use nocterm_plugin_api::{ ContributionContext, Event, HostError, Kind, LocalId, Zone, capability::{ - files::{ - FILE_TIMEOUT_MS, FileAnswer, FileFailure, FileReply, MAX_FILE_REQUESTS, ServeFiles, - }, + files::{FileReply, ServeFiles}, terminals::{ Bar, MAX_TERMINALS, Open, OpenTerminal, ShowTerminalBar, Write, WriteTerminal, - terminal_output, + terminal_output_owned, }, }, }; @@ -53,16 +47,13 @@ use nocterm_session::{ }; use nocterm_workspace::{Workspace, WorkspaceEvent}; +mod file_requests; mod fs; mod line; +use file_requests::Waiting; use line::{Fed, LineEditor, Prompt}; -/// A file request of a plugin's terminal: the plugin, the terminal and the request's number. -type FileKey = (PluginId, String, u32); -/// The file requests waiting for the plugin's answer, by key. -type Waiting = Rc>>>; - /// Most writes waiting for a terminal to show them. const OUTPUT_BACKLOG: usize = 64; @@ -150,7 +141,7 @@ impl PluginTerminals { self.following.borrow_mut().take(); self.providers.borrow_mut().take(); self.open.borrow_mut().clear(); - self.waiting.borrow_mut().clear(); + self.waiting.borrow_mut().close(); } fn live(&self, plugin: &PluginId) -> usize { @@ -306,8 +297,8 @@ impl Apply for PluginTerminals { .clone() .ok_or(HostError::Unavailable)?; let (files, asks) = if request.files { - let (asks, asked) = mpsc::channel(MAX_FILE_REQUESTS); - let files: Arc = Arc::new(fs::PluginFs::new(asks)); + let (fs, asked) = fs::PluginFs::channel(); + let files: Arc = Arc::new(fs); (Some(files), Some(asked)) } else { (None, None) @@ -344,6 +335,7 @@ impl Apply for PluginTerminals { call: call.clone(), providers, terminal: request.terminal, + alive: alive.clone(), }; if let Some(asked) = asks { serve_files(tab.clone(), asked, self.waiting.clone(), cx); @@ -455,6 +447,7 @@ struct Tab { call: Call, providers: PluginProviders, terminal: String, + alive: Arc, } /// Hands the lines typed into a tab to its plugin, then that it closed; the file requests of a @@ -468,9 +461,7 @@ fn forward_lines(tab: Tab, mut lines: mpsc::Receiver, waiting: Waiting, }; report(&tab.host, &tab.call, event, &tab.providers, cx); } - waiting - .borrow_mut() - .retain(|(plugin, open, _), _| *plugin != tab.call.plugin || *open != tab.terminal); + waiting.borrow_mut().close_tab(&tab); let closed = Event::TerminalClosed { terminal: tab.terminal.clone(), }; @@ -479,59 +470,40 @@ fn forward_lines(tab: Tab, mut lines: mpsc::Receiver, waiting: Waiting, .detach(); } -/// Hands each file request of a tab to its plugin as a `file-request` event and waits for the -/// answer, at most [`FILE_TIMEOUT_MS`]. A request the plugin is not told of fails at once. +/// Hands each file request of a tab to the plugin and tracks its answer until the deadline. fn serve_files(tab: Tab, mut asked: mpsc::Receiver, waiting: Waiting, cx: &mut App) { cx.spawn(async move |cx| { - let mut next: u32 = 0; while let Some(asked) = asked.next().await { let (op, reply) = asked.into_parts(); - let request = next; - next = next.wrapping_add(1); - let key: FileKey = (tab.call.plugin.clone(), tab.terminal.clone(), request); - waiting.borrow_mut().insert(key.clone(), reply); + let request = waiting + .borrow_mut() + .begin(&tab, reply, cx.background_executor().now()); + let Some(request) = request else { + continue; + }; let event = Event::FileRequest { terminal: tab.terminal.clone(), request, op, }; - if !report(&tab.host, &tab.call, event, &tab.providers, cx) { - fail(&waiting, &key, "the plugin is not running"); - continue; + if report(&tab.host, &tab.call, event, &tab.providers, cx) { + file_requests::schedule(&waiting, cx); + } else { + waiting + .borrow_mut() + .fail(&tab, request, "the plugin is not running"); } - let timeout = cx - .background_executor() - .timer(Duration::from_millis(u64::from(FILE_TIMEOUT_MS))); - let waiting = waiting.clone(); - cx.spawn(async move |_| { - timeout.await; - fail(&waiting, &key, "the plugin did not answer in time"); - }) - .detach(); } }) .detach(); } -/// Fails the request `key` if it still waits. -fn fail(waiting: &Waiting, key: &FileKey, reason: &str) { - if let Some(reply) = waiting.borrow_mut().remove(key) { - let _ = reply.send(FileAnswer::Failed(FileFailure::Other(reason.to_owned()))); - } -} - /// The plugin's answer to a file request of one of its tabs. impl Apply for PluginTerminals { - fn apply(&self, plugin: &PluginId, request: FileReply, _: &mut App) -> Result<(), HostError> { - let key: FileKey = (plugin.clone(), request.terminal, request.request); - let reply = self - .waiting + fn apply(&self, plugin: &PluginId, request: FileReply, cx: &mut App) -> Result<(), HostError> { + self.waiting .borrow_mut() - .remove(&key) - .ok_or(HostError::Unavailable)?; - reply - .send(request.answer) - .map_err(|_| HostError::Unavailable) + .complete(plugin, request, cx.background_executor().now()) } } @@ -543,7 +515,7 @@ impl Apply for PluginTerminals { .filter(|tab| tab.alive.load(Ordering::Acquire)) .ok_or(HostError::Unavailable)?; tab.output - .try_send(terminal_output(&request.text).into_bytes()) + .try_send(terminal_output_owned(request.text).into_bytes()) .map_err(|_| HostError::RateLimited { retry_after_ms: 250, }) diff --git a/src/shell_setup/user_plugins/terminals/file_requests.rs b/src/shell_setup/user_plugins/terminals/file_requests.rs new file mode 100644 index 00000000..e14c8d92 --- /dev/null +++ b/src/shell_setup/user_plugins/terminals/file_requests.rs @@ -0,0 +1,211 @@ +//! Each window tracks outstanding replies and schedules their nearest deadline. + +use std::{ + cell::RefCell, + collections::BTreeMap, + rc::Rc, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::{Duration, Instant}, +}; + +use futures::channel::oneshot; +use gpui_kit::AsyncApp; +use nocterm_plugin_api::{ + HostError, + capability::files::{FILE_TIMEOUT_MS, FileAnswer, FileFailure, FileReply, MAX_FILE_REQUESTS}, +}; +use nocterm_plugin_model::PluginId; + +use super::Tab; + +pub(super) type Waiting = Rc>; +const FILE_TIMEOUT: Duration = Duration::from_millis(FILE_TIMEOUT_MS as u64); +const TIMED_OUT: &str = "the plugin did not answer in time"; + +struct Pending { + id: u32, + expires: Instant, + reply: oneshot::Sender, +} + +struct TabRequests { + alive: Arc, + pending: Vec, +} + +impl TabRequests { + fn take(&mut self, id: u32) -> Option { + let index = self.pending.iter().position(|request| request.id == id)?; + Some(self.pending.swap_remove(index)) + } +} + +#[derive(Default)] +pub(super) struct FileRequests { + tabs: BTreeMap>, + next: u32, + timer_running: bool, + closed: bool, +} + +impl FileRequests { + pub(super) fn begin( + &mut self, + tab: &Tab, + reply: oneshot::Sender, + now: Instant, + ) -> Option { + if self.closed || !tab.alive.load(Ordering::Acquire) || reply.is_canceled() { + return None; + } + let tabs = self.tabs.entry(tab.call.plugin.clone()).or_default(); + if !tabs + .get(&tab.terminal) + .is_some_and(|requests| Arc::ptr_eq(&requests.alive, &tab.alive)) + { + tabs.insert( + tab.terminal.clone(), + TabRequests { + alive: tab.alive.clone(), + pending: Vec::new(), + }, + ); + } + let requests = tabs + .get_mut(&tab.terminal) + .expect("tab requests are registered"); + requests + .pending + .retain(|request| !request.reply.is_canceled()); + if requests.pending.len() >= MAX_FILE_REQUESTS { + send_failure( + reply, + "too many plugin file requests are waiting for an answer", + ); + return None; + } + let id = self.next; + self.next = id.wrapping_add(1); + requests.pending.push(Pending { + id, + expires: now + FILE_TIMEOUT, + reply, + }); + Some(id) + } + + pub(super) fn complete( + &mut self, + plugin: &PluginId, + reply: FileReply, + now: Instant, + ) -> Result<(), HostError> { + let requests = self + .tabs + .get_mut(plugin) + .and_then(|tabs| tabs.get_mut(&reply.terminal)) + .filter(|requests| requests.alive.load(Ordering::Acquire)) + .ok_or(HostError::Unavailable)?; + let pending = requests.take(reply.request).ok_or(HostError::Unavailable)?; + if pending.expires <= now { + send_failure(pending.reply, TIMED_OUT); + return Err(HostError::Unavailable); + } + pending + .reply + .send(reply.answer) + .map_err(|_| HostError::Unavailable) + } + + pub(super) fn fail(&mut self, tab: &Tab, id: u32, message: &str) { + let request = self + .tabs + .get_mut(&tab.call.plugin) + .and_then(|tabs| tabs.get_mut(&tab.terminal)) + .filter(|requests| Arc::ptr_eq(&requests.alive, &tab.alive)) + .and_then(|requests| requests.take(id)); + if let Some(request) = request { + send_failure(request.reply, message); + } + } + + pub(super) fn close_tab(&mut self, tab: &Tab) { + let Some(tabs) = self.tabs.get_mut(&tab.call.plugin) else { + return; + }; + if tabs + .get(&tab.terminal) + .is_some_and(|requests| Arc::ptr_eq(&requests.alive, &tab.alive)) + { + tabs.remove(&tab.terminal); + } + if tabs.is_empty() { + self.tabs.remove(&tab.call.plugin); + } + } + + pub(super) fn close(&mut self) { + self.closed = true; + self.tabs.clear(); + } + + fn arm(&mut self, now: Instant) -> Option { + if self.timer_running { + return None; + } + let next = self + .tabs + .values() + .flat_map(|tabs| tabs.values()) + .flat_map(|requests| &requests.pending) + .map(|request| request.expires) + .min()?; + self.timer_running = true; + Some(next.saturating_duration_since(now)) + } + + fn expire(&mut self, now: Instant) -> Option { + for requests in self.tabs.values_mut().flat_map(|tabs| tabs.values_mut()) { + for request in requests + .pending + .extract_if(.., |request| request.expires <= now) + { + send_failure(request.reply, TIMED_OUT); + } + } + self.timer_running = false; + self.arm(now) + } +} + +/// At most one delayed wake per window, with a weak reference to its request state. +pub(super) fn schedule(waiting: &Waiting, cx: &mut AsyncApp) { + let executor = cx.background_executor(); + let Some(duration) = waiting.borrow_mut().arm(executor.now()) else { + return; + }; + let executor = executor.clone(); + let waiting = Rc::downgrade(waiting); + let mut timer = executor.timer(duration); + cx.spawn(async move |_| { + loop { + timer.await; + let Some(waiting) = waiting.upgrade() else { + break; + }; + let duration = waiting.borrow_mut().expire(executor.now()); + let Some(duration) = duration else { + break; + }; + timer = executor.timer(duration); + } + }) + .detach(); +} + +fn send_failure(reply: oneshot::Sender, message: &str) { + let _ = reply.send(FileAnswer::Failed(FileFailure::Other(message.to_owned()))); +} diff --git a/src/shell_setup/user_plugins/terminals/fs.rs b/src/shell_setup/user_plugins/terminals/fs.rs index 45a6b251..4badfe00 100644 --- a/src/shell_setup/user_plugins/terminals/fs.rs +++ b/src/shell_setup/user_plugins/terminals/fs.rs @@ -5,13 +5,14 @@ //! answer. Paths are checked before the plugin is asked, contents travel as base64 and are //! bounded on both ways, and nothing here touches a file of this computer. -use futures::{ - SinkExt as _, - channel::{mpsc, oneshot}, -}; +use std::sync::{Arc, Mutex, Weak}; + +use futures::channel::{mpsc, oneshot}; use nocterm_plugin_api::{ base64, - capability::files::{FileAnswer, FileEntry, FileFailure, FileOp, MAX_FILE_BYTES}, + capability::files::{ + FileAnswer, FileEntry, FileFailure, FileOp, MAX_FILE_BYTES, MAX_FILE_REQUESTS, + }, }; use nocterm_session::{ DirEntry, EntryKind, FileMetadata, FsCapabilities, FsError, FsFuture, RemoteFs, @@ -33,25 +34,67 @@ impl Asked { /// The file system of one plugin terminal. Cloning it shares the way to the plugin. #[derive(Clone)] pub(super) struct PluginFs { - asks: mpsc::Sender, + mailbox: Arc>, +} + +struct Mailbox { + sender: mpsc::Sender, + live: usize, +} + +/// Releases admission when the caller receives an answer or drops its future. +struct Slot(Arc>); + +impl Drop for Slot { + fn drop(&mut self) { + self.0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .live -= 1; + } } impl PluginFs { - pub(super) fn new(asks: mpsc::Sender) -> Self { - Self { asks } + pub(super) fn channel() -> (Self, mpsc::Receiver) { + // A futures mpsc sender has one reserved slot in addition to the buffer. + let (sender, receiver) = mpsc::channel(MAX_FILE_REQUESTS - 1); + let fs = Self { + mailbox: Arc::new(Mutex::new(Mailbox { sender, live: 0 })), + }; + (fs, receiver) } - /// Asks the plugin and waits for its answer. A path the host would not ask about is refused - /// here, and a closed tab or a plugin that never answers is an error. - async fn ask(mut self, op: FileOp) -> Result { + fn send(&self, asked: Asked) -> Result { + let over_limit = + || FsError::Other("too many plugin file requests are waiting for an answer".into()); + let mut mailbox = self + .mailbox + .lock() + .unwrap_or_else(|error| error.into_inner()); + if mailbox.sender.is_closed() { + return Err(FsError::NotConnected); + } + if mailbox.live >= MAX_FILE_REQUESTS { + return Err(over_limit()); + } + mailbox.sender.try_send(asked).map_err(|error| { + if error.is_full() { + over_limit() + } else { + FsError::NotConnected + } + })?; + mailbox.live += 1; + Ok(Slot(self.mailbox.clone())) + } + + /// Validates before enqueueing and keeps the slot through the reply. + async fn ask(self, op: FileOp) -> Result { op.check().map_err(|error| { FsError::Other(format!("not a path the plugin is asked about: {error}")) })?; let (reply, answer) = oneshot::channel(); - self.asks - .send(Asked { op, reply }) - .await - .map_err(|_| FsError::NotConnected)?; + let _slot = self.send(Asked { op, reply })?; answer .await .map_err(|_| FsError::Other("the plugin did not answer".into())) @@ -238,8 +281,7 @@ impl RemoteFs for PluginFs { fs: self.clone(), path: path.to_owned(), create: mode == UploadMode::Create, - bytes: Vec::new(), - published: false, + contents: UploadContents::Writable(UploadBytes::Contiguous(Vec::new())), }; Box::pin(async move { Ok(Box::new(upload) as Box) }) } @@ -254,8 +296,18 @@ struct Downloaded { impl RemoteDownload for Downloaded { fn read(&mut self, max_bytes: usize) -> FsFuture> { let end = self.bytes.len().min(self.at.saturating_add(max_bytes)); - let chunk = self.bytes[self.at..end].to_vec(); - self.at = end; + let chunk = if self.at == 0 && end == self.bytes.len() { + std::mem::take(&mut self.bytes) + } else { + let chunk = self.bytes[self.at..end].to_vec(); + if end == self.bytes.len() { + self.bytes = Vec::new(); + self.at = 0; + } else { + self.at = end; + } + chunk + }; Box::pin(async move { Ok(chunk) }) } @@ -269,46 +321,164 @@ struct Upload { fs: PluginFs, path: String, create: bool, - bytes: Vec, - published: bool, + contents: UploadContents, +} + +/// Once sealed, only a definite Create collision returns the bytes for a name retry. +enum UploadContents { + Writable(UploadBytes), + Sealed(Arc), } -impl Upload { - fn publish(&mut self, path: String) -> FsFuture { - if self.published { - return Box::pin(async { Err(FsError::Other("the upload was published".into())) }); +type SealedBytes = Mutex>; + +/// Keep a bounded first batch in its original buffers until a later write needs them joined. +enum UploadBytes { + Contiguous(Vec), + Batch { chunks: Vec>, len: usize }, +} + +impl UploadBytes { + fn len(&self) -> usize { + match self { + Self::Contiguous(bytes) => bytes.len(), + Self::Batch { len, .. } => *len, + } + } + + fn into_contiguous(self) -> Vec { + match self { + Self::Contiguous(bytes) => bytes, + Self::Batch { chunks, len } => { + let mut bytes = Vec::with_capacity(len); + for chunk in chunks { + bytes.extend_from_slice(&chunk); + } + bytes + } + } + } + + fn contiguous(&mut self) -> &mut Vec { + if matches!(self, Self::Batch { .. }) { + let staged = std::mem::replace(self, Self::Contiguous(Vec::new())); + *self = Self::Contiguous(staged.into_contiguous()); } - self.published = true; + let Self::Contiguous(bytes) = self else { + unreachable!() + }; + bytes + } +} + +fn publish( + fs: PluginFs, + path: String, + create: bool, + bytes: UploadBytes, + retry: Option>, +) -> FsFuture { + Box::pin(async move { + // The detached operation may outlive its upload handle before it starts. + if retry + .as_ref() + .is_some_and(|stage| stage.strong_count() == 0) + { + return Err(sealed_error()); + } + let data = match &bytes { + UploadBytes::Contiguous(bytes) => base64::encode(bytes), + UploadBytes::Batch { chunks, .. } => base64::encode_segments(chunks), + }; let op = FileOp::Write { path: path.clone(), - data: base64::encode(&self.bytes), - create: self.create, + data, + create, }; - let fs = self.fs.clone(); - Box::pin(async move { - match fs.ask(op).await? { - FileAnswer::Done => Ok(path), - FileAnswer::Failed(failure) => Err(failed(failure, &path)), - _ => Err(unexpected()), + let retained = retry.filter(|_| create).map(|retry| (retry, bytes)); + match fs.ask(op).await? { + FileAnswer::Done => Ok(path), + FileAnswer::Failed(failure) => { + if matches!(failure, FileFailure::AlreadyExists) + && let Some((retry, bytes)) = retained + && let Some(retry) = retry.upgrade() + { + *retry.lock().unwrap_or_else(|error| error.into_inner()) = Some(bytes); + } + Err(failed(failure, &path)) } - }) + _ => Err(unexpected()), + } + }) +} + +fn sealed_error() -> FsError { + FsError::Other("the upload is sealed or has already been published".into()) +} + +fn upload_size_error() -> FsError { + FsError::Other(format!( + "a plugin's files hold at most {} KiB", + MAX_FILE_BYTES / 1024 + )) +} + +fn append(contents: &mut Vec, bytes: Vec) { + if contents.is_empty() && !bytes.is_empty() && bytes.capacity() <= MAX_FILE_BYTES { + *contents = bytes; + } else { + contents.extend_from_slice(&bytes); } } impl RemoteUpload for Upload { fn write(&mut self, bytes: Vec) -> FsFuture<()> { - if self.published { - return Box::pin(async { Err(FsError::Other("the upload was published".into())) }); + let UploadContents::Writable(contents) = &mut self.contents else { + return Box::pin(async { Err(sealed_error()) }); + }; + if bytes.len() > MAX_FILE_BYTES - contents.len() { + return Box::pin(async { Err(upload_size_error()) }); } - if self.bytes.len() + bytes.len() > MAX_FILE_BYTES { + append(contents.contiguous(), bytes); + Box::pin(async { Ok(()) }) + } + + fn write_batch(&mut self, mut chunks: Vec>) -> FsFuture<()> { + if chunks.is_empty() { + return Box::pin(async { Ok(()) }); + } + if chunks.len() > 8 || chunks.iter().any(|chunk| chunk.len() > 32 * 1024) { return Box::pin(async { - Err(FsError::Other(format!( - "a plugin's files hold at most {} KiB", - MAX_FILE_BYTES / 1024 - ))) + Err(FsError::Other("upload batch exceeds 8 × 32 KiB".into())) }); } - self.bytes.extend_from_slice(&bytes); + let UploadContents::Writable(contents) = &mut self.contents else { + return Box::pin(async { Err(sealed_error()) }); + }; + let additional = chunks.iter().map(Vec::len).sum::(); + if additional > MAX_FILE_BYTES - contents.len() { + return Box::pin(async { Err(upload_size_error()) }); + } + if let [chunk] = chunks.as_mut_slice() { + append(contents.contiguous(), std::mem::take(chunk)); + } else if contents.len() == 0 + && chunks.capacity() <= 8 + && chunks + .iter() + .try_fold(0usize, |total, chunk| total.checked_add(chunk.capacity())) + .is_some_and(|capacity| capacity <= MAX_FILE_BYTES) + { + *contents = UploadBytes::Batch { + chunks, + len: additional, + }; + } else { + let contents = contents.contiguous(); + contents.reserve_exact(additional); + for chunk in chunks { + contents.extend_from_slice(&chunk); + } + } Box::pin(async { Ok(()) }) } @@ -316,14 +486,42 @@ impl RemoteUpload for Upload { if !nocterm_session::fs::valid_publication_name(&name) { return Box::pin(async { Err(FsError::Other("not a file name".into())) }); } - let parent = nocterm_session::fs::path::parent(&self.path).to_owned(); - let path = nocterm_session::fs::path::join(&parent, &name); - self.publish(path) + let parent = nocterm_session::fs::path::parent(&self.path); + let path = nocterm_session::fs::path::join(parent, &name); + let (bytes, retry) = match &mut self.contents { + UploadContents::Writable(contents) => { + let bytes = std::mem::replace(contents, UploadBytes::Contiguous(Vec::new())); + let retry = Arc::new(Mutex::new(None)); + let weak = Arc::downgrade(&retry); + self.contents = UploadContents::Sealed(retry); + (Some(bytes), weak) + } + UploadContents::Sealed(retry) => { + let bytes = retry + .lock() + .unwrap_or_else(|error| error.into_inner()) + .take(); + (bytes, Arc::downgrade(retry)) + } + }; + let Some(bytes) = bytes else { + return Box::pin(async { Err(sealed_error()) }); + }; + publish(self.fs.clone(), path, self.create, bytes, Some(retry)) } - fn finish(mut self: Box) -> FsFuture { - let path = self.path.clone(); - self.publish(path) + fn finish(self: Box) -> FsFuture { + let bytes = match self.contents { + UploadContents::Writable(bytes) => Some(bytes), + UploadContents::Sealed(retry) => retry + .lock() + .unwrap_or_else(|error| error.into_inner()) + .take(), + }; + let Some(bytes) = bytes else { + return Box::pin(async { Err(sealed_error()) }); + }; + publish(self.fs, self.path, self.create, bytes, None) } fn cancel(self: Box) -> FsFuture<()> { diff --git a/src/shell_setup/user_plugins/terminals/fs/tests.rs b/src/shell_setup/user_plugins/terminals/fs/tests.rs index 960075b7..8074e2da 100644 --- a/src/shell_setup/user_plugins/terminals/fs/tests.rs +++ b/src/shell_setup/user_plugins/terminals/fs/tests.rs @@ -5,11 +5,13 @@ use std::sync::{Arc, Mutex}; use futures::{StreamExt as _, channel::mpsc, executor::block_on, future::join}; use nocterm_plugin_api::{ base64, - capability::files::{FileAnswer, FileEntry, FileFailure, FileOp, MAX_FILE_BYTES}, + capability::files::{ + FileAnswer, FileEntry, FileFailure, FileOp, MAX_FILE_BYTES, MAX_FILE_REQUESTS, + }, }; use nocterm_session::{EntryKind, FsError, RemoteFs, fs::UploadMode}; -use super::{Asked, PluginFs}; +use super::PluginFs; /// A plugin that answers each request with the next of `answers`, and the requests it was asked. fn plugin( @@ -19,7 +21,7 @@ fn plugin( impl std::future::Future, Arc>>, ) { - let (asks, mut asked) = mpsc::channel::(8); + let (fs, mut asked) = PluginFs::channel(); let seen = Arc::new(Mutex::new(Vec::new())); let log = seen.clone(); let serve = async move { @@ -35,7 +37,7 @@ fn plugin( } } }; - (PluginFs::new(asks), serve, seen) + (fs, serve, seen) } fn file(name: &str, directory: bool) -> FileEntry { @@ -188,6 +190,264 @@ fn an_upload_larger_than_a_plugin_file_is_refused_before_the_plugin_is_asked() { assert!(seen.lock().unwrap().is_empty()); } +#[test] +fn rejected_batches_leave_prior_bytes_available_for_a_valid_batch() { + let (fs, serve, seen) = plugin(vec![FileAnswer::Done]); + block_on(join( + async move { + let mut upload = fs.upload("/batch.bin", UploadMode::Create).await.unwrap(); + upload.write(vec![1; 32 * 1024]).await.unwrap(); + assert!(upload.write_batch(vec![vec![2]; 9]).await.is_err()); + assert!( + upload + .write_batch(vec![vec![2; 32 * 1024 + 1]]) + .await + .is_err() + ); + assert!( + upload + .write_batch(vec![vec![2; 32 * 1024]; 5]) + .await + .is_err() + ); + upload + .write_batch(vec![vec![3; 32 * 1024]; 4]) + .await + .unwrap(); + assert_eq!(upload.finish().await.unwrap(), "/batch.bin"); + }, + serve, + )); + let seen = seen.lock().unwrap(); + let [ + FileOp::Write { + path, + data, + create: true, + }, + ] = seen.as_slice() + else { + panic!("one staged write expected"); + }; + assert_eq!(path, "/batch.bin"); + let bytes = base64::decode(data).unwrap(); + assert_eq!(bytes.len(), MAX_FILE_BYTES); + assert_eq!(&bytes[..32 * 1024], vec![1; 32 * 1024]); + assert_eq!(&bytes[32 * 1024..], vec![3; 128 * 1024]); +} + +#[test] +fn a_second_batch_and_a_single_chunk_extend_the_same_file_in_order() { + let (fs, serve, seen) = plugin(vec![FileAnswer::Done]); + block_on(join( + async move { + let mut upload = fs.upload("/continued", UploadMode::Create).await.unwrap(); + upload + .write_batch(vec![b"ab".to_vec(), b"c".to_vec()]) + .await + .unwrap(); + upload + .write_batch(vec![b"d".to_vec(), b"efg".to_vec()]) + .await + .unwrap(); + upload.write(b"hij".to_vec()).await.unwrap(); + assert_eq!(upload.finish().await.unwrap(), "/continued"); + }, + serve, + )); + assert_eq!( + seen.lock().unwrap().as_slice(), + [FileOp::Write { + path: "/continued".into(), + data: base64::encode(b"abcdefghij"), + create: true, + }], + ); +} + +#[test] +fn finishing_an_empty_file_and_reading_it_back_preserve_eof() { + let (fs, serve, seen) = plugin(vec![FileAnswer::Done, FileAnswer::Content(String::new())]); + block_on(join( + async move { + let upload = fs.upload("/empty", UploadMode::Create).await.unwrap(); + assert_eq!(upload.finish().await.unwrap(), "/empty"); + let mut read = fs.download("/empty").await.unwrap(); + assert!(read.read(MAX_FILE_BYTES).await.unwrap().is_empty()); + assert!(read.read(1).await.unwrap().is_empty()); + read.close().await.unwrap(); + }, + serve, + )); + assert!(matches!( + seen.lock().unwrap().as_slice(), + [FileOp::Write { path, data, create: true }, FileOp::Read { path: read }] + if path == "/empty" && data.is_empty() && read == "/empty" + )); +} + +#[test] +fn an_unpolled_publication_cannot_outlive_a_canceled_upload() { + use futures::FutureExt as _; + + let (fs, mut asked) = PluginFs::channel(); + block_on(async { + let mut upload = fs.upload("/file", UploadMode::Create).await.unwrap(); + upload.write(vec![7]).await.unwrap(); + let publication = upload.publish_as("file".into()); + upload.cancel().await.unwrap(); + assert!(matches!(publication.now_or_never(), Some(Err(_)))); + }); + assert!(asked.try_recv().is_err()); +} + +#[test] +fn an_unacknowledged_publication_keeps_the_stage_sealed() { + use futures::FutureExt as _; + + let (fs, mut asked) = PluginFs::channel(); + block_on(async { + let mut upload = fs.upload("/file", UploadMode::Create).await.unwrap(); + upload.write(vec![7]).await.unwrap(); + let mut publication = upload.publish_as("file".into()); + assert!(publication.as_mut().now_or_never().is_none()); + let (_, reply) = asked.try_recv().unwrap().into_parts(); + assert!(upload.publish_as("overlap".into()).await.is_err()); + drop(publication); + assert!(reply.is_canceled()); + assert!(upload.write(vec![8]).await.is_err()); + assert!(upload.publish_as("unknown".into()).await.is_err()); + assert!(upload.finish().await.is_err()); + }); + assert!(asked.try_recv().is_err()); +} + +#[test] +fn a_replace_collision_cannot_publish_the_stage_under_another_name() { + let (fs, serve, seen) = plugin(vec![FileAnswer::Failed(FileFailure::AlreadyExists)]); + block_on(join( + async move { + let mut upload = fs.upload("/original", UploadMode::Replace).await.unwrap(); + upload.write(vec![7]).await.unwrap(); + assert!(matches!( + upload.publish_as("original".into()).await, + Err(FsError::AlreadyExists { path }) if path == "/original" + )); + assert!(upload.publish_as("retry".into()).await.is_err()); + }, + serve, + )); + assert!(matches!( + seen.lock().unwrap().as_slice(), + [FileOp::Write { path, create: false, .. }] if path == "/original" + )); +} + +#[tokio::test] +async fn a_full_size_transfer_publishes_the_same_bytes_after_a_late_name_collision() { + use nocterm_localfs::LocalFilesystem; + use nocterm_session::{HostAddress, Target}; + use nocterm_transfer_runtime::{TransferRuntime, TransferRuntimeDeps}; + use nocterm_transfers::{ + CollisionPolicy, TransferRequests, TransferService, TransferState, UploadRequest, + }; + use std::time::Duration; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let source = root.join("source.bin"); + let bytes: Vec<_> = (0..5).flat_map(|chunk| vec![chunk; 32 * 1024]).collect(); + std::fs::write(&source, &bytes).unwrap(); + let local = Arc::new(LocalFilesystem::with_base(root).unwrap()); + let transfers = + TransferRuntime::start(TransferRuntimeDeps::new(local, Default::default())).unwrap(); + let (fs, serve, seen) = plugin(vec![ + FileAnswer::Found(None), + FileAnswer::Failed(FileFailure::AlreadyExists), + FileAnswer::Found(None), + FileAnswer::Done, + ]); + let id = transfers + .enqueue(UploadRequest { + sources: vec![source], + host: HostAddress::direct(Target::new("probe", "plugin", 22)), + destination: "/dest".into(), + fs: Arc::new(fs), + collisions: CollisionPolicy::Rename, + }) + .unwrap(); + let finished = async { + loop { + let revision = transfers.revision().unwrap(); + let progress = transfers.progress(id).unwrap(); + if progress.state.finished() { + break progress; + } + transfers.changed_since(revision).unwrap().await; + } + }; + let progress = tokio::select! { + result = tokio::time::timeout(Duration::from_secs(10), finished) => result.unwrap(), + () = serve => panic!("the plugin stopped serving the transfer"), + }; + assert_eq!(progress.state, TransferState::Completed, "{progress:?}"); + assert_eq!(progress.sent_bytes, MAX_FILE_BYTES as u64); + let seen = seen.lock().unwrap(); + let writes: Vec<_> = seen + .iter() + .filter(|op| matches!(op, FileOp::Write { .. })) + .collect(); + let data = base64::encode(&bytes); + assert_eq!( + writes, + [ + &FileOp::Write { + path: "/dest/source.bin".into(), + data: data.clone(), + create: true + }, + &FileOp::Write { + path: "/dest/source (1).bin".into(), + data, + create: true + }, + ] + ); +} + +#[test] +#[ignore = "manual timing for bounded plugin file staging"] +fn measure_plugin_file_staging() { + use std::{hint::black_box, io::Write as _, time::Instant}; + + let (fs, mut asked) = PluginFs::channel(); + block_on(async { + for count in [1, 5] { + let mut stage = Vec::new(); + let mut abandoned = Vec::new(); + for _ in 0..250 { + let mut upload = fs.upload("/timed", UploadMode::Create).await.unwrap(); + let input = (0..count).map(|id| vec![id; 32 * 1024]).collect(); + let start = Instant::now(); + upload.write_batch(black_box(input)).await.unwrap(); + stage.push(start.elapsed().as_nanos()); + let start = Instant::now(); + let publication = black_box(upload.finish()); + abandoned.push(start.elapsed().as_nanos()); + drop(publication); + } + stage.sort_unstable(); + abandoned.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{count} chunks of 32 KiB, staging median/p95 {}/{} ns, unpolled finish median/p95 {}/{} ns", + stage[125], stage[237], abandoned[125], abandoned[237], + ).unwrap(); + } + }); + assert!(asked.try_recv().is_err()); +} + #[test] fn creating_a_directory_that_is_there_already_is_accepted() { let (fs, serve, _) = plugin(vec![ @@ -224,3 +484,53 @@ fn a_plugin_that_never_answers_fails_the_request() { .0; assert!(matches!(failed, Err(FsError::Other(_)))); } + +#[test] +fn canceling_asks_cannot_leave_an_unbounded_mailbox() { + use futures::FutureExt as _; + + let (fs, mut asked) = PluginFs::channel(); + for _ in 0..512 { + let _ = fs.read_dir("/").now_or_never(); + } + for _ in 0..MAX_FILE_REQUESTS { + let (_, reply) = asked.try_recv().unwrap().into_parts(); + assert!(reply.is_canceled()); + } + assert!(matches!(asked.try_recv(), Err(mpsc::TryRecvError::Empty))); + + let mut followup = fs.read_dir("/next"); + assert!(followup.as_mut().now_or_never().is_none()); + let (op, reply) = asked.try_recv().unwrap().into_parts(); + assert!(matches!(op, FileOp::List { path } if path == "/next")); + reply.send(FileAnswer::Listed(Vec::new())).unwrap(); + assert!(matches!(followup.as_mut().now_or_never(), Some(Ok(list)) if list.is_empty())); +} + +#[test] +fn dispatched_requests_still_use_slots_until_answered_or_canceled() { + use futures::FutureExt as _; + + let (fs, mut asked) = PluginFs::channel(); + let mut requests = Vec::new(); + for _ in 0..MAX_FILE_REQUESTS { + let mut future = fs.read_dir("/"); + assert!(future.as_mut().now_or_never().is_none()); + let (_, reply) = asked.try_recv().unwrap().into_parts(); + requests.push((future, reply)); + } + assert!(matches!( + fs.read_dir("/refused").now_or_never(), + Some(Err(FsError::Other(_))) + )); + assert!(matches!(asked.try_recv(), Err(mpsc::TryRecvError::Empty))); + + let (canceled, reply) = requests.pop().unwrap(); + drop(canceled); + assert!(reply.is_canceled()); + let mut next = fs.read_dir("/accepted"); + assert!(next.as_mut().now_or_never().is_none()); + let (_, reply) = asked.try_recv().unwrap().into_parts(); + reply.send(FileAnswer::Listed(Vec::new())).unwrap(); + assert!(matches!(next.as_mut().now_or_never(), Some(Ok(list)) if list.is_empty())); +} diff --git a/src/shell_setup/user_plugins/terminals/tests.rs b/src/shell_setup/user_plugins/terminals/tests.rs index 9e8275c2..5b7ed7a8 100644 --- a/src/shell_setup/user_plugins/terminals/tests.rs +++ b/src/shell_setup/user_plugins/terminals/tests.rs @@ -107,3 +107,5 @@ fn a_half_typed_line_is_not_a_clean_prompt_until_it_is_cleared(cx: &mut TestAppC [b"\x08 \x08\x08 \x08".as_slice(), READY].concat() ); } + +mod files_bridge; diff --git a/src/shell_setup/user_plugins/terminals/tests/files_bridge.rs b/src/shell_setup/user_plugins/terminals/tests/files_bridge.rs new file mode 100644 index 00000000..1359f57a --- /dev/null +++ b/src/shell_setup/user_plugins/terminals/tests/files_bridge.rs @@ -0,0 +1,319 @@ +//! File requests crossing the terminal bridge and the window's reply provider. + +use std::{ + rc::Rc, + sync::{Arc, atomic::AtomicBool}, + time::Duration, +}; + +use futures::{FutureExt as _, channel::mpsc}; +use gpui_kit::{AnyWindowHandle, AppContext as _, Entity, TestAppContext, WeakEntity}; +use nocterm_plugin_api::{ + ContributionContext, Event, HostError, Kind, LocalId, Zone, + capability::files::{FILE_TIMEOUT_MS, FileAnswer, FileReply, MAX_FILE_REQUESTS, ServeFiles}, +}; +use nocterm_plugin_host::{ + Call, HostPorts, PluginHost, + test_support::{MemoryData, MemoryPackages, MemoryRecords, Script, ScriptedRuntime, package}, +}; +use nocterm_plugin_model::PluginId; +use nocterm_plugin_ports::{Apply, PluginProviders}; +use nocterm_session::Session; + +use super::super::{ + PluginTerminals, Tab, TerminalsHandle, drive, forward_lines, fs::PluginFs, serve_files, +}; +use crate::shell_setup::user_plugin_panel::TerminalBars; + +const FILE_TIMEOUT: Duration = Duration::from_millis(FILE_TIMEOUT_MS as u64); +const TERMINAL: &str = "files"; + +struct Bridge { + host: Entity, + script: Script, + terminals: Rc, + plugin: PluginId, + call: Call, + providers: PluginProviders, +} + +impl Bridge { + fn new(cx: &mut TestAppContext) -> Self { + cx.add_empty_window(); + let window: AnyWindowHandle = cx.windows()[0]; + let script = Script::new(); + let host = cx.new(|_| { + PluginHost::new(HostPorts { + records: MemoryRecords::new(), + data: MemoryData::new(), + packages: MemoryPackages::new(), + runtime: ScriptedRuntime::new(&script), + net: None, + }) + }); + let plugin = host + .update(cx, |host, cx| host.install(package(1), &[], cx)) + .unwrap(); + cx.run_until_parked(); + let terminals = PluginTerminals::new( + window, + WeakEntity::new_invalid(), + Rc::new(|_, _, _, _| Ok(())), + host.downgrade(), + TerminalBars::new(WeakEntity::new_invalid(), false), + ); + let providers = + PluginProviders::new().with_serve_files(Rc::new(TerminalsHandle::new(&terminals))); + terminals.bind(providers.clone()); + let call = Call { + window: window.window_id(), + plugin: plugin.clone(), + local: LocalId::parse("board").unwrap(), + context: ContributionContext { + kind: Kind::Panel, + zone: Zone::Center, + }, + in_focus: false, + terminal: None, + }; + Self { + host, + script, + terminals, + plugin, + call, + providers, + } + } + + fn open(&self, cx: &mut TestAppContext) -> Session { + self.open_holding_lines(cx).0 + } + + fn open_holding_lines(&self, cx: &mut TestAppContext) -> (Session, mpsc::Sender) { + let (fs, asked) = PluginFs::channel(); + let (typed, lines) = mpsc::channel(1); + let hold_lines = typed.clone(); + let (output, written) = mpsc::channel(1); + let (session, driver) = nocterm_session::channel(Some(Arc::new(fs))); + let alive = Arc::new(AtomicBool::new(true)); + let executor = cx.executor(); + let tab_alive = alive.clone(); + let clock = executor.clone(); + executor + .spawn(async move { + drive(driver, written, typed, tab_alive, clock).await; + drop(output); + }) + .detach(); + let tab = Tab { + host: self.host.downgrade(), + call: self.call.clone(), + providers: self.providers.clone(), + terminal: TERMINAL.into(), + alive, + }; + cx.update(|cx| { + serve_files(tab.clone(), asked, self.terminals.waiting.clone(), cx); + forward_lines(tab, lines, self.terminals.waiting.clone(), cx); + }); + (session, hold_lines) + } + + fn requests(&self) -> Vec { + self.script + .events() + .into_iter() + .filter_map(|event| match event { + Event::FileRequest { request, .. } => Some(request), + _ => None, + }) + .collect() + } + + fn reply(&self, request: u32, cx: &mut TestAppContext) -> Result<(), HostError> { + let handle = TerminalsHandle::new(&self.terminals); + cx.update(|cx| { + Apply::::apply( + &handle, + &self.plugin, + FileReply { + terminal: TERMINAL.into(), + request, + answer: FileAnswer::Listed(Vec::new()), + }, + cx, + ) + }) + } +} + +#[gpui_kit::test] +fn the_plugin_file_bridge_bounds_live_requests_and_reuses_an_answered_slot( + cx: &mut TestAppContext, +) { + let bridge = Bridge::new(cx); + let tab = bridge.open(cx); + let fs = tab.fs().unwrap(); + let mut pending: Vec<_> = (0..MAX_FILE_REQUESTS).map(|_| fs.read_dir("/")).collect(); + for reply in &mut pending { + assert!(reply.as_mut().now_or_never().is_none()); + } + cx.run_until_parked(); + let mut excess = fs.read_dir("/excess"); + let refused = excess.as_mut().now_or_never(); + cx.run_until_parked(); + assert_eq!(bridge.requests().len(), MAX_FILE_REQUESTS); + assert!( + refused + .or_else(|| excess.as_mut().now_or_never()) + .unwrap() + .is_err() + ); + + let first = bridge.requests()[0]; + bridge.reply(first, cx).unwrap(); + assert!( + pending[0] + .as_mut() + .now_or_never() + .unwrap() + .unwrap() + .is_empty() + ); + let mut admitted = fs.read_dir("/admitted"); + assert!(admitted.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + assert_eq!(bridge.requests().len(), MAX_FILE_REQUESTS + 1); + let newest = *bridge.requests().last().unwrap(); + bridge.reply(newest, cx).unwrap(); + assert!( + admitted + .as_mut() + .now_or_never() + .unwrap() + .unwrap() + .is_empty() + ); + + let mut canceled = fs.read_dir("/canceled"); + assert!(canceled.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + drop(canceled); + let mut another = fs.read_dir("/after-cancel"); + assert!(another.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + assert!(another.as_mut().now_or_never().is_none()); + let current = *bridge.requests().last().unwrap(); + bridge.reply(current, cx).unwrap(); + assert!(matches!(another.as_mut().now_or_never(), Some(Ok(list)) if list.is_empty())); +} + +#[gpui_kit::test] +fn the_plugin_file_bridge_keeps_individual_deadlines_and_rejects_replies_to_a_closed_tab( + cx: &mut TestAppContext, +) { + let bridge = Bridge::new(cx); + let tab = bridge.open(cx); + let fs = tab.fs().unwrap(); + let executor = cx.executor(); + let mut first = fs.read_dir("/first"); + assert!(first.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + executor.advance_clock(FILE_TIMEOUT / 2); + let mut second = fs.read_dir("/second"); + assert!(second.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + executor.advance_clock(FILE_TIMEOUT / 2); + cx.run_until_parked(); + assert!(first.as_mut().now_or_never().unwrap().is_err()); + assert!(second.as_mut().now_or_never().is_none()); + let requests = bridge.requests(); + assert!(matches!( + bridge.reply(requests[0], cx), + Err(HostError::Unavailable) + )); + tab.close(); + cx.run_until_parked(); + assert!(second.as_mut().now_or_never().unwrap().is_err()); + + let replacement = bridge.open(cx); + let mut fresh = replacement.fs().unwrap().read_dir("/fresh"); + assert!(fresh.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + assert!(matches!( + bridge.reply(requests[0], cx), + Err(HostError::Unavailable) + )); + assert!(fresh.as_mut().now_or_never().is_none()); + let current = *bridge.requests().last().unwrap(); + bridge.reply(current, cx).unwrap(); + assert!(fresh.as_mut().now_or_never().unwrap().unwrap().is_empty()); +} + +#[gpui_kit::test] +fn closing_the_old_file_tab_does_not_clear_requests_from_its_replacement(cx: &mut TestAppContext) { + let bridge = Bridge::new(cx); + let (old, hold_lines) = bridge.open_holding_lines(cx); + let mut retired = old.fs().unwrap().read_dir("/retired"); + assert!(retired.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + old.close(); + cx.run_until_parked(); + + let replacement = bridge.open(cx); + let mut current = replacement.fs().unwrap().read_dir("/current"); + assert!(current.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + let attempts = bridge.requests(); + assert_eq!(attempts.len(), 2); + assert!(retired.as_mut().now_or_never().unwrap().is_err()); + drop(hold_lines); + cx.run_until_parked(); + assert!(current.as_mut().now_or_never().is_none()); + bridge.reply(attempts[1], cx).unwrap(); + assert!(matches!(current.as_mut().now_or_never(), Some(Ok(list)) if list.is_empty())); +} + +#[gpui_kit::test] +#[ignore = "measure the file bridge's scheduler work with a controlled GPUI clock"] +fn measure_completed_plugin_file_request_timer_work(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + let clock = cx.executor(); + for completed in [32, 512, 4096] { + let bridge = Bridge::new(cx); + let tab = bridge.open(cx); + let fs = tab.fs().unwrap(); + for _ in 0..completed { + let mut answer = fs.read_dir("/"); + assert!(answer.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + bridge + .reply(*bridge.requests().last().unwrap(), cx) + .unwrap(); + assert!(matches!(answer.as_mut().now_or_never(), Some(Ok(list)) if list.is_empty())); + } + + clock.advance_clock(FILE_TIMEOUT / 2); + let mut later = fs.read_dir("/later"); + assert!(later.as_mut().now_or_never().is_none()); + cx.run_until_parked(); + let started = Instant::now(); + clock.advance_clock(FILE_TIMEOUT / 2); + cx.run_until_parked(); + let elapsed = started.elapsed(); + assert!(later.as_mut().now_or_never().is_none()); + clock.advance_clock(FILE_TIMEOUT / 2); + cx.run_until_parked(); + assert!(later.as_mut().now_or_never().unwrap().is_err()); + tab.close(); + cx.run_until_parked(); + writeln!( + std::io::stdout().lock(), + "{completed} answered, processing the first deadline took {} ns", + elapsed.as_nanos(), + ) + .unwrap(); + } +} diff --git a/tests/transfer_filesystem.rs b/tests/transfer_filesystem.rs index 85e8e76e..45d7e2bd 100644 --- a/tests/transfer_filesystem.rs +++ b/tests/transfer_filesystem.rs @@ -104,6 +104,76 @@ fn empty_directory_upload_creates_remote_directory_without_completed_files() { let metadata = futures::executor::block_on(fixture.remote.metadata("/dest/empty")).unwrap(); assert_eq!(metadata.kind, nocterm_session::EntryKind::Directory); } + +#[tokio::test] +#[ignore = "manual timing of native directory discovery and small-file publication"] +async fn measure_small_file_directory_upload() { + use std::io::Write as _; + + for (count, nested) in [(0, false), (32, false), (1024, false), (1024, true)] { + let mut elapsed = Vec::new(); + for _ in 0..8 { + let fixture = Fixture::new(); + let source = fixture.root.path().join("tree"); + std::fs::create_dir(&source).unwrap(); + let files = (0..count) + .map(|index| { + if nested { + format!("group-{}/file-{index:04}", index / 32) + } else { + format!("file-{index:04}") + } + }) + .collect::>(); + for (index, relative) in files.iter().enumerate() { + let path = source.join(relative); + if nested { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + } + std::fs::write(path, [index as u8; 128]).unwrap(); + } + + let start = Instant::now(); + let id = fixture.upload(source, CollisionPolicy::Skip); + let progress = tokio::time::timeout(Duration::from_secs(10), async { + loop { + let revision = fixture.runtime.revision().unwrap(); + let progress = + nocterm_transfers::TransferRequests::progress(fixture.runtime.as_ref(), id) + .unwrap(); + if progress.state.finished() { + break progress; + } + fixture.runtime.changed_since(revision).unwrap().await; + } + }) + .await + .unwrap(); + elapsed.push(start.elapsed()); + assert_eq!(progress.state, TransferState::Completed); + assert_eq!(progress.completed_files, count as u64); + assert_eq!(progress.sent_bytes, 128 * count as u64); + assert!(progress.errors.is_empty()); + for (index, relative) in files.iter().enumerate() { + assert_eq!( + fixture + .remote + .bytes(&format!("/dest/tree/{relative}")) + .unwrap(), + [index as u8; 128] + ); + } + } + elapsed.sort_unstable(); + writeln!( + std::io::stderr().lock(), + "{count} files, nested={nested}, batch p50={:?}, max={:?}", + elapsed[elapsed.len() / 2], + elapsed.last().unwrap() + ) + .unwrap(); + } +} #[test] fn empty_directory_download_creates_native_directory_without_completed_files() { let fixture = Fixture::new(); @@ -172,10 +242,10 @@ fn upload_keeps_opened_original_source_when_its_ancestor_is_replaced_by_a_link() } #[test] fn source_growth_or_truncation_during_acknowledgement_refuses_publication() { - for growth in [false, true] { + for (original, modified) in [(128, 3), (128, 129), (100000, 3), (100000, 100001)] { let fixture = Fixture::new(); let source = fixture.root.path().join("file"); - std::fs::write(&source, vec![1; 100000]).unwrap(); + std::fs::write(&source, vec![1; original]).unwrap(); fixture .remote .seed_file("/dest/file", b"old-final") @@ -197,7 +267,7 @@ fn source_growth_or_truncation_during_acknowledgement_refuses_publication() { .write(true) .open(&source) .unwrap() - .set_len(if growth { 100001 } else { 3 }) + .set_len(modified) .unwrap(); gate.release(); let progress = fixture.finished(id); diff --git a/vendor/alacritty_terminal/NOCTERM.md b/vendor/alacritty_terminal/NOCTERM.md index 8a04b1fc..3d512a75 100644 --- a/vendor/alacritty_terminal/NOCTERM.md +++ b/vendor/alacritty_terminal/NOCTERM.md @@ -12,7 +12,9 @@ tests remain intact; Nocterm's additional coverage lives beside the modified engine methods and in `crates/vt/src/emulator.rs`. This is an internal Cargo patch, not a new published terminal library. -`src/term/cell.rs`, `src/term/mod.rs`, `src/term/keyboard.rs` and `src/tty/unix.rs` differ from the +`src/grid/mod.rs`, `src/grid/storage.rs`, `src/grid/resize.rs`, `src/grid/row.rs`, +`src/term/cell.rs`, `src/term/mod.rs`, +`src/term/keyboard.rs`, `src/term/selection_text.rs` and `src/tty/unix.rs` differ from the distribution's library sources. The Unix shell-user lookup uses equivalent `?` error propagation to satisfy current Clippy without changing environment-variable fallback behavior. Cargo uses the original normalized package dependencies. @@ -23,6 +25,13 @@ Nocterm's verification. ## Behavior and memory +Selection availability uses the same character traversal as clipboard +extraction. It stops as soon as the copied text would be nonempty and +allocates no text buffer. Regular copying appends directly into its result +without assembling intermediate strings for each row. +Consumers can request a prefix bounded by Unicode scalars using the same +character traversal and final newline rules. + Metadata is disabled by default. `Term::set_output_timestamp_ms` opts in and supplies the host's observation time. Nocterm calls it when feeding the parser. The resulting `LogicalLine` records a monotonic number and the first output time @@ -39,9 +48,24 @@ removing hyperlink/underline data. A bounded, one-entry cache shares the same `Arc` between ordinary characters of a logical line and attribute template; it does not retain an unbounded map of old lines. The scrollback limit still bounds retained cells and metadata. Marked output blanks count as occupied -for resize, so explicit blank lines are preserved. Without opt-in, upstream +for resize, so explicit blank lines are preserved. A row with zero occupied +cells has no lineage to look up. The existing row occupancy bookkeeping lets +the first write on such a row skip scanning the cells. Without opt-in, upstream cell emptiness and terminal behavior are unchanged. +Column reflow transfers cells directly between adjacent rows when widening. +When narrowing, the row drops empty trailing cells before allocating space for +the cells that wrap. A short suffix at the end of a logical line can reserve +room for its new row up front. As narrowing visits rows from oldest to newest, +the temporary buffer discards rows as soon as they exceed the scrollback limit. +Wide character spacers and the occupied range follow the same reflow rules. + +Scrollback starts with a batch of at most 16 initialized rows and increases +the batch as history fills, up to the existing 1,000-row growth ceiling. The +history-growth path also caps each batch at the remaining configured capacity. +Rows retain their existing ring order and remain immediately usable after a +rotation. Resize keeps using spare rows from the same ring. + Untrusted output cannot grow one cell's combining-character vector indefinitely: the engine retains at most 64 zero-width scalars per cell and ignores further marks until that cell is replaced or cleared. This limit applies before @@ -83,6 +107,23 @@ changing kitty support clear negotiated state. Input encoding remains in into rendered output. The GPUI adapter uses only available logical/shifted key metadata and never invents physical layout, keypad or modifier handedness. +## Searchable grid changes + +The grid records mutable cell access and operations that change their coordinates, +including buffer switches, scrollback eviction and reflow. The emulator consumes +this flag after parsing so cursor movement and protocol replies preserve active +search work. Review direct grid storage writes when updating the fork. +Top-origin upward scrolling also counts the rotation of retained history, +independently of viewport offset and history size. +`Row::occupied_end` exposes the existing dirty bound. For terminal cells the +untouched suffix has blank text and no line metadata, regardless of background. +Readers that preserve soft-wrap spacing still use the physical row width. +Clipboard extraction uses the dirty bound when finding the last text cell +on an unwrapped row, so increasing terminal width only adds work for cells +that were actually modified. +The term separately versions actual palette overrides so the host can invalidate +paint after color changes without comparing every slot. + ## Verification and updates ```sh diff --git a/vendor/alacritty_terminal/src/grid/mod.rs b/vendor/alacritty_terminal/src/grid/mod.rs index 4e394d9d..fe8dfa4a 100644 --- a/vendor/alacritty_terminal/src/grid/mod.rs +++ b/vendor/alacritty_terminal/src/grid/mod.rs @@ -1,3 +1,4 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. //! A specialized 2D grid implementation optimized for use in a terminal. use std::cmp::{max, min}; @@ -135,6 +136,14 @@ pub struct Grid { /// Maximum number of lines in history. max_scroll_limit: usize, + + /// Cells or their grid coordinates may have changed since the last observation. + #[cfg_attr(feature = "serde", serde(skip))] + content_changed: bool, + + /// Total upward rotation of the history in this buffer. + #[cfg_attr(feature = "serde", serde(skip))] + history_scroll: u64, } impl Grid { @@ -147,6 +156,8 @@ impl Grid { cursor: Cursor::default(), lines, columns, + content_changed: false, + history_scroll: 0, } } @@ -154,6 +165,7 @@ impl Grid { pub fn update_history(&mut self, history_size: usize) { let current_history_size = self.history_size(); if current_history_size > history_size { + self.mark_content_changed(); self.raw.shrink_lines(current_history_size - history_size); } self.display_offset = min(self.display_offset, history_size); @@ -173,9 +185,10 @@ impl Grid { } fn increase_scroll_limit(&mut self, count: usize) { - let count = min(count, self.max_scroll_limit - self.history_size()); + let remaining = self.max_scroll_limit - self.history_size(); + let count = min(count, remaining); if count != 0 { - self.raw.initialize(count, self.columns); + self.raw.initialize(count, self.columns, remaining); } } @@ -193,6 +206,7 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + self.mark_content_changed(); // When rotating the entire region, just reset everything. if region.end - region.start <= positions { for i in (region.start.0..region.end.0).map(Line::from) { @@ -254,6 +268,7 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + self.mark_content_changed(); // When rotating the entire region with fixed lines at the top, just reset everything. if region.end - region.start <= positions && region.start != 0 { for i in (region.start.0..region.end.0).map(Line::from) { @@ -270,6 +285,8 @@ impl Grid { // Only rotate the entire history if the active region starts at the top. if region.start == 0 { + self.history_scroll = self.history_scroll.wrapping_add(positions as u64); + // Create scrollback for the new lines. self.increase_scroll_limit(positions); @@ -338,6 +355,7 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + self.mark_content_changed(); self.clear_history(); self.saved_cursor = Cursor::default(); @@ -353,6 +371,21 @@ impl Grid { } impl Grid { + #[inline] + pub(crate) fn mark_content_changed(&mut self) { + self.content_changed = true; + } + + pub(crate) fn take_content_changed(&mut self) -> bool { + std::mem::take(&mut self.content_changed) + } + + /// Upward translation of retained history since this buffer was created. + /// Callers must separately account for reflow and retain only in-bounds rows. + pub fn history_scroll(&self) -> u64 { + self.history_scroll + } + /// Reset a visible region within the grid. pub fn reset_region>(&mut self, bounds: R) where @@ -374,6 +407,7 @@ impl Grid { debug_assert!(start < self.screen_lines() as i32); debug_assert!(end <= self.screen_lines() as i32); + self.mark_content_changed(); for line in (start.0..end.0).map(Line::from) { self.raw[line].reset(&self.cursor.template); } @@ -382,7 +416,11 @@ impl Grid { #[inline] pub fn clear_history(&mut self) { // Explicitly purge all lines from history. - self.raw.shrink_lines(self.history_size()); + let history_size = self.history_size(); + if history_size != 0 { + self.mark_content_changed(); + } + self.raw.shrink_lines(history_size); // Reset display offset. self.display_offset = 0; @@ -398,7 +436,8 @@ impl Grid { self.truncate(); // Initialize everything with empty new lines. - self.raw.initialize(self.max_scroll_limit - self.history_size(), self.columns); + let remaining = self.max_scroll_limit - self.history_size(); + self.raw.initialize(remaining, self.columns, remaining); } /// This is used only for truncating before saving ref-tests. @@ -462,6 +501,7 @@ impl Index for Grid { impl IndexMut for Grid { #[inline] fn index_mut(&mut self, index: Line) -> &mut Row { + self.mark_content_changed(); &mut self.raw[index] } } diff --git a/vendor/alacritty_terminal/src/grid/resize.rs b/vendor/alacritty_terminal/src/grid/resize.rs index 37f93691..b48592c1 100644 --- a/vendor/alacritty_terminal/src/grid/resize.rs +++ b/vendor/alacritty_terminal/src/grid/resize.rs @@ -1,6 +1,8 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. //! Grid resize and reflow. use std::cmp::{Ordering, max, min}; +use std::collections::VecDeque; use std::mem; use crate::index::{Boundary, Column, Line}; @@ -16,6 +18,10 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + if lines != self.lines || columns != self.columns { + self.mark_content_changed(); + } + // Use empty template cell for resetting cells due to resize. let template = mem::take(&mut self.cursor.template); @@ -147,22 +153,15 @@ impl Grid { let len = min(row.len(), num_wrapped); // Insert leading spacer when there's not enough room for reflowing wide char. - let mut cells = if row[Column(len - 1)].flags().contains(Flags::WIDE_CHAR) { + if row[Column(len - 1)].flags().contains(Flags::WIDE_CHAR) { num_wrapped -= 1; - - let mut cells = row.front_split_off(len - 1); - + last_row.append_prefix_from(&mut row, len - 1); let mut spacer = T::default(); spacer.flags_mut().insert(Flags::LEADING_WIDE_CHAR_SPACER); - cells.push(spacer); - - cells + last_row.push(spacer); } else { - row.front_split_off(len) - }; - - // Add removed cells to previous row and reflow content. - last_row.append(&mut cells); + last_row.append_prefix_from(&mut row, len); + } let cursor_buffer_line = self.lines - self.cursor.point.line.0 as usize - 1; @@ -251,7 +250,18 @@ impl Grid { self.cursor.point.column += 1; } - let mut new_raw = Vec::with_capacity(self.raw.len()); + // Reflow visits rows from oldest to newest. Retain only the rows + // that can survive in the grid under the scrollback limit. + let limit = self.max_scroll_limit + self.lines; + let mut new_raw = VecDeque::with_capacity(self.raw.len().min(limit)); + let push_row = |rows: &mut VecDeque<_>, row| { + if rows.len() == limit { + rows.pop_front(); + } else if rows.len() == rows.capacity() { + rows.reserve_exact(rows.capacity().min(limit - rows.len()).max(1)); + } + rows.push_back(row); + }; let mut buffered: Option> = None; let mut rows = self.raw.take_all(); @@ -270,7 +280,12 @@ impl Grid { loop { // Remove all cells which require reflowing. - let mut wrapped = match row.shrink(columns) { + let overflow = if reflow { + row.shrink_for_reflow(columns) + } else { + row.shrink(columns) + }; + let mut wrapped = match overflow { Some(wrapped) if reflow => wrapped, _ => { let cursor_buffer_line = self.lines - self.cursor.point.line.0 as usize - 1; @@ -280,7 +295,7 @@ impl Grid { Vec::new() } else { // Since it fits, just push the existing line without any reflow. - new_raw.push(row); + push_row(&mut new_raw, row); break; } }, @@ -302,7 +317,7 @@ impl Grid { if len > 0 && wrapped[len - 1].flags().contains(Flags::LEADING_WIDE_CHAR_SPACER) { if len == 1 { row[Column(columns - 1)].flags_mut().insert(Flags::WRAPLINE); - new_raw.push(row); + push_row(&mut new_raw, row); break; } else { // Remove the leading spacer from the end of the wrapped row. @@ -311,10 +326,10 @@ impl Grid { } } - new_raw.push(row); + push_row(&mut new_raw, row); // Set line as wrapped if cells got removed. - if let Some(cell) = new_raw.last_mut().and_then(|r| r.last_mut()) { + if let Some(cell) = new_raw.back_mut().and_then(|r| r.last_mut()) { cell.flags_mut().insert(Flags::WRAPLINE); } @@ -363,10 +378,9 @@ impl Grid { } } - // Reverse iterator and use it as the new grid storage. - let mut reversed: Vec> = new_raw.drain(..).rev().collect(); - reversed.truncate(self.max_scroll_limit + self.lines); - self.raw.replace_inner(reversed); + let mut rows = Vec::from(new_raw); + rows.reverse(); + self.raw.replace_inner(rows); // Clamp display offset in case some lines went off. self.display_offset = min(self.display_offset, self.history_size()); diff --git a/vendor/alacritty_terminal/src/grid/row.rs b/vendor/alacritty_terminal/src/grid/row.rs index 040f724d..1e8cab7d 100644 --- a/vendor/alacritty_terminal/src/grid/row.rs +++ b/vendor/alacritty_terminal/src/grid/row.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use crate::grid::GridCell; use crate::index::Column; -use crate::term::cell::ResetDiscriminant; +use crate::term::cell::{Flags, ResetDiscriminant}; /// A row in the grid. #[derive(Default, Clone, Debug)] @@ -69,6 +69,20 @@ impl Row { /// /// This will return all non-empty cells that were removed. pub fn shrink(&mut self, columns: usize) -> Option> + where + T: GridCell, + { + self.shrink_to_columns(columns, false) + } + + pub(crate) fn shrink_for_reflow(&mut self, columns: usize) -> Option> + where + T: GridCell, + { + self.shrink_to_columns(columns, true) + } + + fn shrink_to_columns(&mut self, columns: usize, reflow: bool) -> Option> where T: GridCell, { @@ -76,14 +90,28 @@ impl Row { return None; } - // Split off cells for a new row. - let mut new_row = self.inner.split_off(columns); - let index = new_row.iter().rposition(|c| !c.is_empty()).map_or(0, |i| i + 1); - new_row.truncate(index); - + // Drop the empty tail in place before allocating space for wrapped cells. + let end = self.inner[columns..] + .iter() + .rposition(|cell| !cell.is_empty()) + .map_or(columns, |index| columns + index + 1); + self.inner.truncate(end); self.occ = min(self.occ, columns); - if new_row.is_empty() { None } else { Some(new_row) } + if end == columns { + return None; + } + + let overflow = end - columns; + // A short suffix ending a logical line usually becomes a new row. + // Give it space for its remaining blank cells before moving the suffix. + if reflow && overflow < columns && !self.inner[end - 1].flags().contains(Flags::WRAPLINE) { + let mut suffix = Vec::with_capacity(columns); + suffix.extend(self.inner.drain(columns..)); + Some(suffix) + } else { + Some(self.inner.split_off(columns)) + } } /// Reset all cells in the row to the `template` cell. @@ -122,6 +150,12 @@ impl Row { self.inner.len() } + /// Exclusive upper bound of the cells modified since initialization or reset. + #[inline] + pub fn occupied_end(&self) -> usize { + self.occ + } + #[inline] pub fn last(&self) -> Option<&T> { self.inner.last() @@ -138,7 +172,9 @@ impl Row { where T: GridCell, { - self.occ += vec.len(); + if !vec.is_empty() { + self.occ = self.inner.len() + vec.len(); + } self.inner.append(vec); } @@ -167,6 +203,21 @@ impl Row { std::mem::swap(&mut split, &mut self.inner); split } + + /// Move the prefix of a wrapped row directly into this row. + #[inline] + pub(super) fn append_prefix_from(&mut self, from: &mut Self, count: usize) { + debug_assert_eq!(self.occ, self.inner.len()); + self.inner.extend(from.inner.drain(..count)); + self.occ += count; + from.occ = from.occ.saturating_sub(count); + } + + #[inline] + pub(super) fn push(&mut self, cell: T) { + self.inner.push(cell); + self.occ = self.inner.len(); + } } impl<'a, T> IntoIterator for &'a Row { diff --git a/vendor/alacritty_terminal/src/grid/storage.rs b/vendor/alacritty_terminal/src/grid/storage.rs index 6d7984d4..3ba9098d 100644 --- a/vendor/alacritty_terminal/src/grid/storage.rs +++ b/vendor/alacritty_terminal/src/grid/storage.rs @@ -1,4 +1,4 @@ -use std::cmp::max; +use std::cmp::{max, min}; use std::mem; use std::mem::MaybeUninit; use std::ops::{Index, IndexMut}; @@ -9,6 +9,8 @@ use serde::{Deserialize, Serialize}; use super::Row; use crate::index::Line; +/// First batch of spare rows for a light terminal or viewport resize. +const INITIAL_ROW_BATCH: usize = 16; /// Maximum number of buffered lines outside of the grid for performance optimization. const MAX_CACHE_SIZE: usize = 1_000; @@ -47,8 +49,8 @@ pub struct Storage { /// /// Shrinking this length allows reducing the number of lines in the scrollback buffer without /// having to truncate the raw `inner` buffer. - /// As long as `len` is bigger than `inner`, it is also possible to grow the scrollback buffer - /// without any additional insertions. + /// While `len` is smaller than `inner.len()`, the scrollback buffer can grow + /// into existing rows without allocating more cells. len: usize, } @@ -85,7 +87,7 @@ impl Storage { let additional_lines = next - self.visible_lines; let columns = self[Line(0)].len(); - self.initialize(additional_lines, columns); + self.initialize(additional_lines, columns, usize::MAX); // Update visible lines. self.visible_lines = next; @@ -121,16 +123,24 @@ impl Storage { self.inner.truncate(self.len); } - /// Dynamically grow the storage buffer at runtime. + /// Grows the ring, limiting speculative rows to the caller's growth budget. #[inline] - pub fn initialize(&mut self, additional_rows: usize, columns: usize) + pub fn initialize(&mut self, additional_rows: usize, columns: usize, max_rows_to_add: usize) where T: Default, { if self.len + additional_rows > self.inner.len() { self.rezero(); - let realloc_size = self.inner.len() + max(additional_rows, MAX_CACHE_SIZE); + // Start small so a few output lines do not reserve thousands of cells. + // Once history reaches a full cache batch, keep the existing dense growth. + let history = self.len - self.visible_lines; + let batch = if history < MAX_CACHE_SIZE { + (history * 4).clamp(INITIAL_ROW_BATCH, MAX_CACHE_SIZE) - history + } else { + MAX_CACHE_SIZE + }; + let realloc_size = self.len + max(additional_rows, min(batch, max_rows_to_add)); self.inner.resize_with(realloc_size, || Row::new(columns)); } @@ -267,7 +277,7 @@ impl IndexMut for Storage { mod tests { use crate::grid::GridCell; use crate::grid::row::Row; - use crate::grid::storage::{MAX_CACHE_SIZE, Storage}; + use crate::grid::storage::{INITIAL_ROW_BATCH, Storage}; use crate::index::{Column, Line}; use crate::term::cell::Flags; @@ -345,7 +355,7 @@ mod tests { /// 2: - /// 3: \0 /// ... - /// MAX_CACHE_SIZE: \0 + /// INITIAL_ROW_BATCH: \0 #[test] fn grow_after_zero() { // Setup storage area. @@ -366,7 +376,7 @@ mod tests { visible_lines: 4, len: 4, }; - expected.inner.append(&mut vec![filled_row('\0'); MAX_CACHE_SIZE]); + expected.inner.append(&mut vec![filled_row('\0'); INITIAL_ROW_BATCH]); assert_eq!(storage.visible_lines, expected.visible_lines); assert_eq!(storage.inner, expected.inner); @@ -386,7 +396,7 @@ mod tests { /// 2: - /// 3: \0 /// ... - /// MAX_CACHE_SIZE: \0 + /// INITIAL_ROW_BATCH: \0 #[test] fn grow_before_zero() { // Setup storage area. @@ -407,7 +417,7 @@ mod tests { visible_lines: 4, len: 4, }; - expected.inner.append(&mut vec![filled_row('\0'); MAX_CACHE_SIZE]); + expected.inner.append(&mut vec![filled_row('\0'); INITIAL_ROW_BATCH]); assert_eq!(storage.visible_lines, expected.visible_lines); assert_eq!(storage.inner, expected.inner); @@ -686,7 +696,7 @@ mod tests { assert_eq!(storage.len, shrinking_expected.len); // Grow buffer. - storage.initialize(1, 1); + storage.initialize(1, 1, usize::MAX); // Make sure the previously freed elements are reused. let growing_expected = Storage { @@ -727,7 +737,7 @@ mod tests { // Initialize additional lines. let init_size = 3; - storage.initialize(init_size, 1); + storage.initialize(init_size, 1, usize::MAX); // Generate expected grid. let mut expected_inner = vec![ @@ -738,7 +748,7 @@ mod tests { filled_row('4'), filled_row('5'), ]; - let expected_init_size = std::cmp::max(init_size, MAX_CACHE_SIZE); + let expected_init_size = 18; expected_inner.append(&mut vec![filled_row('\0'); expected_init_size]); let expected_storage = Storage { inner: expected_inner, zero: 0, visible_lines: 0, len: 9 }; @@ -747,6 +757,15 @@ mod tests { assert_eq!(storage.inner, expected_storage.inner); } + #[test] + fn a_small_history_allocates_only_rows_the_grid_can_use() { + let mut storage = Storage::::with_capacity(48, 260); + storage.initialize(1, 260, 3); + assert_eq!(storage.len(), 49); + assert_eq!(storage.inner.len(), 51); + assert_eq!(storage[Line(-1)].len(), 260); + } + #[test] fn rotate_wrap_zero() { let mut storage: Storage = Storage { diff --git a/vendor/alacritty_terminal/src/term/cell.rs b/vendor/alacritty_terminal/src/term/cell.rs index 451778df..a20387cf 100644 --- a/vendor/alacritty_terminal/src/term/cell.rs +++ b/vendor/alacritty_terminal/src/term/cell.rs @@ -302,22 +302,22 @@ pub trait LineLength { impl LineLength for grid::Row { fn line_length(&self) -> Column { - let mut length = Column(0); - - if self[Column(self.len() - 1)].flags.contains(Flags::WRAPLINE) { + let has_text = |cell: &Cell| { + cell.c != ' ' + || cell.extra.as_ref().is_some_and(|extra| !extra.zerowidth.is_empty()) + }; + let last = &self[Column(self.len() - 1)]; + if last.flags.contains(Flags::WRAPLINE) || has_text(last) { return Column(self.len()); } - for (index, cell) in self[..].iter().rev().enumerate() { - if cell.c != ' ' - || cell.extra.as_ref().map(|extra| extra.zerowidth.is_empty()) == Some(false) - { - length = Column(self.len() - index); - break; - } - } - - length + // Only the occupied prefix may contain text added since reset. + Column( + self[..Column(self.occupied_end())] + .iter() + .rposition(has_text) + .map_or(0, |index| index + 1), + ) } } @@ -365,6 +365,16 @@ mod tests { assert_eq!(row.line_length(), Column(6)); } + #[test] + fn line_length_keeps_combining_marks_and_ignores_background_after_growth() { + let mut row = Row::::new(10); + row[Column(3)].push_zerowidth('\u{301}'); + row[Column(4)].bg = Color::Named(NamedColor::Red); + row.grow(500); + + assert_eq!(row.line_length(), Column(4)); + } + #[test] fn line_length_works_with_wrapline() { let mut row = Row::::new(10); diff --git a/vendor/alacritty_terminal/src/term/mod.rs b/vendor/alacritty_terminal/src/term/mod.rs index 2e94c5d8..dc4712e2 100644 --- a/vendor/alacritty_terminal/src/term/mod.rs +++ b/vendor/alacritty_terminal/src/term/mod.rs @@ -16,8 +16,8 @@ use unicode_width::UnicodeWidthChar; use crate::event::{Event, EventListener}; use crate::grid::{Dimensions, Grid, GridIterator, Scroll}; use crate::index::{self, Boundary, Column, Direction, Line, Point, Side}; -use crate::selection::{Selection, SelectionRange, SelectionType}; -use crate::term::cell::{Cell, CellExtra, Flags, LineLength, LogicalLine}; +use crate::selection::{Selection, SelectionRange}; +use crate::term::cell::{Cell, CellExtra, Flags, LogicalLine}; use crate::term::color::Colors; use crate::vi_mode::{ViModeCursor, ViMotion}; use crate::vte::ansi::{ @@ -31,6 +31,7 @@ pub mod color; mod keyboard; use keyboard::KeyboardProtocol; pub mod search; +mod selection_text; /// Minimum number of columns. /// @@ -309,6 +310,7 @@ pub struct Term { /// Modified terminal colors. colors: Colors, + palette_revision: u64, /// Current style of the cursor. cursor_style: Option, @@ -449,7 +451,11 @@ impl Term { } fn current_logical_line(&self) -> Option { - self.grid[self.grid.cursor.point.line][..].iter().find_map(|cell| cell.logical_line()) + let row = &self.grid[self.grid.cursor.point.line]; + if row.occ == 0 { + return None; + } + row[..].iter().find_map(|cell| cell.logical_line()) } fn ensure_logical_line(&mut self) -> Option { @@ -502,6 +508,7 @@ impl Term { vi_mode_cursor: Default::default(), cursor_style: Default::default(), colors: color::Colors::default(), + palette_revision: 0, title_stack: Default::default(), is_focused: Default::default(), selection: Default::default(), @@ -595,109 +602,22 @@ impl Term { /// Convert the active selection to a String. pub fn selection_to_string(&self) -> Option { - let selection_range = self.selection.as_ref().and_then(|s| s.to_range(self))?; - let SelectionRange { start, end, .. } = selection_range; - - let mut res = String::new(); - - match self.selection.as_ref() { - Some(Selection { ty: SelectionType::Block, .. }) => { - for line in (start.line.0..end.line.0).map(Line::from) { - res += self - .line_to_string(line, start.column..end.column, start.column.0 != 0) - .trim_end(); - res += "\n"; - } + selection_text::selection_to_string(self) + } - res += self.line_to_string(end.line, start.column..end.column, true).trim_end(); - }, - Some(Selection { ty: SelectionType::Lines, .. }) => { - res = self.bounds_to_string(start, end) + "\n"; - }, - _ => { - res = self.bounds_to_string(start, end); - }, - } + /// Whether copying the active selection would produce any text. + pub fn selection_has_text(&self) -> bool { + selection_text::selection_has_text(self) + } - Some(res) + /// Copy at most the first `max_chars` Unicode scalars of the selection. + pub fn selection_text_prefix(&self, max_chars: usize) -> Option { + selection_text::selection_text_prefix(self, max_chars) } /// Convert range between two points to a String. pub fn bounds_to_string(&self, start: Point, end: Point) -> String { - let mut res = String::new(); - - for line in (start.line.0..=end.line.0).map(Line::from) { - let start_col = if line == start.line { start.column } else { Column(0) }; - let end_col = if line == end.line { end.column } else { self.last_column() }; - - res += &self.line_to_string(line, start_col..end_col, line == end.line); - } - - res.strip_suffix('\n').map(str::to_owned).unwrap_or(res) - } - - /// Convert a single line in the grid to a String. - fn line_to_string( - &self, - line: Line, - mut cols: Range, - include_wrapped_wide: bool, - ) -> String { - let mut text = String::new(); - - let grid_line = &self.grid[line]; - let line_length = cmp::min(grid_line.line_length(), cols.end + 1); - - // Include wide char when trailing spacer is selected. - if grid_line[cols.start].flags.contains(Flags::WIDE_CHAR_SPACER) { - cols.start -= 1; - } - - let mut tab_mode = false; - for column in (cols.start.0..line_length.0).map(Column::from) { - let cell = &grid_line[column]; - - // Skip over cells until next tab-stop once a tab was found. - if tab_mode { - if self.tabs[column] || cell.c != ' ' { - tab_mode = false; - } else { - continue; - } - } - - if cell.c == '\t' { - tab_mode = true; - } - - if !cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) { - // Push cells primary character. - text.push(cell.c); - - // Push zero-width characters. - for c in cell.zerowidth().into_iter().flatten() { - text.push(*c); - } - } - } - - if cols.end >= self.columns() - 1 - && (line_length.0 == 0 - || !self.grid[line][line_length - 1].flags.contains(Flags::WRAPLINE)) - { - text.push('\n'); - } - - // If wide char is not part of the selection, but leading spacer is, include it. - if line_length == self.columns() - && line_length.0 >= 2 - && grid_line[line_length - 1].flags.contains(Flags::LEADING_WIDE_CHAR_SPACER) - && include_wrapped_wide - { - text.push(self.grid[line - 1i32][Column(0)].c); - } - - text + selection_text::bounds_to_string(self, start, end) } /// Terminal content required for rendering. @@ -714,6 +634,12 @@ impl Term { &self.grid } + /// Whether active cells or their grid coordinates may have changed since the last call. + /// Cursor movement, mode changes, and scrolling the view alone leave it clear. + pub fn take_grid_changed(&mut self) -> bool { + self.grid.take_content_changed() + } + /// Mutable access to the raw grid data structure. pub fn grid_mut(&mut self) -> &mut Grid { &mut self.grid @@ -796,6 +722,7 @@ impl Term { self.sync_keyboard_mode(); mem::swap(&mut self.grid, &mut self.inactive_grid); + self.grid.mark_content_changed(); self.mode ^= TermMode::ALT_SCREEN; self.selection = None; self.mark_fully_damaged(); @@ -1020,6 +947,12 @@ impl Term { &self.colors } + /// Version of the program's palette overrides. + #[inline] + pub fn palette_revision(&self) -> u64 { + self.palette_revision + } + /// Insert a linebreak at the current cursor position. #[inline] fn wrapline(&mut self) @@ -1698,12 +1631,13 @@ impl Handler for Term { fn set_color(&mut self, index: usize, color: Rgb) { trace!("Setting color[{index}] = {color:?}"); - // Damage terminal if the color changed and it's not the cursor. - if index != NamedColor::Cursor as usize && self.colors[index] != Some(color) { - self.mark_fully_damaged(); + if self.colors[index] != Some(color) { + self.palette_revision = self.palette_revision.wrapping_add(1); + if index != NamedColor::Cursor as usize { + self.mark_fully_damaged(); + } + self.colors[index] = Some(color); } - - self.colors[index] = Some(color); } /// Respond to a color query escape sequence. @@ -1728,12 +1662,13 @@ impl Handler for Term { fn reset_color(&mut self, index: usize) { trace!("Resetting color[{index}]"); - // Damage terminal if the color changed and it's not the cursor. - if index != NamedColor::Cursor as usize && self.colors[index].is_some() { - self.mark_fully_damaged(); + if self.colors[index].is_some() { + self.palette_revision = self.palette_revision.wrapping_add(1); + if index != NamedColor::Cursor as usize { + self.mark_fully_damaged(); + } + self.colors[index] = None; } - - self.colors[index] = None; } /// Store data into clipboard. diff --git a/vendor/alacritty_terminal/src/term/selection_text.rs b/vendor/alacritty_terminal/src/term/selection_text.rs new file mode 100644 index 00000000..9df3c33a --- /dev/null +++ b/vendor/alacritty_terminal/src/term/selection_text.rs @@ -0,0 +1,246 @@ +// Modified by Nocterm contributors; licensed under Apache-2.0. +use std::cmp; +use std::ops::{ControlFlow, Range}; + +use crate::grid::Dimensions; +use crate::index::{Column, Line, Point}; +use crate::selection::{SelectionRange, SelectionType}; +use crate::term::{ + Term, + cell::{Flags, LineLength}, +}; + +pub(super) fn selection_to_string(term: &Term) -> Option { + let selection = term.selection.as_ref()?; + let SelectionRange { start, end, .. } = selection.to_range(term)?; + match selection.ty { + SelectionType::Block => { + let mut text = String::new(); + for line in (start.line.0..end.line.0).map(Line::from) { + text += line_to_string(term, line, start.column..end.column, start.column.0 != 0) + .trim_end(); + text.push('\n'); + } + text += line_to_string(term, end.line, start.column..end.column, true).trim_end(); + Some(text) + } + SelectionType::Lines => { + let mut text = bounds_to_string(term, start, end); + text.push('\n'); + Some(text) + } + _ => Some(bounds_to_string(term, start, end)), + } +} + +pub(super) fn selection_has_text(term: &Term) -> bool { + let Some(selection) = term.selection.as_ref() else { + return false; + }; + let Some(SelectionRange { start, end, .. }) = selection.to_range(term) else { + return false; + }; + match selection.ty { + SelectionType::Lines => true, + SelectionType::Block if start.line != end.line => true, + SelectionType::Block => visit_line(term, end.line, start.column..end.column, true, |ch| { + if ch.is_whitespace() { + ControlFlow::Continue(()) + } else { + ControlFlow::Break(()) + } + }) + .is_break(), + _ => { + // The serializer strips one trailing newline. One newline alone + // is empty, while a second character makes the result nonempty. + let mut one_newline = false; + for (line, columns, last) in selection_rows(term, start, end) { + if visit_line(term, line, columns, last, |ch| { + if ch != '\n' || one_newline { + return ControlFlow::Break(()); + } + one_newline = true; + ControlFlow::Continue(()) + }) + .is_break() + { + return true; + } + } + false + } + } +} + +pub(super) fn selection_text_prefix(term: &Term, max_chars: usize) -> Option { + let selection = term.selection.as_ref()?; + let SelectionRange { start, end, .. } = selection.to_range(term)?; + let mut prefix = String::new(); + let mut remaining = max_chars; + if selection.ty == SelectionType::Block { + for line in (start.line.0..=end.line.0).map(Line::from) { + if remaining == 0 { + break; + } + let final_row = line == end.line; + let text = line_to_string( + term, + line, + start.column..end.column, + final_row || start.column.0 != 0, + ); + for ch in text.trim_end().chars().chain((!final_row).then_some('\n')) { + if remaining == 0 { + return Some(prefix); + } + prefix.push(ch); + remaining -= 1; + } + } + return Some(prefix); + } + + for (line, columns, last) in selection_rows(term, start, end) { + if visit_line(term, line, columns, last, |ch| { + if remaining == 0 { + return ControlFlow::Break(()); + } + prefix.push(ch); + remaining -= 1; + ControlFlow::Continue(()) + }) + .is_break() + { + return Some(prefix); + } + } + if prefix.ends_with('\n') { + prefix.pop(); + remaining += 1; + } + if selection.ty == SelectionType::Lines && remaining > 0 { + prefix.push('\n'); + } + Some(prefix) +} + +pub(super) fn bounds_to_string(term: &Term, start: Point, end: Point) -> String { + let mut text = String::new(); + for (line, columns, last) in selection_rows(term, start, end) { + let _ = visit_line(term, line, columns, last, |ch| { + text.push(ch); + ControlFlow::Continue(()) + }); + } + if text.ends_with('\n') { + text.pop(); + } + text +} + +fn selection_rows( + term: &Term, + start: Point, + end: Point, +) -> impl Iterator, bool)> { + let last_column = term.last_column(); + (start.line.0..=end.line.0).map(move |line| { + let line = Line(line); + let first_column = if line == start.line { + start.column + } else { + Column(0) + }; + let last = line == end.line; + let end_column = if last { end.column } else { last_column }; + (line, first_column..end_column, last) + }) +} + +fn line_to_string( + term: &Term, + line: Line, + columns: Range, + include_wrapped_wide: bool, +) -> String { + let mut text = String::new(); + let _ = visit_line(term, line, columns, include_wrapped_wide, |ch| { + text.push(ch); + ControlFlow::Continue(()) + }); + text +} + +/// Visit the same characters in both the copy and availability paths. +fn visit_line( + term: &Term, + line: Line, + mut cols: Range, + include_wrapped_wide: bool, + mut visit: impl FnMut(char) -> ControlFlow<()>, +) -> ControlFlow<()> { + let grid_line = &term.grid[line]; + let line_length = cmp::min(grid_line.line_length(), cols.end + 1); + + // Include wide char when trailing spacer is selected. + if grid_line[cols.start] + .flags + .contains(Flags::WIDE_CHAR_SPACER) + { + cols.start -= 1; + } + + let mut tab_mode = false; + for column in (cols.start.0..line_length.0).map(Column::from) { + let cell = &grid_line[column]; + + // Skip over cells until next tab-stop once a tab was found. + if tab_mode { + if term.tabs[column] || cell.c != ' ' { + tab_mode = false; + } else { + continue; + } + } + + if cell.c == '\t' { + tab_mode = true; + } + + if !cell + .flags + .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) + { + // Push cells primary character. + visit(cell.c)?; + + // Push zero-width characters. + for c in cell.zerowidth().into_iter().flatten() { + visit(*c)?; + } + } + } + + if cols.end >= term.columns() - 1 + && (line_length.0 == 0 + || !term.grid[line][line_length - 1] + .flags + .contains(Flags::WRAPLINE)) + { + visit('\n')?; + } + + // If wide char is not part of the selection, but leading spacer is, include it. + if line_length == term.columns() + && line_length.0 >= 2 + && grid_line[line_length - 1] + .flags + .contains(Flags::LEADING_WIDE_CHAR_SPACER) + && include_wrapped_wide + { + visit(term.grid[line - 1i32][Column(0)].c)?; + } + + ControlFlow::Continue(()) +} diff --git a/vendor/gpui-base/Cargo.lock b/vendor/gpui-base/Cargo.lock index 6a2e14e8..e2074d02 100644 --- a/vendor/gpui-base/Cargo.lock +++ b/vendor/gpui-base/Cargo.lock @@ -901,20 +901,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - [[package]] name = "ciborium" version = "0.2.2" @@ -1016,9 +1002,9 @@ dependencies = [ [[package]] name = "cocoa" -version = "0.26.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2" +checksum = "ad36507aeb7e16159dfe68db81ccc27571c3ccd4b76fb2fb72fc59e7a4b1b64c" dependencies = [ "bitflags 2.13.1", "block", @@ -2280,7 +2266,6 @@ dependencies = [ "anyhow", "ashpd", "async-channel", - "chrono", "criterion 0.5.1", "data-url", "futures", @@ -2293,6 +2278,7 @@ dependencies = [ "indoc", "instant", "itertools 0.13.0", + "jiff", "lsp-types", "markdown", "markup5ever_rcdom", @@ -2318,8 +2304,6 @@ dependencies = [ [[package]] name = "gpui-pre" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e87a42bb37c7cb4e76dd1ac0ce88851e46e976e0373a47ab3e0757abffee54d" dependencies = [ "accesskit", "anyhow", @@ -2328,7 +2312,6 @@ dependencies = [ "backtrace", "bindgen", "bitflags 2.13.1", - "chrono", "core-video", "criterion 0.8.2", "ctor", @@ -2353,6 +2336,7 @@ dependencies = [ "image", "inventory", "itertools 0.14.0", + "jiff", "log", "lyon", "num_cpus", @@ -2399,7 +2383,7 @@ dependencies = [ "anyhow", "block2 0.6.2", "cbindgen", - "cocoa 0.26.0", + "cocoa 0.26.1", "core-foundation 0.10.1", "core-video", "derive_more", @@ -2484,8 +2468,6 @@ dependencies = [ [[package]] name = "gpui-pre-linux" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aac7022e347409454777701082201742710052813964a1e25160f7e22c965ad" dependencies = [ "accesskit", "accesskit_unix", @@ -2539,7 +2521,7 @@ dependencies = [ "anyhow", "async-task", "block2 0.6.2", - "cocoa 0.26.0", + "cocoa 0.26.1", "core-foundation 0.10.1", "core-foundation-sys", "core-graphics 0.24.0", @@ -2695,14 +2677,12 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8049963b716df01b67b58f86000597f222d5b31b15b35069b23a3b07f3c68352" dependencies = [ "async-task", "backtrace", - "chrono", "flume", "futures", + "jiff", "parking_lot", "rand 0.9.5", "wasm_thread", @@ -2787,8 +2767,6 @@ dependencies = [ [[package]] name = "gpui-pre-wgpu" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0b02657b56b09140ce542f5e4434fb96d9fdaba0fd0035ba7dba13c171ddb9b" dependencies = [ "anyhow", "bytemuck", @@ -2815,8 +2793,6 @@ dependencies = [ [[package]] name = "gpui-pre-windows" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05592a6f9e3e6bb7a9f2a0d4779271cf747a948db1c07b02448de777ffff8f3" dependencies = [ "accesskit", "accesskit_windows", @@ -2844,12 +2820,10 @@ dependencies = [ [[package]] name = "gpui-pre-zlog" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7506302091e66d7fb5e04a5b3480e90cff0bbe3157458d7df91a41c59238c48" dependencies = [ "anyhow", - "chrono", "gpui-pre-collections", + "jiff", "log", ] @@ -3134,30 +3108,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core 0.62.2", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -3451,6 +3401,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "js-sys", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.22.4" @@ -3521,13 +3525,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -3627,9 +3630,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] @@ -5007,9 +5010,9 @@ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ "portable-atomic", ] @@ -7315,12 +7318,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "serde", "wasm-bindgen-macro", @@ -7329,19 +7331,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -7349,22 +7352,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.4", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -7495,9 +7498,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -7515,9 +7518,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] diff --git a/vendor/gpui-base/Cargo.toml b/vendor/gpui-base/Cargo.toml index 8fbfd5ef..6532e31c 100644 --- a/vendor/gpui-base/Cargo.toml +++ b/vendor/gpui-base/Cargo.toml @@ -68,8 +68,9 @@ version = "1.1.3" [dependencies.anyhow] version = "1" -[dependencies.chrono] -version = "0.4.38" +[dependencies.jiff] +version = "1.1" +features = ["js"] [dependencies.data-url] version = "0.3" @@ -244,3 +245,11 @@ useless_conversion = "allow" [lints.clippy.style] level = "allow" priority = -1 + +[patch.crates-io] +gpui-pre = { path = "../gpui-pre" } +gpui-pre-linux = { path = "../gpui-pre-linux" } +gpui-pre-scheduler = { path = "../gpui-pre-scheduler" } +gpui-pre-wgpu = { path = "../gpui-pre-wgpu" } +gpui-pre-windows = { path = "../gpui-pre-windows" } +gpui-pre-zlog = { path = "../gpui-pre-zlog" } diff --git a/vendor/gpui-base/NOCTERM.md b/vendor/gpui-base/NOCTERM.md index 5cbde24c..f55e8472 100644 --- a/vendor/gpui-base/NOCTERM.md +++ b/vendor/gpui-base/NOCTERM.md @@ -1,5 +1,8 @@ # Nocterm's GPUI Base zoom patch +Multiline inputs refresh their pointer and rectangular-selection affordances +when Alt changes. Other modifier transitions leave the rendered input current. + The input engine exposes its existing synchronous document revision through a read-only getter. Programmatic value replacement advances it even when Change events are suppressed. The existing counter wraps at u64::MAX; consumers that @@ -32,6 +35,32 @@ explicit overrides, removed/replaced groups and callback behavior. Nocterm's workspace tests also retain the real native header double-click regression. Remove this patch when upstream offers equivalent safe request reconciliation. +Text selection line boxes test vertical clipping before looking up glyph positions +and allocate space only for the boxes returned to the viewport. Source selection, +copying and hit testing still use their existing text layouts. + +Fit-content paragraphs rendered as a single text element carry their trailing +space on the same layout node. The text bounds used for selection exclude the +paragraph gap. + +Large non-scrollable documents with text-only paragraphs, including inline +code spans, group their layout leaves into anonymous blocks of 32. This +bounds the temporary child arrays used by each Taffy block pass. The grouped root uses the content wrapper's +width when it is resolved. Paragraph indices, trailing spacing and paint +order still come from the original document. Short documents, virtualized +documents and documents with embedded inline elements use their original +layout path. + +Inline text leaves wholly clipped private hitboxes out of the frame's hit +test. Partially visible text keeps its hitbox, and only spans with links +register link-specific handlers. Clipped text remains part of the layout +and selection geometry. + +Inline flow wrapping and shaping use the sorted highlights intersecting +each line or fragment. Font-size segmentation is clipped in document byte +coordinates before constructing positioned text, keeping explicit line +breaks, style boundaries and source positions. + The published crate's `src/text/text_view.rs` unit test refers to the omitted repository root README. `tests/upstream/README.md` preserves that exact file from the same pinned commit; only the test include path changes. Existing assertions @@ -77,3 +106,50 @@ geometry, so ScrollableMask does not map wheel deltas through stale absolute content-height estimates. Horizontal routing and axis locks keep their existing behavior. Remove this patch when upstream provides equivalent relative wheel routing for variable-height lists. + +The text input paints single-row rectangular selections with GPUI's solid quad +primitive. Rectangles smaller than a device pixel keep their original path +coverage. Multi-row selection shapes retain the original outline, and token +gaps, masking, clipping and active-window styling use the same selection +ranges. Common text selection can therefore avoid creating the GPU renderer's +full-window path attachments. + +Scrollbars keep their visibility curves. Passive exits normally follow the +display callback. Two consecutive samples faster than 15 ms switch the +current exit to paced timer wakeups. At most one fade wake per scrollbar +is pending, with a shorter final interval when needed to reach the initial +deadline. Hover, wheel, track clicks and dragging keep their input path. +The scrollbar keeps interaction state and geometry together and separates +theme resolution, motion and GPUI painting. + +Dock last-panel guards stop checking visibility as soon as they encounter +a second visible panel. Hidden panels only affect how far the guard scans. + +When a tab group's membership changes, retained view entities keep their +observers. Each new view receives one observer, and departures detach as part +of reconciliation. The subscription table is sized to the current group. + +Tab-group reconciliation retains the panel observers when the ordered view +identities match. The group and its render snapshots share that immutable +list for as long as it describes their panels. Active-state delivery prunes +departed panel IDs after membership changes and move handoffs. + +Selecting a tab clamps the new index in its group while preserving the +existing edit result. Structural changes still normalize the tree. Panel +lookup stops at the last matching group in layout order, and existence +checks reuse that lookup without collecting panel IDs. + +Split resizing updates the existing size vector in place. The same +redistribution, size limits and notifications apply to pointer drags +and programmatic resizing. A zero-distance drag still synchronizes +the measured panel sizes. + +Committing split slot sizes updates the target split using the existing +child-count check. The canonical tree shape is preserved by size-only edits. + +Button semantic refinements are stored only when supplied, rather than +embedding two empty large style values in each transient button. The first +builder moves its refinement into the owned slot; repeated builders merge +into that slot. The same selected-then-disabled precedence still applies +and unconfigured states add no heap allocation. Remove this patch when +upstream avoids embedding unused button state refinements. diff --git a/vendor/gpui-base/src/button.rs b/vendor/gpui-base/src/button.rs index 84a870c4..59cefc57 100644 --- a/vendor/gpui-base/src/button.rs +++ b/vendor/gpui-base/src/button.rs @@ -1,3 +1,4 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. use std::rc::Rc; use gpui::{ @@ -142,8 +143,14 @@ impl Button { crate::state_style::resolve_style( &self.style, [ - self.selected.then_some(&self.semantic_styles.selected), - self.disabled.then_some(&self.semantic_styles.disabled), + self.semantic_styles + .selected + .as_deref() + .filter(|_| self.selected), + self.semantic_styles + .disabled + .as_deref() + .filter(|_| self.disabled), ] .into_iter() .flatten(), @@ -164,24 +171,33 @@ impl Selectable for Button { /// Semantic styles supported by [`Button`]. #[derive(Default)] pub struct ButtonStyles { - selected: StyleRefinement, - disabled: StyleRefinement, + // Most buttons supply no semantic override for the current state. Store + // only supplied refinements instead of copying two large empty values + // through every element builder. + selected: Option>, + disabled: Option>, } impl ButtonStyles { /// Refines the root style when the button is selected. pub fn selected(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self { - self.selected - .refine(&build(StateStyle::default()).into_refinement()); + Self::refine(&mut self.selected, build(StateStyle::default())); self } /// Refines the root style when the button is disabled. pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self { - self.disabled - .refine(&build(StateStyle::default()).into_refinement()); + Self::refine(&mut self.disabled, build(StateStyle::default())); self } + + fn refine(slot: &mut Option>, style: StateStyle) { + let refinement = style.into_refinement(); + match slot { + Some(existing) => existing.refine(&refinement), + None => *slot = Some(Box::new(refinement)), + } + } } impl Styled for Button { @@ -495,6 +511,41 @@ mod tests { ); } + #[gpui::test] + fn repeated_semantic_styles_preserve_earlier_painted_properties(cx: &mut TestAppContext) { + struct Host; + impl Render for Host { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Button::new("semantic") + .size(px(40.)) + .selected(true) + .disabled(true) + .styles(|styles| styles.selected(|style| style.bg(gpui::rgb(0x123456)))) + .styles(|styles| { + styles.selected(|style| style.border_1().border_color(gpui::rgb(0x654321))) + }) + .styles(|styles| styles.disabled(|style| style.bg(gpui::rgb(0xabcdef)))) + } + } + + let (_, context) = cx.add_window_view(|_, _| Host); + context.update(|window, cx| { + window.draw(cx).clear(cx); + let quads = window.painted_quads(); + let background = quads + .iter() + .find(|quad| quad.background == gpui::rgb(0xabcdef).into()) + .expect("disabled background"); + assert!( + quads.iter().any(|quad| { + quad.bounds == background.bounds + && quad.border_color == gpui::rgb(0x654321).into() + }), + "earlier selected border must survive the later disabled background" + ); + }); + } + #[gpui::test] fn accessibility_role_label_and_disabled_action_surface(cx: &mut TestAppContext) { type Captured = Arc>>; diff --git a/vendor/gpui-base/src/calendar.rs b/vendor/gpui-base/src/calendar.rs index ea98c558..c9d5aa02 100644 --- a/vendor/gpui-base/src/calendar.rs +++ b/vendor/gpui-base/src/calendar.rs @@ -1,19 +1,23 @@ +// Modified by Nocterm: use Jiff civil dates and checked calendar arithmetic. use crate::TestSupportExt as _; use std::rc::Rc; use crate::{h_flex, styled::StyledExt as _, v_flex}; -use chrono::{Datelike, Local, NaiveDate, Weekday}; use gpui::{ AnyElement, App, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle, InteractiveElement, IntoElement, ParentElement, Render, RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div, px, }; +use jiff::{ + Span, ZonedDateTime, + civil::{Date as CivilDate, Weekday}, +}; /// A controlled calendar value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Date { - Single(Option), - Range(Option, Option), + Single(Option), + Range(Option, Option), } impl std::fmt::Display for Date { @@ -28,13 +32,13 @@ impl std::fmt::Display for Date { } } -impl From for Date { - fn from(value: NaiveDate) -> Self { +impl From for Date { + fn from(value: CivilDate) -> Self { Self::Single(Some(value)) } } -impl From<(NaiveDate, NaiveDate)> for Date { - fn from((start, end): (NaiveDate, NaiveDate)) -> Self { +impl From<(CivilDate, CivilDate)> for Date { + fn from((start, end): (CivilDate, CivilDate)) -> Self { Self::Range(Some(start), Some(end)) } } @@ -46,13 +50,13 @@ impl Date { pub fn is_complete(&self) -> bool { matches!(self, Self::Single(Some(_)) | Self::Range(Some(_), Some(_))) } - pub fn start(&self) -> Option { + pub fn start(&self) -> Option { match self { Self::Single(Some(v)) | Self::Range(Some(v), _) => Some(*v), _ => None, } } - pub fn end(&self) -> Option { + pub fn end(&self) -> Option { match self { Self::Range(_, Some(v)) => Some(*v), _ => None, @@ -60,14 +64,14 @@ impl Date { } pub fn format(&self, format: &str) -> Option { match self { - Self::Single(Some(v)) => Some(v.format(format).to_string().into()), + Self::Single(Some(v)) => Some(v.strftime(format).to_string().into()), Self::Range(Some(a), Some(b)) => { - Some(format!("{} - {}", a.format(format), b.format(format)).into()) + Some(format!("{} - {}", a.strftime(format), b.strftime(format)).into()) } _ => None, } } - pub fn is_active(&self, value: &NaiveDate) -> bool { + pub fn is_active(&self, value: &CivilDate) -> bool { match self { Self::Single(v) => *v == Some(*value), Self::Range(a, b) => *a == Some(*value) || *b == Some(*value), @@ -76,43 +80,43 @@ impl Date { pub fn is_single(&self) -> bool { matches!(self, Self::Single(_)) } - pub fn is_in_range(&self, value: &NaiveDate) -> bool { + pub fn is_in_range(&self, value: &CivilDate) -> bool { matches!(self, Self::Range(Some(a), Some(b)) if value >= a && value <= b) } } pub struct IntervalMatcher { - before: Option, - after: Option, + before: Option, + after: Option, } pub struct RangeMatcher { - from: Option, - to: Option, + from: Option, + to: Option, } pub enum Matcher { DayOfWeek(Vec), Interval(IntervalMatcher), Range(RangeMatcher), - Custom(Box bool + Send + Sync>), + Custom(Box bool + Send + Sync>), } impl From> for Matcher { fn from(v: Vec) -> Self { Self::DayOfWeek(v) } } -impl bool + Send + Sync + 'static> From for Matcher { +impl bool + Send + Sync + 'static> From for Matcher { fn from(v: F) -> Self { Self::Custom(Box::new(v)) } } impl Matcher { - pub fn interval(before: Option, after: Option) -> Self { + pub fn interval(before: Option, after: Option) -> Self { Self::Interval(IntervalMatcher { before, after }) } - pub fn range(from: Option, to: Option) -> Self { + pub fn range(from: Option, to: Option) -> Self { Self::Range(RangeMatcher { from, to }) } - pub fn custom bool + Send + Sync + 'static>(f: F) -> Self { + pub fn custom bool + Send + Sync + 'static>(f: F) -> Self { Self::Custom(Box::new(f)) } pub fn is_match(&self, date: &Date) -> bool { @@ -122,9 +126,11 @@ impl Matcher { _ => false, } } - pub fn matched(&self, date: &NaiveDate) -> bool { + pub fn matched(&self, date: &CivilDate) -> bool { match self { - Self::DayOfWeek(days) => days.contains(&date.weekday().num_days_from_sunday()), + Self::DayOfWeek(days) => { + days.contains(&(date.weekday().to_sunday_zero_offset() as u32)) + } Self::Interval(v) => { v.before.is_some_and(|x| date < &x) || v.after.is_some_and(|x| date > &x) } @@ -174,19 +180,19 @@ pub struct CalendarState { current_month: u8, years: Vec>, year_page: i32, - today: NaiveDate, + today: CivilDate, number_of_months: usize, disabled_matcher: Option>, } impl CalendarState { pub fn new(_: &mut Window, cx: &mut Context) -> Self { - let today = Local::now().date_naive(); + let today = ZonedDateTime::now().date(); Self { focus_handle: cx.focus_handle(), view: CalendarView::Day, date: Date::Single(None), - current_year: today.year(), + current_year: i32::from(today.year()), current_month: today.month() as u8, years: vec![], year_page: 0, @@ -194,7 +200,7 @@ impl CalendarState { number_of_months: 1, disabled_matcher: None, } - .year_range((today.year() - 50, today.year() + 50)) + .year_range((i32::from(today.year()) - 50, i32::from(today.year()) + 50)) } pub fn disabled_matcher(mut self, matcher: impl Into) -> Self { self.disabled_matcher = Some(Rc::new(matcher.into())); @@ -230,11 +236,11 @@ impl CalendarState { self.date = date; if let Some(v) = date.start() { self.current_month = v.month() as u8; - self.current_year = v.year(); + self.current_year = i32::from(v.year()); } true } - pub fn select_date(&mut self, value: NaiveDate) -> bool { + pub fn select_date(&mut self, value: CivilDate) -> bool { if self .disabled_matcher .as_ref() @@ -258,7 +264,7 @@ impl CalendarState { /// Activates a day item and emits [`CalendarEvent::Selected`] once the /// controlled value is complete. This is the single pointer/keyboard /// activation path used by the calendar root. - pub fn activate_date(&mut self, value: NaiveDate, cx: &mut Context) -> bool { + pub fn activate_date(&mut self, value: CivilDate, cx: &mut Context) -> bool { let complete = self.select_date(value); if complete { cx.emit(CalendarEvent::Selected(self.date())); @@ -285,7 +291,8 @@ impl CalendarState { cx.notify(); } fn apply_year_range(&mut self, range: (i32, i32)) { - self.years = (range.0..range.1) + self.years = (range.0.max(i32::from(CivilDate::MIN.year())) + ..range.1.min(i32::from(CivilDate::MAX.year()) + 1)) .collect::>() .chunks(20) .map(<[_]>::to_vec) @@ -303,18 +310,18 @@ impl CalendarState { n.rem_euclid(12) as u32 + 1, ) } - pub fn days(&self) -> Vec> { + pub fn days(&self) -> Vec> { self.month_days().into_iter().flatten().collect() } /// Calendar weeks grouped by visible month. This preserves six-week /// months and is the preferred rendering API. - pub fn month_days(&self) -> Vec>> { + pub fn month_days(&self) -> Vec>> { (0..self.number_of_months) .map(|n| { days_in_month( self.current_year, self.current_month as u32 + n as u32, - Weekday::Sun, + Weekday::Sunday, ) }) .collect() @@ -341,7 +348,16 @@ impl CalendarState { true } } + fn has_prev_month(&self) -> bool { + self.current_year > i32::from(CivilDate::MIN.year()) || self.current_month > 1 + } + fn has_next_month(&self) -> bool { + self.current_year < i32::from(CivilDate::MAX.year()) || self.current_month < 12 + } pub fn prev_month(&mut self) { + if !self.has_prev_month() { + return; + } if self.current_month == 1 { self.current_year -= 1; self.current_month = 12; @@ -350,6 +366,9 @@ impl CalendarState { } } pub fn next_month(&mut self) { + if !self.has_next_month() { + return; + } if self.current_month == 12 { self.current_year += 1; self.current_month = 1; @@ -369,7 +388,7 @@ impl CalendarState { pub fn current_month(&self) -> u8 { self.current_month } - pub fn today(&self) -> NaiveDate { + pub fn today(&self) -> CivilDate { self.today } pub fn years_on_page(&self) -> &[i32] { @@ -383,7 +402,10 @@ impl CalendarState { self.view = CalendarView::Day; } pub fn select_year(&mut self, year: i32) { - self.current_year = year; + self.current_year = year.clamp( + i32::from(CivilDate::MIN.year()), + i32::from(CivilDate::MAX.year()), + ); self.view = CalendarView::Day; } } @@ -574,7 +596,7 @@ impl Calendar { id: id.into(), state: state.clone(), number_of_months: 1, - first_day_of_week: Weekday::Sun, + first_day_of_week: Weekday::Sunday, style: StyleRefinement::default(), item: Rc::new(|item, _, _, _| item.into_any_element()), label: Rc::new(|kind, value| match kind { @@ -639,7 +661,9 @@ impl RenderOnce for Calendar { let view = self.state.read(cx).view(); let mut header = h_flex().items_center().justify_between().child({ let st = CalendarItemState::new(CalendarItemKind::Previous).disabled( - view.is_month() || (view.is_year() && !self.state.read(cx).has_prev_year_page()), + view.is_month() + || (view.is_year() && !self.state.read(cx).has_prev_year_page()) + || (view.is_day() && !self.state.read(cx).has_prev_month()), ); let mut item = CalendarItem::new("calendar-prev", st).with_label((self.label)(st.kind(), 0)); @@ -708,7 +732,9 @@ impl RenderOnce for Calendar { } header = header.child({ let st = CalendarItemState::new(CalendarItemKind::Next).disabled( - view.is_month() || (view.is_year() && !self.state.read(cx).has_next_year_page()), + view.is_month() + || (view.is_year() && !self.state.read(cx).has_next_year_page()) + || (view.is_day() && !self.state.read(cx).has_next_month()), ); let mut item = CalendarItem::new("calendar-next", st).with_label((self.label)(st.kind(), 0)); @@ -747,7 +773,7 @@ impl RenderOnce for Calendar { header_row = header_row.child(self.render_item( format!("weekday-{offset}-{weekday}"), st, - (weekday + self.first_day_of_week.num_days_from_sunday() as i32) % 7, + (weekday + self.first_day_of_week.to_sunday_zero_offset() as i32) % 7, window, cx, )); @@ -755,6 +781,9 @@ impl RenderOnce for Calendar { month = month.child(header_row); for (week_index, week) in weeks.iter().enumerate() { let mut week_row = h_flex(); + if week_index == 0 && week.len() < 7 { + week_row = week_row.justify_end(); + } for date in week { let date = *date; let st = { @@ -765,7 +794,7 @@ impl RenderOnce for Calendar { CalendarItemState::new(CalendarItemKind::Day) .active(s.date().is_active(&date)) .in_range(s.date().is_in_range(&date)) - .muted(date.month() != m || disabled) + .muted(u32::from(date.month() as u8) != m || disabled) .disabled(disabled) .today(date == s.today()) }; @@ -828,26 +857,36 @@ impl RenderOnce for Calendar { } } -fn days_in_month(year: i32, month: u32, first_day: Weekday) -> Vec> { - let total = year as i64 * 12 + month as i64 - 1; - let year = total.div_euclid(12) as i32; - let month = total.rem_euclid(12) as u32 + 1; - let first = NaiveDate::from_ymd_opt(year, month, 1).unwrap(); - let next = if month == 12 { - NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap() - } else { - NaiveDate::from_ymd_opt(year, month + 1, 1).unwrap() +fn days_in_month(year: i32, month: u32, first_day: Weekday) -> Vec> { + let total = i64::from(year) * 12 + i64::from(month) - 1; + let Ok(year) = i16::try_from(total.div_euclid(12)) else { + return Vec::new(); + }; + let month = total.rem_euclid(12) as i8 + 1; + let Ok(first) = CivilDate::new(year, month, 1) else { + return Vec::new(); }; - let offset = - (first.weekday().num_days_from_sunday() + 7 - first_day.num_days_from_sunday()) % 7; - let start = first - chrono::Duration::days(offset as i64); - let count = ((next - start).num_days() as usize).div_ceil(7) * 7; - (0..count) - .map(|n| start + chrono::Duration::days(n as i64)) - .collect::>() - .chunks(7) - .map(<[_]>::to_vec) - .collect() + let offset = i64::from( + (first.weekday().to_sunday_zero_offset() + 7 - first_day.to_sunday_zero_offset()) % 7, + ); + let count = ((i64::from(first.days_in_month()) + offset) as usize).div_ceil(7); + let start = first.checked_add(Span::new().days(-offset)); + let leading = if start.is_err() { offset as usize } else { 0 }; + let mut next = Some(start.unwrap_or(CivilDate::MIN)); + let mut weeks = Vec::with_capacity(count); + for index in 0..count { + let mut days = Vec::with_capacity(7); + let slots = if index == 0 { 7 - leading } else { 7 }; + for _ in 0..slots { + let Some(date) = next else { + break; + }; + days.push(date); + next = date.tomorrow().ok(); + } + weeks.push(days); + } + weeks } #[cfg(test)] @@ -886,9 +925,7 @@ mod tests { for mode in [CalendarView::Day, CalendarView::Month, CalendarView::Year] { cx.update(|window, cx| { view.read(cx).calendar.clone().update(cx, |state, cx| { - state.apply_date(Date::Single(Some( - NaiveDate::from_ymd_opt(2026, 9, 7).unwrap(), - ))); + state.apply_date(Date::Single(Some(CivilDate::new(2026, 9, 7).unwrap()))); state.set_view(mode); cx.notify(); }); @@ -943,8 +980,8 @@ mod tests { #[gpui::test] fn range_selection_restarts_and_completes(cx: &mut gpui::TestAppContext) { let s = state(cx, Date::Range(None, None)); - let a = NaiveDate::from_ymd_opt(2025, 2, 10).unwrap(); - let b = NaiveDate::from_ymd_opt(2025, 2, 12).unwrap(); + let a = CivilDate::new(2025, 2, 10).unwrap(); + let b = CivilDate::new(2025, 2, 12).unwrap(); s.update(cx, |s, _| { assert!(!s.select_date(a)); assert!(s.select_date(b)); @@ -961,24 +998,19 @@ mod tests { let s = state(cx, Date::Single(None)); s.update(cx, |s, _| { s.disabled_matcher = Some(Rc::new(Matcher::range( - Some(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()), - Some(NaiveDate::from_ymd_opt(2025, 1, 31).unwrap()), + Some(CivilDate::new(2025, 1, 1).unwrap()), + Some(CivilDate::new(2025, 1, 31).unwrap()), ))) }); s.update(cx, |s, _| { - assert!(!s.select_date(NaiveDate::from_ymd_opt(2025, 1, 2).unwrap())) + assert!(!s.select_date(CivilDate::new(2025, 1, 2).unwrap())) }); } #[gpui::test] fn month_navigation_crosses_year(cx: &mut gpui::TestAppContext) { - let s = state( - cx, - Date::Single(Some(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap())), - ); + let s = state(cx, Date::Single(Some(CivilDate::new(2025, 1, 1).unwrap()))); s.update(cx, |s, _| { - s.apply_date(Date::Single(Some( - NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(), - ))); + s.apply_date(Date::Single(Some(CivilDate::new(2025, 1, 1).unwrap()))); s.prev_month(); }); assert_eq!( @@ -992,16 +1024,32 @@ mod tests { ); } + #[gpui::test] + fn month_navigation_stays_within_supported_dates(cx: &mut gpui::TestAppContext) { + let s = state(cx, Date::Single(Some(CivilDate::MIN))); + s.update(cx, |s, _| { + s.apply_date(Date::Single(Some(CivilDate::MIN))); + s.prev_month(); + assert_eq!( + (s.current_year(), s.current_month()), + (i32::from(CivilDate::MIN.year()), 1) + ); + assert!(!s.has_prev_month()); + s.apply_date(Date::Single(Some(CivilDate::MAX))); + s.next_month(); + assert_eq!( + (s.current_year(), s.current_month()), + (i32::from(CivilDate::MAX.year()), 12) + ); + assert!(!s.has_next_month()); + }); + } + #[gpui::test] fn six_week_month_is_not_truncated(cx: &mut gpui::TestAppContext) { - let s = state( - cx, - Date::Single(Some(NaiveDate::from_ymd_opt(2025, 8, 1).unwrap())), - ); + let s = state(cx, Date::Single(Some(CivilDate::new(2025, 8, 1).unwrap()))); s.update(cx, |s, _| { - s.apply_date(Date::Single(Some( - NaiveDate::from_ymd_opt(2025, 8, 1).unwrap(), - ))); + s.apply_date(Date::Single(Some(CivilDate::new(2025, 8, 1).unwrap()))); assert_eq!(s.month_days().len(), 1); assert_eq!(s.month_days()[0].len(), 6); assert_eq!(s.days().len(), 6); @@ -1050,8 +1098,8 @@ mod tests { let (harness, _) = cx.add_window_view(EventHarness::new); let s = harness.read_with(cx, |h, _| h.calendar.clone()); s.update(cx, |s, _| s.date = Date::Range(None, None)); - let start = NaiveDate::from_ymd_opt(2025, 4, 4).unwrap(); - let end = NaiveDate::from_ymd_opt(2025, 4, 8).unwrap(); + let start = CivilDate::new(2025, 4, 4).unwrap(); + let end = CivilDate::new(2025, 4, 8).unwrap(); s.update(cx, |s, cx| { assert!(!s.activate_date(start, cx)); assert!(s.activate_date(end, cx)); @@ -1076,3 +1124,7 @@ mod tests { ); } } + +#[cfg(test)] +#[path = "calendar_grid_tests.rs"] +mod calendar_grid_tests; diff --git a/vendor/gpui-base/src/calendar_grid_tests.rs b/vendor/gpui-base/src/calendar_grid_tests.rs new file mode 100644 index 00000000..f0fa3741 --- /dev/null +++ b/vendor/gpui-base/src/calendar_grid_tests.rs @@ -0,0 +1,113 @@ +// Modified by Nocterm: exercise the active calendar grid instead of the unused component helper. +use jiff::civil::{Date as CivilDate, Weekday}; + +use super::days_in_month; + +#[test] +fn test_days_in_month() { + assert_eq!(CivilDate::new(2024, 2, 1).unwrap().days_in_month(), 29); + assert_eq!(CivilDate::new(2023, 2, 1).unwrap().days_in_month(), 28); + assert_eq!(CivilDate::new(2023, 1, 1).unwrap().days_in_month(), 31); + assert_eq!(CivilDate::new(2023, 4, 1).unwrap().days_in_month(), 30); +} + +#[test] +fn test_days() { + #[track_caller] + fn assert_case(date: CivilDate, first_day: Weekday, expected: Vec<&str>) { + let out = days_in_month(i32::from(date.year()), date.month() as u32, first_day) + .iter() + .map(|week| { + week.iter() + .map(|d| { + if d.year() == date.year() && d.month() == date.month() { + format!("{:2}", d.day()) + } else if d.year() == date.year() { + format!("{}-{}", d.month(), d.day()) + } else { + format!("{}-{}-{}", d.year(), d.month(), d.day()) + } + }) + .collect::>() + .join("|") + }) + .collect::>(); + + assert_eq!(out, expected); + } + + assert_case( + CivilDate::new(2024, 8, 1).unwrap(), + Weekday::Sunday, + vec![ + "7-28|7-29|7-30|7-31| 1| 2| 3", + " 4| 5| 6| 7| 8| 9|10", + "11|12|13|14|15|16|17", + "18|19|20|21|22|23|24", + "25|26|27|28|29|30|31", + ], + ); + assert_case( + CivilDate::new(2025, 1, 1).unwrap(), + Weekday::Sunday, + vec![ + "2024-12-29|2024-12-30|2024-12-31| 1| 2| 3| 4", + " 5| 6| 7| 8| 9|10|11", + "12|13|14|15|16|17|18", + "19|20|21|22|23|24|25", + "26|27|28|29|30|31|2-1", + ], + ); + + assert_case( + CivilDate::new(2024, 2, 1).unwrap(), + Weekday::Sunday, + vec![ + "1-28|1-29|1-30|1-31| 1| 2| 3", + " 4| 5| 6| 7| 8| 9|10", + "11|12|13|14|15|16|17", + "18|19|20|21|22|23|24", + "25|26|27|28|29|3-1|3-2", + ], + ); + assert_case( + CivilDate::new(2023, 2, 20).unwrap(), + Weekday::Sunday, + vec![ + "1-29|1-30|1-31| 1| 2| 3| 4", + " 5| 6| 7| 8| 9|10|11", + "12|13|14|15|16|17|18", + "19|20|21|22|23|24|25", + "26|27|28|3-1|3-2|3-3|3-4", + ], + ); + + // Monday-first week: Feb 2023 starts on a Wednesday, so the grid + // shifts to start on Monday (column 0 = Mon 30 Jan). + assert_case( + CivilDate::new(2023, 2, 1).unwrap(), + Weekday::Monday, + vec![ + "1-30|1-31| 1| 2| 3| 4| 5", + " 6| 7| 8| 9|10|11|12", + "13|14|15|16|17|18|19", + "20|21|22|23|24|25|26", + "27|28|3-1|3-2|3-3|3-4|3-5", + ], + ); +} + +#[test] +fn boundary_months_keep_all_representable_days_without_wrapping() { + for (date, month) in [(CivilDate::MIN, 1), (CivilDate::MAX, 12)] { + let grid = days_in_month(i32::from(date.year()), month, Weekday::Monday); + let days = grid.into_iter().flatten().collect::>(); + assert!(days.contains(&date)); + assert_eq!( + days.iter().filter(|d| d.month() as u32 == month).count(), + 31 + ); + assert!(days.windows(2).all(|w| w[0].tomorrow().ok() == Some(w[1]))); + } + assert!(days_in_month(10000, 1, Weekday::Monday).is_empty()); +} diff --git a/vendor/gpui-base/src/dock/active.rs b/vendor/gpui-base/src/dock/active.rs index 20cae4f0..18e0c148 100644 --- a/vendor/gpui-base/src/dock/active.rs +++ b/vendor/gpui-base/src/dock/active.rs @@ -1,4 +1,6 @@ -use std::collections::HashMap; +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use std::collections::{HashMap, HashSet}; use super::layout::PanelId; @@ -20,6 +22,7 @@ use super::layout::PanelId; pub(crate) struct ActiveTracker { notified: HashMap, sync_scheduled: bool, + prune_pending: bool, } impl ActiveTracker { @@ -48,7 +51,10 @@ impl ActiveTracker { displayed: Option, ) -> Vec<(PanelId, bool)> { // A panel that left the group is forgotten, not deactivated. - self.notified.retain(|panel, _| panels.contains(panel)); + if std::mem::take(&mut self.prune_pending) && !self.notified.is_empty() { + let members: HashSet<_> = panels.iter().copied().collect(); + self.notified.retain(|panel, _| members.contains(panel)); + } let mut deactivations = Vec::new(); let mut activation = None; @@ -81,11 +87,18 @@ impl ActiveTracker { deactivations } + /// Reconcile departures against the final membership when the scheduled + /// delivery runs. Display changes within that membership need no prune. + pub(crate) fn membership_changed(&mut self) { + self.prune_pending = true; + } + /// Record what a panel was last told, without emitting anything. Used /// when a panel moves between groups while displayed, so the move does /// not look like an edge to the destination group. pub(crate) fn seed(&mut self, panel: PanelId, active: bool) { self.notified.insert(panel, active); + self.membership_changed(); } /// What this tracker last told `panel`, if anything. A pure read: it does @@ -161,6 +174,7 @@ mod tests { let mut tracker = ActiveTracker::default(); tracker.reconcile(&[panel(1), panel(2)], Some(panel(1))); + tracker.membership_changed(); let changes = tracker.reconcile(&[panel(2)], Some(panel(2))); assert_eq!( diff --git a/vendor/gpui-base/src/dock/layout/edit.rs b/vendor/gpui-base/src/dock/layout/edit.rs index 2f6d4af9..a10ce104 100644 --- a/vendor/gpui-base/src/dock/layout/edit.rs +++ b/vendor/gpui-base/src/dock/layout/edit.rs @@ -1,3 +1,5 @@ +// Nocterm: keep selection and size edits local to their target node. + use std::collections::HashMap; use gpui::Pixels; @@ -79,45 +81,36 @@ impl PaneTree { } pub fn set_active(&mut self, node: NodeId, ix: usize) -> EditResult { - self.edit(|tree| { - let Some(path) = tree.path_of_node(node) else { - return false; - }; - let NodeKind::Tabs { active_ix, .. } = tree.node_at_mut(&path).kind_mut() else { - return false; - }; - if *active_ix == ix { - return false; - } - *active_ix = ix; - true - }) + let Some(path) = self.path_of_node(node) else { + return EditResult::default(); + }; + let NodeKind::Tabs { panels, active_ix } = self.node_at_mut(&path).kind_mut() else { + return EditResult::default(); + }; + // The layout is canonical already. Only this index can need clamping, + // and a request that differs before clamping still counts as an edit. + let changed = *active_ix != ix; + *active_ix = ix.min(panels.len().saturating_sub(1)); + EditResult { changed } } - /// Replace a split's slot sizes wholesale. - /// - /// A no-op, like every other operation given input it cannot resolve, if - /// `new_sizes.len()` does not match the split's child count: no rule in - /// `normalize` repairs a length mismatch, so applying it would otherwise - /// leave `children.len() != sizes.len()` and trip `normalize`'s - /// `debug_assert!`. + /// Replace a split's slot sizes. The vector must match its child count. + /// Changing size preferences preserves the already normalized tree shape. pub fn set_sizes(&mut self, node: NodeId, new_sizes: Vec>) -> EditResult { - self.edit(|tree| { - let Some(path) = tree.path_of_node(node) else { - return false; - }; - let NodeKind::Split { - children, sizes, .. - } = tree.node_at_mut(&path).kind_mut() - else { - return false; - }; - if new_sizes.len() != children.len() || *sizes == new_sizes { - return false; - } - *sizes = new_sizes; - true - }) + let Some(path) = self.path_of_node(node) else { + return EditResult::default(); + }; + let NodeKind::Split { + children, sizes, .. + } = self.node_at_mut(&path).kind_mut() + else { + return EditResult::default(); + }; + if new_sizes.len() != children.len() || *sizes == new_sizes { + return EditResult::default(); + } + *sizes = new_sizes; + EditResult { changed: true } } } @@ -181,7 +174,7 @@ impl PaneTree { /// Whether `panel` is anywhere in this tree. pub fn contains_panel(&self, panel: PanelId) -> bool { - self.panels().any(|candidate| candidate == panel) + self.find_panel_node(panel).is_some() } } @@ -344,6 +337,9 @@ fn split_parent_of(path: &super::tree::NodePath) -> Option<(super::tree::NodePat Some((parent.iter().copied().collect(), ix)) } +#[cfg(test)] +mod split_sizes_tests; + #[cfg(test)] mod tests { use super::super::*; @@ -572,6 +568,89 @@ mod tests { assert!(!result.changed()); } + #[test] + fn selecting_clamps_the_index_and_leaves_other_groups_alone() { + let (mut tree, tabs) = tree_with_one_group(); + tree.insert_panel( + panel(2), + InsertTarget::Tabs { + node: tabs, + ix: None, + activate: false, + }, + ); + tree.split(tabs, panel(3), Placement::Right, Some(px(90.))); + let other = tree.find_panel_node(panel(3)).unwrap(); + let before = tree.clone(); + + assert!(tree.set_active(tabs, usize::MAX).changed()); + assert!(tree.set_active(tabs, usize::MAX).changed()); + assert!(!tree.set_active(tabs, 1).changed()); + assert!(!tree.set_active(tree.root().id(), 1).changed()); + assert!(matches!( + tree.find_node(tabs).unwrap().kind(), + PaneRef::Tabs { active_ix: 1, .. } + )); + assert_eq!(tree.find_node(other), before.find_node(other)); + assert!(tree.set_active(tabs, 0).changed()); + assert_eq!(tree, before); + } + + #[test] + #[ignore = "manual CPU measurement of a wide pane tree"] + fn measure_selection_in_a_wide_pane_tree() { + use std::{hint::black_box, time::Instant}; + + let groups: usize = std::env::var("NOCTERM_PROFILE_PANE_COUNT") + .map(|value| value.parse().unwrap()) + .unwrap_or(128); + assert!(groups >= 1); + let (mut tree, first) = tree_with_one_group(); + for group in 0..groups { + let first_panel = panel(1 + group as u64 * 2); + if group > 0 { + assert!( + tree.split(first, first_panel, Placement::Right, None) + .changed() + ); + } + let node = tree.find_panel_node(first_panel).unwrap(); + assert!( + tree.insert_panel( + panel(first_panel.as_u64() + 1), + InsertTarget::Tabs { + node, + ix: None, + activate: false + }, + ) + .changed() + ); + } + + let mut samples = Vec::new(); + for _ in 0..101 { + let start = Instant::now(); + for selection in 0..512 { + let group = (selection / 2) % groups; + let second = 2 + group as u64 * 2; + let node = tree.find_panel_node(black_box(panel(second))).unwrap(); + black_box(tree.set_active(node, 1 - selection % 2).changed()); + } + samples.push(start.elapsed().as_nanos() as f64 / 512.0); + } + samples.sort_unstable_by(f64::total_cmp); + assert_eq!(tree.panels().count(), groups * 2); + assert!(matches!( + tree.find_node(first).unwrap().kind(), + PaneRef::Tabs { active_ix: 0, .. } + )); + eprintln!( + "groups={groups} selection_p50_ns={:.2} selection_p95_ns={:.2}", + samples[50], samples[95] + ); + } + #[test] fn set_sizes_replaces_a_matching_length_vector() { let (mut tree, tabs) = tree_with_one_group(); diff --git a/vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs b/vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs new file mode 100644 index 00000000..8a9daef3 --- /dev/null +++ b/vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs @@ -0,0 +1,151 @@ +// Nocterm: characterize split commits and measure their dependence on tree size. + +use super::{NodeId, PaneTree, PanelId, Placement}; +use crate::dock::{ + DockArea, DockEvent, DockLayout, PaneRef, PanelInfo, RootKind, test_support::TestPanel, +}; + +use gpui::{Modifiers, MouseButton, Pixels, TestAppContext, point, px}; +use std::{cell::Cell, hint::black_box, rc::Rc, time::Instant}; + +fn nested_split(descendants: usize) -> PaneTree { + let mut tree = PaneTree::new(RootKind::Split); + let anchor = PanelId::from_u64(1); + tree.split(tree.root().id(), anchor, Placement::Right, None); + let first = tree.find_panel_node(anchor).unwrap(); + tree.split(first, PanelId::from_u64(2), Placement::Right, None); + for id in 0..descendants { + tree.split( + first, + PanelId::from_u64(id as u64 + 3), + Placement::Bottom, + None, + ); + } + let PaneRef::Split { children, .. } = tree.root().kind() else { + panic!("expected a root split"); + }; + assert_eq!(children.len(), 2); + tree +} + +fn slot_sizes(tree: &PaneTree, node: NodeId) -> &[Option] { + let PaneRef::Split { sizes, .. } = tree.find_node(node).unwrap().kind() else { + panic!("expected a split"); + }; + sizes +} + +#[test] +fn a_split_size_write_leaves_nested_layouts_alone() { + let mut tree = nested_split(8); + let root = tree.root().id(); + let tabs = tree.find_panel_node(PanelId::from_u64(1)).unwrap(); + let PaneRef::Split { children, .. } = tree.root().kind() else { + panic!("expected a root split"); + }; + let descendants = children.to_vec(); + let sizes = vec![Some(px(220.)), None]; + assert!(tree.set_sizes(root, sizes.clone()).changed()); + assert!(!tree.set_sizes(root, sizes.clone()).changed()); + assert!(!tree.set_sizes(tabs, vec![Some(px(180.))]).changed()); + let removed = PanelId::from_u64(9); + let removed_node = tree.find_panel_node(removed).unwrap(); + assert_eq!(slot_sizes(&tree, root), &sizes); + let PaneRef::Split { children, .. } = tree.root().kind() else { + panic!("expected a root split"); + }; + assert_eq!(children, &descendants); + assert!(tree.remove_panel(removed).changed()); + assert!(!tree.set_sizes(removed_node, sizes.clone()).changed()); + assert_eq!(slot_sizes(&tree, root), sizes); +} + +fn dumped_split(area: &DockArea, app: &gpui::App) -> Vec { + let PanelInfo::Stack { sizes, .. } = area.dump(app).center.info else { + panic!("expected a saved split"); + }; + sizes +} + +#[gpui::test] +fn dragging_a_split_commits_the_measured_sizes_on_release(cx: &mut TestAppContext) { + cx.update(|app| { + let _ = crate::Theme::global_mut(app); + }); + let (area, cx) = + cx.add_window_view(|window, cx| DockArea::new("split-commit", None, window, cx)); + cx.update(|window, app| { + area.update(app, |area, cx| { + area.set_center( + DockLayout::h_split() + .child( + DockLayout::tabs().panel(TestPanel::new("First", cx)), + Some(px(300.)), + ) + .child( + DockLayout::tabs().panel(TestPanel::new("Second", cx)), + Some(px(300.)), + ), + window, + cx, + ); + }); + }); + cx.run_until_parked(); + let initial = cx.read(|app| dumped_split(area.read(app), app)); + let changes = Rc::new(Cell::new(0)); + let _subscription = cx.update(|window, app| { + let changes = changes.clone(); + window.subscribe(&area, app, move |_, event: &DockEvent, _, _| { + if matches!(event, DockEvent::LayoutChanged) { + changes.set(changes.get() + 1); + } + }) + }); + let seam = initial[0]; + let y = px(72.); + let modifiers = Modifiers::default(); + cx.simulate_mouse_down(point(seam - px(2.), y), MouseButton::Left, modifiers); + cx.simulate_mouse_move(point(seam + px(10.), y), Some(MouseButton::Left), modifiers); + let target = seam + px(40.); + cx.simulate_mouse_move(point(target, y), Some(MouseButton::Left), modifiers); + assert_eq!(changes.get(), 0); + cx.simulate_mouse_up(point(target, y), MouseButton::Left, modifiers); + cx.run_until_parked(); + let saved = cx.read(|app| dumped_split(area.read(app), app)); + assert_eq!(changes.get(), 1); + assert_eq!(saved, [target, initial[1] - px(40.)]); +} + +#[test] +#[ignore = "manual CPU measurement of a split size commit"] +fn measure_split_size_commits() { + let descendants = std::env::var("NOCTERM_PROFILE_SPLIT_DESCENDANTS") + .map(|value| value.parse::().unwrap()) + .unwrap_or(128); + let change = std::env::var("NOCTERM_PROFILE_SPLIT_CHANGE").as_deref() != Ok("0"); + let mut tree = nested_split(descendants); + let root = tree.root().id(); + assert!( + tree.set_sizes(root, vec![Some(px(210.)), Some(px(300.))]) + .changed() + ); + let mut samples = Vec::new(); + for _ in 0..101 { + let started = Instant::now(); + for step in 0..256 { + let first = if change && step % 2 == 0 { 220. } else { 210. }; + let values = black_box(vec![Some(px(first)), Some(px(300.))]); + assert_eq!(tree.set_sizes(root, values).changed(), change); + } + samples.push(started.elapsed().as_nanos() as f64 / 256.); + } + samples.sort_unstable_by(f64::total_cmp); + assert_eq!(tree.panels().count(), descendants + 2); + assert_eq!(slot_sizes(&tree, root), &[Some(px(210.)), Some(px(300.))]); + eprintln!( + "descendants={descendants} change={change} commit_p50_ns={:.2} commit_p95_ns={:.2}", + samples[50], samples[95] + ); +} diff --git a/vendor/gpui-base/src/dock/layout/mod.rs b/vendor/gpui-base/src/dock/layout/mod.rs index d0cd3de7..a2bbc8e9 100644 --- a/vendor/gpui-base/src/dock/layout/mod.rs +++ b/vendor/gpui-base/src/dock/layout/mod.rs @@ -1,3 +1,5 @@ +// Nocterm: document the canonical layout invariant. + mod builder; mod edit; mod node; @@ -9,8 +11,7 @@ pub use edit::{EditResult, InsertTarget}; // `NodeKind` stays crate-private: `dock_area` reads through it to resolve slot // sizes before a dump, but nothing outside this crate may build a node without -// going through `PaneTree`, which is what guarantees normalization always -// runs. +// going through `PaneTree`, which maintains the normalized shape. pub(crate) use node::NodeKind; pub use node::{NodeId, PaneNode, PaneRef, PanelId}; pub use tree::{PaneTree, RootKind}; diff --git a/vendor/gpui-base/src/dock/layout/node.rs b/vendor/gpui-base/src/dock/layout/node.rs index d04d4352..6f071ecc 100644 --- a/vendor/gpui-base/src/dock/layout/node.rs +++ b/vendor/gpui-base/src/dock/layout/node.rs @@ -1,3 +1,5 @@ +// Nocterm: document the canonical layout invariant. + use gpui::{Axis, EntityId, Pixels}; /// Stable container identity. Survives structural edits and normalization so @@ -36,8 +38,8 @@ impl From for PanelId { } } -/// The shape of one container. Private: every mutation goes through -/// [`PaneTree`] so normalization always runs. +/// The shape of one container. Private: edits go through [`PaneTree`], +/// which maintains the normalized shape. /// /// [`PaneTree`]: super::PaneTree #[derive(Clone, PartialEq, Debug)] diff --git a/vendor/gpui-base/src/dock/layout/tree.rs b/vendor/gpui-base/src/dock/layout/tree.rs index ad743995..b912c8d1 100644 --- a/vendor/gpui-base/src/dock/layout/tree.rs +++ b/vendor/gpui-base/src/dock/layout/tree.rs @@ -1,3 +1,5 @@ +// Nocterm: short-circuit panel lookup in reverse layout order. + use std::sync::atomic::{AtomicU64, Ordering}; use smallvec::SmallVec; @@ -38,10 +40,10 @@ fn next_node_id() -> NodeId { /// no entity handle lives in here, so a tree can be built, edited, compared /// and serialized with no `App` in sight. /// -/// Every edit method normalizes before returning and reports what it did as -/// an [`EditResult`](super::EditResult), so there is no window in which a -/// caller can observe a tree with an empty container, a one-child split, or an -/// out-of-range active index. +/// Every edit preserves normalization and reports what it did as an +/// [`EditResult`](super::EditResult), so a caller cannot observe an empty +/// nested container, a nested one-child split, or an out-of-range active +/// index. #[derive(Clone, PartialEq, Debug)] pub struct PaneTree { root: PaneNode, @@ -99,19 +101,18 @@ impl PaneTree { self.path_of_node(id).map(|path| self.node_at(&path)) } - /// The tab node holding `panel`. + /// The last tab node in layout order holding `panel`. pub fn find_panel_node(&self, panel: PanelId) -> Option { - let mut found = None; - self.root.walk(&mut |node| { - let holds = match node.kind() { - PaneRef::Tabs { panels, .. } => panels.contains(&panel), - PaneRef::Split { .. } => false, - }; - if holds { - found = Some(node.id()); + fn find(node: &PaneNode, panel: PanelId) -> Option { + match node.kind_ref() { + NodeKind::Tabs { panels, .. } => panels.contains(&panel).then_some(node.id()), + NodeKind::Split { children, .. } => { + children.iter().rev().find_map(|child| find(child, panel)) + } } - }); - found + } + + find(&self.root, panel) } pub(crate) fn path_of_node(&self, id: NodeId) -> Option { @@ -300,4 +301,18 @@ mod tests { assert!(tree.find_node(tabs).is_some()); assert_eq!(tree.find_panel_node(panel_id(1)), Some(tabs)); } + + #[test] + fn panel_lookup_prefers_the_last_group_holding_that_panel() { + let mut tree = PaneTree::new(RootKind::Split); + let repeated = panel_id(1); + let first = tree.push_tabs_for_test(tree.root().id(), vec![repeated]); + let second = tree.push_tabs_for_test(tree.root().id(), vec![repeated]); + tree.normalize(); + + assert_eq!(tree.find_panel_node(repeated), Some(second)); + assert_eq!(tree.find_panel_node(panel_id(2)), None); + tree.remove_panel(repeated); + assert_eq!(tree.find_panel_node(repeated), Some(first)); + } } diff --git a/vendor/gpui-base/src/dock/tab_group.rs b/vendor/gpui-base/src/dock/tab_group.rs index 899349c1..444befeb 100644 --- a/vendor/gpui-base/src/dock/tab_group.rs +++ b/vendor/gpui-base/src/dock/tab_group.rs @@ -2,17 +2,23 @@ //! A tab group's behavior, with no appearance of its own. use crate::TestSupportExt as _; -use std::{rc::Rc, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + rc::Rc, + sync::Arc, +}; use gpui::{ - AnyElement, AnyView, App, Bounds, Context, Div, DragMoveEvent, Empty, EventEmitter, - FocusHandle, Focusable, InteractiveElement as _, IntoElement, ParentElement as _, Pixels, - Render, Stateful, Styled as _, Subscription, WeakEntity, Window, div, - prelude::FluentBuilder as _, px, + App, Bounds, Context, DragMoveEvent, EntityId, EventEmitter, FocusHandle, Focusable, + InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, Styled as _, + Subscription, WeakEntity, Window, prelude::FluentBuilder as _, px, }; use crate::Placement; +pub(crate) use rendering::BareTabGroup; +pub use rendering::{TabGroupContext, TabGroupRenderer}; + use super::{ active::ActiveTracker, drag::{ @@ -153,7 +159,7 @@ pub struct TabGroup { /// Handed to the callbacks in [`TabGroupContext`], which are built from a /// plain `&App` and so cannot ask for it. this: WeakEntity, - panels: Vec>, + panels: Rc<[Arc]>, active_ix: usize, zoomed: bool, zoom_revision: u64, @@ -164,7 +170,7 @@ pub struct TabGroup { renderer: Rc, /// Nocterm: the area draws the group as a cached view, and the tab bar draws /// every panel's title, so any panel's change draws the group again. - _panel_changes: Vec, + panel_observations: HashMap, } impl TabGroup { @@ -175,7 +181,7 @@ impl TabGroup { Self { node, this: cx.weak_entity(), - panels: Vec::new(), + panels: Rc::default(), active_ix: 0, zoomed: false, zoom_revision: 0, @@ -185,7 +191,7 @@ impl TabGroup { active: ActiveTracker::default(), drop_indicator: None, renderer: Rc::new(BareTabGroup), - _panel_changes: Vec::new(), + panel_observations: HashMap::new(), } } @@ -281,53 +287,7 @@ impl TabGroup { /// A snapshot of everything a skin needs to draw this group. pub fn context(&self, cx: &App) -> TabGroupContext { - let group = self.this.clone(); - - TabGroupContext { - node: self.node, - panels: self.panels.clone(), - active_panel: self.active_panel(cx), - active_ix: self.active_ix, - zoomed: self.zoomed, - constraints: self.constraints, - active_panel_closable: self.is_closable(cx), - draggable: self.draggable(cx), - panel_close_allowed: self.closable_panels(cx), - droppable: self.droppable(), - // A stale indicator would otherwise outlive a drag that was - // cancelled while hovering this group. - drop_indicator: cx - .has_active_drag() - .then_some(self.drop_indicator) - .flatten(), - on_select_tab: { - let group = group.clone(); - Rc::new(move |ix, window, cx| { - _ = group.update(cx, |group, cx| group.select_tab(ix, window, cx)); - }) - }, - on_close: { - let group = group.clone(); - Rc::new(move |panel, _, cx| { - _ = group.update(cx, |group, cx| group.close_panel(panel, cx)); - }) - }, - on_toggle_zoom: { - let group = group.clone(); - Rc::new(move |window, cx| { - _ = group.update(cx, |group, cx| group.toggle_zoom(window, cx)); - }) - }, - on_drop_panel: { - let group = group.clone(); - Rc::new(move |drag, ix, activate, _, cx| { - _ = group.update(cx, |group, cx| group.on_drop(&drag, ix, activate, cx)); - }) - }, - on_drop_item: Rc::new(move |item, placement, _, cx| { - _ = group.update(cx, |group, cx| group.emit_drag_drop(&item, placement, cx)); - }), - } + TabGroupContext::from_group(self, cx) } } @@ -344,29 +304,55 @@ impl TabGroup { active_ix: usize, window: &mut Window, cx: &mut Context, + ) { + let same_panels = panels.len() == self.panels.len() + && panels + .iter() + .zip(self.panels.iter()) + .all(|(next, held)| Arc::ptr_eq(next, held)); + if !same_panels { + self.replace_panels(panels, window, cx); + } + self.active_ix = active_ix.min(self.panels.len().saturating_sub(1)); + self.schedule_active_sync(window, cx); + cx.notify(); + } + + fn replace_panels( + &mut self, + panels: Vec>, + window: &mut Window, + cx: &mut Context, ) { let group = cx.weak_entity(); - let existing: Vec = self.panels.iter().map(|panel| panel.panel_id(cx)).collect(); - for panel in panels.iter() { + let existing: HashSet = + self.panels.iter().map(|panel| panel.panel_id(cx)).collect(); + for panel in &panels { if !existing.contains(&panel.panel_id(cx)) { panel.on_added_to(group.clone(), window, cx); } } - self.panels = panels; - self._panel_changes = self - .panels - .iter() - .map(|panel| { - let group = group.clone(); - panel.view().observe(cx, move |cx| { - _ = group.update(cx, |_, cx| cx.notify()); + self.panels = panels.into(); + // A membership edit can leave most of the views in place. Move + // their observations into a map sized for the new membership; any + // remaining old subscriptions detach when this update returns. + let mut previous = std::mem::take(&mut self.panel_observations); + let mut observations = HashMap::with_capacity(self.panels.len()); + for panel in self.panels.iter() { + let view = panel.view(); + let id = view.entity_id(); + observations.entry(id).or_insert_with(|| { + previous.remove(&id).unwrap_or_else(|| { + let group = group.clone(); + view.observe(cx, move |cx| { + _ = group.update(cx, |_, cx| cx.notify()); + }) }) - }) - .collect(); - self.active_ix = active_ix.min(self.panels.len().saturating_sub(1)); - self.schedule_active_sync(window, cx); - cx.notify(); + }); + } + self.panel_observations = observations; + self.active.membership_changed(); } /// Replace everything the container knows about this group's place in the @@ -644,8 +630,8 @@ impl Render for TabGroup { let context = self.context(cx); let renderer = self.renderer.clone(); let focus_handle = self.focus_handle(cx); - let droppable = context.droppable; - let indicator = context.drop_indicator; + let droppable = context.is_droppable(); + let indicator = context.drop_indicator(); renderer .frame(&context, window, cx) @@ -699,7 +685,7 @@ impl Render for TabGroup { this.emit_drag_drop(item, placement, cx); })) }) - .map(|this| match context.active_panel.as_ref() { + .map(|this| match context.active_panel() { Some(panel) => this.child(renderer.render_active_panel( panel.view(), &context, @@ -715,1065 +701,10 @@ impl Render for TabGroup { } } -type SelectTabHandler = Rc; -type ClosePanelHandler = Rc; -type ToggleZoomHandler = Rc; -type DropPanelHandler = Rc, bool, &mut Window, &mut App)>; -type DropItemHandler = Rc, &mut Window, &mut App)>; - -/// What a skin needs to draw a tab group, and the callbacks it invokes rather -/// than reimplementing behavior. -#[derive(Clone)] -pub struct TabGroupContext { - node: NodeId, - panels: Vec>, - active_panel: Option>, - active_ix: usize, - zoomed: bool, - constraints: TabGroupConstraints, - draggable: bool, - panel_close_allowed: bool, - droppable: bool, - active_panel_closable: bool, - drop_indicator: Option, - on_select_tab: SelectTabHandler, - on_close: ClosePanelHandler, - on_toggle_zoom: ToggleZoomHandler, - on_drop_panel: DropPanelHandler, - on_drop_item: DropItemHandler, -} - -impl TabGroupContext { - /// The `Tabs` node this group mirrors, for a skin that needs to name the - /// group in a drag payload or a drop target. - pub fn node(&self) -> NodeId { - self.node - } - - /// Every panel in the group, in tab order — visible or not. A skin filters - /// with [`PanelView::visible`] when it draws. - pub fn panels(&self) -> &[Arc] { - &self.panels - } - - pub fn active_ix(&self) -> usize { - self.active_ix - } - - /// The panel on screen, which is the displayed tab unless that panel has - /// gone invisible. - pub fn active_panel(&self) -> Option<&Arc> { - self.active_panel.as_ref() - } - - pub fn drop_indicator(&self) -> Option { - self.drop_indicator - } - - pub fn is_zoomed(&self) -> bool { - self.zoomed - } - - pub fn is_collapsed(&self) -> bool { - self.constraints.is_collapsed() - } - - /// Whether the active panel can be closed. - pub fn is_closable(&self) -> bool { - self.active_panel_closable - } - - /// Whether `panel` can be closed from this group. Uses the same constraints - /// as [`TabGroup::close_panel`], including the panel's own `closable` flag. - pub fn is_panel_closable(&self, panel: PanelId, cx: &App) -> bool { - self.constraints.is_closable() - && self.panel_close_allowed - && self - .panels - .iter() - .any(|candidate| candidate.panel_id(cx) == panel && candidate.closable(cx)) - } - - pub fn is_locked(&self) -> bool { - self.constraints.is_locked() - } - - pub fn is_draggable(&self) -> bool { - self.draggable - } - - pub fn is_droppable(&self) -> bool { - self.droppable - } - - pub fn select_tab(&self, ix: usize, window: &mut Window, cx: &mut App) { - (self.on_select_tab)(ix, window, cx); - } - - pub fn close(&self, panel: PanelId, window: &mut Window, cx: &mut App) { - (self.on_close)(panel, window, cx); - } - - pub fn toggle_zoom(&self, window: &mut Window, cx: &mut App) { - (self.on_toggle_zoom)(window, cx); - } - - /// The drag payload for the tab at `ix`, for a skin wiring `on_drag` onto - /// its tabs. `None` when `ix` names no panel. - pub fn drag_panel(&self, ix: usize, cx: &App) -> Option { - self.panels - .get(ix) - .map(|panel| DragPanel::new(panel.panel_id(cx), self.node)) - } - - /// A panel dropped on the tab bar. `ix` names the slot it lands in, or - /// `None` to append; `activate` decides whether it becomes displayed. - pub fn drop_panel( - &self, - drag: DragPanel, - ix: Option, - activate: bool, - window: &mut Window, - cx: &mut App, - ) { - (self.on_drop_panel)(drag, ix, activate, window, cx); - } - - /// A host-owned drag dropped on the tab bar. `placement` is `None` to - /// merge into this group rather than split beside it. - pub fn drop_item( - &self, - item: AnyDrag, - placement: Option, - window: &mut Window, - cx: &mut App, - ) { - (self.on_drop_item)(item, placement, window, cx); - } -} - -/// Appearance for a tab group. Base draws none of it. -/// -/// The two frame hooks return the element itself rather than wrapping one, -/// because base attaches focus, keyboard grouping, and drop handling to the -/// very elements the skin styles: a wrapper would put the hit area and the -/// painted area on different elements. -#[allow(unused_variables)] -pub trait TabGroupRenderer: 'static { - /// The group's outer frame, which base tracks focus on. - /// - /// Identified rather than plain, so a skin can add a role, a tooltip, or - /// scroll tracking; `Stateful

` does everything base needs from it. - /// Appearance only. The group is laid out as a column that fills its slot - /// around whatever this returns, because a group that does not is a strip - /// of tabs with no content under it. - /// A renderer that needs the painted group bounds can attach `on_prepaint` - /// here and identify the group with [`TabGroupContext::node`]. - fn frame(&self, group: &TabGroupContext, window: &mut Window, cx: &mut App) -> Stateful
{ - div().id("tab-group") - } - - /// The region below the tab bar, which base installs drop handling on. - fn content_frame( - &self, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> Stateful
{ - div().id("tab-group-content") - } - - fn render_tab_bar( - &self, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> AnyElement; - - /// How the displayed panel's view is placed in the content region. The - /// skin receives the view rather than an element so it can decide how the - /// view is cached and stretched. - fn render_active_panel( - &self, - panel: AnyView, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> AnyElement { - panel.into_any_element() - } - - fn render_drop_indicator( - &self, - indicator: DropIndicator, - window: &mut Window, - cx: &mut App, - ) -> Option { - None - } - - fn render_empty( - &self, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> Option { - None - } -} - -/// The renderer a group starts with: the displayed panel and nothing else. -pub(crate) struct BareTabGroup; - -impl TabGroupRenderer for BareTabGroup { - fn render_tab_bar(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> AnyElement { - Empty.into_any_element() - } -} +mod rendering; #[cfg(test)] -mod tests { - use std::cell::RefCell; - - use gpui::{ - AppContext as _, Entity, Modifiers, MouseButton, StatefulInteractiveElement as _, - TestAppContext, VisualTestContext, point, px, size, - }; - - use super::*; - use crate::dock::test_support::{ - PanelSignal, build_group, drain, drain_active, log_of, panel_id, - }; - - /// The node `build_group` gives its group. - fn group_node() -> NodeId { - NodeId::from_u64(1) - } - - fn elsewhere() -> NodeId { - NodeId::from_u64(7) - } - - fn content_bounds() -> Bounds { - Bounds { - origin: point(px(0.), px(0.)), - size: size(px(400.), px(300.)), - } - } - - /// Collect the group's outgoing intents as readable strings, so an - /// assertion reads as the sentence the event means. - fn record_events( - group: &Entity, - cx: &mut VisualTestContext, - ) -> Rc>> { - let events: Rc>> = Rc::default(); - let sink = events.clone(); - cx.update(|_, cx| { - cx.subscribe(group, move |_, event: &TabGroupEvent, _| { - sink.borrow_mut().push(describe(event)); - }) - .detach(); - }); - events - } - - fn describe(event: &TabGroupEvent) -> String { - match event { - TabGroupEvent::Drop { - panel, - source, - target, - } => match target { - InsertTarget::Tabs { node, ix, activate } => format!( - "drop panel {} from {} into tabs {} at {:?} activate={}", - panel.as_u64(), - source.as_u64(), - node.as_u64(), - ix, - activate - ), - InsertTarget::Split { - node, placement, .. - } => format!( - "drop panel {} from {} split {} {}", - panel.as_u64(), - source.as_u64(), - node.as_u64(), - placement - ), - }, - TabGroupEvent::DragDrop { target, .. } => format!( - "item onto {} at {:?}", - target.node().as_u64(), - target.placement() - ), - TabGroupEvent::ClosePanel { panel } => format!("close {}", panel.as_u64()), - TabGroupEvent::ActiveChanged { ix } => format!("active {ix}"), - TabGroupEvent::ZoomIn { .. } => "zoom in".into(), - TabGroupEvent::ZoomOut { .. } => "zoom out".into(), - } - } - - #[gpui::test] - fn a_group_announces_its_first_panel_active(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a"], cx); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("a", true)]); - let _ = (group, panels); - } - - #[gpui::test] - fn selecting_another_tab_deactivates_then_activates(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - drain_active(&log); - - cx.update(|window, cx| { - group.update(cx, |group, cx| group.select_tab(1, window, cx)); - }); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("a", false), ("b", true)]); - } - - #[gpui::test] - fn the_context_snapshots_the_group_state(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - - let seen = cx.update(|_, cx| { - group.update(cx, |group, cx| { - let context = group.context(cx); - ( - context.panels().len(), - context.active_ix(), - context.is_zoomed(), - ) - }) - }); - - assert_eq!(seen, (2, 0, false)); - } - - /// A panel hidden while it holds the displayed slot is still the panel - /// told it is active; only what gets drawn falls back to a visible one. - #[gpui::test] - fn a_hidden_displayed_panel_is_still_the_active_one(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - cx.update(|_, cx| { - panels[0].update(cx, |panel, cx| panel.set_visible(false, cx)); - }); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("a", true)]); - assert_eq!( - cx.update(|_, cx| group.read(cx).active_panel(cx).unwrap().panel_name(cx)), - "b", - "rendering falls back to the first visible panel" - ); - } - - /// `on_removed` is a departing panel's deactivation signal, so the group - /// must not also announce `false` to it. - #[gpui::test] - fn a_panel_dropped_from_the_group_is_never_told_it_went_inactive(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - drain(&log); - - cx.update(|window, cx| { - let remaining: Vec> = vec![Arc::new(panels[1].clone())]; - group.update(cx, |group, cx| { - group.sync_from_tree(remaining, 0, window, cx) - }); - }); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("b", true)]); - } - - #[gpui::test] - fn selecting_a_tab_that_is_not_there_changes_nothing(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - drain_active(&log); - let events = record_events(&group, cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| group.select_tab(5, window, cx)); - }); - cx.run_until_parked(); - - assert_eq!(cx.update(|_, cx| group.read(cx).active_ix()), 0); - assert!(events.borrow().is_empty()); - assert!(drain_active(&log).is_empty()); - } - - #[gpui::test] - fn a_locked_group_can_be_neither_dragged_nor_dropped_into(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - let unlocked = cx.update(|_, cx| { - let context = group.read(cx).context(cx); - (context.is_draggable(), context.is_droppable()) - }); - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).dock_locked(true), - window, - cx, - ) - }) - }); - let locked = cx.update(|_, cx| { - let context = group.read(cx).context(cx); - (context.is_draggable(), context.is_droppable()) - }); - - assert_eq!(unlocked, (true, true)); - assert_eq!(locked, (false, false)); - } - - /// Zoom retains the same native reorder and drop affordances. - #[gpui::test] - fn a_zoomed_group_keeps_tab_drag_and_drop(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx); - group.set_zoomed(true, window, cx); - }) - }); - - assert!(cx.update(|_, cx| group.read(cx).context(cx).is_droppable())); - assert!(cx.update(|_, cx| group.read(cx).context(cx).is_draggable())); - assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_locked())); - } - - /// Dragging the last visible panel out of the only group would leave the - /// dock empty and undroppable, so it is refused. - #[gpui::test] - fn the_only_groups_last_visible_panel_cannot_be_dragged_out(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(true), window, cx) - }) - }); - let alone = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - let beside_others = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); - - assert!(!alone); - assert!(beside_others); - } - - #[gpui::test] - fn a_panel_from_another_group_lands_as_one_move(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); - cx.update(|_, cx| { - group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); - }); - cx.run_until_parked(); - - assert_eq!( - *events.borrow(), - vec!["drop panel 99 from 7 into tabs 1 at None activate=true"] - ); - } - - #[gpui::test] - fn dropping_a_panel_back_onto_its_own_group_is_ignored(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - let events = record_events(&group, cx); - - let panel = panel_id(&panels[0], cx); - let drag = DragPanel::new(panel, group_node()); - cx.update(|_, cx| { - group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); - }); - cx.run_until_parked(); - - assert!(events.borrow().is_empty()); - } - - #[gpui::test] - fn a_hovering_split_turns_a_drop_into_a_split(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Right), - drag.drag_session_id(), - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - group.on_drop(&drag, None, true, cx); - }); - }); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec!["drop panel 99 from 7 split 1 Right"]); - } - - /// The tab bar reports the slot a drop landed on, and a slot always means - /// "into these tabs" however the content area had resolved the cursor. - #[gpui::test] - fn a_tab_slot_overrides_the_hovering_split(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Right), - drag.drag_session_id(), - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - group.on_drop(&drag, Some(0), true, cx); - }); - }); - cx.run_until_parked(); - - assert_eq!( - *events.borrow(), - vec!["drop panel 99 from 7 into tabs 1 at Some(0) activate=true"] - ); - } - - /// A lone panel splitting out of its own group would empty that group and - /// refill it, which is no move at all. - #[gpui::test] - fn a_lone_panel_cannot_split_out_of_its_own_group(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(panel_id(&panels[0], cx), group_node()); - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Right), - drag.drag_session_id(), - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - group.on_drop(&drag, None, true, cx); - }); - }); - cx.run_until_parked(); - - assert!(events.borrow().is_empty()); - } - - #[gpui::test] - fn the_placeholder_replays_only_when_the_target_moves(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let bounds = content_bounds(); - let source = DropPlaceholderBounds::new(point(px(10.), px(10.)), size(px(96.), px(30.))); - - let sync = |placement: Option, cx: &mut VisualTestContext| { - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder(bounds, placement, 42, source, cx); - group.drop_indicator.unwrap() - }) - }) - }; - - let first = sync(Some(Placement::Left), cx); - let again = sync(Some(Placement::Left), cx); - let moved = sync(Some(Placement::Right), cx); - - assert_eq!(first.epoch(), 0); - assert_eq!(first.from(), source, "the first run flies in from the drag"); - assert_eq!(again.epoch(), 0, "an unchanged target keeps animating"); - assert_eq!(again.from(), source); - assert_eq!(moved.epoch(), 1, "a moved target replays from where it was"); - assert_eq!(moved.from(), first.to()); - assert_eq!( - moved.to(), - DropPlaceholderBounds::for_placement(bounds, Some(Placement::Right)) - ); - } - - /// The indicator is hit state, not a latch: a drag cancelled while - /// hovering must not leave the placeholder painted. - #[gpui::test] - fn the_indicator_is_withheld_when_no_drag_is_in_flight(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - - let (stored, published) = cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Top), - 42, - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - ( - group.drop_indicator.is_some(), - group.context(cx).drop_indicator().is_some(), - ) - }) - }); - - assert!(stored); - assert!(!published); - } - - #[gpui::test] - fn a_host_drag_reports_the_group_and_the_edge_it_resolved(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.emit_drag_drop(&AnyDrag::new(7u32), Some(Placement::Bottom), cx) - }); - }); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec!["item onto 1 at Some(Bottom)"]); - } - - #[gpui::test] - fn closing_asks_the_container_rather_than_editing_the_group(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - let events = record_events(&group, cx); - let panel = panel_id(&panels[1], cx); - - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.close_panel(panel, cx); - // A panel that is not a member is not this group's to close. - group.close_panel(PanelId::from_u64(4242), cx); - }); - }); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec![format!("close {}", panel.as_u64())]); - assert_eq!( - cx.update(|_, cx| group.read(cx).panels().len()), - 2, - "the group still holds both panels until the container edits the tree" - ); - } - - #[gpui::test] - fn zooming_toggles_and_tells_the_displayed_panel(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); - cx.run_until_parked(); - cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec!["zoom in", "zoom out"]); - assert!(!cx.update(|_, cx| group.read(cx).is_zoomed())); - assert_eq!( - drain(&log) - .into_iter() - .filter(|(_, signal)| matches!(signal, PanelSignal::Zoomed(_))) - .collect::>(), - vec![ - ("a", PanelSignal::Zoomed(true)), - ("a", PanelSignal::Zoomed(false)) - ], - "the old TabPanel sent this to itself, where the default no-op swallowed it" - ); - } - - /// A real drag over a locked group must resolve nothing: base installs no - /// drop handling on one, so the placement is never computed and the layout - /// tree is never asked to move anything. - #[gpui::test] - fn a_drag_over_a_locked_group_resolves_nothing(cx: &mut TestAppContext) { - let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).dock_locked(true), - window, - cx, - ) - }) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - drag_from_the_tab_into_the_content(cx); - - assert!( - cx.update(|_, cx| group.read(cx).drop_indicator.is_none()), - "a locked group installs no drag-move listener, so nothing resolved" - ); - } - - /// `Dock::new` marks a dock's last group unclosable so the dock cannot be - /// emptied out from under itself. - #[gpui::test] - fn a_group_the_container_sealed_shut_refuses_to_close(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - let events = record_events(&group, cx); - let panel = panel_id(&panels[0], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).closable(false), - window, - cx, - ); - group.close_panel(panel, cx); - }) - }); - cx.run_until_parked(); - - assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_closable())); - assert!(events.borrow().is_empty()); - } - - /// The last visible panel of the only group has nowhere to go, so it is - /// not closable either — closing it would empty the region out from under - /// itself. Placing a sibling beside the group makes the same panel - /// closable again, which is what pins the reason to `alone` rather than to - /// something else the sealed default also forbids. - #[gpui::test] - fn the_only_groups_last_panel_is_not_closable(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(true), window, cx) - }) - }); - let alone = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - let beside_a_sibling = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); - - assert!(!alone); - assert!(beside_a_sibling); - } - - /// Collapsing takes the displayed panel off screen, and the active-state - /// contract counts that as no panel being displayed. - #[gpui::test] - fn collapsing_deactivates_the_displayed_panel_and_expanding_restores_it( - cx: &mut TestAppContext, - ) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - assert_eq!(drain_active(&log), vec![("a", true)]); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).collapsed(true), - window, - cx, - ) - }) - }); - cx.run_until_parked(); - assert_eq!(drain_active(&log), vec![("a", false)]); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - cx.run_until_parked(); - assert_eq!(drain_active(&log), vec![("a", true)]); - } - - // ---- the renderer seam ---- - - /// Where `RecordingRenderer` puts its content frame. Deliberately not the - /// window's own origin or size, so a listener on the outer frame would - /// report different bounds. - fn skin_content() -> Bounds { - Bounds { - origin: point(px(100.), px(50.)), - size: size(px(400.), px(300.)), - } - } - - /// A skin that records which hooks base calls, and lays its two frames out - /// at known coordinates so a test can tell them apart by hit geometry. - struct RecordingRenderer { - calls: Rc>>, - } - - impl RecordingRenderer { - fn saw(&self, call: &'static str) { - self.calls.borrow_mut().push(call); - } - } - - impl TabGroupRenderer for RecordingRenderer { - fn frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ - self.saw("frame"); - div().id("skin-frame").relative().size_full() - } - - fn content_frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ - self.saw("content_frame"); - div() - .id("skin-content") - .absolute() - .left(skin_content().origin.x) - .top(skin_content().origin.y) - .w(skin_content().size.width) - .h(skin_content().size.height) - } - - fn render_tab_bar( - &self, - group: &TabGroupContext, - _: &mut Window, - cx: &mut App, - ) -> AnyElement { - self.saw("tab_bar"); - div() - .id("skin-tab") - .absolute() - .left(px(0.)) - .top(px(0.)) - .w(px(80.)) - .h(px(24.)) - .when_some(group.drag_panel(0, cx), |this, drag| { - this.on_drag(drag, |drag, offset, _, cx| { - drag.set_drag_offset(offset); - cx.new(|_| drag.clone()) - }) - }) - .into_any_element() - } - - fn render_active_panel( - &self, - panel: AnyView, - _: &TabGroupContext, - _: &mut Window, - _: &mut App, - ) -> AnyElement { - self.saw("active_panel"); - panel.into_any_element() - } - - fn render_empty( - &self, - _: &TabGroupContext, - _: &mut Window, - _: &mut App, - ) -> Option { - self.saw("empty"); - None - } - - fn render_drop_indicator( - &self, - _: DropIndicator, - _: &mut Window, - _: &mut App, - ) -> Option { - self.saw("drop_indicator"); - None - } - } - - fn build_skinned_group<'a>( - names: &[&'static str], - cx: &'a mut TestAppContext, - ) -> ( - Entity, - Rc>>, - &'a mut VisualTestContext, - ) { - let calls: Rc>> = Rc::default(); - let renderer = Rc::new(RecordingRenderer { - calls: calls.clone(), - }); - let (group, cx) = cx.add_window_view(|window, cx| { - TabGroup::new(NodeId::from_u64(1), window, cx).with_renderer(renderer) - }); - - let names = names.to_vec(); - let log = log_of(); - cx.update(|window, cx| { - let views: Vec> = names - .iter() - .map(|name| { - Arc::new(crate::dock::test_support::TestPanel::logging( - name, &log, cx, - )) as _ - }) - .collect(); - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx); - group.sync_from_tree(views, 0, window, cx); - }); - }); - cx.run_until_parked(); - calls.borrow_mut().clear(); - - (group, calls, cx) - } - - /// Press on the skin's tab, start the drag, and move into the right-hand - /// third of `skin_content()`. - fn drag_from_the_tab_into_the_content(cx: &mut VisualTestContext) { - cx.simulate_mouse_down( - point(px(20.), px(10.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.simulate_mouse_move( - point(px(30.), px(14.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.simulate_mouse_move( - point(px(450.), px(200.)), - MouseButton::Left, - Modifiers::none(), - ); - } - - /// The composition contract every later renderer copies: which hooks base - /// calls, and in what order. - #[gpui::test] - fn the_renderer_composes_frame_then_tab_bar_then_content(cx: &mut TestAppContext) { - let (_group, calls, cx) = build_skinned_group(&["a"], cx); - - cx.update(|window, cx| window.draw(cx).clear(cx)); - - assert_eq!( - *calls.borrow(), - vec!["frame", "tab_bar", "content_frame", "active_panel"], - "the tab bar is a sibling of the content, not a child of it" - ); - } - - /// With nothing to display base asks for the empty element instead of the - /// active panel, and never for both. - #[gpui::test] - fn an_empty_group_asks_the_renderer_for_its_empty_state(cx: &mut TestAppContext) { - let (_group, calls, cx) = build_skinned_group(&[], cx); - - cx.update(|window, cx| window.draw(cx).clear(cx)); - - assert_eq!( - *calls.borrow(), - vec!["frame", "tab_bar", "content_frame", "empty"] - ); - } - - /// The drop listeners must sit on the content frame, not the outer frame: - /// a drag over the group resolves against the content frame's own bounds, - /// which the skin — not base — decides. - #[gpui::test] - fn the_content_frame_is_what_a_drag_is_measured_against(cx: &mut TestAppContext) { - let (group, calls, cx) = build_skinned_group(&["a", "b"], cx); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - drag_from_the_tab_into_the_content(cx); - - let indicator = cx - .update(|_, cx| group.read(cx).drop_indicator) - .expect("the content frame's drag-move listener ran"); - - assert_eq!( - indicator.bounds(), - skin_content(), - "measured against the content frame, not the full-size outer frame" - ); - assert_eq!(indicator.placement(), Some(Placement::Right)); - - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert!( - calls.borrow().contains(&"drop_indicator"), - "a published indicator is handed to the renderer to draw" - ); - } - - /// A drop landing on the content frame reports a move the container can - /// apply, and clears the hover state behind it. - #[gpui::test] - fn dropping_on_the_content_frame_reports_the_move(cx: &mut TestAppContext) { - let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); - let events = record_events(&group, cx); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - drag_from_the_tab_into_the_content(cx); - cx.simulate_mouse_up( - point(px(450.), px(200.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.run_until_parked(); - - assert_eq!(events.borrow().len(), 1, "got {:?}", events.borrow()); - assert!( - events.borrow()[0].ends_with("split 1 Right"), - "got {:?}", - events.borrow() - ); - assert!(cx.update(|_, cx| group.read(cx).drop_indicator.is_none())); - } -} +mod tests; mod zoom; diff --git a/vendor/gpui-base/src/dock/tab_group/constraints.rs b/vendor/gpui-base/src/dock/tab_group/constraints.rs index d73ec35b..90bd41c6 100644 --- a/vendor/gpui-base/src/dock/tab_group/constraints.rs +++ b/vendor/gpui-base/src/dock/tab_group/constraints.rs @@ -17,7 +17,7 @@ impl TabGroup { /// be rearranged around. Only visible panels count, so a hidden panel does /// not keep the last visible one draggable and leave the dock empty. pub(super) fn is_last_panel(&self, cx: &App) -> bool { - self.constraints.is_alone() && self.visible_panels(cx).count() <= 1 + self.constraints.is_alone() && self.visible_panels(cx).nth(1).is_none() } pub(super) fn draggable(&self, cx: &App) -> bool { diff --git a/vendor/gpui-base/src/dock/tab_group/rendering.rs b/vendor/gpui-base/src/dock/tab_group/rendering.rs new file mode 100644 index 00000000..112b2c27 --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/rendering.rs @@ -0,0 +1,280 @@ +// Moved by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +//! Tab-group appearance contract and its render-time snapshot. +use std::{rc::Rc, sync::Arc}; + +use gpui::{ + AnyElement, AnyView, App, Div, Empty, InteractiveElement as _, IntoElement, Stateful, Window, + div, +}; + +use super::{ + AnyDrag, DragPanel, DropIndicator, NodeId, PanelId, PanelView, Placement, TabGroup, + TabGroupConstraints, +}; + +type SelectTabHandler = Rc; +type ClosePanelHandler = Rc; +type ToggleZoomHandler = Rc; +type DropPanelHandler = Rc, bool, &mut Window, &mut App)>; +type DropItemHandler = Rc, &mut Window, &mut App)>; + +/// What a skin needs to draw a tab group, and the callbacks it invokes rather +/// than reimplementing behavior. +#[derive(Clone)] +pub struct TabGroupContext { + node: NodeId, + panels: Rc<[Arc]>, + active_panel: Option>, + active_ix: usize, + zoomed: bool, + constraints: TabGroupConstraints, + draggable: bool, + panel_close_allowed: bool, + droppable: bool, + active_panel_closable: bool, + drop_indicator: Option, + on_select_tab: SelectTabHandler, + on_close: ClosePanelHandler, + on_toggle_zoom: ToggleZoomHandler, + on_drop_panel: DropPanelHandler, + on_drop_item: DropItemHandler, +} + +impl TabGroupContext { + pub(super) fn from_group(source: &TabGroup, cx: &App) -> Self { + let group = source.this.clone(); + + Self { + node: source.node, + panels: source.panels.clone(), + active_panel: source.active_panel(cx), + active_ix: source.active_ix, + zoomed: source.zoomed, + constraints: source.constraints, + active_panel_closable: source.is_closable(cx), + draggable: source.draggable(cx), + panel_close_allowed: source.closable_panels(cx), + droppable: source.droppable(), + // A stale indicator would otherwise outlive a drag that was + // cancelled while hovering this group. + drop_indicator: cx + .has_active_drag() + .then_some(source.drop_indicator) + .flatten(), + on_select_tab: { + let group = group.clone(); + Rc::new(move |ix, window, cx| { + _ = group.update(cx, |group, cx| group.select_tab(ix, window, cx)); + }) + }, + on_close: { + let group = group.clone(); + Rc::new(move |panel, _, cx| { + _ = group.update(cx, |group, cx| group.close_panel(panel, cx)); + }) + }, + on_toggle_zoom: { + let group = group.clone(); + Rc::new(move |window, cx| { + _ = group.update(cx, |group, cx| group.toggle_zoom(window, cx)); + }) + }, + on_drop_panel: { + let group = group.clone(); + Rc::new(move |drag, ix, activate, _, cx| { + _ = group.update(cx, |group, cx| group.on_drop(&drag, ix, activate, cx)); + }) + }, + on_drop_item: Rc::new(move |item, placement, _, cx| { + _ = group.update(cx, |group, cx| group.emit_drag_drop(&item, placement, cx)); + }), + } + } + + /// The `Tabs` node this group mirrors, for a skin that needs to name the + /// group in a drag payload or a drop target. + pub fn node(&self) -> NodeId { + self.node + } + + /// Every panel in the group, in tab order — visible or not. A skin filters + /// with [`PanelView::visible`] when it draws. + pub fn panels(&self) -> &[Arc] { + &self.panels + } + + pub fn active_ix(&self) -> usize { + self.active_ix + } + + /// The panel on screen, which is the displayed tab unless that panel has + /// gone invisible. + pub fn active_panel(&self) -> Option<&Arc> { + self.active_panel.as_ref() + } + + pub fn drop_indicator(&self) -> Option { + self.drop_indicator + } + + pub fn is_zoomed(&self) -> bool { + self.zoomed + } + + pub fn is_collapsed(&self) -> bool { + self.constraints.is_collapsed() + } + + /// Whether the active panel can be closed. + pub fn is_closable(&self) -> bool { + self.active_panel_closable + } + + /// Whether `panel` can be closed from this group. Uses the same constraints + /// as [`TabGroup::close_panel`], including the panel's own `closable` flag. + pub fn is_panel_closable(&self, panel: PanelId, cx: &App) -> bool { + self.constraints.is_closable() + && self.panel_close_allowed + && self + .panels + .iter() + .any(|candidate| candidate.panel_id(cx) == panel && candidate.closable(cx)) + } + + pub fn is_locked(&self) -> bool { + self.constraints.is_locked() + } + + pub fn is_draggable(&self) -> bool { + self.draggable + } + + pub fn is_droppable(&self) -> bool { + self.droppable + } + + pub fn select_tab(&self, ix: usize, window: &mut Window, cx: &mut App) { + (self.on_select_tab)(ix, window, cx); + } + + pub fn close(&self, panel: PanelId, window: &mut Window, cx: &mut App) { + (self.on_close)(panel, window, cx); + } + + pub fn toggle_zoom(&self, window: &mut Window, cx: &mut App) { + (self.on_toggle_zoom)(window, cx); + } + + /// The drag payload for the tab at `ix`, for a skin wiring `on_drag` onto + /// its tabs. `None` when `ix` names no panel. + pub fn drag_panel(&self, ix: usize, cx: &App) -> Option { + self.panels + .get(ix) + .map(|panel| DragPanel::new(panel.panel_id(cx), self.node)) + } + + /// A panel dropped on the tab bar. `ix` names the slot it lands in, or + /// `None` to append; `activate` decides whether it becomes displayed. + pub fn drop_panel( + &self, + drag: DragPanel, + ix: Option, + activate: bool, + window: &mut Window, + cx: &mut App, + ) { + (self.on_drop_panel)(drag, ix, activate, window, cx); + } + + /// A host-owned drag dropped on the tab bar. `placement` is `None` to + /// merge into this group rather than split beside it. + pub fn drop_item( + &self, + item: AnyDrag, + placement: Option, + window: &mut Window, + cx: &mut App, + ) { + (self.on_drop_item)(item, placement, window, cx); + } +} + +/// Appearance for a tab group. Base draws none of it. +/// +/// The two frame hooks return the element itself rather than wrapping one, +/// because base attaches focus, keyboard grouping, and drop handling to the +/// very elements the skin styles: a wrapper would put the hit area and the +/// painted area on different elements. +#[allow(unused_variables)] +pub trait TabGroupRenderer: 'static { + /// The group's outer frame, which base tracks focus on. + /// + /// Identified rather than plain, so a skin can add a role, a tooltip, or + /// scroll tracking; `Stateful
` does everything base needs from it. + /// Appearance only. The group is laid out as a column that fills its slot + /// around whatever this returns, because a group that does not is a strip + /// of tabs with no content under it. + /// A renderer that needs the painted group bounds can attach `on_prepaint` + /// here and identify the group with [`TabGroupContext::node`]. + fn frame(&self, group: &TabGroupContext, window: &mut Window, cx: &mut App) -> Stateful
{ + div().id("tab-group") + } + + /// The region below the tab bar, which base installs drop handling on. + fn content_frame( + &self, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> Stateful
{ + div().id("tab-group-content") + } + + fn render_tab_bar( + &self, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> AnyElement; + + /// How the displayed panel's view is placed in the content region. The + /// skin receives the view rather than an element so it can decide how the + /// view is cached and stretched. + fn render_active_panel( + &self, + panel: AnyView, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> AnyElement { + panel.into_any_element() + } + + fn render_drop_indicator( + &self, + indicator: DropIndicator, + window: &mut Window, + cx: &mut App, + ) -> Option { + None + } + + fn render_empty( + &self, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> Option { + None + } +} + +/// The renderer a group starts with: the displayed panel and nothing else. +pub(crate) struct BareTabGroup; + +impl TabGroupRenderer for BareTabGroup { + fn render_tab_bar(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> AnyElement { + Empty.into_any_element() + } +} diff --git a/vendor/gpui-base/src/dock/tab_group/tests.rs b/vendor/gpui-base/src/dock/tab_group/tests.rs new file mode 100644 index 00000000..c7951718 --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/tests.rs @@ -0,0 +1,615 @@ +// Moved by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use std::cell::RefCell; + +use gpui::{Entity, TestAppContext, VisualTestContext, point, size}; + +use super::*; +use crate::dock::test_support::{PanelSignal, build_group, drain, drain_active, log_of, panel_id}; + +/// The node `build_group` gives its group. +fn group_node() -> NodeId { + NodeId::from_u64(1) +} + +fn elsewhere() -> NodeId { + NodeId::from_u64(7) +} + +fn content_bounds() -> Bounds { + Bounds { + origin: point(px(0.), px(0.)), + size: size(px(400.), px(300.)), + } +} + +/// Collect the group's outgoing intents as readable strings, so an +/// assertion reads as the sentence the event means. +fn record_events(group: &Entity, cx: &mut VisualTestContext) -> Rc>> { + let events: Rc>> = Rc::default(); + let sink = events.clone(); + cx.update(|_, cx| { + cx.subscribe(group, move |_, event: &TabGroupEvent, _| { + sink.borrow_mut().push(describe(event)); + }) + .detach(); + }); + events +} + +fn describe(event: &TabGroupEvent) -> String { + match event { + TabGroupEvent::Drop { + panel, + source, + target, + } => match target { + InsertTarget::Tabs { node, ix, activate } => format!( + "drop panel {} from {} into tabs {} at {:?} activate={}", + panel.as_u64(), + source.as_u64(), + node.as_u64(), + ix, + activate + ), + InsertTarget::Split { + node, placement, .. + } => format!( + "drop panel {} from {} split {} {}", + panel.as_u64(), + source.as_u64(), + node.as_u64(), + placement + ), + }, + TabGroupEvent::DragDrop { target, .. } => format!( + "item onto {} at {:?}", + target.node().as_u64(), + target.placement() + ), + TabGroupEvent::ClosePanel { panel } => format!("close {}", panel.as_u64()), + TabGroupEvent::ActiveChanged { ix } => format!("active {ix}"), + TabGroupEvent::ZoomIn { .. } => "zoom in".into(), + TabGroupEvent::ZoomOut { .. } => "zoom out".into(), + } +} + +#[gpui::test] +fn a_group_announces_its_first_panel_active(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a"], cx); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("a", true)]); + let _ = (group, panels); +} + +#[gpui::test] +fn selecting_another_tab_deactivates_then_activates(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + drain_active(&log); + + cx.update(|window, cx| { + group.update(cx, |group, cx| group.select_tab(1, window, cx)); + }); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("a", false), ("b", true)]); +} + +#[gpui::test] +fn the_context_snapshots_the_group_state(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + + let seen = cx.update(|_, cx| { + group.update(cx, |group, cx| { + let context = group.context(cx); + ( + context.panels().len(), + context.active_ix(), + context.is_zoomed(), + ) + }) + }); + + assert_eq!(seen, (2, 0, false)); +} + +/// A panel hidden while it holds the displayed slot is still the panel +/// told it is active; only what gets drawn falls back to a visible one. +#[gpui::test] +fn a_hidden_displayed_panel_is_still_the_active_one(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + cx.update(|_, cx| { + panels[0].update(cx, |panel, cx| panel.set_visible(false, cx)); + }); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("a", true)]); + assert_eq!( + cx.update(|_, cx| group.read(cx).active_panel(cx).unwrap().panel_name(cx)), + "b", + "rendering falls back to the first visible panel" + ); +} + +/// `on_removed` is a departing panel's deactivation signal, so the group +/// must not also announce `false` to it. +#[gpui::test] +fn a_panel_dropped_from_the_group_is_never_told_it_went_inactive(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + drain(&log); + + cx.update(|window, cx| { + let remaining: Vec> = vec![Arc::new(panels[1].clone())]; + group.update(cx, |group, cx| { + group.sync_from_tree(remaining, 0, window, cx) + }); + }); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("b", true)]); +} + +#[gpui::test] +fn selecting_a_tab_that_is_not_there_changes_nothing(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + drain_active(&log); + let events = record_events(&group, cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| group.select_tab(5, window, cx)); + }); + cx.run_until_parked(); + + assert_eq!(cx.update(|_, cx| group.read(cx).active_ix()), 0); + assert!(events.borrow().is_empty()); + assert!(drain_active(&log).is_empty()); +} + +#[gpui::test] +fn a_locked_group_can_be_neither_dragged_nor_dropped_into(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + let unlocked = cx.update(|_, cx| { + let context = group.read(cx).context(cx); + (context.is_draggable(), context.is_droppable()) + }); + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).dock_locked(true), + window, + cx, + ) + }) + }); + let locked = cx.update(|_, cx| { + let context = group.read(cx).context(cx); + (context.is_draggable(), context.is_droppable()) + }); + + assert_eq!(unlocked, (true, true)); + assert_eq!(locked, (false, false)); +} + +/// Zoom retains the same native reorder and drop affordances. +#[gpui::test] +fn a_zoomed_group_keeps_tab_drag_and_drop(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx); + group.set_zoomed(true, window, cx); + }) + }); + + assert!(cx.update(|_, cx| group.read(cx).context(cx).is_droppable())); + assert!(cx.update(|_, cx| group.read(cx).context(cx).is_draggable())); + assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_locked())); +} + +/// Dragging the last visible panel out of the only group would leave the +/// dock empty and undroppable, so it is refused. +#[gpui::test] +fn the_only_groups_last_visible_panel_cannot_be_dragged_out(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(true), window, cx) + }) + }); + let alone = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + let beside_others = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); + + assert!(!alone); + assert!(beside_others); +} + +#[gpui::test] +fn a_panel_from_another_group_lands_as_one_move(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); + cx.update(|_, cx| { + group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); + }); + cx.run_until_parked(); + + assert_eq!( + *events.borrow(), + vec!["drop panel 99 from 7 into tabs 1 at None activate=true"] + ); +} + +#[gpui::test] +fn dropping_a_panel_back_onto_its_own_group_is_ignored(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + let events = record_events(&group, cx); + + let panel = panel_id(&panels[0], cx); + let drag = DragPanel::new(panel, group_node()); + cx.update(|_, cx| { + group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); + }); + cx.run_until_parked(); + + assert!(events.borrow().is_empty()); +} + +#[gpui::test] +fn a_hovering_split_turns_a_drop_into_a_split(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Right), + drag.drag_session_id(), + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + group.on_drop(&drag, None, true, cx); + }); + }); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec!["drop panel 99 from 7 split 1 Right"]); +} + +/// The tab bar reports the slot a drop landed on, and a slot always means +/// "into these tabs" however the content area had resolved the cursor. +#[gpui::test] +fn a_tab_slot_overrides_the_hovering_split(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Right), + drag.drag_session_id(), + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + group.on_drop(&drag, Some(0), true, cx); + }); + }); + cx.run_until_parked(); + + assert_eq!( + *events.borrow(), + vec!["drop panel 99 from 7 into tabs 1 at Some(0) activate=true"] + ); +} + +/// A lone panel splitting out of its own group would empty that group and +/// refill it, which is no move at all. +#[gpui::test] +fn a_lone_panel_cannot_split_out_of_its_own_group(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(panel_id(&panels[0], cx), group_node()); + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Right), + drag.drag_session_id(), + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + group.on_drop(&drag, None, true, cx); + }); + }); + cx.run_until_parked(); + + assert!(events.borrow().is_empty()); +} + +#[gpui::test] +fn the_placeholder_replays_only_when_the_target_moves(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let bounds = content_bounds(); + let source = DropPlaceholderBounds::new(point(px(10.), px(10.)), size(px(96.), px(30.))); + + let sync = |placement: Option, cx: &mut VisualTestContext| { + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder(bounds, placement, 42, source, cx); + group.drop_indicator.unwrap() + }) + }) + }; + + let first = sync(Some(Placement::Left), cx); + let again = sync(Some(Placement::Left), cx); + let moved = sync(Some(Placement::Right), cx); + + assert_eq!(first.epoch(), 0); + assert_eq!(first.from(), source, "the first run flies in from the drag"); + assert_eq!(again.epoch(), 0, "an unchanged target keeps animating"); + assert_eq!(again.from(), source); + assert_eq!(moved.epoch(), 1, "a moved target replays from where it was"); + assert_eq!(moved.from(), first.to()); + assert_eq!( + moved.to(), + DropPlaceholderBounds::for_placement(bounds, Some(Placement::Right)) + ); +} + +/// The indicator is hit state, not a latch: a drag cancelled while +/// hovering must not leave the placeholder painted. +#[gpui::test] +fn the_indicator_is_withheld_when_no_drag_is_in_flight(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + + let (stored, published) = cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Top), + 42, + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + ( + group.drop_indicator.is_some(), + group.context(cx).drop_indicator().is_some(), + ) + }) + }); + + assert!(stored); + assert!(!published); +} + +#[gpui::test] +fn a_host_drag_reports_the_group_and_the_edge_it_resolved(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.emit_drag_drop(&AnyDrag::new(7u32), Some(Placement::Bottom), cx) + }); + }); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec!["item onto 1 at Some(Bottom)"]); +} + +#[gpui::test] +fn closing_asks_the_container_rather_than_editing_the_group(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + let events = record_events(&group, cx); + let panel = panel_id(&panels[1], cx); + + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.close_panel(panel, cx); + // A panel that is not a member is not this group's to close. + group.close_panel(PanelId::from_u64(4242), cx); + }); + }); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec![format!("close {}", panel.as_u64())]); + assert_eq!( + cx.update(|_, cx| group.read(cx).panels().len()), + 2, + "the group still holds both panels until the container edits the tree" + ); +} + +#[gpui::test] +fn zooming_toggles_and_tells_the_displayed_panel(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); + cx.run_until_parked(); + cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec!["zoom in", "zoom out"]); + assert!(!cx.update(|_, cx| group.read(cx).is_zoomed())); + assert_eq!( + drain(&log) + .into_iter() + .filter(|(_, signal)| matches!(signal, PanelSignal::Zoomed(_))) + .collect::>(), + vec![ + ("a", PanelSignal::Zoomed(true)), + ("a", PanelSignal::Zoomed(false)) + ], + "the old TabPanel sent this to itself, where the default no-op swallowed it" + ); +} + +/// `Dock::new` marks a dock's last group unclosable so the dock cannot be +/// emptied out from under itself. +#[gpui::test] +fn a_group_the_container_sealed_shut_refuses_to_close(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + let events = record_events(&group, cx); + let panel = panel_id(&panels[0], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).closable(false), + window, + cx, + ); + group.close_panel(panel, cx); + }) + }); + cx.run_until_parked(); + + assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_closable())); + assert!(events.borrow().is_empty()); +} + +/// The last visible panel of the only group has nowhere to go, so it is +/// not closable either — closing it would empty the region out from under +/// itself. Placing a sibling beside the group makes the same panel +/// closable again, which is what pins the reason to `alone` rather than to +/// something else the sealed default also forbids. +#[gpui::test] +fn the_only_groups_last_panel_is_not_closable(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(true), window, cx) + }) + }); + let alone = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + let beside_a_sibling = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); + + assert!(!alone); + assert!(beside_a_sibling); +} + +/// Collapsing takes the displayed panel off screen, and the active-state +/// contract counts that as no panel being displayed. +#[gpui::test] +fn collapsing_deactivates_the_displayed_panel_and_expanding_restores_it(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + assert_eq!(drain_active(&log), vec![("a", true)]); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).collapsed(true), + window, + cx, + ) + }) + }); + cx.run_until_parked(); + assert_eq!(drain_active(&log), vec![("a", false)]); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + cx.run_until_parked(); + assert_eq!(drain_active(&log), vec![("a", true)]); +} + +mod rendering; +mod selection; + +#[gpui::test] +fn dock_membership_changes_keep_only_live_panel_observations(cx: &mut TestAppContext) { + use crate::dock::{DockArea, DockPlacement, test_support::TestPanel}; + use std::cell::Cell; + + let (area, cx) = + cx.add_window_view(|window, cx| DockArea::new("observed-dock", None, window, cx)); + let (survivor, removed, notifications, _observation) = cx.update(|window, cx| { + let survivor = TestPanel::new("survivor", cx); + let removed = TestPanel::new("removed", cx); + area.update(cx, |area, cx| { + for panel in [&survivor, &removed] { + area.add_panel(panel.clone(), DockPlacement::Center, None, window, cx); + } + }); + // The panel received the group handle through Panel::on_added_to. + let group = survivor + .read(cx) + .group + .as_ref() + .and_then(WeakEntity::upgrade) + .unwrap(); + let notifications = Rc::new(Cell::new(0)); + let observed = notifications.clone(); + let observation = cx.observe(&group, move |_, _| observed.set(observed.get() + 1)); + (survivor, removed, notifications, observation) + }); + + cx.update(|window, cx| { + area.update(cx, |area, cx| { + area.remove_panel(removed.clone(), window, cx) + }); + }); + cx.run_until_parked(); + notifications.set(0); + cx.update(|_, cx| removed.update(cx, |_, cx| cx.notify())); + assert_eq!(notifications.get(), 0); + cx.update(|_, cx| survivor.update(cx, |_, cx| cx.notify())); + assert_eq!(notifications.get(), 1); +} diff --git a/vendor/gpui-base/src/dock/tab_group/tests/rendering.rs b/vendor/gpui-base/src/dock/tab_group/tests/rendering.rs new file mode 100644 index 00000000..310151cd --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/tests/rendering.rs @@ -0,0 +1,259 @@ +// Moved by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use super::super::*; +use super::record_events; +use crate::dock::test_support::log_of; +use gpui::{ + AnyElement, AnyView, AppContext as _, Div, Entity, Modifiers, MouseButton, Stateful, + StatefulInteractiveElement as _, TestAppContext, VisualTestContext, div, point, size, +}; +use std::cell::RefCell; + +/// Where `RecordingRenderer` puts its content frame. Deliberately not the +/// window's own origin or size, so a listener on the outer frame would +/// report different bounds. +fn skin_content() -> Bounds { + Bounds { + origin: point(px(100.), px(50.)), + size: size(px(400.), px(300.)), + } +} + +/// A skin that records which hooks base calls, and lays its two frames out +/// at known coordinates so a test can tell them apart by hit geometry. +struct RecordingRenderer { + calls: Rc>>, +} + +impl RecordingRenderer { + fn saw(&self, call: &'static str) { + self.calls.borrow_mut().push(call); + } +} + +impl TabGroupRenderer for RecordingRenderer { + fn frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ + self.saw("frame"); + div().id("skin-frame").relative().size_full() + } + + fn content_frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ + self.saw("content_frame"); + div() + .id("skin-content") + .absolute() + .left(skin_content().origin.x) + .top(skin_content().origin.y) + .w(skin_content().size.width) + .h(skin_content().size.height) + } + + fn render_tab_bar(&self, group: &TabGroupContext, _: &mut Window, cx: &mut App) -> AnyElement { + self.saw("tab_bar"); + div() + .id("skin-tab") + .absolute() + .left(px(0.)) + .top(px(0.)) + .w(px(80.)) + .h(px(24.)) + .when_some(group.drag_panel(0, cx), |this, drag| { + this.on_drag(drag, |drag, offset, _, cx| { + drag.set_drag_offset(offset); + cx.new(|_| drag.clone()) + }) + }) + .into_any_element() + } + + fn render_active_panel( + &self, + panel: AnyView, + _: &TabGroupContext, + _: &mut Window, + _: &mut App, + ) -> AnyElement { + self.saw("active_panel"); + panel.into_any_element() + } + + fn render_empty(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Option { + self.saw("empty"); + None + } + + fn render_drop_indicator( + &self, + _: DropIndicator, + _: &mut Window, + _: &mut App, + ) -> Option { + self.saw("drop_indicator"); + None + } +} + +fn build_skinned_group<'a>( + names: &[&'static str], + cx: &'a mut TestAppContext, +) -> ( + Entity, + Rc>>, + &'a mut VisualTestContext, +) { + let calls: Rc>> = Rc::default(); + let renderer = Rc::new(RecordingRenderer { + calls: calls.clone(), + }); + let (group, cx) = cx.add_window_view(|window, cx| { + TabGroup::new(NodeId::from_u64(1), window, cx).with_renderer(renderer) + }); + + let names = names.to_vec(); + let log = log_of(); + cx.update(|window, cx| { + let views: Vec> = names + .iter() + .map(|name| { + Arc::new(crate::dock::test_support::TestPanel::logging( + name, &log, cx, + )) as _ + }) + .collect(); + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx); + group.sync_from_tree(views, 0, window, cx); + }); + }); + cx.run_until_parked(); + calls.borrow_mut().clear(); + + (group, calls, cx) +} + +/// Press on the skin's tab, start the drag, and move into the right-hand +/// third of `skin_content()`. +fn drag_from_the_tab_into_the_content(cx: &mut VisualTestContext) { + cx.simulate_mouse_down( + point(px(20.), px(10.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.), px(14.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(450.), px(200.)), + MouseButton::Left, + Modifiers::none(), + ); +} + +/// The composition contract every later renderer copies: which hooks base +/// calls, and in what order. +#[gpui::test] +fn the_renderer_composes_frame_then_tab_bar_then_content(cx: &mut TestAppContext) { + let (_group, calls, cx) = build_skinned_group(&["a"], cx); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + + assert_eq!( + *calls.borrow(), + vec!["frame", "tab_bar", "content_frame", "active_panel"], + "the tab bar is a sibling of the content, not a child of it" + ); +} + +/// With nothing to display base asks for the empty element instead of the +/// active panel, and never for both. +#[gpui::test] +fn an_empty_group_asks_the_renderer_for_its_empty_state(cx: &mut TestAppContext) { + let (_group, calls, cx) = build_skinned_group(&[], cx); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + + assert_eq!( + *calls.borrow(), + vec!["frame", "tab_bar", "content_frame", "empty"] + ); +} + +/// The drop listeners must sit on the content frame, not the outer frame: +/// a drag over the group resolves against the content frame's own bounds, +/// which the skin — not base — decides. +#[gpui::test] +fn the_content_frame_is_what_a_drag_is_measured_against(cx: &mut TestAppContext) { + let (group, calls, cx) = build_skinned_group(&["a", "b"], cx); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + drag_from_the_tab_into_the_content(cx); + + let indicator = cx + .update(|_, cx| group.read(cx).drop_indicator) + .expect("the content frame's drag-move listener ran"); + + assert_eq!( + indicator.bounds(), + skin_content(), + "measured against the content frame, not the full-size outer frame" + ); + assert_eq!(indicator.placement(), Some(Placement::Right)); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + calls.borrow().contains(&"drop_indicator"), + "a published indicator is handed to the renderer to draw" + ); +} + +/// A drop landing on the content frame reports a move the container can +/// apply, and clears the hover state behind it. +#[gpui::test] +fn dropping_on_the_content_frame_reports_the_move(cx: &mut TestAppContext) { + let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); + let events = record_events(&group, cx); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + drag_from_the_tab_into_the_content(cx); + cx.simulate_mouse_up( + point(px(450.), px(200.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.run_until_parked(); + + assert_eq!(events.borrow().len(), 1, "got {:?}", events.borrow()); + assert!( + events.borrow()[0].ends_with("split 1 Right"), + "got {:?}", + events.borrow() + ); + assert!(cx.update(|_, cx| group.read(cx).drop_indicator.is_none())); +} + +/// A real drag over a locked group must resolve nothing: base installs no +/// drop handling on one, so the placement is never computed and the layout +/// tree is never asked to move anything. +#[gpui::test] +fn a_drag_over_a_locked_group_resolves_nothing(cx: &mut TestAppContext) { + let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).dock_locked(true), + window, + cx, + ) + }) + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + drag_from_the_tab_into_the_content(cx); + + assert!( + cx.update(|_, cx| group.read(cx).drop_indicator.is_none()), + "a locked group installs no drag-move listener, so nothing resolved" + ); +} diff --git a/vendor/gpui-base/src/dock/tab_group/tests/selection.rs b/vendor/gpui-base/src/dock/tab_group/tests/selection.rs new file mode 100644 index 00000000..69726bb4 --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/tests/selection.rs @@ -0,0 +1,126 @@ +// Added by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use std::{ + cell::Cell, + io::Write as _, + rc::Rc, + time::{Duration, Instant}, +}; + +use gpui::{TestAppContext, VisualTestContext}; + +use crate::dock::{ + DockArea, DockLayout, DockPlacement, PaneRef, PanelId, TabGroup, + test_support::{Log, TestPanel, drain, drain_active, log_of}, +}; + +fn open_dock<'a>( + names: impl IntoIterator, + log: &Log, + cx: &'a mut TestAppContext, +) -> ( + gpui::Entity, + Vec>, + &'a mut VisualTestContext, +) { + let (area, cx) = + cx.add_window_view(|window, cx| DockArea::new("tab-selection", None, window, cx)); + let panels = cx.update(|window, cx| { + let panels: Vec<_> = names + .into_iter() + .map(|name| TestPanel::logging(name, log, cx)) + .collect(); + let layout = panels + .iter() + .cloned() + .fold(DockLayout::tabs(), DockLayout::panel); + area.update(cx, |area, cx| area.set_center(layout, window, cx)); + panels + }); + cx.run_until_parked(); + (area, panels, cx) +} + +#[gpui::test] +fn a_panel_visibility_change_still_invalidates_its_group_after_selection(cx: &mut TestAppContext) { + let log = log_of(); + let (area, panels, cx) = open_dock(["first", "second"], &log, cx); + drain(&log); + let second = PanelId::from(panels[1].entity_id()); + let group = cx.read(|cx| { + panels[1] + .read(cx) + .group + .as_ref() + .and_then(|group| group.upgrade()) + .unwrap() + }); + cx.update(|window, cx| area.update(cx, |area, cx| area.select_panel(second, window, cx))); + cx.run_until_parked(); + assert_eq!(drain_active(&log), [("first", false), ("second", true)]); + + let invalidated = Rc::new(Cell::new(false)); + let _observation = cx.update(|_, cx| { + let invalidated = invalidated.clone(); + cx.observe(&group, move |_: gpui::Entity, _| { + invalidated.set(true) + }) + }); + cx.update(|_, cx| panels[1].update(cx, |panel, cx| panel.set_visible(false, cx))); + cx.run_until_parked(); + assert!(invalidated.get()); + assert_eq!( + cx.read(|cx| group.read(cx).active_panel(cx).unwrap().panel_name(cx)), + "first" + ); + assert!(drain_active(&log).is_empty()); +} + +#[gpui::test] +#[ignore = "release profile of native dock selection and deferred active-state delivery"] +fn measure_selecting_a_panel_in_a_large_dock(cx: &mut TestAppContext) { + let size = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(256usize), |value| value.parse()) + .unwrap(); + assert!(size > 1); + let log = log_of(); + let (area, panels, cx) = open_dock(std::iter::repeat_n("tab", size), &log, cx); + drain(&log); + let ids: Vec<_> = panels + .iter() + .map(|panel| PanelId::from(panel.entity_id())) + .collect(); + let mut selection = [Duration::ZERO; 301]; + let mut settled = [Duration::ZERO; 301]; + for (step, (selection, settled)) in selection.iter_mut().zip(&mut settled).enumerate() { + let ix = (step + 1) % size; + let started = Instant::now(); + cx.update(|window, cx| area.update(cx, |area, cx| area.select_panel(ids[ix], window, cx))); + *selection = started.elapsed(); + cx.run_until_parked(); + *settled = started.elapsed(); + assert_eq!(drain_active(&log), [("tab", false), ("tab", true)]); + } + cx.read(|cx| { + let layout = area.read(cx).layout(DockPlacement::Center).unwrap(); + let node = layout + .find_node(layout.find_panel_node(ids[0]).unwrap()) + .unwrap(); + let PaneRef::Tabs { panels, active_ix } = node.kind() else { + panic!("expected a tab group"); + }; + assert_eq!(panels, ids); + assert_eq!(active_ix, selection.len() % size); + }); + selection.sort_unstable(); + settled.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "tabs={size} selection_p50={:?} selection_p95={:?} settled_p50={:?} settled_p95={:?}", + selection[150], + selection[285], + settled[150], + settled[285], + ) + .unwrap(); +} diff --git a/vendor/gpui-base/src/frame_loop.rs b/vendor/gpui-base/src/frame_loop.rs new file mode 100644 index 00000000..4f7fcec8 --- /dev/null +++ b/vendor/gpui-base/src/frame_loop.rs @@ -0,0 +1,114 @@ +// Nocterm: drive continuous interactions from the window's frame clock. +use std::{ + cell::Cell, + rc::{Rc, Weak}, + time::Duration, +}; + +use gpui::{App, Context, WeakEntity, Window}; + +/// A cancellable next-frame loop owned by a view or gesture. +/// +/// The callback receives elapsed time and returns whether to request another +/// frame. It is responsible for invalidating only the content it changes. +#[derive(Default)] +pub struct FrameLoop(Option>>); + +impl FrameLoop { + pub fn is_active(&self) -> bool { + self.0.as_ref().is_some_and(|running| running.get()) + } + + pub fn stop(&mut self) { + self.0 = None; + } + + pub fn start( + &mut self, + window: &Window, + cx: &Context, + tick: impl Fn(&mut T, Duration, &mut Window, &mut Context) -> bool + 'static, + ) { + if self.is_active() { + return; + } + let running = Rc::new(Cell::new(true)); + let mut previous = cx.background_executor().now(); + let clock = move |cx: &App| { + let now = cx.background_executor().now(); + now.saturating_duration_since(std::mem::replace(&mut previous, now)) + }; + next( + window, + Rc::downgrade(&running), + cx.weak_entity(), + clock, + tick, + ); + self.0 = Some(running); + } +} + +fn next( + window: &Window, + active: Weak>, + entity: WeakEntity, + mut clock: impl FnMut(&App) -> Duration + 'static, + tick: impl Fn(&mut T, Duration, &mut Window, &mut Context) -> bool + 'static, +) { + window.on_next_frame(move |window, cx| { + if !active.upgrade().is_some_and(|running| running.get()) { + return; + } + let elapsed = clock(cx); + let again = entity.update(cx, |entity, cx| tick(entity, elapsed, window, cx)); + let Some(running) = active.upgrade() else { + return; + }; + if matches!(again, Ok(true)) && running.get() { + next(window, active, entity, clock, tick); + } else { + running.set(false); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{AppContext as _, Empty, TestAppContext}; + + #[gpui::test] + fn frame_loop_tracks_elapsed_time_and_cancels_pending_callbacks(cx: &mut TestAppContext) { + let window = cx.add_window(|_, _| Empty); + let intervals = cx.update(|cx| cx.new(|_| Vec::new())); + let mut frames = FrameLoop::default(); + let start = |frames: &mut FrameLoop, cx: &mut TestAppContext| { + window + .update(cx, |_, window, cx| { + intervals.update(cx, |_, cx| { + frames.start(window, cx, |intervals, elapsed, _, _| { + intervals.push(elapsed); + true + }); + }); + }) + .unwrap(); + }; + let frame = |ms, cx: &mut TestAppContext| { + cx.executor().advance_clock(Duration::from_millis(ms)); + window + .update(cx, |_, window, cx| window.simulate_next_frame(cx)) + .unwrap(); + }; + start(&mut frames, cx); + frame(5, cx); + frame(11, cx); + frames.stop(); + start(&mut frames, cx); + frame(8, cx); + frames.stop(); + frame(20, cx); + cx.update(|cx| assert_eq!(intervals.read(cx), &[5, 11, 8].map(Duration::from_millis))); + } +} diff --git a/vendor/gpui-base/src/input/base/element.rs b/vendor/gpui-base/src/input/base/element.rs index 5c79ba96..1b6d535b 100644 --- a/vendor/gpui-base/src/input/base/element.rs +++ b/vendor/gpui-base/src/input/base/element.rs @@ -1,3 +1,4 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. use crate::input::{InputExtras as _, InputModeKind}; use gpui::Corners; use gpui::Half; @@ -22,6 +23,7 @@ use crate::{ use super::{ InputBaseState, RangeDecorationStyle, TextDecoration, + highlight_shape::{SelectionHighlight, frame_outline_points, outline_path}, layout::{LastLayout, WhitespaceIndicators}, mode::LayoutMode, }; @@ -716,15 +718,8 @@ impl TextElement { bounds: &Bounds, ) -> Option> { let corners = Self::layout_range_corners(&range, last_layout)?; - let points = frame_outline_points(&corners); let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); - let mut builder = gpui::PathBuilder::fill(); - builder.move_to(origin + *points.first()?); - for point in points.iter().skip(1) { - builder.line_to(origin + *point); - } - builder.close(); - builder.build().ok() + outline_path(&corners, origin) } /// Project a buffer range through the visible (non-folded) shaped lines. @@ -921,14 +916,19 @@ impl TextElement { bounds: &mut Bounds, window: &mut Window, cx: &mut App, - ) -> Vec> { + ) -> Vec { let state = self.state.read(cx); if !state.focus_handle.is_focused(window) { return vec![]; } let active_id = state.active_selection().id; - let mut paths = Vec::new(); + let mut highlights = Vec::new(); + let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); + let highlight = |range| { + let corners = Self::layout_range_corners(&range, last_layout)?; + SelectionHighlight::new(&corners, origin, window.scale_factor()) + }; for selection in state.selections.iter() { let is_active = selection.id == active_id; @@ -976,25 +976,17 @@ impl TextElement { .take_while(|s| s.range().start < range.end) { if start < span.range().start { - paths.extend(Self::layout_match_range( - start..span.range().start, - last_layout, - bounds, - )); + highlights.extend(highlight(start..span.range().start)); } start = span.range().end.max(start); } } if start < range.end { - paths.extend(Self::layout_match_range( - start..range.end, - last_layout, - bounds, - )); + highlights.extend(highlight(start..range.end)); } } - paths + highlights } /// Calculate the visible range of lines in the viewport. @@ -2194,7 +2186,7 @@ pub(super) struct PrepaintState { cursor_scroll_offset: Point, /// row index (zero based), no wrap, same line as the cursor. current_row: Option, - selection_paths: Vec>, + selection_highlights: Vec, hover_highlight_path: Option>, search_match_paths: Vec<(Path, bool)>, document_color_paths: Vec<(Path, Hsla)>, @@ -2272,40 +2264,6 @@ fn print_points_as_svg_path( } } -fn frame_outline_points(corners: &[Corners>]) -> Vec> { - let rects = corners - .iter() - .map(|corners| (corners.top_left, corners.bottom_right)) - .collect::>(); - let mut points = Vec::with_capacity(rects.len() * 4); - let first = rects[0]; - let last = rects[rects.len() - 1]; - points.push(first.0); - points.push(point(first.1.x, first.0.y)); - for pair in rects.windows(2) { - let current = pair[0]; - let next = pair[1]; - points.push(current.1); - points.push(point(next.1.x, current.1.y)); - points.push(point(next.1.x, next.1.y)); - } - if points.last() != Some(&last.1) { - points.push(last.1); - } - points.push(point(last.0.x, last.1.y)); - for pair in rects.windows(2).rev() { - let current = pair[1]; - let next = pair[0]; - points.push(point(current.0.x, current.0.y)); - points.push(point(next.0.x, current.0.y)); - points.push(point(next.0.x, next.0.y)); - } - if points.last() != points.first() { - points.push(points[0]); - } - points -} - fn pad_frame_corners( corners: &[Corners>], horizontal_padding: Pixels, @@ -2768,7 +2726,7 @@ impl Element for TextElement { .map(|info| info.bounds); let search_match_paths = self.layout_search_matches(&last_layout, &mut bounds, cx); - let selection_paths = self.layout_selections(&last_layout, &mut bounds, window, cx); + let selection_highlights = self.layout_selections(&last_layout, &mut bounds, window, cx); let hover_highlight_path = self.layout_hover_highlight(&last_layout, &mut bounds, cx); let document_color_paths = self.layout_document_colors(&document_colors, &last_layout, &bounds, cx); @@ -2862,7 +2820,7 @@ impl Element for TextElement { cursor_infos, cursor_scroll_offset, current_row, - selection_paths, + selection_highlights, search_match_paths, hover_highlight_path, hover_definition_hitbox, @@ -3020,8 +2978,8 @@ impl Element for TextElement { } } - for path in prepaint.selection_paths.drain(..) { - window.paint_path(path, editor_style.selection); + for highlight in prepaint.selection_highlights.drain(..) { + highlight.paint(editor_style.selection, window); } // Paint hover highlight diff --git a/vendor/gpui-base/src/input/base/highlight_shape.rs b/vendor/gpui-base/src/input/base/highlight_shape.rs new file mode 100644 index 00000000..a867bebf --- /dev/null +++ b/vendor/gpui-base/src/input/base/highlight_shape.rs @@ -0,0 +1,89 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{Bounds, Corners, Hsla, Path, Pixels, Point, Window, fill, point}; + +/// The fill for a visible selection, in shaped text coordinates. +pub(super) enum SelectionHighlight { + Rect(Bounds), + Outline(Path), +} + +impl SelectionHighlight { + pub(super) fn new( + corners: &[Corners>], + origin: Point, + scale_factor: f32, + ) -> Option { + if let [one] = corners { + let left = one.top_left.x.min(one.top_right.x); + let right = one.top_left.x.max(one.top_right.x); + let rect = Bounds::from_corners( + origin + point(left, one.top_left.y), + origin + point(right, one.bottom_right.y), + ); + // GPUI snaps solid quads to device pixels. Keep partial coverage + // for a nonzero shape narrower than one device pixel. + if f32::from(rect.size.width) * scale_factor >= 1. + && f32::from(rect.size.height) * scale_factor >= 1. + { + return Some(Self::Rect(rect)); + } + } + outline_path(corners, origin).map(Self::Outline) + } + + pub(super) fn paint(self, color: Hsla, window: &mut Window) { + match self { + Self::Rect(bounds) => window.paint_quad(fill(bounds, color)), + Self::Outline(path) => window.paint_path(path, color), + } + } +} + +pub(super) fn outline_path( + corners: &[Corners>], + origin: Point, +) -> Option> { + let points = frame_outline_points(corners); + let mut builder = gpui::PathBuilder::fill(); + builder.move_to(origin + *points.first()?); + for point in points.iter().skip(1) { + builder.line_to(origin + *point); + } + builder.close(); + builder.build().ok() +} + +pub(super) fn frame_outline_points(corners: &[Corners>]) -> Vec> { + let rects = corners + .iter() + .map(|corners| (corners.top_left, corners.bottom_right)) + .collect::>(); + let mut points = Vec::with_capacity(rects.len() * 4); + let first = rects[0]; + let last = rects[rects.len() - 1]; + points.push(first.0); + points.push(point(first.1.x, first.0.y)); + for pair in rects.windows(2) { + let current = pair[0]; + let next = pair[1]; + points.push(current.1); + points.push(point(next.1.x, current.1.y)); + points.push(point(next.1.x, next.1.y)); + } + if points.last() != Some(&last.1) { + points.push(last.1); + } + points.push(point(last.0.x, last.1.y)); + for pair in rects.windows(2).rev() { + let current = pair[1]; + let next = pair[0]; + points.push(point(current.0.x, current.0.y)); + points.push(point(next.0.x, current.0.y)); + points.push(point(next.0.x, next.0.y)); + } + if points.last() != points.first() { + points.push(points[0]); + } + points +} diff --git a/vendor/gpui-base/src/input/base/state.rs b/vendor/gpui-base/src/input/base/state.rs index 4b8651ea..3e74172b 100644 --- a/vendor/gpui-base/src/input/base/state.rs +++ b/vendor/gpui-base/src/input/base/state.rs @@ -4533,7 +4533,14 @@ impl Render for InputBaseState { .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move)) .on_scroll_wheel(window.listener_for(&entity, InputBaseState::on_scroll_wheel)) .when(self.is_multi_line() && !self.disabled, |this| { - this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify())) + let alt = window.modifiers().alt; + this.on_modifiers_changed(cx.listener( + move |_, event: &gpui::ModifiersChangedEvent, _, cx| { + if event.modifiers.alt != alt { + cx.notify(); + } + }, + )) }) .when(!self.disabled, |this| { if self.is_multi_line() && window.modifiers().alt { diff --git a/vendor/gpui-base/src/input/mod.rs b/vendor/gpui-base/src/input/mod.rs index bb2ae494..06da6480 100644 --- a/vendor/gpui-base/src/input/mod.rs +++ b/vendor/gpui-base/src/input/mod.rs @@ -1,3 +1,4 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. //! Text input: the shared editing engine and the three states built on it. //! //! Nothing here should be `pub` unless it is reachable from outside the crate. @@ -28,6 +29,8 @@ mod display_map; mod editor; #[path = "base/element.rs"] mod element; +#[path = "base/highlight_shape.rs"] +mod highlight_shape; #[path = "editor/highlighting.rs"] mod highlighting; #[path = "editor/indent.rs"] diff --git a/vendor/gpui-base/src/lib.rs b/vendor/gpui-base/src/lib.rs index 1978efc4..e878c4c7 100644 --- a/vendor/gpui-base/src/lib.rs +++ b/vendor/gpui-base/src/lib.rs @@ -4,6 +4,8 @@ //! colors, sizing, and motion belong to applications or the //! `gpui-component` façade. +// Nocterm: export a window-frame driver for continuous interactions. + mod accordion; pub mod actions; mod alert_dialog; @@ -25,6 +27,7 @@ pub mod dock; mod element_ext; mod event; mod focus_trap; +mod frame_loop; mod geometry; mod global_state; mod history; @@ -111,6 +114,7 @@ pub use event::{InteractiveElementExt, OngoingScrollExt}; pub use focus_trap::FocusTrapElement; #[doc(hidden)] pub use focus_trap::active_focus_trap; +pub use frame_loop::FrameLoop; pub use geometry::*; pub use global_state::{DeferredPopover, GlobalState}; pub use history::History; diff --git a/vendor/gpui-base/src/resizable/mod.rs b/vendor/gpui-base/src/resizable/mod.rs index b536c2d1..e9eb7986 100644 --- a/vendor/gpui-base/src/resizable/mod.rs +++ b/vendor/gpui-base/src/resizable/mod.rs @@ -1,8 +1,8 @@ +// Nocterm: redistribute split sizes in place during a resize. + use std::ops::Range; -use gpui::{ - Along, App, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px, -}; +use gpui::{Along, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px}; mod panel; mod resize_handle; @@ -263,7 +263,7 @@ impl ResizableState { panel.size_range.clone() } - fn sync_real_panel_sizes(&mut self, _: &App) { + fn sync_real_panel_sizes(&mut self) { for (i, panel) in self.panels.iter().enumerate() { self.sizes[i] = panel.bounds.size.along(self.axis); } @@ -282,68 +282,61 @@ impl ResizableState { _: &mut Window, cx: &mut Context, ) { - let old_sizes = self.sizes.clone(); - - let mut ix = ix; // Only resize the left panels. - if ix >= old_sizes.len() - 1 { + if ix >= self.sizes.len().saturating_sub(1) { return; } - let container_size = self.container_size(); - self.sync_real_panel_sizes(cx); - let move_changed = size - old_sizes[ix]; + let old_size = self.sizes[ix]; + let move_changed = size - old_size; if move_changed == px(0.) { + self.sync_real_panel_sizes(); return; } + let container_size = self.container_size(); let size_range = self.panel_size_range(ix); let new_size = size.clamp(size_range.start, size_range.end); - let is_expand = move_changed > px(0.); - let main_ix = ix; - let mut new_sizes = old_sizes.clone(); + let mut ix = ix; + self.sizes[ix] = new_size; - if is_expand { - let mut changed = new_size - old_sizes[ix]; - new_sizes[ix] = new_size; + if move_changed > px(0.) { + let mut changed = new_size - old_size; - while changed > px(0.) && ix < old_sizes.len() - 1 { + while changed > px(0.) && ix < self.sizes.len() - 1 { ix += 1; let size_range = self.panel_size_range(ix); - let available_size = (new_sizes[ix] - size_range.start).max(px(0.)); + let available_size = (self.sizes[ix] - size_range.start).max(px(0.)); let to_reduce = changed.min(available_size); - new_sizes[ix] -= to_reduce; + self.sizes[ix] -= to_reduce; changed -= to_reduce; } } else { let mut changed = new_size - size; - new_sizes[ix] = new_size; while changed > px(0.) && ix > 0 { ix -= 1; let size_range = self.panel_size_range(ix); - let available_size = (new_sizes[ix] - size_range.start).max(px(0.)); + let available_size = (self.sizes[ix] - size_range.start).max(px(0.)); let to_reduce = changed.min(available_size); changed -= to_reduce; - new_sizes[ix] -= to_reduce; + self.sizes[ix] -= to_reduce; } - new_sizes[main_ix + 1] += old_sizes[main_ix] - size - changed; + self.sizes[main_ix + 1] += old_size - size - changed; } // If total size exceeds container size, adjust the main panel - let total_size: Pixels = new_sizes.iter().map(|s| s.as_f32()).sum::().into(); + let total_size: Pixels = self.sizes.iter().map(|s| s.as_f32()).sum::().into(); if total_size > container_size { let overflow = total_size - container_size; - new_sizes[main_ix] = (new_sizes[main_ix] - overflow).max(size_range.start); + self.sizes[main_ix] = (self.sizes[main_ix] - overflow).max(size_range.start); } - for (i, _) in old_sizes.iter().enumerate() { - let size = new_sizes[i]; - self.panels[i].size = Some(size); + for (panel, &size) in self.panels.iter_mut().zip(&self.sizes) { + panel.size = Some(size); } - self.sizes = new_sizes; cx.notify(); } @@ -396,6 +389,8 @@ pub(crate) struct ResizablePanelState { #[cfg(test)] mod tests { + mod drag_work; + use std::{ cell::{Cell, RefCell}, rc::Rc, diff --git a/vendor/gpui-base/src/resizable/tests/drag_work.rs b/vendor/gpui-base/src/resizable/tests/drag_work.rs new file mode 100644 index 00000000..d1b145f2 --- /dev/null +++ b/vendor/gpui-base/src/resizable/tests/drag_work.rs @@ -0,0 +1,98 @@ +// Nocterm: characterize repeated divider input and measure split redistribution. + +use super::*; +use std::{hint::black_box, time::Instant}; + +#[gpui::test] +fn repeated_pointer_positions_and_reversal_preserve_rendered_split_sizes(cx: &mut TestAppContext) { + let (cx, state, resizes) = harness(cx); + let boundary = cx.debug_bounds("second-panel").unwrap().left(); + cx.simulate_mouse_down( + point(boundary - px(2.), px(50.)), + MouseButton::Left, + Modifiers::default(), + ); + cx.simulate_mouse_move( + point(boundary + px(10.), px(50.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + for (position, expected) in [(220., 220.), (220., 220.), (130., 130.), (60., 100.)] { + cx.simulate_mouse_move( + point(px(position), px(50.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + cx.debug_bounds("first-panel").unwrap().size.width, + px(expected) + ); + } + cx.simulate_mouse_up( + point(px(60.), px(50.)), + MouseButton::Left, + Modifiers::default(), + ); + state.read_with(cx, |state, _| { + assert_eq!(state.sizes(), &[px(100.), px(300.)]) + }); + assert_eq!(resizes.get(), 1); +} + +struct WideSplit { + state: gpui::Entity, + panels: usize, +} + +impl Render for WideSplit { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().w(px(self.panels as f32 * 300.)).h(px(100.)).child( + h_resizable("wide-split") + .with_state(&self.state) + .children((0..self.panels).map(|_| resizable_panel().size(px(300.)))), + ) + } +} + +#[gpui::test] +#[ignore = "manual CPU measurement of a rendered split's resize operation"] +fn measure_programmatic_panel_resizing(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_SPLIT_COUNT") + .map(|value| value.parse::().unwrap()) + .unwrap_or(16); + assert!(count >= 2); + let state = cx.update(|cx| cx.new(|_| ResizableState::default())); + let (_, cx) = cx.add_window_view({ + let state = state.clone(); + move |_, _| WideSplit { + state, + panels: count, + } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let mut samples = Vec::new(); + for _ in 0..101 { + samples.push(cx.update(|window, cx| { + state.update(cx, |state, cx| { + let start = Instant::now(); + for step in 0..256 { + let width = if step % 2 == 0 { 260. } else { 320. }; + state.resize_panel(0, black_box(px(width)), window, cx); + } + start.elapsed().as_nanos() as f64 / 256. + }) + })); + } + samples.sort_unstable_by(f64::total_cmp); + state.read_with(cx, |state, _| { + assert_eq!(state.sizes().len(), count); + assert_eq!(state.sizes()[0], px(320.)); + assert_eq!(state.sizes()[1], px(280.)); + }); + eprintln!( + "panels={count} resize_p50_ns={:.2} resize_p95_ns={:.2}", + samples[50], samples[95] + ); +} diff --git a/vendor/gpui-base/src/scrollbar.rs b/vendor/gpui-base/src/scrollbar.rs index 89eee2d5..06a0dff7 100644 --- a/vendor/gpui-base/src/scrollbar.rs +++ b/vendor/gpui-base/src/scrollbar.rs @@ -1,48 +1,37 @@ // Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. -use std::{cell::Cell, ops::Deref, panic::Location, rc::Rc}; + +use std::{ + cell::{Cell, RefCell}, + ops::Deref, + panic::Location, + rc::Rc, +}; use instant::{Duration, Instant}; -use crate::{ - AxisExt, - animation::{ease_in_cubic, ease_out_cubic}, - theme::ActiveTheme as _, -}; +use crate::AxisExt; use gpui::{ - Anchor, App, Axis, Background, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element, - ElementId, EntityId, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, - IntoElement, IsZero, LayoutId, ListState, MouseDownEvent, MouseMoveEvent, MouseUpEvent, - PaintQuad, Pixels, Point, Position, ScrollHandle, ScrollWheelEvent, Size, Style, - TouchDragEvent, TouchPhase, UniformListScrollHandle, Window, fill, point, - prelude::FluentBuilder, px, relative, size, + App, Axis, Bounds, ElementId, EntityId, IntoElement, ListState, Pixels, Point, ScrollHandle, + Size, UniformListScrollHandle, Window, point, px, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +mod appearance; +mod element; +mod motion; +mod redraw; + +pub use appearance::{ScrollbarStyles, ScrollbarThumbStyle, ScrollbarTrackStyle}; +pub use motion::{ScrollbarEntrance, ScrollbarMotion}; +use motion::{VisibilityAnimation, WidthAnimation}; +use redraw::FadeRedraw; + +#[cfg(test)] +mod tests; + /// The width of the scrollbar (THUMB_ACTIVE_INSET * 2 + THUMB_ACTIVE_WIDTH) const WIDTH: Pixels = px(4. * 2. + 8.); -const MIN_THUMB_SIZE: Pixels = px(48.); - -const THUMB_WIDTH: Pixels = px(6.); -const THUMB_RADIUS: Pixels = Pixels::ZERO; -const THUMB_INSET: Pixels = px(4.); - -const THUMB_ACTIVE_WIDTH: Pixels = px(8.); -const THUMB_ACTIVE_RADIUS: Pixels = Pixels::ZERO; -const THUMB_ACTIVE_INSET: Pixels = px(4.); - -/// How long visibility is held after the last activity, when the styled layer -/// projects no [`ScrollbarMotion`] of its own. -/// -/// This is a visibility hold rather than motion: without it [`ScrollbarMode::Scrolling`] -/// could never reveal the scrollbar. -const DEFAULT_IDLE: Duration = Duration::from_secs(2); - -fn clamp_thumb_radius(radius: Pixels, bounds: Bounds) -> Pixels { - radius - .min(bounds.size.width / 2.) - .min(bounds.size.height / 2.) -} /// Scrollbar show mode. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash, Default, JsonSchema)] @@ -164,7 +153,13 @@ impl ScrollbarHandle for ListState { #[doc(hidden)] #[derive(Debug, Clone)] -struct ScrollbarState(Rc>); +struct ScrollbarState(Rc); + +#[derive(Debug)] +struct ScrollbarRuntime { + inner: Cell, + fade_redraw: RefCell, +} #[doc(hidden)] #[derive(Debug, Clone, Copy)] @@ -188,350 +183,71 @@ struct ScrollbarStateInner { impl Default for ScrollbarState { fn default() -> Self { let now = Instant::now(); - Self(Rc::new(Cell::new(ScrollbarStateInner { - hovered_axis: None, - hovered_on_thumb: None, - dragged_axis: None, - drag_pos: point(px(0.), px(0.)), - last_scroll_offset: point(px(0.), px(0.)), - last_scroll_time: None, - last_update: now, - drag_update_scheduled: false, - drag_update_generation: 0, - idle_timer_scheduled: false, - visibility: VisibilityAnimation::hidden(now), - vertical_width: WidthAnimation::new(now), - horizontal_width: WidthAnimation::new(now), - }))) - } -} - -#[derive(Debug, Clone, Copy)] -struct ScalarTransition { - from: T, - target: T, - started_at: Instant, - duration: Duration, -} - -impl ScalarTransition { - fn settled(value: T, now: Instant) -> Self { - Self { - from: value, - target: value, - started_at: now, - duration: Duration::ZERO, - } - } - - fn sample(&self, now: Instant, interpolate: impl FnOnce(T, T, f32) -> T) -> (T, bool) { - if self.from == self.target || self.duration.is_zero() { - return (self.target, false); - } - let linear = now.saturating_duration_since(self.started_at).as_secs_f32() - / self.duration.as_secs_f32(); - if linear >= 1.0 { - (self.target, false) - } else { - ( - interpolate(self.from, self.target, linear.clamp(0.0, 1.0)), - true, - ) - } - } - - fn start(&mut self, from: T, target: T, duration: Duration, now: Instant) { - self.from = from; - self.target = target; - self.started_at = now; - self.duration = duration; - } - - fn settle(&mut self, target: T, now: Instant) { - self.start(target, target, Duration::ZERO, now); - } -} - -#[derive(Debug, Clone, Copy)] -struct WidthAnimation { - transition: ScalarTransition, - initialized: bool, -} - -impl WidthAnimation { - fn new(now: Instant) -> Self { - Self { - transition: ScalarTransition::settled(Pixels::ZERO, now), - initialized: false, - } - } - - fn sample(&self, now: Instant) -> (Pixels, bool) { - self.transition.sample(now, |from, target, linear| { - from + (target - from) * ease_out_cubic(linear) - }) - } - - /// Move toward `target` over `duration`. A zero duration adopts the target - /// immediately, which is how reduced motion and a motionless theme arrive here. - fn set_target(&mut self, target: Pixels, duration: Duration, now: Instant) -> (Pixels, bool) { - if duration.is_zero() || !self.initialized { - self.transition.settle(target, now); - self.initialized = true; - } else if self.transition.target != target { - let from = self.sample(now).0; - self.transition.start(from, target, duration, now); - } - self.sample(now) - } -} - -/// How a scrollbar becomes visible. -/// -/// The styled layer chooses the choreography; Base only plays it. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum ScrollbarEntrance { - /// Fade in without moving. - #[default] - Fade, - /// Slide in from the nearest edge while fading. - SlideAndFade, -} - -/// Motion tokens used by [`Scrollbar`]. -/// -/// Base installs no motion of its own: every transition duration defaults to -/// zero, so visibility and thumb width snap. Product timing belongs to the -/// styled layer, which projects it through [`crate::ScrollbarTheme`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct ScrollbarMotion { - idle: Duration, - enter: Duration, - exit: Duration, - expand: Duration, - entrance: ScrollbarEntrance, - thumb_hover_entrance: ScrollbarEntrance, -} - -impl Default for ScrollbarMotion { - fn default() -> Self { - Self { - idle: DEFAULT_IDLE, - enter: Duration::ZERO, - exit: Duration::ZERO, - expand: Duration::ZERO, - entrance: ScrollbarEntrance::Fade, - thumb_hover_entrance: ScrollbarEntrance::Fade, - } + Self(Rc::new(ScrollbarRuntime { + inner: Cell::new(ScrollbarStateInner { + hovered_axis: None, + hovered_on_thumb: None, + dragged_axis: None, + drag_pos: point(px(0.), px(0.)), + last_scroll_offset: point(px(0.), px(0.)), + last_scroll_time: None, + last_update: now, + drag_update_scheduled: false, + drag_update_generation: 0, + idle_timer_scheduled: false, + visibility: VisibilityAnimation::hidden(now), + vertical_width: WidthAnimation::new(now), + horizontal_width: WidthAnimation::new(now), + }), + fade_redraw: RefCell::default(), + })) } } -impl ScrollbarMotion { - /// How long visibility is held after the last scroll, drag, or hover. - pub fn with_idle(mut self, idle: Duration) -> Self { - self.idle = idle; - self - } - - /// How long the scrollbar takes to become fully visible. - pub fn with_enter(mut self, enter: Duration) -> Self { - self.enter = enter; - self - } - - /// How long the scrollbar takes to fade away once the idle hold expires. - pub fn with_exit(mut self, exit: Duration) -> Self { - self.exit = exit; - self - } - - /// How long the thumb takes to reach a new width. - pub fn with_expand(mut self, expand: Duration) -> Self { - self.expand = expand; - self - } - - /// Which entrance choreography to play. - pub fn with_entrance(mut self, entrance: ScrollbarEntrance) -> Self { - self.entrance = entrance; - self - } - - /// Which entrance choreography to play when hover reveals the thumb. - pub fn with_thumb_hover_entrance(mut self, entrance: ScrollbarEntrance) -> Self { - self.thumb_hover_entrance = entrance; - self - } - - pub fn idle(&self) -> Duration { - self.idle - } - - pub fn enter(&self) -> Duration { - self.enter - } - - pub fn exit(&self) -> Duration { - self.exit - } - - pub fn expand(&self) -> Duration { - self.expand - } - - pub fn entrance(&self) -> ScrollbarEntrance { - self.entrance - } - - pub fn thumb_hover_entrance(&self) -> ScrollbarEntrance { - self.thumb_hover_entrance - } +impl Deref for ScrollbarState { + type Target = Cell; - fn entrance_for(&self, mode: ScrollbarMode, thumb_hovered: bool) -> ScrollbarEntrance { - if mode.is_hover() && thumb_hovered { - self.thumb_hover_entrance - } else { - self.entrance - } + fn deref(&self) -> &Self::Target { + &self.0.inner } } -#[derive(Debug, Clone, Copy)] -struct VisibilityAnimation { - opacity: ScalarTransition, - position: ScalarTransition, - entrance: ScrollbarEntrance, -} - -#[derive(Debug, Clone, Copy)] -struct VisibilitySample { - opacity: f32, - position: f32, - running: bool, -} - -impl VisibilityAnimation { - fn hidden(now: Instant) -> Self { - Self { - opacity: ScalarTransition::settled(0.0, now), - position: ScalarTransition::settled(0.0, now), - entrance: ScrollbarEntrance::Fade, - } - } - - fn sample(&self, now: Instant) -> VisibilitySample { - let entering = - self.opacity.target > self.opacity.from || self.position.target > self.position.from; - let (opacity, opacity_running) = self.opacity.sample(now, |from, target, linear| { - let factor = if entering { - linear - } else { - ease_in_cubic(linear) - }; - from + (target - from) * factor - }); - let (position, position_running) = self.position.sample(now, |from, target, linear| { - let factor = if entering { - ease_out_cubic(linear) - } else { - ease_in_cubic(linear) - }; - from + (target - from) * factor - }); - - VisibilitySample { - opacity, - position, - running: opacity_running || position_running, - } - } - - /// Reverse or start a transition toward `visible`. - /// - /// The leg runs for `enter` or `exit` scaled by the distance still to cover, - /// so an interrupted transition keeps its speed instead of restarting. - fn set_visible( - &mut self, +impl ScrollbarState { + fn request_visibility_redraw( + &self, + running: bool, visible: bool, - entrance: ScrollbarEntrance, - enter: Duration, - exit: Duration, + remaining: Duration, now: Instant, + window: &mut Window, + cx: &mut App, ) { - let target = if visible { 1.0 } else { 0.0 }; - let full_duration = if visible { enter } else { exit }; - if full_duration.is_zero() { - // A motionless policy — reduced motion, an always-visible scrollbar, - // or a theme that projects no motion — adopts the target outright, - // even if a transition was in flight when the policy changed. - self.opacity.settle(target, now); - self.position.settle(target, now); - self.entrance = entrance; - return; - } - if self.opacity.target == target - && self.position.target == target - && self.entrance == entrance - { - return; - } - - let sample = self.sample(now); - let from_position = if visible && entrance == ScrollbarEntrance::Fade { - 1.0 + let mut fade = self.0.fade_redraw.borrow_mut(); + if running && !visible { + if fade.schedule(now, remaining, window, cx) { + let state = Rc::downgrade(&self.0); + let view = window.current_view(); + window.on_next_frame(move |_, cx| { + let Some(state) = state.upgrade() else { + return; + }; + if state + .fade_redraw + .borrow_mut() + .frame_delivered(cx.background_executor().now()) + { + cx.notify(view); + } + }); + } } else { - sample.position - }; - let distance = (target - sample.opacity) - .abs() - .max((target - from_position).abs()); - let duration = full_duration.mul_f32(distance); - self.opacity.start(sample.opacity, target, duration, now); - self.position.start(from_position, target, duration, now); - self.entrance = entrance; - } -} - -fn visibility_translation(axis: Axis, track_width: Pixels, progress: f32) -> Point { - let offset = track_width * (1.0 - progress.clamp(0.0, 1.0)); - if axis.is_vertical() { - point(offset, px(0.)) - } else { - point(px(0.), offset) - } -} - -fn wants_visible( - mode: ScrollbarMode, - is_hovered: bool, - is_dragging: bool, - last_scroll_time: Option, - idle: Duration, - now: Instant, -) -> bool { - mode.is_always() - || is_dragging - || (mode.is_hover() && is_hovered) - || last_scroll_time.is_some_and(|last| now.saturating_duration_since(last) < idle) -} - -fn tracks_thumb_hover(mode: ScrollbarMode, is_visible: bool) -> bool { - mode.is_hover() || is_visible -} - -fn hover_keeps_visible(mode: ScrollbarMode, is_hovered: bool, is_currently_visible: bool) -> bool { - is_hovered && (mode.is_hover() || (mode == ScrollbarMode::Scrolling && is_currently_visible)) -} - -impl Deref for ScrollbarState { - type Target = Rc>; - - fn deref(&self) -> &Self::Target { - &self.0 + fade.cancel(); + if running { + window.request_animation_frame(); + } + } } -} -impl ScrollbarState { fn notify_drag( &self, now: Instant, @@ -604,13 +320,11 @@ impl ScrollbarStateInner { state } - fn with_hovered_on_thumb(&self, axis: Option) -> Self { + fn with_hovered_on_thumb(&self, axis: Option, now: Instant) -> Self { let mut state = *self; state.hovered_on_thumb = axis; - if self.is_scrollbar_visible() { - if axis.is_some() { - state.last_scroll_time = Some(Instant::now()); - } + if axis.is_some() && self.is_scrollbar_visible(now) { + state.last_scroll_time = Some(now); } state } @@ -638,8 +352,8 @@ impl ScrollbarStateInner { state } - fn is_scrollbar_visible(&self) -> bool { - self.dragged_axis.is_some() || self.visibility.sample(Instant::now()).opacity > 0.0 + fn is_scrollbar_visible(&self, now: Instant) -> bool { + self.dragged_axis.is_some() || self.visibility.sample(now).opacity > 0.0 } } @@ -654,129 +368,6 @@ pub enum ScrollbarAxis { Both, } -/// Paint-only styles for a scrollbar track. -#[derive(Clone, Default)] -pub struct ScrollbarTrackStyle { - background: Option, - border: Option, - width: Option, -} - -impl ScrollbarTrackStyle { - pub fn bg(mut self, background: Hsla) -> Self { - self.background = Some(background); - self - } - - pub fn border_color(mut self, border: Hsla) -> Self { - self.border = Some(border); - self - } - - pub fn width(mut self, width: impl Into) -> Self { - self.width = Some(width.into()); - self - } -} - -impl FluentBuilder for ScrollbarTrackStyle {} - -/// Paint-only styles for a scrollbar thumb. -#[derive(Clone, Default)] -pub struct ScrollbarThumbStyle { - background: Option, - width: Option, - inset: Option, - radius: Option, - min_length: Option, -} - -impl ScrollbarThumbStyle { - pub fn bg(mut self, background: impl Into) -> Self { - self.background = Some(background.into()); - self - } - - pub fn width(mut self, width: impl Into) -> Self { - self.width = Some(width.into()); - self - } - - pub fn inset(mut self, inset: impl Into) -> Self { - self.inset = Some(inset.into()); - self - } - - pub fn radius(mut self, radius: impl Into) -> Self { - self.radius = Some(radius.into()); - self - } - - pub fn min_length(mut self, min_length: impl Into) -> Self { - self.min_length = Some(min_length.into()); - self - } -} - -impl FluentBuilder for ScrollbarThumbStyle {} - -/// Typed paint styles supported by [`Scrollbar`]. -#[derive(Clone, Default)] -pub struct ScrollbarStyles { - track: ScrollbarTrackStyle, - track_hover: ScrollbarTrackStyle, - track_active: ScrollbarTrackStyle, - thumb: ScrollbarThumbStyle, - thumb_hover: ScrollbarThumbStyle, - thumb_active: ScrollbarThumbStyle, -} - -impl ScrollbarStyles { - pub fn track(mut self, build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle) -> Self { - self.track = build(self.track); - self - } - - pub fn track_hover( - mut self, - build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, - ) -> Self { - self.track_hover = build(self.track_hover); - self - } - - pub fn track_active( - mut self, - build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, - ) -> Self { - self.track_active = build(self.track_active); - self - } - - pub fn thumb(mut self, build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle) -> Self { - self.thumb = build(self.thumb); - self - } - - pub fn thumb_hover( - mut self, - build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, - ) -> Self { - self.thumb_hover = build(self.thumb_hover); - self - } - - pub fn thumb_active( - mut self, - build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, - ) -> Self { - self.thumb_active = build(self.thumb_active); - self - } -} - -impl FluentBuilder for ScrollbarStyles {} - impl From for ScrollbarAxis { fn from(axis: Axis) -> Self { match axis { @@ -960,214 +551,6 @@ impl Scrollbar { pub const fn width() -> Pixels { WIDTH } - - fn resolve_track( - &self, - cx: &App, - state: &ScrollbarTrackStyle, - global_state: &ScrollbarTrackStyle, - default_border: Hsla, - ) -> (Hsla, Hsla) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - ( - state - .background - .or(self.styles.track.background) - .or(global_state.background) - .or(global.track.background) - .unwrap_or_else(gpui::transparent_black), - state - .border - .or(self.styles.track.border) - .or(global_state.border) - .or(global.track.border) - .unwrap_or(default_border), - ) - } - - fn resolve_thumb( - &self, - cx: &App, - state: &ScrollbarThumbStyle, - global_state: &ScrollbarThumbStyle, - defaults: ScrollbarThumbStyle, - ) -> (Background, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - ( - state - .background - .or(self.styles.thumb.background) - .or(global_state.background) - .or(global.thumb.background) - .unwrap_or_else(|| defaults.background.unwrap()), - state - .width - .or(self.styles.thumb.width) - .or(global_state.width) - .or(global.thumb.width) - .unwrap_or_else(|| defaults.width.unwrap()), - state - .inset - .or(self.styles.thumb.inset) - .or(global_state.inset) - .or(global.thumb.inset) - .unwrap_or_else(|| defaults.inset.unwrap()), - state - .radius - .or(self.styles.thumb.radius) - .or(global_state.radius) - .or(global.thumb.radius) - .unwrap_or_else(|| defaults.radius.unwrap()), - state - .min_length - .or(self.styles.thumb.min_length) - .or(global_state.min_length) - .or(global.thumb.min_length) - .or(defaults.min_length) - .unwrap_or(MIN_THUMB_SIZE), - ) - } - - /// The thumb colour a scrollbar falls back to when nothing has overridden - /// it, taken from the active theme rather than fixed. - /// - /// It used to be literal black at these alphas. That reads as an ordinary - /// grey thumb on a light surface and as very nearly nothing at all on a - /// dark one, and no palette an application installed could change it: - /// `Theme` carries `scrollbar` beside `tokens` rather than derived from - /// them, so a theme swap moved every token except the ones the scrollbar - /// actually paints with. - /// - /// `foreground` is the token that already means "ink on this surface" and - /// already flips with the appearance, so on a light theme this stays within - /// a hair of the old constant and on a dark one it becomes visible. An - /// explicit `ScrollbarStyles` still wins: this is the bottom of the - /// cascade, not a new top of it. - fn thumb_default_background(cx: &App, alpha: f32) -> Background { - cx.theme().tokens.colors.foreground.alpha(alpha).into() - } - - fn thumb_defaults( - background: Background, - width: Pixels, - inset: Pixels, - radius: Pixels, - ) -> ScrollbarThumbStyle { - ScrollbarThumbStyle { - background: Some(background), - width: Some(width), - inset: Some(inset), - radius: Some(radius), - min_length: Some(MIN_THUMB_SIZE), - } - } - - fn style_for_active( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - let (track, border) = self.resolve_track( - cx, - &self.styles.track_active, - &global.track_active, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb_active, - &global.thumb_active, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.55), - THUMB_ACTIVE_WIDTH, - THUMB_ACTIVE_INSET, - THUMB_ACTIVE_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } - - fn style_for_hovered_thumb( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - let (track, border) = self.resolve_track( - cx, - &self.styles.track_active, - &global.track_active, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb_hover, - &global.thumb_hover, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.55), - THUMB_ACTIVE_WIDTH, - THUMB_ACTIVE_INSET, - THUMB_ACTIVE_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } - - fn style_for_hovered_bar( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - let (track, border) = self.resolve_track( - cx, - &self.styles.track_hover, - &global.track_hover, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb, - &global.thumb, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.35), - THUMB_WIDTH, - THUMB_INSET, - THUMB_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } - - fn style_for_normal( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - - let (track, border) = self.resolve_track( - cx, - &self.styles.track, - &global.track, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb, - &global.thumb, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.35), - THUMB_WIDTH, - THUMB_INSET, - THUMB_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } } impl IntoElement for Scrollbar { @@ -1178,33 +561,6 @@ impl IntoElement for Scrollbar { } } -#[doc(hidden)] -pub struct PrepaintState { - hitbox: Hitbox, - scrollbar_state: ScrollbarState, - states: Vec, -} - -#[doc(hidden)] -pub struct AxisPrepaintState { - axis: Axis, - bar_hitbox: Hitbox, - bounds: Bounds, - radius: Pixels, - bg: Hsla, - border: Hsla, - thumb_bounds: Bounds, - // Bounds of thumb to be rendered. - thumb_fill_bounds: Bounds, - thumb_bg: Background, - geometry: ThumbGeometry, - active_geometry: ThumbGeometry, - track_width: Pixels, - visibility_opacity: f32, - visibility_position: f32, - visibility_requested: bool, -} - /// The same longitudinal geometry drives painting, track clicks and dragging. /// `length` excludes the inset, while `travel` excludes the full logical thumb. #[derive(Clone, Copy)] @@ -1266,1638 +622,3 @@ impl ThumbGeometry { offset } } - -impl Element for Scrollbar { - type RequestLayoutState = (); - type PrepaintState = PrepaintState; - - fn id(&self) -> Option { - Some(self.id.clone()) - } - - fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _: Option<&GlobalElementId>, - _: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - let mut style = Style::default(); - style.position = Position::Absolute; - style.flex_grow = 1.0; - style.flex_shrink = 1.0; - style.size.width = relative(1.).into(); - style.size.height = relative(1.).into(); - - (window.request_layout(style, None, cx), ()) - } - - fn prepaint( - &mut self, - _: Option<&GlobalElementId>, - _: Option<&InspectorElementId>, - bounds: Bounds, - _: &mut Self::RequestLayoutState, - window: &mut Window, - cx: &mut App, - ) -> Self::PrepaintState { - let bounds = self.resolved_viewport_bounds(bounds); - let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { - window.insert_hitbox(bounds, HitboxBehavior::Normal) - }); - - let state = window - .use_state(cx, |_, _| ScrollbarState::default()) - .read(cx) - .clone(); - - let now = Instant::now(); - let base_theme = cx.theme(); - let mode = self.mode.unwrap_or(base_theme.scrollbar.mode()); - let motion = base_theme.scrollbar.motion(); - // Always-visible scrollbars skip visibility motion but still animate - // their activity width. Reduced motion snaps every channel. - let reduce_motion = cx.reduce_motion(); - let (enter, exit) = if !mode.is_always() && !reduce_motion { - (motion.enter(), motion.exit()) - } else { - (Duration::ZERO, Duration::ZERO) - }; - let expand = if reduce_motion { - Duration::ZERO - } else { - motion.expand() - }; - - let mut inner = state.get(); - let current_offset = self.scroll_handle.offset(); - if current_offset != inner.last_scroll_offset { - inner = inner.with_last_scroll(current_offset, Some(now)); - } - - let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some(); - let is_dragging = inner.dragged_axis.is_some(); - let is_currently_visible = inner.visibility.sample(now).opacity > 0.0; - let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible) - || wants_visible( - mode, - is_hovered, - is_dragging, - inner.last_scroll_time, - motion.idle(), - now, - ); - inner.visibility.set_visible( - visible, - motion.entrance_for(mode, inner.hovered_on_thumb.is_some()), - enter, - exit, - now, - ); - let visibility = inner.visibility.sample(now); - if visibility.running { - window.request_animation_frame(); - } - - if !is_hovered && !is_dragging { - if let Some(last_time) = inner.last_scroll_time { - let elapsed = now.saturating_duration_since(last_time); - if elapsed < motion.idle() && !inner.idle_timer_scheduled { - inner.idle_timer_scheduled = true; - let state = state.clone(); - let current_view = window.current_view(); - let next_delay = motion.idle() - elapsed; - window - .spawn(cx, async move |cx| { - cx.background_executor().timer(next_delay).await; - state.set(state.get().with_idle_timer_scheduled(false)); - cx.update(|_, cx| cx.notify(current_view)).ok(); - }) - .detach(); - } - } - } - state.set(inner); - - let mut states = vec![]; - let mut has_both = self.axis.is_both(); - let scroll_size = self - .scroll_size - .unwrap_or(self.scroll_handle.content_size()); - - for axis in self.axis.all().into_iter() { - let is_vertical = axis.is_vertical(); - let track_width = self - .styles - .track - .width - .or(cx.theme().scrollbar.styles().track.width) - .unwrap_or(WIDTH); - let (scroll_area_size, container_size, scroll_position) = if is_vertical { - ( - scroll_size.height, - hitbox.size.height, - self.scroll_handle.offset().y, - ) - } else { - ( - scroll_size.width, - hitbox.size.width, - self.scroll_handle.offset().x, - ) - }; - - // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible. - let margin_end = if has_both && !is_vertical { - track_width - } else { - px(0.) - }; - - // Hide scrollbar, if the scroll area is smaller than the container. - if scroll_area_size <= container_size { - has_both = false; - continue; - } - - let bounds = Bounds { - origin: if is_vertical { - point( - hitbox.origin.x + hitbox.size.width - track_width, - hitbox.origin.y, - ) - } else { - point( - hitbox.origin.x, - hitbox.origin.y + hitbox.size.height - track_width, - ) - }, - size: gpui::Size { - width: if is_vertical { - track_width - } else { - hitbox.size.width - }, - height: if is_vertical { - hitbox.size.height - } else { - track_width - }, - }, - }; - - let is_always_to_show = mode.is_always(); - let is_hover_to_show = mode.is_hover(); - let is_hovered_on_bar = state.get().hovered_axis == Some(axis); - let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis); - - let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) = - if state.get().dragged_axis == Some(axis) { - self.style_for_active(cx) - } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling) - && (is_hovered_on_bar || is_hovered_on_thumb) - { - if is_hovered_on_thumb { - self.style_for_hovered_thumb(cx) - } else { - self.style_for_hovered_bar(cx) - } - } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) { - if is_hovered_on_thumb { - self.style_for_hovered_thumb(cx) - } else { - self.style_for_hovered_bar(cx) - } - } else { - self.style_for_normal(cx) - }; - - let mut width_animation = if is_vertical { - state.get().vertical_width - } else { - state.get().horizontal_width - }; - let (animated_width, running) = width_animation.set_target(thumb_width, expand, now); - let mut updated = state.get(); - if is_vertical { - updated.vertical_width = width_animation; - } else { - updated.horizontal_width = width_animation; - } - state.set(updated); - thumb_width = animated_width; - if running { - window.request_animation_frame(); - } - - let origin = if is_vertical { - bounds.origin.y - } else { - bounds.origin.x - }; - let geometry = ThumbGeometry::new( - origin, - container_size, - scroll_area_size, - margin_end, - inset, - min_length, - ); - let (_, _, _, _, active_inset, _, active_min_length) = self.style_for_active(cx); - let active_geometry = ThumbGeometry::new( - origin, - container_size, - scroll_area_size, - margin_end, - active_inset, - active_min_length, - ); - let thumb_start = geometry.start(scroll_position) - origin; - - // The clickable area of the thumb - let thumb_length = geometry.length; - let thumb_bounds = if is_vertical { - Bounds::from_anchor_and_size( - Anchor::TopRight, - bounds.top_right() + point(-inset, thumb_start), - size(track_width, thumb_length), - ) - } else { - Bounds::from_anchor_and_size( - Anchor::BottomLeft, - bounds.bottom_left() + point(thumb_start, -inset), - size(thumb_length, track_width), - ) - }; - - // The actual render area of the thumb - let thumb_fill_bounds = if is_vertical { - Bounds::from_anchor_and_size( - Anchor::TopRight, - bounds.top_right() + point(-inset, thumb_start), - size(thumb_width, thumb_length), - ) - } else { - Bounds::from_anchor_and_size( - Anchor::BottomLeft, - bounds.bottom_left() + point(thumb_start, -inset), - size(thumb_length, thumb_width), - ) - }; - - let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { - window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal) - }); - - states.push(AxisPrepaintState { - axis, - bar_hitbox, - bounds, - radius, - bg: bar_bg, - border: bar_border, - thumb_bounds, - thumb_fill_bounds, - thumb_bg, - geometry, - active_geometry, - track_width, - visibility_opacity: visibility.opacity, - visibility_position: visibility.position, - visibility_requested: visible, - }) - } - - PrepaintState { - hitbox, - states, - scrollbar_state: state, - } - } - - fn paint( - &mut self, - _: Option<&GlobalElementId>, - _: Option<&InspectorElementId>, - _: Bounds, - _: &mut Self::RequestLayoutState, - prepaint: &mut Self::PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - let scrollbar_state = &prepaint.scrollbar_state; - let theme = cx.theme(); - let mode = self.mode.unwrap_or(theme.scrollbar.mode()); - let view_id = window.current_view(); - let hitbox_bounds = prepaint.hitbox.bounds; - let is_hover_to_show = mode.is_hover(); - - window.with_content_mask( - Some(ContentMask { - bounds: hitbox_bounds, - }), - |window| { - for state in prepaint.states.iter() { - let axis = state.axis; - let mut radius = state.radius; - if theme.tokens.radius.md.is_zero() { - radius = px(0.); - } - radius = clamp_thumb_radius(radius, state.thumb_fill_bounds); - let bounds = state.bounds; - let thumb_bounds = state.thumb_bounds; - let geometry = state.geometry; - let active_geometry = state.active_geometry; - let is_vertical = axis.is_vertical(); - let visibility_opacity = state.visibility_opacity; - let is_visible = state.visibility_requested || visibility_opacity > 0.0; - let translation = - visibility_translation(axis, state.track_width, state.visibility_position); - let painted_bounds = state.bounds + translation; - let painted_thumb_bounds = state.thumb_fill_bounds + translation; - let painted_track_bg = state.bg.opacity(visibility_opacity); - let painted_border = state.border.opacity(visibility_opacity); - let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity); - - window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox); - - window.paint_layer(hitbox_bounds, |cx| { - cx.paint_quad(fill(painted_bounds, painted_track_bg)); - - cx.paint_quad(PaintQuad { - bounds: painted_bounds, - corner_radii: (0.).into(), - background: gpui::transparent_black().into(), - border_widths: if is_vertical { - Edges { - top: px(0.), - right: px(0.), - bottom: px(0.), - left: px(0.), - } - } else { - Edges { - top: px(0.), - right: px(0.), - bottom: px(0.), - left: px(0.), - } - }, - border_color: painted_border, - border_style: BorderStyle::default(), - }); - - cx.paint_quad( - fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius), - ); - }); - - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - - move |event: &ScrollWheelEvent, phase, _, cx| { - if phase.bubble() && hitbox_bounds.contains(&event.position) { - if scroll_handle.offset() != state.get().last_scroll_offset { - state.set(state.get().with_last_scroll( - scroll_handle.offset(), - Some(Instant::now()), - )); - cx.notify(view_id); - } - } - } - }); - - // A thumb follows the finger, unlike content panning. Claim - // this touch before the window turns it into wheel deltas. - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); - move |event: &TouchDragEvent, phase, window, cx| { - if !phase.bubble() { - return; - } - if event.phase == TouchPhase::Started { - if !is_visible - || window.default_prevented() - || !thumb_bounds.contains(&event.start_position) - { - return; - } - scroll_handle.start_drag(); - state.set(state.get().with_drag_pos( - axis, - event.start_position - thumb_bounds.origin, - )); - } else if state.get().dragged_axis != Some(axis) { - return; - } - if event.phase != TouchPhase::Cancelled { - scroll_handle.set_offset(active_geometry.drag_offset( - axis, - event.position, - state.get().drag_pos, - scroll_handle.offset(), - )); - } - if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) { - scroll_handle.end_drag(); - state.set(state.get().with_unset_drag_pos(Instant::now())); - } - window.prevent_default(); - cx.stop_propagation(); - if event.phase == TouchPhase::Moved { - state.notify_drag( - Instant::now(), - max_fps_duration, - view_id, - window, - cx, - ); - } else { - cx.notify(view_id); - } - } - }); - - if is_visible { - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - - move |event: &MouseDownEvent, phase, _, cx| { - if phase.bubble() && bounds.contains(&event.position) { - cx.stop_propagation(); - - if thumb_bounds.contains(&event.position) { - // click on the thumb bar, set the drag position - let pos = event.position - thumb_bounds.origin; - - scroll_handle.start_drag(); - state.set(state.get().with_drag_pos(axis, pos)); - // Active styling can change the inset or minimum length. - // Keep the original grab point under the pointer on that frame. - scroll_handle.set_offset(active_geometry.drag_offset( - axis, - event.position, - pos, - scroll_handle.offset(), - )); - } else { - // click on the scrollbar, jump to the position - // Set the thumb bar center to the click position - let center = - point(geometry.length / 2., geometry.length / 2.); - scroll_handle.set_offset(geometry.drag_offset( - axis, - event.position, - center, - scroll_handle.offset(), - )); - } - - cx.notify(view_id); - } - } - }); - } - - window.on_mouse_event({ - let scroll_handle = self.scroll_handle.clone(); - let state = scrollbar_state.clone(); - let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); - - move |event: &MouseMoveEvent, _, window, cx| { - let mut notify = false; - // When is hover to show mode or it was visible, - // we need to update the hovered state and increase the last_scroll_time. - let need_hover_to_update = is_hover_to_show || is_visible; - // Update hovered state for scrollbar - if bounds.contains(&event.position) && need_hover_to_update { - let hover_changed = state.get().hovered_axis != Some(axis); - state.set(state.get().with_hovered(Some(axis), Instant::now())); - notify |= hover_changed; - } else if state.get().hovered_axis == Some(axis) { - state.set(state.get().with_hovered(None, Instant::now())); - notify = true; - } - - // Update hovered state for scrollbar thumb - if tracks_thumb_hover(mode, is_visible) - && thumb_bounds.contains(&event.position) - { - if state.get().hovered_on_thumb != Some(axis) { - state.set(state.get().with_hovered_on_thumb(Some(axis))); - notify = true; - } - } else { - if state.get().hovered_on_thumb == Some(axis) { - state.set(state.get().with_hovered_on_thumb(None)); - notify = true; - } - } - - // Move thumb position on dragging - if state.get().dragged_axis == Some(axis) && event.dragging() { - // Stop the event propagation to avoid selecting text or other side effects. - cx.stop_propagation(); - - let offset = active_geometry.drag_offset( - axis, - event.position, - state.get().drag_pos, - scroll_handle.offset(), - ); - if scroll_handle.offset() != offset { - // Coalesce rendering, never discard the newest pointer position. - scroll_handle.set_offset(offset); - notify = true; - } - if notify { - state.notify_drag( - Instant::now(), - max_fps_duration, - view_id, - window, - cx, - ); - } - return; - } - - if notify { - cx.notify(view_id); - } - } - }); - - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - - move |event: &MouseUpEvent, phase, _, cx| { - if phase.bubble() && state.get().dragged_axis == Some(axis) { - scroll_handle.set_offset(active_geometry.drag_offset( - axis, - event.position, - state.get().drag_pos, - scroll_handle.offset(), - )); - scroll_handle.end_drag(); - state.set(state.get().with_unset_drag_pos(Instant::now())); - cx.notify(view_id); - } - } - }); - } - }, - ); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use std::cell::{Cell, RefCell}; - - use gpui::{ - Context, Modifiers, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext, - VisualTestContext, div, - }; - - #[test] - fn thumb_radius_is_limited_by_its_actual_bounds() { - let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.))); - let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.))); - - assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.)); - assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.)); - assert_eq!( - clamp_thumb_radius(Pixels::ZERO, vertical_thumb), - Pixels::ZERO - ); - } - - /// Timing standing in for what a styled layer projects. Base itself ships - /// none of these; see [`motionless_base_snaps_every_transition`]. - const ENTER: Duration = Duration::from_millis(300); - const EXIT: Duration = Duration::from_millis(500); - const EXPAND: Duration = Duration::from_millis(300); - - #[test] - fn visibility_animation_uses_direction_specific_curves_and_durations() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - assert_eq!(animation.sample(start).opacity, 0.0); - let entering = animation.sample(start + ENTER / 2).position; - assert!(entering > 0.5, "ease-out must advance quickly"); - let entered = animation.sample(start + ENTER); - assert_eq!(entered.opacity, 1.0); - assert_eq!(entered.position, 1.0); - - animation.set_visible( - false, - ScrollbarEntrance::SlideAndFade, - ENTER, - EXIT, - start + ENTER, - ); - let exiting = animation.sample(start + ENTER + EXIT / 2).opacity; - assert!(exiting > 0.5, "ease-in must remain visible early in exit"); - assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0); - } - - #[test] - fn entrance_fades_linearly_while_position_eases_out() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - - let halfway = animation.sample(start + ENTER / 2); - assert!((halfway.opacity - 0.5).abs() < 0.001); - assert!(halfway.position > halfway.opacity); - } - - #[test] - fn fade_entrance_snaps_position_and_animates_opacity() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start); - - let initial = animation.sample(start); - assert_eq!(initial.opacity, 0.0); - assert_eq!(initial.position, 1.0); - let halfway = animation.sample(start + ENTER / 2); - assert!((halfway.opacity - 0.5).abs() < 0.001); - assert_eq!(halfway.position, 1.0); - } - - #[test] - fn active_visibility_adopts_a_changed_entrance_policy() { - let start = Instant::now(); - let halfway = start + ENTER / 2; - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - let before = animation.sample(halfway); - - animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway); - let after = animation.sample(halfway); - - assert_eq!( - after.opacity, before.opacity, - "policy changes must not flash" - ); - assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding"); - } - - #[test] - fn base_ships_no_motion_of_its_own() { - let motion = ScrollbarMotion::default(); - assert_eq!(motion.enter(), Duration::ZERO); - assert_eq!(motion.exit(), Duration::ZERO); - assert_eq!(motion.expand(), Duration::ZERO); - assert_eq!(motion.entrance(), ScrollbarEntrance::Fade); - assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade); - assert_eq!( - motion.idle(), - DEFAULT_IDLE, - "the visibility hold is behavior, not motion, and must stay usable" - ); - } - - #[test] - fn hover_mode_slides_only_when_the_thumb_is_hovered() { - let motion = ScrollbarMotion::default() - .with_entrance(ScrollbarEntrance::Fade) - .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade); - - assert_eq!( - motion.entrance_for(ScrollbarMode::Hover, false), - ScrollbarEntrance::Fade - ); - assert_eq!( - motion.entrance_for(ScrollbarMode::Hover, true), - ScrollbarEntrance::SlideAndFade - ); - assert_eq!( - motion.entrance_for(ScrollbarMode::Scrolling, true), - ScrollbarEntrance::Fade - ); - } - - #[test] - fn hidden_scrolling_mode_does_not_track_thumb_hover() { - assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false)); - assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true)); - assert!(tracks_thumb_hover(ScrollbarMode::Hover, false)); - } - - #[test] - fn visible_scrolling_mode_stays_visible_while_hovered() { - assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false)); - assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true)); - assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false)); - } - - #[test] - fn motionless_base_snaps_every_transition() { - let now = Instant::now(); - let motion = ScrollbarMotion::default(); - let mut visibility = VisibilityAnimation::hidden(now); - - visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now); - let shown = visibility.sample(now); - assert_eq!(shown.opacity, 1.0); - assert_eq!(shown.position, 1.0); - assert!(!shown.running, "a motionless theme must request no frames"); - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), shown.position), - Point::default() - ); - - visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now); - let hidden = visibility.sample(now); - assert_eq!(hidden.opacity, 0.0); - assert_eq!(hidden.position, 0.0); - assert!(!hidden.running); - - let mut width = WidthAnimation::new(now); - assert_eq!( - width.set_target(px(8.), motion.expand(), now), - (px(8.), false) - ); - } - - #[test] - fn a_zero_duration_settles_a_transition_already_in_flight() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - - // Reduced motion turns on midway through the entrance. - let midway = start + ENTER / 2; - animation.set_visible( - true, - ScrollbarEntrance::SlideAndFade, - Duration::ZERO, - Duration::ZERO, - midway, - ); - let settled = animation.sample(midway); - assert_eq!(settled.opacity, 1.0); - assert_eq!(settled.position, 1.0); - assert!(!settled.running); - } - - #[test] - fn thumb_expansion_animates_in_both_directions() { - let start = Instant::now(); - let mut animation = WidthAnimation::new(start); - assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false)); - - let (initial, running) = animation.set_target(px(8.), EXPAND, start); - assert_eq!(initial, px(6.)); - assert!(running); - let (expanded_halfway, _) = animation.sample(start + EXPAND / 2); - assert!(expanded_halfway > px(7.)); - - let reversal = start + EXPAND / 2; - let before = animation.sample(reversal).0; - let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal); - assert_eq!(after_reversal, before); - assert!(running); - assert_eq!(animation.sample(reversal + EXPAND).0, px(6.)); - } - - #[test] - fn reduced_motion_snaps_thumb_expansion() { - let now = Instant::now(); - let mut animation = WidthAnimation::new(now); - assert_eq!( - animation.set_target(px(8.), Duration::ZERO, now), - (px(8.), false) - ); - } - - #[test] - fn visibility_translation_moves_toward_the_nearest_edge() { - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), 0.0), - point(px(16.), px(0.)) - ); - assert_eq!( - visibility_translation(Axis::Horizontal, px(16.), 0.0), - point(px(0.), px(16.)) - ); - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), 1.0), - Point::default() - ); - } - - #[test] - fn visibility_animation_reverses_from_current_progress() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - let reversal_time = start + Duration::from_millis(60); - let before = animation.sample(reversal_time); - - animation.set_visible( - false, - ScrollbarEntrance::SlideAndFade, - ENTER, - EXIT, - reversal_time, - ); - let reversed = animation.sample(reversal_time); - assert_eq!(reversed.opacity, before.opacity); - assert_eq!(reversed.position, before.position); - let after = animation.sample(reversal_time + Duration::from_millis(10)); - assert!(after.opacity < before.opacity); - assert!(after.position < before.position); - } - - #[test] - fn always_hover_drag_and_recent_scroll_request_visibility() { - let now = Instant::now(); - let idle = DEFAULT_IDLE; - assert!(wants_visible( - ScrollbarMode::Always, - false, - false, - None, - idle, - now - )); - assert!(wants_visible( - ScrollbarMode::Hover, - true, - false, - None, - idle, - now - )); - assert!(wants_visible( - ScrollbarMode::Scrolling, - false, - true, - None, - idle, - now - )); - assert!(wants_visible( - ScrollbarMode::Scrolling, - false, - false, - Some(now - idle + Duration::from_millis(1)), - idle, - now, - )); - assert!(!wants_visible( - ScrollbarMode::Scrolling, - false, - false, - Some(now - idle), - idle, - now, - )); - - let mut settled = VisibilityAnimation::hidden(now - ENTER); - settled.set_visible( - true, - ScrollbarEntrance::SlideAndFade, - ENTER, - EXIT, - now - ENTER, - ); - assert!(!settled.sample(now).running, "idle hold must not animate"); - } - - #[test] - fn leaving_hover_starts_a_fresh_idle_hold() { - let entered_at = Instant::now(); - let left_at = entered_at + Duration::from_secs(5); - let state = ScrollbarState::default().get(); - - let hovered = state.with_hovered(Some(Axis::Vertical), entered_at); - assert_eq!(hovered.last_scroll_time, Some(entered_at)); - let left = hovered.with_hovered(None, left_at); - assert_eq!(left.last_scroll_time, Some(left_at)); - assert!(wants_visible( - ScrollbarMode::Hover, - false, - false, - left.last_scroll_time, - DEFAULT_IDLE, - left_at + DEFAULT_IDLE - Duration::from_millis(1), - )); - } - - #[test] - fn idle_boundary_starts_the_exit_without_a_jump() { - let activity = Instant::now(); - let exit_start = activity + DEFAULT_IDLE; - let mut animation = VisibilityAnimation::hidden(activity - ENTER); - animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER); - assert!(!wants_visible( - ScrollbarMode::Scrolling, - false, - false, - Some(activity), - DEFAULT_IDLE, - exit_start, - )); - - animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start); - let start = animation.sample(exit_start); - assert_eq!(start.opacity, 1.0); - assert_eq!(start.position, 1.0); - assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0); - } - - #[derive(Clone)] - struct TestHandle { - offset: Rc>>, - content_size: Size, - drag_starts: Rc>, - drag_ends: Rc>, - } - - impl TestHandle { - fn new(content_size: Size) -> Self { - Self { - offset: Rc::new(Cell::new(Point::default())), - content_size, - drag_starts: Rc::new(Cell::new(0)), - drag_ends: Rc::new(Cell::new(0)), - } - } - } - - impl ScrollbarHandle for TestHandle { - fn viewport_bounds(&self) -> Bounds { - Bounds::new(Point::default(), size(px(100.), px(100.))) - } - - fn offset(&self) -> Point { - self.offset.get() - } - - fn set_offset(&self, offset: Point) { - self.offset.set(offset); - } - - fn content_size(&self) -> Size { - self.content_size - } - - fn start_drag(&self) { - self.drag_starts.set(self.drag_starts.get() + 1); - } - - fn end_drag(&self) { - self.drag_ends.set(self.drag_ends.get() + 1); - } - } - - struct ScrollbarHarness { - handle: TestHandle, - axis: ScrollbarAxis, - mode: ScrollbarMode, - } - - impl Render for ScrollbarHarness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .relative() - .size(px(100.)) - .child(Scrollbar::new(&self.handle).axis(self.axis).mode(self.mode)) - } - } - - fn harness( - cx: &mut TestAppContext, - axis: ScrollbarAxis, - mode: ScrollbarMode, - content_size: Size, - ) -> (&mut VisualTestContext, TestHandle) { - let handle = TestHandle::new(content_size); - let (_, cx) = cx.add_window_view({ - let handle = handle.clone(); - move |_, _| ScrollbarHarness { handle, axis, mode } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - (cx, handle) - } - - #[test] - fn explicit_viewport_bounds_override_handle_bounds() { - let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.))); - let scrollbar = Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.)))) - .viewport_bounds(expected); - - assert_eq!( - scrollbar.resolved_viewport_bounds(Bounds::default()), - expected - ); - } - - #[test] - fn layout_viewport_uses_current_element_bounds() { - let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.))); - let scrollbar = - Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout(); - - assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected); - } - - #[test] - fn typed_styles_are_fluent_and_include_geometry() { - let track = gpui::hsla(0.1, 0.2, 0.3, 1.0); - let border = gpui::hsla(0.2, 0.3, 0.4, 1.0); - let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); - let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0); - let active = gpui::hsla(0.5, 0.6, 0.7, 1.0); - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())).styles(|styles| { - styles - .track(|style| { - style - .width(px(14.)) - .bg(track) - .border_color(border) - .when(false, |style| style.width(px(99.))) - }) - .thumb(|style| { - style - .width(px(7.)) - .inset(px(3.)) - .radius(px(3.5)) - .min_length(px(40.)) - .bg(thumb) - }) - .thumb_hover(|style| style.width(px(9.)).bg(hover)) - .thumb_active(|style| style.radius(px(4.5)).bg(active)) - }); - - assert_eq!(scrollbar.styles.track.background, Some(track)); - assert_eq!(scrollbar.styles.track.border, Some(border)); - assert_eq!(scrollbar.styles.track.width, Some(px(14.))); - assert!(scrollbar.styles.thumb.background.is_some()); - assert_eq!(scrollbar.styles.thumb.width, Some(px(7.))); - assert_eq!(scrollbar.styles.thumb.inset, Some(px(3.))); - assert_eq!(scrollbar.styles.thumb.radius, Some(px(3.5))); - assert_eq!(scrollbar.styles.thumb.min_length, Some(px(40.))); - assert!(scrollbar.styles.thumb_hover.background.is_some()); - assert_eq!(scrollbar.styles.thumb_hover.width, Some(px(9.))); - assert!(scrollbar.styles.thumb_active.background.is_some()); - assert_eq!(scrollbar.styles.thumb_active.radius, Some(px(4.5))); - } - - #[gpui::test] - fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) { - cx.update(|cx| { - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())); - - let light = gpui::hsla(0., 0., 0.04, 1.0); - crate::Theme::global_mut(cx).tokens.colors.foreground = light; - let (on_light, ..) = scrollbar.style_for_normal(cx); - - let dark = gpui::hsla(0., 0., 0.98, 1.0); - crate::Theme::global_mut(cx).tokens.colors.foreground = dark; - let (on_dark, ..) = scrollbar.style_for_normal(cx); - - assert_eq!(on_light, Background::from(light.alpha(0.35))); - assert_eq!(on_dark, Background::from(dark.alpha(0.35))); - // The point of the change: a thumb that never moved with the - // palette was invisible on one of the two surfaces. - assert_ne!(on_light, on_dark); - }); - } - - #[gpui::test] - fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) { - cx.update(|cx| { - let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0); - crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0); - - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) - .styles(|styles| styles.thumb(|style| style.bg(chosen))); - let (thumb, ..) = scrollbar.style_for_normal(cx); - - assert_eq!(thumb, Background::from(chosen)); - }); - } - - #[gpui::test] - fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) { - cx.update(|cx| { - let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0); - let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0); - let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); - - crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() - .with_mode(ScrollbarMode::Always) - .with_motion(ScrollbarMotion::default()) - .with_styles( - ScrollbarStyles::default() - .track(|style| style.width(px(13.)).bg(theme_track)) - .thumb(|style| style.width(px(7.)).bg(theme_thumb)), - ); - - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) - .styles(|styles| styles.thumb(|style| style.bg(instance_thumb))); - let (thumb, track, _, width, _, _, _) = scrollbar.style_for_normal(cx); - - assert_eq!(thumb, Background::from(instance_thumb)); - assert_eq!(track, theme_track); - assert_eq!(width, px(7.)); - assert_eq!(cx.theme().scrollbar.styles().track.width, Some(px(13.))); - }); - } - - #[gpui::test] - fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) { - cx.update(|cx| { - let handle = TestHandle::new(Size::default()); - let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling); - let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always); - - assert_eq!(scrolling.style_for_normal(cx).3, px(6.)); - assert_eq!(always.style_for_normal(cx).3, px(6.)); - }); - } - - #[gpui::test] - fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) { - cx.update(|cx| { - let handle = TestHandle::new(Size::default()); - for mode in [ - ScrollbarMode::Scrolling, - ScrollbarMode::Hover, - ScrollbarMode::Always, - ] { - let scrollbar = Scrollbar::new(&handle).mode(mode); - assert_eq!(scrollbar.style_for_normal(cx).3, px(6.)); - assert_eq!(scrollbar.style_for_hovered_bar(cx).3, px(6.)); - assert_eq!(scrollbar.style_for_hovered_thumb(cx).3, px(8.)); - } - }); - } - - #[gpui::test] - fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) { - let (cx, vertical) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Always, - size(px(100.), px(500.)), - ); - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert!(vertical.offset().y < px(0.)); - assert_eq!(vertical.offset().x, px(0.)); - } - - #[gpui::test] - fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) { - let (cx, horizontal) = harness( - cx, - ScrollbarAxis::Horizontal, - ScrollbarMode::Always, - size(px(500.), px(100.)), - ); - cx.simulate_click(point(px(80.), px(95.)), Modifiers::default()); - assert!(horizontal.offset().x < px(0.)); - assert_eq!(horizontal.offset().y, px(0.)); - } - - #[gpui::test] - fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Both, - ScrollbarMode::Always, - size(px(100.), px(100.)), - ); - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert_eq!(handle.offset(), Point::default()); - } - - #[gpui::test] - fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Hover, - size(px(100.), px(500.)), - ); - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert_eq!(handle.offset(), Point::default()); - } - - #[gpui::test] - fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Hover, - size(px(100.), px(500.)), - ); - cx.simulate_mouse_down( - point(px(95.), px(20.)), - MouseButton::Left, - Modifiers::default(), - ); - cx.simulate_mouse_move( - point(px(95.), px(70.)), - Some(MouseButton::Left), - Modifiers::default(), - ); - cx.simulate_mouse_up( - point(px(95.), px(70.)), - MouseButton::Left, - Modifiers::default(), - ); - - assert_eq!(handle.drag_starts.get(), 0); - assert_eq!(handle.drag_ends.get(), 0); - assert_eq!(handle.offset(), Point::default()); - } - - #[gpui::test] - fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Hover, - size(px(100.), px(500.)), - ); - // Base ships no motion, so the reveal is immediate. - cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default()); - cx.run_until_parked(); - - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert!(handle.offset().y < px(0.)); - } - - #[gpui::test] - fn drag_notifications_are_throttled_and_deliver_the_latest_offset(cx: &mut TestAppContext) { - let handle = TestHandle::new(size(px(100.), px(1000.))); - let (view, cx) = cx.add_window_view({ - let handle = handle.clone(); - move |_, _| ScrollbarHarness { - handle, - axis: ScrollbarAxis::Vertical, - mode: ScrollbarMode::Always, - } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - let observed = Rc::new(RefCell::new(Vec::new())); - let _subscription = cx.update(|_, cx| { - let observed = observed.clone(); - let handle = handle.clone(); - cx.observe(&view, move |_, _| { - observed.borrow_mut().push(handle.offset().y) - }) - }); - let state = ScrollbarState::default(); - let now = Instant::now(); - let interval = Duration::from_secs_f64(1. / 30.); - let mut inner = state.get().with_drag_pos(Axis::Vertical, Point::default()); - inner.last_update = now; - state.set(inner); - let update = |offset, elapsed, cx: &mut VisualTestContext| { - handle.set_offset(point(px(0.), px(offset))); - cx.update(|window, cx| { - state.notify_drag(now + elapsed, interval, view.entity_id(), window, cx) - }); - cx.run_until_parked(); - }; - update(-10., Duration::ZERO, cx); - cx.executor().advance_clock(Duration::from_millis(16)); - update(-20., Duration::from_millis(16), cx); - update(-30., Duration::from_millis(16), cx); - // Rendering at 120 Hz must not bypass the configured 30 Hz timer. - cx.update(|window, cx| { - window.simulate_next_frame(cx); - }); - cx.run_until_parked(); - assert!(observed.borrow().is_empty()); - cx.executor().advance_clock(Duration::from_millis(16)); - cx.run_until_parked(); - assert!(observed.borrow().is_empty()); - cx.executor().advance_clock(Duration::from_millis(2)); - cx.run_until_parked(); - assert_eq!( - *observed.borrow(), - vec![px(-30.)], - "one trailing notification must see the newest offset even when movement stops" - ); - - // A second burst gets its own interval, and release invalidates its timer. - let next = state.get().last_update; - handle.set_offset(point(px(0.), px(-40.))); - cx.update(|window, cx| state.notify_drag(next, interval, view.entity_id(), window, cx)); - cx.run_until_parked(); - state.set(state.get().with_unset_drag_pos(Instant::now())); - handle.set_offset(point(px(0.), px(-50.))); - cx.update(|_, cx| cx.notify(view.entity_id())); - assert_eq!(*observed.borrow(), vec![px(-30.), px(-50.)]); - cx.executor().advance_clock(interval); - cx.run_until_parked(); - assert_eq!( - *observed.borrow(), - vec![px(-30.), px(-50.)], - "release must not leave a stale trailing notification" - ); - } - - #[test] - fn full_track_thumb_does_not_reset_the_scroll_offset() { - let geometry = ThumbGeometry::new(px(20.), px(40.), px(500.), px(0.), px(4.), px(64.)); - let offset = point(px(0.), px(-100.)); - assert_eq!( - geometry.drag_offset( - Axis::Vertical, - point(px(0.), px(50.)), - point(px(0.), px(8.)), - offset - ), - offset - ); - } - - #[gpui::test] - fn repeated_touch_and_mouse_drags_keep_the_painted_grab_point(cx: &mut TestAppContext) { - struct Probe { - scrollbar: Scrollbar, - painted: Rc>>, - } - impl IntoElement for Probe { - type Element = Self; - fn into_element(self) -> Self { - self - } - } - impl Element for Probe { - type RequestLayoutState = (); - type PrepaintState = PrepaintState; - fn id(&self) -> Option { - Element::id(&self.scrollbar) - } - fn source_location(&self) -> Option<&'static Location<'static>> { - None - } - fn request_layout( - &mut self, - id: Option<&GlobalElementId>, - inspector: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, ()) { - self.scrollbar.request_layout(id, inspector, window, cx) - } - fn prepaint( - &mut self, - id: Option<&GlobalElementId>, - inspector: Option<&InspectorElementId>, - bounds: Bounds, - layout: &mut (), - window: &mut Window, - cx: &mut App, - ) -> PrepaintState { - let state = self - .scrollbar - .prepaint(id, inspector, bounds, layout, window, cx); - self.painted.set(state.states[0].thumb_fill_bounds); - state - } - fn paint( - &mut self, - id: Option<&GlobalElementId>, - inspector: Option<&InspectorElementId>, - bounds: Bounds, - layout: &mut (), - state: &mut PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - self.scrollbar - .paint(id, inspector, bounds, layout, state, window, cx); - } - } - struct Root { - handle: TestHandle, - painted: Rc>>, - axis: ScrollbarAxis, - viewport: Bounds, - } - impl Render for Root { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div().size(px(400.)).child(Probe { - scrollbar: Scrollbar::new(&self.handle) - .axis(self.axis) - .mode(ScrollbarMode::Always) - .viewport_bounds(self.viewport) - .styles(|style| { - style - .thumb(|style| style.inset(px(6.)).min_length(px(64.))) - .thumb_active(|style| style.inset(px(3.)).min_length(px(72.))) - }), - painted: self.painted.clone(), - }) - } - } - for touch in [true, false] { - for vertical in [true, false] { - for (origin, viewport_size, content_size) in [ - (Point::default(), 200., 1000.), - (point(px(30.), px(40.)), 240., 500.), - ] { - let handle = TestHandle::new(size(px(content_size), px(content_size))); - handle.set_offset(point(px(-100.), px(-100.))); - let painted = Rc::new(Cell::new(Bounds::default())); - let (_, cx) = cx.add_window_view({ - let handle = handle.clone(); - let painted = painted.clone(); - move |_, _| Root { - handle, - painted, - axis: if vertical { - ScrollbarAxis::Vertical - } else { - ScrollbarAxis::Both - }, - viewport: Bounds::new( - origin, - size(px(viewport_size), px(viewport_size)), - ), - } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - let initial = painted.get(); - let start = initial.center(); - let grab = if vertical { - start.y - initial.origin.y - } else { - start.x - initial.origin.x - }; - let axis_delta = |value| { - if vertical { - point(px(0.), px(value)) - } else { - point(px(value), px(0.)) - } - }; - let axis_value = - |point: Point| if vertical { point.y } else { point.x }; - let started_position = if touch { start + axis_delta(5.) } else { start }; - if touch { - cx.simulate_event(TouchDragEvent { - phase: TouchPhase::Started, - start_position: start, - position: started_position, - }); - } else { - cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); - } - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert!( - (axis_value(painted.get().origin) + grab - axis_value(started_position)) - .abs() - < px(0.1), - "starting must preserve the grab point and first displacement" - ); - let mut reference_offset = px(0.); - let mut offset_per_pixel = 0.; - for delta in [0., 24., -8., 32., -10., 8., 0.] { - let position = start + axis_delta(delta); - if touch { - cx.simulate_event(TouchDragEvent { - phase: TouchPhase::Moved, - start_position: start, - position, - }); - } else { - cx.simulate_mouse_move( - position, - Some(MouseButton::Left), - Modifiers::default(), - ); - } - cx.update(|window, cx| window.draw(cx).clear(cx)); - if delta == 0. { - reference_offset = axis_value(handle.offset()); - } - if delta == 24. { - offset_per_pixel = - (axis_value(handle.offset()) - reference_offset) / px(24.); - } - let actual = if vertical { - painted.get().origin.y + grab - } else { - painted.get().origin.x + grab - }; - let expected = if vertical { position.y } else { position.x }; - assert!( - (actual - expected).abs() < px(0.1), - "touch={touch} vertical={vertical} delta={delta}: painted grab {actual:?}, pointer {expected:?}" - ); - } - // Release contains a final displacement without an intervening move. - let expected_offset = reference_offset + px(12.) * offset_per_pixel; - if touch { - cx.simulate_event(TouchDragEvent { - phase: TouchPhase::Ended, - start_position: start, - position: start + axis_delta(12.), - }); - } else { - cx.simulate_mouse_up( - start + axis_delta(12.), - MouseButton::Left, - Modifiers::default(), - ); - } - assert!( - (axis_value(handle.offset()) - expected_offset).abs() < px(0.1), - "release must flush the last displacement" - ); - let released_offset = handle.offset(); - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert_eq!( - handle.offset(), - released_offset, - "leaving active styling must not scroll" - ); - } - } - } - } - - #[gpui::test] - fn touch_thumb_drag_moves_down_and_cancel_releases_handle(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Always, - size(px(100.), px(500.)), - ); - let start_position = point(px(95.), px(20.)); - for (phase, position) in [ - (TouchPhase::Started, start_position), - (TouchPhase::Moved, point(px(95.), px(45.))), - (TouchPhase::Cancelled, point(px(95.), px(45.))), - ] { - cx.simulate_event(TouchDragEvent { - phase, - start_position, - position, - }); - } - assert!( - handle.offset().y < px(0.), - "thumb down must scroll toward later content" - ); - assert_eq!(handle.offset().x, px(0.)); - assert_eq!(handle.drag_starts.get(), 1); - assert_eq!(handle.drag_ends.get(), 1); - } - - #[gpui::test] - fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Always, - size(px(100.), px(500.)), - ); - cx.simulate_mouse_down( - point(px(95.), px(20.)), - MouseButton::Left, - Modifiers::default(), - ); - cx.simulate_mouse_move( - point(px(95.), px(70.)), - Some(MouseButton::Left), - Modifiers::default(), - ); - cx.simulate_mouse_up( - point(px(95.), px(70.)), - MouseButton::Left, - Modifiers::default(), - ); - - assert_eq!(handle.drag_starts.get(), 1); - assert_eq!(handle.drag_ends.get(), 1); - } -} diff --git a/vendor/gpui-base/src/scrollbar/appearance.rs b/vendor/gpui-base/src/scrollbar/appearance.rs new file mode 100644 index 00000000..fff7f64b --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/appearance.rs @@ -0,0 +1,400 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use crate::theme::ActiveTheme as _; +use gpui::{App, Background, Bounds, Hsla, Pixels, prelude::FluentBuilder, px}; + +const MIN_THUMB_SIZE: Pixels = px(48.); + +const THUMB_WIDTH: Pixels = px(6.); +const THUMB_RADIUS: Pixels = Pixels::ZERO; +const THUMB_INSET: Pixels = px(4.); + +const THUMB_ACTIVE_WIDTH: Pixels = px(8.); +const THUMB_ACTIVE_RADIUS: Pixels = Pixels::ZERO; +const THUMB_ACTIVE_INSET: Pixels = px(4.); + +pub(super) fn clamp_thumb_radius(radius: Pixels, bounds: Bounds) -> Pixels { + radius + .min(bounds.size.width / 2.) + .min(bounds.size.height / 2.) +} + +/// Paint-only styles for a scrollbar track. +#[derive(Clone, Default)] +pub struct ScrollbarTrackStyle { + background: Option, + border: Option, + width: Option, +} + +impl ScrollbarTrackStyle { + pub fn bg(mut self, background: Hsla) -> Self { + self.background = Some(background); + self + } + + pub fn border_color(mut self, border: Hsla) -> Self { + self.border = Some(border); + self + } + + pub fn width(mut self, width: impl Into) -> Self { + self.width = Some(width.into()); + self + } +} + +impl FluentBuilder for ScrollbarTrackStyle {} + +/// Paint-only styles for a scrollbar thumb. +#[derive(Clone, Default)] +pub struct ScrollbarThumbStyle { + background: Option, + width: Option, + inset: Option, + radius: Option, + min_length: Option, +} + +impl ScrollbarThumbStyle { + pub fn bg(mut self, background: impl Into) -> Self { + self.background = Some(background.into()); + self + } + + pub fn width(mut self, width: impl Into) -> Self { + self.width = Some(width.into()); + self + } + + pub fn inset(mut self, inset: impl Into) -> Self { + self.inset = Some(inset.into()); + self + } + + pub fn radius(mut self, radius: impl Into) -> Self { + self.radius = Some(radius.into()); + self + } + + pub fn min_length(mut self, min_length: impl Into) -> Self { + self.min_length = Some(min_length.into()); + self + } +} + +impl FluentBuilder for ScrollbarThumbStyle {} + +/// Typed paint styles supported by [`Scrollbar`](super::Scrollbar). +#[derive(Clone, Default)] +pub struct ScrollbarStyles { + track: ScrollbarTrackStyle, + track_hover: ScrollbarTrackStyle, + track_active: ScrollbarTrackStyle, + thumb: ScrollbarThumbStyle, + thumb_hover: ScrollbarThumbStyle, + thumb_active: ScrollbarThumbStyle, +} + +impl ScrollbarStyles { + pub fn track(mut self, build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle) -> Self { + self.track = build(self.track); + self + } + + pub fn track_hover( + mut self, + build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, + ) -> Self { + self.track_hover = build(self.track_hover); + self + } + + pub fn track_active( + mut self, + build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, + ) -> Self { + self.track_active = build(self.track_active); + self + } + + pub fn thumb(mut self, build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle) -> Self { + self.thumb = build(self.thumb); + self + } + + pub fn thumb_hover( + mut self, + build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, + ) -> Self { + self.thumb_hover = build(self.thumb_hover); + self + } + + pub fn thumb_active( + mut self, + build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, + ) -> Self { + self.thumb_active = build(self.thumb_active); + self + } +} + +impl FluentBuilder for ScrollbarStyles {} + +impl ScrollbarStyles { + pub(super) fn track_width(&self, cx: &App) -> Pixels { + self.track + .width + .or(cx.theme().scrollbar.styles().track.width) + .unwrap_or(super::WIDTH) + } + + fn resolve_track( + &self, + cx: &App, + state: &ScrollbarTrackStyle, + global_state: &ScrollbarTrackStyle, + default_border: Hsla, + ) -> (Hsla, Hsla) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + ( + state + .background + .or(self.track.background) + .or(global_state.background) + .or(global.track.background) + .unwrap_or_else(gpui::transparent_black), + state + .border + .or(self.track.border) + .or(global_state.border) + .or(global.track.border) + .unwrap_or(default_border), + ) + } + + fn resolve_thumb( + &self, + cx: &App, + state: &ScrollbarThumbStyle, + global_state: &ScrollbarThumbStyle, + defaults: ScrollbarThumbStyle, + ) -> (Background, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + ( + state + .background + .or(self.thumb.background) + .or(global_state.background) + .or(global.thumb.background) + .unwrap_or_else(|| defaults.background.unwrap()), + state + .width + .or(self.thumb.width) + .or(global_state.width) + .or(global.thumb.width) + .unwrap_or_else(|| defaults.width.unwrap()), + state + .inset + .or(self.thumb.inset) + .or(global_state.inset) + .or(global.thumb.inset) + .unwrap_or_else(|| defaults.inset.unwrap()), + state + .radius + .or(self.thumb.radius) + .or(global_state.radius) + .or(global.thumb.radius) + .unwrap_or_else(|| defaults.radius.unwrap()), + state + .min_length + .or(self.thumb.min_length) + .or(global_state.min_length) + .or(global.thumb.min_length) + .or(defaults.min_length) + .unwrap_or(MIN_THUMB_SIZE), + ) + } + + /// The thumb colour a scrollbar falls back to when nothing has overridden + /// it, taken from the active theme rather than fixed. + /// + /// It used to be literal black at these alphas. That reads as an ordinary + /// grey thumb on a light surface and as very nearly nothing at all on a + /// dark one, and no palette an application installed could change it: + /// `Theme` carries `scrollbar` beside `tokens` rather than derived from + /// them, so a theme swap moved every token except the ones the scrollbar + /// actually paints with. + /// + /// `foreground` is the token that already means "ink on this surface" and + /// already flips with the appearance, so on a light theme this stays within + /// a hair of the old constant and on a dark one it becomes visible. An + /// explicit `ScrollbarStyles` still wins: this is the bottom of the + /// cascade, not a new top of it. + fn thumb_default_background(cx: &App, alpha: f32) -> Background { + cx.theme().tokens.colors.foreground.alpha(alpha).into() + } + + fn thumb_defaults( + background: Background, + width: Pixels, + inset: Pixels, + radius: Pixels, + ) -> ScrollbarThumbStyle { + ScrollbarThumbStyle { + background: Some(background), + width: Some(width), + inset: Some(inset), + radius: Some(radius), + min_length: Some(MIN_THUMB_SIZE), + } + } + + pub(super) fn style_for_active( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + let (track, border) = self.resolve_track( + cx, + &self.track_active, + &global.track_active, + gpui::transparent_black(), + ); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb_active, + &global.thumb_active, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.55), + THUMB_ACTIVE_WIDTH, + THUMB_ACTIVE_INSET, + THUMB_ACTIVE_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } + + pub(super) fn style_for_hovered_thumb( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + let (track, border) = self.resolve_track( + cx, + &self.track_active, + &global.track_active, + gpui::transparent_black(), + ); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb_hover, + &global.thumb_hover, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.55), + THUMB_ACTIVE_WIDTH, + THUMB_ACTIVE_INSET, + THUMB_ACTIVE_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } + + pub(super) fn style_for_hovered_bar( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + let (track, border) = self.resolve_track( + cx, + &self.track_hover, + &global.track_hover, + gpui::transparent_black(), + ); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb, + &global.thumb, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.35), + THUMB_WIDTH, + THUMB_INSET, + THUMB_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } + + pub(super) fn style_for_normal( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + + let (track, border) = + self.resolve_track(cx, &self.track, &global.track, gpui::transparent_black()); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb, + &global.thumb, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.35), + THUMB_WIDTH, + THUMB_INSET, + THUMB_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn typed_styles_are_fluent_and_include_geometry() { + let track = gpui::hsla(0.1, 0.2, 0.3, 1.0); + let border = gpui::hsla(0.2, 0.3, 0.4, 1.0); + let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); + let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0); + let active = gpui::hsla(0.5, 0.6, 0.7, 1.0); + let styles = ScrollbarStyles::default() + .track(|style| { + style + .width(px(14.)) + .bg(track) + .border_color(border) + .when(false, |style| style.width(px(99.))) + }) + .thumb(|style| { + style + .width(px(7.)) + .inset(px(3.)) + .radius(px(3.5)) + .min_length(px(40.)) + .bg(thumb) + }) + .thumb_hover(|style| style.width(px(9.)).bg(hover)) + .thumb_active(|style| style.radius(px(4.5)).bg(active)); + + assert_eq!(styles.track.background, Some(track)); + assert_eq!(styles.track.border, Some(border)); + assert_eq!(styles.track.width, Some(px(14.))); + assert!(styles.thumb.background.is_some()); + assert_eq!(styles.thumb.width, Some(px(7.))); + assert_eq!(styles.thumb.inset, Some(px(3.))); + assert_eq!(styles.thumb.radius, Some(px(3.5))); + assert_eq!(styles.thumb.min_length, Some(px(40.))); + assert!(styles.thumb_hover.background.is_some()); + assert_eq!(styles.thumb_hover.width, Some(px(9.))); + assert!(styles.thumb_active.background.is_some()); + assert_eq!(styles.thumb_active.radius, Some(px(4.5))); + } +} diff --git a/vendor/gpui-base/src/scrollbar/element.rs b/vendor/gpui-base/src/scrollbar/element.rs new file mode 100644 index 00000000..9c8ea162 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/element.rs @@ -0,0 +1,661 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use instant::{Duration, Instant}; + +use crate::{AxisExt, theme::ActiveTheme as _}; +use gpui::{ + Anchor, App, Axis, Background, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element, + GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IsZero, LayoutId, + MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Position, ScrollWheelEvent, + Style, TouchDragEvent, TouchPhase, Window, fill, point, px, relative, size, +}; + +use super::motion::{ + hover_keeps_visible, tracks_thumb_hover, visibility_translation, wants_visible, +}; +use super::{ + Scrollbar, ScrollbarMode, ScrollbarState, ThumbGeometry, appearance::clamp_thumb_radius, +}; + +#[doc(hidden)] +pub struct PrepaintState { + hitbox: Hitbox, + scrollbar_state: ScrollbarState, + pub(super) states: Vec, +} + +#[doc(hidden)] +pub struct AxisPrepaintState { + axis: Axis, + bar_hitbox: Hitbox, + bounds: Bounds, + radius: Pixels, + bg: Hsla, + border: Hsla, + thumb_bounds: Bounds, + // Bounds of thumb to be rendered. + pub(super) thumb_fill_bounds: Bounds, + thumb_bg: Background, + geometry: ThumbGeometry, + active_geometry: ThumbGeometry, + track_width: Pixels, + visibility_opacity: f32, + visibility_position: f32, + visibility_requested: bool, +} + +impl Element for Scrollbar { + type RequestLayoutState = (); + type PrepaintState = PrepaintState; + + fn id(&self) -> Option { + Some(self.id.clone()) + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, Self::RequestLayoutState) { + let mut style = Style::default(); + style.position = Position::Absolute; + style.flex_grow = 1.0; + style.flex_shrink = 1.0; + style.size.width = relative(1.).into(); + style.size.height = relative(1.).into(); + + (window.request_layout(style, None, cx), ()) + } + + fn prepaint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + bounds: Bounds, + _: &mut Self::RequestLayoutState, + window: &mut Window, + cx: &mut App, + ) -> Self::PrepaintState { + let bounds = self.resolved_viewport_bounds(bounds); + let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { + window.insert_hitbox(bounds, HitboxBehavior::Normal) + }); + + let state = window + .use_state(cx, |_, _| ScrollbarState::default()) + .read(cx) + .clone(); + + let now = cx.background_executor().now(); + let base_theme = cx.theme(); + let mode = self.mode.unwrap_or(base_theme.scrollbar.mode()); + let motion = base_theme.scrollbar.motion(); + // Always-visible scrollbars skip visibility motion but still animate + // their activity width. Reduced motion snaps every channel. + let reduce_motion = cx.reduce_motion(); + let (enter, exit) = if !mode.is_always() && !reduce_motion { + (motion.enter(), motion.exit()) + } else { + (Duration::ZERO, Duration::ZERO) + }; + let expand = if reduce_motion { + Duration::ZERO + } else { + motion.expand() + }; + + let mut inner = state.get(); + let current_offset = self.scroll_handle.offset(); + if current_offset != inner.last_scroll_offset { + inner = inner.with_last_scroll(current_offset, Some(now)); + } + + let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some(); + let is_dragging = inner.dragged_axis.is_some(); + let is_currently_visible = inner.visibility.sample(now).opacity > 0.0; + let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible) + || wants_visible( + mode, + is_hovered, + is_dragging, + inner.last_scroll_time, + motion.idle(), + now, + ); + inner.visibility.set_visible( + visible, + motion.entrance_for(mode, inner.hovered_on_thumb.is_some()), + enter, + exit, + now, + ); + let visibility = inner.visibility.sample(now); + state.request_visibility_redraw( + visibility.running, + visible, + inner.visibility.remaining(now), + now, + window, + cx, + ); + + if !is_hovered && !is_dragging { + if let Some(last_time) = inner.last_scroll_time { + let elapsed = now.saturating_duration_since(last_time); + if elapsed < motion.idle() && !inner.idle_timer_scheduled { + inner.idle_timer_scheduled = true; + let state = state.clone(); + let current_view = window.current_view(); + let next_delay = motion.idle() - elapsed; + window + .spawn(cx, async move |cx| { + cx.background_executor().timer(next_delay).await; + state.set(state.get().with_idle_timer_scheduled(false)); + cx.update(|_, cx| cx.notify(current_view)).ok(); + }) + .detach(); + } + } + } + state.set(inner); + + let mut states = vec![]; + let mut has_both = self.axis.is_both(); + let scroll_size = self + .scroll_size + .unwrap_or(self.scroll_handle.content_size()); + + for axis in self.axis.all().into_iter() { + let is_vertical = axis.is_vertical(); + let track_width = self.styles.track_width(cx); + let (scroll_area_size, container_size, scroll_position) = if is_vertical { + ( + scroll_size.height, + hitbox.size.height, + self.scroll_handle.offset().y, + ) + } else { + ( + scroll_size.width, + hitbox.size.width, + self.scroll_handle.offset().x, + ) + }; + + // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible. + let margin_end = if has_both && !is_vertical { + track_width + } else { + px(0.) + }; + + // Hide scrollbar, if the scroll area is smaller than the container. + if scroll_area_size <= container_size { + has_both = false; + continue; + } + + let bounds = Bounds { + origin: if is_vertical { + point( + hitbox.origin.x + hitbox.size.width - track_width, + hitbox.origin.y, + ) + } else { + point( + hitbox.origin.x, + hitbox.origin.y + hitbox.size.height - track_width, + ) + }, + size: gpui::Size { + width: if is_vertical { + track_width + } else { + hitbox.size.width + }, + height: if is_vertical { + hitbox.size.height + } else { + track_width + }, + }, + }; + + let is_always_to_show = mode.is_always(); + let is_hover_to_show = mode.is_hover(); + let is_hovered_on_bar = state.get().hovered_axis == Some(axis); + let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis); + + let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) = + if state.get().dragged_axis == Some(axis) { + self.styles.style_for_active(cx) + } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling) + && (is_hovered_on_bar || is_hovered_on_thumb) + { + if is_hovered_on_thumb { + self.styles.style_for_hovered_thumb(cx) + } else { + self.styles.style_for_hovered_bar(cx) + } + } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) { + if is_hovered_on_thumb { + self.styles.style_for_hovered_thumb(cx) + } else { + self.styles.style_for_hovered_bar(cx) + } + } else { + self.styles.style_for_normal(cx) + }; + + let mut width_animation = if is_vertical { + state.get().vertical_width + } else { + state.get().horizontal_width + }; + let (animated_width, running) = width_animation.set_target(thumb_width, expand, now); + let mut updated = state.get(); + if is_vertical { + updated.vertical_width = width_animation; + } else { + updated.horizontal_width = width_animation; + } + state.set(updated); + thumb_width = animated_width; + if running { + window.request_animation_frame(); + } + + let origin = if is_vertical { + bounds.origin.y + } else { + bounds.origin.x + }; + let geometry = ThumbGeometry::new( + origin, + container_size, + scroll_area_size, + margin_end, + inset, + min_length, + ); + let (_, _, _, _, active_inset, _, active_min_length) = self.styles.style_for_active(cx); + let active_geometry = ThumbGeometry::new( + origin, + container_size, + scroll_area_size, + margin_end, + active_inset, + active_min_length, + ); + let thumb_start = geometry.start(scroll_position) - origin; + + // The clickable area of the thumb + let thumb_length = geometry.length; + let thumb_bounds = if is_vertical { + Bounds::from_anchor_and_size( + Anchor::TopRight, + bounds.top_right() + point(-inset, thumb_start), + size(track_width, thumb_length), + ) + } else { + Bounds::from_anchor_and_size( + Anchor::BottomLeft, + bounds.bottom_left() + point(thumb_start, -inset), + size(thumb_length, track_width), + ) + }; + + // The actual render area of the thumb + let thumb_fill_bounds = if is_vertical { + Bounds::from_anchor_and_size( + Anchor::TopRight, + bounds.top_right() + point(-inset, thumb_start), + size(thumb_width, thumb_length), + ) + } else { + Bounds::from_anchor_and_size( + Anchor::BottomLeft, + bounds.bottom_left() + point(thumb_start, -inset), + size(thumb_length, thumb_width), + ) + }; + + let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { + window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal) + }); + + states.push(AxisPrepaintState { + axis, + bar_hitbox, + bounds, + radius, + bg: bar_bg, + border: bar_border, + thumb_bounds, + thumb_fill_bounds, + thumb_bg, + geometry, + active_geometry, + track_width, + visibility_opacity: visibility.opacity, + visibility_position: visibility.position, + visibility_requested: visible, + }) + } + + PrepaintState { + hitbox, + states, + scrollbar_state: state, + } + } + + fn paint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut Self::RequestLayoutState, + prepaint: &mut Self::PrepaintState, + window: &mut Window, + cx: &mut App, + ) { + let scrollbar_state = &prepaint.scrollbar_state; + let theme = cx.theme(); + let mode = self.mode.unwrap_or(theme.scrollbar.mode()); + let view_id = window.current_view(); + let hitbox_bounds = prepaint.hitbox.bounds; + let is_hover_to_show = mode.is_hover(); + + window.with_content_mask( + Some(ContentMask { + bounds: hitbox_bounds, + }), + |window| { + for state in prepaint.states.iter() { + let axis = state.axis; + let mut radius = state.radius; + if theme.tokens.radius.md.is_zero() { + radius = px(0.); + } + radius = clamp_thumb_radius(radius, state.thumb_fill_bounds); + let bounds = state.bounds; + let thumb_bounds = state.thumb_bounds; + let geometry = state.geometry; + let active_geometry = state.active_geometry; + let is_vertical = axis.is_vertical(); + let visibility_opacity = state.visibility_opacity; + let is_visible = state.visibility_requested || visibility_opacity > 0.0; + let translation = + visibility_translation(axis, state.track_width, state.visibility_position); + let painted_bounds = state.bounds + translation; + let painted_thumb_bounds = state.thumb_fill_bounds + translation; + let painted_track_bg = state.bg.opacity(visibility_opacity); + let painted_border = state.border.opacity(visibility_opacity); + let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity); + + window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox); + + window.paint_layer(hitbox_bounds, |cx| { + cx.paint_quad(fill(painted_bounds, painted_track_bg)); + + cx.paint_quad(PaintQuad { + bounds: painted_bounds, + corner_radii: (0.).into(), + background: gpui::transparent_black().into(), + border_widths: if is_vertical { + Edges { + top: px(0.), + right: px(0.), + bottom: px(0.), + left: px(0.), + } + } else { + Edges { + top: px(0.), + right: px(0.), + bottom: px(0.), + left: px(0.), + } + }, + border_color: painted_border, + border_style: BorderStyle::default(), + }); + + cx.paint_quad( + fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius), + ); + }); + + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + + move |event: &ScrollWheelEvent, phase, _, cx| { + if phase.bubble() && hitbox_bounds.contains(&event.position) { + if scroll_handle.offset() != state.get().last_scroll_offset { + state.set(state.get().with_last_scroll( + scroll_handle.offset(), + Some(cx.background_executor().now()), + )); + cx.notify(view_id); + } + } + } + }); + + // A thumb follows the finger, unlike content panning. Claim + // this touch before the window turns it into wheel deltas. + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); + move |event: &TouchDragEvent, phase, window, cx| { + if !phase.bubble() { + return; + } + if event.phase == TouchPhase::Started { + if !is_visible + || window.default_prevented() + || !thumb_bounds.contains(&event.start_position) + { + return; + } + scroll_handle.start_drag(); + state.set(state.get().with_drag_pos( + axis, + event.start_position - thumb_bounds.origin, + )); + } else if state.get().dragged_axis != Some(axis) { + return; + } + if event.phase != TouchPhase::Cancelled { + scroll_handle.set_offset(active_geometry.drag_offset( + axis, + event.position, + state.get().drag_pos, + scroll_handle.offset(), + )); + } + if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) { + scroll_handle.end_drag(); + state.set( + state + .get() + .with_unset_drag_pos(cx.background_executor().now()), + ); + } + window.prevent_default(); + cx.stop_propagation(); + if event.phase == TouchPhase::Moved { + state.notify_drag( + Instant::now(), + max_fps_duration, + view_id, + window, + cx, + ); + } else { + cx.notify(view_id); + } + } + }); + + if is_visible { + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + + move |event: &MouseDownEvent, phase, _, cx| { + if phase.bubble() && bounds.contains(&event.position) { + cx.stop_propagation(); + + if thumb_bounds.contains(&event.position) { + // click on the thumb bar, set the drag position + let pos = event.position - thumb_bounds.origin; + + scroll_handle.start_drag(); + state.set(state.get().with_drag_pos(axis, pos)); + // Active styling can change the inset or minimum length. + // Keep the original grab point under the pointer on that frame. + scroll_handle.set_offset(active_geometry.drag_offset( + axis, + event.position, + pos, + scroll_handle.offset(), + )); + } else { + // click on the scrollbar, jump to the position + // Set the thumb bar center to the click position + let center = + point(geometry.length / 2., geometry.length / 2.); + scroll_handle.set_offset(geometry.drag_offset( + axis, + event.position, + center, + scroll_handle.offset(), + )); + } + + cx.notify(view_id); + } + } + }); + } + + window.on_mouse_event({ + let scroll_handle = self.scroll_handle.clone(); + let state = scrollbar_state.clone(); + let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); + + move |event: &MouseMoveEvent, _, window, cx| { + let mut notify = false; + // When is hover to show mode or it was visible, + // we need to update the hovered state and increase the last_scroll_time. + let need_hover_to_update = is_hover_to_show || is_visible; + // Update hovered state for scrollbar + if bounds.contains(&event.position) && need_hover_to_update { + let hover_changed = state.get().hovered_axis != Some(axis); + state.set( + state + .get() + .with_hovered(Some(axis), cx.background_executor().now()), + ); + notify |= hover_changed; + } else if state.get().hovered_axis == Some(axis) { + state.set( + state + .get() + .with_hovered(None, cx.background_executor().now()), + ); + notify = true; + } + + // Update hovered state for scrollbar thumb + if tracks_thumb_hover(mode, is_visible) + && thumb_bounds.contains(&event.position) + { + if state.get().hovered_on_thumb != Some(axis) { + state.set(state.get().with_hovered_on_thumb( + Some(axis), + cx.background_executor().now(), + )); + notify = true; + } + } else { + if state.get().hovered_on_thumb == Some(axis) { + state.set(state.get().with_hovered_on_thumb( + None, + cx.background_executor().now(), + )); + notify = true; + } + } + + // Move thumb position on dragging + if state.get().dragged_axis == Some(axis) && event.dragging() { + // Stop the event propagation to avoid selecting text or other side effects. + cx.stop_propagation(); + + let offset = active_geometry.drag_offset( + axis, + event.position, + state.get().drag_pos, + scroll_handle.offset(), + ); + if scroll_handle.offset() != offset { + // Coalesce rendering, never discard the newest pointer position. + scroll_handle.set_offset(offset); + notify = true; + } + if notify { + state.notify_drag( + Instant::now(), + max_fps_duration, + view_id, + window, + cx, + ); + } + return; + } + + if notify { + cx.notify(view_id); + } + } + }); + + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + + move |event: &MouseUpEvent, phase, _, cx| { + if phase.bubble() && state.get().dragged_axis == Some(axis) { + scroll_handle.set_offset(active_geometry.drag_offset( + axis, + event.position, + state.get().drag_pos, + scroll_handle.offset(), + )); + scroll_handle.end_drag(); + state.set( + state + .get() + .with_unset_drag_pos(cx.background_executor().now()), + ); + cx.notify(view_id); + } + } + }); + } + }, + ); + } +} diff --git a/vendor/gpui-base/src/scrollbar/motion.rs b/vendor/gpui-base/src/scrollbar/motion.rs new file mode 100644 index 00000000..6a140307 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/motion.rs @@ -0,0 +1,711 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use instant::{Duration, Instant}; + +use crate::{ + AxisExt, + animation::{ease_in_cubic, ease_out_cubic}, +}; +use gpui::{Axis, Pixels, Point, point, px}; + +use super::ScrollbarMode; + +/// How long visibility is held after the last activity, when the styled layer +/// projects no [`ScrollbarMotion`] of its own. +/// +/// This is a visibility hold rather than motion: without it [`ScrollbarMode::Scrolling`] +/// could never reveal the scrollbar. +const DEFAULT_IDLE: Duration = Duration::from_secs(2); + +#[derive(Debug, Clone, Copy)] +struct ScalarTransition { + from: T, + target: T, + started_at: Instant, + duration: Duration, +} + +impl ScalarTransition { + fn settled(value: T, now: Instant) -> Self { + Self { + from: value, + target: value, + started_at: now, + duration: Duration::ZERO, + } + } + + fn sample(&self, now: Instant, interpolate: impl FnOnce(T, T, f32) -> T) -> (T, bool) { + if self.from == self.target || self.duration.is_zero() { + return (self.target, false); + } + let linear = now.saturating_duration_since(self.started_at).as_secs_f32() + / self.duration.as_secs_f32(); + if linear >= 1.0 { + (self.target, false) + } else { + ( + interpolate(self.from, self.target, linear.clamp(0.0, 1.0)), + true, + ) + } + } + + fn remaining(&self, now: Instant) -> Duration { + if self.from == self.target { + return Duration::ZERO; + } + self.duration + .saturating_sub(now.saturating_duration_since(self.started_at)) + } + + fn start(&mut self, from: T, target: T, duration: Duration, now: Instant) { + self.from = from; + self.target = target; + self.started_at = now; + self.duration = duration; + } + + fn settle(&mut self, target: T, now: Instant) { + self.start(target, target, Duration::ZERO, now); + } +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct WidthAnimation { + transition: ScalarTransition, + initialized: bool, +} + +impl WidthAnimation { + pub(super) fn new(now: Instant) -> Self { + Self { + transition: ScalarTransition::settled(Pixels::ZERO, now), + initialized: false, + } + } + + fn sample(&self, now: Instant) -> (Pixels, bool) { + self.transition.sample(now, |from, target, linear| { + from + (target - from) * ease_out_cubic(linear) + }) + } + + /// Move toward `target` over `duration`. A zero duration adopts the target + /// immediately, which is how reduced motion and a motionless theme arrive here. + pub(super) fn set_target( + &mut self, + target: Pixels, + duration: Duration, + now: Instant, + ) -> (Pixels, bool) { + if duration.is_zero() || !self.initialized { + self.transition.settle(target, now); + self.initialized = true; + } else if self.transition.target != target { + let from = self.sample(now).0; + self.transition.start(from, target, duration, now); + } + self.sample(now) + } +} + +/// How a scrollbar becomes visible. +/// +/// The styled layer chooses the choreography; Base only plays it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ScrollbarEntrance { + /// Fade in without moving. + #[default] + Fade, + /// Slide in from the nearest edge while fading. + SlideAndFade, +} + +/// Motion tokens used by [`Scrollbar`](super::Scrollbar). +/// +/// Base installs no motion of its own: every transition duration defaults to +/// zero, so visibility and thumb width snap. Product timing belongs to the +/// styled layer, which projects it through [`crate::ScrollbarTheme`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ScrollbarMotion { + idle: Duration, + enter: Duration, + exit: Duration, + expand: Duration, + entrance: ScrollbarEntrance, + thumb_hover_entrance: ScrollbarEntrance, +} + +impl Default for ScrollbarMotion { + fn default() -> Self { + Self { + idle: DEFAULT_IDLE, + enter: Duration::ZERO, + exit: Duration::ZERO, + expand: Duration::ZERO, + entrance: ScrollbarEntrance::Fade, + thumb_hover_entrance: ScrollbarEntrance::Fade, + } + } +} + +impl ScrollbarMotion { + /// How long visibility is held after the last scroll, drag, or hover. + pub fn with_idle(mut self, idle: Duration) -> Self { + self.idle = idle; + self + } + + /// How long the scrollbar takes to become fully visible. + pub fn with_enter(mut self, enter: Duration) -> Self { + self.enter = enter; + self + } + + /// How long the scrollbar takes to fade away once the idle hold expires. + pub fn with_exit(mut self, exit: Duration) -> Self { + self.exit = exit; + self + } + + /// How long the thumb takes to reach a new width. + pub fn with_expand(mut self, expand: Duration) -> Self { + self.expand = expand; + self + } + + /// Which entrance choreography to play. + pub fn with_entrance(mut self, entrance: ScrollbarEntrance) -> Self { + self.entrance = entrance; + self + } + + /// Which entrance choreography to play when hover reveals the thumb. + pub fn with_thumb_hover_entrance(mut self, entrance: ScrollbarEntrance) -> Self { + self.thumb_hover_entrance = entrance; + self + } + + pub fn idle(&self) -> Duration { + self.idle + } + + pub fn enter(&self) -> Duration { + self.enter + } + + pub fn exit(&self) -> Duration { + self.exit + } + + pub fn expand(&self) -> Duration { + self.expand + } + + pub fn entrance(&self) -> ScrollbarEntrance { + self.entrance + } + + pub fn thumb_hover_entrance(&self) -> ScrollbarEntrance { + self.thumb_hover_entrance + } + + pub(super) fn entrance_for( + &self, + mode: ScrollbarMode, + thumb_hovered: bool, + ) -> ScrollbarEntrance { + if mode.is_hover() && thumb_hovered { + self.thumb_hover_entrance + } else { + self.entrance + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct VisibilityAnimation { + opacity: ScalarTransition, + position: ScalarTransition, + entrance: ScrollbarEntrance, +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct VisibilitySample { + pub(super) opacity: f32, + pub(super) position: f32, + pub(super) running: bool, +} + +impl VisibilityAnimation { + pub(super) fn hidden(now: Instant) -> Self { + Self { + opacity: ScalarTransition::settled(0.0, now), + position: ScalarTransition::settled(0.0, now), + entrance: ScrollbarEntrance::Fade, + } + } + + pub(super) fn sample(&self, now: Instant) -> VisibilitySample { + let entering = + self.opacity.target > self.opacity.from || self.position.target > self.position.from; + let (opacity, opacity_running) = self.opacity.sample(now, |from, target, linear| { + let factor = if entering { + linear + } else { + ease_in_cubic(linear) + }; + from + (target - from) * factor + }); + let (position, position_running) = self.position.sample(now, |from, target, linear| { + let factor = if entering { + ease_out_cubic(linear) + } else { + ease_in_cubic(linear) + }; + from + (target - from) * factor + }); + + VisibilitySample { + opacity, + position, + running: opacity_running || position_running, + } + } + + pub(super) fn remaining(&self, now: Instant) -> Duration { + self.opacity + .remaining(now) + .max(self.position.remaining(now)) + } + + /// Reverse or start a transition toward `visible`. + /// + /// The leg runs for `enter` or `exit` scaled by the distance still to cover, + /// so an interrupted transition keeps its speed instead of restarting. + pub(super) fn set_visible( + &mut self, + visible: bool, + entrance: ScrollbarEntrance, + enter: Duration, + exit: Duration, + now: Instant, + ) { + let target = if visible { 1.0 } else { 0.0 }; + let full_duration = if visible { enter } else { exit }; + if full_duration.is_zero() { + // A motionless policy — reduced motion, an always-visible scrollbar, + // or a theme that projects no motion — adopts the target outright, + // even if a transition was in flight when the policy changed. + self.opacity.settle(target, now); + self.position.settle(target, now); + self.entrance = entrance; + return; + } + if self.opacity.target == target + && self.position.target == target + && self.entrance == entrance + { + return; + } + + let sample = self.sample(now); + let from_position = if visible && entrance == ScrollbarEntrance::Fade { + 1.0 + } else { + sample.position + }; + let distance = (target - sample.opacity) + .abs() + .max((target - from_position).abs()); + let duration = full_duration.mul_f32(distance); + self.opacity.start(sample.opacity, target, duration, now); + self.position.start(from_position, target, duration, now); + self.entrance = entrance; + } +} + +pub(super) fn visibility_translation( + axis: Axis, + track_width: Pixels, + progress: f32, +) -> Point { + let offset = track_width * (1.0 - progress.clamp(0.0, 1.0)); + if axis.is_vertical() { + point(offset, px(0.)) + } else { + point(px(0.), offset) + } +} + +pub(super) fn wants_visible( + mode: ScrollbarMode, + is_hovered: bool, + is_dragging: bool, + last_scroll_time: Option, + idle: Duration, + now: Instant, +) -> bool { + mode.is_always() + || is_dragging + || (mode.is_hover() && is_hovered) + || last_scroll_time.is_some_and(|last| now.saturating_duration_since(last) < idle) +} + +pub(super) fn tracks_thumb_hover(mode: ScrollbarMode, is_visible: bool) -> bool { + mode.is_hover() || is_visible +} + +pub(super) fn hover_keeps_visible( + mode: ScrollbarMode, + is_hovered: bool, + is_currently_visible: bool, +) -> bool { + is_hovered && (mode.is_hover() || (mode == ScrollbarMode::Scrolling && is_currently_visible)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scrollbar::ScrollbarState; + /// Timing standing in for what a styled layer projects. Base itself ships + /// none of these; see [`motionless_base_snaps_every_transition`]. + const ENTER: Duration = Duration::from_millis(300); + const EXIT: Duration = Duration::from_millis(500); + const EXPAND: Duration = Duration::from_millis(300); + + #[test] + fn visibility_animation_uses_direction_specific_curves_and_durations() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + assert_eq!(animation.sample(start).opacity, 0.0); + let entering = animation.sample(start + ENTER / 2).position; + assert!(entering > 0.5, "ease-out must advance quickly"); + let entered = animation.sample(start + ENTER); + assert_eq!(entered.opacity, 1.0); + assert_eq!(entered.position, 1.0); + + animation.set_visible( + false, + ScrollbarEntrance::SlideAndFade, + ENTER, + EXIT, + start + ENTER, + ); + let exiting = animation.sample(start + ENTER + EXIT / 2).opacity; + assert!(exiting > 0.5, "ease-in must remain visible early in exit"); + assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0); + } + + #[test] + fn entrance_fades_linearly_while_position_eases_out() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + + let halfway = animation.sample(start + ENTER / 2); + assert!((halfway.opacity - 0.5).abs() < 0.001); + assert!(halfway.position > halfway.opacity); + } + + #[test] + fn fade_entrance_snaps_position_and_animates_opacity() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start); + + let initial = animation.sample(start); + assert_eq!(initial.opacity, 0.0); + assert_eq!(initial.position, 1.0); + let halfway = animation.sample(start + ENTER / 2); + assert!((halfway.opacity - 0.5).abs() < 0.001); + assert_eq!(halfway.position, 1.0); + } + + #[test] + fn active_visibility_adopts_a_changed_entrance_policy() { + let start = Instant::now(); + let halfway = start + ENTER / 2; + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + let before = animation.sample(halfway); + + animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway); + let after = animation.sample(halfway); + + assert_eq!( + after.opacity, before.opacity, + "policy changes must not flash" + ); + assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding"); + } + + #[test] + fn base_ships_no_motion_of_its_own() { + let motion = ScrollbarMotion::default(); + assert_eq!(motion.enter(), Duration::ZERO); + assert_eq!(motion.exit(), Duration::ZERO); + assert_eq!(motion.expand(), Duration::ZERO); + assert_eq!(motion.entrance(), ScrollbarEntrance::Fade); + assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade); + assert_eq!( + motion.idle(), + DEFAULT_IDLE, + "the visibility hold is behavior, not motion, and must stay usable" + ); + } + + #[test] + fn hover_mode_slides_only_when_the_thumb_is_hovered() { + let motion = ScrollbarMotion::default() + .with_entrance(ScrollbarEntrance::Fade) + .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade); + + assert_eq!( + motion.entrance_for(ScrollbarMode::Hover, false), + ScrollbarEntrance::Fade + ); + assert_eq!( + motion.entrance_for(ScrollbarMode::Hover, true), + ScrollbarEntrance::SlideAndFade + ); + assert_eq!( + motion.entrance_for(ScrollbarMode::Scrolling, true), + ScrollbarEntrance::Fade + ); + } + + #[test] + fn hidden_scrolling_mode_does_not_track_thumb_hover() { + assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false)); + assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true)); + assert!(tracks_thumb_hover(ScrollbarMode::Hover, false)); + } + + #[test] + fn visible_scrolling_mode_stays_visible_while_hovered() { + assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false)); + assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true)); + assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false)); + } + + #[test] + fn motionless_base_snaps_every_transition() { + let now = Instant::now(); + let motion = ScrollbarMotion::default(); + let mut visibility = VisibilityAnimation::hidden(now); + + visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now); + let shown = visibility.sample(now); + assert_eq!(shown.opacity, 1.0); + assert_eq!(shown.position, 1.0); + assert!(!shown.running, "a motionless theme must request no frames"); + assert_eq!( + visibility_translation(Axis::Vertical, px(16.), shown.position), + Point::default() + ); + + visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now); + let hidden = visibility.sample(now); + assert_eq!(hidden.opacity, 0.0); + assert_eq!(hidden.position, 0.0); + assert!(!hidden.running); + + let mut width = WidthAnimation::new(now); + assert_eq!( + width.set_target(px(8.), motion.expand(), now), + (px(8.), false) + ); + } + + #[test] + fn a_zero_duration_settles_a_transition_already_in_flight() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + + // Reduced motion turns on midway through the entrance. + let midway = start + ENTER / 2; + animation.set_visible( + true, + ScrollbarEntrance::SlideAndFade, + Duration::ZERO, + Duration::ZERO, + midway, + ); + let settled = animation.sample(midway); + assert_eq!(settled.opacity, 1.0); + assert_eq!(settled.position, 1.0); + assert!(!settled.running); + } + + #[test] + fn thumb_expansion_animates_in_both_directions() { + let start = Instant::now(); + let mut animation = WidthAnimation::new(start); + assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false)); + + let (initial, running) = animation.set_target(px(8.), EXPAND, start); + assert_eq!(initial, px(6.)); + assert!(running); + let (expanded_halfway, _) = animation.sample(start + EXPAND / 2); + assert!(expanded_halfway > px(7.)); + + let reversal = start + EXPAND / 2; + let before = animation.sample(reversal).0; + let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal); + assert_eq!(after_reversal, before); + assert!(running); + assert_eq!(animation.sample(reversal + EXPAND).0, px(6.)); + } + + #[test] + fn reduced_motion_snaps_thumb_expansion() { + let now = Instant::now(); + let mut animation = WidthAnimation::new(now); + assert_eq!( + animation.set_target(px(8.), Duration::ZERO, now), + (px(8.), false) + ); + } + + #[test] + fn visibility_translation_moves_toward_the_nearest_edge() { + assert_eq!( + visibility_translation(Axis::Vertical, px(16.), 0.0), + point(px(16.), px(0.)) + ); + assert_eq!( + visibility_translation(Axis::Horizontal, px(16.), 0.0), + point(px(0.), px(16.)) + ); + assert_eq!( + visibility_translation(Axis::Vertical, px(16.), 1.0), + Point::default() + ); + } + + #[test] + fn visibility_animation_reverses_from_current_progress() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + let reversal_time = start + Duration::from_millis(60); + let before = animation.sample(reversal_time); + + animation.set_visible( + false, + ScrollbarEntrance::SlideAndFade, + ENTER, + EXIT, + reversal_time, + ); + let reversed = animation.sample(reversal_time); + assert_eq!(reversed.opacity, before.opacity); + assert_eq!(reversed.position, before.position); + let after = animation.sample(reversal_time + Duration::from_millis(10)); + assert!(after.opacity < before.opacity); + assert!(after.position < before.position); + } + + #[test] + fn always_hover_drag_and_recent_scroll_request_visibility() { + let now = Instant::now(); + let idle = DEFAULT_IDLE; + assert!(wants_visible( + ScrollbarMode::Always, + false, + false, + None, + idle, + now + )); + assert!(wants_visible( + ScrollbarMode::Hover, + true, + false, + None, + idle, + now + )); + assert!(wants_visible( + ScrollbarMode::Scrolling, + false, + true, + None, + idle, + now + )); + assert!(wants_visible( + ScrollbarMode::Scrolling, + false, + false, + Some(now - idle + Duration::from_millis(1)), + idle, + now, + )); + assert!(!wants_visible( + ScrollbarMode::Scrolling, + false, + false, + Some(now - idle), + idle, + now, + )); + + let mut settled = VisibilityAnimation::hidden(now - ENTER); + settled.set_visible( + true, + ScrollbarEntrance::SlideAndFade, + ENTER, + EXIT, + now - ENTER, + ); + assert!(!settled.sample(now).running, "idle hold must not animate"); + } + + #[test] + fn leaving_hover_starts_a_fresh_idle_hold() { + let entered_at = Instant::now(); + let left_at = entered_at + Duration::from_secs(5); + let state = ScrollbarState::default().get(); + + let hovered = state.with_hovered(Some(Axis::Vertical), entered_at); + assert_eq!(hovered.last_scroll_time, Some(entered_at)); + let left = hovered.with_hovered(None, left_at); + assert_eq!(left.last_scroll_time, Some(left_at)); + assert!(wants_visible( + ScrollbarMode::Hover, + false, + false, + left.last_scroll_time, + DEFAULT_IDLE, + left_at + DEFAULT_IDLE - Duration::from_millis(1), + )); + } + + #[test] + fn idle_boundary_starts_the_exit_without_a_jump() { + let activity = Instant::now(); + let exit_start = activity + DEFAULT_IDLE; + let mut animation = VisibilityAnimation::hidden(activity - ENTER); + animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER); + assert!(!wants_visible( + ScrollbarMode::Scrolling, + false, + false, + Some(activity), + DEFAULT_IDLE, + exit_start, + )); + + animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start); + let start = animation.sample(exit_start); + assert_eq!(start.opacity, 1.0); + assert_eq!(start.position, 1.0); + assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0); + } +} diff --git a/vendor/gpui-base/src/scrollbar/redraw.rs b/vendor/gpui-base/src/scrollbar/redraw.rs new file mode 100644 index 00000000..25b96df9 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/redraw.rs @@ -0,0 +1,86 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. +//! Frame sampling and bounded wakeups for a single passive fade. + +use gpui::{App, Task, Window}; +use instant::{Duration, Instant}; + +const FADE_INTERVAL: Duration = Duration::from_nanos(16_666_667); +const FAST_FRAME_INTERVAL: Duration = Duration::from_millis(15); + +#[derive(Debug, Default)] +pub(super) struct FadeRedraw { + phase: Phase, + frame_pending: bool, +} + +#[derive(Debug, Default)] +enum Phase { + #[default] + Idle, + Sampling { + previous: Instant, + fast: u8, + }, + Paced { + deadline: Instant, + _task: Task<()>, + }, +} + +impl FadeRedraw { + /// Returns true when the caller must register the platform callback. + pub(super) fn schedule( + &mut self, + now: Instant, + remaining: Duration, + window: &mut Window, + cx: &mut App, + ) -> bool { + if matches!(self.phase, Phase::Idle) { + self.phase = Phase::Sampling { + previous: now, + fast: 0, + }; + } + match self.phase { + Phase::Sampling { fast, .. } if fast < 2 => { + return !std::mem::replace(&mut self.frame_pending, true); + } + Phase::Paced { deadline, .. } if now < deadline => return false, + _ => {} + } + + let wait = remaining.min(FADE_INTERVAL); + let timer = cx.background_executor().timer(wait); + let view = window.current_view(); + let task = window.spawn(cx, async move |cx| { + timer.await; + cx.update(|_, cx| cx.notify(view)).ok(); + }); + self.phase = Phase::Paced { + deadline: now + wait, + _task: task, + }; + false + } + + pub(super) fn frame_delivered(&mut self, now: Instant) -> bool { + self.frame_pending = false; + let Phase::Sampling { previous, fast } = &mut self.phase else { + return false; + }; + // Count actual platform callbacks. Extra layouts during a frame and a + // single short interval do not switch a 60 Hz window to timer wakes. + if now.saturating_duration_since(*previous) < FAST_FRAME_INTERVAL { + *fast += 1; + } else { + *fast = 0; + } + *previous = now; + true + } + + pub(super) fn cancel(&mut self) { + self.phase = Phase::Idle; + } +} diff --git a/vendor/gpui-base/src/scrollbar/tests.rs b/vendor/gpui-base/src/scrollbar/tests.rs new file mode 100644 index 00000000..3021b179 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/tests.rs @@ -0,0 +1,751 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. +use super::appearance::clamp_thumb_radius; +use super::element::PrepaintState; +use super::*; +use std::cell::RefCell; + +use gpui::{ + Background, Context, Element, GlobalElementId, InspectorElementId, LayoutId, Modifiers, + MouseButton, ParentElement as _, Render, Styled as _, TestAppContext, TouchDragEvent, + TouchPhase, VisualTestContext, div, size, +}; + +#[test] +fn thumb_radius_is_limited_by_its_actual_bounds() { + let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.))); + let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.))); + + assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.)); + assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.)); + assert_eq!( + clamp_thumb_radius(Pixels::ZERO, vertical_thumb), + Pixels::ZERO + ); +} + +#[derive(Clone)] +struct TestHandle { + offset: Rc>>, + content_size: Size, + drag_starts: Rc>, + drag_ends: Rc>, +} + +impl TestHandle { + fn new(content_size: Size) -> Self { + Self { + offset: Rc::new(Cell::new(Point::default())), + content_size, + drag_starts: Rc::new(Cell::new(0)), + drag_ends: Rc::new(Cell::new(0)), + } + } +} + +impl ScrollbarHandle for TestHandle { + fn viewport_bounds(&self) -> Bounds { + Bounds::new(Point::default(), size(px(100.), px(100.))) + } + + fn offset(&self) -> Point { + self.offset.get() + } + + fn set_offset(&self, offset: Point) { + self.offset.set(offset); + } + + fn content_size(&self) -> Size { + self.content_size + } + + fn start_drag(&self) { + self.drag_starts.set(self.drag_starts.get() + 1); + } + + fn end_drag(&self) { + self.drag_ends.set(self.drag_ends.get() + 1); + } +} + +struct ScrollbarHarness { + handle: TestHandle, + axis: ScrollbarAxis, + mode: ScrollbarMode, +} + +impl Render for ScrollbarHarness { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .relative() + .size(px(100.)) + .child(Scrollbar::new(&self.handle).axis(self.axis).mode(self.mode)) + } +} + +fn harness( + cx: &mut TestAppContext, + axis: ScrollbarAxis, + mode: ScrollbarMode, + content_size: Size, +) -> (&mut VisualTestContext, TestHandle) { + let handle = TestHandle::new(content_size); + let (_, cx) = cx.add_window_view({ + let handle = handle.clone(); + move |_, _| ScrollbarHarness { handle, axis, mode } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + (cx, handle) +} + +#[test] +fn explicit_viewport_bounds_override_handle_bounds() { + let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.))); + let scrollbar = + Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.)))).viewport_bounds(expected); + + assert_eq!( + scrollbar.resolved_viewport_bounds(Bounds::default()), + expected + ); +} + +#[test] +fn layout_viewport_uses_current_element_bounds() { + let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.))); + let scrollbar = + Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout(); + + assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected); +} + +#[gpui::test] +fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) { + cx.update(|cx| { + let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())); + + let light = gpui::hsla(0., 0., 0.04, 1.0); + crate::Theme::global_mut(cx).tokens.colors.foreground = light; + let (on_light, ..) = scrollbar.styles.style_for_normal(cx); + + let dark = gpui::hsla(0., 0., 0.98, 1.0); + crate::Theme::global_mut(cx).tokens.colors.foreground = dark; + let (on_dark, ..) = scrollbar.styles.style_for_normal(cx); + + assert_eq!(on_light, Background::from(light.alpha(0.35))); + assert_eq!(on_dark, Background::from(dark.alpha(0.35))); + // The point of the change: a thumb that never moved with the + // palette was invisible on one of the two surfaces. + assert_ne!(on_light, on_dark); + }); +} + +#[gpui::test] +fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) { + cx.update(|cx| { + let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0); + crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0); + + let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) + .styles(|styles| styles.thumb(|style| style.bg(chosen))); + let (thumb, ..) = scrollbar.styles.style_for_normal(cx); + + assert_eq!(thumb, Background::from(chosen)); + }); +} + +#[gpui::test] +fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) { + cx.update(|cx| { + let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0); + let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0); + let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); + + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() + .with_mode(ScrollbarMode::Always) + .with_motion(ScrollbarMotion::default()) + .with_styles( + ScrollbarStyles::default() + .track(|style| style.width(px(13.)).bg(theme_track)) + .thumb(|style| style.width(px(7.)).bg(theme_thumb)), + ); + + let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) + .styles(|styles| styles.thumb(|style| style.bg(instance_thumb))); + let (thumb, track, _, width, _, _, _) = scrollbar.styles.style_for_normal(cx); + + assert_eq!(thumb, Background::from(instance_thumb)); + assert_eq!(track, theme_track); + assert_eq!(width, px(7.)); + assert_eq!(scrollbar.styles.track_width(cx), px(13.)); + }); +} + +#[gpui::test] +fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) { + cx.update(|cx| { + let handle = TestHandle::new(Size::default()); + let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling); + let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always); + + assert_eq!(scrolling.styles.style_for_normal(cx).3, px(6.)); + assert_eq!(always.styles.style_for_normal(cx).3, px(6.)); + }); +} + +#[gpui::test] +fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) { + cx.update(|cx| { + let handle = TestHandle::new(Size::default()); + for mode in [ + ScrollbarMode::Scrolling, + ScrollbarMode::Hover, + ScrollbarMode::Always, + ] { + let scrollbar = Scrollbar::new(&handle).mode(mode); + assert_eq!(scrollbar.styles.style_for_normal(cx).3, px(6.)); + assert_eq!(scrollbar.styles.style_for_hovered_bar(cx).3, px(6.)); + assert_eq!(scrollbar.styles.style_for_hovered_thumb(cx).3, px(8.)); + } + }); +} + +#[gpui::test] +fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) { + let (cx, vertical) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert!(vertical.offset().y < px(0.)); + assert_eq!(vertical.offset().x, px(0.)); +} + +#[gpui::test] +fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) { + let (cx, horizontal) = harness( + cx, + ScrollbarAxis::Horizontal, + ScrollbarMode::Always, + size(px(500.), px(100.)), + ); + cx.simulate_click(point(px(80.), px(95.)), Modifiers::default()); + assert!(horizontal.offset().x < px(0.)); + assert_eq!(horizontal.offset().y, px(0.)); +} + +#[gpui::test] +fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Both, + ScrollbarMode::Always, + size(px(100.), px(100.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert_eq!(handle.offset(), Point::default()); +} + +#[gpui::test] +fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Hover, + size(px(100.), px(500.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert_eq!(handle.offset(), Point::default()); +} + +#[gpui::test] +fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Hover, + size(px(100.), px(500.)), + ); + cx.simulate_mouse_down( + point(px(95.), px(20.)), + MouseButton::Left, + Modifiers::default(), + ); + cx.simulate_mouse_move( + point(px(95.), px(70.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.simulate_mouse_up( + point(px(95.), px(70.)), + MouseButton::Left, + Modifiers::default(), + ); + + assert_eq!(handle.drag_starts.get(), 0); + assert_eq!(handle.drag_ends.get(), 0); + assert_eq!(handle.offset(), Point::default()); +} + +#[gpui::test] +fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Hover, + size(px(100.), px(500.)), + ); + // Base ships no motion, so the reveal is immediate. + cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default()); + cx.run_until_parked(); + + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert!(handle.offset().y < px(0.)); +} + +#[gpui::test] +fn drag_notifications_are_throttled_and_deliver_the_latest_offset(cx: &mut TestAppContext) { + let handle = TestHandle::new(size(px(100.), px(1000.))); + let (view, cx) = cx.add_window_view({ + let handle = handle.clone(); + move |_, _| ScrollbarHarness { + handle, + axis: ScrollbarAxis::Vertical, + mode: ScrollbarMode::Always, + } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let observed = Rc::new(RefCell::new(Vec::new())); + let _subscription = cx.update(|_, cx| { + let observed = observed.clone(); + let handle = handle.clone(); + cx.observe(&view, move |_, _| { + observed.borrow_mut().push(handle.offset().y) + }) + }); + let state = ScrollbarState::default(); + let now = Instant::now(); + let interval = Duration::from_secs_f64(1. / 30.); + let mut inner = state.get().with_drag_pos(Axis::Vertical, Point::default()); + inner.last_update = now; + state.set(inner); + let update = |offset, elapsed, cx: &mut VisualTestContext| { + handle.set_offset(point(px(0.), px(offset))); + cx.update(|window, cx| { + state.notify_drag(now + elapsed, interval, view.entity_id(), window, cx) + }); + cx.run_until_parked(); + }; + update(-10., Duration::ZERO, cx); + cx.executor().advance_clock(Duration::from_millis(16)); + update(-20., Duration::from_millis(16), cx); + update(-30., Duration::from_millis(16), cx); + // Rendering at 120 Hz must not bypass the configured 30 Hz timer. + cx.update(|window, cx| { + window.simulate_next_frame(cx); + }); + cx.run_until_parked(); + assert!(observed.borrow().is_empty()); + cx.executor().advance_clock(Duration::from_millis(16)); + cx.run_until_parked(); + assert!(observed.borrow().is_empty()); + cx.executor().advance_clock(Duration::from_millis(2)); + cx.run_until_parked(); + assert_eq!( + *observed.borrow(), + vec![px(-30.)], + "one trailing notification must see the newest offset even when movement stops" + ); + + // A second burst gets its own interval, and release invalidates its timer. + let next = state.get().last_update; + handle.set_offset(point(px(0.), px(-40.))); + cx.update(|window, cx| state.notify_drag(next, interval, view.entity_id(), window, cx)); + cx.run_until_parked(); + state.set(state.get().with_unset_drag_pos(Instant::now())); + handle.set_offset(point(px(0.), px(-50.))); + cx.update(|_, cx| cx.notify(view.entity_id())); + assert_eq!(*observed.borrow(), vec![px(-30.), px(-50.)]); + cx.executor().advance_clock(interval); + cx.run_until_parked(); + assert_eq!( + *observed.borrow(), + vec![px(-30.), px(-50.)], + "release must not leave a stale trailing notification" + ); +} + +#[test] +fn full_track_thumb_does_not_reset_the_scroll_offset() { + let geometry = ThumbGeometry::new(px(20.), px(40.), px(500.), px(0.), px(4.), px(64.)); + let offset = point(px(0.), px(-100.)); + assert_eq!( + geometry.drag_offset( + Axis::Vertical, + point(px(0.), px(50.)), + point(px(0.), px(8.)), + offset + ), + offset + ); +} + +#[gpui::test] +fn repeated_touch_and_mouse_drags_keep_the_painted_grab_point(cx: &mut TestAppContext) { + struct Probe { + scrollbar: Scrollbar, + painted: Rc>>, + } + impl IntoElement for Probe { + type Element = Self; + fn into_element(self) -> Self { + self + } + } + impl Element for Probe { + type RequestLayoutState = (); + type PrepaintState = PrepaintState; + fn id(&self) -> Option { + Element::id(&self.scrollbar) + } + fn source_location(&self) -> Option<&'static Location<'static>> { + None + } + fn request_layout( + &mut self, + id: Option<&GlobalElementId>, + inspector: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, ()) { + self.scrollbar.request_layout(id, inspector, window, cx) + } + fn prepaint( + &mut self, + id: Option<&GlobalElementId>, + inspector: Option<&InspectorElementId>, + bounds: Bounds, + layout: &mut (), + window: &mut Window, + cx: &mut App, + ) -> PrepaintState { + let state = self + .scrollbar + .prepaint(id, inspector, bounds, layout, window, cx); + self.painted.set(state.states[0].thumb_fill_bounds); + state + } + fn paint( + &mut self, + id: Option<&GlobalElementId>, + inspector: Option<&InspectorElementId>, + bounds: Bounds, + layout: &mut (), + state: &mut PrepaintState, + window: &mut Window, + cx: &mut App, + ) { + self.scrollbar + .paint(id, inspector, bounds, layout, state, window, cx); + } + } + struct Root { + handle: TestHandle, + painted: Rc>>, + axis: ScrollbarAxis, + viewport: Bounds, + } + impl Render for Root { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().size(px(400.)).child(Probe { + scrollbar: Scrollbar::new(&self.handle) + .axis(self.axis) + .mode(ScrollbarMode::Always) + .viewport_bounds(self.viewport) + .styles(|style| { + style + .thumb(|style| style.inset(px(6.)).min_length(px(64.))) + .thumb_active(|style| style.inset(px(3.)).min_length(px(72.))) + }), + painted: self.painted.clone(), + }) + } + } + for touch in [true, false] { + for vertical in [true, false] { + for (origin, viewport_size, content_size) in [ + (Point::default(), 200., 1000.), + (point(px(30.), px(40.)), 240., 500.), + ] { + let handle = TestHandle::new(size(px(content_size), px(content_size))); + handle.set_offset(point(px(-100.), px(-100.))); + let painted = Rc::new(Cell::new(Bounds::default())); + let (_, cx) = cx.add_window_view({ + let handle = handle.clone(); + let painted = painted.clone(); + move |_, _| Root { + handle, + painted, + axis: if vertical { + ScrollbarAxis::Vertical + } else { + ScrollbarAxis::Both + }, + viewport: Bounds::new(origin, size(px(viewport_size), px(viewport_size))), + } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let initial = painted.get(); + let start = initial.center(); + let grab = if vertical { + start.y - initial.origin.y + } else { + start.x - initial.origin.x + }; + let axis_delta = |value| { + if vertical { + point(px(0.), px(value)) + } else { + point(px(value), px(0.)) + } + }; + let axis_value = |point: Point| if vertical { point.y } else { point.x }; + let started_position = if touch { start + axis_delta(5.) } else { start }; + if touch { + cx.simulate_event(TouchDragEvent { + phase: TouchPhase::Started, + start_position: start, + position: started_position, + }); + } else { + cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); + } + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + (axis_value(painted.get().origin) + grab - axis_value(started_position)).abs() + < px(0.1), + "starting must preserve the grab point and first displacement" + ); + let mut reference_offset = px(0.); + let mut offset_per_pixel = 0.; + for delta in [0., 24., -8., 32., -10., 8., 0.] { + let position = start + axis_delta(delta); + if touch { + cx.simulate_event(TouchDragEvent { + phase: TouchPhase::Moved, + start_position: start, + position, + }); + } else { + cx.simulate_mouse_move( + position, + Some(MouseButton::Left), + Modifiers::default(), + ); + } + cx.update(|window, cx| window.draw(cx).clear(cx)); + if delta == 0. { + reference_offset = axis_value(handle.offset()); + } + if delta == 24. { + offset_per_pixel = + (axis_value(handle.offset()) - reference_offset) / px(24.); + } + let actual = if vertical { + painted.get().origin.y + grab + } else { + painted.get().origin.x + grab + }; + let expected = if vertical { position.y } else { position.x }; + assert!( + (actual - expected).abs() < px(0.1), + "touch={touch} vertical={vertical} delta={delta}: painted grab {actual:?}, pointer {expected:?}" + ); + } + // Release contains a final displacement without an intervening move. + let expected_offset = reference_offset + px(12.) * offset_per_pixel; + if touch { + cx.simulate_event(TouchDragEvent { + phase: TouchPhase::Ended, + start_position: start, + position: start + axis_delta(12.), + }); + } else { + cx.simulate_mouse_up( + start + axis_delta(12.), + MouseButton::Left, + Modifiers::default(), + ); + } + assert!( + (axis_value(handle.offset()) - expected_offset).abs() < px(0.1), + "release must flush the last displacement" + ); + let released_offset = handle.offset(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + handle.offset(), + released_offset, + "leaving active styling must not scroll" + ); + } + } + } +} + +#[gpui::test] +fn touch_thumb_drag_moves_down_and_cancel_releases_handle(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + let start_position = point(px(95.), px(20.)); + for (phase, position) in [ + (TouchPhase::Started, start_position), + (TouchPhase::Moved, point(px(95.), px(45.))), + (TouchPhase::Cancelled, point(px(95.), px(45.))), + ] { + cx.simulate_event(TouchDragEvent { + phase, + start_position, + position, + }); + } + assert!( + handle.offset().y < px(0.), + "thumb down must scroll toward later content" + ); + assert_eq!(handle.offset().x, px(0.)); + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.drag_ends.get(), 1); +} + +#[gpui::test] +fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + cx.simulate_mouse_down( + point(px(95.), px(20.)), + MouseButton::Left, + Modifiers::default(), + ); + cx.simulate_mouse_move( + point(px(95.), px(70.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.simulate_mouse_up( + point(px(95.), px(70.)), + MouseButton::Left, + Modifiers::default(), + ); + + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.drag_ends.get(), 1); +} + +#[gpui::test] +fn idle_fade_coalesces_redraws_and_reaches_the_hidden_state(cx: &mut TestAppContext) { + let tint = gpui::hsla(0.82, 0.9, 0.5, 1.); + let idle = Duration::from_millis(80); + cx.update(|cx| { + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() + .with_motion( + ScrollbarMotion::default() + .with_idle(idle) + .with_exit(Duration::from_millis(51)), + ) + .with_styles(ScrollbarStyles::default().thumb(|thumb| thumb.bg(tint))); + }); + let handle = TestHandle::new(size(px(100.), px(500.))); + let (view, cx) = cx.add_window_view(|_, _| ScrollbarHarness { + handle: handle.clone(), + axis: ScrollbarAxis::Vertical, + mode: ScrollbarMode::Scrolling, + }); + let notifications = Rc::new(Cell::new(0)); + let _observation = cx.update(|_, cx| { + let notifications = notifications.clone(); + cx.observe(&view, move |_, _| { + notifications.set(notifications.get() + 1) + }) + }); + let executor = cx.executor(); + let advance = |duration| { + executor.advance_clock(duration); + while executor.tick() {} + }; + let draw_thumb = |window: &mut Window, cx: &mut App| { + window.draw(cx).clear(cx); + window + .painted_quads() + .into_iter() + .filter_map(|quad| quad.background.as_solid()) + .find(|color| color.h == tint.h) + .map_or(0., |color| color.a) + }; + handle.set_offset(point(px(0.), px(-20.))); + assert_eq!(cx.update(draw_thumb), 1.); + advance(idle); + assert_eq!(cx.update(draw_thumb), 1.); + for _ in 0..2 { + advance(Duration::from_millis(6)); + assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 1); + assert!((0. ..1.).contains(&cx.update(draw_thumb))); + } + assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 0); + + notifications.set(0); + advance(Duration::from_millis(16)); + assert_eq!(notifications.get(), 0); + let alpha = cx.update(draw_thumb); + assert!((0. ..1.).contains(&alpha)); + advance(Duration::from_millis(1)); + assert_eq!(notifications.get(), 1); + assert!(cx.update(draw_thumb) < alpha); + + advance(Duration::from_millis(17)); + assert_eq!(notifications.get(), 2); + cx.update(draw_thumb); + advance(Duration::from_millis(5)); + assert_eq!(notifications.get(), 3); + assert_eq!(cx.update(draw_thumb), 0.); + advance(Duration::from_millis(20)); + assert_eq!(notifications.get(), 3); +} + +#[gpui::test] +fn an_idle_fade_uses_platform_frames_at_the_ordinary_display_rate(cx: &mut TestAppContext) { + let idle = Duration::from_millis(70); + cx.update(|cx| { + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new().with_motion( + ScrollbarMotion::default() + .with_idle(idle) + .with_exit(Duration::from_millis(100)), + ); + }); + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Scrolling, + size(px(100.), px(500.)), + ); + handle.set_offset(point(px(0.), px(-20.))); + let draw = |window: &mut Window, cx: &mut App| window.draw(cx).clear(cx); + cx.update(draw); + cx.executor().advance_clock(idle); + cx.update(draw); + for _ in 0..4 { + cx.executor().advance_clock(Duration::from_millis(16)); + assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 1); + cx.update(draw); + } +} diff --git a/vendor/gpui-base/src/text/document.rs b/vendor/gpui-base/src/text/document.rs index 915c65ac..0720c7b6 100644 --- a/vendor/gpui-base/src/text/document.rs +++ b/vendor/gpui-base/src/text/document.rs @@ -12,6 +12,10 @@ use crate::text::{ node::{BlockNode, NodeContext, SourceRangeSelection}, }; +// Nocterm: bound the number of text leaves in each Taffy block layout pass. +const PARAGRAPHS_PER_GROUP: usize = 32; +const MIN_GROUPED_PARAGRAPHS: usize = 256; + /// The parsed document AST. #[derive(Debug, Clone, PartialEq, Default)] pub(crate) struct ParsedDocument { @@ -195,7 +199,7 @@ impl ParsedDocument { ) -> impl IntoElement { let Some(list_state) = list_state else { let blocks_len = self.blocks.len(); - return div().children(self.blocks.iter().enumerate().map(move |(ix, node)| { + let mut render_block = |ix, node: &BlockNode| { let is_last = ix + 1 == blocks_len; node.render_block( NodeRenderOptions { @@ -207,7 +211,26 @@ impl ParsedDocument { window, cx, ) - })); + }; + if self.can_group_paragraphs(node_cx) { + // The TextView content wrapper supplies the paragraph width. + return div().w_full().children( + self.blocks + .chunks(PARAGRAPHS_PER_GROUP) + .enumerate() + .map(|(group, blocks)| { + div().children(blocks.iter().enumerate().map(|(index, node)| { + render_block(group * PARAGRAPHS_PER_GROUP + index, node) + })) + }), + ); + } + return div().children( + self.blocks + .iter() + .enumerate() + .map(|(ix, node)| render_block(ix, node)), + ); }; let options = NodeRenderOptions { @@ -243,4 +266,17 @@ impl ParsedDocument { .size_full(), ) } + + fn can_group_paragraphs(&self, node_cx: &NodeContext) -> bool { + let gap = node_cx.style.paragraph_gap().0; + self.blocks.len() >= MIN_GROUPED_PARAGRAPHS + && gap.is_finite() + && gap >= 0. + && self.blocks.iter().all(|node| { + matches!(node, BlockNode::Paragraph(paragraph) if paragraph.children.iter().all(|child| { + child.custom.is_none() + && child.image.is_none() + })) + }) + } } diff --git a/vendor/gpui-base/src/text/inline.rs b/vendor/gpui-base/src/text/inline.rs index 8767ff00..a73d6219 100644 --- a/vendor/gpui-base/src/text/inline.rs +++ b/vendor/gpui-base/src/text/inline.rs @@ -1,209 +1,43 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + use gpui::Corners; use std::{ - cell::RefCell, - collections::HashMap, - mem, ops::Range, rc::Rc, - sync::{Arc, Mutex, Weak}, + sync::{Arc, Mutex}, }; use gpui::{ - App, BorderStyle, Bounds, ClickEvent, CursorStyle, Edges, Element, ElementId, GlobalElementId, - Half, HighlightStyle, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IntoElement, LayoutId, - MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, - SharedString, StyledText, TextAlign, TextLayout, TextRun, TextStyle, Window, point, px, quad, - size, + App, BorderStyle, Bounds, Edges, Element, ElementId, GlobalElementId, Half, Hitbox, + HitboxBehavior, Hsla, InspectorElementId, IntoElement, LayoutId, Pixels, Rems, SharedString, + Style, StyledText, TextLayout, TextStyle, Window, point, px, quad, size, +}; + +mod geometry; +mod highlights; +mod pointer; +mod retained_layout; + +pub(super) use geometry::point_in_text_selection; +use geometry::{glyph_boxes, range_boxes, selection_for_multi_click}; +pub(super) use highlights::{ + InlineHighlight, append_node_highlights, fade_highlights, highlights_in_range, text_runs, + text_size_ranges, text_size_ranges_in, }; +use pointer::InlinePointer; +use retained_layout::{RetainedLayout, has_retained_layout, retain_layout, take_retained_layout}; use crate::{ - GlobalState, TextSelection, - input::Selection, - text::TextViewMultiClickKind, - text::node::LinkMark, - text::range_highlight::RevealAt, - text::selection::word_range_at, - text::state::LineSpan, - text::text_view::{LinkClickHandlerFn, handle_link_click}, + GlobalState, input::Selection, text::TextViewMultiClickKind, text::node::LinkMark, + text::range_highlight::RevealAt, text::state::LineSpan, text::text_view::LinkClickHandlerFn, text_selection::text_rows_extent, }; -/// The style applied to one range of inline text. -/// -/// A [`HighlightStyle`] carries no font family, so the family an inline code -/// span is set in rides beside it; `None` keeps the family of the enclosing -/// text style. -#[derive(Clone, Debug, Default, PartialEq)] -pub(super) struct InlineHighlight { - pub(super) style: HighlightStyle, - pub(super) font_family: Option, - pub(super) font_size_scale: Option, -} - -impl InlineHighlight { - /// Layers `other` over `self`, the way [`HighlightStyle::highlight`] does. - fn highlight(mut self, other: &InlineHighlight) -> Self { - self.style = self.style.highlight(other.style); - if other.font_family.is_some() { - self.font_family = other.font_family.clone(); - } - if other.font_size_scale.is_some() { - self.font_size_scale = other.font_size_scale; - } - self - } -} - -impl From for InlineHighlight { - fn from(style: HighlightStyle) -> Self { - Self { - style, - font_family: None, - font_size_scale: None, - } - } -} - -/// Merges two highlight lists over one text into non-overlapping ranges, -/// cutting at every endpoint of every input range. Same sweep as -/// [`gpui::combine_highlights`], for [`InlineHighlight`] payloads. -pub(super) fn combine_highlights( - a: impl IntoIterator, InlineHighlight)>, - b: impl IntoIterator, InlineHighlight)>, -) -> Vec<(Range, InlineHighlight)> { - let mut endpoints = Vec::new(); - let mut highlights = Vec::new(); - for (range, highlight) in a.into_iter().chain(b) { - if !range.is_empty() { - let id = highlights.len(); - endpoints.push((range.start, id, true)); - endpoints.push((range.end, id, false)); - highlights.push(highlight); - } - } - endpoints.sort_unstable_by_key(|(position, _, _)| *position); - - let mut combined = Vec::new(); - let mut active: Vec = Vec::new(); - let mut ix = 0; - for (position, id, is_start) in endpoints { - if position > ix && !active.is_empty() { - let style = active.iter().fold(InlineHighlight::default(), |acc, id| { - acc.highlight(&highlights[*id]) - }); - combined.push((ix..position, style)); - } - ix = position; - if is_start { - active.push(id); - } else { - active.retain(|active_id| *active_id != id); - } - } - combined -} - -/// Layers a streamed fade-in over `highlights`: text inside each fade range -/// loses that share of its color, and a highlight background fades with it so -/// an inline code chip does not appear before its text. -pub(super) fn fade_highlights( - highlights: Vec<(Range, InlineHighlight)>, - fades: &[(Range, f32)], -) -> Vec<(Range, InlineHighlight)> { - if fades.is_empty() { - return highlights; - } - let fade_highlights = fades.iter().map(|(range, fade_out)| { - ( - range.clone(), - InlineHighlight::from(HighlightStyle { - fade_out: Some(*fade_out), - ..Default::default() - }), - ) - }); - let mut combined = combine_highlights(highlights, fade_highlights); - for (_, highlight) in &mut combined { - if let Some(fade_out) = highlight.style.fade_out - && let Some(background) = highlight.style.background_color.as_mut() - { - background.fade_out(fade_out); - } - } - combined -} - -/// Builds the [`TextRun`]s for `text_len` bytes of inline text: each -/// highlight refines `default_style` over its range, and a highlight that -/// names a font family shapes its run in that family. -pub(super) fn text_runs( - text_len: usize, - default_style: &TextStyle, - highlights: &[(Range, InlineHighlight)], -) -> Vec { - let mut runs = Vec::with_capacity(highlights.len() * 2 + 1); - let mut ix = 0; - for (range, highlight) in highlights { - if ix < range.start { - runs.push(default_style.clone().to_run(range.start - ix)); - } - let mut run = default_style - .clone() - .highlight(highlight.style) - .to_run(range.len()); - if let Some(family) = &highlight.font_family { - run.font.family = family.clone(); - } - runs.push(run); - ix = range.end; - } - if ix < text_len { - runs.push(default_style.to_run(text_len - ix)); - } - runs -} - -/// Splits text into contiguous ranges sharing one font size. GPUI runs can -/// vary the font but not its size, so each range needs its own shaped line. -pub(super) fn text_size_ranges( - text_len: usize, - highlights: &[(Range, InlineHighlight)], -) -> Vec<(Range, f32)> { - let mut ranges: Vec<(Range, f32)> = Vec::new(); - let mut push = |range: Range, scale: f32| { - if range.is_empty() { - return; - } - if let Some((last, last_scale)) = ranges.last_mut() - && *last_scale == scale - && last.end == range.start - { - last.end = range.end; - } else { - ranges.push((range, scale)); - } - }; - let mut cursor = 0; - for (range, highlight) in highlights { - push(cursor..range.start, 1.); - push(range.clone(), highlight.font_size_scale.unwrap_or(1.)); - cursor = range.end; - } - push(cursor..text_len, 1.); - ranges -} - -/// A inline element used to render a inline text and support selectable. -/// -/// All text in TextView (including the CodeBlock) used this for text rendering. +/// Selectable inline text drawn by TextView and its code blocks. pub(super) struct Inline { text: SharedString, links: Rc, LinkMark)>>, highlights: Vec<(Range, InlineHighlight)>, - styled_text: StyledText, - /// The resolved style from a parent deferred layout, when there is one. - text_style: Option, - paint_origin: Option>, selection_bounds: Option>, selection_source: Option<(Arc>, Range)>, /// Range highlight backgrounds, painted behind the text. @@ -211,12 +45,10 @@ pub(super) struct Inline { /// The start of a pending reveal, when it is in this text. reveal: Option, link_click_handler: Option>, - /// What this frame's layout was shaped with, to hand the shaped text to - /// the next frame (see [`RetainedLayout`]). - retained_key: Option<(Vec, TextStyle)>, - /// The shaped text is in the table, not in `styled_text`, until paint - /// takes it back. - handed_over: bool, + bottom_padding: Rems, + /// Nocterm: only hold a layout while this element owns the shaped text. + /// Prepaint returns it to the retained table; paint briefly takes it back. + layout: Option, state: Arc>, } @@ -229,74 +61,6 @@ pub(crate) struct InlineState { pub(super) selection: Option, } -/// One frame's [`StyledText`], kept for the next frame's [`Inline`] of the -/// same [`InlineState`]. -/// -/// A [`TextLayout`] remembers the size and the shaped lines of its last -/// measurement and answers a repeated measure at the same wrap width from -/// them, but a fresh `StyledText` every frame throws that away, so every -/// frame of a scroll paid for a line wrapper, a shaping-cache lookup that -/// hashes the whole paragraph, and the allocations around them for every -/// visible paragraph. Handing the same `StyledText` to the next frame makes -/// those measurements hits. A layout is only reused when the text, the runs -/// (colors, fades, fonts) and the text style (font size, line height) it was -/// shaped with are unchanged; a different wrap width misses inside -/// `TextLayout` and reshapes as before. -/// -/// `StyledText` is main-thread only (an `Rc` inside), while `InlineState` -/// travels through the background parse, so the layouts live in a -/// thread-local table keyed by the state's address, with a `Weak` to tell a -/// live state from a reused address. -struct RetainedLayout { - state: Weak>, - styled_text: StyledText, - text: SharedString, - runs: Vec, - text_style: TextStyle, -} - -thread_local! { - static RETAINED_LAYOUTS: RefCell> = RefCell::new(HashMap::new()); -} - -/// Dead entries (states that were dropped without a final paint, e.g. a -/// replaced document) are swept once the table grows past this many. -const RETAINED_SWEEP_AT: usize = 4096; - -fn state_key(state: &Arc>) -> usize { - Arc::as_ptr(state) as usize -} - -/// Takes the layout retained for `state`, if the previous frame left one. -fn take_retained_layout(state: &Arc>) -> Option { - RETAINED_LAYOUTS.with(|layouts| { - let retained = layouts.borrow_mut().remove(&state_key(state))?; - // The address may belong to a new state by now. - retained - .state - .upgrade() - .is_some_and(|live| Arc::ptr_eq(&live, state)) - .then_some(retained) - }) -} - -/// Whether the table already holds a layout for `state`: every entry left -/// by the previous frame is taken at layout time, so one that is present -/// afterwards was put there this frame, by another element of the same state. -fn has_retained_layout(state: &Arc>) -> bool { - RETAINED_LAYOUTS.with(|layouts| layouts.borrow().contains_key(&state_key(state))) -} - -fn retain_layout(state: &Arc>, retained: RetainedLayout) { - RETAINED_LAYOUTS.with(|layouts| { - let mut layouts = layouts.borrow_mut(); - if layouts.len() >= RETAINED_SWEEP_AT { - layouts.retain(|_, retained| retained.state.strong_count() > 0); - } - layouts.insert(state_key(state), retained); - }); -} - impl InlineState { /// Save actually rendered text for selected text to use. pub(crate) fn set_text(&mut self, text: SharedString) { @@ -315,38 +79,12 @@ impl Inline { /// table holds one layout per state, and an element must never be left /// to paint without its shaped text. fn retain_styled_text(&mut self) { - if self.handed_over || self.retained_key.is_none() || has_retained_layout(&self.state) { + if has_retained_layout(&self.state) { return; } - let Some((runs, text_style)) = self.retained_key.take() else { - return; - }; - retain_layout( - &self.state, - RetainedLayout { - state: Arc::downgrade(&self.state), - styled_text: mem::replace(&mut self.styled_text, StyledText::new("")), - text: self.text.clone(), - runs, - text_style, - }, - ); - self.handed_over = true; - } - - /// Takes the shaped text back from the table for painting. `false` when - /// it is gone, in which case there is nothing to paint with. - fn reclaim_styled_text(&mut self) -> bool { - if !self.handed_over { - return true; + if let Some(layout) = self.layout.take() { + retain_layout(&self.state, layout); } - let Some(retained) = take_retained_layout(&self.state) else { - return false; - }; - self.styled_text = retained.styled_text; - self.retained_key = Some((retained.runs, retained.text_style)); - self.handed_over = false; - true } pub(super) fn new( @@ -363,33 +101,18 @@ impl Inline { Self { links: Rc::new(links), highlights, - text: text.clone(), - styled_text: StyledText::new(text), - text_style: None, - paint_origin: None, + text, selection_bounds: None, selection_source: None, range_backgrounds: Vec::new(), reveal: None, link_click_handler, - retained_key: None, - handed_over: false, + bottom_padding: Rems::ZERO, + layout: None, state, } } - /// Use the resolved style captured by a deferred parent layout. - pub(super) fn text_style(mut self, text_style: TextStyle) -> Self { - self.text_style = Some(text_style); - self - } - - /// Preserve the shared inline-flow baseline through GPUI's element-bound snapping. - pub(super) fn paint_origin(mut self, origin: Point) -> Self { - self.paint_origin = Some(origin); - self - } - pub(super) fn selection_bounds(mut self, bounds: Bounds) -> Self { self.selection_bounds = Some(bounds); self @@ -411,6 +134,51 @@ impl Inline { self } + pub(super) fn bottom_padding(mut self, padding: Rems) -> Self { + self.bottom_padding = padding; + self + } + + fn prepare_layout(&mut self, text_style: TextStyle) { + let runs = text_runs(self.text.len(), &text_style, &self.highlights); + + // Reuse the previous frame's shaped text when it was shaped from the + // same text, runs and style; `StyledText` consumes its runs on every + // layout, so they are handed over again either way. + let retained = take_retained_layout(&self.state).filter(|retained| { + retained.text == self.text && retained.runs == runs && retained.text_style == text_style + }); + let styled_text = match retained { + Some(retained) => retained.styled_text.with_runs(runs.clone()), + None => StyledText::new(self.text.clone()).with_runs(runs.clone()), + }; + self.layout = Some(RetainedLayout { + styled_text, + text: self.text.clone(), + runs, + text_style, + }); + } + + pub(super) fn prepaint_positioned( + &mut self, + available: Bounds, + style: TextStyle, + window: &mut Window, + cx: &mut App, + ) -> (Bounds, InlinePrepaint) { + self.prepare_layout(style); + let size = self + .layout + .as_mut() + .expect("prepared layout") + .styled_text + .measure_as_block(available.size, window, cx); + let bounds = Bounds::new(available.origin, size); + let prepared = self.prepaint(None, None, bounds, &mut px(0.), window, cx); + (bounds, prepared) + } + /// Scroll the line `reveal` starts on into view during prepaint. pub(super) fn reveal(mut self, reveal: Option) -> Self { self.reveal = reveal; @@ -420,11 +188,10 @@ impl Inline { /// Ask the enclosing list to scroll the line of the pending reveal into /// view, and report where it is and whether it is inside the visible /// area. - fn request_reveal(&self, window: &mut Window) { - let Some(reveal) = &self.reveal else { + fn request_reveal(reveal: Option<&RevealAt>, text_layout: &TextLayout, window: &mut Window) { + let Some(reveal) = reveal else { return; }; - let text_layout = self.styled_text.layout(); let bounds = text_layout.bounds(); let line_height = text_layout.line_height(); let glyphs = glyph_boxes( @@ -466,35 +233,6 @@ impl Inline { ); } - /// Get link at given mouse position. - fn link_for_position( - layout: &TextLayout, - links: &Vec<(Range, LinkMark)>, - position: Point, - ) -> Option { - let offset = layout.index_for_position(position).ok()?; - for (range, link) in links.iter() { - if range.contains(&offset) { - return Some(link.clone()); - } - } - - None - } - - /// Get the range of the link at given mouse position. - fn link_range_for_position( - layout: &TextLayout, - links: &[(Range, LinkMark)], - position: Point, - ) -> Option> { - let offset = layout.index_for_position(position).ok()?; - links - .iter() - .find(|(range, _)| range.contains(&offset)) - .map(|(range, _)| range.clone()) - } - /// Paint selected bounds for debug. #[allow(unused)] fn paint_selected_bounds(&self, bounds: Bounds, window: &mut Window, cx: &mut App) { @@ -692,7 +430,7 @@ impl Inline { .iter() .map(|line| line.wrap_boundaries.len() + 1) .sum(); - let mut line_bounds = Vec::with_capacity(row_count); + let mut line_bounds = Vec::new(); let mut row_ix = 0; let mut y = origin.y; for line in &lines { @@ -704,18 +442,28 @@ impl Inline { .map(|boundary| layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix].index) .chain([line.len()]); for row_end in row_ends { - let mut width = layout.x_for_index(row_end) - layout.x_for_index(row_start); + let start = std::mem::replace(&mut row_start, row_end); + let row_y = y; + y += line_height; row_ix += 1; + if row_y >= mask_bounds.bottom() || y <= mask_bounds.top() { + continue; + } + let mut width = layout.x_for_index(row_end) - layout.x_for_index(start); if row_ix < row_count { width += line_height.half(); } - let bounds = Bounds::new(point(origin.x, y), size(width, line_height)) + let bounds = Bounds::new(point(origin.x, row_y), size(width, line_height)) .intersect(&mask_bounds); if bounds.size.width > px(0.) && bounds.size.height > px(0.) { + if line_bounds.is_empty() { + // A partially visible row can intersect either edge. + let visible = ((mask_bounds.size.height / line_height).ceil() as usize) + .saturating_add(1); + line_bounds.reserve_exact(row_count.min(visible)); + } line_bounds.push(bounds); } - y += line_height; - row_start = row_end; } } line_bounds @@ -849,9 +597,14 @@ impl IntoElement for Inline { } } +pub(super) enum InlinePrepaint { + Visible(Hitbox), + Clipped(Bounds), +} + impl Element for Inline { - type RequestLayoutState = (); - type PrepaintState = Hitbox; + type RequestLayoutState = Pixels; + type PrepaintState = InlinePrepaint; fn id(&self) -> Option { None @@ -863,46 +616,41 @@ impl Element for Inline { fn request_layout( &mut self, - global_element_id: Option<&GlobalElementId>, - inspector_id: Option<&InspectorElementId>, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, window: &mut Window, - cx: &mut App, + _: &mut App, ) -> (LayoutId, Self::RequestLayoutState) { - let text_style = self - .text_style - .clone() - .unwrap_or_else(|| window.text_style()); - let runs = text_runs(self.text.len(), &text_style, &self.highlights); - - // Reuse the previous frame's shaped text when it was shaped from the - // same text, runs and style; `StyledText` consumes its runs on every - // layout, so they are handed over again either way. - let retained = take_retained_layout(&self.state).filter(|retained| { - retained.text == self.text && retained.runs == runs && retained.text_style == text_style - }); - self.styled_text = match retained { - Some(retained) => retained.styled_text.with_runs(runs.clone()), - None => StyledText::new(self.text.clone()).with_runs(runs.clone()), - }; - self.retained_key = Some((runs, text_style)); - let (layout_id, _) = - self.styled_text - .request_layout(global_element_id, inspector_id, window, cx); - - (layout_id, ()) + self.prepare_layout(window.text_style()); + let mut style = Style::default(); + style.padding.bottom = self.bottom_padding.into(); + let padding = window.pixel_snap(self.bottom_padding.to_pixels(window.rem_size())); + let layout = self + .layout + .as_mut() + .expect("prepared layout") + .styled_text + .request_layout_with_style(style, window); + (layout, padding) } fn prepaint( &mut self, id: Option<&GlobalElementId>, inspector_id: Option<&InspectorElementId>, - bounds: Bounds, - _: &mut Self::RequestLayoutState, + mut bounds: Bounds, + padding: &mut Self::RequestLayoutState, window: &mut Window, cx: &mut App, ) -> Self::PrepaintState { - let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size); - self.styled_text + // The gap belongs to layout, outside the text clip and hitbox. + bounds.size.height = (bounds.size.height - *padding).max(Pixels::ZERO); + let layout = self + .layout + .as_mut() + .expect("request_layout precedes prepaint"); + layout + .styled_text .prepaint(id, inspector_id, bounds, &mut (), window, cx); // Report this element's laid-out extent so an ancestor TextView with @@ -922,37 +670,45 @@ impl Element for Inline { } } - self.request_reveal(window); + Self::request_reveal(self.reveal.as_ref(), layout.styled_text.layout(), window); - let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); self.retain_styled_text(); - hitbox + // This private hitbox cannot participate in GPUI's frame hit test when masked. + if bounds.intersect(&window.content_mask().bounds).is_empty() { + InlinePrepaint::Clipped(bounds) + } else { + InlinePrepaint::Visible(window.insert_hitbox(bounds, HitboxBehavior::Normal)) + } } fn paint( &mut self, global_id: Option<&GlobalElementId>, _: Option<&InspectorElementId>, - bounds: Bounds, + _: Bounds, _: &mut Self::RequestLayoutState, prepaint: &mut Self::PrepaintState, window: &mut Window, cx: &mut App, ) { - let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size); - let current_view = window.current_view(); - let hitbox = prepaint; - if !self.reclaim_styled_text() { - // Cannot happen (only this element takes what it handed over, - // and a live state is never swept); skip the frame rather than - // paint an unmeasured placeholder. - return; + let bounds = match prepaint { + InlinePrepaint::Visible(hitbox) => hitbox.bounds, + InlinePrepaint::Clipped(bounds) => *bounds, + }; + if self.layout.is_none() { + self.layout = take_retained_layout(&self.state); } - let text_layout = self.styled_text.layout().clone(); + let Some(layout) = &self.layout else { + return; + }; + let text_layout = layout.styled_text.layout().clone(); if !self.range_backgrounds.is_empty() { self.paint_range_highlights(&text_layout, window); } - self.styled_text + self.layout + .as_mut() + .expect("retained layout was just restored") + .styled_text .paint(global_id, None, bounds, &mut (), &mut (), window, cx); // layout selections @@ -976,17 +732,6 @@ impl Element for Inline { }); } - if is_selection || is_selectable { - window.set_cursor_style(CursorStyle::IBeam, &hitbox); - } - - // link cursor pointer - let hovered_link = - Self::link_range_for_position(&text_layout, &self.links, window.mouse_position()); - if hovered_link.is_some() { - window.set_cursor_style(CursorStyle::PointingHand, &hitbox); - } - if let Some(selection) = &state.selection { let color = GlobalState::global(cx) .text_view_state() @@ -1002,165 +747,37 @@ impl Element for Inline { } } - if is_selectable { - if let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() { - let text_bounds = Self::text_line_bounds( - &text_layout, - text_layout.line_height(), - window.content_mask().bounds, - ); - text_view_state.update(cx, |state, _| { - state.selection_adapter.register_inline(text_bounds); - state - .selection_adapter - .register_text_run(crate::TextSelectionRun::new( - self.text.clone(), - text_layout.clone(), - hitbox.bounds, - )); - }); - } - - window.on_mouse_event({ - let hitbox = hitbox.clone(); - let text_layout = text_layout.clone(); - let inline_state = self.state.clone(); - let text = self.text.clone(); - let text_view_state = GlobalState::global(cx).text_view_state().cloned(); - let line_bounds = self.selection_bounds; - move |event: &MouseDownEvent, phase, window, cx| { - if !phase.bubble() - || !hitbox.is_hovered(window) - || event.button != MouseButton::Left - { - return; - } - - if event.click_count == 3 - && let Some(line_bounds) = line_bounds - { - GlobalState::suppress_text_selection(cx); - if let Some(view) = &text_view_state { - view.update(cx, |state, cx| { - state.set_multi_click_line(line_bounds, cx) - }); - } - cx.notify(current_view); - return; - } - - // A finger selects read-only text with a long press only; - // a double tap selects nothing here, neither the mouse's - // plain word nor the window layer's touch selection. The - // handles and the menu on a double tap belong to `Input`. - if event.click_count == 2 && GlobalState::is_touch_press(cx) { - GlobalState::suppress_text_selection(cx); - return; - } - - let kind = match event.click_count { - 2 => TextViewMultiClickKind::Word, - 3 => TextViewMultiClickKind::Paragraph, - _ => return, - }; - - let Some(range) = selection_for_multi_click( - &text, - &text_layout, - hitbox.bounds, - event.position, - kind, - ) else { - return; - }; - - let selected_text = text[range.clone()].to_string(); - - // This renderer owns multi-click selection. Prevent the - // window selection layer from handling the same press. - GlobalState::suppress_text_selection(cx); - - if let Ok(mut inline_state) = inline_state.lock() { - inline_state.selection = Some(range.into()); - } - if let Some(text_view_state) = &text_view_state { - text_view_state.update(cx, |state, cx| { - state.set_multi_click_selection( - event.position, - kind, - selected_text, - cx, - ); - }); - } - cx.notify(current_view); - } - }); - } - - // Mouse move: repaint only when the pointer enters, leaves or moves - // between links, so the link cursor follows it. Hovering plain text - // changes nothing painted. - if !self.links.is_empty() { - window.on_mouse_event({ - let hitbox = hitbox.clone(); - let text_layout = text_layout.clone(); - let links = self.links.clone(); - let mut hovered_link = hovered_link; - move |event: &MouseMoveEvent, phase, window, cx| { - if !phase.bubble() || !hitbox.is_hovered(window) { - return; - } - - let updated = - Self::link_range_for_position(&text_layout, &links, event.position); - if hovered_link != updated { - hovered_link = updated; - cx.notify(current_view); - } - } + if is_selectable + && let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() + { + let text_bounds = Self::text_line_bounds( + &text_layout, + text_layout.line_height(), + window.content_mask().bounds, + ); + text_view_state.update(cx, |state, _| { + state.selection_adapter.register_inline(text_bounds); + state + .selection_adapter + .register_text_run(crate::TextSelectionRun::new( + self.text.clone(), + text_layout.clone(), + bounds, + )); }); } - if !is_selection { - // click to open link - window.on_mouse_event({ - let links = self.links.clone(); - let text_layout = text_layout.clone(); - let hitbox = hitbox.clone(); - let text_view_state = GlobalState::global(cx).text_view_state().cloned(); - let link_click_handler = self.link_click_handler.clone(); - - move |event: &MouseUpEvent, phase, window, cx| { - if !phase.bubble() || !hitbox.is_hovered(window) { - return; - } - if text_view_state - .as_ref() - .is_some_and(|state| state.read(cx).has_selection(cx)) - { - return; - } - - if let Some(link) = - Self::link_for_position(&text_layout, &links, event.position) - { - TextSelection::end(window, cx); - cx.stop_propagation(); - let click = ClickEvent::Mouse(MouseClickEvent { - down: MouseDownEvent { - button: event.button, - position: event.position, - modifiers: event.modifiers, - click_count: event.click_count, - first_mouse: false, - }, - up: event.clone(), - }); - handle_link_click(&link_click_handler, link.url, click, window, cx); - } - } - }); + if let InlinePrepaint::Visible(hitbox) = prepaint { + InlinePointer { + hitbox, + text_layout: &text_layout, + inline_state: &self.state, + text: &self.text, + links: &self.links, + link_click_handler: &self.link_click_handler, + line_bounds: self.selection_bounds, + } + .register(is_selectable, is_selection, window, cx); } drop(state); @@ -1168,1269 +785,15 @@ impl Element for Inline { } } -/// Where one glyph of laid-out text paints: its row, and its horizontal -/// extent past the text's origin, alignment applied. `text` is the byte range -/// of the text it draws. -#[derive(Clone, Debug, PartialEq)] -struct GlyphBox { - text: Range, - row: usize, - left: Pixels, - right: Pixels, -} - -/// The glyphs of `text_layout`, sorted by the text they draw, each placed -/// the way GPUI paints it: every row aligned in `align_width` by `align`, -/// and a glyph reaching to the next one on its row, or to the row's end. -/// -/// Glyphs are read in the order they paint, so right-to-left text, whose -/// glyphs paint in the reverse order of its text, is placed as it shows. -fn glyph_boxes(text_layout: &TextLayout, align: TextAlign, align_width: Pixels) -> Vec { - let mut boxes = Vec::new(); - let mut row = 0; - let mut line_start = 0; - for line in text_layout.line_layouts() { - let layout = &line.unwrapped_layout; - let glyphs = layout - .runs - .iter() - .flat_map(|run| run.glyphs.iter()) - .collect::>(); - // Each row starts at a wrap boundary glyph, and ends where the next - // row starts, or at the end of the line. - let run_offsets = layout - .runs - .iter() - .scan(0, |offset, run| { - let start = *offset; - *offset += run.glyphs.len(); - Some(start) - }) - .collect::>(); - let row_starts = line - .wrap_boundaries - .iter() - .map(|boundary| run_offsets[boundary.run_ix] + boundary.glyph_ix) - .collect::>(); - let line_boxes = boxes.len(); - let mut from = 0; - for (row_in_line, to) in row_starts.iter().copied().chain([glyphs.len()]).enumerate() { - let start_x = if row_in_line == 0 { - Pixels::ZERO - } else { - glyphs[from].position.x - }; - let end_x = glyphs - .get(to) - .map_or(layout.width, |glyph| glyph.position.x); - let shift = aligned_row_left(align, align_width, end_x - start_x) - start_x; - for ix in from..to { - let glyph = glyphs[ix]; - let right = if ix + 1 < to { - glyphs[ix + 1].position.x - } else { - end_x - }; - boxes.push(GlyphBox { - text: line_start + glyph.index..line_start + glyph.index, - row: row + row_in_line, - left: shift + glyph.position.x, - right: shift + right, - }); - } - from = to; - } - - // A glyph draws its text up to where the next glyph's text starts. - let line_boxes = &mut boxes[line_boxes..]; - line_boxes.sort_by_key(|glyph| glyph.text.start); - let line_end = line_start + line.len(); - for ix in 0..line_boxes.len() { - let start = line_boxes[ix].text.start; - line_boxes[ix].text.end = line_boxes[ix + 1..] - .iter() - .map(|glyph| glyph.text.start) - .find(|next| *next > start) - .unwrap_or(line_end); - } - - row += line.wrap_boundaries.len() + 1; - line_start = line_end + 1; - } - boxes -} - -fn aligned_row_left(align: TextAlign, align_width: Pixels, width: Pixels) -> Pixels { - match align { - TextAlign::Left => Pixels::ZERO, - TextAlign::Center => (align_width - width) / 2., - TextAlign::Right => align_width - width, - } -} - -/// The boxes behind the text of `range`, as a row and the horizontal extent -/// on it, from `glyphs` sorted by the text they draw: every glyph drawing -/// some of that text, joined where they touch on a row. -fn range_boxes(glyphs: &[GlyphBox], range: Range) -> Vec<(usize, Pixels, Pixels)> { - let first = glyphs.partition_point(|glyph| glyph.text.end <= range.start); - let mut hits = glyphs[first..] - .iter() - .take_while(|glyph| glyph.text.start < range.end) - .map(|glyph| (glyph.row, glyph.left, glyph.right)) - .collect::>(); - hits.sort_by(|a, b| { - (a.0, a.1) - .partial_cmp(&(b.0, b.1)) - .unwrap_or(std::cmp::Ordering::Equal) - }); - - let mut boxes: Vec<(usize, Pixels, Pixels)> = Vec::with_capacity(hits.len()); - for (row, left, right) in hits { - match boxes.last_mut() { - Some(last) if last.0 == row && left <= last.2 => last.2 = last.2.max(right), - _ => boxes.push((row, left, right)), - } - } - boxes -} - -fn selection_for_multi_click( - text: &str, - text_layout: &TextLayout, - bounds: Bounds, - pos: Point, - kind: TextViewMultiClickKind, -) -> Option> { - if !bounds.contains(&pos) { - return None; - } - - let offset = text_layout.index_for_position(pos).ok()?; - - match kind { - TextViewMultiClickKind::Word => word_range_at(text, offset), - // Known limitation: a paragraph maps to a single Inline run here. When a - // paragraph embeds an inline image it is split into multiple Inline runs, - // so triple-click only selects the run on the clicked side of the image. - TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => { - (!text.is_empty()).then_some(0..text.len()) - } - } -} - -/// Check if a `pos` is within a `bounds`, considering multi-line selections. -pub(super) fn point_in_text_selection( - pos: Point, - char_width: Pixels, - selection_start: Point, - selection_end: Point, - line_height: Pixels, -) -> bool { - let point_in_line = |point: Point| point.y >= pos.y && point.y < pos.y + line_height; - let top = selection_start.y.min(selection_end.y); - let bottom = selection_start.y.max(selection_end.y); - let x = pos.x + char_width.half(); - - // Out of the vertical bounds - if pos.y + line_height <= top || pos.y > bottom { - return false; - } - - // Treat the selection as single-line when both drag points fall within the - // same rendered line, even if their y coordinates differ inside that line. - if point_in_line(selection_start) && point_in_line(selection_end) { - let left = selection_start.x.min(selection_end.x); - let right = selection_start.x.max(selection_end.x); - return x >= left && x <= right; - } - - let (top_point, bottom_point) = if selection_start.y < selection_end.y { - (selection_start, selection_end) - } else { - (selection_end, selection_start) - }; - let is_top_line = point_in_line(top_point); - let is_bottom_line = point_in_line(bottom_point); - - if is_top_line { - return x >= top_point.x; - } else if is_bottom_line { - return x <= bottom_point.x; - } else { - return true; - } -} - #[cfg(test)] -mod fade_highlights_tests { - use super::*; - - #[test] - fn fades_text_and_background_only_inside_the_range() { - let code = InlineHighlight::from(HighlightStyle { - background_color: Some(gpui::red()), - ..Default::default() - }); - let combined = fade_highlights(vec![(0..4, code)], &[(2..6, 0.5)]); - - let ranges: Vec<_> = combined.iter().map(|(range, _)| range.clone()).collect(); - assert_eq!(ranges, vec![0..2, 2..4, 4..6]); - - let (_, untouched) = &combined[0]; - assert_eq!(untouched.style.fade_out, None); - assert_eq!(untouched.style.background_color.unwrap().a, 1.0); - - let (_, faded_code) = &combined[1]; - assert_eq!(faded_code.style.fade_out, Some(0.5)); - assert_eq!(faded_code.style.background_color.unwrap().a, 0.5); - - let (_, faded_text) = &combined[2]; - assert_eq!(faded_text.style.fade_out, Some(0.5)); - assert!(faded_text.style.background_color.is_none()); - } - - #[test] - fn no_fades_leave_highlights_untouched() { - let bold = InlineHighlight::from(HighlightStyle { - font_weight: Some(gpui::FontWeight::BOLD), - ..Default::default() - }); - let highlights = vec![(1..3, bold)]; - assert_eq!(fade_highlights(highlights.clone(), &[]), highlights); - } -} - -#[cfg(test)] -mod line_bounds_tests { - use super::*; - use super::{ - test_draw::in_prepaint, - test_fonts::{BODY, WideMonoTextSystem}, - }; - use gpui::{AvailableSpace, TestApp, size}; - - /// The character walk this replaced, kept as the oracle: one box per - /// character from `position_for_index`, unioned per row. - fn by_character( - text: &str, - text_layout: &TextLayout, - line_height: Pixels, - mask_bounds: Bounds, - ) -> Vec> { - let mut line_bounds = Vec::new(); - let mut current_line_y = None; - let mut current_bounds: Option> = None; - let mut offset = 0; - for c in text.chars() { - let next_offset = offset + c.len_utf8(); - let Some(pos) = text_layout.position_for_index(offset) else { - offset = next_offset; - continue; - }; - let mut char_width = line_height.half(); - if let Some(next_pos) = text_layout.position_for_index(next_offset) - && next_pos.y == pos.y - { - char_width = next_pos.x - pos.x; - } - let bounds = Bounds::from_corners(pos, point(pos.x + char_width, pos.y + line_height)) - .intersect(&mask_bounds); - if bounds.size.width > px(0.) && bounds.size.height > px(0.) { - if current_line_y == Some(pos.y) { - if let Some(current) = current_bounds.as_mut() { - *current = current.union(&bounds); - } - } else { - if let Some(current) = current_bounds.take() { - line_bounds.push(current); - } - current_line_y = Some(pos.y); - current_bounds = Some(bounds); - } - } - offset = next_offset; - } - if let Some(current) = current_bounds { - line_bounds.push(current); - } - line_bounds - } - - #[test] - fn row_walk_matches_the_character_walk() { - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, |window, cx| { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16.).into(), - ..Default::default() - }; - let origin = point(px(7.), px(11.)); - let mask = Bounds::new(point(px(0.), px(0.)), size(px(1000.), px(1000.))); - let clipped = Bounds::new(point(px(20.), px(30.)), size(px(50.), px(60.))); - for text in [ - "", - "one row", - "a long paragraph that wraps onto several rows of eight pixel glyphs", - "first line\nsecond line that also wraps around\n\nfourth", - "中文与 English 混排的一段文字也会换行", - "trailing newline\n", - ] { - for wrap_width in [40., 100., 1000.] { - let runs = text_runs(text.len(), &style, &[]); - let styled = - StyledText::new(SharedString::from(text.to_string())).with_runs(runs); - let layout = styled.layout().clone(); - let mut element = styled.into_any_element(); - element.layout_as_root( - size( - AvailableSpace::Definite(px(wrap_width)), - AvailableSpace::MinContent, - ), - window, - cx, - ); - element.prepaint_at(origin, window, cx); - let line_height = layout.line_height(); - for mask in [mask, clipped] { - let expected = by_character(text, &layout, line_height, mask); - let actual = Inline::text_line_bounds(&layout, line_height, mask); - let context = format!("{text:?} at {wrap_width}px in {mask:?}"); - // The character walk placed a wrapped row's first - // character at the end of the row before it: that row's - // box started one glyph in, and a row holding only that - // one glyph had no box at all. The row walk covers every - // row from its start, so it may see more rows, never - // fewer, and agrees on every row the walk could see. - assert!( - actual.len() >= expected.len(), - "rows of {context}: {} < {}", - actual.len(), - expected.len() - ); - for (row, expected) in expected.iter().enumerate() { - let actual = actual - .iter() - .find(|actual| actual.top() == expected.top()) - .unwrap_or_else(|| panic!("row {row} of {context} is missing")); - assert_eq!( - actual.bottom(), - expected.bottom(), - "row {row} of {context}" - ); - assert_eq!(actual.right(), expected.right(), "row {row} of {context}"); - assert!( - actual.left() <= expected.left(), - "row {row} of {context} starts at {:?}, after {:?}", - actual.left(), - expected.left() - ); - } - for actual in &actual { - assert_eq!( - actual.left(), - origin.x.max(mask.left()), - "left of {context}" - ); - } - } - } - } - }); - } -} - +mod fade_highlights_tests; #[cfg(test)] -mod range_highlight_tests { - use super::*; - use super::{ - test_draw::in_prepaint, - test_fonts::{BODY, WideMonoTextSystem}, - }; - use gpui::{AvailableSpace, TestApp, size}; - - /// Lays `text` out at `wrap_width` and returns the highlight boxes of - /// `range` with rows aligned by `align`: the left and right edges past - /// the text's origin, and the row. - fn boxes( - text: &'static str, - wrap_width: f32, - align: TextAlign, - range: Range, - ) -> Vec<(Pixels, Pixels, usize)> { - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, move |window, cx| { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16.).into(), - ..Default::default() - }; - let styled = StyledText::new(SharedString::from(text)).with_runs(text_runs( - text.len(), - &style, - &[], - )); - let layout = styled.layout().clone(); - let mut element = styled.into_any_element(); - element.layout_as_root( - size( - AvailableSpace::Definite(px(wrap_width)), - AvailableSpace::MinContent, - ), - window, - cx, - ); - let origin = point(px(7.), px(11.)); - element.prepaint_at(origin, window, cx); - let glyphs = glyph_boxes(&layout, align, layout.bounds().size.width); - range_boxes(&glyphs, range) - .into_iter() - .map(|(row, left, right)| (left, right, row)) - .collect() - }) - } - - /// The selection fast paths decide a whole inline from this extent, so it - /// must start exactly at the first row the per-character walk tests and - /// reach at least the bottom of the last one. It may reach further: a - /// trailing empty line, or a last row whose only character the walk - /// places at the end of the row before it, holds no row the walk tests. - #[test] - fn text_rows_extent_matches_the_character_walk() { - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, |window, cx| { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16.).into(), - ..Default::default() - }; - let origin = point(px(7.), px(11.3)); - for text in [ - "one row", - "a long paragraph that wraps onto several rows of eight pixel glyphs", - "first line\nsecond line that also wraps around\n\nfourth", - "中文与 English 混排的一段文字也会换行", - "trailing newline\n", - ] { - for wrap_width in [40., 100., 1000.] { - let runs = text_runs(text.len(), &style, &[]); - let styled = - StyledText::new(SharedString::from(text.to_string())).with_runs(runs); - let layout = styled.layout().clone(); - let mut element = styled.into_any_element(); - element.layout_as_root( - size( - AvailableSpace::Definite(px(wrap_width)), - AvailableSpace::MinContent, - ), - window, - cx, - ); - element.prepaint_at(origin, window, cx); - // Taller than the layout's rows, as a window line height - // may be. - let line_height = layout.line_height() + px(3.); - let rows_y = text - .char_indices() - .filter_map(|(offset, _)| layout.position_for_index(offset)) - .map(|position| position.y); - let top = rows_y.clone().fold(Pixels::MAX, Pixels::min); - let bottom = rows_y.fold(Pixels::MIN, Pixels::max) + line_height; - - let (rows_top, rows_bottom) = text_rows_extent(&layout, line_height); - let context = format!("{text:?} at {wrap_width}px"); - assert_eq!(rows_top, top, "top of {context}"); - assert!(rows_bottom >= bottom, "bottom of {context}"); - } - } - }); - } - - #[test] - fn a_highlight_starting_a_wrapped_row_paints_only_that_row() { - // Three rows of "aaaa ", "bbbb ", "cccc". - let text = "aaaa bbbb cccc"; - let rows = boxes(text, 45., TextAlign::Left, 0..text.len()); - assert_eq!(rows.len(), 3, "{rows:?}"); - - let bbbb = text.find("bbbb").unwrap(); - let highlight = boxes(text, 45., TextAlign::Left, bbbb..bbbb + 4); - assert_eq!(highlight.len(), 1, "{highlight:?}"); - assert_eq!(highlight[0].0, px(0.)); - assert_eq!(highlight[0].2, 1); - - // Across the wrap, each row only as far as its text. - let across = boxes(text, 45., TextAlign::Left, 2..7); - assert_eq!(across.len(), 2, "{across:?}"); - assert_eq!(across[0].1, rows[0].1); - assert_eq!((across[1].0, across[1].2), (px(0.), 1)); - } - - #[test] - fn highlights_after_a_hard_line_break_start_on_its_row() { - // Rows "aa", "bbb cc": the break is one byte of the text, not a glyph. - let text = "aa\nbbb cc"; - let bbb = text.find("bbb").unwrap(); - let aa = boxes(text, 1000., TextAlign::Left, 0..2); - let highlight = boxes(text, 1000., TextAlign::Left, bbb..bbb + 3); - assert_eq!(highlight.len(), 1, "{highlight:?}"); - assert_eq!(highlight[0].0, px(0.)); - assert_eq!(highlight[0].2, 1); - // Three glyphs as wide as the two of "aa" and a half. - assert_eq!(highlight[0].1, (aa[0].1 - aa[0].0) * 1.5); - } - - #[test] - fn highlights_follow_centered_and_right_aligned_rows() { - // Rows "aaaa ", "bbbb ", "cc": the last is narrower than the text, so - // alignment moves it. - let text = "aaaa bbbb cc"; - let cc = text.find("cc").unwrap()..text.len(); - let widest = boxes(text, 45., TextAlign::Left, 0..5)[0].1; - let left = boxes(text, 45., TextAlign::Left, cc.clone())[0]; - let center = boxes(text, 45., TextAlign::Center, cc.clone())[0]; - let right = boxes(text, 45., TextAlign::Right, cc)[0]; - let width = left.1 - left.0; - assert!(width > px(0.) && width < widest, "{left:?} in {widest:?}"); - // GPUI aligns each row in the width of the laid-out text, the wrap - // width here. - let align_width = px(45.); - assert_eq!(left.0, px(0.)); - assert_eq!( - center, - ( - (align_width - width) / 2., - (align_width + width) / 2., - left.2 - ) - ); - assert_eq!(right, (align_width - width, align_width, left.2)); - } -} - -/// A platform text system for tests where the `Mono` family shapes twice as -/// wide as every other family, so a measurement that ignores the family of a -/// run comes out visibly short. +mod line_bounds_tests; #[cfg(test)] -pub(super) mod test_draw { - use gpui::{App, Context, IntoElement, Render, Styled as _, TestApp, Window, canvas, px}; - use std::{cell::RefCell, rc::Rc}; - - struct Probe { - body: Option>, - } - - impl Render for Probe { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let body = self.body.take(); - canvas( - move |_, window, cx| { - if let Some(body) = body { - body(window, cx); - } - }, - |_, _, _, _| {}, - ) - .w(px(1000.)) - .h(px(1000.)) - } - } - - /// Runs `f` inside a real prepaint pass and returns its value. - /// - /// Measuring an inline object lays its GPUI element out through the - /// window, which GPUI only permits while a frame is being drawn, so a test - /// that builds a real element cannot call the measurement helpers straight - /// from `TestAppWindow::update`. - pub(crate) fn in_prepaint( - app: &mut TestApp, - f: impl FnOnce(&mut Window, &mut App) -> R + 'static, - ) -> R { - let slot: Rc>> = Rc::new(RefCell::new(None)); - let out = slot.clone(); - let mut window = app.open_window(|_, _| Probe { - body: Some(Box::new(move |window, cx| { - *out.borrow_mut() = Some(f(window, cx)); - })), - }); - window.draw(); - let value = slot.borrow_mut().take(); - value.expect("prepaint probe did not run") - } -} - +mod range_highlight_tests; #[cfg(test)] -pub(super) mod test_fonts { - use gpui::{ - Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun, FontWeight, GlyphId, LineLayout, - Pixels, PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, Size, - TextRenderingMode, point, px, size, - }; - use std::{borrow::Cow, cell::RefCell}; - - pub(crate) const BODY: &str = "Body"; - pub(crate) const MONO: &str = "Mono"; - const BODY_ID: FontId = FontId(1); - const MONO_ID: FontId = FontId(2); - const BOLD_BODY_ID: FontId = FontId(3); - const BOLD_MONO_ID: FontId = FontId(4); - const UNITS_PER_EM: f32 = 1000.; - - pub(crate) struct WideMonoTextSystem; - - impl WideMonoTextSystem { - /// Advance of one glyph in `font_id`, in em units. - fn advance_units(font_id: FontId) -> f32 { - match font_id { - MONO_ID => 1000., - BOLD_MONO_ID => 1250., - BODY_ID => 500., - BOLD_BODY_ID => 750., - _ => 500., - } - } - - /// Width of `text` shaped entirely in `family` at `font_size`. - pub(crate) fn width_of(text: &str, family: &str, font_size: Pixels) -> Pixels { - let font_id = if family == MONO { MONO_ID } else { BODY_ID }; - font_size * (Self::advance_units(font_id) / UNITS_PER_EM) * text.chars().count() as f32 - } - } - - thread_local! { - static SHAPED_LINE_RECORDER: RefCell>> = const { RefCell::new(None) }; - } - - struct ShapeRecorderGuard; - - impl Drop for ShapeRecorderGuard { - fn drop(&mut self) { - SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take()); - } - } - - /// Runs `f` while recording text submitted to [`PlatformTextSystem::layout_line`]. - pub(crate) fn record_shaped_lines(f: impl FnOnce() -> R) -> (R, Vec) { - SHAPED_LINE_RECORDER.with(|recorder| *recorder.borrow_mut() = Some(Vec::new())); - let _guard = ShapeRecorderGuard; - let result = f(); - let shaped_lines = - SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take().unwrap_or_default()); - (result, shaped_lines) - } - - impl PlatformTextSystem for WideMonoTextSystem { - fn add_fonts(&self, _fonts: Vec>) -> anyhow::Result<()> { - Ok(()) - } - - fn all_font_names(&self) -> Vec { - vec![BODY.into(), MONO.into()] - } - - fn font_id(&self, descriptor: &Font) -> anyhow::Result { - Ok( - match ( - descriptor.family.as_ref() == MONO, - descriptor.weight == FontWeight::BOLD, - ) { - (true, true) => BOLD_MONO_ID, - (true, false) => MONO_ID, - (false, true) => BOLD_BODY_ID, - (false, false) => BODY_ID, - }, - ) - } - - fn font_metrics(&self, _font_id: FontId) -> FontMetrics { - FontMetrics { - units_per_em: UNITS_PER_EM as u32, - ascent: 800., - descent: -200., - line_gap: 0., - underline_position: -100., - underline_thickness: 50., - cap_height: 700., - x_height: 500., - bounding_box: Bounds { - origin: point(0., -200.), - size: size(1000., 1000.), - }, - } - } - - fn typographic_bounds( - &self, - font_id: FontId, - _glyph_id: GlyphId, - ) -> anyhow::Result> { - Ok(Bounds { - origin: point(0., 0.), - size: size(Self::advance_units(font_id), 700.), - }) - } - - fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> anyhow::Result> { - Ok(size(Self::advance_units(font_id), 0.)) - } - - fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option { - Some(GlyphId(ch as u32)) - } - - fn glyph_raster_bounds( - &self, - _params: &RenderGlyphParams, - ) -> anyhow::Result> { - Ok(Bounds::default()) - } - - fn rasterize_glyph( - &self, - _params: &RenderGlyphParams, - raster_bounds: Bounds, - ) -> anyhow::Result<(Size, Vec)> { - Ok((raster_bounds.size, Vec::new())) - } - - fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { - SHAPED_LINE_RECORDER.with(|recorder| { - if let Some(lines) = recorder.borrow_mut().as_mut() { - lines.push(text.to_string()); - } - }); - - let mut position = px(0.); - let mut shaped_runs = Vec::new(); - let mut run_start = 0; - for run in runs { - let run_text = &text[run_start..run_start + run.len]; - let advance = font_size * (Self::advance_units(run.font_id) / UNITS_PER_EM); - let mut glyphs = Vec::new(); - for (ix, ch) in run_text.char_indices() { - glyphs.push(ShapedGlyph { - id: GlyphId(ch as u32), - position: point(position, px(0.)), - index: run_start + ix, - is_emoji: false, - }); - position += advance; - } - shaped_runs.push(ShapedRun { - font_id: run.font_id, - glyphs, - }); - run_start += run.len; - } - let metrics = self.font_metrics(BODY_ID); - LineLayout { - font_size, - width: position, - ascent: font_size * (metrics.ascent / UNITS_PER_EM), - // Native backends normalize the signed font metric for shaped lines. - descent: font_size * (-metrics.descent / UNITS_PER_EM), - runs: shaped_runs, - len: text.len(), - } - } - - fn recommended_rendering_mode( - &self, - _font_id: FontId, - _font_size: Pixels, - ) -> TextRenderingMode { - TextRenderingMode::Grayscale - } - } -} - +pub(super) mod test_draw; #[cfg(test)] -mod tests { - use super::{ - GlyphBox, InlineHighlight, aligned_row_left, combine_highlights, point_in_text_selection, - range_boxes, text_runs, - }; - use gpui::{FontWeight, HighlightStyle, SharedString, TextAlign, TextStyle, point, px}; - use std::ops::Range; - - fn mono(style: HighlightStyle) -> InlineHighlight { - InlineHighlight { - style, - font_family: Some(SharedString::from("Mono")), - font_size_scale: None, - } - } - - #[test] - fn text_runs_shape_a_code_highlight_in_its_font_family() { - let style = TextStyle { - font_family: SharedString::from("Body"), - ..Default::default() - }; - let highlights = vec![(4..8, mono(HighlightStyle::default()))]; - - let runs = text_runs(12, &style, &highlights); - - let families = runs - .iter() - .map(|run| (run.len, run.font.family.as_ref())) - .collect::>(); - assert_eq!(families, vec![(4, "Body"), (4, "Mono"), (4, "Body")]); - } - - #[test] - fn rows_align_the_way_gpui_paints_them() { - let width = px(100.); - assert_eq!(aligned_row_left(TextAlign::Left, width, px(40.)), px(0.)); - assert_eq!(aligned_row_left(TextAlign::Center, width, px(40.)), px(30.)); - assert_eq!(aligned_row_left(TextAlign::Right, width, px(40.)), px(60.)); - } - - fn glyph(text: Range, row: usize, left: f32, right: f32) -> GlyphBox { - GlyphBox { - text, - row, - left: px(left), - right: px(right), - } - } - - #[test] - fn range_boxes_join_the_glyphs_of_a_range_on_each_row() { - // "ab cd" wrapped after the space, glyphs 8px wide. - let glyphs = [ - glyph(0..1, 0, 0., 8.), - glyph(1..2, 0, 8., 16.), - glyph(2..3, 0, 16., 24.), - glyph(3..4, 1, 0., 8.), - glyph(4..5, 1, 8., 16.), - ]; - let boxes = |range| range_boxes(&glyphs, range); - assert_eq!(boxes(1..2), [(0, px(8.), px(16.))]); - assert_eq!(boxes(0..5), [(0, px(0.), px(24.)), (1, px(0.), px(16.))]); - // Starting at the wrap paints the next row only. - assert_eq!(boxes(3..5), [(1, px(0.), px(16.))]); - assert!(boxes(2..2).is_empty()); - } - - #[test] - fn range_boxes_follow_right_to_left_glyphs() { - // Three two-byte letters painted right to left: the first letter's - // glyph is the rightmost. - let glyphs = [ - glyph(0..2, 0, 16., 24.), - glyph(2..4, 0, 8., 16.), - glyph(4..6, 0, 0., 8.), - ]; - assert_eq!(range_boxes(&glyphs, 0..2), [(0, px(16.), px(24.))]); - assert_eq!(range_boxes(&glyphs, 2..6), [(0, px(0.), px(16.))]); - } - - #[test] - fn range_boxes_cover_a_glyph_drawing_part_of_the_range() { - // A ligature drawing "fi" in one glyph. - let glyphs = [glyph(0..2, 0, 0., 10.), glyph(2..3, 0, 10., 15.)]; - assert_eq!(range_boxes(&glyphs, 1..2), [(0, px(0.), px(10.))]); - } - - #[test] - fn combine_highlights_cuts_a_bold_span_at_the_code_boundary() { - // `**bold `code`**`: the bold mark spans the code mark, so the - // combined list carries the weight on both sides and the family on - // the code side only. - let bold = InlineHighlight::from(HighlightStyle { - font_weight: Some(FontWeight::BOLD), - ..Default::default() - }); - let combined = combine_highlights( - vec![(0..10, bold)], - vec![(6..10, mono(HighlightStyle::default()))], - ); - - assert_eq!(combined.len(), 2); - assert_eq!(combined[0].0, 0..6); - assert_eq!(combined[0].1.style.font_weight, Some(FontWeight::BOLD)); - assert_eq!(combined[0].1.font_family, None); - assert_eq!(combined[1].0, 6..10); - assert_eq!(combined[1].1.style.font_weight, Some(FontWeight::BOLD)); - assert_eq!(combined[1].1.font_family.as_deref(), Some("Mono")); - } - - #[test] - fn test_point_in_text_selection() { - let line_height = px(20.); - let char_width = px(10.); - let start = point(px(50.), px(50.)); - let end = point(px(150.), px(150.)); - - // First line but haft line height, true - // | p --------| - // | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(50.), px(40.)), - char_width, - start, - end, - line_height - )); - - // First line in selection, true - // | p --------| - // | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(50.), px(50.)), - char_width, - start, - end, - line_height - )); - // First line, but left out of selection, false - // p |-----------| - // | selection | - // |-----------| - assert!(!point_in_text_selection( - point(px(40.), px(50.)), - char_width, - start, - end, - line_height - )); - // First line but right out of selection, true - // |-----------| p - // | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(160.), px(50.)), - char_width, - start, - end, - line_height - )); - - // Middle line in selection, true - // |-----------| - // | p | - // |-----------| - assert!(point_in_text_selection( - point(px(100.), px(70.)), - char_width, - start, - end, - line_height - )); - // Middle line, but left out of selection, true - // |-----------| - // p | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(40.), px(70.)), - char_width, - start, - end, - line_height - )); - // Middle line, but right out of selection, true - // |-----------| - // | selection | p - // |-----------| - assert!(point_in_text_selection( - point(px(160.), px(70.)), - char_width, - start, - end, - line_height - )); - - // Last line in selection, true - // |-----------| - // | selection | - // |------- p -| - assert!(point_in_text_selection( - point(px(100.), px(140.)), - char_width, - start, - end, - line_height - )); - // Last line, but left out of selection, true - // - // |-----------| - // | selection | - // p |-----------| - assert!(point_in_text_selection( - point(px(40.), px(140.)), - char_width, - start, - end, - line_height - )); - // Last line, but right out of selection, false - // |-----------| - // | selection | - // |-----------| p - assert!(!point_in_text_selection( - point(px(160.), px(140.)), - char_width, - start, - end, - line_height - )); - - // Out of vertical bounds (top), false - // p - // |-----------| - // | selection | - // |-----------| - assert!(!point_in_text_selection( - point(px(100.), px(20.)), - char_width, - start, - end, - line_height - )); - // Out of vertical bounds (bottom), false - // |-----------| - // | selection | - // |-----------| - // p - assert!(!point_in_text_selection( - point(px(100.), px(160.)), - char_width, - start, - end, - line_height - )); - } - - #[test] - fn test_point_in_text_selection_reversed_drag_direction() { - let line_height = px(20.); - let char_width = px(10.); - - // Mouse down on lower line then drag upward to x=150. - // Top line should follow current mouse x, bottom line should keep anchor x. - let start = point(px(80.), px(150.)); - let end = point(px(150.), px(50.)); - - // On top line, selection starts from top cursor x (150), so x=140 should be excluded. - assert!(!point_in_text_selection( - point(px(140.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(point_in_text_selection( - point(px(150.), px(50.)), - char_width, - start, - end, - line_height - )); - - // On bottom line, selection ends at anchor x (80), so x=90 should be excluded. - assert!(point_in_text_selection( - point(px(75.), px(140.)), - char_width, - start, - end, - line_height - )); - assert!(!point_in_text_selection( - point(px(80.), px(140.)), - char_width, - start, - end, - line_height - )); - } - - #[test] - fn test_point_in_text_selection_same_visual_line_with_different_y() { - let line_height = px(20.); - let char_width = px(10.); - let start = point(px(100.), px(55.)); - let end = point(px(60.), px(58.)); - - assert!(!point_in_text_selection( - point(px(40.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(point_in_text_selection( - point(px(70.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(!point_in_text_selection( - point(px(110.), px(50.)), - char_width, - start, - end, - line_height - )); - } - - #[test] - fn test_point_in_text_selection_same_visual_line_with_reversed_y() { - let line_height = px(20.); - let char_width = px(10.); - let start = point(px(60.), px(58.)); - let end = point(px(100.), px(55.)); - - assert!(!point_in_text_selection( - point(px(40.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(point_in_text_selection( - point(px(70.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(!point_in_text_selection( - point(px(110.), px(50.)), - char_width, - start, - end, - line_height - )); - } -} - +pub(super) mod test_fonts; #[cfg(test)] -mod retained_layout_tests { - use gpui::{ - AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, - TestAppContext, Window, div, px, - }; - - use super::RETAINED_LAYOUTS; - use crate::text::{TextView, TextViewState}; - - /// The same document shown twice in one window, as a preview beside the - /// text: both `Inline`s share every `InlineState`. - struct Twice { - state: Entity, - } - - impl Render for Twice { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .w(px(300.)) - .child(TextView::new(&self.state)) - .child(TextView::new(&self.state)) - } - } - - /// Without the hand-over rule the second copy's prepaint replaced the - /// first copy's entry, and the first copy painted with the second's - /// layout — at the second's bounds. - #[gpui::test] - fn the_same_paragraph_rendered_twice_in_a_frame_keeps_one_layout_and_paints_both( - cx: &mut TestAppContext, - ) { - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, cx| Twice { - state: cx - .new(|cx| TextViewState::markdown("First paragraph.\n\nSecond **paragraph**.", cx)), - }); - cx.run_until_parked(); - - // Frame 1 fills the table, frame 2 reuses it; neither may lose the - // shaped text of either copy (painting an unmeasured placeholder - // panics inside GPUI). - for _ in 0..3 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - let retained = RETAINED_LAYOUTS.with(|layouts| layouts.borrow().len()); - assert_eq!(retained, 2, "one layout per paragraph state"); - } - - struct Once { - state: Entity, - } - - impl Render for Once { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div().w(px(300.)).child(TextView::new(&self.state)) - } - } - - /// A paragraph with a code span is laid out by `InlineFlow`, as one - /// `Inline` per wrapped fragment. The fragments' states have to outlive - /// the frame, or every frame shapes the fragments again and leaves the - /// table an entry nobody will take. - #[gpui::test] - fn inline_flow_fragments_keep_their_layouts_across_frames(cx: &mut TestAppContext) { - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, cx| Once { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - }); - cx.run_until_parked(); - - for _ in 0..3 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - // "Call ", "foo" and " now.": three fragments on one line. - let (retained, alive) = RETAINED_LAYOUTS.with(|layouts| { - let layouts = layouts.borrow(); - ( - layouts.len(), - layouts - .values() - .filter(|retained| retained.state.strong_count() > 0) - .count(), - ) - }); - assert_eq!(retained, 3, "one layout per fragment"); - assert_eq!( - alive, 3, - "every retained layout belongs to a live fragment state" - ); - } - - #[gpui::test] - fn shortening_an_inline_flow_releases_obsolete_fragment_layouts(cx: &mut TestAppContext) { - cx.update(crate::init); - let source = "word `code` ".repeat(100); - let (view, cx) = cx.add_window_view(|_, cx| Once { - state: cx.new(|cx| TextViewState::markdown(&source, cx)), - }); - cx.run_until_parked(); - for _ in 0..2 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - view.update(cx, |view, cx| { - view.state.update(cx, |state, cx| { - state.set_text("word `code` now", cx); - }); - }); - cx.run_until_parked(); - for _ in 0..2 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - let alive = RETAINED_LAYOUTS.with(|layouts| { - layouts - .borrow() - .values() - .filter(|retained| retained.state.strong_count() > 0) - .count() - }); - assert_eq!(alive, 3, "one live layout per remaining fragment"); - } -} +mod tests; diff --git a/vendor/gpui-base/src/text/inline/fade_highlights_tests.rs b/vendor/gpui-base/src/text/inline/fade_highlights_tests.rs new file mode 100644 index 00000000..c22e76eb --- /dev/null +++ b/vendor/gpui-base/src/text/inline/fade_highlights_tests.rs @@ -0,0 +1,36 @@ +use super::{InlineHighlight, fade_highlights}; +use gpui::HighlightStyle; + +#[test] +fn fades_text_and_background_only_inside_the_range() { + let code = InlineHighlight::from(HighlightStyle { + background_color: Some(gpui::red()), + ..Default::default() + }); + let combined = fade_highlights(vec![(0..4, code)], &[(2..6, 0.5)]); + + let ranges: Vec<_> = combined.iter().map(|(range, _)| range.clone()).collect(); + assert_eq!(ranges, vec![0..2, 2..4, 4..6]); + + let (_, untouched) = &combined[0]; + assert_eq!(untouched.style.fade_out, None); + assert_eq!(untouched.style.background_color.unwrap().a, 1.0); + + let (_, faded_code) = &combined[1]; + assert_eq!(faded_code.style.fade_out, Some(0.5)); + assert_eq!(faded_code.style.background_color.unwrap().a, 0.5); + + let (_, faded_text) = &combined[2]; + assert_eq!(faded_text.style.fade_out, Some(0.5)); + assert!(faded_text.style.background_color.is_none()); +} + +#[test] +fn no_fades_leave_highlights_untouched() { + let bold = InlineHighlight::from(HighlightStyle { + font_weight: Some(gpui::FontWeight::BOLD), + ..Default::default() + }); + let highlights = vec![(1..3, bold)]; + assert_eq!(fade_highlights(highlights.clone(), &[]), highlights); +} diff --git a/vendor/gpui-base/src/text/inline/geometry.rs b/vendor/gpui-base/src/text/inline/geometry.rs new file mode 100644 index 00000000..b30434cc --- /dev/null +++ b/vendor/gpui-base/src/text/inline/geometry.rs @@ -0,0 +1,204 @@ +use gpui::{Bounds, Half, Pixels, Point, TextAlign, TextLayout}; +use std::ops::Range; + +use crate::text::{TextViewMultiClickKind, selection::word_range_at}; + +/// Where one glyph of laid-out text paints: its row, and its horizontal +/// extent past the text's origin, alignment applied. `text` is the byte range +/// of the text it draws. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct GlyphBox { + pub(super) text: Range, + pub(super) row: usize, + pub(super) left: Pixels, + pub(super) right: Pixels, +} + +/// The glyphs of `text_layout`, sorted by the text they draw, each placed +/// the way GPUI paints it: every row aligned in `align_width` by `align`, +/// and a glyph reaching to the next one on its row, or to the row's end. +/// +/// Glyphs are read in the order they paint, so right-to-left text, whose +/// glyphs paint in the reverse order of its text, is placed as it shows. +pub(super) fn glyph_boxes( + text_layout: &TextLayout, + align: TextAlign, + align_width: Pixels, +) -> Vec { + let mut boxes = Vec::new(); + let mut row = 0; + let mut line_start = 0; + for line in text_layout.line_layouts() { + let layout = &line.unwrapped_layout; + let glyphs = layout + .runs + .iter() + .flat_map(|run| run.glyphs.iter()) + .collect::>(); + // Each row starts at a wrap boundary glyph, and ends where the next + // row starts, or at the end of the line. + let run_offsets = layout + .runs + .iter() + .scan(0, |offset, run| { + let start = *offset; + *offset += run.glyphs.len(); + Some(start) + }) + .collect::>(); + let row_starts = line + .wrap_boundaries + .iter() + .map(|boundary| run_offsets[boundary.run_ix] + boundary.glyph_ix) + .collect::>(); + let line_boxes = boxes.len(); + let mut from = 0; + for (row_in_line, to) in row_starts.iter().copied().chain([glyphs.len()]).enumerate() { + let start_x = if row_in_line == 0 { + Pixels::ZERO + } else { + glyphs[from].position.x + }; + let end_x = glyphs + .get(to) + .map_or(layout.width, |glyph| glyph.position.x); + let shift = aligned_row_left(align, align_width, end_x - start_x) - start_x; + for ix in from..to { + let glyph = glyphs[ix]; + let right = if ix + 1 < to { + glyphs[ix + 1].position.x + } else { + end_x + }; + boxes.push(GlyphBox { + text: line_start + glyph.index..line_start + glyph.index, + row: row + row_in_line, + left: shift + glyph.position.x, + right: shift + right, + }); + } + from = to; + } + + // A glyph draws its text up to where the next glyph's text starts. + let line_boxes = &mut boxes[line_boxes..]; + line_boxes.sort_by_key(|glyph| glyph.text.start); + let line_end = line_start + line.len(); + for ix in 0..line_boxes.len() { + let start = line_boxes[ix].text.start; + line_boxes[ix].text.end = line_boxes[ix + 1..] + .iter() + .map(|glyph| glyph.text.start) + .find(|next| *next > start) + .unwrap_or(line_end); + } + + row += line.wrap_boundaries.len() + 1; + line_start = line_end + 1; + } + boxes +} + +pub(super) fn aligned_row_left(align: TextAlign, align_width: Pixels, width: Pixels) -> Pixels { + match align { + TextAlign::Left => Pixels::ZERO, + TextAlign::Center => (align_width - width) / 2., + TextAlign::Right => align_width - width, + } +} + +/// The boxes behind the text of `range`, as a row and the horizontal extent +/// on it, from `glyphs` sorted by the text they draw: every glyph drawing +/// some of that text, joined where they touch on a row. +pub(super) fn range_boxes( + glyphs: &[GlyphBox], + range: Range, +) -> Vec<(usize, Pixels, Pixels)> { + let first = glyphs.partition_point(|glyph| glyph.text.end <= range.start); + let mut hits = glyphs[first..] + .iter() + .take_while(|glyph| glyph.text.start < range.end) + .map(|glyph| (glyph.row, glyph.left, glyph.right)) + .collect::>(); + hits.sort_by(|a, b| { + (a.0, a.1) + .partial_cmp(&(b.0, b.1)) + .unwrap_or(std::cmp::Ordering::Equal) + }); + + let mut boxes: Vec<(usize, Pixels, Pixels)> = Vec::with_capacity(hits.len()); + for (row, left, right) in hits { + match boxes.last_mut() { + Some(last) if last.0 == row && left <= last.2 => last.2 = last.2.max(right), + _ => boxes.push((row, left, right)), + } + } + boxes +} + +/// Check if a `pos` is within a `bounds`, considering multi-line selections. +pub(in crate::text) fn point_in_text_selection( + pos: Point, + char_width: Pixels, + selection_start: Point, + selection_end: Point, + line_height: Pixels, +) -> bool { + let point_in_line = |point: Point| point.y >= pos.y && point.y < pos.y + line_height; + let top = selection_start.y.min(selection_end.y); + let bottom = selection_start.y.max(selection_end.y); + let x = pos.x + char_width.half(); + + // Out of the vertical bounds + if pos.y + line_height <= top || pos.y > bottom { + return false; + } + + // Treat the selection as single-line when both drag points fall within the + // same rendered line, even if their y coordinates differ inside that line. + if point_in_line(selection_start) && point_in_line(selection_end) { + let left = selection_start.x.min(selection_end.x); + let right = selection_start.x.max(selection_end.x); + return x >= left && x <= right; + } + + let (top_point, bottom_point) = if selection_start.y < selection_end.y { + (selection_start, selection_end) + } else { + (selection_end, selection_start) + }; + let is_top_line = point_in_line(top_point); + let is_bottom_line = point_in_line(bottom_point); + + if is_top_line { + return x >= top_point.x; + } else if is_bottom_line { + return x <= bottom_point.x; + } else { + return true; + } +} + +pub(super) fn selection_for_multi_click( + text: &str, + text_layout: &TextLayout, + bounds: Bounds, + pos: Point, + kind: TextViewMultiClickKind, +) -> Option> { + if !bounds.contains(&pos) { + return None; + } + + let offset = text_layout.index_for_position(pos).ok()?; + + match kind { + TextViewMultiClickKind::Word => word_range_at(text, offset), + // Known limitation: a paragraph maps to a single Inline run here. When a + // paragraph embeds an inline image it is split into multiple Inline runs, + // so triple-click only selects the run on the clicked side of the image. + TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => { + (!text.is_empty()).then_some(0..text.len()) + } + } +} diff --git a/vendor/gpui-base/src/text/inline/highlights.rs b/vendor/gpui-base/src/text/inline/highlights.rs new file mode 100644 index 00000000..d51d69d3 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/highlights.rs @@ -0,0 +1,214 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{HighlightStyle, SharedString, TextRun, TextStyle}; +use smallvec::SmallVec; +use std::{mem, ops::Range}; + +/// The style applied to one range of inline text. +/// +/// A [`HighlightStyle`] carries no font family, so the family an inline code +/// span is set in rides beside it; `None` keeps the family of the enclosing +/// text style. +#[derive(Clone, Debug, Default, PartialEq)] +pub(in crate::text) struct InlineHighlight { + pub(in crate::text) style: HighlightStyle, + pub(in crate::text) font_family: Option, + pub(in crate::text) font_size_scale: Option, +} + +impl InlineHighlight { + /// Layers `other` over `self`, the way [`HighlightStyle::highlight`] does. + fn highlight(mut self, other: &InlineHighlight) -> Self { + self.style = self.style.highlight(other.style); + if other.font_family.is_some() { + self.font_family = other.font_family.clone(); + } + if other.font_size_scale.is_some() { + self.font_size_scale = other.font_size_scale; + } + self + } +} + +impl From for InlineHighlight { + fn from(style: HighlightStyle) -> Self { + Self { + style, + font_family: None, + font_size_scale: None, + } + } +} + +/// Merges two highlight lists over one text into non-overlapping ranges, +/// cutting at every endpoint of every input range. Same sweep as +/// [`gpui::combine_highlights`], for [`InlineHighlight`] payloads. +pub(super) fn combine_highlights( + a: impl IntoIterator, InlineHighlight)>, + b: impl IntoIterator, InlineHighlight)>, +) -> Vec<(Range, InlineHighlight)> { + let mut endpoints = Vec::new(); + let mut highlights = Vec::new(); + for (range, highlight) in a.into_iter().chain(b) { + if !range.is_empty() { + let id = highlights.len(); + endpoints.push((range.start, id, true)); + endpoints.push((range.end, id, false)); + highlights.push(highlight); + } + } + endpoints.sort_unstable_by_key(|(position, _, _)| *position); + + let mut combined = Vec::new(); + let mut active: Vec = Vec::new(); + let mut ix = 0; + for (position, id, is_start) in endpoints { + if position > ix && !active.is_empty() { + let style = active.iter().fold(InlineHighlight::default(), |acc, id| { + acc.highlight(&highlights[*id]) + }); + combined.push((ix..position, style)); + } + ix = position; + if is_start { + active.push(id); + } else { + active.retain(|active_id| *active_id != id); + } + } + combined +} + +// Nocterm: adjacent inline children usually contribute zero or one mark. +// Sweep only when marks overlap, so long paragraphs do not rebuild every +// earlier highlight while visiting each unstyled or singly styled child. +pub(in crate::text) fn append_node_highlights( + highlights: &mut Vec<(Range, InlineHighlight)>, + mut node: SmallVec<[(Range, InlineHighlight); 2]>, +) { + node.retain(|(span, _)| span.start < span.end); + let Some((first, _)) = node.first() else { + return; + }; + if highlights + .last() + .is_none_or(|(last, _)| last.end <= first.start) + && node.windows(2).all(|pair| pair[0].0.end <= pair[1].0.start) + { + highlights.extend(node); + } else { + *highlights = combine_highlights(mem::take(highlights), node); + } +} + +/// Layers a streamed fade-in over `highlights`: text inside each fade range +/// loses that share of its color, and a highlight background fades with it so +/// an inline code chip does not appear before its text. +pub(in crate::text) fn fade_highlights( + highlights: Vec<(Range, InlineHighlight)>, + fades: &[(Range, f32)], +) -> Vec<(Range, InlineHighlight)> { + if fades.is_empty() { + return highlights; + } + let fade_highlights = fades.iter().map(|(range, fade_out)| { + ( + range.clone(), + InlineHighlight::from(HighlightStyle { + fade_out: Some(*fade_out), + ..Default::default() + }), + ) + }); + let mut combined = combine_highlights(highlights, fade_highlights); + for (_, highlight) in &mut combined { + if let Some(fade_out) = highlight.style.fade_out + && let Some(background) = highlight.style.background_color.as_mut() + { + background.fade_out(fade_out); + } + } + combined +} + +/// Builds the [`TextRun`]s for `text_len` bytes of inline text: each +/// highlight refines `default_style` over its range, and a highlight that +/// names a font family shapes its run in that family. +pub(in crate::text) fn text_runs( + text_len: usize, + default_style: &TextStyle, + highlights: &[(Range, InlineHighlight)], +) -> Vec { + let mut runs = Vec::with_capacity(highlights.len() * 2 + 1); + let mut ix = 0; + for (range, highlight) in highlights { + if ix < range.start { + runs.push(default_style.clone().to_run(range.start - ix)); + } + let mut run = default_style + .clone() + .highlight(highlight.style) + .to_run(range.len()); + if let Some(family) = &highlight.font_family { + run.font.family = family.clone(); + } + runs.push(run); + ix = range.end; + } + if ix < text_len { + runs.push(default_style.to_run(text_len - ix)); + } + runs +} + +/// Splits text into contiguous ranges sharing one font size. GPUI runs can +/// vary the font but not its size, so each range needs its own shaped line. +pub(in crate::text) fn text_size_ranges( + text_len: usize, + highlights: &[(Range, InlineHighlight)], +) -> Vec<(Range, f32)> { + text_size_ranges_in(0..text_len, highlights) +} + +/// Selects highlights intersecting `span`. The input ranges are sorted and +/// disjoint, as produced by the inline highlight composition. +pub(in crate::text) fn highlights_in_range<'a>( + highlights: &'a [(Range, InlineHighlight)], + span: &Range, +) -> &'a [(Range, InlineHighlight)] { + let first = highlights.partition_point(|(range, _)| range.end <= span.start); + let remaining = &highlights[first..]; + let last = remaining.partition_point(|(range, _)| range.start < span.end); + &remaining[..last] +} + +/// Font-size segments clipped to an absolute byte range of the original text. +pub(in crate::text) fn text_size_ranges_in( + span: Range, + highlights: &[(Range, InlineHighlight)], +) -> Vec<(Range, f32)> { + let mut ranges: Vec<(Range, f32)> = Vec::new(); + let mut push = |range: Range, scale: f32| { + if range.is_empty() { + return; + } + if let Some((last, last_scale)) = ranges.last_mut() + && *last_scale == scale + && last.end == range.start + { + last.end = range.end; + } else { + ranges.push((range, scale)); + } + }; + let mut cursor = span.start; + for (range, highlight) in highlights_in_range(highlights, &span) { + let start = span.start.max(range.start); + let end = span.end.min(range.end); + push(cursor..start, 1.); + push(start..end, highlight.font_size_scale.unwrap_or(1.)); + cursor = end; + } + push(cursor..span.end, 1.); + ranges +} diff --git a/vendor/gpui-base/src/text/inline/line_bounds_tests.rs b/vendor/gpui-base/src/text/inline/line_bounds_tests.rs new file mode 100644 index 00000000..a147fb8f --- /dev/null +++ b/vendor/gpui-base/src/text/inline/line_bounds_tests.rs @@ -0,0 +1,149 @@ +use super::*; +use super::{ + test_draw::in_prepaint, + test_fonts::{BODY, WideMonoTextSystem}, +}; +use gpui::{AvailableSpace, TestApp, size}; + +/// The character walk this replaced, kept as the oracle: one box per +/// character from `position_for_index`, unioned per row. +fn by_character( + text: &str, + text_layout: &TextLayout, + line_height: Pixels, + mask_bounds: Bounds, +) -> Vec> { + let mut line_bounds = Vec::new(); + let mut current_line_y = None; + let mut current_bounds: Option> = None; + let mut offset = 0; + for c in text.chars() { + let next_offset = offset + c.len_utf8(); + let Some(pos) = text_layout.position_for_index(offset) else { + offset = next_offset; + continue; + }; + let mut char_width = line_height.half(); + if let Some(next_pos) = text_layout.position_for_index(next_offset) + && next_pos.y == pos.y + { + char_width = next_pos.x - pos.x; + } + let bounds = Bounds::from_corners(pos, point(pos.x + char_width, pos.y + line_height)) + .intersect(&mask_bounds); + if bounds.size.width > px(0.) && bounds.size.height > px(0.) { + if current_line_y == Some(pos.y) { + if let Some(current) = current_bounds.as_mut() { + *current = current.union(&bounds); + } + } else { + if let Some(current) = current_bounds.take() { + line_bounds.push(current); + } + current_line_y = Some(pos.y); + current_bounds = Some(bounds); + } + } + offset = next_offset; + } + if let Some(current) = current_bounds { + line_bounds.push(current); + } + line_bounds +} + +#[test] +fn row_walk_matches_the_character_walk() { + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, |window, cx| { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16.).into(), + ..Default::default() + }; + let origin = point(px(7.), px(11.)); + let mask = Bounds::new(point(px(0.), px(0.)), size(px(1000.), px(1000.))); + let clipped = Bounds::new(point(px(20.), px(30.)), size(px(50.), px(60.))); + for text in [ + "", + "one row", + "a long paragraph that wraps onto several rows of eight pixel glyphs", + "first line\nsecond line that also wraps around\n\nfourth", + "中文与 English 混排的一段文字也会换行", + "trailing newline\n", + ] { + for wrap_width in [40., 100., 1000.] { + let runs = text_runs(text.len(), &style, &[]); + let styled = StyledText::new(SharedString::from(text.to_string())).with_runs(runs); + let layout = styled.layout().clone(); + let mut element = styled.into_any_element(); + element.layout_as_root( + size( + AvailableSpace::Definite(px(wrap_width)), + AvailableSpace::MinContent, + ), + window, + cx, + ); + element.prepaint_at(origin, window, cx); + let line_height = layout.line_height(); + let full = Inline::text_line_bounds(&layout, line_height, mask); + for mask in [ + mask, + clipped, + Bounds::new( + point(origin.x, origin.y + line_height), + size(px(100.), line_height), + ), + Bounds::new( + point(origin.x, layout.bounds().bottom()), + size(px(100.), line_height), + ), + ] { + let expected = by_character(text, &layout, line_height, mask); + let actual = Inline::text_line_bounds(&layout, line_height, mask); + let clipped_full: Vec<_> = full + .iter() + .map(|bounds| bounds.intersect(&mask)) + .filter(|bounds| bounds.size.width > px(0.) && bounds.size.height > px(0.)) + .collect(); + assert_eq!(actual, clipped_full); + let context = format!("{text:?} at {wrap_width}px in {mask:?}"); + // The character walk placed a wrapped row's first + // character at the end of the row before it: that row's + // box started one glyph in, and a row holding only that + // one glyph had no box at all. The row walk covers every + // row from its start, so it may see more rows, never + // fewer, and agrees on every row the walk could see. + assert!( + actual.len() >= expected.len(), + "rows of {context}: {} < {}", + actual.len(), + expected.len() + ); + for (row, expected) in expected.iter().enumerate() { + let actual = actual + .iter() + .find(|actual| actual.top() == expected.top()) + .unwrap_or_else(|| panic!("row {row} of {context} is missing")); + assert_eq!(actual.bottom(), expected.bottom(), "row {row} of {context}"); + assert_eq!(actual.right(), expected.right(), "row {row} of {context}"); + assert!( + actual.left() <= expected.left(), + "row {row} of {context} starts at {:?}, after {:?}", + actual.left(), + expected.left() + ); + } + for actual in &actual { + assert_eq!( + actual.left(), + origin.x.max(mask.left()), + "left of {context}" + ); + } + } + } + } + }); +} diff --git a/vendor/gpui-base/src/text/inline/pointer.rs b/vendor/gpui-base/src/text/inline/pointer.rs new file mode 100644 index 00000000..f36b3568 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/pointer.rs @@ -0,0 +1,234 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use std::{ + ops::Range, + rc::Rc, + sync::{Arc, Mutex}, +}; + +use gpui::{ + App, Bounds, ClickEvent, CursorStyle, Hitbox, MouseButton, MouseClickEvent, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, TextLayout, Window, +}; + +use crate::{ + GlobalState, TextSelection, + text::TextViewMultiClickKind, + text::node::LinkMark, + text::text_view::{LinkClickHandlerFn, handle_link_click}, +}; + +use super::{InlineState, geometry::selection_for_multi_click}; + +/// The geometry and callbacks used to install one inline's pointer handlers. +pub(super) struct InlinePointer<'a> { + pub(super) hitbox: &'a Hitbox, + pub(super) text_layout: &'a TextLayout, + pub(super) inline_state: &'a Arc>, + pub(super) text: &'a SharedString, + pub(super) links: &'a Rc, LinkMark)>>, + pub(super) link_click_handler: &'a Option>, + pub(super) line_bounds: Option>, +} + +impl InlinePointer<'_> { + pub(super) fn register( + self, + is_selectable: bool, + is_selection: bool, + window: &mut Window, + cx: &mut App, + ) { + let Self { + hitbox, + text_layout, + inline_state, + text, + links, + link_click_handler, + line_bounds, + } = self; + let has_links = !links.is_empty(); + let current_view = window.current_view(); + let text_view_state = GlobalState::global(cx).text_view_state().cloned(); + if is_selection || is_selectable { + window.set_cursor_style(CursorStyle::IBeam, hitbox); + } + + // link cursor pointer + let hovered_link = has_links + .then(|| link_range_for_position(text_layout, links, window.mouse_position())) + .flatten(); + if hovered_link.is_some() { + window.set_cursor_style(CursorStyle::PointingHand, hitbox); + } + + if is_selectable { + window.on_mouse_event({ + let hitbox = hitbox.clone(); + let text_layout = text_layout.clone(); + let inline_state = inline_state.clone(); + let text = text.clone(); + let text_view_state = text_view_state.clone(); + move |event: &MouseDownEvent, phase, window, cx| { + if !phase.bubble() + || !hitbox.is_hovered(window) + || event.button != MouseButton::Left + { + return; + } + + if event.click_count == 3 + && let Some(line_bounds) = line_bounds + { + GlobalState::suppress_text_selection(cx); + if let Some(view) = &text_view_state { + view.update(cx, |state, cx| { + state.set_multi_click_line(line_bounds, cx) + }); + } + cx.notify(current_view); + return; + } + + // A finger selects read-only text with a long press only; + // a double tap selects nothing here, neither the mouse's + // plain word nor the window layer's touch selection. The + // handles and the menu on a double tap belong to `Input`. + if event.click_count == 2 && GlobalState::is_touch_press(cx) { + GlobalState::suppress_text_selection(cx); + return; + } + + let kind = match event.click_count { + 2 => TextViewMultiClickKind::Word, + 3 => TextViewMultiClickKind::Paragraph, + _ => return, + }; + + let Some(range) = selection_for_multi_click( + &text, + &text_layout, + hitbox.bounds, + event.position, + kind, + ) else { + return; + }; + + let selected_text = text[range.clone()].to_string(); + + // This renderer owns multi-click selection. Prevent the + // window selection layer from handling the same press. + GlobalState::suppress_text_selection(cx); + + if let Ok(mut inline_state) = inline_state.lock() { + inline_state.selection = Some(range.into()); + } + if let Some(text_view_state) = &text_view_state { + text_view_state.update(cx, |state, cx| { + state.set_multi_click_selection( + event.position, + kind, + selected_text, + cx, + ); + }); + } + cx.notify(current_view); + } + }); + } + + // Mouse move: repaint only when the pointer enters, leaves or moves + // between links, so the link cursor follows it. Hovering plain text + // changes nothing painted. + if has_links { + window.on_mouse_event({ + let hitbox = hitbox.clone(); + let text_layout = text_layout.clone(); + let links = links.clone(); + let mut hovered_link = hovered_link; + move |event: &MouseMoveEvent, phase, window, cx| { + if !phase.bubble() || !hitbox.is_hovered(window) { + return; + } + + let updated = link_range_for_position(&text_layout, &links, event.position); + if hovered_link != updated { + hovered_link = updated; + cx.notify(current_view); + } + } + }); + } + + if has_links && !is_selection { + // click to open link + window.on_mouse_event({ + let links = links.clone(); + let text_layout = text_layout.clone(); + let hitbox = hitbox.clone(); + let text_view_state = text_view_state.clone(); + let link_click_handler = link_click_handler.clone(); + + move |event: &MouseUpEvent, phase, window, cx| { + if !phase.bubble() || !hitbox.is_hovered(window) { + return; + } + if text_view_state + .as_ref() + .is_some_and(|state| state.read(cx).has_selection(cx)) + { + return; + } + + if let Some(link) = link_for_position(&text_layout, &links, event.position) { + TextSelection::end(window, cx); + cx.stop_propagation(); + let click = ClickEvent::Mouse(MouseClickEvent { + down: MouseDownEvent { + button: event.button, + position: event.position, + modifiers: event.modifiers, + click_count: event.click_count, + first_mouse: false, + }, + up: event.clone(), + }); + handle_link_click(&link_click_handler, link.url, click, window, cx); + } + } + }); + } + } +} + +/// Get link at given mouse position. +fn link_for_position( + layout: &TextLayout, + links: &[(Range, LinkMark)], + position: Point, +) -> Option { + let offset = layout.index_for_position(position).ok()?; + for (range, link) in links.iter() { + if range.contains(&offset) { + return Some(link.clone()); + } + } + + None +} + +/// Get the range of the link at given mouse position. +fn link_range_for_position( + layout: &TextLayout, + links: &[(Range, LinkMark)], + position: Point, +) -> Option> { + let offset = layout.index_for_position(position).ok()?; + links + .iter() + .find(|(range, _)| range.contains(&offset)) + .map(|(range, _)| range.clone()) +} diff --git a/vendor/gpui-base/src/text/inline/range_highlight_tests.rs b/vendor/gpui-base/src/text/inline/range_highlight_tests.rs new file mode 100644 index 00000000..dd7b3546 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/range_highlight_tests.rs @@ -0,0 +1,160 @@ +use super::*; +use super::{ + test_draw::in_prepaint, + test_fonts::{BODY, WideMonoTextSystem}, +}; +use gpui::{AvailableSpace, TestApp, TextAlign, size}; + +/// Lays `text` out at `wrap_width` and returns the highlight boxes of +/// `range` with rows aligned by `align`: the left and right edges past +/// the text's origin, and the row. +fn boxes( + text: &'static str, + wrap_width: f32, + align: TextAlign, + range: Range, +) -> Vec<(Pixels, Pixels, usize)> { + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, move |window, cx| { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16.).into(), + ..Default::default() + }; + let styled = + StyledText::new(SharedString::from(text)).with_runs(text_runs(text.len(), &style, &[])); + let layout = styled.layout().clone(); + let mut element = styled.into_any_element(); + element.layout_as_root( + size( + AvailableSpace::Definite(px(wrap_width)), + AvailableSpace::MinContent, + ), + window, + cx, + ); + let origin = point(px(7.), px(11.)); + element.prepaint_at(origin, window, cx); + let glyphs = glyph_boxes(&layout, align, layout.bounds().size.width); + range_boxes(&glyphs, range) + .into_iter() + .map(|(row, left, right)| (left, right, row)) + .collect() + }) +} + +/// The selection fast paths decide a whole inline from this extent, so it +/// must start exactly at the first row the per-character walk tests and +/// reach at least the bottom of the last one. It may reach further: a +/// trailing empty line, or a last row whose only character the walk +/// places at the end of the row before it, holds no row the walk tests. +#[test] +fn text_rows_extent_matches_the_character_walk() { + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, |window, cx| { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16.).into(), + ..Default::default() + }; + let origin = point(px(7.), px(11.3)); + for text in [ + "one row", + "a long paragraph that wraps onto several rows of eight pixel glyphs", + "first line\nsecond line that also wraps around\n\nfourth", + "中文与 English 混排的一段文字也会换行", + "trailing newline\n", + ] { + for wrap_width in [40., 100., 1000.] { + let runs = text_runs(text.len(), &style, &[]); + let styled = StyledText::new(SharedString::from(text.to_string())).with_runs(runs); + let layout = styled.layout().clone(); + let mut element = styled.into_any_element(); + element.layout_as_root( + size( + AvailableSpace::Definite(px(wrap_width)), + AvailableSpace::MinContent, + ), + window, + cx, + ); + element.prepaint_at(origin, window, cx); + // Taller than the layout's rows, as a window line height + // may be. + let line_height = layout.line_height() + px(3.); + let rows_y = text + .char_indices() + .filter_map(|(offset, _)| layout.position_for_index(offset)) + .map(|position| position.y); + let top = rows_y.clone().fold(Pixels::MAX, Pixels::min); + let bottom = rows_y.fold(Pixels::MIN, Pixels::max) + line_height; + + let (rows_top, rows_bottom) = text_rows_extent(&layout, line_height); + let context = format!("{text:?} at {wrap_width}px"); + assert_eq!(rows_top, top, "top of {context}"); + assert!(rows_bottom >= bottom, "bottom of {context}"); + } + } + }); +} + +#[test] +fn a_highlight_starting_a_wrapped_row_paints_only_that_row() { + // Three rows of "aaaa ", "bbbb ", "cccc". + let text = "aaaa bbbb cccc"; + let rows = boxes(text, 45., TextAlign::Left, 0..text.len()); + assert_eq!(rows.len(), 3, "{rows:?}"); + + let bbbb = text.find("bbbb").unwrap(); + let highlight = boxes(text, 45., TextAlign::Left, bbbb..bbbb + 4); + assert_eq!(highlight.len(), 1, "{highlight:?}"); + assert_eq!(highlight[0].0, px(0.)); + assert_eq!(highlight[0].2, 1); + + // Across the wrap, each row only as far as its text. + let across = boxes(text, 45., TextAlign::Left, 2..7); + assert_eq!(across.len(), 2, "{across:?}"); + assert_eq!(across[0].1, rows[0].1); + assert_eq!((across[1].0, across[1].2), (px(0.), 1)); +} + +#[test] +fn highlights_after_a_hard_line_break_start_on_its_row() { + // Rows "aa", "bbb cc": the break is one byte of the text, not a glyph. + let text = "aa\nbbb cc"; + let bbb = text.find("bbb").unwrap(); + let aa = boxes(text, 1000., TextAlign::Left, 0..2); + let highlight = boxes(text, 1000., TextAlign::Left, bbb..bbb + 3); + assert_eq!(highlight.len(), 1, "{highlight:?}"); + assert_eq!(highlight[0].0, px(0.)); + assert_eq!(highlight[0].2, 1); + // Three glyphs as wide as the two of "aa" and a half. + assert_eq!(highlight[0].1, (aa[0].1 - aa[0].0) * 1.5); +} + +#[test] +fn highlights_follow_centered_and_right_aligned_rows() { + // Rows "aaaa ", "bbbb ", "cc": the last is narrower than the text, so + // alignment moves it. + let text = "aaaa bbbb cc"; + let cc = text.find("cc").unwrap()..text.len(); + let widest = boxes(text, 45., TextAlign::Left, 0..5)[0].1; + let left = boxes(text, 45., TextAlign::Left, cc.clone())[0]; + let center = boxes(text, 45., TextAlign::Center, cc.clone())[0]; + let right = boxes(text, 45., TextAlign::Right, cc)[0]; + let width = left.1 - left.0; + assert!(width > px(0.) && width < widest, "{left:?} in {widest:?}"); + // GPUI aligns each row in the width of the laid-out text, the wrap + // width here. + let align_width = px(45.); + assert_eq!(left.0, px(0.)); + assert_eq!( + center, + ( + (align_width - width) / 2., + (align_width + width) / 2., + left.2 + ) + ); + assert_eq!(right, (align_width - width, align_width, left.2)); +} diff --git a/vendor/gpui-base/src/text/inline/retained_layout.rs b/vendor/gpui-base/src/text/inline/retained_layout.rs new file mode 100644 index 00000000..baa65e3b --- /dev/null +++ b/vendor/gpui-base/src/text/inline/retained_layout.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::InlineState; +use gpui::{SharedString, StyledText, TextRun, TextStyle}; +use std::{ + cell::RefCell, + collections::HashMap, + sync::{Arc, Mutex, Weak}, +}; + +/// One frame's [`StyledText`], kept for the next frame's [`super::Inline`] of the +/// same [`InlineState`]. +/// +/// A [`gpui::TextLayout`] remembers the size and the shaped lines of its last +/// measurement and answers a repeated measure at the same wrap width from +/// them, but a fresh `StyledText` every frame throws that away, so every +/// frame of a scroll paid for a line wrapper, a shaping-cache lookup that +/// hashes the whole paragraph, and the allocations around them for every +/// visible paragraph. Handing the same `StyledText` to the next frame makes +/// those measurements hits. A layout is only reused when the text, the runs +/// (colors, fades, fonts) and the text style (font size, line height) it was +/// shaped with are unchanged; a different wrap width misses inside +/// `TextLayout` and reshapes as before. +/// +/// `StyledText` is main-thread only (an `Rc` inside), while `InlineState` +/// travels through the background parse, so the layouts live in a +/// thread-local table keyed by the state's address, with a `Weak` to tell a +/// live state from a reused address. +pub(super) struct RetainedLayout { + pub(super) styled_text: StyledText, + pub(super) text: SharedString, + pub(super) runs: Vec, + pub(super) text_style: TextStyle, +} + +type InlineOwner = Mutex; + +struct Entry { + state: Weak, + layout: RetainedLayout, +} + +#[derive(Default)] +struct RetainedLayouts { + entries: HashMap, + inserts_until_sweep: usize, +} + +thread_local! { + static RETAINED_LAYOUTS: RefCell = RefCell::new(RetainedLayouts::default()); +} + +const RETAINED_SWEEP_AT: usize = 4096; + +impl RetainedLayouts { + fn insert(&mut self, state: &Arc, layout: RetainedLayout) { + if self.inserts_until_sweep == 0 + && (self.entries.len() >= RETAINED_SWEEP_AT + || self.entries.capacity() > RETAINED_SWEEP_AT * 4) + { + self.entries + .retain(|_, entry| entry.state.strong_count() > 0); + let live_budget = self.entries.len().max(RETAINED_SWEEP_AT); + if self.entries.capacity() > live_budget.saturating_mul(4) { + self.entries.shrink_to(live_budget); + } + // A sweep visits the table's buckets even if most are empty. + self.inserts_until_sweep = self.entries.capacity().max(RETAINED_SWEEP_AT); + } + self.inserts_until_sweep = self.inserts_until_sweep.saturating_sub(1); + self.entries.insert( + state_key(state), + Entry { + state: Arc::downgrade(state), + layout, + }, + ); + } +} + +fn state_key(state: &Arc) -> usize { + Arc::as_ptr(state) as usize +} + +/// Takes the layout retained for this exact state. +pub(super) fn take_retained_layout(state: &Arc) -> Option { + RETAINED_LAYOUTS.with(|layouts| { + let entry = layouts.borrow_mut().entries.remove(&state_key(state))?; + entry + .state + .upgrade() + .is_some_and(|live| Arc::ptr_eq(&live, state)) + .then_some(entry.layout) + }) +} + +/// An element of the same state may have handed over its layout this frame. +pub(super) fn has_retained_layout(state: &Arc) -> bool { + RETAINED_LAYOUTS.with(|layouts| layouts.borrow().entries.contains_key(&state_key(state))) +} + +pub(super) fn retain_layout(state: &Arc, layout: RetainedLayout) { + RETAINED_LAYOUTS.with(|layouts| layouts.borrow_mut().insert(state, layout)); +} + +#[cfg(test)] +mod tests; diff --git a/vendor/gpui-base/src/text/inline/retained_layout/tests.rs b/vendor/gpui-base/src/text/inline/retained_layout/tests.rs new file mode 100644 index 00000000..4322a1bd --- /dev/null +++ b/vendor/gpui-base/src/text/inline/retained_layout/tests.rs @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 + +use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, + TestAppContext, Window, div, px, +}; + +use super::RETAINED_LAYOUTS; +use crate::text::{TextView, TextViewState}; + +/// The same document shown twice in one window, as a preview beside the +/// text: both `Inline`s share every `InlineState`. +struct Twice { + state: Entity, +} + +impl Render for Twice { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(px(300.)) + .child(TextView::new(&self.state)) + .child(TextView::new(&self.state)) + } +} + +/// Without the hand-over rule the second copy's prepaint replaced the +/// first copy's entry, and the first copy painted with the second's +/// layout — at the second's bounds. +#[gpui::test] +fn the_same_paragraph_rendered_twice_in_a_frame_keeps_one_layout_and_paints_both( + cx: &mut TestAppContext, +) { + cx.update(crate::init); + let (_, cx) = cx.add_window_view(|_, cx| Twice { + state: cx + .new(|cx| TextViewState::markdown("First paragraph.\n\nSecond **paragraph**.", cx)), + }); + cx.run_until_parked(); + + // Frame 1 fills the table, frame 2 reuses it; neither may lose the + // shaped text of either copy (painting an unmeasured placeholder + // panics inside GPUI). + for _ in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + let retained = RETAINED_LAYOUTS.with(|layouts| layouts.borrow().entries.len()); + assert_eq!(retained, 2, "one layout per paragraph state"); +} + +struct Once { + state: Entity, +} + +impl Render for Once { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().w(px(300.)).child(TextView::new(&self.state)) + } +} + +/// A paragraph with a code span is laid out by `InlineFlow`, as one +/// `Inline` per wrapped fragment. The fragments' states have to outlive +/// the frame, or every frame shapes the fragments again and leaves the +/// table an entry nobody will take. +#[gpui::test] +fn inline_flow_fragments_keep_their_layouts_across_frames(cx: &mut TestAppContext) { + cx.update(crate::init); + let (_, cx) = cx.add_window_view(|_, cx| Once { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + }); + cx.run_until_parked(); + + for _ in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + // "Call ", "foo" and " now.": three fragments on one line. + let (retained, alive) = RETAINED_LAYOUTS.with(|layouts| { + let layouts = layouts.borrow(); + ( + layouts.entries.len(), + layouts + .entries + .values() + .filter(|retained| retained.state.strong_count() > 0) + .count(), + ) + }); + assert_eq!(retained, 3, "one layout per fragment"); + assert_eq!( + alive, 3, + "every retained layout belongs to a live fragment state" + ); +} + +#[gpui::test] +fn shortening_an_inline_flow_releases_obsolete_fragment_layouts(cx: &mut TestAppContext) { + cx.update(crate::init); + let source = "word `code` ".repeat(100); + let (view, cx) = cx.add_window_view(|_, cx| Once { + state: cx.new(|cx| TextViewState::markdown(&source, cx)), + }); + cx.run_until_parked(); + for _ in 0..2 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + view.update(cx, |view, cx| { + view.state.update(cx, |state, cx| { + state.set_text("word `code` now", cx); + }); + }); + cx.run_until_parked(); + for _ in 0..2 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + let alive = RETAINED_LAYOUTS.with(|layouts| { + layouts + .borrow() + .entries + .values() + .filter(|retained| retained.state.strong_count() > 0) + .count() + }); + assert_eq!(alive, 3, "one live layout per remaining fragment"); +} diff --git a/vendor/gpui-base/src/text/inline/test_draw.rs b/vendor/gpui-base/src/text/inline/test_draw.rs new file mode 100644 index 00000000..b2438c55 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/test_draw.rs @@ -0,0 +1,44 @@ +use gpui::{App, Context, IntoElement, Render, Styled as _, TestApp, Window, canvas, px}; +use std::{cell::RefCell, rc::Rc}; + +struct Probe { + body: Option>, +} + +impl Render for Probe { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let body = self.body.take(); + canvas( + move |_, window, cx| { + if let Some(body) = body { + body(window, cx); + } + }, + |_, _, _, _| {}, + ) + .w(px(1000.)) + .h(px(1000.)) + } +} + +/// Runs `f` inside a real prepaint pass and returns its value. +/// +/// Measuring an inline object lays its GPUI element out through the +/// window, which GPUI only permits while a frame is being drawn, so a test +/// that builds a real element cannot call the measurement helpers straight +/// from `TestAppWindow::update`. +pub(crate) fn in_prepaint( + app: &mut TestApp, + f: impl FnOnce(&mut Window, &mut App) -> R + 'static, +) -> R { + let slot: Rc>> = Rc::new(RefCell::new(None)); + let out = slot.clone(); + let mut window = app.open_window(|_, _| Probe { + body: Some(Box::new(move |window, cx| { + *out.borrow_mut() = Some(f(window, cx)); + })), + }); + window.draw(); + let value = slot.borrow_mut().take(); + value.expect("prepaint probe did not run") +} diff --git a/vendor/gpui-base/src/text/inline/test_fonts.rs b/vendor/gpui-base/src/text/inline/test_fonts.rs new file mode 100644 index 00000000..639e08fe --- /dev/null +++ b/vendor/gpui-base/src/text/inline/test_fonts.rs @@ -0,0 +1,181 @@ +use gpui::{ + Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun, FontWeight, GlyphId, LineLayout, + Pixels, PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, Size, TextRenderingMode, + point, px, size, +}; +use std::{borrow::Cow, cell::RefCell}; + +pub(crate) const BODY: &str = "Body"; +pub(crate) const MONO: &str = "Mono"; +const BODY_ID: FontId = FontId(1); +const MONO_ID: FontId = FontId(2); +const BOLD_BODY_ID: FontId = FontId(3); +const BOLD_MONO_ID: FontId = FontId(4); +const UNITS_PER_EM: f32 = 1000.; + +pub(crate) struct WideMonoTextSystem; + +impl WideMonoTextSystem { + /// Advance of one glyph in `font_id`, in em units. + fn advance_units(font_id: FontId) -> f32 { + match font_id { + MONO_ID => 1000., + BOLD_MONO_ID => 1250., + BODY_ID => 500., + BOLD_BODY_ID => 750., + _ => 500., + } + } + + /// Width of `text` shaped entirely in `family` at `font_size`. + pub(crate) fn width_of(text: &str, family: &str, font_size: Pixels) -> Pixels { + let font_id = if family == MONO { MONO_ID } else { BODY_ID }; + font_size * (Self::advance_units(font_id) / UNITS_PER_EM) * text.chars().count() as f32 + } +} + +thread_local! { + static SHAPED_LINE_RECORDER: RefCell>> = const { RefCell::new(None) }; +} + +struct ShapeRecorderGuard; + +impl Drop for ShapeRecorderGuard { + fn drop(&mut self) { + SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take()); + } +} + +/// Runs `f` while recording text submitted to [`PlatformTextSystem::layout_line`]. +pub(crate) fn record_shaped_lines(f: impl FnOnce() -> R) -> (R, Vec) { + SHAPED_LINE_RECORDER.with(|recorder| *recorder.borrow_mut() = Some(Vec::new())); + let _guard = ShapeRecorderGuard; + let result = f(); + let shaped_lines = + SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take().unwrap_or_default()); + (result, shaped_lines) +} + +impl PlatformTextSystem for WideMonoTextSystem { + fn add_fonts(&self, _fonts: Vec>) -> anyhow::Result<()> { + Ok(()) + } + + fn all_font_names(&self) -> Vec { + vec![BODY.into(), MONO.into()] + } + + fn font_id(&self, descriptor: &Font) -> anyhow::Result { + Ok( + match ( + descriptor.family.as_ref() == MONO, + descriptor.weight == FontWeight::BOLD, + ) { + (true, true) => BOLD_MONO_ID, + (true, false) => MONO_ID, + (false, true) => BOLD_BODY_ID, + (false, false) => BODY_ID, + }, + ) + } + + fn font_metrics(&self, _font_id: FontId) -> FontMetrics { + FontMetrics { + units_per_em: UNITS_PER_EM as u32, + ascent: 800., + descent: -200., + line_gap: 0., + underline_position: -100., + underline_thickness: 50., + cap_height: 700., + x_height: 500., + bounding_box: Bounds { + origin: point(0., -200.), + size: size(1000., 1000.), + }, + } + } + + fn typographic_bounds( + &self, + font_id: FontId, + _glyph_id: GlyphId, + ) -> anyhow::Result> { + Ok(Bounds { + origin: point(0., 0.), + size: size(Self::advance_units(font_id), 700.), + }) + } + + fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> anyhow::Result> { + Ok(size(Self::advance_units(font_id), 0.)) + } + + fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option { + Some(GlyphId(ch as u32)) + } + + fn glyph_raster_bounds( + &self, + _params: &RenderGlyphParams, + ) -> anyhow::Result> { + Ok(Bounds::default()) + } + + fn rasterize_glyph( + &self, + _params: &RenderGlyphParams, + raster_bounds: Bounds, + ) -> anyhow::Result<(Size, Vec)> { + Ok((raster_bounds.size, Vec::new())) + } + + fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { + SHAPED_LINE_RECORDER.with(|recorder| { + if let Some(lines) = recorder.borrow_mut().as_mut() { + lines.push(text.to_string()); + } + }); + + let mut position = px(0.); + let mut shaped_runs = Vec::new(); + let mut run_start = 0; + for run in runs { + let run_text = &text[run_start..run_start + run.len]; + let advance = font_size * (Self::advance_units(run.font_id) / UNITS_PER_EM); + let mut glyphs = Vec::new(); + for (ix, ch) in run_text.char_indices() { + glyphs.push(ShapedGlyph { + id: GlyphId(ch as u32), + position: point(position, px(0.)), + index: run_start + ix, + is_emoji: false, + }); + position += advance; + } + shaped_runs.push(ShapedRun { + font_id: run.font_id, + glyphs, + }); + run_start += run.len; + } + let metrics = self.font_metrics(BODY_ID); + LineLayout { + font_size, + width: position, + ascent: font_size * (metrics.ascent / UNITS_PER_EM), + // Native backends normalize the signed font metric for shaped lines. + descent: font_size * (-metrics.descent / UNITS_PER_EM), + runs: shaped_runs, + len: text.len(), + } + } + + fn recommended_rendering_mode( + &self, + _font_id: FontId, + _font_size: Pixels, + ) -> TextRenderingMode { + TextRenderingMode::Grayscale + } +} diff --git a/vendor/gpui-base/src/text/inline/tests.rs b/vendor/gpui-base/src/text/inline/tests.rs new file mode 100644 index 00000000..f8159075 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/tests.rs @@ -0,0 +1,410 @@ +use super::{ + InlineHighlight, + geometry::{GlyphBox, aligned_row_left}, + highlights::combine_highlights, + point_in_text_selection, range_boxes, text_runs, +}; +use gpui::{FontWeight, HighlightStyle, SharedString, TextAlign, TextStyle, point, px}; +use std::ops::Range; + +fn mono(style: HighlightStyle) -> InlineHighlight { + InlineHighlight { + style, + font_family: Some(SharedString::from("Mono")), + font_size_scale: None, + } +} + +#[test] +fn text_runs_shape_a_code_highlight_in_its_font_family() { + let style = TextStyle { + font_family: SharedString::from("Body"), + ..Default::default() + }; + let highlights = vec![(4..8, mono(HighlightStyle::default()))]; + + let runs = text_runs(12, &style, &highlights); + + let families = runs + .iter() + .map(|run| (run.len, run.font.family.as_ref())) + .collect::>(); + assert_eq!(families, vec![(4, "Body"), (4, "Mono"), (4, "Body")]); +} + +#[test] +fn rows_align_the_way_gpui_paints_them() { + let width = px(100.); + assert_eq!(aligned_row_left(TextAlign::Left, width, px(40.)), px(0.)); + assert_eq!(aligned_row_left(TextAlign::Center, width, px(40.)), px(30.)); + assert_eq!(aligned_row_left(TextAlign::Right, width, px(40.)), px(60.)); +} + +fn glyph(text: Range, row: usize, left: f32, right: f32) -> GlyphBox { + GlyphBox { + text, + row, + left: px(left), + right: px(right), + } +} + +#[test] +fn range_boxes_join_the_glyphs_of_a_range_on_each_row() { + // "ab cd" wrapped after the space, glyphs 8px wide. + let glyphs = [ + glyph(0..1, 0, 0., 8.), + glyph(1..2, 0, 8., 16.), + glyph(2..3, 0, 16., 24.), + glyph(3..4, 1, 0., 8.), + glyph(4..5, 1, 8., 16.), + ]; + let boxes = |range| range_boxes(&glyphs, range); + assert_eq!(boxes(1..2), [(0, px(8.), px(16.))]); + assert_eq!(boxes(0..5), [(0, px(0.), px(24.)), (1, px(0.), px(16.))]); + // Starting at the wrap paints the next row only. + assert_eq!(boxes(3..5), [(1, px(0.), px(16.))]); + assert!(boxes(2..2).is_empty()); +} + +#[test] +fn range_boxes_follow_right_to_left_glyphs() { + // Three two-byte letters painted right to left: the first letter's + // glyph is the rightmost. + let glyphs = [ + glyph(0..2, 0, 16., 24.), + glyph(2..4, 0, 8., 16.), + glyph(4..6, 0, 0., 8.), + ]; + assert_eq!(range_boxes(&glyphs, 0..2), [(0, px(16.), px(24.))]); + assert_eq!(range_boxes(&glyphs, 2..6), [(0, px(0.), px(16.))]); +} + +#[test] +fn range_boxes_cover_a_glyph_drawing_part_of_the_range() { + // A ligature drawing "fi" in one glyph. + let glyphs = [glyph(0..2, 0, 0., 10.), glyph(2..3, 0, 10., 15.)]; + assert_eq!(range_boxes(&glyphs, 1..2), [(0, px(0.), px(10.))]); +} + +#[test] +fn combine_highlights_cuts_a_bold_span_at_the_code_boundary() { + // `**bold `code`**`: the bold mark spans the code mark, so the + // combined list carries the weight on both sides and the family on + // the code side only. + let bold = InlineHighlight::from(HighlightStyle { + font_weight: Some(FontWeight::BOLD), + ..Default::default() + }); + let combined = combine_highlights( + vec![(0..10, bold)], + vec![(6..10, mono(HighlightStyle::default()))], + ); + + assert_eq!(combined.len(), 2); + assert_eq!(combined[0].0, 0..6); + assert_eq!(combined[0].1.style.font_weight, Some(FontWeight::BOLD)); + assert_eq!(combined[0].1.font_family, None); + assert_eq!(combined[1].0, 6..10); + assert_eq!(combined[1].1.style.font_weight, Some(FontWeight::BOLD)); + assert_eq!(combined[1].1.font_family.as_deref(), Some("Mono")); +} + +#[test] +fn appending_child_marks_matches_the_sweep_for_gaps_and_nested_styles() { + let bold = InlineHighlight::from(HighlightStyle { + font_weight: Some(FontWeight::BOLD), + ..Default::default() + }); + let code = mono(HighlightStyle::default()); + let cases = [ + vec![(0..6, bold.clone())], + vec![], + vec![(8..8, code.clone()), (8..14, bold.clone())], + vec![(18..22, code.clone()), (16..22, bold.clone())], + vec![(22..23, code)], + ]; + let mut old = Vec::new(); + let mut current = Vec::new(); + for child in cases { + old = combine_highlights(old, child.clone()); + super::append_node_highlights(&mut current, child.into_iter().collect()); + assert_eq!(current, old); + } +} + +#[test] +#[ignore = "manual release benchmark for long formatted paragraphs"] +fn many_child_marks_benchmark() { + let style = mono(HighlightStyle::default()); + let mut old = Vec::new(); + let previous = std::time::Instant::now(); + for index in 0..512 { + let first = index * 4; + old = combine_highlights(old, [(first..first + 2, style.clone())]); + } + let previous = previous.elapsed(); + let mut current = Vec::new(); + let optimized = std::time::Instant::now(); + for index in 0..512 { + let first = index * 4; + super::append_node_highlights( + &mut current, + [(first..first + 2, style.clone())].into_iter().collect(), + ); + } + let optimized = optimized.elapsed(); + assert_eq!(current, old); + eprintln!("512 children: sweep {previous:?}, append {optimized:?}"); +} + +#[test] +fn test_point_in_text_selection() { + let line_height = px(20.); + let char_width = px(10.); + let start = point(px(50.), px(50.)); + let end = point(px(150.), px(150.)); + + // First line but haft line height, true + // | p --------| + // | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(50.), px(40.)), + char_width, + start, + end, + line_height + )); + + // First line in selection, true + // | p --------| + // | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(50.), px(50.)), + char_width, + start, + end, + line_height + )); + // First line, but left out of selection, false + // p |-----------| + // | selection | + // |-----------| + assert!(!point_in_text_selection( + point(px(40.), px(50.)), + char_width, + start, + end, + line_height + )); + // First line but right out of selection, true + // |-----------| p + // | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(160.), px(50.)), + char_width, + start, + end, + line_height + )); + + // Middle line in selection, true + // |-----------| + // | p | + // |-----------| + assert!(point_in_text_selection( + point(px(100.), px(70.)), + char_width, + start, + end, + line_height + )); + // Middle line, but left out of selection, true + // |-----------| + // p | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(40.), px(70.)), + char_width, + start, + end, + line_height + )); + // Middle line, but right out of selection, true + // |-----------| + // | selection | p + // |-----------| + assert!(point_in_text_selection( + point(px(160.), px(70.)), + char_width, + start, + end, + line_height + )); + + // Last line in selection, true + // |-----------| + // | selection | + // |------- p -| + assert!(point_in_text_selection( + point(px(100.), px(140.)), + char_width, + start, + end, + line_height + )); + // Last line, but left out of selection, true + // + // |-----------| + // | selection | + // p |-----------| + assert!(point_in_text_selection( + point(px(40.), px(140.)), + char_width, + start, + end, + line_height + )); + // Last line, but right out of selection, false + // |-----------| + // | selection | + // |-----------| p + assert!(!point_in_text_selection( + point(px(160.), px(140.)), + char_width, + start, + end, + line_height + )); + + // Out of vertical bounds (top), false + // p + // |-----------| + // | selection | + // |-----------| + assert!(!point_in_text_selection( + point(px(100.), px(20.)), + char_width, + start, + end, + line_height + )); + // Out of vertical bounds (bottom), false + // |-----------| + // | selection | + // |-----------| + // p + assert!(!point_in_text_selection( + point(px(100.), px(160.)), + char_width, + start, + end, + line_height + )); +} + +#[test] +fn test_point_in_text_selection_reversed_drag_direction() { + let line_height = px(20.); + let char_width = px(10.); + + // Mouse down on lower line then drag upward to x=150. + // Top line should follow current mouse x, bottom line should keep anchor x. + let start = point(px(80.), px(150.)); + let end = point(px(150.), px(50.)); + + // On top line, selection starts from top cursor x (150), so x=140 should be excluded. + assert!(!point_in_text_selection( + point(px(140.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(point_in_text_selection( + point(px(150.), px(50.)), + char_width, + start, + end, + line_height + )); + + // On bottom line, selection ends at anchor x (80), so x=90 should be excluded. + assert!(point_in_text_selection( + point(px(75.), px(140.)), + char_width, + start, + end, + line_height + )); + assert!(!point_in_text_selection( + point(px(80.), px(140.)), + char_width, + start, + end, + line_height + )); +} + +#[test] +fn test_point_in_text_selection_same_visual_line_with_different_y() { + let line_height = px(20.); + let char_width = px(10.); + let start = point(px(100.), px(55.)); + let end = point(px(60.), px(58.)); + + assert!(!point_in_text_selection( + point(px(40.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(point_in_text_selection( + point(px(70.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(!point_in_text_selection( + point(px(110.), px(50.)), + char_width, + start, + end, + line_height + )); +} + +#[test] +fn test_point_in_text_selection_same_visual_line_with_reversed_y() { + let line_height = px(20.); + let char_width = px(10.); + let start = point(px(60.), px(58.)); + let end = point(px(100.), px(55.)); + + assert!(!point_in_text_selection( + point(px(40.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(point_in_text_selection( + point(px(70.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(!point_in_text_selection( + point(px(110.), px(50.)), + char_width, + start, + end, + line_height + )); +} diff --git a/vendor/gpui-base/src/text/inline_flow.rs b/vendor/gpui-base/src/text/inline_flow.rs index 00de6d88..121b9605 100644 --- a/vendor/gpui-base/src/text/inline_flow.rs +++ b/vendor/gpui-base/src/text/inline_flow.rs @@ -1,29 +1,36 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + use std::{ cell::RefCell, ops::Range, rc::Rc, sync::{Arc, Mutex}, }; -use unicode_segmentation::UnicodeSegmentation as _; use gpui::{ - AbsoluteLength, AnyElement, App, AvailableSpace, Bounds, DefiniteLength, Element, ElementId, - GlobalElementId, Hsla, ImageSource, InspectorElementId, InteractiveElement as _, IntoElement, - LayoutId, LineFragment as WrapLineFragment, ObjectFit, Pixels, Refineable as _, ShapedLine, - SharedString, Size, StatefulInteractiveElement as _, Styled, StyledImage as _, TextRun, - TextStyle, WhiteSpace, Window, img, point, prelude::FluentBuilder as _, px, relative, size, + AnyElement, App, AvailableSpace, Bounds, DefiniteLength, Element, ElementId, GlobalElementId, + Hsla, ImageSource, InspectorElementId, InteractiveElement as _, IntoElement, LayoutId, + ObjectFit, Pixels, Refineable as _, SharedString, Size, StatefulInteractiveElement as _, + Styled, StyledImage as _, TextStyle, WhiteSpace, Window, img, point, + prelude::FluentBuilder as _, px, relative, size, }; use crate::text::text_view::{LinkClickHandlerFn, handle_link_click}; use super::{ - inline::{Inline, InlineHighlight, InlineState, text_runs, text_size_ranges}, - inline_object::{InlineObject, MeasuredInlineObject}, + inline::{Inline, InlineHighlight, InlinePrepaint, InlineState}, + inline_object::InlineObject, node::LinkMark, range_highlight::RevealAt, }; -const IMAGE_LEN: usize = 1; +mod layout; + +pub(super) use layout::intrinsic_width; +use layout::{ + InlineFlowLayout, MeasureItem, PositionedFragment, layout_measured_flow, measure_image_size, + prepare_objects, +}; pub(super) const INLINE_CODE_PADDING: f32 = 2.; pub(super) struct InlineFlow { @@ -167,80 +174,6 @@ struct InlineFlowTypography { line_height: Pixels, } -#[derive(Default)] -struct InlineFlowLayout { - fragments: Vec, - size: Size, - wrap_width: Option, -} - -enum PositionedFragment { - Object { - item_ix: usize, - origin: gpui::Point, - object: Box, - selection_bounds: Bounds, - }, - Text { - item_ix: usize, - origin: gpui::Point, - size: Size, - source_range: Range, - font_size: Pixels, - text: SharedString, - links: Vec<(Range, LinkMark)>, - highlights: Vec<(Range, InlineHighlight)>, - selection_bounds: Bounds, - /// The rounded box behind a code span, relative to the flow. - code_background: Option<(Bounds, Hsla)>, - }, - Image { - item_ix: usize, - origin: gpui::Point, - size: Size, - }, -} - -enum MeasureItem { - Object { - text: SharedString, - id: usize, - renderer: Arc, - style: gpui::HighlightStyle, - }, - Text { - text: SharedString, - links: Vec<(Range, LinkMark)>, - highlights: Vec<(Range, InlineHighlight)>, - }, - Image { - source: ImageSource, - width: Option, - height: Option, - }, -} - -struct LineFragmentLayout { - item_ix: usize, - kind: LineFragmentKind, - size: Size, - source_range: Range, - baseline: Pixels, -} - -enum LineFragmentKind { - Object(Box), - Text { - font_size: Pixels, - text: SharedString, - links: Vec<(Range, LinkMark)>, - highlights: Vec<(Range, InlineHighlight)>, - /// The code span's box, relative to the fragment. - code_background: Option<(Bounds, Hsla)>, - }, - Image, -} - impl InlineFlow { pub(super) fn new( id: impl Into, @@ -307,9 +240,23 @@ impl IntoElement for InlineFlow { } } +// Nocterm: positioned text needs no layout-tree node or drawable wrapper. +pub(super) struct InlineFlowPrepaint { + order: Vec, + text: Vec<(Inline, Bounds, InlinePrepaint)>, +} + +enum PrepaintedFragment { + Text { + index: usize, + background: Option<(Bounds, Hsla)>, + }, + Element(AnyElement), +} + impl Element for InlineFlow { type RequestLayoutState = InlineFlowLayoutState; - type PrepaintState = Vec<(AnyElement, Option<(Bounds, gpui::Hsla)>)>; + type PrepaintState = InlineFlowPrepaint; fn id(&self) -> Option { Some(self.id.clone()) @@ -428,12 +375,23 @@ impl Element for InlineFlow { cx: &mut App, ) -> Self::PrepaintState { let frame_state = request_layout.frame_state.clone(); + let mut prepaint = InlineFlowPrepaint { + order: Vec::new(), + text: Vec::new(), + }; let Some(layout) = request_layout.current.borrow().clone() else { - return Vec::new(); + return prepaint; }; let typography = request_layout.typography.clone(); let text_style = &typography.text_style; - let mut elements = Vec::with_capacity(layout.fragments.len()); + prepaint.order.reserve(layout.fragments.len()); + prepaint.text.reserve( + layout + .fragments + .iter() + .filter(|fragment| matches!(fragment, PositionedFragment::Text { .. })) + .count(), + ); // A reveal goes to the fragment it starts in. A line break lays out // no fragment, so a reveal starting on one, or on an empty line, goes @@ -510,7 +468,7 @@ impl Element for InlineFlow { window, cx, ); - elements.push((element, None)); + prepaint.order.push(PrepaintedFragment::Element(element)); } PositionedFragment::Text { item_ix, @@ -578,35 +536,26 @@ impl Element for InlineFlow { .filter(|_| reveal_fragment == Some(fragment_ix)) .map(|reveal| reveal.clamp(source_range.start, source_range.end)), ) - .text_style(fragment_style.clone()) .selection_bounds(Bounds::new( point(bounds.left(), bounds.top() + selection_bounds.top()), size(bounds.size.width, selection_bounds.size.height), - )) - .paint_origin(bounds.origin + origin + point(padding, Pixels::ZERO)) - .into_any_element(); - // The `Inline` is its own layout root, with no box around - // it: its text measures with the window's text style, so - // the fragment's style is pushed for the layout. - window.with_rem_size(Some(typography.rem_size), |window| { - window.with_text_style( - Some(fragment_style.subtract(&Default::default())), - |window| { - element.prepaint_as_root( - bounds.origin + origin + point(padding, Pixels::ZERO), - size( - AvailableSpace::Definite( - fragment_size.width - padding * 2., - ), - AvailableSpace::Definite(fragment_size.height), - ), - window, - cx, - ); - }, - ); + )); + let refinement = fragment_style.subtract(&Default::default()); + let available = Bounds::new( + bounds.origin + origin + point(padding, Pixels::ZERO), + size(fragment_size.width - padding * 2., fragment_size.height), + ); + let (bounds, prepared) = + window.with_rem_size(Some(typography.rem_size), |window| { + window.with_text_style(Some(refinement), |window| { + element.prepaint_positioned(available, fragment_style, window, cx) + }) + }); + prepaint.order.push(PrepaintedFragment::Text { + index: prepaint.text.len(), + background, }); - elements.push((element, background)); + prepaint.text.push((element, bounds, prepared)); } PositionedFragment::Image { item_ix, @@ -624,7 +573,7 @@ impl Element for InlineFlow { }; let (origin, fragment_size) = (*origin, *fragment_size); let mut element = Self::image_element( - elements.len(), + prepaint.order.len(), source, link, title.as_str(), @@ -640,7 +589,7 @@ impl Element for InlineFlow { window, cx, ); - elements.push((element, None)); + prepaint.order.push(PrepaintedFragment::Element(element)); } } } @@ -650,7 +599,7 @@ impl Element for InlineFlow { .fragment_states .truncate(text_fragment_count); - elements + prepaint } fn paint( @@ -675,774 +624,21 @@ impl Element for InlineFlow { } } let radius = crate::Theme::global(cx).tokens.radius.sm; - for (element, background) in prepaint { - if let Some((bounds, color)) = background { - window.paint_quad(gpui::fill(*bounds, *color).corner_radii(radius)); - } - element.paint(window, cx); - } - } -} - -impl From<&InlineFlowItem> for MeasureItem { - fn from(item: &InlineFlowItem) -> Self { - match item { - InlineFlowItem::Object { - text, - id, - renderer, - style, - .. - } => Self::Object { - text: text.clone(), - id: *id, - renderer: renderer.clone(), - style: *style, - }, - InlineFlowItem::Text { - state: _, - text, - links, - highlights, - .. - } => MeasureItem::Text { - text: text.clone(), - links: links.clone(), - highlights: highlights.clone(), - }, - InlineFlowItem::Image { - source, - width, - height, - .. - } => MeasureItem::Image { - source: source.clone(), - width: *width, - height: *height, - }, - } - } -} - -impl MeasureItem { - fn len(&self) -> usize { - match self { - MeasureItem::Text { text, .. } => text.len(), - MeasureItem::Image { .. } | MeasureItem::Object { .. } => IMAGE_LEN, - } - } - - /// Whether `other` lays out the same as this item. An object is - /// rendered anew every frame, so a flow with one is never reused. - fn same_layout_input(&self, other: &Self) -> bool { - match (self, other) { - ( - MeasureItem::Text { - text, - links, - highlights, - }, - MeasureItem::Text { - text: other_text, - links: other_links, - highlights: other_highlights, - }, - ) => text == other_text && links == other_links && highlights == other_highlights, - ( - MeasureItem::Image { width, height, .. }, - MeasureItem::Image { - width: other_width, - height: other_height, - .. - }, - ) => width == other_width && height == other_height, - _ => false, - } - } -} - -/// Intrinsic width for table sizing, using the same objects and wrapping inputs as painting. -pub(super) fn intrinsic_width( - items: &[InlineFlowItem], - window: &mut Window, - cx: &mut App, -) -> Pixels { - let items = items.iter().map(MeasureItem::from).collect::>(); - let line_height = window.line_height(); - let rem_size = window.rem_size(); - let images = items - .iter() - .enumerate() - .map(|(ix, item)| match item { - MeasureItem::Image { - source, - width, - height, - } => Some(measure_image_size( - ix, - source, - *width, - *height, - line_height, - rem_size, - window, - cx, - )), - _ => None, - }) - .collect::>(); - layout_flow(&items, &images, &window.text_style(), None, window, cx) - .size - .width -} - -fn prepare_objects( - items: &[MeasureItem], - text_style: &TextStyle, - window: &mut Window, - cx: &mut App, -) -> Vec> { - items - .iter() - .map(|item| match item { - MeasureItem::Object { - text, - id, - renderer, - style, - } => { - let style = text_style.clone().highlight(*style); - let context = super::InlineRenderContext::new( - style.clone(), - style.font_size.to_pixels(window.rem_size()), - style.line_height_in_pixels(window.rem_size()), - window.rem_size(), - ); - // Must be the id `InlineObject` paints under: GPUI asserts a - // stateful child (a plugin's HoverCard) sees the same id path - // in request_layout as in prepaint, and the element is laid - // out here but painted inside `InlineObject`. - Some(window.with_id(("inline-object", *id), |window| { - let element = window - .with_text_style(Some(style.subtract(&Default::default())), |window| { - renderer(&context, window, cx) - }); - MeasuredInlineObject::measure(text, element, &style, window, cx) - })) - } - _ => None, - }) - .collect() -} - -fn layout_flow( - items: &[MeasureItem], - image_sizes: &[Option>], - text_style: &TextStyle, - wrap_width: Option, - window: &mut Window, - cx: &mut App, -) -> InlineFlowLayout { - let objects = prepare_objects(items, text_style, window, cx); - layout_measured_flow( - items, - image_sizes, - &objects, - text_style, - wrap_width, - window, - cx, - ) -} - -#[cfg(test)] -thread_local! { - /// How many flows were laid out (wrapped and shaped) on this thread. - pub(super) static FLOW_LAYOUTS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -fn layout_measured_flow( - items: &[MeasureItem], - image_sizes: &[Option>], - prepared_objects: &[Option], - text_style: &TextStyle, - wrap_width: Option, - window: &mut Window, - _cx: &mut App, -) -> InlineFlowLayout { - #[cfg(test)] - FLOW_LAYOUTS.with(|layouts| layouts.set(layouts.get() + 1)); - let rem_size = window.rem_size(); - let line_height = plain_line_height(text_style, rem_size, window); - let total_len = items.iter().map(MeasureItem::len).sum::(); - if total_len == 0 { - return InlineFlowLayout::default(); - } - - let objects = prepared_objects - .iter() - .map(|object| object.clone().map(|object| object.fit_text(wrap_width))) - .collect::>(); - let line_ranges = line_ranges(items, image_sizes, &objects, text_style, wrap_width, window); - let font_size = text_style.font_size.to_pixels(rem_size); - let mut fragments = Vec::new(); - let mut max_width = Pixels::ZERO; - let mut y = Pixels::ZERO; - - for line_range in line_ranges { - let mut line_fragments = Vec::new(); - let mut line_width = Pixels::ZERO; - // `LineLayout` is the metric source used by the text paint path. Its - // descent is normalized positive by native backends, whereas - // `FontMetrics::descent` remains signed. Start with the same shaped - // body metrics used below for every text fragment rather than mixing - // those two conventions through `TextSystem::baseline_offset`. - let body_runs = text_runs(1, text_style, &[]); - let body_line = shape_line(" ".into(), font_size, &body_runs, window); - let body_baseline = centered_baseline(&body_line, line_height); - // Like a plain text line, the body line box is the line height even - // when the font's glyphs are taller; runs may overflow it as far as - // body glyphs do. - let body_overflow_above = (body_line.ascent - body_baseline).max(Pixels::ZERO); - let body_overflow_below = - (body_line.descent - (line_height - body_baseline)).max(Pixels::ZERO); - let mut line_ascent = body_baseline; - let mut line_descent = line_height - body_baseline; - let mut item_start = 0; - - for (item_ix, item) in items.iter().enumerate() { - let item_end = item_start + item.len(); - if item_end <= line_range.start { - item_start = item_end; - continue; - } - if item_start >= line_range.end { - break; - } - - match item { - MeasureItem::Text { - text, - links, - highlights, - } => { - let local_start = line_range.start.max(item_start) - item_start; - let local_end = line_range.end.min(item_end) - item_start; - for (segment, scale) in text_size_ranges(text.len(), highlights) { - let start = local_start.max(segment.start); - let end = local_end.min(segment.end); - if start >= end { - continue; - } - let subtext = SharedString::from(text[start..end].to_string()); - let mut highlights = - slice_ranges(highlights, start, end, |range, style| { - (range, style.clone()) - }); - let links = - slice_ranges(links, start, end, |range, link| (range, link.clone())); - let runs = text_runs(subtext.len(), text_style, &highlights); - let segment_font_size = font_size * scale; - let shaped_line = - shape_line(subtext.clone(), segment_font_size, &runs, window); - let is_code = highlights.iter().any(|(_, h)| h.font_size_scale.is_some()); - let padding = if is_code { - px(INLINE_CODE_PADDING * 2.) - } else { - Pixels::ZERO - }; - let width = shaped_line.width() + padding; - // Measure the run by its glyph box. The body strut already - // carries the line's leading, so a run only has to fit its - // glyphs: leading of its own would make a smaller or - // differently proportioned run, such as inline code, push - // its line taller than a plain one. Positioning grows the - // box back to the line. The compact code background is - // painted independently. - let glyph_size = size(width, shaped_line.ascent + shaped_line.descent); - let baseline = shaped_line.ascent; - let code_background = is_code - .then(|| { - code_background( - &shaped_line, - &runs, - segment_font_size, - &mut highlights, - glyph_size, - baseline, - window, - ) - }) - .flatten(); - line_ascent = line_ascent.max(baseline - body_overflow_above); - line_descent = - line_descent.max(glyph_size.height - baseline - body_overflow_below); - line_width += width; - line_fragments.push(LineFragmentLayout { - item_ix, - kind: LineFragmentKind::Text { - font_size: segment_font_size, - text: subtext, - links, - highlights, - code_background, - }, - size: glyph_size, - source_range: start..end, - baseline: baseline, - }); - } - } - MeasureItem::Object { .. } => { - let object = objects[item_ix].as_ref().unwrap().clone(); - let metrics = object.metrics; - line_ascent = line_ascent.max(metrics.baseline); - line_descent = line_descent.max(metrics.size.height - metrics.baseline); - line_width += metrics.size.width; - line_fragments.push(LineFragmentLayout { - item_ix, - kind: LineFragmentKind::Object(Box::new(object)), - size: metrics.size, - source_range: 0..IMAGE_LEN, - baseline: metrics.baseline, - }); - } - MeasureItem::Image { .. } => { - if line_range.start <= item_start && item_end <= line_range.end { - let size = image_sizes[item_ix] - .expect("image size should be measured before layout"); - line_width += size.width; - let baseline = (size.height / 2. + body_baseline - line_height / 2.) - .max(Pixels::ZERO) - .min(size.height); - line_ascent = line_ascent.max(baseline); - line_descent = line_descent.max(size.height - baseline); - line_fragments.push(LineFragmentLayout { - item_ix, - kind: LineFragmentKind::Image, - size, - source_range: 0..IMAGE_LEN, - baseline: baseline, - }); - } - } - } - - item_start = item_end; - } - - let mut x = Pixels::ZERO; - for mut fragment in line_fragments { - // Give a text run's glyph box equal leading on both sides, as - // much as the line allows: its glyphs are painted centered in the - // box, so this keeps them on the line's baseline, and a body run - // gets exactly the line box. The leading is negative where the - // glyphs overflow the line, as a plain text line's do. - let leading = match fragment.kind { - LineFragmentKind::Text { .. } => (line_ascent - fragment.baseline) - .min(line_descent - (fragment.size.height - fragment.baseline)) - .max(-fragment.size.height / 2.), - _ => Pixels::ZERO, - }; - fragment.size.height += leading * 2.; - fragment.baseline += leading; - let origin = point(x, y + line_ascent - fragment.baseline); - let selection_bounds = Bounds::new( - point(x, y), - size(fragment.size.width, line_ascent + line_descent), - ); - let positioned = match fragment.kind { - LineFragmentKind::Object(object) => PositionedFragment::Object { - item_ix: fragment.item_ix, - origin, - object, - selection_bounds, - }, - LineFragmentKind::Text { - font_size, - text, - links, - highlights, - code_background, - } => PositionedFragment::Text { - item_ix: fragment.item_ix, - origin, - size: fragment.size, - source_range: fragment.source_range, - selection_bounds, - font_size, - text, - links, - highlights, - code_background: code_background.map(|(background, color)| { - ( - Bounds::new( - origin + point(Pixels::ZERO, leading) + background.origin, - background.size, - ), - color, - ) - }), - }, - LineFragmentKind::Image => PositionedFragment::Image { - item_ix: fragment.item_ix, - origin, - size: fragment.size, - }, - }; - x += fragment.size.width; - fragments.push(positioned); - } - - max_width = max_width.max(line_width); - y += line_ascent + line_descent; - } - - InlineFlowLayout { - fragments, - size: size(max_width, y), - wrap_width, - } -} - -/// The rounded box behind a code span, relative to the fragment: centered on -/// the capital-height body of the text, with the descender room shared -/// between both sides instead of added only below. Takes the background -/// color out of `highlights`, so the text does not paint it a second time -/// at the full line height. -fn code_background( - shaped_line: &ShapedLine, - runs: &[TextRun], - font_size: Pixels, - highlights: &mut [(Range, InlineHighlight)], - fragment_size: Size, - baseline: Pixels, - window: &Window, -) -> Option<(Bounds, Hsla)> { - let cap_height = runs - .iter() - .map(|run| { - let font = window.text_system().resolve_font(&run.font); - window.text_system().cap_height(font, font_size) - }) - .fold(Pixels::ZERO, Pixels::max); - let vertical_padding = font_size * 0.125 + shaped_line.descent / 2.; - let color = highlights - .iter() - .find_map(|(_, h)| h.style.background_color); - for (_, highlight) in highlights.iter_mut() { - highlight.style.background_color = None; - } - color.map(|color| { - ( - Bounds::new( - point(Pixels::ZERO, baseline - cap_height - vertical_padding), - size(fragment_size.width, cap_height + vertical_padding * 2.), - ), - color, - ) - }) -} - -fn line_ranges( - items: &[MeasureItem], - image_sizes: &[Option>], - objects: &[Option], - text_style: &TextStyle, - wrap_width: Option, - window: &mut Window, -) -> Vec> { - let total_len = items.iter().map(MeasureItem::len).sum::(); - let mut hard_lines = Vec::new(); - let mut line_start = 0; - let mut item_start = 0; - - for item in items { - if let MeasureItem::Text { text, .. } = item { - for (newline, _) in text.match_indices('\n') { - let newline = item_start + newline; - hard_lines.push(line_start..newline); - line_start = newline + 1; - } - } - item_start += item.len(); - } - hard_lines.push(line_start..total_len); - - let Some(wrap_width) = wrap_width else { - return hard_lines; - }; - let rem_size = window.rem_size(); - let font_size = text_style.font_size.to_pixels(rem_size); - let mut wrapper = window - .text_system() - .line_wrapper(text_style.font(), font_size); - let mut ranges = Vec::new(); - - for hard_line in hard_lines { - let mut item_start = 0; - let mut wrap_fragments = Vec::new(); - for (ix, item) in items.iter().enumerate() { - let item_end = item_start + item.len(); - if item_end > hard_line.start && item_start < hard_line.end { - match item { - MeasureItem::Text { - text, highlights, .. - } => { - let start = hard_line.start.max(item_start) - item_start; - let end = hard_line.end.min(item_end) - item_start; - if start < end { - push_text_wrap_fragments( - &mut wrap_fragments, - text, - highlights, - start..end, - text_style, - wrap_width, - window, - ); - } - } - MeasureItem::Object { .. } => { - wrap_fragments.push(WrapLineFragment::element( - objects[ix].as_ref().unwrap().metrics.size.width, - IMAGE_LEN, - )); - } - MeasureItem::Image { .. } => { - if hard_line.start <= item_start && item_end <= hard_line.end { - wrap_fragments.push(WrapLineFragment::element( - image_sizes[ix] - .expect("image size should be measured before wrapping") - .width, - IMAGE_LEN, - )); - } - } - } - } - item_start = item_end; - } - - let boundaries = wrapper - .wrap_line(&wrap_fragments, wrap_width) - .map(|boundary| hard_line.start + boundary.ix.min(hard_line.len())) - .collect::>(); - let mut start = hard_line.start; - - for end in boundaries { - if start < end { - ranges.push(start..end); - } - start = end; - } - - if start < hard_line.end || hard_line.is_empty() { - ranges.push(start..hard_line.end); - } - } - - ranges -} - -/// Appends the wrap fragments for `range` of `text`. The line wrapper -/// measures text fragments in the body font, so a span whose highlight sets -/// another family is shaped with the same run the renderer uses and enters -/// the wrapper as measured elements. Oversized spans retain word boundaries; -/// oversized words can break at grapheme boundaries without splitting Unicode. -fn push_text_wrap_fragments<'a>( - fragments: &mut Vec>, - text: &'a str, - highlights: &[(Range, InlineHighlight)], - range: Range, - text_style: &TextStyle, - wrap_width: Pixels, - window: &mut Window, -) { - let font_size = text_style.font_size.to_pixels(window.rem_size()); - let mut cursor = range.start; - for (highlight_range, highlight) in highlights { - if highlight.font_family.is_none() { - continue; - } - let start = highlight_range.start.max(cursor); - let end = highlight_range.end.min(range.end); - if start >= end { - continue; - } - if cursor < start { - fragments.push(WrapLineFragment::text(&text[cursor..start])); - } - let span = &text[start..end]; - let measure = |text: &str| { - let runs = text_runs( - text.len(), - text_style, - &[(0..text.len(), highlight.clone())], - ); - window - .text_system() - .layout_line( - text, - font_size * highlight.font_size_scale.unwrap_or(1.), - &runs, - None, - ) - .width - }; - let padding = if highlight.font_size_scale.is_some() { - px(INLINE_CODE_PADDING * 2.) - } else { - Pixels::ZERO - }; - let width = measure(span) + padding; - if width <= wrap_width { - fragments.push(WrapLineFragment::element(width, span.len())); - } else { - for word in span.split_word_bounds() { - let width = measure(word) + padding; - if width <= wrap_width { - fragments.push(WrapLineFragment::element(width, word.len())); - } else { - for grapheme in word.graphemes(true) { - fragments.push(WrapLineFragment::element( - measure(grapheme) + padding, - grapheme.len(), - )); + for fragment in &mut prepaint.order { + match fragment { + PrepaintedFragment::Text { index, background } => { + if let Some((bounds, color)) = background { + window.paint_quad(gpui::fill(*bounds, *color).corner_radii(radius)); } + let (inline, bounds, prepared) = &mut prepaint.text[*index]; + inline.paint(None, None, *bounds, &mut px(0.), prepared, window, cx); } + PrepaintedFragment::Element(element) => element.paint(window, cx), } } - cursor = end; - } - if cursor < range.end { - fragments.push(WrapLineFragment::text(&text[cursor..range.end])); } } -#[allow(clippy::too_many_arguments)] -fn measure_image_size( - ix: usize, - source: &ImageSource, - width: Option, - height: Option, - line_height: Pixels, - rem_size: Pixels, - window: &mut Window, - cx: &mut App, -) -> Size { - let intrinsic_size = if width.is_some() && height.is_some() { - None - } else { - intrinsic_image_size(ix, source, width, height, window, cx) - }; - image_size(width, height, intrinsic_size, line_height, rem_size) -} - -fn intrinsic_image_size( - ix: usize, - source: &ImageSource, - width: Option, - height: Option, - window: &mut Window, - cx: &mut App, -) -> Option> { - let mut element = img(source.clone()) - .id(ix) - .object_fit(ObjectFit::Contain) - .max_w(relative(1.)) - .when_some(width, |this, width| this.w(width)) - .when_some(height, |this, height| this.h(height)) - .into_any_element(); - let measured_size = element.layout_as_root(AvailableSpace::min_size(), window, cx); - - if measured_size.width <= Pixels::ZERO || measured_size.height <= Pixels::ZERO { - None - } else { - Some(measured_size) - } -} - -fn image_size( - width: Option, - height: Option, - intrinsic_size: Option>, - line_height: Pixels, - rem_size: Pixels, -) -> Size { - let base_size = AbsoluteLength::Pixels(line_height); - match (width, height) { - (Some(width), Some(height)) => size( - width.to_pixels(base_size, rem_size), - height.to_pixels(base_size, rem_size), - ), - (Some(width), None) => { - let width = width.to_pixels(base_size, rem_size); - let height = intrinsic_size - .and_then(|intrinsic_size| { - (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) - .then(|| width * (intrinsic_size.height / intrinsic_size.width)) - }) - .unwrap_or(line_height); - size(width, height) - } - (None, Some(height)) => { - let height = height.to_pixels(base_size, rem_size); - let width = intrinsic_size - .and_then(|intrinsic_size| { - (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) - .then(|| height * (intrinsic_size.width / intrinsic_size.height)) - }) - .unwrap_or(height); - size(width, height) - } - (None, None) => inline_image_size_for_line(intrinsic_size, line_height), - } -} - -fn inline_image_size_for_line( - intrinsic_size: Option>, - line_height: Pixels, -) -> Size { - let height = line_height * 0.75; - let aspect_ratio = intrinsic_size - .and_then(|intrinsic_size| { - (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) - .then(|| intrinsic_size.width / intrinsic_size.height) - }) - .unwrap_or(1.); - - size((height * aspect_ratio).max(px(1.)), height.max(px(1.))) -} - -fn shape_line( - text: SharedString, - font_size: Pixels, - runs: &[TextRun], - window: &mut Window, -) -> ShapedLine { - window.text_system().shape_line(text, font_size, runs, None) -} - -/// The line height GPUI's text layout gives a plain line in `text_style`. -/// Unlike `Window::line_height`, it is not first rounded to a whole logical -/// pixel, which would make a flow line taller than a plain one. -fn plain_line_height(text_style: &TextStyle, rem_size: Pixels, window: &Window) -> Pixels { - window.pixel_snap( - text_style - .line_height - .to_pixels(text_style.font_size, rem_size), - ) -} - -/// Returns where GPUI text painting puts the baseline of `shaped_line` in a -/// box `line_height` tall: centered, even when the glyphs overflow the box. -/// `ShapedLine::descent` is positive; do not substitute the signed -/// `FontMetrics::descent` exposed by `TextSystem::baseline_offset` here. -fn centered_baseline(shaped_line: &ShapedLine, line_height: Pixels) -> Pixels { - (line_height - shaped_line.ascent - shaped_line.descent) / 2. + shaped_line.ascent -} - pub(super) fn slice_ranges( ranges: &[(Range, T)], start: usize, @@ -1461,498 +657,4 @@ pub(super) fn slice_ranges( } #[cfg(test)] -mod tests { - use super::*; - use gpui::SharedUri; - - mod frames { - use super::super::FLOW_LAYOUTS; - use crate::text::{TextView, TextViewState}; - use gpui::{ - AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, - Styled as _, TestAppContext, VisualTestContext, Window, div, px, - }; - - struct Answer { - state: Entity, - width: Pixels, - } - - impl Render for Answer { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div().w(self.width).child(TextView::new(&self.state)) - } - } - - fn draw(cx: &mut VisualTestContext) { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - fn layouts() -> usize { - FLOW_LAYOUTS.with(|layouts| layouts.get()) - } - - /// Scrolling redraws every visible paragraph each frame; a flow whose - /// text, style and width are unchanged has nothing to wrap or shape. - #[gpui::test] - fn an_unchanged_flow_is_not_laid_out_again(cx: &mut TestAppContext) { - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, cx| Answer { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - width: px(300.), - }); - cx.run_until_parked(); - draw(cx); - let after_first_frame = layouts(); - assert!(after_first_frame >= 1, "the first frame lays the flow out"); - - for _ in 0..3 { - draw(cx); - } - - assert_eq!(layouts(), after_first_frame, "a frame that changes nothing"); - } - - #[gpui::test] - fn a_flow_is_laid_out_again_at_another_width(cx: &mut TestAppContext) { - cx.update(crate::init); - let (answer, cx) = cx.add_window_view(|_, cx| Answer { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - width: px(300.), - }); - cx.run_until_parked(); - draw(cx); - let before = layouts(); - - answer.update(cx, |answer, _| answer.width = px(120.)); - draw(cx); - - assert!(layouts() > before, "a narrower flow wraps differently"); - } - - #[gpui::test] - fn a_flow_is_laid_out_again_when_its_text_changes(cx: &mut TestAppContext) { - cx.update(crate::init); - let (answer, cx) = cx.add_window_view(|_, cx| Answer { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - width: px(300.), - }); - cx.run_until_parked(); - draw(cx); - let before = layouts(); - - answer.update(cx, |answer, cx| { - answer.state.update(cx, |state, cx| { - state.set_text("Call `foo` and `bar` now.", cx); - }) - }); - cx.run_until_parked(); - draw(cx); - - assert!(layouts() > before, "a new text has a new layout"); - } - } - - #[test] - fn atomic_objects_wrap_and_share_a_baseline_at_multiple_font_sizes() { - use super::super::inline::test_draw::in_prepaint; - use super::super::inline::test_fonts::{BODY, WideMonoTextSystem}; - use gpui::TestApp; - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, |window, cx| { - for scale in [1., 1.5, 2.] { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16. * scale).into(), - ..Default::default() - }; - let items = vec![ - MeasureItem::Text { - text: "中文 ".into(), - links: vec![], - highlights: vec![], - }, - MeasureItem::Object { - text: "x²".into(), - id: 0, - renderer: Arc::new(|_, _, _| None), - style: Default::default(), - }, - MeasureItem::Object { - text: "y²".into(), - id: 1, - renderer: Arc::new(|_, _, _| None), - style: Default::default(), - }, - MeasureItem::Text { - text: " English".into(), - links: vec![], - highlights: vec![], - }, - ]; - for width in [1., 30., 80., 500.] { - let layout = layout_flow( - &items, - &[None, None, None, None], - &style, - Some(px(width)), - window, - cx, - ); - let objects: Vec<_> = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Object { origin, object, .. } => { - Some((origin, object)) - } - _ => None, - }) - .collect(); - assert_eq!(objects.len(), 2); - for (origin, object) in &objects { - assert!(object.metrics.size.width <= px(width)); - assert!(origin.y >= px(0.)); - assert!(origin.y + object.metrics.size.height <= layout.size.height); - } - if width == 500. { - assert_eq!( - objects[0].0.y + objects[0].1.metrics.baseline, - objects[1].0.y + objects[1].1.metrics.baseline - ); - } - } - } - }); - } - - #[test] - fn inline_image_without_explicit_size_scales_intrinsic_ratio_to_line_height() { - let line_height = px(20.); - let intrinsic_size = size(px(160.), px(40.)); - - let measured = inline_image_size_for_line(Some(intrinsic_size), line_height); - - assert_eq!(measured, size(px(60.), px(15.))); - } - - #[test] - fn inline_image_without_intrinsic_size_uses_compact_square_fallback() { - let measured = inline_image_size_for_line(None, px(20.)); - - assert_eq!(measured, size(px(15.), px(15.))); - } - - /// Line breaking must see the width of an inline code span in its own - /// family. With a body-font-only wrapper the span below is measured at - /// half its shaped width, the line is kept whole, and the flow reports a - /// width past `wrap_width`. - #[test] - fn inline_code_near_the_wrap_width_does_not_overflow_the_flow() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{AbsoluteLength, Empty, HighlightStyle, TestApp}; - - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - - let font_size = px(10.); - let text_style = TextStyle { - font_family: SharedString::from(BODY), - font_size: AbsoluteLength::Pixels(font_size), - ..Default::default() - }; - let lead = SharedString::from("See "); - let tail_text = " with code_span_here end"; - let code = tail_text.find("code_span_here").unwrap(); - let code_range = code..code + "code_span_here".len(); - let code_highlight = InlineHighlight { - style: HighlightStyle::default(), - font_family: Some(SharedString::from(MONO)), - font_size_scale: None, - }; - let items = vec![ - MeasureItem::Text { - text: lead.clone(), - links: vec![], - highlights: vec![], - }, - MeasureItem::Image { - source: SharedUri::from("https://example.com/badge.png").into(), - width: None, - height: None, - }, - MeasureItem::Text { - text: SharedString::from(tail_text), - links: vec![], - highlights: vec![(code_range.clone(), code_highlight)], - }, - ]; - let image_size = size(px(10.), px(10.)); - let image_sizes = vec![None, Some(image_size), None]; - // Body text, the image and the mono span fill the wrap width exactly; - // the trailing "end" only fits if the span is under-measured. - let wrap_width = WideMonoTextSystem::width_of("See with ", BODY, font_size) - + image_size.width - + WideMonoTextSystem::width_of("code_span_here", MONO, font_size); - - let layout = window.update(|_, window, cx| { - layout_flow( - &items, - &image_sizes, - &text_style, - Some(wrap_width), - window, - cx, - ) - }); - - assert!( - layout.size.width <= wrap_width, - "flow width {:?} exceeds wrap width {:?}", - layout.size.width, - wrap_width - ); - let mono_fragment_width = layout - .fragments - .iter() - .find_map(|fragment| match fragment { - PositionedFragment::Text { text, size, .. } if text.contains("code_span_here") => { - Some(size.width) - } - _ => None, - }) - .expect("the code span is laid out as a text fragment"); - assert!( - mono_fragment_width >= WideMonoTextSystem::width_of("code_span_here", MONO, font_size), - "the code span fragment is shaped in the mono family" - ); - // The image sits vertically centred in its line, so line membership is - // read off the text fragments only. - let text_lines = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Text { text, origin, .. } => Some((text.trim(), origin.y)), - PositionedFragment::Image { .. } | PositionedFragment::Object { .. } => None, - }) - .collect::>(); - let first_y = text_lines[0].1; - assert!( - text_lines - .iter() - .any(|(text, y)| text.contains("code_span_here") && *y == first_y), - "the span stays on the first line: {text_lines:?}" - ); - assert!( - text_lines - .iter() - .any(|(text, y)| *text == "end" && *y > first_y), - "the trailing word wraps to a second line: {text_lines:?}" - ); - } - #[test] - fn long_inline_code_wraps_in_mixed_flow() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{Empty, TestApp}; - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - let style = TextStyle { - font_family: BODY.into(), - font_size: AbsoluteLength::Pixels(px(10.)), - ..Default::default() - }; - for text in [ - "one two three four five six", - "very_long_unbroken_identifier", - "你好世界你好世界你好世界", - "e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}", - ] { - let items = vec![ - MeasureItem::Image { - source: SharedUri::from("https://example.com/icon.png").into(), - width: None, - height: None, - }, - MeasureItem::Text { - text: text.into(), - links: vec![], - highlights: vec![( - 0..text.len(), - InlineHighlight { - font_family: Some(MONO.into()), - ..Default::default() - }, - )], - }, - ]; - let image_sizes = vec![Some(size(px(10.), px(10.))), None]; - let layout = window.update(|_, window, cx| { - layout_flow(&items, &image_sizes, &style, Some(px(100.)), window, cx) - }); - assert!(layout.size.width <= px(100.), "{text:?}: {:?}", layout.size); - let reconstructed: String = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Text { text, .. } => Some(text.as_ref()), - _ => None, - }) - .collect(); - assert_eq!(reconstructed, text); - } - } - - #[test] - fn inline_code_line_is_as_tall_as_a_plain_line_when_glyphs_overflow_it() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{Empty, TestApp}; - - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - let style = TextStyle { - font_family: BODY.into(), - font_size: AbsoluteLength::Pixels(px(40.)), - line_height: px(30.).into(), - ..Default::default() - }; - let items = vec![MeasureItem::Text { - text: "a code z".into(), - links: vec![], - highlights: vec![( - 2..6, - InlineHighlight { - font_family: Some(MONO.into()), - font_size_scale: Some(0.875), - ..Default::default() - }, - )], - }]; - // The 40px glyphs are taller than the 30px line. A plain text line - // keeps the line height and lets them overflow, so a line with - // inline code must not grow to fit them. - window.update(|_, window, cx| { - let layout = layout_flow(&items, &[None], &style, None, window, cx); - assert_eq!(layout.size.height, window.pixel_snap(px(30.))); - }); - } - - #[test] - fn inline_code_size_is_relative_and_uses_the_native_body_baseline() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{Empty, TestApp}; - - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - // These are the 16px body size and the example-markdown preview's - // 1.25x/1.5x inherited text-size zooms. - for body_size in [16., 20., 24.] { - let style = TextStyle { - font_family: BODY.into(), - font_size: AbsoluteLength::Pixels(px(body_size)), - ..Default::default() - }; - let items = vec![MeasureItem::Text { - text: "a code z".into(), - links: vec![], - highlights: vec![( - 2..6, - InlineHighlight { - font_family: Some(MONO.into()), - font_size_scale: Some(0.875), - ..Default::default() - }, - )], - }]; - window.update(|_, window, cx| { - let layout = layout_flow(&items, &[None], &style, None, window, cx); - let text_fragments = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Text { - text, - font_size, - origin, - size, - .. - } => Some((text.as_ref(), *font_size, origin.y, *size)), - _ => None, - }) - .collect::>(); - assert_eq!(text_fragments.len(), 3); - assert_eq!(text_fragments[0].1, px(body_size)); - assert_eq!(text_fragments[1].0, "code"); - assert_eq!(text_fragments[1].1, px(body_size * 0.875)); - // The code run's box stays inside the line, so whatever it - // paints over its box cannot reach a neighboring line. - assert!(text_fragments[1].2 >= Pixels::ZERO); - assert!(text_fragments[1].2 + text_fragments[1].3.height <= layout.size.height); - assert_eq!( - text_fragments[1].3.width, - WideMonoTextSystem::width_of("code", MONO, px(body_size * 0.875)) - + px(INLINE_CODE_PADDING * 2.) - ); - - // GPUI paints shaped lines with positive `LineLayout::descent`. - // Derive the ordinary body glyph baseline directly from that - // native-compatible shaped line, rather than `baseline_offset`, - // whose FontMetrics descent is intentionally signed. - let body_runs = text_runs(1, &style, &[]); - let body_line = shape_line("a".into(), px(body_size), &body_runs, window); - let body_line_height = plain_line_height(&style, window.rem_size(), window); - let plain_body_baseline = (body_line_height - body_line.ascent - body_line.descent) - / 2. - + body_line.ascent; - // The smaller code run fits inside the body line, so the - // line must be exactly as tall as a plain one. - assert_eq!( - layout.size.height, body_line_height, - "{body_size}px line height" - ); - let mut painted_glyph_baseline = - |fragment: &(&str, Pixels, Pixels, Size)| { - let runs = if fragment.0 == "code" { - text_runs( - fragment.0.len(), - &style, - &[( - 0..fragment.0.len(), - InlineHighlight { - font_family: Some(MONO.into()), - font_size_scale: Some(0.875), - ..Default::default() - }, - )], - ) - } else { - text_runs(fragment.0.len(), &style, &[]) - }; - let shaped = shape_line(fragment.0.into(), fragment.1, &runs, window); - fragment.2 - + (fragment.3.height - shaped.ascent - shaped.descent) / 2. - + shaped.ascent - }; - - // `origin` is passed unchanged to Inline::paint_origin, so this - // checks the first body glyph's painted row position, not only - // the enclosing paragraph height. It must agree with a normal - // body line and with the adjacent inline-code glyph baseline. - assert_eq!( - text_fragments[0].2, - Pixels::ZERO, - "{body_size}px body origin" - ); - assert_eq!( - painted_glyph_baseline(&text_fragments[0]), - plain_body_baseline, - "{body_size}px body glyph baseline" - ); - assert_eq!( - painted_glyph_baseline(&text_fragments[1]), - plain_body_baseline, - "{body_size}px code glyph baseline" - ); - }); - } - } -} +mod tests; diff --git a/vendor/gpui-base/src/text/inline_flow/layout.rs b/vendor/gpui-base/src/text/inline_flow/layout.rs new file mode 100644 index 00000000..9803da79 --- /dev/null +++ b/vendor/gpui-base/src/text/inline_flow/layout.rs @@ -0,0 +1,685 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use std::{ops::Range, sync::Arc}; + +use gpui::{ + AbsoluteLength, App, AvailableSpace, Bounds, DefiniteLength, Hsla, ImageSource, + InteractiveElement as _, IntoElement as _, ObjectFit, Pixels, Refineable as _, ShapedLine, + SharedString, Size, Styled as _, StyledImage as _, TextRun, TextStyle, Window, img, point, + prelude::FluentBuilder as _, px, relative, size, +}; + +use crate::text::{ + InlineRenderContext, + inline::{InlineHighlight, highlights_in_range, text_runs, text_size_ranges_in}, + inline_object::MeasuredInlineObject, + node::LinkMark, +}; + +use super::{INLINE_CODE_PADDING, InlineFlowItem, InlineRenderer, slice_ranges}; + +mod wrapping; +use wrapping::line_ranges; + +const IMAGE_LEN: usize = 1; + +#[derive(Default)] +pub(super) struct InlineFlowLayout { + pub(super) fragments: Vec, + pub(super) size: Size, + pub(super) wrap_width: Option, +} + +pub(super) enum PositionedFragment { + Object { + item_ix: usize, + origin: gpui::Point, + object: Box, + selection_bounds: Bounds, + }, + Text { + item_ix: usize, + origin: gpui::Point, + size: Size, + source_range: Range, + font_size: Pixels, + text: SharedString, + links: Vec<(Range, LinkMark)>, + highlights: Vec<(Range, InlineHighlight)>, + selection_bounds: Bounds, + /// The rounded box behind a code span, relative to the flow. + code_background: Option<(Bounds, Hsla)>, + }, + Image { + item_ix: usize, + origin: gpui::Point, + size: Size, + }, +} + +pub(super) enum MeasureItem { + Object { + text: SharedString, + id: usize, + renderer: Arc, + style: gpui::HighlightStyle, + }, + Text { + text: SharedString, + links: Vec<(Range, LinkMark)>, + highlights: Vec<(Range, InlineHighlight)>, + }, + Image { + source: ImageSource, + width: Option, + height: Option, + }, +} + +struct LineFragmentLayout { + item_ix: usize, + kind: LineFragmentKind, + size: Size, + source_range: Range, + baseline: Pixels, +} + +enum LineFragmentKind { + Object(Box), + Text { + font_size: Pixels, + text: SharedString, + links: Vec<(Range, LinkMark)>, + highlights: Vec<(Range, InlineHighlight)>, + /// The code span's box, relative to the fragment. + code_background: Option<(Bounds, Hsla)>, + }, + Image, +} + +impl From<&InlineFlowItem> for MeasureItem { + fn from(item: &InlineFlowItem) -> Self { + match item { + InlineFlowItem::Object { + text, + id, + renderer, + style, + .. + } => Self::Object { + text: text.clone(), + id: *id, + renderer: renderer.clone(), + style: *style, + }, + InlineFlowItem::Text { + state: _, + text, + links, + highlights, + .. + } => MeasureItem::Text { + text: text.clone(), + links: links.clone(), + highlights: highlights.clone(), + }, + InlineFlowItem::Image { + source, + width, + height, + .. + } => MeasureItem::Image { + source: source.clone(), + width: *width, + height: *height, + }, + } + } +} + +impl MeasureItem { + fn len(&self) -> usize { + match self { + MeasureItem::Text { text, .. } => text.len(), + MeasureItem::Image { .. } | MeasureItem::Object { .. } => IMAGE_LEN, + } + } + + /// Whether `other` lays out the same as this item. An object is + /// rendered anew every frame, so a flow with one is never reused. + pub(super) fn same_layout_input(&self, other: &Self) -> bool { + match (self, other) { + ( + MeasureItem::Text { + text, + links, + highlights, + }, + MeasureItem::Text { + text: other_text, + links: other_links, + highlights: other_highlights, + }, + ) => text == other_text && links == other_links && highlights == other_highlights, + ( + MeasureItem::Image { width, height, .. }, + MeasureItem::Image { + width: other_width, + height: other_height, + .. + }, + ) => width == other_width && height == other_height, + _ => false, + } + } +} + +/// Intrinsic width for table sizing, using the same objects and wrapping inputs as painting. +pub(in crate::text) fn intrinsic_width( + items: &[InlineFlowItem], + window: &mut Window, + cx: &mut App, +) -> Pixels { + let items = items.iter().map(MeasureItem::from).collect::>(); + let line_height = window.line_height(); + let rem_size = window.rem_size(); + let images = items + .iter() + .enumerate() + .map(|(ix, item)| match item { + MeasureItem::Image { + source, + width, + height, + } => Some(measure_image_size( + ix, + source, + *width, + *height, + line_height, + rem_size, + window, + cx, + )), + _ => None, + }) + .collect::>(); + layout_flow(&items, &images, &window.text_style(), None, window, cx) + .size + .width +} + +pub(super) fn prepare_objects( + items: &[MeasureItem], + text_style: &TextStyle, + window: &mut Window, + cx: &mut App, +) -> Vec> { + items + .iter() + .map(|item| match item { + MeasureItem::Object { + text, + id, + renderer, + style, + } => { + let style = text_style.clone().highlight(*style); + let context = InlineRenderContext::new( + style.clone(), + style.font_size.to_pixels(window.rem_size()), + style.line_height_in_pixels(window.rem_size()), + window.rem_size(), + ); + // Must be the id `InlineObject` paints under: GPUI asserts a + // stateful child (a plugin's HoverCard) sees the same id path + // in request_layout as in prepaint, and the element is laid + // out here but painted inside `InlineObject`. + Some(window.with_id(("inline-object", *id), |window| { + let element = window + .with_text_style(Some(style.subtract(&Default::default())), |window| { + renderer(&context, window, cx) + }); + MeasuredInlineObject::measure(text, element, &style, window, cx) + })) + } + _ => None, + }) + .collect() +} + +pub(super) fn layout_flow( + items: &[MeasureItem], + image_sizes: &[Option>], + text_style: &TextStyle, + wrap_width: Option, + window: &mut Window, + cx: &mut App, +) -> InlineFlowLayout { + let objects = prepare_objects(items, text_style, window, cx); + layout_measured_flow( + items, + image_sizes, + &objects, + text_style, + wrap_width, + window, + cx, + ) +} + +#[cfg(test)] +thread_local! { + /// How many flows were laid out (wrapped and shaped) on this thread. + pub(super) static FLOW_LAYOUTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(super) fn layout_measured_flow( + items: &[MeasureItem], + image_sizes: &[Option>], + prepared_objects: &[Option], + text_style: &TextStyle, + wrap_width: Option, + window: &mut Window, + _cx: &mut App, +) -> InlineFlowLayout { + #[cfg(test)] + FLOW_LAYOUTS.with(|layouts| layouts.set(layouts.get() + 1)); + let rem_size = window.rem_size(); + let line_height = plain_line_height(text_style, rem_size, window); + let total_len = items.iter().map(MeasureItem::len).sum::(); + if total_len == 0 { + return InlineFlowLayout::default(); + } + + let objects = prepared_objects + .iter() + .map(|object| object.clone().map(|object| object.fit_text(wrap_width))) + .collect::>(); + let line_ranges = line_ranges(items, image_sizes, &objects, text_style, wrap_width, window); + let font_size = text_style.font_size.to_pixels(rem_size); + let mut fragments = Vec::new(); + let mut max_width = Pixels::ZERO; + let mut y = Pixels::ZERO; + + for line_range in line_ranges { + let mut line_fragments = Vec::new(); + let mut line_width = Pixels::ZERO; + // `LineLayout` is the metric source used by the text paint path. Its + // descent is normalized positive by native backends, whereas + // `FontMetrics::descent` remains signed. Start with the same shaped + // body metrics used below for every text fragment rather than mixing + // those two conventions through `TextSystem::baseline_offset`. + let body_runs = text_runs(1, text_style, &[]); + let body_line = shape_line(" ".into(), font_size, &body_runs, window); + let body_baseline = centered_baseline(&body_line, line_height); + // Like a plain text line, the body line box is the line height even + // when the font's glyphs are taller; runs may overflow it as far as + // body glyphs do. + let body_overflow_above = (body_line.ascent - body_baseline).max(Pixels::ZERO); + let body_overflow_below = + (body_line.descent - (line_height - body_baseline)).max(Pixels::ZERO); + let mut line_ascent = body_baseline; + let mut line_descent = line_height - body_baseline; + let mut item_start = 0; + + for (item_ix, item) in items.iter().enumerate() { + let item_end = item_start + item.len(); + if item_end <= line_range.start { + item_start = item_end; + continue; + } + if item_start >= line_range.end { + break; + } + + match item { + MeasureItem::Text { + text, + links, + highlights, + } => { + let local_start = line_range.start.max(item_start) - item_start; + let local_end = line_range.end.min(item_end) - item_start; + for (segment, scale) in text_size_ranges_in(local_start..local_end, highlights) + { + let start = segment.start; + let end = segment.end; + let subtext = SharedString::from(text[start..end].to_string()); + let mut highlights = slice_ranges( + highlights_in_range(highlights, &(start..end)), + start, + end, + |range, style| (range, style.clone()), + ); + let links = + slice_ranges(links, start, end, |range, link| (range, link.clone())); + let runs = text_runs(subtext.len(), text_style, &highlights); + let segment_font_size = font_size * scale; + let shaped_line = + shape_line(subtext.clone(), segment_font_size, &runs, window); + let is_code = highlights.iter().any(|(_, h)| h.font_size_scale.is_some()); + let padding = if is_code { + px(INLINE_CODE_PADDING * 2.) + } else { + Pixels::ZERO + }; + let width = shaped_line.width() + padding; + // Measure the run by its glyph box. The body strut already + // carries the line's leading, so a run only has to fit its + // glyphs: leading of its own would make a smaller or + // differently proportioned run, such as inline code, push + // its line taller than a plain one. Positioning grows the + // box back to the line. The compact code background is + // painted independently. + let glyph_size = size(width, shaped_line.ascent + shaped_line.descent); + let baseline = shaped_line.ascent; + let code_background = is_code + .then(|| { + code_background( + &shaped_line, + &runs, + segment_font_size, + &mut highlights, + glyph_size, + baseline, + window, + ) + }) + .flatten(); + line_ascent = line_ascent.max(baseline - body_overflow_above); + line_descent = + line_descent.max(glyph_size.height - baseline - body_overflow_below); + line_width += width; + line_fragments.push(LineFragmentLayout { + item_ix, + kind: LineFragmentKind::Text { + font_size: segment_font_size, + text: subtext, + links, + highlights, + code_background, + }, + size: glyph_size, + source_range: start..end, + baseline: baseline, + }); + } + } + MeasureItem::Object { .. } => { + let object = objects[item_ix].as_ref().unwrap().clone(); + let metrics = object.metrics; + line_ascent = line_ascent.max(metrics.baseline); + line_descent = line_descent.max(metrics.size.height - metrics.baseline); + line_width += metrics.size.width; + line_fragments.push(LineFragmentLayout { + item_ix, + kind: LineFragmentKind::Object(Box::new(object)), + size: metrics.size, + source_range: 0..IMAGE_LEN, + baseline: metrics.baseline, + }); + } + MeasureItem::Image { .. } => { + if line_range.start <= item_start && item_end <= line_range.end { + let size = image_sizes[item_ix] + .expect("image size should be measured before layout"); + line_width += size.width; + let baseline = (size.height / 2. + body_baseline - line_height / 2.) + .max(Pixels::ZERO) + .min(size.height); + line_ascent = line_ascent.max(baseline); + line_descent = line_descent.max(size.height - baseline); + line_fragments.push(LineFragmentLayout { + item_ix, + kind: LineFragmentKind::Image, + size, + source_range: 0..IMAGE_LEN, + baseline: baseline, + }); + } + } + } + + item_start = item_end; + } + + let mut x = Pixels::ZERO; + for mut fragment in line_fragments { + // Give a text run's glyph box equal leading on both sides, as + // much as the line allows: its glyphs are painted centered in the + // box, so this keeps them on the line's baseline, and a body run + // gets exactly the line box. The leading is negative where the + // glyphs overflow the line, as a plain text line's do. + let leading = match fragment.kind { + LineFragmentKind::Text { .. } => (line_ascent - fragment.baseline) + .min(line_descent - (fragment.size.height - fragment.baseline)) + .max(-fragment.size.height / 2.), + _ => Pixels::ZERO, + }; + fragment.size.height += leading * 2.; + fragment.baseline += leading; + let origin = point(x, y + line_ascent - fragment.baseline); + let selection_bounds = Bounds::new( + point(x, y), + size(fragment.size.width, line_ascent + line_descent), + ); + let positioned = match fragment.kind { + LineFragmentKind::Object(object) => PositionedFragment::Object { + item_ix: fragment.item_ix, + origin, + object, + selection_bounds, + }, + LineFragmentKind::Text { + font_size, + text, + links, + highlights, + code_background, + } => PositionedFragment::Text { + item_ix: fragment.item_ix, + origin, + size: fragment.size, + source_range: fragment.source_range, + selection_bounds, + font_size, + text, + links, + highlights, + code_background: code_background.map(|(background, color)| { + ( + Bounds::new( + origin + point(Pixels::ZERO, leading) + background.origin, + background.size, + ), + color, + ) + }), + }, + LineFragmentKind::Image => PositionedFragment::Image { + item_ix: fragment.item_ix, + origin, + size: fragment.size, + }, + }; + x += fragment.size.width; + fragments.push(positioned); + } + + max_width = max_width.max(line_width); + y += line_ascent + line_descent; + } + + InlineFlowLayout { + fragments, + size: size(max_width, y), + wrap_width, + } +} + +/// The rounded box behind a code span, relative to the fragment: centered on +/// the capital-height body of the text, with the descender room shared +/// between both sides instead of added only below. Takes the background +/// color out of `highlights`, so the text does not paint it a second time +/// at the full line height. +fn code_background( + shaped_line: &ShapedLine, + runs: &[TextRun], + font_size: Pixels, + highlights: &mut [(Range, InlineHighlight)], + fragment_size: Size, + baseline: Pixels, + window: &Window, +) -> Option<(Bounds, Hsla)> { + let cap_height = runs + .iter() + .map(|run| { + let font = window.text_system().resolve_font(&run.font); + window.text_system().cap_height(font, font_size) + }) + .fold(Pixels::ZERO, Pixels::max); + let vertical_padding = font_size * 0.125 + shaped_line.descent / 2.; + let color = highlights + .iter() + .find_map(|(_, h)| h.style.background_color); + for (_, highlight) in highlights.iter_mut() { + highlight.style.background_color = None; + } + color.map(|color| { + ( + Bounds::new( + point(Pixels::ZERO, baseline - cap_height - vertical_padding), + size(fragment_size.width, cap_height + vertical_padding * 2.), + ), + color, + ) + }) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn measure_image_size( + ix: usize, + source: &ImageSource, + width: Option, + height: Option, + line_height: Pixels, + rem_size: Pixels, + window: &mut Window, + cx: &mut App, +) -> Size { + let intrinsic_size = if width.is_some() && height.is_some() { + None + } else { + intrinsic_image_size(ix, source, width, height, window, cx) + }; + image_size(width, height, intrinsic_size, line_height, rem_size) +} + +fn intrinsic_image_size( + ix: usize, + source: &ImageSource, + width: Option, + height: Option, + window: &mut Window, + cx: &mut App, +) -> Option> { + let mut element = img(source.clone()) + .id(ix) + .object_fit(ObjectFit::Contain) + .max_w(relative(1.)) + .when_some(width, |this, width| this.w(width)) + .when_some(height, |this, height| this.h(height)) + .into_any_element(); + let measured_size = element.layout_as_root(AvailableSpace::min_size(), window, cx); + + if measured_size.width <= Pixels::ZERO || measured_size.height <= Pixels::ZERO { + None + } else { + Some(measured_size) + } +} + +fn image_size( + width: Option, + height: Option, + intrinsic_size: Option>, + line_height: Pixels, + rem_size: Pixels, +) -> Size { + let base_size = AbsoluteLength::Pixels(line_height); + match (width, height) { + (Some(width), Some(height)) => size( + width.to_pixels(base_size, rem_size), + height.to_pixels(base_size, rem_size), + ), + (Some(width), None) => { + let width = width.to_pixels(base_size, rem_size); + let height = intrinsic_size + .and_then(|intrinsic_size| { + (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) + .then(|| width * (intrinsic_size.height / intrinsic_size.width)) + }) + .unwrap_or(line_height); + size(width, height) + } + (None, Some(height)) => { + let height = height.to_pixels(base_size, rem_size); + let width = intrinsic_size + .and_then(|intrinsic_size| { + (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) + .then(|| height * (intrinsic_size.width / intrinsic_size.height)) + }) + .unwrap_or(height); + size(width, height) + } + (None, None) => inline_image_size_for_line(intrinsic_size, line_height), + } +} + +pub(super) fn inline_image_size_for_line( + intrinsic_size: Option>, + line_height: Pixels, +) -> Size { + let height = line_height * 0.75; + let aspect_ratio = intrinsic_size + .and_then(|intrinsic_size| { + (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) + .then(|| intrinsic_size.width / intrinsic_size.height) + }) + .unwrap_or(1.); + + size((height * aspect_ratio).max(px(1.)), height.max(px(1.))) +} + +pub(super) fn shape_line( + text: SharedString, + font_size: Pixels, + runs: &[TextRun], + window: &mut Window, +) -> ShapedLine { + window.text_system().shape_line(text, font_size, runs, None) +} + +/// The line height GPUI's text layout gives a plain line in `text_style`. +/// Unlike `Window::line_height`, it is not first rounded to a whole logical +/// pixel, which would make a flow line taller than a plain one. +pub(super) fn plain_line_height( + text_style: &TextStyle, + rem_size: Pixels, + window: &Window, +) -> Pixels { + window.pixel_snap( + text_style + .line_height + .to_pixels(text_style.font_size, rem_size), + ) +} + +/// Returns where GPUI text painting puts the baseline of `shaped_line` in a +/// box `line_height` tall: centered, even when the glyphs overflow the box. +/// `ShapedLine::descent` is positive; do not substitute the signed +/// `FontMetrics::descent` exposed by `TextSystem::baseline_offset` here. +fn centered_baseline(shaped_line: &ShapedLine, line_height: Pixels) -> Pixels { + (line_height - shaped_line.ascent - shaped_line.descent) / 2. + shaped_line.ascent +} diff --git a/vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs b/vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs new file mode 100644 index 00000000..454d7af2 --- /dev/null +++ b/vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs @@ -0,0 +1,189 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use std::ops::Range; + +use gpui::{LineFragment, Pixels, Size, TextStyle, Window, px}; +use unicode_segmentation::UnicodeSegmentation as _; + +use crate::text::{ + inline::{InlineHighlight, highlights_in_range, text_runs}, + inline_object::MeasuredInlineObject, +}; + +use super::{IMAGE_LEN, INLINE_CODE_PADDING, MeasureItem}; + +pub(super) fn line_ranges( + items: &[MeasureItem], + image_sizes: &[Option>], + objects: &[Option], + text_style: &TextStyle, + wrap_width: Option, + window: &mut Window, +) -> Vec> { + let total_len = items.iter().map(MeasureItem::len).sum::(); + let mut hard_lines = Vec::new(); + let mut line_start = 0; + let mut item_start = 0; + + for item in items { + if let MeasureItem::Text { text, .. } = item { + for (newline, _) in text.match_indices('\n') { + let newline = item_start + newline; + hard_lines.push(line_start..newline); + line_start = newline + 1; + } + } + item_start += item.len(); + } + hard_lines.push(line_start..total_len); + + let Some(wrap_width) = wrap_width else { + return hard_lines; + }; + let rem_size = window.rem_size(); + let font_size = text_style.font_size.to_pixels(rem_size); + let mut wrapper = window + .text_system() + .line_wrapper(text_style.font(), font_size); + let mut ranges = Vec::new(); + + for hard_line in hard_lines { + let mut item_start = 0; + let mut wrap_fragments = Vec::new(); + for (ix, item) in items.iter().enumerate() { + let item_end = item_start + item.len(); + if item_end > hard_line.start && item_start < hard_line.end { + match item { + MeasureItem::Text { + text, highlights, .. + } => { + let start = hard_line.start.max(item_start) - item_start; + let end = hard_line.end.min(item_end) - item_start; + if start < end { + push_text_wrap_fragments( + &mut wrap_fragments, + text, + highlights, + start..end, + text_style, + wrap_width, + window, + ); + } + } + MeasureItem::Object { .. } => { + wrap_fragments.push(LineFragment::element( + objects[ix].as_ref().unwrap().metrics.size.width, + IMAGE_LEN, + )); + } + MeasureItem::Image { .. } => { + if hard_line.start <= item_start && item_end <= hard_line.end { + wrap_fragments.push(LineFragment::element( + image_sizes[ix] + .expect("image size should be measured before wrapping") + .width, + IMAGE_LEN, + )); + } + } + } + } + item_start = item_end; + } + + let boundaries = wrapper + .wrap_line(&wrap_fragments, wrap_width) + .map(|boundary| hard_line.start + boundary.ix.min(hard_line.len())) + .collect::>(); + let mut start = hard_line.start; + + for end in boundaries { + if start < end { + ranges.push(start..end); + } + start = end; + } + + if start < hard_line.end || hard_line.is_empty() { + ranges.push(start..hard_line.end); + } + } + + ranges +} + +/// Appends the wrap fragments for `range` of `text`. The line wrapper +/// measures text fragments in the body font, so a span whose highlight sets +/// another family is shaped with the same run the renderer uses and enters +/// the wrapper as measured elements. Oversized spans retain word boundaries; +/// oversized words can break at grapheme boundaries without splitting Unicode. +fn push_text_wrap_fragments<'a>( + fragments: &mut Vec>, + text: &'a str, + highlights: &[(Range, InlineHighlight)], + range: Range, + text_style: &TextStyle, + wrap_width: Pixels, + window: &mut Window, +) { + let font_size = text_style.font_size.to_pixels(window.rem_size()); + let mut cursor = range.start; + for (highlight_range, highlight) in highlights_in_range(highlights, &range) { + if highlight.font_family.is_none() { + continue; + } + let start = highlight_range.start.max(cursor); + let end = highlight_range.end.min(range.end); + if start >= end { + continue; + } + if cursor < start { + fragments.push(LineFragment::text(&text[cursor..start])); + } + let span = &text[start..end]; + let measure = |text: &str| { + let runs = text_runs( + text.len(), + text_style, + &[(0..text.len(), highlight.clone())], + ); + window + .text_system() + .layout_line( + text, + font_size * highlight.font_size_scale.unwrap_or(1.), + &runs, + None, + ) + .width + }; + let padding = if highlight.font_size_scale.is_some() { + px(INLINE_CODE_PADDING * 2.) + } else { + Pixels::ZERO + }; + let width = measure(span) + padding; + if width <= wrap_width { + fragments.push(LineFragment::element(width, span.len())); + } else { + for word in span.split_word_bounds() { + let width = measure(word) + padding; + if width <= wrap_width { + fragments.push(LineFragment::element(width, word.len())); + } else { + for grapheme in word.graphemes(true) { + fragments.push(LineFragment::element( + measure(grapheme) + padding, + grapheme.len(), + )); + } + } + } + } + cursor = end; + } + if cursor < range.end { + fragments.push(LineFragment::text(&text[cursor..range.end])); + } +} diff --git a/vendor/gpui-base/src/text/inline_flow/tests.rs b/vendor/gpui-base/src/text/inline_flow/tests.rs new file mode 100644 index 00000000..bbc0c1fa --- /dev/null +++ b/vendor/gpui-base/src/text/inline_flow/tests.rs @@ -0,0 +1,493 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use super::layout::{inline_image_size_for_line, layout_flow, plain_line_height, shape_line}; +use super::*; +use crate::text::inline::text_runs; +use gpui::{AbsoluteLength, SharedUri}; + +mod frames { + use super::super::layout::FLOW_LAYOUTS; + use crate::text::{TextView, TextViewState}; + use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, + Styled as _, TestAppContext, VisualTestContext, Window, div, px, + }; + + struct Answer { + state: Entity, + width: Pixels, + } + + impl Render for Answer { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().w(self.width).child(TextView::new(&self.state)) + } + } + + fn draw(cx: &mut VisualTestContext) { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + fn layouts() -> usize { + FLOW_LAYOUTS.with(|layouts| layouts.get()) + } + + /// Scrolling redraws every visible paragraph each frame; a flow whose + /// text, style and width are unchanged has nothing to wrap or shape. + #[gpui::test] + fn an_unchanged_flow_is_not_laid_out_again(cx: &mut TestAppContext) { + cx.update(crate::init); + let (_, cx) = cx.add_window_view(|_, cx| Answer { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + width: px(300.), + }); + cx.run_until_parked(); + draw(cx); + let after_first_frame = layouts(); + assert!(after_first_frame >= 1, "the first frame lays the flow out"); + + for _ in 0..3 { + draw(cx); + } + + assert_eq!(layouts(), after_first_frame, "a frame that changes nothing"); + } + + #[gpui::test] + fn a_flow_is_laid_out_again_at_another_width(cx: &mut TestAppContext) { + cx.update(crate::init); + let (answer, cx) = cx.add_window_view(|_, cx| Answer { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + width: px(300.), + }); + cx.run_until_parked(); + draw(cx); + let before = layouts(); + + answer.update(cx, |answer, _| answer.width = px(120.)); + draw(cx); + + assert!(layouts() > before, "a narrower flow wraps differently"); + } + + #[gpui::test] + fn a_flow_is_laid_out_again_when_its_text_changes(cx: &mut TestAppContext) { + cx.update(crate::init); + let (answer, cx) = cx.add_window_view(|_, cx| Answer { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + width: px(300.), + }); + cx.run_until_parked(); + draw(cx); + let before = layouts(); + + answer.update(cx, |answer, cx| { + answer.state.update(cx, |state, cx| { + state.set_text("Call `foo` and `bar` now.", cx); + }) + }); + cx.run_until_parked(); + draw(cx); + + assert!(layouts() > before, "a new text has a new layout"); + } +} + +#[test] +fn atomic_objects_wrap_and_share_a_baseline_at_multiple_font_sizes() { + use super::super::inline::test_draw::in_prepaint; + use super::super::inline::test_fonts::{BODY, WideMonoTextSystem}; + use gpui::TestApp; + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, |window, cx| { + for scale in [1., 1.5, 2.] { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16. * scale).into(), + ..Default::default() + }; + let items = vec![ + MeasureItem::Text { + text: "中文 ".into(), + links: vec![], + highlights: vec![], + }, + MeasureItem::Object { + text: "x²".into(), + id: 0, + renderer: Arc::new(|_, _, _| None), + style: Default::default(), + }, + MeasureItem::Object { + text: "y²".into(), + id: 1, + renderer: Arc::new(|_, _, _| None), + style: Default::default(), + }, + MeasureItem::Text { + text: " English".into(), + links: vec![], + highlights: vec![], + }, + ]; + for width in [1., 30., 80., 500.] { + let layout = layout_flow( + &items, + &[None, None, None, None], + &style, + Some(px(width)), + window, + cx, + ); + let objects: Vec<_> = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Object { origin, object, .. } => Some((origin, object)), + _ => None, + }) + .collect(); + assert_eq!(objects.len(), 2); + for (origin, object) in &objects { + assert!(object.metrics.size.width <= px(width)); + assert!(origin.y >= px(0.)); + assert!(origin.y + object.metrics.size.height <= layout.size.height); + } + if width == 500. { + assert_eq!( + objects[0].0.y + objects[0].1.metrics.baseline, + objects[1].0.y + objects[1].1.metrics.baseline + ); + } + } + } + }); +} + +#[test] +fn inline_image_without_explicit_size_scales_intrinsic_ratio_to_line_height() { + let line_height = px(20.); + let intrinsic_size = size(px(160.), px(40.)); + + let measured = inline_image_size_for_line(Some(intrinsic_size), line_height); + + assert_eq!(measured, size(px(60.), px(15.))); +} + +#[test] +fn inline_image_without_intrinsic_size_uses_compact_square_fallback() { + let measured = inline_image_size_for_line(None, px(20.)); + + assert_eq!(measured, size(px(15.), px(15.))); +} + +/// Line breaking must see the width of an inline code span in its own +/// family. With a body-font-only wrapper the span below is measured at +/// half its shaped width, the line is kept whole, and the flow reports a +/// width past `wrap_width`. +#[test] +fn inline_code_near_the_wrap_width_does_not_overflow_the_flow() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, HighlightStyle, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + + let font_size = px(10.); + let text_style = TextStyle { + font_family: SharedString::from(BODY), + font_size: AbsoluteLength::Pixels(font_size), + ..Default::default() + }; + let lead = SharedString::from("See "); + let tail_text = " with code_span_here end"; + let code = tail_text.find("code_span_here").unwrap(); + let code_range = code..code + "code_span_here".len(); + let code_highlight = InlineHighlight { + style: HighlightStyle::default(), + font_family: Some(SharedString::from(MONO)), + font_size_scale: None, + }; + let items = vec![ + MeasureItem::Text { + text: lead.clone(), + links: vec![], + highlights: vec![], + }, + MeasureItem::Image { + source: SharedUri::from("https://example.com/badge.png").into(), + width: None, + height: None, + }, + MeasureItem::Text { + text: SharedString::from(tail_text), + links: vec![], + highlights: vec![(code_range.clone(), code_highlight)], + }, + ]; + let image_size = size(px(10.), px(10.)); + let image_sizes = vec![None, Some(image_size), None]; + // Body text, the image and the mono span fill the wrap width exactly; + // the trailing "end" only fits if the span is under-measured. + let wrap_width = WideMonoTextSystem::width_of("See with ", BODY, font_size) + + image_size.width + + WideMonoTextSystem::width_of("code_span_here", MONO, font_size); + + let layout = window.update(|_, window, cx| { + layout_flow( + &items, + &image_sizes, + &text_style, + Some(wrap_width), + window, + cx, + ) + }); + + assert!( + layout.size.width <= wrap_width, + "flow width {:?} exceeds wrap width {:?}", + layout.size.width, + wrap_width + ); + let mono_fragment_width = layout + .fragments + .iter() + .find_map(|fragment| match fragment { + PositionedFragment::Text { text, size, .. } if text.contains("code_span_here") => { + Some(size.width) + } + _ => None, + }) + .expect("the code span is laid out as a text fragment"); + assert!( + mono_fragment_width >= WideMonoTextSystem::width_of("code_span_here", MONO, font_size), + "the code span fragment is shaped in the mono family" + ); + // The image sits vertically centred in its line, so line membership is + // read off the text fragments only. + let text_lines = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Text { text, origin, .. } => Some((text.trim(), origin.y)), + PositionedFragment::Image { .. } | PositionedFragment::Object { .. } => None, + }) + .collect::>(); + let first_y = text_lines[0].1; + assert!( + text_lines + .iter() + .any(|(text, y)| text.contains("code_span_here") && *y == first_y), + "the span stays on the first line: {text_lines:?}" + ); + assert!( + text_lines + .iter() + .any(|(text, y)| *text == "end" && *y > first_y), + "the trailing word wraps to a second line: {text_lines:?}" + ); +} +#[test] +fn long_inline_code_wraps_in_mixed_flow() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, TestApp}; + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(10.)), + ..Default::default() + }; + for text in [ + "one two three four five six", + "very_long_unbroken_identifier", + "你好世界你好世界你好世界", + "e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}", + ] { + let items = vec![ + MeasureItem::Image { + source: SharedUri::from("https://example.com/icon.png").into(), + width: None, + height: None, + }, + MeasureItem::Text { + text: text.into(), + links: vec![], + highlights: vec![( + 0..text.len(), + InlineHighlight { + font_family: Some(MONO.into()), + ..Default::default() + }, + )], + }, + ]; + let image_sizes = vec![Some(size(px(10.), px(10.))), None]; + let layout = window.update(|_, window, cx| { + layout_flow(&items, &image_sizes, &style, Some(px(100.)), window, cx) + }); + assert!(layout.size.width <= px(100.), "{text:?}: {:?}", layout.size); + let reconstructed: String = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Text { text, .. } => Some(text.as_ref()), + _ => None, + }) + .collect(); + assert_eq!(reconstructed, text); + } +} + +#[test] +fn inline_code_line_is_as_tall_as_a_plain_line_when_glyphs_overflow_it() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(40.)), + line_height: px(30.).into(), + ..Default::default() + }; + let items = vec![MeasureItem::Text { + text: "a code z".into(), + links: vec![], + highlights: vec![( + 2..6, + InlineHighlight { + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + ..Default::default() + }, + )], + }]; + // The 40px glyphs are taller than the 30px line. A plain text line + // keeps the line height and lets them overflow, so a line with + // inline code must not grow to fit them. + window.update(|_, window, cx| { + let layout = layout_flow(&items, &[None], &style, None, window, cx); + assert_eq!(layout.size.height, window.pixel_snap(px(30.))); + }); +} + +#[test] +fn inline_code_size_is_relative_and_uses_the_native_body_baseline() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + // These are the 16px body size and the example-markdown preview's + // 1.25x/1.5x inherited text-size zooms. + for body_size in [16., 20., 24.] { + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(body_size)), + ..Default::default() + }; + let items = vec![MeasureItem::Text { + text: "a code z".into(), + links: vec![], + highlights: vec![( + 2..6, + InlineHighlight { + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + ..Default::default() + }, + )], + }]; + window.update(|_, window, cx| { + let layout = layout_flow(&items, &[None], &style, None, window, cx); + let text_fragments = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Text { + text, + font_size, + origin, + size, + .. + } => Some((text.as_ref(), *font_size, origin.y, *size)), + _ => None, + }) + .collect::>(); + assert_eq!(text_fragments.len(), 3); + assert_eq!(text_fragments[0].1, px(body_size)); + assert_eq!(text_fragments[1].0, "code"); + assert_eq!(text_fragments[1].1, px(body_size * 0.875)); + // The code run's box stays inside the line, so whatever it + // paints over its box cannot reach a neighboring line. + assert!(text_fragments[1].2 >= Pixels::ZERO); + assert!(text_fragments[1].2 + text_fragments[1].3.height <= layout.size.height); + assert_eq!( + text_fragments[1].3.width, + WideMonoTextSystem::width_of("code", MONO, px(body_size * 0.875)) + + px(INLINE_CODE_PADDING * 2.) + ); + + // GPUI paints shaped lines with positive `LineLayout::descent`. + // Derive the ordinary body glyph baseline directly from that + // native-compatible shaped line, rather than `baseline_offset`, + // whose FontMetrics descent is intentionally signed. + let body_runs = text_runs(1, &style, &[]); + let body_line = shape_line("a".into(), px(body_size), &body_runs, window); + let body_line_height = plain_line_height(&style, window.rem_size(), window); + let plain_body_baseline = + (body_line_height - body_line.ascent - body_line.descent) / 2. + body_line.ascent; + // The smaller code run fits inside the body line, so the + // line must be exactly as tall as a plain one. + assert_eq!( + layout.size.height, body_line_height, + "{body_size}px line height" + ); + let mut painted_glyph_baseline = |fragment: &(&str, Pixels, Pixels, Size)| { + let runs = if fragment.0 == "code" { + text_runs( + fragment.0.len(), + &style, + &[( + 0..fragment.0.len(), + InlineHighlight { + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + ..Default::default() + }, + )], + ) + } else { + text_runs(fragment.0.len(), &style, &[]) + }; + let shaped = shape_line(fragment.0.into(), fragment.1, &runs, window); + fragment.2 + + (fragment.3.height - shaped.ascent - shaped.descent) / 2. + + shaped.ascent + }; + + // `origin` is passed unchanged to the positioned Inline, so this + // checks the first body glyph's painted row position, not only + // the enclosing paragraph height. It must agree with a normal + // body line and with the adjacent inline-code glyph baseline. + assert_eq!( + text_fragments[0].2, + Pixels::ZERO, + "{body_size}px body origin" + ); + assert_eq!( + painted_glyph_baseline(&text_fragments[0]), + plain_body_baseline, + "{body_size}px body glyph baseline" + ); + assert_eq!( + painted_glyph_baseline(&text_fragments[1]), + plain_body_baseline, + "{body_size}px code glyph baseline" + ); + }); + } +} diff --git a/vendor/gpui-base/src/text/node.rs b/vendor/gpui-base/src/text/node.rs index 9fb6b37e..6be967de 100644 --- a/vendor/gpui-base/src/text/node.rs +++ b/vendor/gpui-base/src/text/node.rs @@ -12,6 +12,7 @@ use gpui::{ img, prelude::FluentBuilder as _, px, relative, rems, }; use markdown::mdast; +use smallvec::SmallVec; use crate::{ StyledExt, h_flex, @@ -21,8 +22,8 @@ use crate::{ MarkdownNode, TableActionsFn, document::NodeRenderOptions, inline::{ - Inline, InlineHighlight, InlineState, combine_highlights, fade_highlights, text_runs, - text_size_ranges, + Inline, InlineHighlight, InlineState, append_node_highlights, fade_highlights, + text_runs, text_size_ranges, }, inline_flow::{InlineFlow, InlineFlowItem, slice_ranges}, range_highlight::{RangeHighlightFrame, RevealAt, RevealRequest}, @@ -1198,7 +1199,7 @@ impl Paragraph { for inline_node in &self.children { let text_len = inline_node.text.len(); text.push_str(&inline_node.text); - let mut node_highlights = vec![]; + let mut node_highlights = SmallVec::new(); for (range, style) in &inline_node.marks { let inner_range = (offset + range.start)..(offset + range.end); let mut highlight = mark_highlight(style, node_cx, cx); @@ -1212,7 +1213,7 @@ impl Paragraph { } node_highlights.push((inner_range, highlight)); } - highlights = combine_highlights(highlights, node_highlights); + append_node_highlights(&mut highlights, node_highlights); offset += text_len; } let text = SharedString::from(text); @@ -2105,8 +2106,8 @@ impl Paragraph { mark_highlight(mark, node_cx, cx), ) }) - .collect::>(); - highlights = combine_highlights(highlights, node_highlights); + .collect(); + append_node_highlights(&mut highlights, node_highlights); offset += inline_node.text.len(); } highlights @@ -2118,6 +2119,7 @@ impl Paragraph { fn render( &self, fade_key: Option, + gap: Rems, node_cx: &NodeContext, _window: &mut Window, cx: &mut App, @@ -2127,12 +2129,15 @@ impl Paragraph { let backgrounds = node_cx.range_backgrounds(fade_key); if self.should_render_inline_flow() { - return InlineFlow::new( - leaf_element_id(fade_key), - self.inline_flow_items(fade_key, fades, backgrounds, node_cx, cx), - node_cx.link_click_handler.clone(), - ) - .into_any_element(); + return gapped( + InlineFlow::new( + leaf_element_id(fade_key), + self.inline_flow_items(fade_key, fades, backgrounds, node_cx, cx), + node_cx.link_click_handler.clone(), + ) + .into_any_element(), + gap, + ); } let has_image = children.iter().any(|child| child.image.is_some()); @@ -2141,7 +2146,7 @@ impl Paragraph { if !has_image { let (text, highlights, mut links) = self.plain_render(node_cx, cx); if text.is_empty() { - return div().into_any_element(); + return div().pb(gap).into_any_element(); } for (_, link_mark) in &mut links { if let Some(identifier) = link_mark.identifier.as_ref() @@ -2162,6 +2167,7 @@ impl Paragraph { highlights, node_cx.link_click_handler.clone(), ) + .bottom_padding(gap) .range_backgrounds(backgrounds) .reveal(reveal) .into_any_element(); @@ -2249,7 +2255,7 @@ impl Paragraph { highlights.clear(); offset = 0; } else { - let mut node_highlights = vec![]; + let mut node_highlights = SmallVec::new(); for (range, style) in &inline_node.marks { let inner_range = (offset + range.start)..(offset + range.end); let mut highlight = mark_highlight(style, node_cx, cx); @@ -2274,7 +2280,7 @@ impl Paragraph { node_highlights.push((inner_range, highlight)); } - highlights = combine_highlights(highlights, node_highlights); + append_node_highlights(&mut highlights, node_highlights); offset += text_len; } } @@ -2299,19 +2305,15 @@ impl Paragraph { ); } - // Text alone is one `Inline`, which needs no box of its own. Images - // keep an identified box: an image's element state is its animation, + // Images keep an identified box: its element state is the animation, // and the box scopes that state per paragraph. - if !has_image { - return child_nodes - .pop() - .unwrap_or_else(|| div().into_any_element()); - } - - div() - .id(leaf_element_id(fade_key)) - .children(child_nodes) - .into_any_element() + gapped( + div() + .id(leaf_element_id(fade_key)) + .children(child_nodes) + .into_any_element(), + gap, + ) } fn should_render_inline_flow(&self) -> bool { @@ -2437,7 +2439,7 @@ impl Paragraph { highlights.clear(); offset = 0; } else { - let mut node_highlights = vec![]; + let mut node_highlights = SmallVec::new(); for (range, style) in &inline_node.marks { let inner_range = (offset + range.start)..(offset + range.end); let mut highlight = mark_highlight(style, node_cx, cx); @@ -2461,7 +2463,7 @@ impl Paragraph { node_highlights.push((inner_range, highlight)); } - highlights = combine_highlights(highlights, node_highlights); + append_node_highlights(&mut highlights, node_highlights); offset += text_len; } } @@ -3129,7 +3131,10 @@ impl BlockNode { this.border_r_1().border_color(style.border()) }) .refine_style(&style.table_cell()) - .child(cell.children.render(fade_key, node_cx, window, cx)), + .child( + cell.children + .render(fade_key, Rems::ZERO, node_cx, window, cx), + ), ); } rows.push( @@ -3239,7 +3244,10 @@ impl BlockNode { this.border_r_1().border_color(style.border()) }) .refine_style(&style.table_cell()) - .child(cell.children.render(fade_key, node_cx, window, cx)), + .child( + cell.children + .render(fade_key, Rems::ZERO, node_cx, window, cx), + ), ); } @@ -3309,15 +3317,16 @@ impl BlockNode { node.render_block(NodeRenderOptions { ix, ..options }, node_cx, window, cx) })) .into_any_element(), - BlockNode::Paragraph(paragraph) => gapped( - paragraph.render( - paragraph.span.map(|span| TextLeafKey::block(span.start)), - node_cx, - window, - cx, - ), - mb, - ), + BlockNode::Paragraph(paragraph) => { + // Preserve the wrapper's behavior for non-CSS padding values. + let (gap, wrapper) = if mb.0.is_finite() && mb.0 >= 0.0 { + (mb, Rems::ZERO) + } else { + (Rems::ZERO, mb) + }; + let key = paragraph.span.map(|span| TextLeafKey::block(span.start)); + gapped(paragraph.render(key, gap, node_cx, window, cx), wrapper) + } BlockNode::Heading { level, children, @@ -3343,6 +3352,7 @@ impl BlockNode { .refine_style(&node_cx.style.heading(*level)) .child(children.render( span.map(|span| TextLeafKey::block(span.start)), + Rems::ZERO, node_cx, window, cx, diff --git a/vendor/gpui-base/src/text_selection.rs b/vendor/gpui-base/src/text_selection.rs index a7719ddd..af77aabe 100644 --- a/vendor/gpui-base/src/text_selection.rs +++ b/vendor/gpui-base/src/text_selection.rs @@ -1,8 +1,10 @@ +// Nocterm: avoid duplicate drag projections and updates to unchanged participants. use std::{ collections::HashMap, ops::Range, rc::Rc, sync::atomic::{AtomicU64, Ordering}, + time::Duration, }; use gpui::{ @@ -17,7 +19,7 @@ use crate::text_boundary::{line_range_at, word_range_at}; use crate::touch_selection::{ EdgeDrag, SelectionEdge, TouchHandle, TouchSelectionSnapshot, caret_in_view, }; -use crate::{AutoScroll, GlobalState}; +use crate::{AutoScroll, FrameLoop, GlobalState}; /// An opaque selection layer identifier. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] @@ -1094,6 +1096,29 @@ impl TouchSelection { } } +#[derive(Default)] +struct AncestorScroll { + frames: FrameLoop, + target: Option<(Pixels, Point)>, + geometry: Option<(Bounds, Point)>, + stalled: Duration, +} + +impl AncestorScroll { + fn stop(&mut self) { + *self = Self::default(); + } + + fn update(&mut self, delta: Option, position: Point) { + if let Some(delta) = delta { + self.target = Some((delta, position)); + self.stalled = Duration::ZERO; + } else { + self.stop(); + } + } +} + /// Window-local generic text-selection state. #[derive(Default)] struct WindowSelectionState { @@ -1108,12 +1133,7 @@ struct WindowSelectionState { finish_frame_scheduled: bool, refresh_held_cursor: bool, mouse_down_prepared: bool, - auto_scroll: AutoScroll, - /// Where the anchor's text was when the last synthetic wheel went out, - /// and how many went out without moving it. A container at its end - /// cannot scroll further; pushing it on would only make one that - /// bounces stretch and snap back on every tick. - auto_scroll_stall: (Option<(Bounds, Point)>, u8), + auto_scroll: AncestorScroll, touch: TouchSelection, /// This entity, so that touch changes can notify observers from paths that /// only hold an [`App`]. @@ -1287,7 +1307,6 @@ impl WindowSelectionState { registration: TextSelectionRegistration, cx: &mut App, ) { - self.prune_dead_participants(); if self.is_selecting && registration.self_scroll && self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) @@ -1904,15 +1923,19 @@ impl WindowSelectionState { if !self.is_selecting { return; } - let endpoint = self.endpoint(position, window, cx); - self.did_hit_text |= endpoint.inside_text; - self.cursor = Some(endpoint); + self.move_cursor(position, window, cx); if window.is_none() { self.update_participant_auto_scroll(position, cx); } self.publish_snapshots(cx); } + fn move_cursor(&mut self, position: Point, window: Option<&Window>, cx: &App) { + let endpoint = self.endpoint(position, window, cx); + self.did_hit_text |= endpoint.inside_text; + self.cursor = Some(endpoint); + } + fn endpoint( &mut self, position: Point, @@ -2027,78 +2050,48 @@ impl WindowSelectionState { fn publish_snapshots(&mut self, cx: &mut App) { self.prune_dead_participants(); - let snapshot = self.snapshot(); - let single_participant = self.single_participant(); + let projection = self.snapshot().and_then(|snapshot| { + let ordered = + |id: EntityId| Some((id, self.participants.get(&id)?.registration.document_order)); + Some(( + snapshot, + ordered(snapshot.anchor.entity_id()?)?, + ordered(snapshot.cursor.entity_id()?)?, + )) + }); for (id, registration) in &self.participants { let Some(participant) = registration.participant.upgrade() else { continue; }; - let participant_snapshot = (registration.registration.scope == self.active_scope - && self.participates(*id, registration) - && single_participant.is_none_or(|single| single == *id)) - .then_some(snapshot) - .flatten() - .map(|mut snapshot| { - snapshot.coverage = self.coverage_for(*id); - snapshot + let next = projection.and_then(|(mut snapshot, (anchor, start), (cursor, end))| { + if registration.registration.scope != self.active_scope { + return None; + } + snapshot.coverage = if anchor == cursor && *id == anchor { + TextSelectionCoverage::Bounded + } else if anchor == cursor { + return None; + } else if *id == anchor || *id == cursor { + if (*id == anchor) == (start < end) { + TextSelectionCoverage::ToEnd + } else { + TextSelectionCoverage::FromStart + } + } else if (start.min(end)..=start.max(end)) + .contains(®istration.registration.document_order) + { + TextSelectionCoverage::Full + } else { + return None; + }; + Some(snapshot) }); - participant.update(cx, |state, cx| state.set_snapshot(participant_snapshot, cx)); - } - } - - fn coverage_for(&self, id: EntityId) -> TextSelectionCoverage { - let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return TextSelectionCoverage::Bounded; - }; - let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return TextSelectionCoverage::Bounded; - }; - if anchor == cursor { - return TextSelectionCoverage::Bounded; - } - let anchor_order = self.participants[&anchor].registration.document_order; - let cursor_order = self.participants[&cursor].registration.document_order; - if id != anchor && id != cursor { - TextSelectionCoverage::Full - } else if (id == anchor) == (anchor_order < cursor_order) { - TextSelectionCoverage::ToEnd - } else { - TextSelectionCoverage::FromStart + if participant.read(cx).snapshot != next { + participant.update(cx, |state, cx| state.set_snapshot(next, cx)); + } } } - fn single_participant(&self) -> Option { - let anchor = self.anchor.as_ref()?.entity_id()?; - let cursor = self.cursor.as_ref()?.entity_id()?; - (anchor == cursor).then_some(anchor) - } - - fn participates(&self, id: EntityId, registration: &ParticipantRegistration) -> bool { - let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return false; - }; - let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return false; - }; - let Some(anchor_registration) = self.participants.get(&anchor) else { - return false; - }; - let Some(cursor_registration) = self.participants.get(&cursor) else { - return false; - }; - let start = anchor_registration - .registration - .document_order - .min(cursor_registration.registration.document_order); - let end = anchor_registration - .registration - .document_order - .max(cursor_registration.registration.document_order); - (start..=end).contains(®istration.registration.document_order) - || id == anchor - || id == cursor - } - fn update_auto_scroll( &mut self, position: Point, @@ -2145,45 +2138,56 @@ impl WindowSelectionState { visible_bounds.bottom() - HIT_TEST_INSET, ), ); - self.auto_scroll.last_drag_position = Some(event_position); - self.auto_scroll_stall = (None, 0); - let window = window.window_handle(); - self.auto_scroll.set(delta, cx, move |delta, state, cx| { - let Some(position) = state.auto_scroll.last_drag_position else { - return; - }; - // Hold off once the container has shown, over a few ticks, that - // it has nowhere left to go; the next move of the finger asks - // again. - const STALLED_TICKS: u8 = 3; - let geometry = state - .anchor_registration() - .map(|(_, registration)| (registration.bounds, registration.scroll_offset)); - let (last, stalled) = &mut state.auto_scroll_stall; - if *last == geometry { - *stalled = stalled.saturating_add(1); - if *stalled >= STALLED_TICKS { - return; - } - } else { - *last = geometry; - *stalled = 0; + self.auto_scroll.update(delta, event_position); + if delta.is_some() { + self.auto_scroll + .frames + .start(window, cx, Self::scroll_ancestor); + } + } + + fn scroll_ancestor( + &mut self, + elapsed: Duration, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let Some((delta, position)) = self.auto_scroll.target else { + return false; + }; + let geometry = self + .anchor_registration() + .map(|(_, registration)| (registration.bounds, registration.scroll_offset)); + if geometry.is_none() || !self.is_selecting { + return false; + } + // Once the ancestor stops moving, stop waking the frame clock. The next + // pointer move can restart it after a resize or after reversing direction. + if self.auto_scroll.geometry == geometry { + self.auto_scroll.stalled += elapsed; + if self.auto_scroll.stalled >= Duration::from_millis(50) { + return false; } - let window = window; - cx.defer(move |cx| { - _ = window.update(cx, |_, window, cx| { - window.dispatch_event( - ScrollWheelEvent { - position, - delta: ScrollDelta::Pixels(point(px(0.), -delta)), - ..Default::default() - } - .to_platform_input(), - cx, - ); - }); + } else { + self.auto_scroll.geometry = geometry; + self.auto_scroll.stalled = Duration::ZERO; + } + let frames = elapsed.as_secs_f32().min(0.032) / 0.016; + let window = window.window_handle(); + cx.defer(move |cx| { + _ = window.update(cx, |_, window, cx| { + window.dispatch_event( + ScrollWheelEvent { + position, + delta: ScrollDelta::Pixels(point(px(0.), -(delta * frames))), + ..Default::default() + } + .to_platform_input(), + cx, + ); }); }); + true } /// Drives the anchor participant's own scrolling, measured against the @@ -2815,19 +2819,22 @@ fn paint_text_selection(state: &Entity, window: &mut Windo let mouse_move_state = state.downgrade(); window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { - if phase.bubble() - && let Some(state) = mouse_move_state.upgrade() - { - state.update(cx, |state, cx| { - // A handle drag maps the pointer through the handle's offset; - // the raw pointer must not fight it. - if state.touch.drag.is_some() { - return; - } - state.update_in_window(event.position, window, cx) - }); - WindowSelectionState::resolve_content_keys(&state, cx); + if !phase.bubble() || cx.has_active_drag() { + return; + } + let Some(state) = mouse_move_state.upgrade() else { + return; + }; + let selection = state.read(cx); + // Touch handles already apply their own pointer offset. + if !selection.is_selecting || selection.touch.drag.is_some() { + return; } + state.update(cx, |state, cx| { + state.move_cursor(event.position, Some(window), cx); + state.update_auto_scroll(event.position, window, cx); + }); + WindowSelectionState::resolve_content_keys(&state, cx); }); let mouse_up_state = state.downgrade(); @@ -4055,8 +4062,8 @@ mod tests { cx, ); state.update_in_window(point(px(1.), px(50.)), window, cx); - assert!(!state.auto_scroll.is_active()); - assert!(state.auto_scroll.last_drag_position.is_none()); + assert!(!state.auto_scroll.frames.is_active()); + assert!(state.auto_scroll.target.is_none()); }); }) .unwrap(); @@ -4079,7 +4086,7 @@ mod tests { assert!(state.anchor.is_some()); state.update_in_window(point(px(1.), px(50.)), window, cx); - assert!(!state.auto_scroll.is_active()); + assert!(!state.auto_scroll.frames.is_active()); }); }) .unwrap(); diff --git a/vendor/gpui-base/src/time_field.rs b/vendor/gpui-base/src/time_field.rs index f4572d96..284a244d 100644 --- a/vendor/gpui-base/src/time_field.rs +++ b/vendor/gpui-base/src/time_field.rs @@ -1,13 +1,14 @@ +// Modified by Nocterm: use Jiff civil time. use crate::TestSupportExt as _; use std::rc::Rc; -use chrono::{NaiveTime, Timelike as _}; use gpui::{ AnyElement, App, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, Render, RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _, }; +use jiff::civil::Time; use crate::{ Decrement, Increment, StyledExt as _, @@ -41,7 +42,7 @@ pub enum TimePrecision { } impl TimePrecision { - /// The `chrono` format that displays a time at this precision and cycle. + /// The strftime format that displays a time at this precision and cycle. pub fn format(self, hour_cycle: HourCycle) -> &'static str { match (self, hour_cycle) { (Self::Minute, HourCycle::H23) => "%H:%M", @@ -52,12 +53,12 @@ impl TimePrecision { } /// Drop the components finer than this precision. - pub fn truncate(self, time: NaiveTime) -> NaiveTime { + pub fn truncate(self, time: Time) -> Time { let second = match self { Self::Minute => 0, Self::Second => time.second(), }; - NaiveTime::from_hms_opt(time.hour(), time.minute(), second).unwrap_or(time) + Time::new(time.hour(), time.minute(), second, 0).unwrap_or(time) } } @@ -98,14 +99,14 @@ impl TimeSegment { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TimeFieldEvent { /// Keyboard editing changed the time. - Change(NaiveTime), + Change(Time), } /// The pure editing rules of a [`TimeFieldState`], kept apart from focus so /// they can be tested without a window. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct SegmentEditor { - time: NaiveTime, + time: Time, precision: TimePrecision, hour_cycle: HourCycle, segment: TimeSegment, @@ -116,7 +117,7 @@ struct SegmentEditor { impl SegmentEditor { fn new() -> Self { Self { - time: NaiveTime::MIN, + time: Time::MIN, precision: TimePrecision::default(), hour_cycle: HourCycle::default(), segment: TimeSegment::Hour, @@ -148,12 +149,12 @@ impl SegmentEditor { /// The displayed value of a segment: the hour follows the cycle, and the /// period is `0` for AM and `1` for PM. fn value(&self, segment: TimeSegment) -> u32 { - let hour = self.time.hour(); + let hour = self.time.hour() as u32; match (segment, self.hour_cycle) { (TimeSegment::Hour, HourCycle::H23) => hour, (TimeSegment::Hour, HourCycle::H12) => (hour + 11) % 12 + 1, - (TimeSegment::Minute, _) => self.time.minute(), - (TimeSegment::Second, _) => self.time.second(), + (TimeSegment::Minute, _) => self.time.minute() as u32, + (TimeSegment::Second, _) => self.time.second() as u32, (TimeSegment::Period, _) => hour / 12, } } @@ -166,16 +167,19 @@ impl SegmentEditor { } } - fn with_value(&self, segment: TimeSegment, value: u32) -> NaiveTime { + fn with_value(&self, segment: TimeSegment, value: u32) -> Time { let time = self.time; let pm_offset = time.hour() / 12 * 12; + let Ok(value) = i8::try_from(value) else { + return time; + }; match (segment, self.hour_cycle) { - (TimeSegment::Hour, HourCycle::H23) => time.with_hour(value), + (TimeSegment::Hour, HourCycle::H23) => time.with().hour(value).build(), // 12 AM is midnight and 12 PM is noon. - (TimeSegment::Hour, HourCycle::H12) => time.with_hour(value % 12 + pm_offset), - (TimeSegment::Minute, _) => time.with_minute(value), - (TimeSegment::Second, _) => time.with_second(value), - (TimeSegment::Period, _) => time.with_hour(time.hour() % 12 + value * 12), + (TimeSegment::Hour, HourCycle::H12) => time.with().hour(value % 12 + pm_offset).build(), + (TimeSegment::Minute, _) => time.with().minute(value).build(), + (TimeSegment::Second, _) => time.with().second(value).build(), + (TimeSegment::Period, _) => time.with().hour(time.hour() % 12 + value * 12).build(), } .unwrap_or(time) } @@ -198,7 +202,7 @@ impl SegmentEditor { self.pending_digit = None; } - fn set_time(&mut self, time: NaiveTime) -> bool { + fn set_time(&mut self, time: Time) -> bool { let time = self.precision.truncate(time); if self.time == time { // Keep a half-typed segment when the owner echoes the same value back. @@ -348,12 +352,12 @@ impl TimeFieldState { } } - pub fn time(&self) -> NaiveTime { + pub fn time(&self) -> Time { self.editor.time } /// Replace the time without emitting [`TimeFieldEvent::Change`]. - pub fn set_time(&mut self, time: NaiveTime, _: &mut Window, cx: &mut Context) { + pub fn set_time(&mut self, time: Time, _: &mut Window, cx: &mut Context) { if self.editor.set_time(time) { cx.notify(); } @@ -585,7 +589,7 @@ impl RenderOnce for TimeField { .id(self.id.clone()) .test_support() .role(Role::TimeInput) - .aria_value(SharedString::from(editor.time.format(format).to_string())) + .aria_value(SharedString::from(editor.time.strftime(format).to_string())) .track_focus(&focus_handle.clone().tab_stop(!disabled)) .when(!disabled, |this| { this.key_context(CONTEXT) @@ -635,8 +639,8 @@ impl RenderOnce for TimeField { mod tests { use super::*; - fn hms(h: u32, m: u32, s: u32) -> NaiveTime { - NaiveTime::from_hms_opt(h, m, s).unwrap() + fn hms(h: u32, m: u32, s: u32) -> Time { + Time::new(h as i8, m as i8, s as i8, 0).unwrap() } fn editor(precision: TimePrecision, hour_cycle: HourCycle) -> SegmentEditor { diff --git a/vendor/gpui-base/tests/element_ext.rs b/vendor/gpui-base/tests/element_ext.rs index 7cfb21ad..6404aacd 100644 --- a/vendor/gpui-base/tests/element_ext.rs +++ b/vendor/gpui-base/tests/element_ext.rs @@ -1,8 +1,15 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. use std::{cell::RefCell, rc::Rc}; use gpui::{Context, IntoElement, Render, Styled as _, TestAppContext, Window, div, px}; use gpui_base::ElementExt as _; +mod flow_layout; +mod inline_layout_sweeps; +mod inline_pointer; +mod paragraph_layout; +mod selection_highlight; + struct PrepaintHarness { captured: Rc>>>, } diff --git a/vendor/gpui-base/tests/flow_layout.rs b/vendor/gpui-base/tests/flow_layout.rs new file mode 100644 index 00000000..8ad87684 --- /dev/null +++ b/vendor/gpui-base/tests/flow_layout.rs @@ -0,0 +1,91 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, Styled as _, + TestAppContext, Window, div, px, +}; +use gpui_base::{TextView, TextViewState}; +use std::time::Instant; + +struct FlowDocument { + width: Pixels, + text: Entity, +} + +impl Render for FlowDocument { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(self.width) + .h(px(420.)) + .overflow_hidden() + .child(TextView::new(&self.text)) + } +} + +#[gpui::test] +fn reflow_keeps_hard_breaks_and_text_across_code_spans(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + let source = "Prefix **bold** and `code with words` \nsecond *line* and `你好世界你好世界` \nfinal line"; + let (root, cx) = cx.add_window_view(|_, cx| FlowDocument { + width: px(360.), + text: cx.new(|cx| TextViewState::markdown(source, cx)), + }); + cx.run_until_parked(); + + let mut heights = Vec::new(); + for width in [360., 150., 360.] { + cx.update(|window, cx| { + root.update(cx, |root, cx| { + root.width = px(width); + cx.notify(); + }); + window.draw(cx).clear(cx); + }); + root.read_with(cx, |root, cx| { + let text = root.text.read(cx); + let rendered = text.rendered_text(); + assert_eq!( + rendered.as_str().trim(), + "Prefix bold and code with words\nsecond line and 你好世界你好世界\nfinal line" + ); + heights.push(text.bounds().size.height); + }); + } + assert!(heights[1] > heights[0]); + assert_eq!(heights[0], heights[2]); +} + +#[gpui::test] +#[ignore = "manual profile for one Markdown paragraph with explicit line breaks"] +fn measure_reflow_of_styled_hard_breaks(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + for lines in [32, 256, 1024, 4096] { + let source: String = (0..lines) + .map(|line| format!("Row {line} with **bold** and `styled code` \n")) + .collect(); + let (root, cx) = cx.add_window_view(|_, cx| FlowDocument { + width: px(360.), + text: cx.new(|cx| TextViewState::markdown(&source, cx)), + }); + cx.run_until_parked(); + let text = root.read_with(cx, |root, cx| root.text.read(cx).rendered_text()); + assert!(text.as_str().contains(&format!("Row {}", lines - 1))); + assert!(text.as_str().lines().count() >= lines); + let mut elapsed = Vec::new(); + let mut heights = Vec::new(); + for width in [340., 440., 320., 460., 300., 400., 280., 420., 260.] { + let time = cx.update(|window, cx| { + root.update(cx, |root, cx| { + root.width = px(width); + cx.notify(); + }); + let start = Instant::now(); + window.draw(cx).clear(cx); + start.elapsed().as_micros() + }); + elapsed.push(time); + heights.push(root.read_with(cx, |root, cx| root.text.read(cx).bounds().size.height)); + } + println!("{lines} hard lines: draw_us {elapsed:?}; height {heights:?}"); + } +} diff --git a/vendor/gpui-base/tests/inline_layout_sweeps.rs b/vendor/gpui-base/tests/inline_layout_sweeps.rs new file mode 100644 index 00000000..8d8b9d4c --- /dev/null +++ b/vendor/gpui-base/tests/inline_layout_sweeps.rs @@ -0,0 +1,297 @@ +// SPDX-License-Identifier: Apache-2.0 + +use gpui::{ + AppContext, AvailableSpace, Bounds, Context, Element, Entity, IntoElement, Modifiers, + ParentElement, Render, Styled, StyledText, TestAppContext, TextOverflow, TextStyleRefinement, + WhiteSpace, Window, canvas, div, hsla, point, px, rems, size, +}; +use gpui_base::text::{RangeHighlight, TextView, TextViewState, TextViewStyle}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; +use std::time::Instant; + +struct Document { + state: Entity, +} + +impl Render for Document { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(px(520.)) + .h(px(640.)) + .overflow_hidden() + .child(TextView::new(&self.state).selectable(true)) + } +} + +fn source(paragraphs: usize) -> String { + (0..paragraphs) + .map(|row| format!("Row **{row}** with *styled inline content* and `code`.\n\n")) + .collect() +} + +#[gpui::test] +fn clipped_document_keeps_its_highlight_and_selection_after_replacement(cx: &mut TestAppContext) { + const PARAGRAPHS: usize = 1_500; + let dense = source(PARAGRAPHS); + cx.update(gpui_base::init); + let (view, cx) = cx.add_window_view(|_, cx| Document { + state: cx.new(|cx| TextViewState::markdown(&dense, cx)), + }); + cx.run_until_parked(); + let state = view.read_with(cx, |view, _| view.state.clone()); + let color = hsla(0.23, 1., 0.5, 1.); + for (index, rows) in [PARAGRAPHS, 2, PARAGRAPHS].into_iter().enumerate() { + if index > 0 { + state.update(cx, |state, cx| state.set_text(&source(rows), cx)); + cx.run_until_parked(); + } + state.update(cx, |state, cx| { + let rendered = state.rendered_text(); + let expected = format!("Row {} with styled inline content and code.", rows - 1); + assert!(rendered.as_str().contains(&expected)); + state + .set_range_highlights([RangeHighlight::new(0..3, color)], cx) + .unwrap(); + }); + for _ in 0..2 { + cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + assert!( + window + .painted_quads() + .iter() + .any(|quad| quad.background == color.into()), + "visible first-word highlight must survive the handoff" + ); + }); + } + state.update(cx, |state, cx| { + state.select_all(cx); + assert_eq!(state.selected_text(), state.rendered_text().as_str()); + }); + } +} + +struct ParagraphSpacing { + state: Entity, + gap: gpui::Rems, + clicks: Arc, +} + +impl Render for ParagraphSpacing { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let clicks = self.clicks.clone(); + div().w(px(250.)).child( + TextView::new(&self.state) + .style(TextViewStyle::default().with_paragraph_gap(self.gap)) + .on_link_click(move |url, _, _, _| { + assert_eq!(url.as_str(), "https://example.org/target"); + clicks.fetch_add(1, Ordering::Relaxed); + }), + ) + } +} + +#[gpui::test] +fn paragraph_spacing_moves_following_text_without_extending_link_hitboxes(cx: &mut TestAppContext) { + let source = "[first](https://example.org/target)\n\nsecond `code`\n\nthird"; + let colors = [ + hsla(0.08, 1., 0.5, 1.), + hsla(0.17, 1., 0.5, 1.), + hsla(0.27, 1., 0.5, 1.), + ]; + let clicks = Arc::new(AtomicUsize::new(0)); + cx.update(gpui_base::init); + let (view, cx) = cx.add_window_view(|_, cx| ParagraphSpacing { + state: cx.new(|cx| TextViewState::markdown(source, cx)), + gap: rems(0.), + clicks: clicks.clone(), + }); + cx.run_until_parked(); + let state = view.read_with(cx, |view, _| view.state.clone()); + state.update(cx, |state, cx| { + let text = state.rendered_text(); + state + .set_range_highlights( + ["first", "second", "third"] + .into_iter() + .zip(colors) + .map(|(word, color)| { + let start = text.as_str().find(word).unwrap(); + RangeHighlight::new(start..start + word.len(), color) + }), + cx, + ) + .unwrap(); + }); + + let visible_rows = |window: &mut Window, cx: &mut gpui::App| { + window.refresh(); + window.draw(cx).clear(cx); + colors.map(|color| { + window + .painted_quads() + .iter() + .find(|quad| quad.background == color.into()) + .unwrap() + .bounds + .map(|coord| px(coord.0 / window.scale_factor())) + }) + }; + for scale in [1., 1.25, 1.5, 2.] { + cx.simulate_scale_factor_change(scale); + view.update(cx, |view, cx| { + view.gap = rems(0.); + cx.notify(); + }); + let before = cx.update(visible_rows); + view.update(cx, |view, cx| { + view.gap = rems(1.375); + cx.notify(); + }); + let (after, gap) = cx.update(|window, cx| { + ( + visible_rows(window, cx), + window.pixel_snap(view.read(cx).gap.to_pixels(window.rem_size())), + ) + }); + let tolerance = px(0.001); + assert_eq!(before[0], after[0]); + for (index, (before, after)) in before.into_iter().zip(after).enumerate().skip(1) { + assert_eq!(before.size, after.size); + assert_eq!(before.left(), after.left()); + assert!( + (after.top() - before.top() - gap * index as f32).abs() < tolerance, + "row {index} at scale {scale}" + ); + } + let count = clicks.load(Ordering::Relaxed); + cx.simulate_click( + point( + after[0].center().x, + (after[0].bottom() + after[1].top()) / 2., + ), + Modifiers::none(), + ); + assert_eq!(clicks.load(Ordering::Relaxed), count); + cx.simulate_click(after[0].center(), Modifiers::none()); + assert_eq!(clicks.load(Ordering::Relaxed), count + 1); + } +} + +#[gpui::test] +fn positioned_text_matches_standard_text_layout_at_fractional_scale(cx: &mut TestAppContext) { + let cx = cx.add_empty_window(); + let origin = point(px(14.25), px(9.6)); + let offered = size(px(96.37), px(43.8)); + for scale in [1., 1.25, 1.5, 2.] { + cx.simulate_scale_factor_change(scale); + cx.draw(origin, offered.map(AvailableSpace::Definite), |_, _| { + canvas( + move |bounds, window, cx| { + for truncate in [false, true] { + let style = TextStyleRefinement { + white_space: Some(if truncate { + WhiteSpace::Nowrap + } else { + WhiteSpace::Normal + }), + text_overflow: truncate.then(|| TextOverflow::Truncate("…".into())), + ..Default::default() + }; + window.with_text_style(Some(style), |window| { + let text = "office Λάμδα عَرَبِيّ and a later word"; + let standard = StyledText::new(text); + let expected = standard.layout().clone(); + standard.into_any_element().prepaint_as_root( + bounds.origin, + offered.map(AvailableSpace::Definite), + window, + cx, + ); + + let mut positioned = StyledText::new(text); + let measured = positioned.measure_as_block(offered, window, cx); + positioned.prepaint( + None, + None, + Bounds::new(bounds.origin, measured), + &mut (), + window, + cx, + ); + let actual = positioned.layout(); + assert_eq!(actual.bounds(), expected.bounds()); + assert_eq!(actual.line_height(), expected.line_height()); + for (index, _) in text.char_indices() { + let position = expected.position_for_index(index); + assert_eq!(actual.position_for_index(index), position); + if let Some(position) = position { + assert_eq!( + actual.index_for_position(position), + expected.index_for_position(position), + ); + } + } + }); + } + }, + |_, (), _, _| {}, + ) + }); + } +} + +#[gpui::test] +#[ignore = "manual dense Markdown redraw workload"] +fn measure_inline_layout_redraw(cx: &mut TestAppContext) { + let paragraphs = std::env::var("NOCTERM_MARKDOWN_PROBE_ROWS") + .map(|rows| rows.parse().expect("paragraph count")) + .unwrap_or(4_096); + let plain = std::env::var("NOCTERM_MARKDOWN_PROBE_FORMAT").as_deref() == Ok("plain"); + let text = if plain { + (0..paragraphs) + .map(|row| format!("Row {row} has a line of ordinary selectable text.\n\n")) + .collect() + } else { + source(paragraphs) + }; + cx.update(gpui_base::init); + let start = Instant::now(); + let (view, cx) = cx.add_window_view(|_, cx| Document { + state: cx.new(|cx| TextViewState::markdown(&text, cx)), + }); + cx.run_until_parked(); + let initial = start.elapsed(); + let visible = view.read_with(cx, |view, cx| view.state.read(cx).rendered_text()); + assert!( + visible + .as_str() + .contains(&format!("Row {}", paragraphs - 1)) + ); + let samples = std::env::var("NOCTERM_MARKDOWN_PROBE_REDRAWS") + .map(|count| count.parse().expect("redraw count")) + .unwrap_or(11); + assert!(samples > 0); + let mut redraw = vec![0; samples]; + for sample in &mut redraw { + let start = Instant::now(); + cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + }); + *sample = start.elapsed().as_micros(); + } + redraw.sort_unstable(); + println!( + "{paragraphs} paragraphs initial_us={} redraw_count={samples} redraw_min_us={} redraw_median_us={} redraw_max_us={}", + initial.as_micros(), + redraw[0], + redraw[samples / 2], + redraw[samples - 1] + ); +} diff --git a/vendor/gpui-base/tests/inline_pointer.rs b/vendor/gpui-base/tests/inline_pointer.rs new file mode 100644 index 00000000..ea050d6a --- /dev/null +++ b/vendor/gpui-base/tests/inline_pointer.rs @@ -0,0 +1,119 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext as _, Context, Entity, InputEvent as _, InteractiveElement as _, IntoElement, + Modifiers, MouseMoveEvent, ParentElement as _, Render, ScrollHandle, + StatefulInteractiveElement as _, Styled as _, TestAppContext, Window, div, point, px, +}; +use gpui_base::{TextSelectionLayer, TextView, TextViewState}; +use std::time::Instant; + +struct ScrollingLink { + scroll: ScrollHandle, + text: Entity, +} + +impl Render for ScrollingLink { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .id("scrolling-link") + .w(px(240.)) + .h(px(32.)) + .overflow_y_scroll() + .track_scroll(&self.scroll) + .child(div().h(px(100.))) + .child(TextView::new(&self.text)) + .child(div().h(px(100.))) + } +} + +#[gpui::test] +fn a_clipped_link_opens_once_scrolled_into_view(cx: &mut TestAppContext) { + check_scrolled_link(cx, "[open](https://example.com)", 100., 10.); +} + +#[gpui::test] +fn a_partially_clipped_link_in_positioned_text_still_opens(cx: &mut TestAppContext) { + check_scrolled_link(cx, "[open](https://example.com) next to `code`", 110., 4.); +} + +fn check_scrolled_link(cx: &mut TestAppContext, markdown: &str, offset: f32, click_y: f32) { + cx.update(gpui_base::init); + let scroll = ScrollHandle::new(); + let (_, cx) = cx.add_window_view(|_, cx| ScrollingLink { + scroll: scroll.clone(), + text: cx.new(|cx| TextViewState::markdown(markdown, cx)), + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + cx.simulate_click(point(px(10.), px(110.)), Modifiers::default()); + assert_eq!(cx.opened_url(), None); + + scroll.set_offset(point(px(0.), px(-offset))); + cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + }); + cx.simulate_click(point(px(10.), px(click_y)), Modifiers::default()); + assert_eq!(cx.opened_url().as_deref(), Some("https://example.com")); +} + +struct ClippedTranscript(Entity); + +impl Render for ClippedTranscript { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().child(TextSelectionLayer).child( + div() + .w(px(470.)) + .h(px(420.)) + .overflow_hidden() + .child(TextView::new(&self.0).selectable(true)), + ) + } +} + +#[gpui::test] +#[ignore = "manual pointer benchmark for long, clipped Markdown"] +fn measure_pointer_dispatch_in_clipped_transcript(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + let plain = "contains ordinary selectable text."; + let mixed = "contains **bold**, *italic* and `code` text."; + for (rows, body) in [(8, plain), (4_096, plain), (4_096, mixed)] { + let source: String = (0..rows) + .map(|row| format!("Row {row} {body}\n\n")) + .collect(); + let (view, cx) = cx.add_window_view(|_, cx| { + ClippedTranscript(cx.new(|cx| TextViewState::markdown(&source, cx))) + }); + cx.run_until_parked(); + assert!( + view.read_with(cx, |view, cx| view.0.read(cx).rendered_text()) + .as_str() + .contains(&format!("Row {}", rows - 1)) + ); + + let mut samples = [0; 11]; + for elapsed in &mut samples { + *elapsed = cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + + let start = Instant::now(); + for dy in (0..32_i16).cycle().take(256) { + window.dispatch_event( + MouseMoveEvent { + position: point(px(62.), px(5. + f32::from(dy))), + ..Default::default() + } + .to_platform_input(), + cx, + ); + } + start.elapsed().as_micros() + }); + } + samples.sort_unstable(); + println!("{rows} paragraphs ({body}), 256 mouse moves: {samples:?} µs"); + } +} diff --git a/vendor/gpui-base/tests/paragraph_layout.rs b/vendor/gpui-base/tests/paragraph_layout.rs new file mode 100644 index 00000000..9871626c --- /dev/null +++ b/vendor/gpui-base/tests/paragraph_layout.rs @@ -0,0 +1,161 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext as _, Context, Entity, IntoElement, Modifiers, MouseButton, ParentElement as _, + Pixels, Render, Styled as _, TestAppContext, Window, div, hsla, point, px, rems, size, +}; +use gpui_base::{ + TextSelectionLayer, TextView, TextViewState, TextViewStyle, + text::{RangeHighlight, SelectionFormat}, +}; + +struct Transcript { + text: Entity, + width: Option, +} + +impl Render for Transcript { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let text = TextView::new(&self.text) + .selectable(true) + .selection_format(SelectionFormat::Source) + .style(TextViewStyle::default().with_paragraph_gap(rems(0.125))); + let content = match self.width { + Some(width) => div().w(width).child(text), + None => div().flex().items_start().child(text.flex_none()), + }; + div() + .text_size(px(9.25)) + .line_height(px(12.375)) + .child(TextSelectionLayer) + .child(content) + } +} + +#[gpui::test] +fn long_markdown_preserves_wrapped_lines_and_drag_selection(cx: &mut TestAppContext) { + check_geometry_and_drag(cx, "with words."); +} + +#[gpui::test] +fn long_markdown_with_inline_code_preserves_wrapped_lines_and_drag_selection( + cx: &mut TestAppContext, +) { + check_geometry_and_drag(cx, "**with** `code words`"); +} + +fn check_geometry_and_drag(cx: &mut TestAppContext, ending: &str) { + cx.update(gpui_base::init); + let rows: Vec<_> = (0..257) + .map(|row| format!("Paragraph {row:03} {ending}")) + .collect(); + let source = rows.join("\n\n"); + let across_boundary = rows[31..33].join("\n\n"); + + for width in [Some(px(94.5)), Some(px(202.25)), None] { + let (view, cx) = cx.add_window_view(|_, cx| Transcript { + text: cx.new(|cx| TextViewState::markdown("", cx)), + width, + }); + cx.simulate_resize(size(px(450.), px(1200.))); + cx.simulate_scale_factor_change(1.25); + let text = view.read_with(cx, |view, _| view.text.clone()); + let colors = [hsla(0.17, 1., 0.5, 1.), hsla(0.53, 1., 0.5, 1.)]; + let mut paint = |source: &str| { + text.update(cx, |text, cx| text.set_text(source, cx)); + cx.run_until_parked(); + text.update(cx, |text, cx| { + let rendered = text.rendered_text(); + text.set_range_highlights( + rows[31..33].iter().zip(colors).map(|(row, color)| { + let visible = row.replace(['*', '`'], ""); + let start = rendered.as_str().find(&visible).unwrap(); + RangeHighlight::new(start..start + visible.len(), color) + }), + cx, + ) + .unwrap(); + }); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let quads = window.painted_quads(); + colors.map(|color| { + let mut lines: Vec<_> = quads + .iter() + .filter(|quad| quad.background == color.into()) + .map(|quad| quad.bounds.map(|value| px(value.0 / window.scale_factor()))) + .collect(); + lines.sort_by_key(|line| line.top()); + assert!(!lines.is_empty(), "missing highlight at width {width:?}"); + lines + }) + }) + }; + let flat = paint(&rows[..35].join("\n\n")); + let grouped = paint(&source); + assert_eq!(grouped, flat, "width {width:?}"); + + let first = grouped[0].first().unwrap(); + let last = grouped[1].last().unwrap(); + let start = point(first.left() + px(0.2), first.center().y); + let end = point(last.right() + px(0.5), last.center().y); + cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + let selected = text.read_with(cx, |text, _| text.selected_text()); + assert_eq!( + selected, across_boundary, + "width {width:?}, drag {start:?} to {end:?}" + ); + } +} + +#[gpui::test] +#[ignore = "manual timing for a warm frame of a long Markdown reply with inline code"] +fn measure_warm_redraw_with_inline_code(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + cx.update(gpui_base::init); + for paragraphs in [32, 512, 4096] { + let source: String = (0..paragraphs) + .map(|row| format!("Paragraph {row} has **emphasis** and `inline code`.\n\n")) + .collect(); + let (view, cx) = cx.add_window_view(|_, cx| Transcript { + text: cx.new(|cx| TextViewState::markdown(&source, cx)), + width: Some(px(250.)), + }); + cx.simulate_resize(size(px(400.), px(600.))); + cx.run_until_parked(); + let text = view.read_with(cx, |view, _| view.text.clone()); + let final_row = format!("Paragraph {}", paragraphs - 1); + let expected_height = text.read_with(cx, |text, _| { + assert!(text.rendered_text().as_str().contains(&final_row)); + text.bounds().size.height + }); + let mut draws = [0; 11]; + for elapsed in &mut draws { + *elapsed = cx.update(|window, cx| { + let start = Instant::now(); + window.refresh(); + window.draw(cx).clear(cx); + start.elapsed().as_micros() + }); + assert_eq!( + text.read_with(cx, |text, _| text.bounds().size.height), + expected_height + ); + } + draws.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{paragraphs} paragraphs, warm draw median/max µs: {}/{}", + draws[draws.len() / 2], + draws[draws.len() - 1], + ) + .unwrap(); + } +} diff --git a/vendor/gpui-base/tests/selection_highlight.rs b/vendor/gpui-base/tests/selection_highlight.rs new file mode 100644 index 00000000..b3a3386a --- /dev/null +++ b/vendor/gpui-base/tests/selection_highlight.rs @@ -0,0 +1,148 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext, Context, Entity, IntoElement, KeyDownEvent, Keystroke, Modifiers, ParentElement, + Render, Styled, TestAppContext, Window, div, px, +}; +use gpui_base::{ + Theme, + input::{Input, InputEditorStyle, InputState, Textarea, TextareaState}, +}; +use std::{cell::Cell, rc::Rc}; + +struct SelectionField { + state: Entity, +} + +struct MultilineSelectionField { + state: Entity, +} + +impl Render for MultilineSelectionField { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Textarea::new(&self.state) + } +} + +#[gpui::test] +fn multiline_selection_refreshes_for_changes_to_alt(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + let (view, cx) = cx.add_window_view(|window, cx| MultilineSelectionField { + state: cx.new(|cx| TextareaState::new(window, cx).default_value("first\nsecond")), + }); + let state = view.read_with(cx, |view, _| view.state.clone()); + cx.update(|window, cx| { + window.activate_window(); + state.update(cx, |state, cx| state.focus(window, cx)); + window.draw(cx).clear(cx); + }); + cx.run_until_parked(); + let notifications = Rc::new(Cell::new(0)); + let _subscription = cx.update(|_, cx| { + let notifications = notifications.clone(); + cx.observe(&state, move |_, _| { + notifications.set(notifications.get() + 1) + }) + }); + + let control = Modifiers { + control: true, + ..Modifiers::none() + }; + cx.simulate_modifiers_change(control); + assert_eq!(notifications.get(), 0, "Ctrl press"); + cx.simulate_event(KeyDownEvent { + keystroke: Keystroke::parse("ctrl-f13").unwrap(), + is_held: false, + prefer_character_input: false, + }); + let before_release = notifications.get(); + cx.simulate_modifiers_change(Modifiers::none()); + assert_eq!(notifications.get(), before_release, "Ctrl release"); + + let alt = Modifiers { + alt: true, + ..Modifiers::none() + }; + cx.simulate_modifiers_change(alt); + assert_eq!(notifications.get(), before_release + 1); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let while_alt_held = notifications.get(); + cx.simulate_modifiers_change(Modifiers { + control: true, + ..alt + }); + assert_eq!(notifications.get(), while_alt_held); + cx.simulate_modifiers_change(Modifiers::none()); + assert_eq!(notifications.get(), while_alt_held + 1); +} + +impl Render for SelectionField { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(px(120.)) + .overflow_hidden() + .child(Input::new(&self.state)) + } +} + +#[gpui::test] +fn selected_text_paints_a_clipped_rectangle_and_clears_after_replacement(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + for (value, masked, scale) in [ + ("Büro Ως", false, 1.), + ("שלום مرحبا", false, 1.5), + ("masked 🔑 password", true, 2.), + ( + "Long field value crossing the end of a narrow input field", + false, + 1.5, + ), + ] { + let (view, cx) = cx.add_window_view(move |window, cx| SelectionField { + state: cx.new(|cx| { + InputState::new(window, cx) + .default_value(value) + .masked(masked) + }), + }); + cx.simulate_scale_factor_change(scale); + let state = view.read_with(cx, |view, _| view.state.clone()); + cx.update(|window, cx| { + window.activate_window(); + state.update(cx, |state, cx| { + state.focus(window, cx); + state.select_all(window, cx); + }); + assert_eq!(state.read(cx).selected_range(), 0..value.len()); + }); + cx.run_until_parked(); + + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let color = InputEditorStyle::default() + .resolved(&Theme::global(cx).tokens) + .selection; + let highlights: Vec<_> = window + .painted_quads() + .into_iter() + .filter(|quad| quad.background == color.into()) + .collect(); + assert_eq!(highlights.len(), 1, "{value}"); + let highlight = highlights[0]; + let visible = highlight.bounds.intersect(&highlight.content_mask.bounds); + assert!(!visible.is_empty(), "{value}"); + assert!(f64::from(visible.right()) <= 120. * f64::from(scale)); + + state.update(cx, |state, cx| state.replace_all("replacement", window, cx)); + window.draw(cx).clear(cx); + assert_eq!(state.read(cx).value().as_str(), "replacement"); + assert!( + window + .painted_quads() + .iter() + .all(|quad| quad.background != color.into()) + ); + }); + } +} diff --git a/vendor/gpui-component/Cargo.lock b/vendor/gpui-component/Cargo.lock index 03bd79d9..aa6001b8 100644 --- a/vendor/gpui-component/Cargo.lock +++ b/vendor/gpui-component/Cargo.lock @@ -67,15 +67,6 @@ dependencies = [ "equator", ] -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "annotate-snippets" version = "0.12.16" @@ -649,20 +640,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - [[package]] name = "clang-sys" version = "1.9.1" @@ -1051,7 +1028,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.2", + "redox_users 0.5.3", "windows-sys 0.61.2", ] @@ -1713,14 +1690,11 @@ dependencies = [ [[package]] name = "gpui-base" version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64bb52b29a8dcdc8d3f595b8b0839c076f237572ab601ba4577d3da8ae085728" dependencies = [ "aho-corasick", "anyhow", "ashpd", "async-channel", - "chrono", "data-url", "futures", "gpui-pre", @@ -1729,6 +1703,7 @@ dependencies = [ "html5ever", "instant", "itertools 0.13.0", + "jiff", "lsp-types", "markdown", "markup5ever_rcdom", @@ -1756,7 +1731,6 @@ name = "gpui-component" version = "0.7.0" dependencies = [ "anyhow", - "chrono", "core-text", "enum-iterator", "gpui-base", @@ -1768,6 +1742,7 @@ dependencies = [ "indoc", "instant", "itertools 0.13.0", + "jiff", "log", "lsp-types", "markdown", @@ -1859,8 +1834,6 @@ dependencies = [ [[package]] name = "gpui-pre" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e87a42bb37c7cb4e76dd1ac0ce88851e46e976e0373a47ab3e0757abffee54d" dependencies = [ "accesskit", "anyhow", @@ -1869,7 +1842,6 @@ dependencies = [ "backtrace", "bindgen", "bitflags 2.13.1", - "chrono", "core-video", "ctor", "derive_more", @@ -1891,6 +1863,7 @@ dependencies = [ "image", "inventory", "itertools 0.14.0", + "jiff", "log", "lyon", "num_cpus", @@ -2057,14 +2030,12 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8049963b716df01b67b58f86000597f222d5b31b15b35069b23a3b07f3c68352" dependencies = [ "async-task", "backtrace", - "chrono", "flume", "futures", + "jiff", "parking_lot", "rand 0.9.5", "web-time", @@ -2119,12 +2090,10 @@ dependencies = [ [[package]] name = "gpui-pre-zlog" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7506302091e66d7fb5e04a5b3480e90cff0bbe3157458d7df91a41c59238c48" dependencies = [ "anyhow", - "chrono", "gpui-pre-collections", + "jiff", "log", ] @@ -2348,30 +2317,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core 0.62.2", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -2667,6 +2612,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "js-sys", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -2679,13 +2678,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -2799,9 +2797,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] @@ -3707,6 +3705,21 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "postage" version = "0.5.0" @@ -4170,11 +4183,10 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" dependencies = [ - "getrandom 0.2.17", "libredox", "thiserror 2.0.20", ] @@ -6306,12 +6318,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "serde", "wasm-bindgen-macro", @@ -6320,19 +6331,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6340,22 +6352,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.4", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -6375,9 +6387,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -7426,3 +7438,15 @@ dependencies = [ "syn 3.0.4", "winnow 1.0.4", ] + +[[patch.unused]] +name = "gpui-pre-linux" +version = "0.3.7" + +[[patch.unused]] +name = "gpui-pre-wgpu" +version = "0.3.7" + +[[patch.unused]] +name = "gpui-pre-windows" +version = "0.3.7" diff --git a/vendor/gpui-component/Cargo.toml b/vendor/gpui-component/Cargo.toml index d1f3e727..8415ba08 100644 --- a/vendor/gpui-component/Cargo.toml +++ b/vendor/gpui-component/Cargo.toml @@ -269,8 +269,9 @@ path = "tests/theme_compat.rs" [dependencies.anyhow] version = "1" -[dependencies.chrono] -version = "0.4.38" +[dependencies.jiff] +version = "1.1" +features = ["js"] [dependencies.enum-iterator] version = "2.1.0" @@ -584,3 +585,12 @@ useless_conversion = "allow" [lints.clippy.style] level = "allow" priority = -1 + +[patch.crates-io] +gpui-base = { path = "../gpui-base" } +gpui-pre = { path = "../gpui-pre" } +gpui-pre-linux = { path = "../gpui-pre-linux" } +gpui-pre-scheduler = { path = "../gpui-pre-scheduler" } +gpui-pre-wgpu = { path = "../gpui-pre-wgpu" } +gpui-pre-windows = { path = "../gpui-pre-windows" } +gpui-pre-zlog = { path = "../gpui-pre-zlog" } diff --git a/vendor/gpui-component/NOCTERM.md b/vendor/gpui-component/NOCTERM.md index b572d429..b1c63060 100644 --- a/vendor/gpui-component/NOCTERM.md +++ b/vendor/gpui-component/NOCTERM.md @@ -11,6 +11,44 @@ commit `0c830f4d257e69fdd17200650533ab4ca9a40cc0`, path `crates/component`. The upstream source, copyright notices and Apache-2.0 license are retained. This is an internal Cargo patch; the crate is excluded from Nocterm's workspace. +`src/command` folds each search query once. When editing it keeps the same +built-in rows, the component reuses their measured heights. Custom rows +still measure their children, and changes to layout inputs or the installed +model still invalidate measurement. + +Hosts with fixed choices can install a `Command` before mounting its +`CommandState`. The dialog then renders the state directly for its lifetime. +Dynamic command builders continue to install their model through rendering. + +List search applies already-completed delegate queries without scheduling a +loading animation or a completion timer. Pending delegates keep their loading +indicator while running. Issuing another query cancels the current task, including +when the user returns to a previously completed query. The List element wrapper +and its tests live in separate modules from the list state. + +Shared plain-choice pickers can use viewport measurement for large result +sets. Offscreen row heights are estimated until the rows are laid out. +Small results still measure intrinsic height, and the unrestricted command +palette constructor keeps the exact layout path. The shared interaction +state continues to own filtering, keyboard navigation and the selected +index. Remove this option when upstream can bound initial row layout +without changing short-list sizing. + +`src/dock/tab_panel.rs` shares the current bar's interaction snapshot with all +tab handlers. Each click, close and drop callback retains the same snapshot, +keeping a full copy of the panel list out of each individual callback. + +`src/tooltip.rs` skips the slide transition when the previous and current +triggers share the same horizontal center. Hover delay and fades still use +the toolkit's existing transitions. + +`src/shimmer.rs` limits redraw requests for a repeating text shimmer to 60 per +second. The sweep follows the existing synchronized clock and one-shot timing +is unchanged. + +`src/spinner.rs` applies the same redraw limit to decorative loading spinners. +The rotation still follows the configured duration and easing. + `src/menu/app_menu_bar.rs` changes menu behavior. `AppMenuBar::set_menus` updates a closed menu bar's snapshot in place, retaining existing menu entities, button identities and keyboard focus. `is_open` lets the window preserve an open @@ -98,7 +136,36 @@ built-in jump-to-latest control keep their existing ownership. Remove this forwarder when upstream exposes an equivalent query. +`src/command/command.rs` exposes lazy row measurement for ungrouped command +palettes. Nocterm's workspace palette uses the same viewport measurement as +plain choice lists, including exact sizing for short search results. Remove +this constructor when upstream exposes equivalent sizing. + `Cargo.toml` lists `log` under `[package.metadata.cargo-machete] ignored`. Nocterm runs cargo-machete over the whole repository; the upstream dependency is kept unchanged so the manifest does not drift from upstream. Remove the entry when upstream drops or uses the dependency. + +Tab panels collect the visible logical tab indices once per strip and pass +the resulting tabs directly to the tab bar. Tab bars build overflow menu +metadata only when their menu is enabled. The content corner policy stops +counting once it knows whether the title is visible. + +Tabs resolve their variant colors from one borrowed theme and build semantic +style refinements only for the selected or disabled states they apply. The +variant geometry and color rules live in one module shared with the tab bar. + +Switch thumb travel keeps the theme's spring and full display cadence while +moving. Its settling criterion also allows a scale-aware half-physical-pixel +remaining displacement envelope, stopping otherwise unnecessary redraws of the +host. The final thumb position, early reversal momentum and reduced-motion +behavior are unchanged. Remove this patch when upstream uses equivalent +physical-pixel settling. + +Styled buttons resolve their variant colors from one borrowed theme and build +selected and disabled refinements only when those controlled states apply. +An interactive button also reuses its hover colors for group highlighting. +The variant and visual policy live together in `button/button/variant.rs`; +existing tests moved to `button/button/tests.rs`. The Base control still owns +semantic precedence, focus, interaction and accessibility. Remove this patch +when upstream prepares only the applied visual states. diff --git a/vendor/gpui-component/src/button/button.rs b/vendor/gpui-component/src/button/button.rs index 67e45779..753362e5 100644 --- a/vendor/gpui-component/src/button/button.rs +++ b/vendor/gpui-component/src/button/button.rs @@ -1,20 +1,20 @@ // Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. -use std::rc::Rc; use crate::ThemeStyled as _; use crate::{ - ActiveTheme, Colorize as _, Disableable, Icon, Placement, RoleOverride, Selectable, Sizable, - Size, StyleSized, StyledExt, + ActiveTheme, Disableable, Icon, Placement, RoleOverride, Selectable, Sizable, Size, StyleSized, + StyledExt, button::ButtonIcon, h_flex, select::Caret, tooltip::{ManagedTooltipExt as _, Tooltip}, }; use gpui::{ - AnyElement, App, Background, ClickEvent, Corners, Edges, ElementId, Hsla, InteractiveElement, - Interactivity, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString, + AnyElement, App, ClickEvent, Corners, Edges, ElementId, InteractiveElement, Interactivity, + IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, - prelude::FluentBuilder as _, relative, transparent_white, + prelude::FluentBuilder as _, relative, }; +use std::rc::Rc; /// Product-wide button metrics. Installing this optional global changes only /// the size of standard buttons; variants and theme colours remain native. @@ -63,155 +63,6 @@ impl From for ButtonRounded { } } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub struct ButtonCustomVariant { - color: Hsla, - foreground: Hsla, - shadow: bool, - hover: Hsla, - active: Hsla, -} - -pub trait ButtonVariants: Sized { - fn with_variant(self, variant: ButtonVariant) -> Self; - - /// With the primary style for the Button. - fn primary(self) -> Self { - self.with_variant(ButtonVariant::Primary) - } - - /// With the secondary style for the Button. - fn secondary(self) -> Self { - self.with_variant(ButtonVariant::Secondary) - } - - /// With the danger style for the Button. - fn danger(self) -> Self { - self.with_variant(ButtonVariant::Danger) - } - - /// With the warning style for the Button. - fn warning(self) -> Self { - self.with_variant(ButtonVariant::Warning) - } - - /// With the success style for the Button. - fn success(self) -> Self { - self.with_variant(ButtonVariant::Success) - } - - /// With the info style for the Button. - fn info(self) -> Self { - self.with_variant(ButtonVariant::Info) - } - - /// With the ghost style for the Button. - fn ghost(self) -> Self { - self.with_variant(ButtonVariant::Ghost) - } - - /// With the link style for the Button. - fn link(self) -> Self { - self.with_variant(ButtonVariant::Link) - } - - /// With the text style for the Button, it will no padding look like a normal text. - fn text(self) -> Self { - self.with_variant(ButtonVariant::Text) - } - - /// With the custom style for the Button. - fn custom(self, style: ButtonCustomVariant) -> Self { - self.with_variant(ButtonVariant::Custom(style)) - } -} - -impl ButtonCustomVariant { - pub fn new(cx: &App) -> Self { - Self { - color: cx.theme().transparent, - foreground: cx.theme().foreground, - hover: cx.theme().transparent, - active: cx.theme().transparent, - shadow: false, - } - } - - /// Set background color, default is transparent. - pub fn color(mut self, color: Hsla) -> Self { - self.color = color; - self - } - - /// Set foreground color, default is theme foreground. - pub fn foreground(mut self, color: Hsla) -> Self { - self.foreground = color; - self - } - - /// Set hover background color, default is transparent. - pub fn hover(mut self, color: Hsla) -> Self { - self.hover = color; - self - } - - /// Set active background color, default is transparent. - pub fn active(mut self, color: Hsla) -> Self { - self.active = color; - self - } - - /// Set shadow, default is false. - pub fn shadow(mut self, shadow: bool) -> Self { - self.shadow = shadow; - self - } -} - -/// The variant of the Button. -#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)] -pub enum ButtonVariant { - #[default] - Default, - Primary, - Secondary, - Danger, - Info, - Success, - Warning, - Ghost, - Link, - Text, - Custom(ButtonCustomVariant), -} - -impl ButtonVariant { - #[inline] - pub fn is_link(&self) -> bool { - matches!(self, Self::Link) - } - - #[inline] - pub fn is_text(&self) -> bool { - matches!(self, Self::Text) - } - - #[inline] - pub fn is_ghost(&self) -> bool { - matches!(self, Self::Ghost) - } - - #[inline] - fn no_padding(&self) -> bool { - self.is_link() || self.is_text() - } - - #[inline] - fn is_default(&self) -> bool { - matches!(self, Self::Default) - } -} - /// A Button element. #[derive(IntoElement)] pub struct Button { @@ -636,9 +487,6 @@ impl RenderOnce for Button { let mut base = self.base; let children = self.children; let instance_style = base.style().clone(); - let normal_style = style.normal(self.outline, cx); - let selected_style = style.selected(self.outline, cx); - let disabled_style = style.disabled(self.outline, cx); let icon_size = self.icon_size.unwrap_or_else(|| match self.size { Size::Size(v) => Size::Size(v * 0.75), _ => self.size, @@ -650,11 +498,13 @@ impl RenderOnce for Button { .read(cx) .clone(); let is_focused = focus_handle.is_focused(window); + let theme = cx.theme(); + let normal_style = style.normal(self.outline, theme); let rounding = match self.rounded { - ButtonRounded::Small => cx.theme().radius * 0.5, - ButtonRounded::Medium => cx.theme().radius, - ButtonRounded::Large => cx.theme().radius * 2.0, + ButtonRounded::Small => theme.radius * 0.5, + ButtonRounded::Medium => theme.radius, + ButtonRounded::Large => theme.radius * 2.0, ButtonRounded::Size(px) => px, ButtonRounded::None => Pixels::ZERO, }; @@ -672,10 +522,9 @@ impl RenderOnce for Button { interactive && (self.variant.is_link() || self.variant.is_text()), |this| this.cursor_pointer(), ) - .when( - !disabled && cx.theme().shadow && normal_style.shadow, - |this| this.shadow_xs(), - ) + .when(!disabled && theme.shadow && normal_style.shadow, |this| { + this.shadow_xs() + }) .when(!style.no_padding(), |this| { if self.label.is_none() && children.is_empty() { // Icon Button @@ -747,20 +596,20 @@ impl RenderOnce for Button { // A loading button keeps its normal colors, but must not react // to the pointer, it is not waiting for another click. .when(interactive, |this| { + let hover_style = style.hovered(self.outline, theme); this.hover(|this| { - let hover_style = style.hovered(self.outline, cx); this.bg(hover_style.bg) .border_color(hover_style.border) .text_color(hover_style.fg) }) .active(|this| { - let active_style = style.active(self.outline, cx); + let active_style = style.active(self.outline, theme); this.bg(active_style.bg) .border_color(active_style.border) .text_color(active_style.fg) }) .when_some(hover_group, |this, group| { - let idle_bg = style.hovered(self.outline, cx).bg.opacity(0.5); + let idle_bg = hover_style.bg.opacity(0.5); this.when(hover_group_held, |this| this.bg(idle_bg)) .group_hover(group, |this| this.bg(idle_bg)) }) @@ -823,23 +672,31 @@ impl RenderOnce for Button { .disabled(disabled) // Base layers semantic states over the builder chain, so the caller's // own style is replayed inside each state to keep it the closest layer. - .styles(|styles| { - styles - .selected(|style| { - style - .bg(selected_style.bg) - .border_color(selected_style.border) - .text_color(selected_style.fg) - .refine_style(&instance_style) - }) - .disabled(|style| { - style - .bg(disabled_style.bg) - .text_color(disabled_style.fg) - .border_color(disabled_style.border) - .shadow_none() - .refine_style(&instance_style) - }) + .when(selected || disabled, |this| { + this.styles(|mut styles| { + if selected { + let selected_style = style.selected(self.outline, theme); + styles = styles.selected(|style| { + style + .bg(selected_style.bg) + .border_color(selected_style.border) + .text_color(selected_style.fg) + .refine_style(&instance_style) + }); + } + if disabled { + let disabled_style = style.disabled(self.outline, theme); + styles = styles.disabled(|style| { + style + .bg(disabled_style.bg) + .text_color(disabled_style.fg) + .border_color(disabled_style.border) + .shadow_none() + .refine_style(&instance_style) + }); + } + styles + }) }) .when_some(accessibility_label, |this, label| { this.accessibility_label(label) @@ -919,1098 +776,10 @@ impl RenderOnce for Button { } } -struct ButtonVariantStyle { - bg: Background, - border: Hsla, - fg: Hsla, - underline: bool, - shadow: bool, -} - -#[derive(Clone, Copy)] -enum ButtonStyleState { - Normal, - Hovered, - Active, -} - -impl ButtonVariant { - fn outline_background(&self, state: ButtonStyleState, cx: &mut App) -> Background { - match (self, state) { - (Self::Default, ButtonStyleState::Normal) => cx.theme().input_background().into(), - (Self::Default, ButtonStyleState::Hovered) => cx - .theme() - .input - .mix_oklab(cx.theme().transparent, 0.5) - .into(), - (Self::Default, ButtonStyleState::Active) => cx - .theme() - .input - .mix_oklab(cx.theme().transparent, 0.7) - .into(), - (Self::Primary, ButtonStyleState::Normal) => { - cx.theme().tokens.primary.background.opacity(0.1) - } - (Self::Primary, ButtonStyleState::Hovered) => { - cx.theme().tokens.primary_hover.background.opacity(0.2) - } - (Self::Primary, ButtonStyleState::Active) => { - cx.theme().tokens.primary_active.background.opacity(0.4) - } - (Self::Secondary, ButtonStyleState::Normal) => { - cx.theme().tokens.secondary.background.opacity(0.1) - } - (Self::Secondary, ButtonStyleState::Hovered) => { - cx.theme().tokens.secondary_hover.background.opacity(0.2) - } - (Self::Secondary, ButtonStyleState::Active) => { - cx.theme().tokens.secondary_active.background.opacity(0.4) - } - (Self::Danger, ButtonStyleState::Normal) => { - cx.theme().tokens.danger.background.opacity(0.1) - } - (Self::Danger, ButtonStyleState::Hovered) => { - cx.theme().tokens.danger_hover.background.opacity(0.2) - } - (Self::Danger, ButtonStyleState::Active) => { - cx.theme().tokens.danger_active.background.opacity(0.4) - } - (Self::Warning, ButtonStyleState::Normal) => { - cx.theme().tokens.warning.background.opacity(0.1) - } - (Self::Warning, ButtonStyleState::Hovered) => { - cx.theme().tokens.warning_hover.background.opacity(0.2) - } - (Self::Warning, ButtonStyleState::Active) => { - cx.theme().tokens.warning_active.background.opacity(0.4) - } - (Self::Success, ButtonStyleState::Normal) => { - cx.theme().tokens.success.background.opacity(0.1) - } - (Self::Success, ButtonStyleState::Hovered) => { - cx.theme().tokens.success_hover.background.opacity(0.2) - } - (Self::Success, ButtonStyleState::Active) => { - cx.theme().tokens.success_active.background.opacity(0.4) - } - (Self::Info, ButtonStyleState::Normal) => { - cx.theme().tokens.info.background.opacity(0.1) - } - (Self::Info, ButtonStyleState::Hovered) => { - cx.theme().tokens.info_hover.background.opacity(0.2) - } - (Self::Info, ButtonStyleState::Active) => { - cx.theme().tokens.info_active.background.opacity(0.4) - } - (Self::Ghost | Self::Link | Self::Text, _) => cx.theme().transparent.into(), - (Self::Custom(colors), _) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(), - } - } - - fn bg_color(&self, outline: bool, cx: &mut App) -> Background { - if outline { - return self.outline_background(ButtonStyleState::Normal, cx); - } - - match self { - Self::Default => cx.theme().tokens.button.into(), - Self::Primary => cx.theme().tokens.button_primary.into(), - Self::Secondary => cx.theme().tokens.button_secondary.into(), - Self::Danger => cx.theme().tokens.button_danger.into(), - Self::Warning => cx.theme().tokens.button_warning.into(), - Self::Success => cx.theme().tokens.button_success.into(), - Self::Info => cx.theme().tokens.button_info.into(), - Self::Ghost | Self::Link | Self::Text => cx.theme().transparent.into(), - Self::Custom(colors) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(), - } - } - - fn text_color(&self, outline: bool, cx: &mut App) -> Hsla { - match self { - Self::Default => cx.theme().button_foreground, - Self::Primary => { - if outline { - cx.theme().primary - } else { - cx.theme().button_primary_foreground - } - } - Self::Secondary => { - if outline { - cx.theme().secondary_foreground - } else { - cx.theme().button_secondary_foreground - } - } - Self::Ghost => cx.theme().secondary_foreground, - Self::Danger => { - if outline { - cx.theme().danger - } else { - cx.theme().button_danger_foreground - } - } - Self::Warning => { - if outline { - cx.theme().warning - } else { - cx.theme().button_warning_foreground - } - } - Self::Success => { - if outline { - cx.theme().success - } else { - cx.theme().button_success_foreground - } - } - Self::Info => { - if outline { - cx.theme().info - } else { - cx.theme().button_info_foreground - } - } - Self::Link => cx.theme().link, - Self::Text => cx.theme().foreground.opacity(0.9), - Self::Custom(colors) => colors.foreground, - } - } - - fn border_color(&self, outline: bool, cx: &mut App) -> Hsla { - match self { - Self::Default => cx.theme().input, - Self::Secondary => cx.theme().border, - Self::Primary => cx.theme().primary, - Self::Danger => { - if outline { - cx.theme().danger.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_danger - } - } - Self::Info => { - if outline { - cx.theme().info.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_info - } - } - Self::Warning => { - if outline { - cx.theme().warning.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_warning - } - } - Self::Success => { - if outline { - cx.theme().success.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_success - } - } - Self::Ghost | Self::Link | Self::Text => cx.theme().transparent, - Self::Custom(colors) => { - if outline { - colors.color.mix_oklab(transparent_white(), 0.4) - } else { - colors.color - } - } - } - } - - fn underline(&self, _: &App) -> bool { - match self { - Self::Link => true, - _ => false, - } - } - - fn shadow(&self, _outline: bool, _: &App) -> bool { - match self { - Self::Custom(c) => c.shadow, - _ => false, - } - } - - fn normal(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg = self.bg_color(outline, cx); - let border = self.border_color(outline, cx); - let fg = self.text_color(outline, cx); - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn hovered(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg: Background = match self { - Self::Default => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_hover.into() - } - } - Self::Primary => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_primary_hover.into() - } - } - Self::Secondary => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_secondary_hover.into() - } - } - Self::Danger => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_danger_hover.into() - } - } - Self::Warning => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_warning_hover.into() - } - } - Self::Success => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_success_hover.into() - } - } - Self::Info => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_info_hover.into() - } - } - Self::Custom(colors) => colors.hover.into(), - Self::Ghost => { - let accent: Background = cx.theme().tokens.accent.into(); - if cx.theme().mode.is_dark() { - accent.opacity(0.5) - } else { - accent - } - } - Self::Link => cx.theme().transparent.into(), - Self::Text => cx.theme().transparent.into(), - }; - - let border = self.border_color(outline, cx); - let fg = match self { - Self::Link => cx.theme().link_hover, - Self::Text => cx.theme().foreground, - Self::Ghost => cx.theme().accent_foreground, - _ => self.text_color(outline, cx), - }; - - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn active(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg = match self { - Self::Default => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_active.into() - } - } - Self::Primary => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_primary_active.into() - } - } - Self::Secondary => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_secondary_active.into() - } - } - Self::Ghost => cx.theme().tokens.button_active.into(), - Self::Danger => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_danger_active.into() - } - } - Self::Warning => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_warning_active.into() - } - } - Self::Success => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_success_active.into() - } - } - Self::Info => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_info_active.into() - } - } - Self::Custom(colors) => colors.active.into(), - Self::Link => cx.theme().transparent.into(), - Self::Text => cx.theme().transparent.into(), - }; - let border = self.border_color(outline, cx); - let fg = match self { - Self::Link => cx.theme().link_active, - Self::Text => cx.theme().foreground.opacity(0.7), - _ => self.text_color(outline, cx), - }; - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn selected(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - if outline { - let active_style = self.active(outline, cx); - - return ButtonVariantStyle { - fg: self.text_color(outline, cx), - ..active_style - }; - } - - let bg = match self { - Self::Default => cx.theme().tokens.button_active.into(), - Self::Primary => cx.theme().tokens.button_primary_active.into(), - Self::Secondary => cx.theme().tokens.button_secondary_active.into(), - Self::Ghost => cx.theme().tokens.secondary_active.into(), - Self::Danger => cx.theme().tokens.button_danger_active.into(), - Self::Warning => cx.theme().tokens.button_warning_active.into(), - Self::Success => cx.theme().tokens.button_success_active.into(), - Self::Info => cx.theme().tokens.button_info_active.into(), - Self::Link => cx.theme().transparent.into(), - Self::Text => cx.theme().transparent.into(), - Self::Custom(colors) => colors.active.into(), - }; - - let border = self.border_color(outline, cx); - let fg = match self { - Self::Link => cx.theme().link_active, - Self::Text => cx.theme().foreground.opacity(0.7), - _ => self.text_color(false, cx), - }; - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn disabled(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg = match self { - Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent.into(), - Self::Primary => cx.theme().tokens.button_primary.background.opacity(0.15), - Self::Danger => cx.theme().tokens.button_danger.background.opacity(0.15), - Self::Warning => cx.theme().tokens.button_warning.background.opacity(0.15), - Self::Success => cx.theme().tokens.button_success.background.opacity(0.15), - Self::Info => cx.theme().tokens.button_info.background.opacity(0.15), - Self::Secondary => cx.theme().tokens.button_secondary.background.opacity(1.5), - Self::Custom(style) => style.color.opacity(0.15).into(), - }; - let fg = cx.theme().muted_foreground.opacity(0.5); - let (bg, border) = if outline { - ( - self.outline_background(ButtonStyleState::Normal, cx) - .opacity(0.5), - self.border_color(true, cx).opacity(0.5), - ) - } else if let Self::Default = self { - ( - cx.theme().input_background().opacity(0.5).into(), - cx.theme().input.opacity(0.5), - ) - } else { - let border = match self { - Self::Primary => cx.theme().button_primary.opacity(0.15), - Self::Secondary => cx.theme().button_secondary.opacity(1.5), - Self::Danger => cx.theme().button_danger.opacity(0.15), - Self::Warning => cx.theme().button_warning.opacity(0.15), - Self::Success => cx.theme().button_success.opacity(0.15), - Self::Info => cx.theme().button_info.opacity(0.15), - Self::Custom(style) => style.color.opacity(0.15), - Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent, - }; - (bg, border) - }; - - let underline = self.underline(cx); - let shadow = false; - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } -} +mod variant; +pub use variant::{ButtonCustomVariant, ButtonVariant, ButtonVariants}; #[cfg(test)] -mod tests { - use super::*; - use crate::IconName; - use gpui::{linear_color_stop, linear_gradient, px}; - - /// A button's announced name is its label, unless it was given one — which - /// is the case an icon-only button and a row-shaped button both need. - #[test] - fn an_explicit_accessibility_label_replaces_the_visible_one() { - let plain = Button::new("save").label("Save"); - assert_eq!(plain.accessibility_label, None); - assert_eq!(plain.label.as_deref(), Some("Save")); - - let named = Button::new("row") - .label("Save") - .accessibility_label("Save the current document"); - assert_eq!( - named.accessibility_label.as_deref(), - Some("Save the current document"), - "an explicit name must win over the visible label" - ); - assert_eq!( - named.label.as_deref(), - Some("Save"), - "and must not change what is drawn" - ); - } - - #[gpui::test] - fn disabled_legacy_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{Context, Modifiers, Render, point}; - - struct Harness(Rc>, Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let button_clicks = self.0.clone(); - let parent_clicks = self.1.clone(); - div() - .id("disabled-button-parent") - .tab_group() - .size(px(100.)) - .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1)) - .child( - Button::new("disabled-legacy") - .disabled(true) - .size_full() - .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)), - ) - } - } - - cx.update(crate::init); - let button_clicks = Rc::new(Cell::new(0)); - let parent_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let button_clicks = button_clicks.clone(); - let parent_clicks = parent_clicks.clone(); - move |_, _| Harness(button_clicks, parent_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - - assert_eq!(button_clicks.get(), 0); - assert_eq!(parent_clicks.get(), 0); - cx.update(|window, cx| assert!(window.focused(cx).is_none())); - } - - #[gpui::test] - fn enabled_button_delegates_pointer_enter_and_space_once(cx: &mut gpui::TestAppContext) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{ - ClickEvent, Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, point, - }; - - struct Harness(Rc>, Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let clicks = self.0.clone(); - let keyboard_clicks = self.1.clone(); - div().tab_group().size(px(100.)).child( - Button::new("enabled-legacy") - .size_full() - .on_click(move |event, _, _| { - clicks.set(clicks.get() + 1); - if matches!(event, ClickEvent::Keyboard(_)) { - keyboard_clicks.set(keyboard_clicks.get() + 1); - } - }), - ) - } - } - - cx.update(crate::init); - let clicks = Rc::new(Cell::new(0)); - let keyboard_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let clicks = clicks.clone(); - let keyboard_clicks = keyboard_clicks.clone(); - move |_, _| Harness(clicks, keyboard_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.update(|window, cx| { - assert!(window.focused(cx).is_some()); - window.draw(cx).clear(cx); - }); - for key in ["enter", "space"] { - let keystroke = Keystroke::parse(key).unwrap(); - cx.simulate_event(KeyDownEvent { - keystroke: keystroke.clone(), - is_held: false, - prefer_character_input: false, - }); - cx.simulate_event(KeyUpEvent { keystroke }); - } - - assert_eq!(clicks.get(), 3); - assert_eq!(keyboard_clicks.get(), 2); - } - - #[gpui::test] - fn loading_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{Context, Modifiers, Render, point}; - - struct Harness(Rc>, Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let button_clicks = self.0.clone(); - let parent_clicks = self.1.clone(); - div() - .id("loading-button-parent") - .tab_group() - .size(px(100.)) - .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1)) - .child( - Button::new("loading-legacy") - .loading(true) - .size_full() - .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)), - ) - } - } - - cx.update(crate::init); - let button_clicks = Rc::new(Cell::new(0)); - let parent_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let button_clicks = button_clicks.clone(); - let parent_clicks = parent_clicks.clone(); - move |_, _| Harness(button_clicks, parent_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - - assert_eq!(button_clicks.get(), 0); - assert_eq!(parent_clicks.get(), 0); - cx.update(|window, cx| assert!(window.focused(cx).is_some())); - } - - #[gpui::test] - fn loading_button_without_callback_still_blocks_parent_activation( - cx: &mut gpui::TestAppContext, - ) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{Context, Modifiers, Render, point}; - - struct Harness(Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let parent_clicks = self.0.clone(); - div() - .id("loading-without-callback-parent") - .tab_group() - .size(px(100.)) - .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1)) - .child( - Button::new("loading-without-callback") - .loading(true) - .size_full(), - ) - } - } - - cx.update(crate::init); - let parent_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let parent_clicks = parent_clicks.clone(); - move |_, _| Harness(parent_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - - assert_eq!(parent_clicks.get(), 0); - cx.update(|window, cx| assert!(window.focused(cx).is_some())); - } - - #[gpui::test] - fn base_activation_is_preserved_and_blocked_while_loading(cx: &mut gpui::TestAppContext) { - use gpui::{Context, Render, point}; - use std::{cell::Cell, rc::Rc}; - - struct Harness { - clicks: Rc>, - loading: bool, - } - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let clicks = self.clicks.clone(); - div().tab_group().child( - Button::new("close") - .with_base( - gpui_base::Button::new("close") - .on_click(move |_, _, _| clicks.set(clicks.get() + 1)), - ) - .loading(self.loading) - .size(px(100.)), - ) - } - } - - cx.update(crate::init); - let clicks = Rc::new(Cell::new(0)); - let (view, cx) = cx.add_window_view({ - let clicks = clicks.clone(); - move |_, _| Harness { - clicks, - loading: false, - } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Default::default()); - assert_eq!(clicks.get(), 1); - - view.update(cx, |view, cx| { - view.loading = true; - cx.notify(); - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Default::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - assert_eq!(clicks.get(), 1); - } - - #[gpui::test] - fn test_button_builder(_cx: &mut gpui::TestAppContext) { - let button = Button::new("complex-button") - .label("Save Changes") - .primary() - .outline() - .large() - .tooltip("Click to save") - .compact() - .loading(false) - .disabled(false) - .selected(false) - .tab_index(1) - .tab_stop(true) - .dropdown_caret(false) - .rounded(ButtonRounded::Medium) - .on_click(|_, _, _| {}); - - assert_eq!(button.label, Some("Save Changes".into())); - assert_eq!(button.variant, ButtonVariant::Primary); - assert!(button.outline); - assert_eq!(button.size, Size::Large); - assert!(button.tooltip.is_some()); - assert!(button.compact); - assert!(!button.loading); - assert!(!button.disabled); - assert!(!button.selected); - assert_eq!(button.toggled, None); - assert_eq!(button.tab_index, 1); - assert!(button.tab_stop); - assert!(!button.dropdown_caret); - assert!(matches!(button.rounded, ButtonRounded::Medium)); - } - - /// A button paints an open popup the way it paints a selection, but the - /// two states are stored apart, so a caller can read back which one it set - /// and a later design can tell them apart visually. - #[test] - fn an_open_trigger_is_stored_apart_from_a_selected_one() { - let open = Button::new("trigger").open(true); - assert!(open.is_open()); - assert!(!open.is_selected()); - assert!(open.shows_selected_style()); - - let selected = Button::new("trigger").selected(true); - assert!(selected.is_selected()); - assert!(!selected.is_open()); - assert!(selected.shows_selected_style()); - - assert!(!Button::new("trigger").shows_selected_style()); - } - - #[test] - fn selected_trigger_presentation_does_not_imply_toggled_accessibility() { - let selected = Button::new("menu-trigger").selected(true); - assert!(selected.selected); - assert_eq!(selected.toggled, None); - - let selected_toggle = Button::new("explicit-toggle").selected(true).toggled(true); - assert!(selected_toggle.selected); - assert_eq!(selected_toggle.toggled, Some(true)); - } - - /// A loading button must be as inert as a disabled one. `interactive` is what - /// gates the hover and active styling, the `cursor_pointer` of link buttons and - /// the `mouse_down` handler, none of which depend on a listener being set. - #[gpui::test] - fn test_button_loading_is_not_interactive(_cx: &mut gpui::TestAppContext) { - assert!(Button::new("test").interactive()); - assert!(!Button::new("test").loading(true).interactive()); - assert!(!Button::new("test").disabled(true).interactive()); - assert!( - !Button::new("test") - .loading(true) - .disabled(true) - .interactive() - ); - - // Loading gates hovering even when an `on_hover` listener is set. - let loading = Button::new("test").loading(true).on_hover(|_, _, _| {}); - assert!(!loading.hoverable()); - } - - /// `selected` is styling only; the toggle state must be opted into, so that - /// ordinary buttons are not announced as toggle buttons. - #[gpui::test] - fn test_button_variant_methods(_cx: &mut gpui::TestAppContext) { - // Test variant check methods - assert!(ButtonVariant::Link.is_link()); - assert!(ButtonVariant::Text.is_text()); - assert!(ButtonVariant::Ghost.is_ghost()); - - // Test no_padding logic - assert!(ButtonVariant::Link.no_padding()); - assert!(ButtonVariant::Text.no_padding()); - assert!(!ButtonVariant::Ghost.no_padding()); - } - - #[gpui::test] - fn link_button_prepaints_its_child(cx: &mut gpui::TestAppContext) { - use gpui::{Context, Render}; - - struct LinkButtonHarness; - - impl Render for LinkButtonHarness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - Button::new("link-button").link().child( - div() - .debug_selector(|| "link-button-child".into()) - .child("Visible link button"), - ) - } - } - - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, _| LinkButtonHarness); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - let bounds = cx - .debug_bounds("link-button-child") - .expect("link button child must participate in layout and prepaint"); - assert!(bounds.size.width > px(0.)); - assert!(bounds.size.height > px(0.)); - } - - #[gpui::test] - fn base_slot_prepaints_complete_button_content(cx: &mut gpui::TestAppContext) { - use gpui::{Context, Render}; - - struct CompleteButtonHarness; - - impl Render for CompleteButtonHarness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .child( - Button::new("complete-button") - .icon(IconName::Plus) - .label("Create") - .child( - div() - .debug_selector(|| "button-custom-content".into()) - .child("Details"), - ) - .dropdown_caret(true), - ) - .child( - Button::new("loading-button") - .icon(IconName::Plus) - .loading_icon(IconName::Loader) - .loading(true) - .label("Creating") - .dropdown_caret(true), - ) - } - } - - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, _| CompleteButtonHarness); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - let bounds = cx - .debug_bounds("button-custom-content") - .expect("application content must prepaint through the Base child seam"); - assert!(bounds.size.width > px(0.)); - assert!(bounds.size.height > px(0.)); - } - - #[gpui::test] - fn test_outline_selected_uses_outline_active_style(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let variant = ButtonVariant::Danger; - let active_style = variant.active(true, cx); - let selected_style = variant.selected(true, cx); - - assert_eq!(selected_style.bg, active_style.bg); - assert_eq!(selected_style.border, active_style.border); - assert_eq!(selected_style.fg, cx.theme().danger); - assert_ne!(selected_style.bg, cx.theme().tokens.danger_active.into()); - }); - } - - #[gpui::test] - fn test_primary_button_uses_gradient_background_tokens(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Gradient", - "mode": "light", - "colors": { - "button.primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)", - "button.primary.hover.background": "linear-gradient(145deg, #4338CA, #0891B2)", - "button.primary.active.background": "linear-gradient(155deg, #3730A3, #0E7490)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.normal(false, cx).bg, - cx.theme().tokens.button_primary.into() - ); - assert_eq!( - ButtonVariant::Primary.hovered(false, cx).bg, - cx.theme().tokens.button_primary_hover.into() - ); - assert_eq!( - ButtonVariant::Primary.active(false, cx).bg, - cx.theme().tokens.button_primary_active.into() - ); - }); - } - - #[gpui::test] - fn test_outline_primary_keeps_original_depth(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Outline Depth", - "mode": "light", - "colors": { - "primary.background": "linear-gradient(180deg, #111827, #020617)", - "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)", - "primary.active.background": "linear-gradient(180deg, #020617, #000000)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.normal(true, cx).bg, - cx.theme().tokens.primary.background.opacity(0.1) - ); - assert_eq!( - ButtonVariant::Primary.hovered(true, cx).bg, - cx.theme().tokens.primary_hover.background.opacity(0.2) - ); - assert_eq!( - ButtonVariant::Primary.active(true, cx).bg, - cx.theme().tokens.primary_active.background.opacity(0.4) - ); - }); - } - - #[gpui::test] - fn test_outline_buttons_use_semantic_gradient_tokens(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Outline Gradient", - "mode": "light", - "colors": { - "primary.background": "linear-gradient(180deg, #111827, #020617)", - "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)", - "primary.active.background": "linear-gradient(180deg, #020617, #000000)", - "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)", - "button.primary.hover.background": "linear-gradient(180deg, #F9FAFB, #E5E7EB)", - "button.primary.active.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)", - "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)", - "danger.hover.background": "linear-gradient(180deg, #F87171, #EF4444)", - "danger.active.background": "linear-gradient(180deg, #DC2626, #B91C1C)", - "button.danger.background": "linear-gradient(180deg, #FEF2F2, #FEE2E2)", - "button.danger.hover.background": "linear-gradient(180deg, #FEE2E2, #FECACA)", - "button.danger.active.background": "linear-gradient(180deg, #FECACA, #FCA5A5)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.normal(true, cx).bg, - cx.theme().tokens.primary.background.opacity(0.1) - ); - assert_eq!( - ButtonVariant::Danger.normal(true, cx).bg, - cx.theme().tokens.danger.background.opacity(0.1) - ); - assert_eq!( - ButtonVariant::Danger.hovered(true, cx).bg, - cx.theme().tokens.danger_hover.background.opacity(0.2) - ); - assert_eq!( - ButtonVariant::Danger.active(true, cx).bg, - cx.theme().tokens.danger_active.background.opacity(0.4) - ); - assert_eq!( - ButtonVariant::Primary.normal(false, cx).bg, - cx.theme().tokens.button_primary.into() - ); - assert_eq!( - ButtonVariant::Danger.normal(false, cx).bg, - linear_gradient( - 180., - linear_color_stop(crate::try_parse_color("#FEF2F2").unwrap(), 0.), - linear_color_stop(crate::try_parse_color("#FEE2E2").unwrap(), 1.) - ) - ); - }); - } - - #[gpui::test] - fn test_disabled_outline_buttons_keep_semantic_backgrounds(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Disabled Outline Gradient", - "mode": "light", - "colors": { - "primary.background": "linear-gradient(180deg, #111827, #020617)", - "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)", - "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)", - "button.danger.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.disabled(true, cx).bg, - cx.theme() - .tokens - .primary - .background - .opacity(0.1) - .opacity(0.5) - ); - assert_eq!( - ButtonVariant::Danger.disabled(true, cx).bg, - cx.theme() - .tokens - .danger - .background - .opacity(0.1) - .opacity(0.5) - ); - assert_ne!( - ButtonVariant::Danger.disabled(true, cx).bg, - cx.theme().input_background().opacity(0.5).into() - ); - assert_ne!( - ButtonVariant::Danger.disabled(true, cx).bg, - cx.theme().tokens.button_danger.background.opacity(0.15) - ); - }); - } -} +mod performance; +#[cfg(test)] +mod tests; diff --git a/vendor/gpui-component/src/button/button/performance.rs b/vendor/gpui-component/src/button/button/performance.rs new file mode 100644 index 00000000..2e0702f1 --- /dev/null +++ b/vendor/gpui-component/src/button/button/performance.rs @@ -0,0 +1,83 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. +use std::{ + hash::{DefaultHasher, Hash, Hasher}, + time::Instant, +}; + +use gpui::{Context, Render, TestAppContext, px, size}; + +use super::*; + +struct Buttons { + count: usize, + mixed: bool, +} + +impl Render for Buttons { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .flex() + .flex_wrap() + .gap_1() + .children((0..self.count).map(|index| { + let variant = match index % 8 { + 0 => ButtonVariant::Default, + 1 => ButtonVariant::Primary, + 2 => ButtonVariant::Secondary, + 3 => ButtonVariant::Ghost, + 4 => ButtonVariant::Danger, + 5 => ButtonVariant::Warning, + 6 => ButtonVariant::Success, + _ => ButtonVariant::Info, + }; + Button::new(index) + .with_variant(variant) + .when(index % 3 == 0, Button::outline) + .label("Button") + .selected(self.mixed && index % 5 == 0) + .disabled(self.mixed && index % 7 == 0) + })) + } +} + +#[gpui::test] +#[ignore = "manual CPU and allocation workload"] +fn measure_button_render_preparation(cx: &mut TestAppContext) { + cx.update(crate::init); + eprintln!( + "base_button_bytes={} component_button_bytes={}", + std::mem::size_of::(), + std::mem::size_of::