diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..35f0f23 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,82 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +# Read the code, nothing else. No step needs a secret, a token or network +# access beyond the package registries. +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + # Smaller builds and cache; backtraces keep their file and line. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + +jobs: + test: + name: test (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + # ubuntu-24.04 is pinned: ubuntu-latest moves to 26.04 in November 2026 + # (actions/runner-images#14748), and nothing has been built against its + # WebKitGTK yet. macos-latest is macOS 26 on Apple silicon. + os: [ubuntu-24.04, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + # Windows has never been run: its failures are listed, not hidden. Remove once green. + continue-on-error: ${{ matrix.os == 'windows-latest' }} + timeout-minutes: 60 + steps: + - name: Keep line endings as committed + if: runner.os == 'Windows' + run: git config --global core.autocrlf false + + - uses: actions/checkout@v7 + + - uses: actions/setup-node@v7 + with: + node-version: 22 + cache: npm + + # The toolchain this was verified with on Linux and macOS. Moving to a + # newer one (new clippy lints included) is a change of its own. + - uses: dtolnay/rust-toolchain@1.97.0 + with: + components: rustfmt, clippy + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: src-tauri + + - name: Linux packages + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y pkg-config libwebkit2gtk-4.1-dev libgtk-3-dev \ + libayatana-appindicator3-dev librsvg2-dev libdbus-1-dev libasound2-dev \ + libxkbcommon-dev libxdo-dev libssl-dev + + # Fast checks first (formatting, types, lint), then tests and builds. + - run: npm ci + - name: Type check + run: npm run typecheck + - name: Lint + run: npm run lint + - name: Rust format + run: cargo fmt --manifest-path src-tauri/Cargo.toml --check + - name: Clippy + run: cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings + + - name: Frontend tests + run: npm test + - name: Frontend build + run: npm run build + - name: Rust tests + run: cargo test --manifest-path src-tauri/Cargo.toml --no-fail-fast diff --git a/VERIFICATION.md b/VERIFICATION.md new file mode 100644 index 0000000..b51a760 --- /dev/null +++ b/VERIFICATION.md @@ -0,0 +1,152 @@ +# macOS verification record + +Running record for the macOS phase described in [NEXT_PHASE.md](NEXT_PHASE.md) (section 8). Everything below was run and seen in this session unless it says **not run**. Branch `macos-verification`, started from `16d6b32`. + +## Machine + +| | | +| --- | --- | +| Hardware | MacBook Air `Mac14,2`, Apple M2 (arm64), 8 cores, 8 GB RAM | +| System | macOS 15.4.1 (24E263), Darwin 24.4.0 | +| Disk at start | 245 GB APFS container, **260 MB free** (99.9 % used). Freed by hand to 15 GB before anything was built. | + +## Toolchain + +| Tool | Version | Note | +| --- | --- | --- | +| Xcode Command Line Tools | 16.3 (`com.apple.pkg.CLTools_Executables` 16.3.0.0.1.1742442376), Apple clang 17.0.0, `xcode-select -p` = `/Library/Developer/CommandLineTools` | No full Xcode (`xcodebuild` unavailable). Tauri's prerequisites say the Command Line Tools are enough for a desktop app. | +| Rust used for this record | **1.97.0** (2d8144b78 2026-07-07), cargo 1.97.0, rustfmt 1.9.0, clippy 0.1.97 | Installed beside the machine's default with `rustup toolchain install 1.97.0 --profile minimal --component rustfmt,clippy`, and called as `cargo +1.97.0`: the same compiler as the Linux run, so a difference comes from the system and not from the compiler. | +| Machine's default Rust | 1.83.0 (2024-11-26), left as the default | Older than `rust-version = "1.95"` in `src-tauri/Cargo.toml`; cargo would refuse to build with it. | +| rustup | 1.27.1, updated itself to 1.29.1 during the install | rustup's default self-update. | +| Node / npm | 22.23.3 (nvm) / 10.9.9 | Meets "Node 20 or newer (22 was used)". | + +Build setting for this machine only, to fit the disk: Rust is compiled with `CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0` in the environment (no debug info, no incremental cache). Nothing in the repository changes; panics still report file and line. + +## Section 1: setup + +| Command | Result | +| --- | --- | +| `xcode-select -p`, `rustc --version`, `node --version` | See the table above. | +| `npm ci` | Ok: 261 packages in 6 s, 153 MB. `npm audit`: 2 moderate, both in `@vitest/mocker` under `vitest` (development only). Not changed. | +| `npm run typecheck` | Clean (2.9 s). | +| `npm run lint` | Clean (1.8 s). | +| `npm test` | **1 failed, 308 passed** (309 tests, 18 files). See below. | +| `npm run build` | Ok (5.4 s). Vite's usual warning that `index-*.js` is over 500 kB (509 kB). | + +### Failure 1: `src/features/feedback/rules.test.tsx`, "an event rule > builds the event pad: a scoped state, and an event that shows Error for 0.7 seconds, and saves what the runtime was tested with" + +``` +AssertionError: expected '' to be '0.2' // Object.is equality + ❯ src/features/feedback/rules.test.tsx:557:25 + 557| expect(seconds.min).toBe("0.2"); +``` + +Not predicted. It failed 5 times out of 5 (the full suite twice, the file alone three times), so it is not intermittent on this machine. + +Cause, from reading the code: the field's `min` and `max` come from the runtime's limits (`EventRules.tsx:206`, `limits ? limits.minHoldMs / 1000 : undefined`), which arrive in the answer to `review_feedback`. `useFeedbackReview` asks only after 150 ms without a change to the draft (`DEBOUNCE_MS`). The test asserts `min` right after its last `selectOptions`, without waiting, so it passes only if some earlier step left 150 ms of quiet for a review to land. The neighbouring test "holds for a time the runtime accepts: the limits come from Rust" checks the same attribute inside `waitFor`. Nothing here depends on macOS; it depends on how fast the steps run. As far as the code shows, the product is not at fault: the field gets its limits once the answer arrives. + +Fixed in the test only (commit `ae2dda4`): it now waits for the bound with `waitFor`, as its neighbour does. After the fix: the file alone 3 times out of 3, then `npm test` **309 passed, 0 failed**; typecheck and lint clean. + +## Section 2: first build + +All from `src-tauri/`, with `cargo +1.97.0` and the environment above. + +| Command | Result | +| --- | --- | +| `cargo check --all-targets` | **Ok on the first try: 0 errors, 0 warnings**, 1 min 46 s (315 crates, including the index download). | +| `cargo fmt --check` | Clean. | +| `cargo clippy --all-targets -- -D warnings` | **Clean.** Run twice: the second time after `touch src/lib.rs src/context/observer/macos.rs`, with `-v`, to be sure the crate was linted and not taken from `cargo check`'s cache: 32 `clippy-driver` runs, no warning. | + +`src/context/observer/macos.rs` went through the compiler with no change. Evidence that it was compiled and not skipped by a `cfg`: `objc2`, `block2` 0.6.2, `objc2-foundation` 0.3.2 and `objc2-app-kit` 0.3.2 were checked, and the library's metadata (`liblaunchdeck_lib-*.rmeta`) contains `MacObserver`. The vendored bindings match what the adapter assumed: `sharedWorkspace`, `notificationCenter`, `frontmostApplication`, `bundleIdentifier`, `localizedName` and `processIdentifier` are safe methods with no `MainThreadMarker`; `addObserverForName_object_queue_usingBlock` is `unsafe` and takes `&block2::DynBlock)>`, which `&RcBlock` dereferences to. Cargo features: none added. + +Also compiled for the first time on this system, with no error: `keyring` 4.2.0 (Keychain), `midir` 0.11.0 with `coremidi` 0.9.2, `enigo` 0.5.0. Compiled is not run: each of them is still to be seen working (section 4). + +Not seen: the warning about the bundle identifier ending in `.app` that NEXT_PHASE.md mentions. It did not appear in `cargo check` or `cargo clippy`; it is presumably printed by Tauri's CLI (`npm run tauri dev` / `build`), to be looked for in section 4. + +Read while checking, not changed: the adapter drops its observer token without `removeObserver`, so the block would outlive `run()`. The runtime (`core/runtime.rs`, around line 576) starts the observer once and never stops it, so the block and the thread live as long as the process and this has no effect today. + +`src-tauri/target` after `check` and `clippy`: 911 MB; 12 GB left on the disk. + +## Section 3: tests + +`cargo +1.97.0 test --no-fail-fast` (without `--no-fail-fast` cargo stops at the first failing test program and the list would be incomplete). 2 min 38 s including the build; `src-tauri/target` grew to 4.4 GB, 9.3 GB left on the disk. + +**704 passed, 5 failed, 2 ignored, in 22 targets** (the library, the binary, 19 test files, doc-tests). 711 tests: the Linux run had 714 (712 passed, 2 ignored). The 3 not built here are the unit tests of `context/observer/x11.rs`, a module compiled only on Unix other than macOS. The 2 ignored are the same as on Linux: the real credential store test (`secret_store`) and the timing benchmark (`state_characterization`). + +| Target | Result | +| --- | --- | +| `--lib` | 555 passed, **2 failed** | +| `--test context_contract` | 0 passed, **1 failed** | +| `--test context_engine` | 12 passed, **2 failed** | +| the other 19 targets | all passed | + +### The five failures, before anything was changed + +1. `surfaces::tests::contract_fixture_matches_the_default_workspace` (lib): `examples/default-workspace.json is stale`. Running `cargo run --example dump_workspace` into a scratch file (the fixture was not touched) and diffing it with the fixture shows exactly four pads differ: Development, Terminal (`x-terminal-emulator` → `Terminal`), VS Code (`code` → `Visual Studio Code`); Productivity, Files (`xdg-open .` → `Finder`), Screenshot (`shell` `gnome-screenshot --interactive` → `system.keyboardShortcut` `cmd+shift+4`). **Predicted.** +2. `persistence::tests::a_real_v3_workspace_migrates_to_exactly_what_ships_now` (lib): `surface 'development' differs after migration` (the assertion stops at the first surface that differs; Productivity differs too, per the diff above). **Predicted.** +3. `the_context_fixture_has_every_field_the_runtime_emits` (`tests/context_contract.rs`): `examples/context-status.json is out of date, missing ["auto.problems[].kind", "manual.problems[].kind"]`. On macOS every `x11` rule gets a problem `{ "kind": "otherSystem" }` where the fixture, made on Linux, has `null`. **Predicted.** +4. `rules_are_checked_reordered_and_flagged` (`tests/context_engine.rs`): `left: [Some(OtherSystem), Some(OtherSystem), Some(Shadowed { by: 0 }), Some(OtherSystem)]`, `right: [None, None, Some(Shadowed { by: 0 }), None]`. Same cause. **Predicted.** +5. `the_same_application_again_is_a_no_op` (`tests/context_engine.rs`): `assertion 'left == right' failed: nothing was activated, left: 2, right: 0`. **Not predicted, and intermittent**: 1 failure in 10 runs alone, 1 in 5 runs of its target, and the full run above. + + Cause, seen with a temporary `eprintln!` (reverted, never committed): in a failing run the events are the same as in a passing one, one `surface.changed` and one `page.changed`, both for `development`, which is the first activation. Only the baseline differs: 0 instead of 2. `until_shown` polls the runtime's state, which `activate` changes under its lock before it publishes `surface.changed` and `page.changed` on the bus, which delivers them to the interface on another task. The test took its baseline in between. The five repeated observations activated nothing (a second activation of the same surface would publish `page.changed` without `surface.changed`). The same window covers the test's other two counts (`ui::STATE`, `ui::CONTEXT`), which `activate` emits after publishing. Nothing about it is specific to macOS; whether it also happens on Linux could not be checked here. + +### Fixes, one commit each + +| Commit | Fixes | What changed | +| --- | --- | --- | +| `3002297` | failures 1 and 2 | The starter workspace's system is a parameter: `Platform { Linux, MacOs, Windows }`, `default_workspace_for(platform)`, `default_workspace()` passing `Platform::current()`. `demo_cmd` (a fifth `cfg!`, Windows only, not listed in NEXT_PHASE.md) takes it too, or the Windows runner would still differ from the Linux fixture. The two tests ask for Linux, as their files hold; `examples/dump_workspace.rs` writes the Linux workspace on every system (checked: on this Mac its output is byte for byte `examples/default-workspace.json`). New tests: on every system, the pads that differ per system and that nothing else differs. | +| `093e7c1` | failures 3 and 4 | `ForegroundObserver::namespace()`, by default the namespace of the system LaunchDeck was built for (right for the macOS, Windows and X11 observers and for `NoObserver`, so the product behaves as before everywhere); the scripted observer says `x11`; the engine keeps it next to the observer's status and `status()` uses it instead of `native_namespace()`. `macos.rs`, `windows.rs`, `x11.rs` and `identity.rs` unchanged. New test `a_rule_for_another_system_is_flagged_wherever_this_runs`. `dump_context` on this Mac now writes exactly `examples/context-status.json`. | +| `699abf3` | failure 5 | Test helper `until_heard(surface)`: waits until the last `page.changed` the interface received is for that surface and the last context it was sent is the runtime's current one (sent after the state). Used by the no-op test and by two tests with the same window that had not failed yet (`app_a_shows_surface_a_app_b_shows_surface_b_on_the_launchpad`, `the_interface_is_told_when_the_context_changes_and_only_then`). No sleep added. | + +No fixture under `examples/` was regenerated or changed. + +### After the fixes + +| Run | Result | +| --- | --- | +| `the_same_application_again_is_a_no_op` alone, 50 times | 50 passed (before: 1 failure in 10) | +| `cargo test --test context_engine`, 20 times | 20 × 15 passed (before: 1 failure in 5) | +| `cargo test --no-fail-fast`, 3 full runs | each **715 passed, 0 failed, 2 ignored** (711 before + 6 new tests), 102 s, 66 s, 66 s | +| `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` | clean after each commit | +| `npm test`, `typecheck`, `lint` | 309 passed; clean | + +`src-tauri/src/surfaces/mod.rs` grew from 905 to 1105 lines in `3002297`, mostly from the new per-system tests. + +### "Worth watching" in NEXT_PHASE.md + +| Item | Result | +| --- | --- | +| Tests that reach a local server through `localhost` | Pass: `localhost_is_resolved_and_reached_when_granted`, `a_grant_is_for_one_scheme_one_host_and_one_port`, `a_name_that_resolves_outside_its_reach_is_refused`, `bad_urls_wrong_schemes_and_other_ports_never_reach_a_server`. | +| Stopping a runaway plugin on Apple silicon | Pass: `an_endless_loop_runs_out_of_fuel_and_is_stopped`, `an_endless_loop_is_also_stopped_by_the_wall_clock`, `runaway_recursion_is_a_stack_overflow_trap`. | +| `#[cfg(unix)]` tests, first time on macOS | All 7 pass: `private_files_are_readable_by_the_owner_only`, `the_audit_log_is_readable_by_the_owner_only`, `symbolic_links_are_refused`, `shell_reports_output_and_failure`, `shell_runs_through_the_same_path`, `failing_command_ends_in_the_error_state`, `unbound_pad_goes_running_then_success_and_emits_action_events`. | + +## Section 5: continuous integration + +`.github/workflows/ci.yml` (commit `b0f13ba`), from the draft in NEXT_PHASE.md. Checked on 2026-10-05 with `gh api` against the actions' releases and `actions/runner-images`: + +| Draft | Now | Why | +| --- | --- | --- | +| `actions/checkout@v7`, `actions/setup-node@v7`, `Swatinem/rust-cache@v2` | unchanged | Current majors: v7.0.1, v7.0.0, v2.9.2. | +| `ubuntu-24.04`, `macos-latest`, `windows-latest` | unchanged | `ubuntu-latest` still means 24.04 and moves to 26.04 in November 2026 (runner-images #14748, open). `macos-latest` is macOS 26 on arm64 (#14167, closed). `windows-latest` is Windows Server 2025. | +| `dtolnay/rust-toolchain@stable` | `@1.97.0` | Stable is 1.99.0 (2026-09-28). 1.97.0 is what was verified on Linux and here; a newer clippy with `-D warnings` could fail for reasons unrelated to any system. Moving is a change of its own. | +| Linux packages | `pkg-config` and `libdbus-1-dev` added | `cargo tree --target x86_64-unknown-linux-gnu`: `libdbus-sys` (through `tauri` → `tao`) links D-Bus with pkg-config; it reached the container only as a dependency of the GTK packages. `alsa-sys` (`midir`) and `xkbcommon` (`enigo`) are covered by the draft's list. Nothing uses OpenSSL or libxdo; `libssl-dev` and `libxdo-dev` stay as Tauri's documented prerequisites. | +| `cargo test` | `cargo test --no-fail-fast` | Every failure is listed, not just those of the first failing program (Windows, section 5 item 2). | +| step order | fast checks (types, lint, fmt, clippy) first, then tests and builds | So that a later check (an architecture check, for example) has an obvious place. Rust does not need the built interface: `cargo clippy --all-targets` passed here with `dist/` moved away. | +| | `permissions: contents: read`, `concurrency` cancelling superseded runs, `CARGO_PROFILE_DEV_DEBUG: line-tables-only`, `core.autocrlf false` on Windows, 60 min timeout | No step needs a secret or a token. | + +Checked: the YAML parses, and `actionlint` 1.7.12 reports nothing. + +**Not run.** The workflow runs on a push to `main` or on a pull request; nothing has been pushed. + +Not done from section 5: the desktop suite job (Linux, on demand or nightly, item 3). + +## Predictions of NEXT_PHASE.md + +| Prediction | Status | +| --- | --- | +| Section 1: "expected: clean, 309 tests. Nothing here is known to depend on the system." | **Corrected.** Typecheck, lint and build are clean; one test of 309 fails, from a race between the test and a 150 ms debounce, not from the system. | +| Section 2: "If this fails, it is expected to fail in one place: `src/context/observer/macos.rs`", most likely for a missing Cargo feature, a block type, a `MainThreadMarker` or `unused_unsafe` | **Did not fail.** `macos.rs` compiled and passed clippy as written; none of the four expected kinds of error appeared. The feature list in `Cargo.toml` was already complete. | +| Section 2: Tauri warns that `dev.launchdeck.app` ends in `.app` | Not seen in `cargo check` or `clippy`; still to be looked for under Tauri's CLI. | +| Section 3: four tests fail on macOS, all from values recorded on Linux | **Confirmed**, all four, for the reasons given. | +| Section 3: "Anything else that fails is new information" | One more, intermittent: `the_same_application_again_is_a_no_op`, a race in the test's baseline, not a fault of the product and not specific to macOS. | +| Section 3: `localhost`, fuel and wall clock on Apple silicon, `#[cfg(unix)]` tests (no prediction / expected to pass) | All pass. | diff --git a/src-tauri/examples/dump_workspace.rs b/src-tauri/examples/dump_workspace.rs index fc2fe3c..80399a7 100644 --- a/src-tauri/examples/dump_workspace.rs +++ b/src-tauri/examples/dump_workspace.rs @@ -2,9 +2,14 @@ //! the contract fixture the TypeScript schemas are tested against. //! //! `cargo run --example dump_workspace > ../examples/default-workspace.json` +//! +//! The fixture is the Linux workspace on every system, so that refreshing it +//! on a Mac or on Windows writes the same file. + +use launchdeck_lib::surfaces::{default_workspace_for, Platform}; fn main() { - let ws = launchdeck_lib::surfaces::default_workspace(); + let ws = default_workspace_for(Platform::Linux); println!( "{}", serde_json::to_string_pretty(&ws).expect("serialise workspace") diff --git a/src-tauri/src/context/engine.rs b/src-tauri/src/context/engine.rs index e925ea1..ce6115a 100644 --- a/src-tauri/src/context/engine.rs +++ b/src-tauri/src/context/engine.rs @@ -113,6 +113,9 @@ pub struct Decision { #[derive(Debug)] pub struct Engine { observer: ObserverStatus, + /// The kind of identity the observer reports, so that a rule of another + /// kind, which can never match, is pointed out. + namespace: Option<&'static str>, /// The last thing the observer reported, whatever it was. observed: Option, /// An application that came to the front and has not stayed there long enough yet. @@ -126,9 +129,10 @@ pub struct Engine { } impl Engine { - pub fn new(observer: ObserverStatus, editing: bool) -> Engine { + pub fn new(observer: ObserverStatus, namespace: Option<&'static str>, editing: bool) -> Engine { Engine { observer, + namespace, observed: None, pending: None, accepted: None, @@ -147,6 +151,10 @@ impl Engine { self.observer = status; } + pub fn namespace(&self) -> Option<&'static str> { + self.namespace + } + /// What is in front now, as last reported. Not what rules are asked about. pub fn observed(&self) -> Option<&Seen> { self.observed.as_ref() @@ -371,7 +379,7 @@ mod tests { impl Deck { fn new(rules: Vec, fallback: Fallback) -> Deck { Deck { - engine: Engine::new(ObserverStatus::available("test"), false), + engine: Engine::new(ObserverStatus::available("test"), Some(X11), false), settings: ContextSettings { auto: true, rules, @@ -921,6 +929,7 @@ mod tests { let mut d = Deck::usual(); d.engine = Engine::new( ObserverStatus::unavailable("Wayland does not say which application is in front."), + None, false, ); assert_eq!(d.mode(), Mode::Unavailable); diff --git a/src-tauri/src/context/observer/mod.rs b/src-tauri/src/context/observer/mod.rs index 4b4dd9b..f444734 100644 --- a/src-tauri/src/context/observer/mod.rs +++ b/src-tauri/src/context/observer/mod.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use serde::Serialize; -use super::identity::ApplicationIdentity; +use super::identity::{native_namespace, ApplicationIdentity}; #[cfg(target_os = "macos")] mod macos; @@ -117,6 +117,13 @@ pub trait ForegroundObserver: Send { /// What it can do on this system, known before it runs. fn status(&self) -> ObserverStatus; + /// The kind of identity it reports (`macos`, `windows`, `x11`), so that a + /// rule written for another kind can be pointed out. An observer of the + /// system LaunchDeck was built for reports that system's kind. + fn namespace(&self) -> Option<&'static str> { + native_namespace() + } + /// Report the application in front now and every change after it, until /// `sink.stopped()`. Blocks: the runtime gives it a thread of its own. /// Never called when `status()` is unavailable. diff --git a/src-tauri/src/context/observer/scripted.rs b/src-tauri/src/context/observer/scripted.rs index 44a32ff..0c2555b 100644 --- a/src-tauri/src/context/observer/scripted.rs +++ b/src-tauri/src/context/observer/scripted.rs @@ -6,6 +6,7 @@ use std::sync::mpsc::{channel, Receiver, Sender}; use std::time::Duration; use super::{ForegroundObserver, ObserverStatus, Report, Sink}; +use crate::context::identity::X11; pub struct ScriptedObserver { status: ObserverStatus, @@ -40,6 +41,11 @@ impl ForegroundObserver for ScriptedObserver { self.status.clone() } + /// X11 identities, whatever system the tests run on. + fn namespace(&self) -> Option<&'static str> { + Some(X11) + } + fn run(self: Box, sink: Sink) { while !sink.stopped() { match self.reports.recv_timeout(Duration::from_millis(50)) { diff --git a/src-tauri/src/context/status.rs b/src-tauri/src/context/status.rs index af149b9..278d02d 100644 --- a/src-tauri/src/context/status.rs +++ b/src-tauri/src/context/status.rs @@ -6,7 +6,7 @@ use serde::Serialize; use super::engine::{Decision, Engine, Mode}; -use super::identity::{native_namespace, ApplicationIdentity}; +use super::identity::ApplicationIdentity; use super::observer::{ObserverStatus, Seen}; use super::rules::ContextSettings; use crate::core::model::Workspace; @@ -100,7 +100,7 @@ pub fn rule_problems( } pub fn status(engine: &Engine, settings: &ContextSettings, workspace: &Workspace) -> ContextStatus { - let namespace = native_namespace(); + let namespace = engine.namespace(); ContextStatus { settings: settings.clone(), observer: engine.observer().clone(), @@ -167,7 +167,7 @@ mod tests { fn the_status_says_what_is_in_front_without_keeping_any_of_it() { let ws = default_workspace(); let settings = ContextSettings::default(); - let mut engine = Engine::new(ObserverStatus::available("test"), false); + let mut engine = Engine::new(ObserverStatus::available("test"), Some(X11), false); assert_eq!( status(&engine, &settings, &ws).foreground, Foreground::Unknown diff --git a/src-tauri/src/core/runtime.rs b/src-tauri/src/core/runtime.rs index dcc0f60..e179eef 100644 --- a/src-tauri/src/core/runtime.rs +++ b/src-tauri/src/core/runtime.rs @@ -538,7 +538,7 @@ impl Runtime { recent: VecDeque::new(), external, pending: BTreeMap::new(), - context: Engine::new(observing.clone(), false), + context: Engine::new(observing.clone(), observer.namespace(), false), }), bus: bus.clone(), engine, diff --git a/src-tauri/src/persistence/mod.rs b/src-tauri/src/persistence/mod.rs index 48ac3f6..9c82da0 100644 --- a/src-tauri/src/persistence/mod.rs +++ b/src-tauri/src/persistence/mod.rs @@ -173,7 +173,7 @@ fn write_file(path: &Path, bytes: &[u8], private: bool) -> std::io::Result<()> { #[cfg(test)] mod tests { use super::*; - use crate::surfaces::default_workspace; + use crate::surfaces::{default_workspace, default_workspace_for, Platform}; #[test] fn workspace_roundtrips_through_disk() { @@ -361,14 +361,15 @@ mod tests { /// The strongest check of the conversion: the schema 3 workspace the last /// release shipped, migrated by the rules in [`bindings`], is the same - /// workspace the code builds by hand today, control by control. + /// workspace the code builds by hand today, control by control. The file + /// was saved on Linux, so it is compared with the Linux starter pads. #[test] fn a_real_v3_workspace_migrates_to_exactly_what_ships_now() { let old: Value = serde_json::from_str(V3_FIXTURE).unwrap(); assert_eq!(old["schemaVersion"], 3); let ws = migrate(old).unwrap(); assert_eq!(ws.schema_version, SCHEMA_VERSION); - let shipped = default_workspace(); + let shipped = default_workspace_for(Platform::Linux); assert_eq!(ws.surfaces.len(), shipped.surfaces.len()); for (a, b) in ws.surfaces.iter().zip(&shipped.surfaces) { assert_eq!(a, b, "surface `{}` differs after migration", b.id); diff --git a/src-tauri/src/surfaces/mod.rs b/src-tauri/src/surfaces/mod.rs index bd402d0..b418638 100644 --- a/src-tauri/src/surfaces/mod.rs +++ b/src-tauri/src/surfaces/mod.rs @@ -9,6 +9,30 @@ use crate::core::model::*; pub mod agent_control; +/// The system a starter workspace is built for. A few starter pads differ by +/// system (the terminal, the editor, the file manager, the screenshot, and how +/// a demo command waits); everything else is the same everywhere. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Platform { + /// Linux, and any other system that is neither macOS nor Windows. + Linux, + MacOs, + Windows, +} + +impl Platform { + /// The system this was built for. + pub fn current() -> Platform { + if cfg!(target_os = "macos") { + Platform::MacOs + } else if cfg!(windows) { + Platform::Windows + } else { + Platform::Linux + } + } +} + // Palette used by the starter surfaces (kept readable on RGB LEDs). const BLUE: Rgb = Rgb::new(40, 110, 255); const GREEN: Rgb = Rgb::new(30, 220, 90); @@ -76,12 +100,11 @@ fn open_page(id: &str) -> Assignment { plugin("navigation", "openPage", json!({ "pageId": id })) } -/// Cross-platform harmless command that takes `secs` seconds then prints `msg`. -fn demo_cmd(secs: u32, msg: &str) -> Assignment { - let command = if cfg!(windows) { - format!("ping -n {} 127.0.0.1 >nul & echo {msg}", secs + 1) - } else { - format!("sleep {secs} && echo '{msg}'") +/// Harmless command that takes `secs` seconds then prints `msg`. +fn demo_cmd(platform: Platform, secs: u32, msg: &str) -> Assignment { + let command = match platform { + Platform::Windows => format!("ping -n {} 127.0.0.1 >nul & echo {msg}", secs + 1), + Platform::Linux | Platform::MacOs => format!("sleep {secs} && echo '{msg}'"), }; shell(&command) } @@ -161,7 +184,7 @@ fn dev_pad( c } -fn development() -> Surface { +fn development(platform: Platform) -> Surface { let mut home = vec![ dev_pad( g(0, 0), @@ -170,12 +193,10 @@ fn development() -> Surface { CYAN, "Launch a terminal (placeholder command).", launch( - if cfg!(target_os = "macos") { - "Terminal" - } else if cfg!(windows) { - "wt" - } else { - "x-terminal-emulator" + match platform { + Platform::Linux => "x-terminal-emulator", + Platform::MacOs => "Terminal", + Platform::Windows => "wt", }, &[], ), @@ -187,10 +208,9 @@ fn development() -> Surface { BLUE, "Launch VS Code (`code` must be on your PATH, or the app name on macOS).", launch( - if cfg!(target_os = "macos") { - "Visual Studio Code" - } else { - "code" + match platform { + Platform::MacOs => "Visual Studio Code", + Platform::Linux | Platform::Windows => "code", }, &[], ), @@ -209,7 +229,7 @@ fn development() -> Surface { "▣", CYAN, "Placeholder: harmless echo. Replace with `docker compose up`.", - demo_cmd(1, "docker: demo only"), + demo_cmd(platform, 1, "docker: demo only"), ), dev_pad( g(0, 1), @@ -217,7 +237,7 @@ fn development() -> Surface { "✓", YELLOW, "Safe demo: sleeps 2s then succeeds. Pad pulses yellow, then turns green.", - demo_cmd(2, "tests passed"), + demo_cmd(platform, 2, "tests passed"), ), dev_pad( g(1, 1), @@ -225,7 +245,7 @@ fn development() -> Surface { "⚒", ORANGE, "Safe demo: sleeps 3s then succeeds.", - demo_cmd(3, "build ok"), + demo_cmd(platform, 3, "build ok"), ), dev_pad( g(2, 1), @@ -233,7 +253,7 @@ fn development() -> Surface { "⚡", GREEN, "Safe demo: sleeps 1s then succeeds.", - demo_cmd(1, "dev server: demo only"), + demo_cmd(platform, 1, "dev server: demo only"), ), dev_pad( g(3, 1), @@ -241,7 +261,7 @@ fn development() -> Surface { "⇪", RED, "Safe demo: sleeps 2s then succeeds. Replace with your deploy script.", - demo_cmd(2, "deploy: demo only"), + demo_cmd(platform, 2, "deploy: demo only"), ), { let mut c = ctl(g(0, 2), "Git", "⑂", PINK, open_page("git")); @@ -266,7 +286,7 @@ fn development() -> Surface { "≡", CYAN, "Safe demo: prints a message.", - demo_cmd(1, "git status: demo only"), + demo_cmd(platform, 1, "git status: demo only"), ), dev_pad( g(1, 0), @@ -274,7 +294,7 @@ fn development() -> Surface { "●", GREEN, "Safe demo. Replace with your commit script.", - demo_cmd(1, "git commit: demo only"), + demo_cmd(platform, 1, "git commit: demo only"), ), dev_pad( g(2, 0), @@ -282,7 +302,7 @@ fn development() -> Surface { "↓", BLUE, "Safe demo. Replace with `git pull`.", - demo_cmd(1, "git pull: demo only"), + demo_cmd(platform, 1, "git pull: demo only"), ), dev_pad( g(3, 0), @@ -290,7 +310,7 @@ fn development() -> Surface { "↑", ORANGE, "Safe demo. Replace with `git push`.", - demo_cmd(1, "git push: demo only"), + demo_cmd(platform, 1, "git push: demo only"), ), back_control(g(0, 7), "home"), ]; @@ -326,20 +346,16 @@ fn development() -> Surface { // Productivity // --------------------------------------------------------------------------- -fn productivity() -> Surface { - let files_app = if cfg!(target_os = "macos") { - launch("Finder", &[]) - } else if cfg!(windows) { - launch("explorer", &[]) - } else { - launch("xdg-open", &["."]) +fn productivity(platform: Platform) -> Surface { + let files_app = match platform { + Platform::Linux => launch("xdg-open", &["."]), + Platform::MacOs => launch("Finder", &[]), + Platform::Windows => launch("explorer", &[]), }; - let screenshot = if cfg!(target_os = "macos") { - shortcut(&["cmd", "shift", "4"]) - } else if cfg!(windows) { - shortcut(&["win", "shift", "s"]) - } else { - shell("gnome-screenshot --interactive") + let screenshot = match platform { + Platform::Linux => shell("gnome-screenshot --interactive"), + Platform::MacOs => shortcut(&["cmd", "shift", "4"]), + Platform::Windows => shortcut(&["win", "shift", "s"]), }; let mut controls = vec![ tool_pad( @@ -436,7 +452,7 @@ fn productivity() -> Surface { "☾", GRAY, "Placeholder: wire this to your OS focus mode with a shell command.", - demo_cmd(1, "dnd: demo only"), + demo_cmd(platform, 1, "dnd: demo only"), ), ]; controls.extend(surface_switchers("productivity")); @@ -690,20 +706,27 @@ fn accessibility() -> Surface { // --------------------------------------------------------------------------- -pub fn starter_surfaces() -> Vec { +pub fn starter_surfaces(platform: Platform) -> Vec { vec![ agent_control::agent_control(), - development(), - productivity(), + development(platform), + productivity(platform), smart_home(), accessibility(), ] } +/// The workspace a new installation on this system starts with. pub fn default_workspace() -> Workspace { + default_workspace_for(Platform::current()) +} + +/// The workspace a new installation on `platform` starts with. Tests that +/// compare with a file recorded on one system ask for that system. +pub fn default_workspace_for(platform: Platform) -> Workspace { Workspace { schema_version: SCHEMA_VERSION, - surfaces: starter_surfaces(), + surfaces: starter_surfaces(platform), last_active_surface: Some(agent_control::SURFACE_ID.into()), preferences: Preferences::default(), context: Default::default(), @@ -784,9 +807,11 @@ mod tests { assert_eq!(ws.schema_version, SCHEMA_VERSION); } + const SYSTEMS: [Platform; 3] = [Platform::Linux, Platform::MacOs, Platform::Windows]; + #[test] fn every_page_is_well_formed() { - for s in starter_surfaces() { + for s in SYSTEMS.into_iter().flat_map(starter_surfaces) { assert!(!s.pages.is_empty(), "{} has no pages", s.id); for p in &s.pages { let mut seen_cells = HashSet::new(); @@ -890,7 +915,8 @@ mod tests { } /// `examples/default-workspace.json` is the contract fixture the TypeScript - /// schemas are tested against. Refresh it with: + /// schemas are tested against. It is the Linux workspace, whichever system + /// runs this. Refresh it with: /// `cargo run --example dump_workspace > ../examples/default-workspace.json` #[test] fn contract_fixture_matches_the_default_workspace() { @@ -898,8 +924,182 @@ mod tests { serde_json::from_str(include_str!("../../../examples/default-workspace.json")).unwrap(); assert_eq!( fixture, - serde_json::to_value(default_workspace()).unwrap(), + serde_json::to_value(default_workspace_for(Platform::Linux)).unwrap(), "examples/default-workspace.json is stale; regenerate it with the dump_workspace example" ); } + + /// `surface/page/label` of every control that is not the same in both. + fn differing_pads(a: &Workspace, b: &Workspace) -> Vec { + assert_eq!(a.surfaces.len(), b.surfaces.len()); + let mut differ = Vec::new(); + for (sa, sb) in a.surfaces.iter().zip(&b.surfaces) { + assert_eq!(sa.pages.len(), sb.pages.len(), "{}", sa.id); + for (pa, pb) in sa.pages.iter().zip(&sb.pages) { + assert_eq!(pa.controls.len(), pb.controls.len(), "{}/{}", sa.id, pa.id); + for (ca, cb) in pa.controls.iter().zip(&pb.controls) { + if ca != cb { + differ.push(format!("{}/{}/{}", sa.id, pa.id, ca.label)); + } + } + } + } + differ + } + + /// What pressing a starter pad does: `provider.action` and its settings. + fn press( + ws: &Workspace, + surface: &str, + page: &str, + label: &str, + ) -> (String, serde_json::Value) { + let control = ws + .surface(surface) + .and_then(|s| s.page(page)) + .and_then(|p| p.controls.iter().find(|c| c.label == label)) + .unwrap_or_else(|| panic!("no pad {surface}/{page}/{label}")); + let a = control.press.as_ref().unwrap(); + (format!("{}.{}", a.provider, a.action), a.args.clone()) + } + + #[test] + fn the_systems_differ_only_in_the_pads_that_must() { + let linux = default_workspace_for(Platform::Linux); + assert_eq!( + differing_pads(&linux, &default_workspace_for(Platform::MacOs)), + [ + "development/home/Terminal", + "development/home/VS Code", + "productivity/home/Files", + "productivity/home/Screenshot", + ] + ); + // On Windows the demo commands wait with `ping` instead of `sleep`. + assert_eq!( + differing_pads(&linux, &default_workspace_for(Platform::Windows)), + [ + "development/home/Terminal", + "development/home/Docker", + "development/home/Tests", + "development/home/Build", + "development/home/Dev Server", + "development/home/Deploy", + "development/git/Git Status", + "development/git/Commit", + "development/git/Pull", + "development/git/Push", + "productivity/home/Files", + "productivity/home/Screenshot", + "productivity/home/Do Not Disturb", + ] + ); + } + + #[test] + fn on_linux_the_starter_pads_use_common_desktop_commands() { + let ws = default_workspace_for(Platform::Linux); + let app = |name: &str| { + ( + "system.launchApplication".to_string(), + json!({ "app": name }), + ) + }; + assert_eq!( + press(&ws, "development", "home", "Terminal"), + app("x-terminal-emulator") + ); + assert_eq!(press(&ws, "development", "home", "VS Code"), app("code")); + assert_eq!( + press(&ws, "productivity", "home", "Files"), + ( + "system.launchApplication".into(), + json!({ "app": "xdg-open", "args": "." }) + ) + ); + assert_eq!( + press(&ws, "productivity", "home", "Screenshot"), + ( + "shell.execute".into(), + json!({ "command": "gnome-screenshot --interactive" }) + ) + ); + assert_eq!( + press(&ws, "development", "home", "Tests"), + ( + "shell.execute".into(), + json!({ "command": "sleep 2 && echo 'tests passed'" }) + ) + ); + } + + #[test] + fn on_macos_the_starter_pads_name_applications_and_use_cmd() { + let ws = default_workspace_for(Platform::MacOs); + let app = |name: &str| { + ( + "system.launchApplication".to_string(), + json!({ "app": name }), + ) + }; + assert_eq!( + press(&ws, "development", "home", "Terminal"), + app("Terminal") + ); + assert_eq!( + press(&ws, "development", "home", "VS Code"), + app("Visual Studio Code") + ); + assert_eq!(press(&ws, "productivity", "home", "Files"), app("Finder")); + assert_eq!( + press(&ws, "productivity", "home", "Screenshot"), + ( + "system.keyboardShortcut".into(), + json!({ "keys": "cmd+shift+4" }) + ) + ); + assert_eq!( + press(&ws, "development", "home", "Tests"), + ( + "shell.execute".into(), + json!({ "command": "sleep 2 && echo 'tests passed'" }) + ) + ); + } + + #[test] + fn on_windows_the_starter_pads_use_windows_programs_and_ping_to_wait() { + let ws = default_workspace_for(Platform::Windows); + let app = |name: &str| { + ( + "system.launchApplication".to_string(), + json!({ "app": name }), + ) + }; + assert_eq!(press(&ws, "development", "home", "Terminal"), app("wt")); + assert_eq!(press(&ws, "development", "home", "VS Code"), app("code")); + assert_eq!(press(&ws, "productivity", "home", "Files"), app("explorer")); + assert_eq!( + press(&ws, "productivity", "home", "Screenshot"), + ( + "system.keyboardShortcut".into(), + json!({ "keys": "win+shift+s" }) + ) + ); + assert_eq!( + press(&ws, "development", "home", "Tests"), + ( + "shell.execute".into(), + json!({ "command": "ping -n 3 127.0.0.1 >nul & echo tests passed" }) + ) + ); + } + + #[test] + fn the_default_workspace_is_the_one_for_this_system() { + assert_eq!( + default_workspace(), + default_workspace_for(Platform::current()) + ); + } } diff --git a/src-tauri/tests/context_engine.rs b/src-tauri/tests/context_engine.rs index e5576a1..29ca205 100644 --- a/src-tauri/tests/context_engine.rs +++ b/src-tauri/tests/context_engine.rs @@ -17,7 +17,7 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use launchdeck_lib::context::engine::{Held, Mode as ContextMode, Outcome}; -use launchdeck_lib::context::identity::X11; +use launchdeck_lib::context::identity::{MACOS, WINDOWS, X11}; use launchdeck_lib::context::observer::scripted::{Script, ScriptedObserver}; use launchdeck_lib::context::status::{Foreground, RuleProblem}; use launchdeck_lib::context::{ @@ -226,6 +226,28 @@ impl Desk { }) .await; } + + /// Until the interface has been told everything about `surface` coming on + /// screen. The runtime's state changes first; then `surface.changed` and + /// `page.changed` go out on the bus, which delivers them on another task, + /// and the state and the context are sent, the context last. Count what + /// the interface heard only after this, or an activation still on its way + /// is counted as something that happened later. + async fn until_heard(&self, surface: &str) { + let (rt, rec) = (self.rt.clone(), self.rec.clone()); + wait_until( + &format!("the interface to hear that {surface} is shown"), + || { + let paged = rec + .runtime_events("page.changed") + .last() + .is_some_and(|p| p["surfaceId"] == surface); + let context = serde_json::to_value(rt.context()).unwrap(); + paged && rec.last(ui::CONTEXT).as_ref() == Some(&context) + }, + ) + .await; + } } /// What the virtual Launchpad shows for a surface, taken by opening it by hand. @@ -267,6 +289,7 @@ async fn app_a_shows_surface_a_app_b_shows_surface_b_on_the_launchpad() { }) .unwrap(); assert_eq!(d.mode(), ContextMode::Auto); + d.until_heard("agent-control").await; let changes_before = d.rec.runtime_events("surface.changed").len(); d.front(CODE).await; @@ -283,6 +306,7 @@ async fn app_a_shows_surface_a_app_b_shows_surface_b_on_the_launchpad() { rt.virtual_handle().frame() == productivity }) .await; + d.until_heard("productivity").await; // It went through the ordinary activation: the same events, the hub, the saved choice. let changes = d.rec.runtime_events("surface.changed"); @@ -346,6 +370,7 @@ async fn the_same_application_again_is_a_no_op() { let d = desk().await; d.front(CODE).await; d.until_shown("development").await; + d.until_heard("development").await; let (events, states, contexts) = ( d.rec.runtime_events("surface.changed").len() + d.rec.runtime_events("page.changed").len(), d.rec.count(ui::STATE), @@ -686,6 +711,36 @@ async fn rules_are_checked_reordered_and_flagged() { assert_eq!(d.page(), "git"); } +/// The observer says which kind of identity it reports, so a rule written on +/// another system is pointed out the same way wherever this runs. The scripted +/// observer reports X11 identities, on a Mac as on Linux. +#[tokio::test(flavor = "multi_thread")] +async fn a_rule_for_another_system_is_flagged_wherever_this_runs() { + let d = desk().await; + let mut settings = d.rt.context().settings; + settings.rules.push(ContextRule { + application: ApplicationIdentity::new(MACOS, "com.apple.Terminal", "Terminal"), + surface_id: "productivity".into(), + page_id: None, + }); + settings.rules.push(ContextRule { + application: ApplicationIdentity::new(WINDOWS, "WindowsTerminal.exe", "Terminal"), + surface_id: "productivity".into(), + page_id: None, + }); + let status = d.rt.update_context(settings).unwrap(); + assert_eq!(status.namespace, Some(X11)); + assert_eq!( + status.problems, + vec![ + None, + None, + Some(RuleProblem::OtherSystem), + Some(RuleProblem::OtherSystem) + ] + ); +} + // --------------------------------------------------------------------------- // What is kept, and what is not // --------------------------------------------------------------------------- @@ -822,6 +877,7 @@ async fn the_interface_is_told_when_the_context_changes_and_only_then() { let before = d.rec.count(ui::CONTEXT); d.front(CODE).await; d.until_shown("development").await; + d.until_heard("development").await; assert!(d.rec.count(ui::CONTEXT) > before); let last = d.rec.last(ui::CONTEXT).unwrap(); assert_eq!(last["mode"], "auto"); diff --git a/src/features/feedback/rules.test.tsx b/src/features/feedback/rules.test.tsx index 8f26ca3..7552add 100644 --- a/src/features/feedback/rules.test.tsx +++ b/src/features/feedback/rules.test.tsx @@ -552,9 +552,13 @@ describe("an event rule", () => { await user.selectOptions(select(ev, "Event rule 1: add a condition"), "Level"); await user.selectOptions(select(ev, "Event rule 1 condition: Level"), "High"); expect(select(ev, "Event rule 1 duration").value).toBe("for"); - const seconds = within(ev).getByRole("spinbutton", { name: "Event rule 1 seconds" }) as HTMLInputElement; + // The bounds are the runtime's limits, which arrive with its review once the draft has been still for a moment. + const seconds = await waitFor(() => { + const el = within(ev).getByRole("spinbutton", { name: "Event rule 1 seconds" }) as HTMLInputElement; + expect(el.min).toBe("0.2"); + return el; + }); expect(seconds.value).toBe("3"); - expect(seconds.min).toBe("0.2"); expect(seconds.max).toBe("60"); await user.clear(seconds); await user.type(seconds, "0.7");