diff --git a/.env.example b/.env.example index edc02e8..26b2738 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,14 @@ # Fleetify local dev secrets. Copy to `.env` (gitignored) and fill in. # -# `dotenvy` loads this into the backend's process env at the top of -# `serve_with_routing_setup` so the Rust side picks it up via -# `std::env::var`. Vite reads `.env`/`.env.local` natively for the -# renderer. Existing shell env wins — set values here are a fallback. +# Only debug builds read `.env` at runtime. In a debug build +# (`npm run dev:tauri`), `dotenvy` loads it into the backend's process env +# at the top of `serve_with_routing_setup` so the Rust side picks it up via +# `std::env::var`. Release builds never read it: a project's `.env` in the +# directory Fleetify is launched from must not configure the app. Existing +# shell env wins — set values here are a fallback. +# +# Vite reads `.env`/`.env.local` natively for the renderer: the dev server +# exposes the `VITE_*` values, and `vite build` inlines them into the bundle. # PostHog product analytics. Both halves should match so backend + frontend # events flow into the same PostHog project. Keys are `phc_*` public keys @@ -17,7 +22,8 @@ VITE_POSTHOG_HOST=https://us.i.posthog.com # Not Diamond — Fleet-owned routing key for the "Auto" model picker. Read at # runtime by the backend (std::env::var). Fleet's own key, independent of any # Not Diamond a user connects in Settings → Routers. Unset ⇒ Auto falls back to -# the offline built-in router. +# the offline built-in router. Development only: never set it in CI or in +# release builds. NOTDIAMOND_API_KEY= # Model catalog API — the published provider/model catalog the picker fetches at diff --git a/.gitignore b/.gitignore index ea2c30d..9ae909f 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,8 @@ fleet.db-wal fleet.db-shm *.premerge-bak src-tauri/gen +# tauri-build rewrites these on every build, from src-tauri/src/app_commands.rs. +src-tauri/permissions/autogenerated src-tauri/binaries .env .env.* diff --git a/CLAUDE.md b/CLAUDE.md index 5f08b7d..094b5c9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -241,22 +241,23 @@ Pre-1.0 this still triggers only a minor bump (we're 0.x — semver lets us brea ## Telemetry & analytics -Fleetify ships two independent telemetry channels. Both default to user -choice; neither leaks prompt content, API keys, or file paths. +Fleetify ships two independent telemetry channels. Dashboard sync is on by +default and can be turned off in Settings → Privacy; product analytics is +off until the user turns it on. `docs/ANALYTICS.md` lists what each one +sends. | Channel | Vendor | Default | Toggle | Outbox | |---|---|---|---|---| -| Anonymous usage analytics | Fleetify cloud (`fleetify.dev`, WebSocket) | **ON** | Settings → Privacy → "Anonymous usage analytics" | `~/.fleetify/telemetry-outbox.sqlite` | -| Crash reports | Fleetify cloud | **ON** | Settings → Privacy → "Crash reports" | (same outbox) | -| Product analytics | PostHog Cloud (US, HTTP `/batch`) | **OFF** | Settings → Privacy → "Product analytics (PostHog)" | `~/.fleetify/posthog-outbox.sqlite` | +| Dashboard sync | Fleetify cloud (`fleetify.dev`, WebSocket) | **ON** | Settings → Privacy → "Dashboard sync" | `~/.fleetify/telemetry-outbox.sqlite` | +| Product analytics | PostHog Cloud (US, HTTP `/batch`) | **OFF** | Settings → Privacy → "Product analytics" | `~/.fleetify/posthog-outbox.sqlite` | ### PostHog integration - **Code:** backend module at `crates/fleetify-backend/src/services/telemetry/posthog/`; frontend wrapper at `src/lib/posthog.ts`. - **Fan-out:** the existing `services/telemetry/emitters.rs::enqueue_payload` writes to both the Fleetify cloud outbox AND the PostHog outbox (the latter via `posthog::enqueue_if_enabled`, gated on a runtime `AtomicBool`). -- **distinct_id:** the persisted `device_id` from `device.json` is reused on both sides. Frontend `posthog.identify(user_id)` after OAuth merges the anonymous person into the authenticated one via `$anon_distinct_id`. +- **distinct_id:** the persisted `device_id` from `device.json` is reused on both sides. Frontend `posthog.identify(user_id)` runs at sign-in, at each launch while signed in, and at opt-in, and only while product analytics is on; it merges the anonymous person into the authenticated one via `$anon_distinct_id`, with the id only (`before_send` strips `$set` / `$set_once`). - **Env keys:** `POSTHOG_API_KEY` (Rust, runtime `std::env::var`) and `VITE_POSTHOG_KEY` (Vite, `import.meta.env`). Unset → backend `init` short-circuits and the renderer wrapper no-ops. `POSTHOG_HOST` / `VITE_POSTHOG_HOST` default to `https://us.i.posthog.com`. -- **Runtime gate:** `telemetry_set_posthog_enabled` Tauri command persists the flag in `fleet.config.json::telemetry.posthog_enabled` AND flips the backend's `ENABLED` atomic live. Live opt-out stops new sends within ~10 s; renderer's `optOut()` stops autocapture immediately. +- **Runtime gate:** `telemetry_set_posthog_enabled` Tauri command persists the flag in `fleet.config.json::telemetry.posthog_enabled` AND flips the backend's `ENABLED` atomic live. Live opt-out stops new sends within ~10 s; the renderer's `optOut()` opts posthog-js out at once and drops every request it would still make, queued events and retries included. ### Local dev diff --git a/Cargo.lock b/Cargo.lock index ab4ce39..eb29c2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -120,6 +131,106 @@ dependencies = [ "serde_json", ] +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.4", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.4", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.4", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -142,6 +253,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + [[package]] name = "async-trait" version = "0.1.89" @@ -346,6 +463,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -355,6 +481,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "brotli" version = "8.0.2" @@ -381,6 +520,7 @@ name = "browser-mcp" version = "0.1.0" dependencies = [ "anyhow", + "fleetify-core", "reqwest 0.12.28", "serde", "serde_json", @@ -496,6 +636,15 @@ dependencies = [ "toml 0.9.12+spec-1.1.0", ] +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.62" @@ -647,6 +796,16 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clang-sys" version = "1.8.1" @@ -973,6 +1132,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "aes", + "block-padding", + "cbc", + "dbus", + "fastrand", + "hkdf", + "num", + "once_cell", + "sha2", + "zeroize", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -1082,6 +1259,7 @@ name = "dispatch-mcp" version = "0.1.0" dependencies = [ "anyhow", + "fleetify-core", "reqwest 0.12.28", "serde", "serde_json", @@ -1241,6 +1419,33 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1296,6 +1501,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.4.1" @@ -1368,6 +1583,7 @@ dependencies = [ name = "fleet-wipe" version = "0.1.0" dependencies = [ + "dbus-secret-service", "keyring", "linux-keyutils", ] @@ -1381,14 +1597,12 @@ dependencies = [ "base64 0.22.1", "chrono", "cpal", - "dotenvy", "fleetify-backend", "fleetify-core", "hound", "keyring", "notify", "notify-debouncer-mini", - "open", "portable-pty 0.9.0", "rand 0.8.6", "reqwest 0.12.28", @@ -1399,6 +1613,7 @@ dependencies = [ "tauri-build", "tauri-plugin-dialog", "tauri-plugin-macos-fps", + "tauri-runtime-wry", "tempfile", "tiny_http", "tokio", @@ -1429,6 +1644,7 @@ dependencies = [ "futures-util", "glob", "http", + "is-wsl", "jsonwebtoken", "keyring", "open", @@ -1450,6 +1666,8 @@ dependencies = [ "tower", "tower-http", "tracing", + "tracing-subscriber", + "url", "uuid", "walkdir", "which 6.0.3", @@ -1461,8 +1679,9 @@ dependencies = [ name = "fleetify-core" version = "0.1.0" dependencies = [ - "serde", + "reqwest 0.12.28", "thiserror 2.0.18", + "tokio", ] [[package]] @@ -1604,6 +1823,19 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.32" @@ -2413,6 +2645,16 @@ dependencies = [ "libc", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + [[package]] name = "ioctl-rs" version = "0.1.6" @@ -2606,8 +2848,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" dependencies = [ "byteorder", + "dbus-secret-service", "linux-keyutils", "log", + "secret-service", "security-framework 2.11.1", "security-framework 3.7.0", "windows-sys 0.60.2", @@ -2860,6 +3104,7 @@ name = "memory-mcp" version = "0.1.0" dependencies = [ "anyhow", + "fleetify-core", "reqwest 0.12.28", "serde", "serde_json", @@ -3037,6 +3282,19 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.11.1", + "cfg-if", + "cfg_aliases 0.2.1", + "libc", + "memoffset 0.9.1", +] + [[package]] name = "nom" version = "7.1.3" @@ -3086,6 +3344,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -3112,6 +3384,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -3149,6 +3430,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3423,6 +3715,7 @@ version = "5.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fbaa89d2ddc8473c78a3adf69eea8cffa28c483b8e02a971ef31527cd0fc92c" dependencies = [ + "dunce", "is-wsl", "libc", "pathdiff", @@ -3434,6 +3727,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "pango" version = "0.18.3" @@ -3584,6 +3887,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkcs1" version = "0.7.5" @@ -3656,6 +3970,20 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + [[package]] name = "portable-pty" version = "0.8.1" @@ -4340,6 +4668,25 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes", + "cbc", + "futures-util", + "generic-array", + "hkdf", + "num", + "once_cell", + "rand 0.8.6", + "serde", + "sha2", + "zbus", +] + [[package]] name = "security-framework" version = "2.11.1" @@ -5026,6 +5373,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "string_cache" version = "0.9.0" @@ -6094,6 +6447,17 @@ version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset 0.9.1", + "tempfile", + "windows-sys 0.60.2", +] + [[package]] name = "unic-char-property" version = "0.9.0" @@ -7436,6 +7800,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "yoke" version = "0.8.2" @@ -7459,6 +7833,62 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-process", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix 0.29.0", + "ordered-stream", + "rand 0.8.6", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -7505,6 +7935,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" @@ -7588,3 +8032,40 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ "zune-core", ] + +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] diff --git a/Cargo.toml b/Cargo.toml index 4408916..432033a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ members = [ [workspace.package] version = "0.1.0" edition = "2021" -license = "MIT" +license = "Apache-2.0" [workspace.dependencies] fleetify-core = { path = "crates/fleetify-core" } @@ -65,13 +65,14 @@ incremental = true # unaffected (it strips symbols). debug = "line-tables-only" -# Vendored fork of tauri-runtime-wry 2.11.2 with a single one-line change so the -# Linux embedded browser (right-panel webview) can be positioned instead of -# stacking full-width at the bottom of the window. This is a verbatim copy of -# the published crate plus the documented delta in -# vendor/tauri-runtime-wry/FLEETIFY_PATCH.md. Upstream bug: tauri-apps/tauri -# #13071 / #10420. Remove this patch (and the vendor/ dir) once upstream ships -# positioned child webviews on Linux. The version must stay equal to the -# tauri-runtime-wry that `tauri` pulls in, or Cargo will ignore the patch. +# Vendored fork of tauri-runtime-wry 2.11.2 with two changes, documented in +# vendor/tauri-runtime-wry/FLEETIFY_PATCH.md: the Linux embedded browser +# (right-panel webview) can be positioned instead of stacking full-width at the +# bottom of the window (upstream bug: tauri-apps/tauri #13071 / #10420), and on +# WebKitGTK a frame inside the app can't use the app page's IPC permissions +# through postMessage. Everything else is a verbatim copy of the published +# crate. Remove this patch (and the vendor/ dir) once upstream fixes both. The +# version must stay equal to the tauri-runtime-wry that `tauri` pulls in, or +# Cargo will ignore the patch. [patch.crates-io] tauri-runtime-wry = { path = "vendor/tauri-runtime-wry" } diff --git a/LICENSE b/LICENSE index 1b98f83..d645695 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,202 @@ -MIT License - -Copyright (c) 2026 Fleetify - -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. + + 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. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..1607843 --- /dev/null +++ b/NOTICE @@ -0,0 +1,14 @@ +Fleetify +Copyright 2026 The Fleetify Authors + +This product includes software developed by The Fleetify Authors +(https://github.com/fleetifydev/fleetify). + +This product includes a modified copy of tauri-runtime-wry +(https://github.com/tauri-apps/tauri), licensed under Apache-2.0 OR MIT, +which carries these copyright notices: + Copyright 2019-2024 Tauri Programme within The Commons Conservancy + Copyright (c) 2017 - Present Tauri Apps Contributors +See vendor/tauri-runtime-wry/. + +Third-party dependency notices ship with each release in THIRD-PARTY-NOTICES. diff --git a/README.md b/README.md index d6f6388..e18bf34 100644 --- a/README.md +++ b/README.md @@ -72,4 +72,4 @@ when the user's session invokes their tools. ## License -MIT (per `Cargo.toml` workspace.package.license). +Licensed under the [Apache License, Version 2.0](LICENSE). See [NOTICE](NOTICE) for attribution. diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..77a760a --- /dev/null +++ b/clippy.toml @@ -0,0 +1,16 @@ +# Every crate in the workspace reads this file. + +# The `open` crate's launchers go through `cmd /c start` on Windows, which +# acts on `"`, `&` and `%` in what it opens. The app opens links and paths +# only through fleetify_backend::open_external, which validates links and +# launches through ShellExecuteExW on Windows. +disallowed-methods = [ + { path = "open::that", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::with", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::that_in_background", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::with_in_background", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::that_detached", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::with_detached", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::commands", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, + { path = "open::with_command", reason = "use fleetify_backend::open_external::{open_url, open_path}" }, +] diff --git a/crates/browser-mcp/Cargo.toml b/crates/browser-mcp/Cargo.toml index b3d5025..31d64ba 100644 --- a/crates/browser-mcp/Cargo.toml +++ b/crates/browser-mcp/Cargo.toml @@ -15,4 +15,6 @@ tokio = { version = "1", default-features = false, features = ["rt", "macros", " serde.workspace = true serde_json.workspace = true anyhow.workspace = true +# fleetify_core::loopback: the no-proxy client builder for calls to the backend. +fleetify-core.workspace = true reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } diff --git a/crates/browser-mcp/src/main.rs b/crates/browser-mcp/src/main.rs index 4183fc4..21c4ae4 100644 --- a/crates/browser-mcp/src/main.rs +++ b/crates/browser-mcp/src/main.rs @@ -107,7 +107,11 @@ async fn call_action(name: &str, args: Value) -> Result { let backend = std::env::var("FLEETIFY_BACKEND_URL").unwrap_or_else(|_| "http://127.0.0.1:8765".into()); let secret = std::env::var("FLEETIFY_INTERNAL_SECRET").unwrap_or_default(); - let client = reqwest::Client::new(); + // Never through a proxy, which would see the internal secret + // (fleetify_core::loopback). + let client = fleetify_core::loopback::http_client_builder() + .build() + .map_err(|e| format!("HTTP client: {e}"))?; let resp = client .post(format!("{backend}/api/internal/browser/action")) .header("x-fleet-internal", secret) diff --git a/crates/dispatch-mcp/Cargo.toml b/crates/dispatch-mcp/Cargo.toml index 6909845..5e245f2 100644 --- a/crates/dispatch-mcp/Cargo.toml +++ b/crates/dispatch-mcp/Cargo.toml @@ -15,4 +15,6 @@ tokio = { version = "1", default-features = false, features = ["rt", "macros", " serde.workspace = true serde_json.workspace = true anyhow.workspace = true +# fleetify_core::loopback: the no-proxy client builder for calls to the backend. +fleetify-core.workspace = true reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } diff --git a/crates/dispatch-mcp/src/main.rs b/crates/dispatch-mcp/src/main.rs index 01d2c07..ce0a527 100644 --- a/crates/dispatch-mcp/src/main.rs +++ b/crates/dispatch-mcp/src/main.rs @@ -156,6 +156,14 @@ fn env_or(k: &str, default: &str) -> String { std::env::var(k).unwrap_or_else(|_| default.to_string()) } +/// The client for calls to the backend: never through a proxy, which would +/// see the internal secret (`fleetify_core::loopback`). +fn backend_client() -> Result { + fleetify_core::loopback::http_client_builder() + .build() + .map_err(|e| format!("HTTP client: {e}")) +} + fn check_rate(session_id: &str) -> Result<(), String> { static LOG: std::sync::OnceLock>>> = std::sync::OnceLock::new(); @@ -205,7 +213,7 @@ async fn dispatch_to_agent(args: Value) -> Result { // chat via the SessionManager fanout (the caller is treated as // the "staff" here for routing purposes). let url = format!("{backend}/api/internal/dispatch"); - let r = reqwest::Client::new() + let r = backend_client()? .post(&url) .header("X-Fleet-Internal", &secret) .json(&json!({ @@ -273,7 +281,7 @@ async fn spawn_agent(args: Value) -> Result { } let url = format!("{backend}/api/internal/spawn"); - let r = reqwest::Client::new() + let r = backend_client()? .post(&url) .header("X-Fleet-Internal", &secret) .json(&Value::Object(body)) diff --git a/crates/fleet-wipe/Cargo.toml b/crates/fleet-wipe/Cargo.toml index ae2e305..ab22782 100644 --- a/crates/fleet-wipe/Cargo.toml +++ b/crates/fleet-wipe/Cargo.toml @@ -5,15 +5,25 @@ edition.workspace = true license.workspace = true publish = false -# Linux: the app stores credentials in the KERNEL keyring (keyring crate's -# linux-keyutils backend), NOT the Secret Service — so `secret-tool` can't see -# them. We enumerate the kernel keyring directly and invalidate Fleetify keys. +# Linux: the app keeps credentials in the Secret Service (keyring crate's +# linux-native-sync-persistent store). We search it with dbus-secret-service, +# the crate and version keyring itself uses, and delete Fleetify items. Builds +# before that store kept credentials in the KERNEL keyring (keyring crate's +# linux-keyutils backend), which `secret-tool` can't see; we still enumerate it +# and invalidate leftover Fleetify keys. [target.'cfg(target_os = "linux")'.dependencies] +dbus-secret-service = { version = "4.1", features = ["crypto-rust"] } linux-keyutils = "0.2" +# The Secret Service test stores its throwaway item through keyring, the way +# the app does, so a keyring upgrade that changes item attributes fails it. +# Keep version and features in step with src-tauri and fleetify-backend. +[target.'cfg(target_os = "linux")'.dev-dependencies] +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } + # macOS (Keychain) / Windows (Credential Manager): delete the fixed login # entry via the same `keyring` crate the app uses, as a belt-and-suspenders to # wipe.mjs's `security` / `cmdkey` enumeration. Feature set mirrors src-tauri # so the backend resolves identically. [target.'cfg(not(target_os = "linux"))'.dependencies] -keyring = { version = "3", features = ["windows-native"] } +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } diff --git a/crates/fleet-wipe/src/main.rs b/crates/fleet-wipe/src/main.rs index e3a69a0..99b5024 100644 --- a/crates/fleet-wipe/src/main.rs +++ b/crates/fleet-wipe/src/main.rs @@ -2,53 +2,200 @@ //! credential half of `npm run wipe` (the file half lives in `scripts/wipe.mjs`). //! //! Why a Rust helper instead of a CLI inside wipe.mjs? The app stores secrets -//! through the `keyring` crate, whose backend differs per OS — and on Linux -//! that backend is the **kernel keyring** (`linux-keyutils`), *not* the Secret -//! Service. So `secret-tool` (what wipe.mjs used) targets the wrong store and -//! the OIDC refresh token survives a wipe → the app silently re-logs-in on the -//! next launch. This helper clears creds the SAME way the app wrote them. +//! through the `keyring` crate, whose backend differs per OS. If the OIDC +//! refresh token survives a wipe, the app silently re-logs-in on the next +//! launch. This helper finds credentials in the store the app wrote them to, +//! by the attributes keyring gives them, with no `secret-tool` install needed. //! -//! - Linux: enumerate the session + persistent kernel keyrings and invalidate -//! every `keyring-rs:*@Fleetify*` key (OIDC refresh token, GitHub link, -//! per-provider keys, per-router keys). +//! - Linux: the app's store is the **Secret Service** (GNOME Keyring, +//! KWallet, ...). Delete every item keyring created whose `service` is +//! `Fleetify` / `Fleetify-*` (OIDC refresh token, GitHub link, voice, +//! per-provider and per-router keys). Builds before that store used the +//! in-memory **kernel keyring** (`linux-keyutils`), so also invalidate any +//! leftover `keyring-rs:*@Fleetify*` key there. //! - macOS: wipe.mjs's `security delete-generic-password` already clears the //! login Keychain; here we also delete the refresh-token entry via the //! keyring crate as a backstop. //! - Windows: same backstop, behind wipe.mjs's `cmdkey`. //! -//! Reads only key *descriptions* (never secret values) and only ever touches -//! keys whose service is `Fleetify` / `Fleetify-*`. Pass `--dry-run` (or -//! `--check`) to list what WOULD be removed without changing anything. +//! Reads only item attributes and key *descriptions* (never secret values) +//! and only ever touches entries whose service is `Fleetify` / `Fleetify-*`. +//! Output names each entry by its service alone, never by its account. +//! Pass `--dry-run` (or `--check`) to list what WOULD be removed without +//! changing anything. Exits with status 1 when the Linux Secret Service sweep +//! fails (unreachable, left locked, or an item can't be deleted), so wipe.mjs +//! reports the failure. fn main() { let dry = std::env::args() .skip(1) .any(|a| a == "--dry-run" || a == "--check"); - let removed = wipe(dry); let verb = if dry { "would remove" } else { "removed" }; - println!("fleet-wipe: {verb} {removed} Fleetify credential(s)"); + match wipe(dry) { + Ok(removed) => println!("fleet-wipe: {verb} {removed} Fleetify credential(s)"), + Err(e) => { + eprintln!("fleet-wipe: {e}"); + std::process::exit(1); + } + } } -/// True for `keyring`-crate key descriptions that belong to Fleetify. The -/// linux-keyutils backend names keys `keyring-rs:@`; we match -/// on the `` half being `Fleetify` or `Fleetify-*` so a stray -/// `NotFleetify` or another app's key is never touched. -// Only the Linux `wipe` enumerates key descriptions; on Windows/macOS this -// helper is unused, so silence dead-code there (keeps `clippy -D warnings` green). +/// True for the keyring service names Fleetify uses: exactly `Fleetify` (the +/// OIDC refresh token) or `Fleetify-*` (`Fleetify-GitHub`, `Fleetify-Voice`, +/// `Fleetify-Provider-`, `Fleetify-Router-`). `FleetifyX`, `fleetify` +/// and another app's services never match. +// Only the Linux sweeps match service names; on Windows/macOS these helpers +// are unused, so silence dead-code there (keeps `clippy -D warnings` green). #[cfg_attr(not(target_os = "linux"), allow(dead_code))] -fn is_fleetify_desc(desc: &str) -> bool { - let Some(rest) = desc.strip_prefix("keyring-rs:") else { - return false; - }; - let Some(at) = rest.rfind('@') else { - return false; - }; - let service = &rest[at + 1..]; +fn is_fleetify_service(service: &str) -> bool { service == "Fleetify" || service.starts_with("Fleetify-") } +/// True for `keyring`-crate key descriptions that belong to Fleetify: we match +/// their `` half ([`kernel_key_service`]) with [`is_fleetify_service`]. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn is_fleetify_desc(desc: &str) -> bool { + kernel_key_service(desc).is_some_and(is_fleetify_service) +} + +/// The `` half of a `keyring`-crate key description. The +/// linux-keyutils backend names keys `keyring-rs:@`, and +/// `` can contain `@`, so the service follows the last one. `None` +/// for any other description. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn kernel_key_service(desc: &str) -> Option<&str> { + let (_, service) = desc.strip_prefix("keyring-rs:")?.rsplit_once('@')?; + Some(service) +} + +/// What a sweep did with one credential, or in a dry run would do. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +enum Outcome<'e> { + WouldRemove, + Removed, + Failed(&'e dyn std::fmt::Display), +} + +/// The output line for one Secret Service item. It names the item by its +/// `service` attribute only and leaves out its `username`: for some services +/// that is the user's Fleetify account ID, and nobody needs it in wipe output. +// Not named `describe_secret_service_item`: CodeQL treats the result of any +// function whose name contains "secret" as sensitive, and would flag every +// line that prints it. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn describe_ss_item(service: &str, outcome: Outcome<'_>) -> String { + match outcome { + Outcome::WouldRemove => format!(" · Secret Service: {service}"), + Outcome::Removed => format!(" ✓ Secret Service: {service}"), + Outcome::Failed(e) => format!(" ! failed to delete Secret Service item {service}: {e}"), + } +} + +/// The output line for one kernel keyring key. It names the key by the +/// `` half of its description only, for the same reason: the +/// `` half can be the user's Fleetify account ID. A description with +/// no service half (the sweep passes none) prints an empty name rather than +/// the whole description. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn describe_kernel_key(desc: &str, outcome: Outcome<'_>) -> String { + let service = kernel_key_service(desc).unwrap_or_default(); + match outcome { + Outcome::WouldRemove => format!(" · kernel keyring: {service}"), + Outcome::Removed => format!(" ✓ kernel keyring: {service}"), + Outcome::Failed(e) => { + format!(" ! failed to invalidate kernel keyring key {service}: {e}") + } + } +} + +/// The `application` attribute keyring puts on every Secret Service item it +/// creates. keyring 3.6.3's module docs say `rust-keyring-client`, but its code +/// (`SsCredential::new_with_target`) and its own tests use `rust-keyring`, as +/// keyring 1.x and 2.x did. The Secret Service test fails if this drifts. +#[cfg(target_os = "linux")] +const KEYRING_APPLICATION: &str = "rust-keyring"; + +/// Deletes the Secret Service items keyring created whose `service` attribute +/// satisfies `matches`, or with `dry_run` only lists them. Prints one line per +/// item, named by its service only ([`describe_ss_item`]); secrets are never +/// read. Returns how many items it removed (or would remove). #[cfg(target_os = "linux")] -fn wipe(dry: bool) -> usize { +fn wipe_secret_service(matches: &dyn Fn(&str) -> bool, dry_run: bool) -> Result { + use dbus_secret_service::{EncryptionType, SecretService}; + use std::collections::HashMap; + + let ss = SecretService::connect(EncryptionType::Dh) + .map_err(|e| format!("cannot reach the Secret Service: {e}"))?; + + // keyring creates its items in the default collection. While that + // collection is locked (e.g. after an auto-login boot), its items come + // back locked: GNOME Keyring then shows only hashed attributes, so their + // `service` can't be matched, and refuses to delete them. So a real run + // unlocks it first, which shows the same prompt the app shows on its + // first keyring access. A dry run changes nothing and only says so. + if let Ok(collection) = ss.get_default_collection() { + if collection.is_locked().unwrap_or(false) { + if dry_run { + println!( + " ! Secret Service: the default collection is locked, so its items \ + are not listed (a real run asks to unlock it)" + ); + } else { + collection.unlock().map_err(|e| { + format!("cannot unlock the Secret Service default collection: {e}") + })?; + } + } + } + + let found = ss + .search_items(HashMap::from([("application", KEYRING_APPLICATION)])) + .map_err(|e| format!("Secret Service search failed: {e}"))?; + let mut count = 0; + let mut failed = 0; + // Items that are still locked sit in another locked collection (or the + // default one, in a dry run). They are skipped: Fleetify writes only to + // the default collection. + for item in &found.unlocked { + let Ok(attributes) = item.get_attributes() else { + continue; + }; + let Some(service) = attributes.get("service").filter(|s| matches(s.as_str())) else { + continue; + }; + if dry_run { + println!("{}", describe_ss_item(service, Outcome::WouldRemove)); + count += 1; + } else if let Err(e) = item.delete() { + eprintln!("{}", describe_ss_item(service, Outcome::Failed(&e))); + failed += 1; + } else { + println!("{}", describe_ss_item(service, Outcome::Removed)); + count += 1; + } + } + if failed > 0 { + return Err(format!( + "{failed} Secret Service item(s) could not be deleted" + )); + } + Ok(count) +} + +/// Linux: the app keeps credentials in the Secret Service; builds before that +/// store kept them in the kernel keyring. Sweep both, even when the Secret +/// Service fails, and report that failure afterwards. +#[cfg(target_os = "linux")] +fn wipe(dry: bool) -> Result { + let secret_service = wipe_secret_service(&is_fleetify_service, dry); + let kernel = wipe_kernel_keyring(dry); + Ok(secret_service? + kernel) +} + +/// Invalidates the `keyring-rs:*@Fleetify*` keys that builds before the Secret +/// Service store left in the kernel keyring. +#[cfg(target_os = "linux")] +fn wipe_kernel_keyring(dry: bool) -> usize { use linux_keyutils::{KeyRing, KeyRingIdentifier}; use std::collections::HashSet; @@ -92,10 +239,16 @@ fn wipe(dry: bool) -> usize { continue; } count += 1; - println!(" {} {desc}", if dry { "·" } else { "✓" }); + let outcome = if dry { + Outcome::WouldRemove + } else { + Outcome::Removed + }; + println!("{}", describe_kernel_key(desc, outcome)); if !dry { if let Err(e) = key.invalidate() { - eprintln!(" ! failed to invalidate {desc}: {e:?}"); + let e = format!("{e:?}"); + eprintln!("{}", describe_kernel_key(desc, Outcome::Failed(&e))); } } } @@ -104,7 +257,12 @@ fn wipe(dry: bool) -> usize { } #[cfg(not(target_os = "linux"))] -fn wipe(dry: bool) -> usize { +fn wipe(dry: bool) -> Result { + Ok(wipe_keychain(dry)) +} + +#[cfg(not(target_os = "linux"))] +fn wipe_keychain(dry: bool) -> usize { // macOS Keychain / Windows Credential Manager. wipe.mjs's `security` / // `cmdkey` enumeration clears every `Fleetify*` service by name; this is a // backstop that removes the fixed login refresh-token entry directly via the @@ -121,7 +279,7 @@ fn wipe(dry: bool) -> usize { if dry { return match entry.get_password() { Ok(_) => { - println!(" · refresh_token@Fleetify"); + println!(" · keychain: Fleetify"); 1 } _ => 0, @@ -129,7 +287,7 @@ fn wipe(dry: bool) -> usize { } match entry.delete_credential() { Ok(()) => { - println!(" ✓ refresh_token@Fleetify"); + println!(" ✓ keychain: Fleetify"); 1 } Err(keyring::Error::NoEntry) => 0, @@ -139,3 +297,145 @@ fn wipe(dry: bool) -> usize { } } } + +#[cfg(test)] +mod tests { + use super::{ + describe_kernel_key, describe_ss_item, is_fleetify_desc, is_fleetify_service, Outcome, + }; + + #[test] + fn fleetify_services_match() { + for service in [ + "Fleetify", + "Fleetify-GitHub", + "Fleetify-Voice", + "Fleetify-Provider-x", + "Fleetify-Router-y", + ] { + assert!(is_fleetify_service(service), "{service:?} should match"); + } + } + + #[test] + fn other_services_do_not_match() { + for service in ["FleetifyX", "fleetify", "Other-Fleetify", ""] { + assert!( + !is_fleetify_service(service), + "{service:?} should not match" + ); + } + } + + #[test] + fn kernel_key_descriptions_match_on_their_service_half() { + assert!(is_fleetify_desc("keyring-rs:refresh_token@Fleetify")); + assert!(is_fleetify_desc("keyring-rs:sub@tenant@Fleetify-GitHub")); + assert!(is_fleetify_desc("keyring-rs:default@Fleetify-Provider-x")); + assert!(!is_fleetify_desc("keyring-rs:refresh_token@FleetifyX")); + assert!(!is_fleetify_desc("keyring-rs:Fleetify@Other-Fleetify")); + assert!(!is_fleetify_desc("refresh_token@Fleetify")); + assert!(!is_fleetify_desc("keyring-rs:no-service")); + } + + #[test] + fn secret_service_lines_name_the_item_by_its_service_only() { + let error = "the item is locked"; + for (outcome, expected) in [ + (Outcome::WouldRemove, " · Secret Service: Fleetify-GitHub"), + (Outcome::Removed, " ✓ Secret Service: Fleetify-GitHub"), + ( + Outcome::Failed(&error), + " ! failed to delete Secret Service item Fleetify-GitHub: the item is locked", + ), + ] { + let line = describe_ss_item("Fleetify-GitHub", outcome); + assert!( + line.contains("Fleetify-GitHub"), + "{line:?} names no service" + ); + assert!(!line.contains("username="), "{line:?} prints a username"); + assert_eq!(line, expected); + } + } + + #[test] + fn kernel_key_lines_name_the_key_by_its_service_only() { + // `acct-42@tenant` is the `` half: it stands in for an ID. + let desc = "keyring-rs:acct-42@tenant@Fleetify-GitHub"; + let error = "KeyRevoked"; + for (outcome, expected) in [ + (Outcome::WouldRemove, " · kernel keyring: Fleetify-GitHub"), + (Outcome::Removed, " ✓ kernel keyring: Fleetify-GitHub"), + ( + Outcome::Failed(&error), + " ! failed to invalidate kernel keyring key Fleetify-GitHub: KeyRevoked", + ), + ] { + let line = describe_kernel_key(desc, outcome); + assert!( + line.contains("Fleetify-GitHub"), + "{line:?} names no service" + ); + assert!(!line.contains("acct-42"), "{line:?} prints the account"); + assert_eq!(line, expected); + } + } +} + +/// Runs against the real Secret Service on the session bus and fails, rather +/// than skips, when there is none. It creates, matches and deletes only its own +/// uniquely named items: the matcher accepts exactly one test service name, so +/// real Fleetify items are never printed or deleted. +#[cfg(all(test, target_os = "linux"))] +mod secret_service_tests { + use super::wipe_secret_service; + use std::time::{SystemTime, UNIX_EPOCH}; + + /// Deletes its test item when dropped, so a failed assertion leaves + /// nothing behind in the keyring. + struct Cleanup(keyring::Entry); + + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = self.0.delete_credential(); + } + } + + /// Stores a throwaway item the way the app stores its credentials. + fn store(service: &str) -> Cleanup { + let entry = keyring::Entry::new(service, "wipe-test").expect("keyring entry"); + if let Err(e) = entry.set_password("not-a-real-secret") { + panic!( + "this test needs a Secret Service provider (e.g. an unlocked \ + gnome-keyring-daemon) on the session bus; storing a test item failed: {e}" + ); + } + Cleanup(entry) + } + + #[test] + fn deletes_only_the_matching_item_keyring_created() { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock after 1970") + .as_nanos(); + let service = format!("Fleetify-WipeTest-{}-{nanos}", std::process::id()); + let target = store(&service); + let other = store(&format!("{service}-keep")); + let only_target = |s: &str| s == service; + + assert_eq!(wipe_secret_service(&only_target, true), Ok(1), "dry run"); + assert!(target.0.get_password().is_ok(), "a dry run must not delete"); + + assert_eq!(wipe_secret_service(&only_target, false), Ok(1), "real run"); + assert!( + matches!(target.0.get_password(), Err(keyring::Error::NoEntry)), + "the matching item should be gone" + ); + assert!( + other.0.get_password().is_ok(), + "a non-matching item must stay" + ); + } +} diff --git a/crates/fleetify-backend/Cargo.toml b/crates/fleetify-backend/Cargo.toml index a83fc95..793af8e 100644 --- a/crates/fleetify-backend/Cargo.toml +++ b/crates/fleetify-backend/Cargo.toml @@ -29,7 +29,11 @@ futures-util = "0.3" chromiumoxide = "0.9" http = "1" regex = "1" -open = "5" +# shellexecute-on-windows: `that_detached` opens through ShellExecuteExW, not +# `cmd /c start`, which would act on `"`, `&` and `%` in what it opens. +# Only `open_external` may call it (clippy.toml). +open = { version = "5", features = ["shellexecute-on-windows"] } +url = "2" rand = "0.8" parking_lot = "0.12" # Used by the Gemini bridge to resolve the `gemini` binary explicitly on @@ -43,9 +47,12 @@ glob = "0.3" # Antigravity SDK bridge reads `GEMINI_API_KEY` from the OS keyring under # `Fleetify-Provider-antigravity-sdk` — same store the Tauri shell writes # to via providers_link, so a single source of truth flows through. -# `windows-native` keeps the credential in the Windows Credential Manager -# (Tauri shell uses the same feature set). -keyring = { version = "3", features = ["windows-native", "apple-native", "linux-native"] } +# One feature set for every crate (src-tauri, fleet-wipe): Keychain on macOS, +# Credential Manager on Windows, Secret Service on Linux. Plain `linux-native` +# (the kernel keyring) is in-memory and loses every credential on reboot. The +# Secret Service store needs libdbus-1-dev + pkg-config to build on Linux; +# `crypto-rust` encrypts secrets on the D-Bus wire. +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } # Loads `.env` (workspace root) into the process environment at server # startup so single-source dev config (POSTHOG_API_KEY, POSTHOG_HOST, …) # works without a wrapper shell script. No-op when `.env` is absent — @@ -58,6 +65,11 @@ dotenvy = "0.15" # code back is to give agy a real terminal that we own. portable-pty = "0.8" +# open_external decides WSL the way the open crate does before it tries +# wslview (open 5.3.5 unix.rs): the same crate. +[target.'cfg(target_os = "linux")'.dependencies] +is-wsl = "0.4" + # Windows-only: read the user's canonical (Machine + User) registry PATH so # spawned CLI agents get the clean PATH a fresh terminal would have — NOT the # bloated runtime PATH our deep launch chain (npm -> cross-env -> tauri -> @@ -76,4 +88,6 @@ rand = "0.8" tokio = { version = "1", features = ["full", "test-util"] } tokio-tungstenite = "0.24" tower = { version = "0.5", features = ["util"] } +# Captures log lines in tests that pin what is never logged. +tracing-subscriber.workspace = true wiremock = "0.6" diff --git a/crates/fleetify-backend/src/agentic/context.rs b/crates/fleetify-backend/src/agentic/context.rs index 5f8f6ce..4dbab82 100644 --- a/crates/fleetify-backend/src/agentic/context.rs +++ b/crates/fleetify-backend/src/agentic/context.rs @@ -85,7 +85,7 @@ pub async fn build_system_context(workspace: &Workspace, header: Option<&str>) - let body = if content.len() > README_BUDGET { format!( "{}\n[truncated at {README_BUDGET} chars — use read_file for the full document]", - &content[..README_BUDGET] + fleetify_core::text::prefix_within_bytes(&content, README_BUDGET) ) } else { content @@ -271,6 +271,26 @@ mod tests { assert!(prompt.contains(&format!("[truncated at {README_BUDGET} chars"))); } + /// Regression: a Turkish README over budget panicked when the cut at + /// byte `README_BUDGET` landed inside a letter. + #[tokio::test] + async fn truncates_oversize_turkish_readme_on_a_character_boundary() { + let dir = tempdir().unwrap(); + let readme = format!("#{}", "ş".repeat(README_BUDGET)); + assert!( + !readme.is_char_boundary(README_BUDGET), + "fixture must put the cut inside a letter" + ); + std::fs::write(dir.path().join("README.md"), &readme).unwrap(); + let ws = Workspace::new(dir.path()).unwrap(); + let prompt = build_system_context(&ws, None).await; + // Keeps the bytes before that letter, then the marker. + let kept = &readme[..README_BUDGET - 1]; + assert!(prompt.contains(&format!( + "\n{kept}\n[truncated at {README_BUDGET} chars" + ))); + } + #[tokio::test] async fn workspace_tree_lists_top_level_only_skipping_noise_dirs() { let dir = tempdir().unwrap(); diff --git a/crates/fleetify-backend/src/auth.rs b/crates/fleetify-backend/src/auth.rs index 1a7a135..c1c1f8f 100644 --- a/crates/fleetify-backend/src/auth.rs +++ b/crates/fleetify-backend/src/auth.rs @@ -11,6 +11,7 @@ use axum::extract::{FromRef, FromRequestParts}; use axum::http::request::Parts; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; +use fleetify_core::endpoints; use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation}; use serde::Deserialize; use sha2::{Digest, Sha256}; @@ -61,20 +62,27 @@ pub struct AuthConfig { } impl AuthConfig { - pub fn from_env() -> Self { - let origin = std::env::var("FLEETIFY_ISSUER") - .unwrap_or_else(|_| "http://localhost:3001".to_string()); - let auth_base = format!("{origin}/api/auth"); + /// Derives the better-auth base (`{origin}/api/auth`, also the expected + /// `iss`) and its JWKS URL from the identity-provider origin. + pub fn new(issuer_origin: String, expected_audience: String) -> Self { + let auth_base = format!("{issuer_origin}/api/auth"); let jwks_url = format!("{auth_base}/jwks"); - let expected_audience = std::env::var("FLEETIFY_AUDIENCE") - .unwrap_or_else(|_| "http://127.0.0.1:8765".to_string()); Self { - issuer_origin: origin, + issuer_origin, auth_base, jwks_url, expected_audience, } } + + /// Production `fleetify.dev` values in release builds, whatever the + /// environment says; debug builds read `FLEETIFY_ISSUER` and + /// `FLEETIFY_RESOURCE` / `FLEETIFY_AUDIENCE` (see + /// [`fleetify_core::endpoints`]). The shell's OAuth client resolves the + /// same values, so the tokens it obtains are the ones validated here. + pub fn from_env() -> Self { + Self::new(endpoints::issuer_origin(), endpoints::api_resource()) + } } // ── Principal ─────────────────────────────────────────────────────── @@ -530,3 +538,19 @@ where Ok(AuthUser(user)) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auth_config_new_derives_prod_urls() { + let c = AuthConfig::new( + "https://fleetify.dev".into(), + "https://fleetify.dev/api".into(), + ); + assert_eq!(c.auth_base, "https://fleetify.dev/api/auth"); + assert_eq!(c.jwks_url, "https://fleetify.dev/api/auth/jwks"); + assert_eq!(c.expected_audience, "https://fleetify.dev/api"); + } +} diff --git a/crates/fleetify-backend/src/bridges/antigravity_sdk.rs b/crates/fleetify-backend/src/bridges/antigravity_sdk.rs index 62ba5b8..fa25b72 100644 --- a/crates/fleetify-backend/src/bridges/antigravity_sdk.rs +++ b/crates/fleetify-backend/src/bridges/antigravity_sdk.rs @@ -730,4 +730,13 @@ mod tests { assert_eq!(b.autonomy_mode, "chat"); assert_eq!(b.model, "gemini-3.5-flash"); } + + // Fails to compile unless keyring's persistent Linux store is enabled: + // plain `linux-native` (keyutils) is in-memory and loses every credential on reboot. + #[cfg(target_os = "linux")] + #[test] + fn linux_keyring_store_survives_reboot() { + #[allow(unused_imports)] + use keyring::keyutils_persistent as _; + } } diff --git a/crates/fleetify-backend/src/bridges/claude.rs b/crates/fleetify-backend/src/bridges/claude.rs index 4b8c5ac..2153416 100644 --- a/crates/fleetify-backend/src/bridges/claude.rs +++ b/crates/fleetify-backend/src/bridges/claude.rs @@ -444,6 +444,17 @@ fn effort_to_claude(effort: &str, model: &str) -> Option<&'static str> { } } +/// Shorten claude-code's stderr for the dev-terminal log line: at most 2048 +/// bytes, backed off to a character boundary, with the dropped byte count. +fn stderr_log_preview(t: &str) -> String { + let head = fleetify_core::text::prefix_within_bytes(t, 2048); + if head.len() < t.len() { + format!("{head}…[truncated {}b]", t.len() - head.len()) + } else { + t.to_string() + } +} + /// Drives the `claude` subprocess. `--mcp-config` injection is Phase 4. pub struct ClaudeBridge { pub session_id: String, @@ -1107,11 +1118,7 @@ impl ClaudeBridge { // line readable when the upstream returns a huge // JSON body (the renderer still gets the full // string via BridgeEvent::Error for the user). - let preview = if t.len() > 2048 { - format!("{}…[truncated {}b]", &t[..2048], t.len() - 2048) - } else { - t.to_string() - }; + let preview = stderr_log_preview(t); tracing::error!( target: "fleetify::bridges::claude", exit_code = code.unwrap_or(-1), @@ -1160,6 +1167,24 @@ impl ClaudeBridge { mod tests { use super::*; + /// Regression: stderr can quote Turkish text (the prompt, a path, an + /// upstream error). A byte-2048 cut inside a letter panicked the task + /// that reports the error, so the session never heard about it. + #[test] + fn stderr_preview_backs_off_to_a_character_boundary() { + let t = format!("a{}", "ş".repeat(1500)); // 3001 bytes + assert!( + !t.is_char_boundary(2048), + "fixture must put byte 2048 inside a letter" + ); + + let preview = stderr_log_preview(&t); + + // Keeps 2047 bytes and reports the 954 it dropped. + assert_eq!(preview, format!("{}…[truncated 954b]", &t[..2047])); + assert_eq!(stderr_log_preview("kısa hata"), "kısa hata"); + } + #[test] fn send_message_accepts_bridge_context() { // Compile-only — just construct a default ctx and assert its shape. diff --git a/crates/fleetify-backend/src/bridges/openai.rs b/crates/fleetify-backend/src/bridges/openai.rs index dc7c01b..9e000cb 100644 --- a/crates/fleetify-backend/src/bridges/openai.rs +++ b/crates/fleetify-backend/src/bridges/openai.rs @@ -159,7 +159,10 @@ impl OpenAIBridge { let body = resp.text().await.unwrap_or_default(); let _ = tx .send(BridgeEvent::Error { - error: format!("OpenAI {s}: {}", &body[..body.len().min(400)]), + error: format!( + "OpenAI {s}: {}", + fleetify_core::text::prefix_within_bytes(&body, 400) + ), }) .await; let _ = tx diff --git a/crates/fleetify-backend/src/bridges/openai_compat.rs b/crates/fleetify-backend/src/bridges/openai_compat.rs index 3c97aa8..ceae70f 100644 --- a/crates/fleetify-backend/src/bridges/openai_compat.rs +++ b/crates/fleetify-backend/src/bridges/openai_compat.rs @@ -226,7 +226,10 @@ impl OpenAICompatBridge { let body = resp.text().await.unwrap_or_default(); let _ = tx .send(BridgeEvent::Error { - error: format!("{provider_id} {s}: {}", &body[..body.len().min(400)]), + error: format!( + "{provider_id} {s}: {}", + fleetify_core::text::prefix_within_bytes(&body, 400) + ), }) .await; let _ = tx diff --git a/crates/fleetify-backend/src/bridges/openai_compat_tools.rs b/crates/fleetify-backend/src/bridges/openai_compat_tools.rs index cce8be6..638e640 100644 --- a/crates/fleetify-backend/src/bridges/openai_compat_tools.rs +++ b/crates/fleetify-backend/src/bridges/openai_compat_tools.rs @@ -259,7 +259,7 @@ impl ToolAdapter for OpenAICompatToolAdapter { return Err(anyhow!( "{}: provider returned {status}: {}", self.provider_id, - &body[..body.len().min(400)] + fleetify_core::text::prefix_within_bytes(&body, 400) )); } @@ -860,6 +860,36 @@ mod tests { assert!(msg.contains("invalid api key")); } + /// Regression: error bodies are not always ASCII (a localized API + /// message, a Turkish proxy page). Cutting one at byte 400 inside a + /// letter panicked instead of reporting the error. + #[tokio::test] + async fn execute_turn_cuts_a_non_ascii_error_body_on_a_character_boundary() { + let server = MockServer::start().await; + let body = format!("E{}", "ş".repeat(300)); // 601 bytes + assert!( + !body.is_char_boundary(400), + "fixture must put byte 400 inside a letter" + ); + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(502).set_body_string(body.clone())) + .mount(&server) + .await; + + let adapter = adapter_for(&server); + let history = adapter.init_history("sys", "hi"); + let (tx, _rx) = mpsc::channel(8); + + let err = adapter + .execute_turn(&history, &catalog_v1(), &tx) + .await + .unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("502")); + // The body is cut back to the 399 bytes before that letter. + assert!(msg.ends_with(&format!(": {}", &body[..399])), "{msg}"); + } + #[tokio::test] async fn full_loop_executes_tool_and_completes_with_text() { // Two-turn flow: provider asks read_file; bridge executes against diff --git a/crates/fleetify-backend/src/bridges/perplexity.rs b/crates/fleetify-backend/src/bridges/perplexity.rs index 7e9f7d3..4dd9932 100644 --- a/crates/fleetify-backend/src/bridges/perplexity.rs +++ b/crates/fleetify-backend/src/bridges/perplexity.rs @@ -166,7 +166,10 @@ impl PerplexityBridge { let body = resp.text().await.unwrap_or_default(); let _ = tx .send(BridgeEvent::Error { - error: format!("perplexity {s}: {}", &body[..body.len().min(400)]), + error: format!( + "perplexity {s}: {}", + fleetify_core::text::prefix_within_bytes(&body, 400) + ), }) .await; let _ = tx diff --git a/crates/fleetify-backend/src/http.rs b/crates/fleetify-backend/src/http.rs index ee90347..7eef813 100644 --- a/crates/fleetify-backend/src/http.rs +++ b/crates/fleetify-backend/src/http.rs @@ -12,6 +12,10 @@ use crate::routers::{ sessions, ssh, user, workflows, workspace, AppState, }; +/// The health route. It answers `{"status":"ok","version":…}`, and the +/// shell polls it at startup before its warm-up talks to the backend. +pub const HEALTH_PATH: &str = "/healthz"; + /// Build the axum app. Single origin: `/healthz`, `/api/*` (auth'd), /// `/events/status` SSE, and the built React assets (when `static_dir`). /// CORS mirrors the Python: localhost:3000 / 127.0.0.1:3000, creds, *. @@ -65,7 +69,7 @@ pub fn app(state: AppState, static_dir: Option) -> Router { let internal_api = internal::router().merge(browser::internal_router()); let routed = Router::new() - .route("/healthz", get(healthz)) + .route(HEALTH_PATH, get(healthz)) .nest("/api", api) .nest("/api/internal", internal_api) .merge(events::router()) diff --git a/crates/fleetify-backend/src/lib.rs b/crates/fleetify-backend/src/lib.rs index 5cfaa46..82d4245 100644 --- a/crates/fleetify-backend/src/lib.rs +++ b/crates/fleetify-backend/src/lib.rs @@ -11,6 +11,7 @@ pub mod bridges; pub mod config; pub mod db; pub mod models; +pub mod open_external; pub mod providers; pub mod routers; pub mod services; @@ -26,7 +27,7 @@ use std::sync::Arc; use tokio::net::TcpListener; use tokio::sync::oneshot; -pub use http::app; +pub use http::{app, HEALTH_PATH}; pub struct ServerHandle { local_addr: SocketAddr, @@ -154,6 +155,14 @@ fn resolve_db_path_in(configured: &str, home: PathBuf, isolate: bool) -> PathBuf } } +/// Whether startup loads a `.env` file into the process environment. Only +/// debug builds do. `dotenvy` searches the working directory and its +/// ancestors, so a release build launched from a terminal inside some +/// project would otherwise pick up that project's `.env`. +pub(crate) fn should_load_dotenv(release_build: bool) -> bool { + !release_build +} + /// Bind `addr` and start serving, hydrating the routing orchestrator with /// the supplied `routing_setup`. The Tauri shell composes the setup from /// `fleet.config.json` + the per-user keychain before invoking this so @@ -163,12 +172,16 @@ pub async fn serve_with_routing_setup( static_dir: Option, routing_setup: services::routing::setup::RoutingSetup, ) -> anyhow::Result { - // Load `.env` from the workspace root (if present) into the process - // environment. Existing env vars are NOT overridden — a real shell-set - // value wins over the file. No-op when `.env` is absent, which is the - // production case. Powers single-source dev config for POSTHOG_API_KEY - // and similar without forcing a wrapper shell script. - let _ = dotenvy::dotenv(); + // Debug builds load the first `.env` found walking up from the working + // directory (the workspace root's under `npm run dev:tauri`) into the + // process environment. Existing env vars are NOT overridden — a real + // shell-set value wins over the file. Powers single-source dev config + // for POSTHOG_API_KEY and similar without forcing a wrapper shell + // script. Release builds never read `.env`: a project's `.env` in the + // launch directory must not configure Fleetify. + if should_load_dotenv(!cfg!(debug_assertions)) { + let _ = dotenvy::dotenv(); + } // Lifespan parity: one-shot ~/.fleet → ~/.fleetify migration. services::migration::migrate_fleet_to_fleetify(); @@ -558,3 +571,14 @@ mod db_path_tests { ); } } + +#[cfg(test)] +mod dotenv_tests { + use super::should_load_dotenv; + + #[test] + fn dotenv_is_read_only_by_debug_builds() { + assert!(!should_load_dotenv(true)); + assert!(should_load_dotenv(false)); + } +} diff --git a/crates/fleetify-backend/src/open_external.rs b/crates/fleetify-backend/src/open_external.rs new file mode 100644 index 0000000..98eb81e --- /dev/null +++ b/crates/fleetify-backend/src/open_external.rs @@ -0,0 +1,1122 @@ +//! Opening a link or a path with the system's default handler: the one way +//! the app does it, for the shell and the backend alike. +//! +//! On Windows, `open::that` runs `cmd /c start "" ""` with the argument +//! inserted raw. A `"` ends the quoting, `&` chains another command, and +//! `%NAME%` expands even inside the quotes. URL parsing lets `"` and `&` into +//! a host: the markdown link `https://x%22&calc.exe&%22y.com/` comes out as +//! `https://x"&calc.exe&"y.com/`. The links the app opens come from markdown +//! it didn't write, provider CLI output and repository remotes. +//! +//! - [`validate_external_url`] accepts only http and https links with a +//! host, and mailto links that fill in only the recipients, subject and +//! body (no `;` in the fields), and only when the serialized URL holds no +//! `"`, whitespace or control character. It drops a link's username and +//! password, and percent-encodes `$` and backticks for PowerShell under +//! WSL (refusing them in a host). +//! - [`open_url`] validates, then opens the serialized URL, never the raw +//! input. +//! - [`open_path`] opens a file or folder the app chose itself, +//! [`open_ui_path`] a folder or document the UI asks for, and +//! [`path_to_reveal`] resolves an item to show in the file manager. All +//! three refuse a Windows network or device path before anything touches +//! it, resolve the path, check what it resolved to (an absolute path; from +//! the UI, a folder or a document; no package on macOS; no character +//! PowerShell acts on under WSL), and open that resolved path. +//! +//! On Windows they launch through `ShellExecuteExW` (`open::that_detached` +//! with the crate's `shellexecute-on-windows` feature): no command shell, +//! no `%` expansion. Elsewhere they use `open::that`, as before: it reports +//! a launcher's failed exit status, which callers rely on to fall back. +//! +//! The workspace's `clippy.toml` forbids every `open` launcher outside this +//! module. + +use std::ffi::OsStr; +use std::fmt; +use std::io; +use std::path::{Path, PathBuf}; + +use url::Url; + +/// Why a link can't be opened. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UrlRejected { + /// It doesn't parse as an absolute URL (the parser's error). + Unparsable(String), + /// Its scheme is not http, https or mailto. + Scheme(String), + /// An http or https link without a host. + NoHost, + /// The serialized URL holds a `"`, whitespace or a control character, + /// which a command line could act on. + UnsafeCharacter(char), + /// A mailto link with a field other than [`MAIL_FIELDS`]: some mail + /// clients attach the local file an `attach` field names. + MailField(String), + /// A mailto link whose fields hold a `;`: some mail clients split fields + /// on it as well as on `&`, so a field hidden in a value would get past + /// [`MAIL_FIELDS`]. + MailSemicolon, +} + +impl fmt::Display for UrlRejected { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unparsable(error) => write!(f, "it isn't a URL ({error})"), + Self::Scheme(scheme) => write!( + f, + "only http, https and mailto links are opened, not {scheme}:" + ), + Self::NoHost => write!(f, "it has no host"), + Self::UnsafeCharacter(c) => write!(f, "it holds a character that isn't allowed: {c:?}"), + Self::MailField(field) => { + write!(f, "a mail link can't set the {field:?} field") + } + Self::MailSemicolon => write!(f, "a mail link's fields can't hold a ;"), + } + } +} + +impl std::error::Error for UrlRejected {} + +/// Why opening a link failed. +#[derive(Debug)] +pub enum OpenError { + /// The link was refused, so nothing was launched. + Rejected(UrlRejected), + /// The system couldn't open it. + Launch(io::Error), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Rejected(rejected) => write!(f, "this link can't be opened: {rejected}"), + Self::Launch(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for OpenError {} + +/// The fields a mailto link may fill in, compared case-insensitively: the +/// recipients, the subject and the body. +pub const MAIL_FIELDS: [&str; 5] = ["to", "cc", "bcc", "subject", "body"]; + +/// `raw` as a URL the system may open: an http or https link with a host, +/// or a mailto link that fills in only [`MAIL_FIELDS`], with no `;` in its +/// fields (some mail clients split on it too). +/// +/// - An http or https link loses its username and password: the browser +/// never sees credentials a remote or a link carried. +/// - The serialized URL must hold no `"`, whitespace or control character. +/// The parser drops tabs and newlines and percent-encodes a `"` or space +/// in a path, query or fragment; what it keeps (a `"` in a host, a space +/// in a mailto address) is refused. +/// - Under WSL, `open::that` hands the URL to `wslview`, which runs it +/// through PowerShell, where `$(…)` runs and `$env:X` expands: a `$` or +/// backtick in the host is refused, and anywhere else it is +/// percent-encoded (`%24`, `%60`). The URL returned is that encoded form. +pub fn validate_external_url(raw: &str) -> Result { + let mut url = Url::parse(raw).map_err(|error| UrlRejected::Unparsable(error.to_string()))?; + match url.scheme() { + "http" | "https" => { + if url.host_str().is_none_or(str::is_empty) { + return Err(UrlRejected::NoHost); + } + // Can't fail: an http(s) URL with a host can have credentials. + let _ = url.set_username(""); + let _ = url.set_password(None); + } + "mailto" => { + // Fields split on `&` (RFC 6068); a client that also splits on + // `;` would find a field hidden in a value. + if url.query().is_some_and(|query| query.contains(';')) { + return Err(UrlRejected::MailSemicolon); + } + if let Some((field, _)) = url + .query_pairs() + .find(|(field, _)| !MAIL_FIELDS.iter().any(|f| f.eq_ignore_ascii_case(field))) + { + return Err(UrlRejected::MailField(field.into_owned())); + } + } + other => return Err(UrlRejected::Scheme(other.to_string())), + } + if let Some(c) = url + .host_str() + .and_then(|host| host.chars().find(|c| matches!(c, '$' | '`'))) + { + return Err(UrlRejected::UnsafeCharacter(c)); + } + if let Some(c) = url + .as_str() + .chars() + .find(|c| *c == '"' || c.is_whitespace() || c.is_control()) + { + return Err(UrlRejected::UnsafeCharacter(c)); + } + if url.as_str().contains(['$', '`']) { + let encoded = url.as_str().replace('$', "%24").replace('`', "%60"); + url = Url::parse(&encoded).map_err(|error| UrlRejected::Unparsable(error.to_string()))?; + } + Ok(url) +} + +/// Opens `raw` with the system's default handler, when +/// [`validate_external_url`] accepts it. What is opened is the serialized +/// URL, never `raw` itself. +pub fn open_url(raw: &str) -> Result<(), OpenError> { + let url = validate_external_url(raw).map_err(OpenError::Rejected)?; + launch(url.as_str()).map_err(OpenError::Launch) +} + +/// Why a path isn't opened or revealed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PathRefused { + /// A Windows network (`\\server\share`, `\\?\UNC\…`) or device (`\\.\…`) + /// path: looking at one signs in to the host. + NetworkOrDevice, + /// Not an absolute path. + Relative, + /// It can't be resolved: it doesn't exist, or can't be read (why). + Unresolvable(String), + /// Opened from the UI, it is neither a folder nor a file with one of the + /// [`DOCUMENT_EXTENSIONS`]. + NotDocumentOrFolder, + /// Under WSL, a character PowerShell acts on. + UnsafeCharacter(char), + /// On macOS, an app bundle or another package, which `open` launches. + Package, +} + +impl fmt::Display for PathRefused { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NetworkOrDevice => write!(f, "it is a network or device path"), + Self::Relative => write!(f, "it isn't an absolute path"), + Self::Unresolvable(error) => write!(f, "it can't be resolved ({error})"), + Self::NotDocumentOrFolder => write!(f, "it is neither a folder nor a document"), + Self::UnsafeCharacter(c) => { + write!(f, "it holds a character that isn't allowed here: {c:?}") + } + Self::Package => write!(f, "it is an application or another package"), + } + } +} + +impl std::error::Error for PathRefused {} + +impl From for io::Error { + fn from(refused: PathRefused) -> Self { + let kind = match refused { + PathRefused::Unresolvable(_) => io::ErrorKind::NotFound, + _ => io::ErrorKind::InvalidInput, + }; + io::Error::new(kind, format!("this path can't be opened: {refused}")) + } +} + +/// Why opening a path from the UI failed. +#[derive(Debug)] +pub enum OpenPathError { + /// The path was refused, so nothing was launched. + Refused(PathRefused), + /// The system couldn't open it. + Launch(io::Error), +} + +impl fmt::Display for OpenPathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Refused(refused) => write!(f, "this path can't be opened: {refused}"), + Self::Launch(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for OpenPathError {} + +/// Opens a file or folder the app chose itself (the logs folder, its own +/// config file) with the system's default handler. `path` must be absolute: +/// a relative one would be resolved against the working directory. +pub fn open_path(path: &Path) -> io::Result<()> { + let target = checked_path(path, Check::AppChosen, PathRules::current(), &SystemFs)?; + launch(target.as_os_str()) +} + +/// Opens a folder, or a file with one of the [`DOCUMENT_EXTENSIONS`], that +/// the UI asks for (`shell_open_path`), with the system's default handler. +pub fn open_ui_path(path: &Path) -> Result<(), OpenPathError> { + let target = checked_path(path, Check::FromUi, PathRules::current(), &SystemFs) + .map_err(OpenPathError::Refused)?; + launch(target.as_os_str()).map_err(OpenPathError::Launch) +} + +/// The path of an existing item to show, selected, in the file manager +/// (`shell_show_item_in_folder`). Nothing is launched: a fallback that opens +/// its folder goes through [`open_path`]. +pub fn path_to_reveal(path: &Path) -> Result { + checked_path(path, Check::Reveal, PathRules::current(), &SystemFs) +} + +/// Extensions of the files the UI may open (`shell_open_path`), compared +/// case-insensitively: the documents and config files the Library lists +/// (`.md` and Cursor's `.mdc` rules, `.toml`, `.json`, `.yaml`, OpenCode's +/// `.ts` plugin hooks) and a few plain-text kinds. Nothing Windows runs: +/// ShellExecute starts executables, scripts and shortcuts. +pub const DOCUMENT_EXTENSIONS: [&str; 11] = [ + "md", "markdown", "mdc", "txt", "json", "jsonc", "yaml", "yml", "toml", "log", "ts", +]; + +/// Extensions of the macOS packages `/usr/bin/open` launches instead of +/// showing (application bundles, plug-ins, installers), compared +/// case-insensitively. +pub const MACOS_PACKAGE_EXTENSIONS: [&str; 16] = [ + "app", + "appex", + "bundle", + "framework", + "plugin", + "prefpane", + "kext", + "pkg", + "mpkg", + "xpc", + "qlgenerator", + "mdimporter", + "saver", + "service", + "action", + "workflow", +]; + +/// Whether `path`, read as a Windows path, is a network path +/// (`\\server\share…`, `//server/share…`, `\\?\UNC\…`) or a device path +/// (`\\.\…`, any other `\\?\` path, an NT `\??\` path). That is any path +/// starting with two separators, except a verbatim local disk path +/// (`\\?\C:\…`). On Windows, looking at such a path, even to check that it +/// exists, can sign in to its host over SMB and hand it the user's NTLM +/// hash; Explorer and ShellExecute connect the same way. A string helper, so +/// it is tested on every platform; the checks apply it on Windows. +pub fn is_windows_network_or_device_path(path: &str) -> bool { + let separator = |b: &u8| matches!(b, b'\\' | b'/'); + match path.as_bytes() { + [first, b'?', b'?', fourth, ..] if separator(first) && separator(fourth) => true, + [first, second, ..] if separator(first) && separator(second) => { + !is_verbatim_disk_path(path) + } + _ => false, + } +} + +/// Whether `path` is a verbatim local disk path: `\\?\`, a drive letter and +/// `:`, then nothing or `\`. +fn is_verbatim_disk_path(path: &str) -> bool { + path.strip_prefix(r"\\?\") + .is_some_and(|rest| match rest.as_bytes() { + [drive, b':'] => drive.is_ascii_alphabetic(), + [drive, b':', b'\\', ..] => drive.is_ascii_alphabetic(), + _ => false, + }) +} + +/// Whether `path`'s last component has one of the +/// [`MACOS_PACKAGE_EXTENSIONS`]: on macOS, `open` would launch it. +pub fn is_macos_package(path: &Path) -> bool { + path.extension() + .and_then(OsStr::to_str) + .is_some_and(|extension| { + MACOS_PACKAGE_EXTENSIONS + .iter() + .any(|package| package.eq_ignore_ascii_case(extension)) + }) +} + +/// Whether a path is refused because the app runs under WSL (`is_wsl`): +/// `open::that` hands it to `wslview` there, which resolves it and pastes it +/// into PowerShell's `Start ""`. A path holding a character that would +/// end that string or act inside it ([`powershell_character`]) is refused. +/// The checks apply it to the resolved path, which is what wslview pastes. +pub fn refused_under_wsl(path: &Path, is_wsl: bool) -> bool { + is_wsl && powershell_character(path).is_some() +} + +/// The first character of `path` that PowerShell acts on inside a +/// double-quoted string: a double quote, or a typographic quote it reads as +/// one (U+201C, U+201D, U+201E), a backtick, a `$` (`$(…)` runs, `$env:X` +/// expands), or a control character. +fn powershell_character(path: &Path) -> Option { + path.to_string_lossy().chars().find(|c| { + matches!(c, '"' | '\u{201C}' | '\u{201D}' | '\u{201E}' | '`' | '$') || c.is_control() + }) +} + +/// Whether `path` names a file with one of the [`DOCUMENT_EXTENSIONS`]. +fn has_document_extension(path: &Path) -> bool { + path.extension() + .and_then(OsStr::to_str) + .is_some_and(|extension| { + DOCUMENT_EXTENSIONS + .iter() + .any(|document| document.eq_ignore_ascii_case(extension)) + }) +} + +/// What a path is checked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Check { + /// A file or folder the app chose itself ([`open_path`]). + AppChosen, + /// A folder or document the UI asks for ([`open_ui_path`]). + FromUi, + /// An item to show in the file manager ([`path_to_reveal`]). + Reveal, +} + +/// The platform rules a path is checked against. +#[derive(Debug, Clone, Copy, Default)] +struct PathRules { + /// Windows: network and device paths are refused. + windows: bool, + /// macOS: packages are refused. + macos: bool, + /// WSL: characters PowerShell acts on are refused. + wsl: bool, +} + +impl PathRules { + /// The rules of the platform the app runs on. + fn current() -> Self { + Self { + windows: cfg!(windows), + macos: cfg!(target_os = "macos"), + wsl: running_under_wsl(), + } + } +} + +/// What a resolved path is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + Folder, + File, + Other, +} + +/// The filesystem as the checks use it, so tests can see which calls run. +trait PathFs { + /// `path` with its symlinks and `..` resolved: on Windows without the + /// `\\?\` prefix, which the shell doesn't take. + fn resolve(&self, path: &Path) -> io::Result; + /// What the resolved `path` is. + fn kind(&self, path: &Path) -> io::Result; +} + +/// The real filesystem. +struct SystemFs; + +impl PathFs for SystemFs { + fn resolve(&self, path: &Path) -> io::Result { + fleetify_core::canonicalize_no_verbatim(path) + } + + fn kind(&self, path: &Path) -> io::Result { + let metadata = std::fs::metadata(path)?; + Ok(if metadata.is_dir() { + Kind::Folder + } else if metadata.is_file() { + Kind::File + } else { + Kind::Other + }) + } +} + +/// The path to open (or reveal) for `path`, or why it isn't opened: +/// +/// 1. On Windows, a network or device path is refused as given, before +/// anything touches the filesystem: resolving it would already sign in to +/// its host. It must also be absolute. +/// 2. It is resolved: symlinks and `..` (`fs.resolve`). +/// 3. What it resolved to is checked, so a symlink is judged by where it +/// leads: for a path from the UI, a folder or a document extension; for +/// anything launched, the macOS package and WSL rules. (The resolved path +/// isn't checked for a network path: a mapped network drive resolves to +/// its share, and resolving has already made any connection.) +/// 4. The resolved path is returned: it is what gets opened, never `path`. +fn checked_path( + path: &Path, + check: Check, + rules: PathRules, + fs: &impl PathFs, +) -> Result { + if rules.windows && is_windows_network_or_device_path(&path.to_string_lossy()) { + return Err(PathRefused::NetworkOrDevice); + } + if !path.is_absolute() { + return Err(PathRefused::Relative); + } + let resolved = fs + .resolve(path) + .map_err(|error| PathRefused::Unresolvable(error.to_string()))?; + if check == Check::FromUi { + match fs.kind(&resolved) { + Ok(Kind::Folder) => {} + Ok(Kind::File) if has_document_extension(&resolved) => {} + _ => return Err(PathRefused::NotDocumentOrFolder), + } + } + // Revealing selects the item in the file manager and launches nothing; + // a fallback that opens its folder goes through `open_path`. + if check != Check::Reveal { + if rules.macos && is_macos_package(&resolved) { + return Err(PathRefused::Package); + } + if rules.wsl { + if let Some(c) = powershell_character(&resolved) { + return Err(PathRefused::UnsafeCharacter(c)); + } + } + } + Ok(resolved) +} + +/// Whether the app runs under WSL, decided the way `open::that` decides to +/// try `wslview` (`is_wsl::is_wsl`, in open 5.3.5's `unix.rs`). +fn running_under_wsl() -> bool { + #[cfg(target_os = "linux")] + { + is_wsl::is_wsl() + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +/// The one call into the system opener. On Windows, `ShellExecuteExW` +/// (`that_detached` with `shellexecute-on-windows`), never `cmd`. Elsewhere +/// `open::that`, which reports a launcher's failed exit status. +#[allow(clippy::disallowed_methods)] +fn launch(target: impl AsRef) -> io::Result<()> { + #[cfg(windows)] + { + open::that_detached(target) + } + #[cfg(not(windows))] + { + open::that(target) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The links an app link opener must open: web pages and mail. + const ACCEPTED: [&str; 3] = [ + "https://example.com/a?b=c#d", + "http://localhost:5173/", + "mailto:hello@example.com", + ]; + + #[test] + fn web_and_mail_links_are_accepted_and_opened_as_serialized() { + for raw in ACCEPTED { + let url = validate_external_url(raw).unwrap_or_else(|e| panic!("{raw}: {e}")); + assert_eq!(url.as_str(), raw); + } + } + + #[test] + fn other_schemes_and_non_urls_are_rejected() { + for raw in [ + "javascript:alert(1)", + "file:///C:/Windows/System32/calc.exe", + "data:text/html,x", + "vbscript:x", + "ms-msdt:/id x", + "search-ms:query=x", + r"\\server\share\x.exe", + r"C:\Windows\System32\calc.exe", + "calc", + "", + ] { + assert!( + validate_external_url(raw).is_err(), + "{raw:?} was accepted as {:?}", + validate_external_url(raw).map(|url| url.to_string()) + ); + } + } + + #[test] + fn a_quote_that_reaches_the_serialized_url_is_rejected() { + // The N1 payload: host parsing keeps `"` and `&`, so on Windows + // `cmd /c start "" ""` would end the quoting and run calc. + let payload = "https://x%22&calc.exe&%22y.com/"; + assert_eq!( + validate_external_url(payload), + Err(UrlRejected::UnsafeCharacter('"')), + "{payload}" + ); + for raw in ["https://x\"y.com/", "mailto:\"evil\"@example.com"] { + assert_eq!( + validate_external_url(raw), + Err(UrlRejected::UnsafeCharacter('"')), + "{raw}" + ); + } + } + + #[test] + fn a_quote_the_parser_percent_encodes_is_harmless() { + // In the path, query and fragment the parser writes `%22`: the + // string handed to the opener holds no quote at all. + let url = validate_external_url("https://example.com/a\"b?c=\"d\"#\"e").unwrap(); + assert!(!url.as_str().contains('"'), "{url}"); + } + + #[test] + fn whitespace_and_control_characters_never_reach_the_opener() { + // The parser drops tabs and newlines, and percent-encodes spaces in + // paths; whatever comes back must hold none of them. + for raw in [ + "https://example.com/a\nb", + "https://example.com/a\tb", + "https://example.com/a\r\nb", + "https://example.com/a b", + " https://example.com/ ", + "mailto:a b@example.com", + "mailto:a\u{7f}b@example.com", + ] { + if let Ok(url) = validate_external_url(raw) { + assert!( + !url.as_str() + .chars() + .any(|c| c == '"' || c.is_whitespace() || c.is_control()), + "{raw:?} came back as {:?}", + url.as_str() + ); + } + } + } + + #[test] + fn a_rejected_link_is_never_launched() { + // open_url validates first: these come back Rejected, so no browser + // starts while the tests run. + for raw in ["javascript:alert(1)", "https://x%22&calc.exe&%22y.com/", ""] { + assert!( + matches!(open_url(raw), Err(OpenError::Rejected(_))), + "{raw:?}" + ); + } + } + + /// A file named `name` in `dir`, created empty. + fn file_in(dir: &Path, name: &str) -> std::path::PathBuf { + let path = dir.join(name); + std::fs::write(&path, b"").unwrap(); + path + } + + /// What `shell_open_path` would open for `path`, checked on the real + /// filesystem without any platform's rules. Nothing is launched. + fn from_ui(path: &Path) -> Result { + checked_path(path, Check::FromUi, PathRules::default(), &SystemFs) + } + + #[test] + fn a_folder_or_a_document_the_library_lists_may_be_opened_from_the_ui() { + let dir = tempfile::tempdir().unwrap(); + assert!(from_ui(dir.path()).is_ok(), "a folder"); + for name in [ + "SKILL.md", + "NOTES.MD", + "rule.mdc", + "notes.markdown", + "readme.txt", + "settings.json", + "tsconfig.jsonc", + "HOOK.yaml", + "ci.yml", + "reviewer.toml", + "fleet.log", + "plugin.ts", + ] { + let path = file_in(dir.path(), name); + assert!(from_ui(&path).is_ok(), "{name}: {:?}", from_ui(&path)); + } + } + + #[test] + fn a_program_script_shortcut_or_extensionless_file_is_not_opened_from_the_ui() { + // On Windows ShellExecute runs these: executables, scripts, shortcuts. + let dir = tempfile::tempdir().unwrap(); + for name in [ + "setup.exe", + "SETUP.EXE", + "run.bat", + "run.cmd", + "run.ps1", + "app.lnk", + "run.sh", + "handler.py", + "script.js", + "Makefile", + ] { + let path = file_in(dir.path(), name); + assert_eq!( + from_ui(&path), + Err(PathRefused::NotDocumentOrFolder), + "{name}" + ); + } + } + + #[test] + fn a_relative_or_missing_path_is_not_opened_from_the_ui() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(from_ui(Path::new("notes.md")), Err(PathRefused::Relative)); + assert_eq!(from_ui(Path::new("./docs")), Err(PathRefused::Relative)); + for missing in ["missing.md", "missing-folder"] { + assert!( + matches!( + from_ui(&dir.path().join(missing)), + Err(PathRefused::Unresolvable(_)) + ), + "{missing}" + ); + } + } + + #[test] + fn a_dollar_or_backtick_is_percent_encoded_for_powershell_under_wsl() { + // Under WSL, open::that tries wslview, which hands the URL to + // PowerShell: `$(…)` runs there and `$env:X` expands. + let url = validate_external_url("https://x.com/$(calc)").unwrap(); + assert_eq!(url.as_str(), "https://x.com/%24(calc)"); + let url = validate_external_url("https://example.com/?q=a`b#c$d").unwrap(); + assert_eq!(url.as_str(), "https://example.com/?q=a%60b#c%24d"); + let url = validate_external_url("mailto:x@example.com?subject=$env:USERNAME").unwrap(); + assert_eq!(url.as_str(), "mailto:x@example.com?subject=%24env:USERNAME"); + // The encoded form re-parses to itself, and validates to itself. + for raw in [ + "https://x.com/$(calc)", + "https://example.com/?q=a`b#c$d", + "mailto:x@example.com?subject=$env:USERNAME", + ] { + let opened = validate_external_url(raw).unwrap(); + assert_eq!( + Url::parse(opened.as_str()).unwrap().as_str(), + opened.as_str() + ); + assert_eq!(validate_external_url(opened.as_str()), Ok(opened.clone())); + } + } + + #[test] + fn a_dollar_or_backtick_in_a_host_is_refused() { + for raw in [ + "https://x$y.com/", + "https://x`y.com/", + "http://$(calc).example/", + ] { + assert!( + matches!( + validate_external_url(raw), + Err(UrlRejected::UnsafeCharacter(_)) + ), + "{raw:?} gave {:?}", + validate_external_url(raw) + ); + } + } + + #[test] + fn under_wsl_a_path_with_a_dollar_or_backtick_is_refused() { + for path in ["/home/u/$(calc).md", "/home/u/a`b.md", "/home/u/$HOME/x.md"] { + assert!(refused_under_wsl(Path::new(path), true), "{path}"); + assert!(!refused_under_wsl(Path::new(path), false), "{path}"); + } + assert!(!refused_under_wsl(Path::new("/home/u/notes.md"), true)); + } + + #[test] + fn under_wsl_a_path_that_could_end_powershells_string_is_refused() { + // wslview pastes the resolved path into `Start ""`: a double + // quote, or one of the typographic quotes PowerShell reads as one, + // ends the string; a control character has no business in a path. + for path in [ + "/home/u/x\";calc;\"/notes.md", + "/home/u/x\u{201C};calc;\u{201C}", + "/home/u/x\u{201D}y", + "/home/u/x\u{201E}y", + "/home/u/a\nb", + "/home/u/a\u{7}b", + ] { + assert!(refused_under_wsl(Path::new(path), true), "{path:?}"); + assert!(!refused_under_wsl(Path::new(path), false), "{path:?}"); + } + // Single typographic quotes and other punctuation are fine. + for path in ["/home/u/it\u{2019}s.md", "/home/u/a&b (c)#d!.md"] { + assert!(!refused_under_wsl(Path::new(path), true), "{path:?}"); + } + } + + #[test] + fn a_mail_link_may_only_fill_in_the_message() { + // Some mail clients attach the local file an `attach` field names. + for raw in [ + "mailto:x@example.com?attach=/home/u/.ssh/id_rsa", + "mailto:x@example.com?Attachment=/etc/passwd", + "mailto:x@example.com?subject=Hi&attach=x", + "mailto:x@example.com?=x", + ] { + assert!( + matches!(validate_external_url(raw), Err(UrlRejected::MailField(_))), + "{raw:?} gave {:?}", + validate_external_url(raw) + ); + } + for raw in [ + "mailto:x@example.com?subject=Hi&body=x", + "mailto:x@example.com?To=y@example.com&CC=z@example.com&bcc=w@example.com", + "mailto:x@example.com", + ] { + assert!(validate_external_url(raw).is_ok(), "{raw:?}"); + } + } + + #[test] + fn credentials_never_reach_the_browser() { + for (raw, opened) in [ + ("https://user:tok@example.com/x", "https://example.com/x"), + ("http://token@example.com/", "http://example.com/"), + ("https://:secret@example.com/a?b", "https://example.com/a?b"), + ] { + assert_eq!( + validate_external_url(raw).unwrap().as_str(), + opened, + "{raw}" + ); + } + } + + #[test] + fn a_relative_path_is_refused() { + for path in ["logs", "./mcp.json", "../x"] { + let error = open_path(Path::new(path)).expect_err(path); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput, "{path}"); + } + } + + #[test] + fn the_windows_launcher_is_shell_execute() { + // open's `shellexecute-on-windows` feature makes `that_detached` call + // ShellExecuteExW instead of `cmd /c start`. + let manifest: toml::Value = toml::from_str(include_str!("../Cargo.toml")).unwrap(); + let open = &manifest["dependencies"]["open"]; + let features = open + .get("features") + .and_then(toml::Value::as_array) + .unwrap_or_else(|| panic!("open has no features: {open}")); + assert!( + features + .iter() + .any(|feature| feature.as_str() == Some("shellexecute-on-windows")), + "{open}" + ); + } + + #[test] + fn a_mail_link_with_a_semicolon_in_its_fields_is_refused() { + // Some mail clients split fields on `;` as well as `&`. + for raw in [ + "mailto:a@example.com?subject=x;attach=/etc/passwd", + "mailto:a@example.com?subject=Hi&body=a;attach=/etc/passwd", + "mailto:a@example.com?;attach=/etc/passwd", + ] { + assert_eq!( + validate_external_url(raw), + Err(UrlRejected::MailSemicolon), + "{raw}" + ); + } + // An encoded semicolon is text in a value, whoever splits. + assert!(validate_external_url("mailto:a@example.com?subject=a%3Bb").is_ok()); + } + + // ── Paths: resolve, check what they resolve to, launch that ── + + /// Windows network and device paths, in the forms the launchers refuse. + const NETWORK_OR_DEVICE: [&str; 13] = [ + r"\\server\share\notes.md", + r"\\server\share", + "//server/share/notes.md", + r"\/server/share\notes.md", + r"/\server\share\notes.md", + r"\\localhost\C$\Users\u\notes.md", + r"\\?\UNC\server\share\notes.md", + r"\\?\unc\server\share\notes.md", + r"\\.\pipe\x", + r"\\.\C:\Users\u\notes.md", + r"\\?\GLOBALROOT\Device\Mup\server\share\notes.md", + r"\\?\Volume{0a1b2c3d-0000-0000-0000-000000000000}\notes.md", + r"\??\UNC\server\share\notes.md", + ]; + + #[test] + fn windows_network_and_device_paths_are_told_from_local_ones() { + for path in NETWORK_OR_DEVICE { + assert!(is_windows_network_or_device_path(path), "{path}"); + } + for path in [ + r"C:\Users\u\notes.md", + "C:/Users/u/notes.md", + r"c:\notes.md", + r"\\?\C:\Users\u\notes.md", + r"\\?\d:\notes.md", + r"\\?\C:", + "C:notes.md", + r"notes\x.md", + r"\Users\u\notes.md", + "/home/u/notes.md", + ] { + assert!(!is_windows_network_or_device_path(path), "{path}"); + } + } + + /// An absolute path on the platform the tests run on. + fn abs(path: &str) -> PathBuf { + if cfg!(windows) { + PathBuf::from(format!(r"C:\{}", path.replace('/', r"\"))) + } else { + PathBuf::from(format!("/{path}")) + } + } + + /// A filesystem where each `(path, resolved, kind)` entry resolves `path` + /// to `resolved`, which is a `kind`. Nothing else exists. + struct FakeFs(Vec<(PathBuf, PathBuf, Kind)>); + + impl PathFs for FakeFs { + fn resolve(&self, path: &Path) -> io::Result { + self.0 + .iter() + .find(|(given, ..)| given == path) + .map(|(_, resolved, _)| resolved.clone()) + .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such file")) + } + + fn kind(&self, path: &Path) -> io::Result { + self.0 + .iter() + .find(|(_, resolved, _)| resolved == path) + .map(|(.., kind)| *kind) + .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such file")) + } + } + + /// A filesystem the checks must not touch. + struct Untouchable; + + impl PathFs for Untouchable { + fn resolve(&self, path: &Path) -> io::Result { + panic!("{path:?} was resolved before it was refused") + } + + fn kind(&self, path: &Path) -> io::Result { + panic!("{path:?} was looked at before it was refused") + } + } + + const CHECKS: [Check; 3] = [Check::AppChosen, Check::FromUi, Check::Reveal]; + + fn windows() -> PathRules { + PathRules { + windows: true, + ..PathRules::default() + } + } + + #[test] + fn on_windows_a_network_path_is_refused_before_anything_looks_at_it() { + // Resolving it, or even checking that it exists, signs in to the host + // over SMB, which hands it the user's NTLM hash. + for check in CHECKS { + for path in NETWORK_OR_DEVICE { + assert_eq!( + checked_path(Path::new(path), check, windows(), &Untouchable), + Err(PathRefused::NetworkOrDevice), + "{check:?} {path}" + ); + } + } + } + + #[test] + fn on_windows_a_mapped_network_drive_still_opens() { + // `Z:\…` on a drive the user mapped resolves to its share's UNC path. + // Only a network path given as one is refused: by the time a path + // has resolved, any connection has been made. + let fs = FakeFs(vec![( + abs("p/notes.md"), + PathBuf::from(r"\\nas\projects\notes.md"), + Kind::File, + )]); + for check in CHECKS { + assert_eq!( + checked_path(&abs("p/notes.md"), check, windows(), &fs), + Ok(PathBuf::from(r"\\nas\projects\notes.md")), + "{check:?}" + ); + } + } + + #[test] + fn the_resolved_path_is_checked_and_is_what_gets_opened() { + let fs = FakeFs(vec![ + (abs("p/notes.md"), abs("p/notes.md"), Kind::File), + // Document-named symlinks: to a script, and to a document. + (abs("p/readme.md"), abs("p/run.bat"), Kind::File), + (abs("p/latest.md"), abs("p/v2/notes.md"), Kind::File), + // A symlink to a folder. + (abs("p/docs"), abs("shared/docs"), Kind::Folder), + ]); + let rules = PathRules::default(); + let check = |path: &str, check| checked_path(&abs(path), check, rules, &fs); + assert_eq!( + check("p/readme.md", Check::FromUi), + Err(PathRefused::NotDocumentOrFolder) + ); + assert_eq!( + check("p/latest.md", Check::FromUi), + Ok(abs("p/v2/notes.md")) + ); + assert_eq!(check("p/docs", Check::FromUi), Ok(abs("shared/docs"))); + assert_eq!(check("p/notes.md", Check::FromUi), Ok(abs("p/notes.md"))); + // The app's own paths and revealed items are resolved too. + assert_eq!( + check("p/latest.md", Check::AppChosen), + Ok(abs("p/v2/notes.md")) + ); + assert_eq!(check("p/readme.md", Check::Reveal), Ok(abs("p/run.bat"))); + } + + #[test] + fn macos_packages_are_told_from_folders() { + for name in [ + "Evil.app", + "EVIL.APP", + "x.appex", + "x.bundle", + "Foo.framework", + "x.plugin", + "x.prefpane", + "x.kext", + "Setup.pkg", + "x.mpkg", + "x.xpc", + "x.qlgenerator", + "x.mdimporter", + "x.saver", + "x.service", + "x.action", + "x.workflow", + ] { + assert!(is_macos_package(&abs(&format!("p/{name}"))), "{name}"); + } + for name in [ + "project", "my-app", "app", "notes.md", "x.app.md", "Contents", + ] { + assert!(!is_macos_package(&abs(&format!("p/{name}"))), "{name}"); + } + } + + #[test] + fn on_macos_a_path_that_resolves_to_a_package_is_never_launched() { + // `open ` launches an app bundle, and a git checkout of one + // carries no quarantine flag. A symlink is resolved first. + let fs = FakeFs(vec![ + (abs("p/Evil.app"), abs("p/Evil.app"), Kind::Folder), + (abs("p/project"), abs("p/Evil.app"), Kind::Folder), + ( + abs("p/Evil.app/Contents"), + abs("p/Evil.app/Contents"), + Kind::Folder, + ), + ]); + let macos = PathRules { + macos: true, + ..PathRules::default() + }; + for check in [Check::AppChosen, Check::FromUi] { + for path in ["p/Evil.app", "p/project"] { + assert_eq!( + checked_path(&abs(path), check, macos, &fs), + Err(PathRefused::Package), + "{check:?} {path}" + ); + } + // A folder inside a package opens as a folder. + assert!(checked_path(&abs("p/Evil.app/Contents"), check, macos, &fs).is_ok()); + } + // Revealing selects it in Finder (`open -R`), which launches nothing. + assert_eq!( + checked_path(&abs("p/project"), Check::Reveal, macos, &fs), + Ok(abs("p/Evil.app")) + ); + // Elsewhere it is a folder like any other. + assert!(checked_path(&abs("p/Evil.app"), Check::FromUi, PathRules::default(), &fs).is_ok()); + } + + #[test] + fn under_wsl_the_resolved_path_is_the_one_that_must_be_safe() { + // wslview resolves the path (`readlink -f`) before it pastes it into + // PowerShell: a clean name that resolves to a quoted folder is + // refused, like the quoted folder itself. + let quoted = abs("p/x\";calc;\""); + let fs = FakeFs(vec![ + (quoted.clone(), quoted.clone(), Kind::Folder), + (abs("p/clean"), quoted.clone(), Kind::Folder), + (abs("p/notes.md"), abs("p/notes.md"), Kind::File), + ]); + let wsl = PathRules { + wsl: true, + ..PathRules::default() + }; + for check in [Check::AppChosen, Check::FromUi] { + for path in [quoted.clone(), abs("p/clean")] { + assert_eq!( + checked_path(&path, check, wsl, &fs), + Err(PathRefused::UnsafeCharacter('"')), + "{check:?} {path:?}" + ); + } + assert!(checked_path(&abs("p/notes.md"), check, wsl, &fs).is_ok()); + } + } + + #[cfg(unix)] + #[test] + fn a_symlink_is_judged_by_where_it_leads() { + use std::os::unix::fs::symlink; + let dir = tempfile::tempdir().unwrap(); + let script = file_in(dir.path(), "run.sh"); + let notes = file_in(dir.path(), "notes.md"); + symlink(&script, dir.path().join("readme.md")).unwrap(); + symlink(¬es, dir.path().join("latest.md")).unwrap(); + assert_eq!( + from_ui(&dir.path().join("readme.md")), + Err(PathRefused::NotDocumentOrFolder) + ); + assert_eq!( + from_ui(&dir.path().join("latest.md")), + Ok(std::fs::canonicalize(¬es).unwrap()) + ); + } +} diff --git a/crates/fleetify-backend/src/routers/chat.rs b/crates/fleetify-backend/src/routers/chat.rs index 4851e29..cf82b35 100644 --- a/crates/fleetify-backend/src/routers/chat.rs +++ b/crates/fleetify-backend/src/routers/chat.rs @@ -2179,18 +2179,7 @@ async fn run_send_flow( opened_in_browser: _, } = &ev { - let opened = match ::open::that(url) { - Ok(_) => true, - Err(e) => { - tracing::warn!( - provider = %provider, - url = %url, - error = %e, - "open browser for auth URL failed; renderer falls back to clickable link" - ); - false - } - }; + let opened = open_auth_url(provider, url); BridgeEvent::AuthRequired { provider: provider.clone(), url: url.clone(), @@ -3626,18 +3615,7 @@ async fn run_dispatched_task( opened_in_browser: _, } = &ev { - let opened = match ::open::that(url) { - Ok(_) => true, - Err(e) => { - tracing::warn!( - provider = %provider, - url = %url, - error = %e, - "open browser for auth URL failed; renderer falls back to clickable link" - ); - false - } - }; + let opened = open_auth_url(provider, url); BridgeEvent::AuthRequired { provider: provider.clone(), url: url.clone(), @@ -4146,11 +4124,43 @@ fn push_text(content: &mut Vec, kind: &str, chunk: &str) { content.push(json!({"type": kind, "text": chunk})); } +/// Opens a provider's sign-in URL (`AuthRequired`) in the browser. False +/// when that failed, so the renderer's info card shows the link to click +/// instead. The URL comes from the provider CLI's output: `open_external` +/// refuses anything but a clean web or email link. +fn open_auth_url(provider: &str, url: &str) -> bool { + match crate::open_external::open_url(url) { + Ok(()) => true, + Err(e) => { + tracing::warn!( + provider = %provider, + url = %url, + error = %e, + "open browser for auth URL failed; renderer falls back to clickable link" + ); + false + } + } +} + #[cfg(test)] mod tests { use super::*; use crate::db::init_pool; + #[test] + fn an_auth_url_from_a_provider_cli_that_isnt_a_web_link_is_not_opened() { + // The renderer then shows the link to click. Refused before anything + // is launched: no browser starts here. + for url in [ + "javascript:alert(1)", + "file:///C:/Windows/System32/calc.exe", + "https://x%22&calc.exe&%22y.com/", + ] { + assert!(!open_auth_url("gemini", url), "{url:?}"); + } + } + async fn fresh_pool() -> sqlx::SqlitePool { init_pool("sqlite::memory:").await.expect("init_pool") } diff --git a/crates/fleetify-backend/src/routers/mcp.rs b/crates/fleetify-backend/src/routers/mcp.rs index e25f406..7fc863c 100644 --- a/crates/fleetify-backend/src/routers/mcp.rs +++ b/crates/fleetify-backend/src/routers/mcp.rs @@ -134,7 +134,7 @@ async fn config_path() -> Json { async fn open_config() -> Json { let p = mcp_registry::registry_path(); - match open::that(&p) { + match crate::open_external::open_path(&p) { Ok(_) => Json(json!({ "ok": true })), Err(e) => Json(json!({ "ok": false, "error": e.to_string() })), } diff --git a/crates/fleetify-backend/src/services/mcp_registry.rs b/crates/fleetify-backend/src/services/mcp_registry.rs index 9b62beb..7d5ffde 100644 --- a/crates/fleetify-backend/src/services/mcp_registry.rs +++ b/crates/fleetify-backend/src/services/mcp_registry.rs @@ -162,10 +162,7 @@ pub fn purge_legacy_builtin_seeds() { .get("builtin") .and_then(|v| v.as_bool()) .unwrap_or(false); - if is_builtin_seed && FLEET_BUILTIN_NAMES.contains(&name.as_str()) { - return false; - } - true + !(is_builtin_seed && FLEET_BUILTIN_NAMES.contains(&name.as_str())) }); if doc.mcp_servers.len() != before { tracing::info!( diff --git a/crates/fleetify-backend/src/services/plugins/icons.rs b/crates/fleetify-backend/src/services/plugins/icons.rs index b42c3e3..90b9090 100644 --- a/crates/fleetify-backend/src/services/plugins/icons.rs +++ b/crates/fleetify-backend/src/services/plugins/icons.rs @@ -10,13 +10,43 @@ //! rewrites `icon` to a `data:` URI (already allowed by the CSP's `img-src`). //! The WebView makes no third-party request at all, and icons survive offline. //! -//! Everything here is best-effort: any failure leaves `icon` untouched. +//! The rule that keeps it so: once [`inline_all`] returns, every `icon` is a +//! `data:` URI or `None`, never a URL. An icon that is not inlined shows an +//! expired cached copy if there is one; otherwise it is dropped, and the +//! renderer draws its fallback glyph. The URL is never the fallback. The +//! WebView would load it itself, with its own DNS and with any cookies for +//! the host, and follow any redirect, since the CSP lets it load any https +//! image. A host can fail the backend's fetch on purpose, telling the backend +//! apart by its User-Agent, and then send the WebView to an internal address +//! the backend would never dial. +//! +//! A catalog load fetches each distinct icon URL once, a few at a time, and +//! waits at most `INLINE_BUDGET` for them. An icon still downloading then +//! shows an expired cached copy, or nothing, for that load, and the download +//! goes on to fill the cache for the next one. +//! +//! Manifests are third-party input, so the fetch is fenced in. The client +//! dials only addresses `is_public_ip` accepts, vetted inside its own DNS +//! resolver so nothing is checked first and resolved again later. It never +//! uses a proxy and never follows a redirect, and a URL that just failed is +//! left alone for `FAILURE_TTL` instead of stalling every catalog load. A URL +//! whose host the resolver refused is left alone as long, without a lookup. +//! +//! One residual risk: a NAT64 network-specific prefix (RFC 6052) cannot be +//! told apart from ordinary global unicast, so on a network that translates +//! one, a name can still reach an internal IPv4 address through it. -use std::net::IpAddr; +use std::collections::HashMap; +use std::future::Future; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::path::{Path, PathBuf}; -use std::time::{Duration, SystemTime}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, LazyLock}; +use std::time::{Duration, Instant, SystemTime}; use base64::Engine; +use parking_lot::Mutex; +use reqwest::dns::{Addrs, Name, Resolve, Resolving}; use sha2::{Digest, Sha256}; use super::types::PluginManifest; @@ -24,8 +54,17 @@ use super::types::PluginManifest; /// Icons are tiny; anything bigger is not an icon. const MAX_ICON_BYTES: usize = 256 * 1024; const FETCH_TIMEOUT: Duration = Duration::from_secs(8); +/// A lookup still unanswered by now is not worth the rest of `FETCH_TIMEOUT`. +const DNS_TIMEOUT: Duration = Duration::from_secs(3); /// Icons change far less often than the catalog that references them. const CACHE_TTL: Duration = Duration::from_secs(7 * 24 * 3600); +/// How long a URL whose fetch failed is skipped before it is tried again. +const FAILURE_TTL: Duration = Duration::from_secs(600); +/// Most icon fetches one catalog load runs at once. +const ICON_CONCURRENCY: usize = 8; +/// How long a catalog load waits for its icons. A fetch still running then +/// finishes in the background and fills the cache for the next load. +const INLINE_BUDGET: Duration = Duration::from_secs(3); const ALLOWED_MIME: &[&str] = &[ "image/svg+xml", @@ -41,16 +80,18 @@ fn cache_dir() -> PathBuf { .join("icons") } -/// The URL to fetch for a manifest `icon`, or `None` when it must be left -/// alone: already inline, not https, or pointed somewhere a third-party +/// The URL to fetch for a manifest `icon`, or `None` when it must not be +/// fetched: already inline, not https, or pointed somewhere a third-party /// manifest has no business sending the backend (credentials, IP literals, -/// local names). +/// local names). Apart from an inline icon, such an icon is then dropped. pub fn fetch_target(icon: &str) -> Option { let url = reqwest::Url::parse(icon.trim()).ok()?; if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() { return None; } - let host = url.host_str()?.to_ascii_lowercase(); + // Without the root dot: `localhost.` is `localhost`, and `printer.` a + // single label, however the URL spelled that dot. + let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase(); // IP literals are refused outright; names are vetted again after DNS. if host .trim_matches(|c| c == '[' || c == ']') @@ -76,32 +117,188 @@ pub fn is_public_ip(ip: IpAddr) -> bool { match ip { IpAddr::V4(v4) => { let o = v4.octets(); + let this_network = o[0] == 0; // 0.0.0.0/8, incl. 0.0.0.0 let cgnat = o[0] == 100 && (o[1] & 0xc0) == 64; // 100.64.0.0/10 + let ietf_protocol = o[..3] == [192, 0, 0]; // 192.0.0.0/24 + let benchmarking = o[0] == 198 && (o[1] & 0xfe) == 18; // 198.18.0.0/15 + let reserved = o[0] >= 240; // 240.0.0.0/4, incl. 255.255.255.255 !(v4.is_loopback() || v4.is_private() || v4.is_link_local() - || v4.is_unspecified() - || v4.is_broadcast() || v4.is_multicast() || v4.is_documentation() - || cgnat) + || this_network + || cgnat + || ietf_protocol + || benchmarking + || reserved) } IpAddr::V6(v6) => { - if let Some(v4) = v6.to_ipv4_mapped() { + if v6.is_loopback() || v6.is_unspecified() { + return false; + } + // An address that carries an IPv4 one can end up at that IPv4 + // address, so the IPv4 address decides. + if let Some(v4) = embedded_ipv4(v6) { return is_public_ip(IpAddr::V4(v4)); } - let head = v6.segments()[0]; - let unique_local = (head & 0xfe00) == 0xfc00; // fc00::/7 - let link_local = (head & 0xffc0) == 0xfe80; // fe80::/10 - !(v6.is_loopback() - || v6.is_unspecified() - || v6.is_multicast() - || unique_local - || link_local) + // Only global unicast can be a public host. Multicast, fc00::/7, + // fe80::/10, fec0::/10 and every other special block fall + // outside 2000::/3. Inside it, 2001::/23 and the documentation + // ranges 2001:db8::/32 and 3fff::/20 are carved out. + let s = v6.segments(); + let global_unicast = (s[0] & 0xe000) == 0x2000; // 2000::/3 + let ietf = s[0] == 0x2001 && s[1] < 0x0200; // 2001::/23 + let docs = (s[0] == 0x2001 && s[1] == 0x0db8) || (s[0] == 0x3fff && s[1] < 0x1000); + global_unicast && !ietf && !docs + } + } +} + +/// The IPv4 address inside an IPv4-compatible (`::a.b.c.d`), IPv4-mapped +/// (`::ffff:a.b.c.d`), 6to4 (`2002:aabb:ccdd::/48`) or NAT64 +/// (`64:ff9b::a.b.c.d`) address. +fn embedded_ipv4(v6: Ipv6Addr) -> Option { + let v4 = |hi: u16, lo: u16| Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo)); + match v6.segments() { + [0x2002, hi, lo, ..] => Some(v4(hi, lo)), + [0x64, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(v4(hi, lo)), + // The IPv4-compatible and the IPv4-mapped forms. + _ => v6.to_ipv4(), + } +} + +/// `addrs` unchanged when every one is public, otherwise an error. All or +/// nothing: a name that answers with a private address next to public ones +/// is pointing somewhere it should not. +pub(crate) fn public_only(addrs: Vec) -> Result, NonPublicAddress> { + if addrs.is_empty() { + Err(NonPublicAddress) + } else if addrs.iter().all(|a| is_public_ip(a.ip())) { + Ok(addrs) + } else { + Err(NonPublicAddress) + } +} + +/// [`public_only`]'s refusal: the icon host resolves to no address at all, +/// or to one [`is_public_ip`] refuses. Unlike a lookup that fails or times +/// out, this is the policy saying no, and it is remembered as a refusal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct NonPublicAddress; + +impl std::fmt::Display for NonPublicAddress { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the icon host resolves to a non-public address, or to none") + } +} + +impl std::error::Error for NonPublicAddress {} + +/// The icon client's DNS resolver. The connector dials exactly the addresses +/// returned here, all vetted by [`public_only`], so a name cannot pass a +/// check on one answer and then be dialled on another (DNS rebinding). +pub(crate) struct PublicOnlyResolver; + +impl Resolve for PublicOnlyResolver { + fn resolve(&self, name: Name) -> Resolving { + let host = name.as_str().to_owned(); + Box::pin(vet_lookup(tokio::net::lookup_host((host, 0)))) + } +} + +/// The error type of a reqwest resolver. +type BoxError = Box; + +/// [`PublicOnlyResolver`]'s answer: the addresses `lookup` finds, if +/// [`public_only`] passes them. Only that check fails with +/// [`NonPublicAddress`]. A lookup that errors or outlasts `DNS_TIMEOUT` is +/// an ordinary error, so it counts as transient. +async fn vet_lookup(lookup: impl Future>) -> Result +where + I: Iterator, +{ + let found = tokio::time::timeout(DNS_TIMEOUT, lookup) + .await + .map_err(|_| "the icon host lookup timed out")??; + let vetted = public_only(found.collect())?; + Ok(Box::new(vetted.into_iter())) +} + +/// Whether `err` is, or wraps, [`NonPublicAddress`]. reqwest buries a +/// resolver's error a few layers down: in 0.12 that is reqwest's error, then +/// hyper-util's client error, then its connector's "dns error". The whole +/// `source()` chain is searched rather than one assumed layer. +fn is_refusal(err: &(dyn std::error::Error + 'static)) -> bool { + std::iter::successors(Some(err), |e| e.source()).any(|e| e.is::()) +} + +/// What one icon fetch came to. Only `Inlined` gives an icon to show. After +/// any other outcome the icon shows an expired cached copy, or nothing. +#[derive(Debug, PartialEq, Eq)] +pub enum Outcome { + /// The icon, as a `data:` URI. + Inlined(String), + /// The fence refused the icon's host. The host is not looked up again + /// within `FAILURE_TTL`. + Refused, + /// Anything else: a timeout, a dead host, an HTTP error or a redirect, + /// a body that is not an acceptable image. Tried again after + /// `FAILURE_TTL`. + Failed, +} + +/// The client for icon fetches. Only [`PublicOnlyResolver`] turns names into +/// addresses. There is no proxy, because a proxy would resolve the name +/// itself and dial whatever it found. +fn icon_client() -> Option { + reqwest::Client::builder() + .timeout(FETCH_TIMEOUT) + .user_agent("Fleet-Marketplace/0.1") + // A redirect could land anywhere, so an icon behind one is not inlined. + .redirect(reqwest::redirect::Policy::none()) + .no_proxy() + .dns_resolver(Arc::new(PublicOnlyResolver)) + .build() + .ok() +} + +/// URLs whose last fetch failed, and when. A dead or slow icon host then +/// costs one `FETCH_TIMEOUT` per `ttl` instead of one per catalog load. +pub(crate) struct FailureCache { + ttl: Duration, + failed: Mutex>, +} + +impl FailureCache { + fn new(ttl: Duration) -> Self { + Self { + ttl, + failed: Mutex::new(HashMap::new()), } } + + fn is_recent(&self, url: &str, now: Instant) -> bool { + self.failed + .lock() + .get(url) + .is_some_and(|&at| now.saturating_duration_since(at) < self.ttl) + } + + fn record(&self, url: &str, now: Instant) { + let mut failed = self.failed.lock(); + // Expired entries are dead weight: the map holds one TTL's worth. + failed.retain(|_, at| now.saturating_duration_since(*at) < self.ttl); + failed.insert(url.to_owned(), now); + } } +static FAILURES: LazyLock = LazyLock::new(|| FailureCache::new(FAILURE_TTL)); + +/// URLs whose host was refused, and when. Within `FAILURE_TTL` such an icon +/// counts as refused without a fetch, so not even DNS is asked again. +static REFUSALS: LazyLock = LazyLock::new(|| FailureCache::new(FAILURE_TTL)); + /// Encode a fetched body as a `data:` URI, or `None` when it is not an /// acceptable image. The content type is what rejects a 200-with-HTML block /// page as firmly as it rejects a 403. @@ -132,21 +329,39 @@ pub fn read_cached(dir: &Path, url: &str, ttl: Duration) -> Option { uri.starts_with("data:image/").then_some(uri) } +/// Numbers this process's cache temp files. With the pid in the name too, no +/// two writes share a temp file, even across processes sharing a cache dir. +static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); + pub fn write_cached(dir: &Path, url: &str, data_uri: &str) { if std::fs::create_dir_all(dir).is_err() { return; } let path = cache_path(dir, url); - let tmp = path.with_extension("tmp"); - if std::fs::write(&tmp, data_uri).is_ok() { - let _ = std::fs::rename(&tmp, &path); + // Fill a temp file of this write's own, then rename it into place. With + // one shared temp name, a writer could rename a file another writer was + // still filling, and a reader would see it half-written. + let n = TMP_COUNTER.fetch_add(1, Ordering::Relaxed); + let tmp = path.with_extension(format!("{}.{n}.tmp", std::process::id())); + if std::fs::write(&tmp, data_uri).is_err() || std::fs::rename(&tmp, &path).is_err() { + let _ = std::fs::remove_file(&tmp); } } /// Fetch one icon and encode it. Split from [`fetch_target`] so the transport /// rules can be exercised against a local server. -pub async fn fetch_data_uri(client: &reqwest::Client, url: reqwest::Url) -> Option { - let mut resp = client.get(url).send().await.ok()?; +pub async fn fetch_data_uri(client: &reqwest::Client, url: reqwest::Url) -> Outcome { + match client.get(url).send().await { + Ok(resp) => read_icon(resp) + .await + .map_or(Outcome::Failed, Outcome::Inlined), + Err(err) if is_refusal(&err) => Outcome::Refused, + Err(_) => Outcome::Failed, + } +} + +/// The icon `resp` carries, as a `data:` URI, or `None` when it is not one. +async fn read_icon(mut resp: reqwest::Response) -> Option { if !resp.status().is_success() || resp .content_length() @@ -171,69 +386,164 @@ pub async fn fetch_data_uri(client: &reqwest::Client, url: reqwest::Url) -> Opti to_data_uri(&content_type, &body) } -/// Every address the host resolves to must be public. Closes the gap -/// [`fetch_target`] cannot: a harmless-looking name pointing at 127.0.0.1. -async fn resolves_publicly(url: &reqwest::Url) -> bool { - let Some(host) = url.host_str() else { - return false; - }; - let Ok(addrs) = tokio::net::lookup_host((host, 443)).await else { - return false; - }; - let addrs: Vec<_> = addrs.collect(); - !addrs.is_empty() && addrs.iter().all(|a| is_public_ip(a.ip())) -} - -async fn inline_one(client: &reqwest::Client, dir: &Path, icon: &str) -> Option { - let url = fetch_target(icon)?; - if let Some(hit) = read_cached(dir, url.as_str(), CACHE_TTL) { - return Some(hit); +/// Fetch one icon as a `data:` URI. A URL that failed within `FAILURE_TTL` +/// is not tried again: retrying it would make every catalog load wait out +/// the same failure. +async fn inline_one(client: reqwest::Client, url: reqwest::Url) -> Outcome { + if FAILURES.is_recent(url.as_str(), Instant::now()) { + return Outcome::Failed; } - let fetched = if resolves_publicly(&url).await { - fetch_data_uri(client, url.clone()).await - } else { - None - }; - match fetched { - Some(uri) => { - write_cached(dir, url.as_str(), &uri); - Some(uri) - } - // Offline or the host is down: an expired copy still beats a blank tile. - None => read_cached(dir, url.as_str(), Duration::MAX), + let outcome = fetch_data_uri(&client, url.clone()).await; + if matches!(outcome, Outcome::Failed) { + FAILURES.record(url.as_str(), Instant::now()); } + outcome +} + +/// Whether `icon` is already inline: a `data:` URI, which loads nothing. +/// Only a literal `data:` prefix counts. With anything in front of it, the +/// WebView would read a relative URL instead. +fn is_inline(icon: &str) -> bool { + icon.starts_with("data:") } -/// Rewrite every fetchable `icon` in `manifests` to a `data:` URI, in place. +/// Rewrite every `icon` in `manifests`, in place, to a `data:` URI or to +/// `None`. No icon is left as a URL; the module docs say why. pub async fn inline_all(manifests: &mut [&mut PluginManifest]) { - inline_all_in(&cache_dir(), manifests).await; + inline_all_in(&cache_dir(), manifests, icon_client()).await; } -async fn inline_all_in(dir: &Path, manifests: &mut [&mut PluginManifest]) { - let Ok(client) = reqwest::Client::builder() - .timeout(FETCH_TIMEOUT) - .user_agent("Fleet-Marketplace/0.1") - // A redirect could land anywhere; an icon that needs one stays a URL. - .redirect(reqwest::redirect::Policy::none()) - .build() - else { - return; - }; - let jobs = manifests.iter().enumerate().filter_map(|(i, m)| { - let icon = m.icon.clone()?; - let client = &client; - Some(async move { (i, inline_one(client, dir, &icon).await) }) - }); - for (i, uri) in futures_util::future::join_all(jobs).await { - if let (Some(uri), Some(m)) = (uri, manifests.get_mut(i)) { - m.icon = Some(uri); +/// [`inline_all`] with the cache directory and the client given. Should the +/// client have failed to build, nothing is fetched, but every icon still +/// goes through [`inline_all_with`], so none is left as a URL. +async fn inline_all_in( + dir: &Path, + manifests: &mut [&mut PluginManifest], + client: Option, +) { + match client { + Some(client) => { + inline_all_with(dir, manifests, |url| inline_one(client.clone(), url)).await; } + None => inline_all_with(dir, manifests, |_| async { Outcome::Failed }).await, } } +/// [`inline_all_in`] with the fetch injected. `fetch` only ever sees a URL +/// that [`fetch_target`] accepted, that has no fresh copy in the cache and +/// whose host was not refused within `FAILURE_TTL`. +/// +/// Each distinct URL is fetched once, at most [`ICON_CONCURRENCY`] at a +/// time, and this returns when every fetch is done or [`INLINE_BUDGET`] has +/// passed. Every icon is then a `data:` URI or `None`. An icon not inlined +/// by then (refused, failed, skipped after a recent failure, or still +/// running) gets an expired cached copy if there is one and is otherwise +/// dropped. An icon [`fetch_target`] refuses is dropped, unless it is +/// already inline. The fetches run on a task of their own, so those still +/// running finish anyway and fill the cache, or [`REFUSALS`], for the next +/// load. +async fn inline_all_with(dir: &Path, manifests: &mut [&mut PluginManifest], fetch: F) +where + F: Fn(reqwest::Url) -> Fut, + Fut: Future + Send + 'static, +{ + let mut shown_by: HashMap> = HashMap::new(); + for (i, m) in manifests.iter_mut().enumerate() { + let Some(icon) = m.icon.as_deref() else { + continue; + }; + if let Some(url) = fetch_target(icon) { + shown_by.entry(url).or_default().push(i); + } else if !is_inline(icon) { + // Refused. As a URL it would send the WebView there instead. + m.icon = None; + } + } + // Catalog order, so the first icons on the page are fetched first. + let mut wanted: Vec<_> = shown_by.into_iter().collect(); + wanted.sort_unstable_by_key(|(_, at)| at[0]); + + // What each URL came to so far; `None` until its fetch reports. + let now = Instant::now(); + let mut outcomes: Vec<_> = wanted + .iter() + .map(|(url, _)| match read_cached(dir, url.as_str(), CACHE_TTL) { + Some(uri) => Some(Outcome::Inlined(uri)), + None if REFUSALS.is_recent(url.as_str(), now) => Some(Outcome::Refused), + None => None, + }) + .collect(); + let fetches: Vec<_> = wanted + .iter() + .enumerate() + .filter(|&(k, _)| outcomes[k].is_none()) + .map(|(k, (url, _))| (k, url.clone(), fetch(url.clone()))) + .collect(); + if !fetches.is_empty() { + let mut arrived = spawn_fetches(dir.to_path_buf(), fetches); + let deadline = tokio::time::Instant::now() + INLINE_BUDGET; + while let Ok(Some((k, outcome))) = tokio::time::timeout_at(deadline, arrived.recv()).await { + outcomes[k] = Some(outcome); + } + } + for ((url, at), outcome) in wanted.into_iter().zip(outcomes) { + let icon = match outcome { + Some(Outcome::Inlined(uri)) => Some(uri), + // Refused, failed, skipped or still running. An expired copy is + // local, so it may stand in; without one the icon goes. The URL + // may not: the WebView would fetch from a host that just refused, + // failed or stalled the backend, which a host can do on purpose. + Some(Outcome::Refused | Outcome::Failed) | None => { + read_cached(dir, url.as_str(), Duration::MAX) + } + }; + for i in at { + manifests[i].icon = icon.clone(); + } + } +} + +/// Run `fetches` on a task of their own, [`ICON_CONCURRENCY`] at a time, +/// caching each icon and recording each refusal as it arrives, and +/// reporting every outcome, with its slot, on the returned channel. +/// +/// The task does not stop when the caller stops listening, so a slow icon +/// still lands in the cache, and a slow refusal in [`REFUSALS`]. It ends +/// when the last fetch does, and each real fetch is bounded by +/// `FETCH_TIMEOUT`. A runtime that shuts down drops the task without polling +/// it again, which cancels the fetches; a cache write is synchronous and +/// atomic, so none is left half-done. +fn spawn_fetches( + dir: PathBuf, + fetches: Vec<(usize, reqwest::Url, Fut)>, +) -> tokio::sync::mpsc::UnboundedReceiver<(usize, Outcome)> +where + Fut: Future + Send + 'static, +{ + use futures_util::StreamExt; + + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + tokio::spawn(async move { + let mut done = futures_util::stream::iter(fetches) + .map(|(k, url, fetch)| async move { (k, url, fetch.await) }) + .buffer_unordered(ICON_CONCURRENCY); + while let Some((k, url, outcome)) = done.next().await { + match &outcome { + Outcome::Inlined(uri) => write_cached(&dir, url.as_str(), uri), + Outcome::Refused => REFUSALS.record(url.as_str(), Instant::now()), + Outcome::Failed => {} + } + // Fails only once the caller's budget has run out. + let _ = tx.send((k, outcome)); + } + }); + rx +} + #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -243,6 +553,9 @@ mod tests { fn fetch_target_accepts_a_public_https_icon() { let u = fetch_target("https://api.iconify.design/logos:asana-icon.svg").unwrap(); assert_eq!(u.host_str(), Some("api.iconify.design")); + // A fully qualified name, root dot included, is still fetchable. + let u = fetch_target("https://example.com./x.svg").unwrap(); + assert_eq!(u.host_str(), Some("example.com.")); } #[test] @@ -264,6 +577,16 @@ mod tests { "https://printer.local/icon.svg", "https://db.internal/icon.svg", "https://user:pw@api.iconify.design/x.svg", + // A trailing dot (the DNS root) names the same host. + "https://localhost./i.png", + "https://localhost../i.png", + "https://foo.localhost./i.png", + "https://nas.local./i.png", + "https://printer./i.png", + "https://router.lan./i.png", + // Spellings the URL parser turns into that dot. + "https://localhost%2e/i.png", + "https://localhost\u{3002}/i.png", ] { assert!(fetch_target(bad).is_none(), "{bad} should be refused"); } @@ -295,6 +618,187 @@ mod tests { } } + #[test] + fn is_public_ip_rejects_reserved_and_embedded_private_ranges() { + for ip in [ + "0.1.2.3", + "100.64.0.1", + "192.0.0.8", + "198.18.0.1", + "198.19.255.255", + "240.0.0.1", + "255.255.255.255", + "::127.0.0.1", + "2002:7f00:1::1", + "64:ff9b::a00:1", + "fec0::1", + ] { + assert!(!is_public_ip(ip.parse().unwrap()), "{ip} must be rejected"); + } + for ip in ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"] { + assert!(is_public_ip(ip.parse().unwrap()), "{ip} must be allowed"); + } + } + + #[test] + fn is_public_ip_judges_an_embedded_ipv4_by_that_address() { + // Each form once around public 8.8.10.0 and once around private + // 10.0.0.1. The halves differ in class, so reading the wrong + // segments flips the verdict. + for (allowed, rejected) in [ + ("::8.8.10.0", "::10.0.0.1"), + ("::ffff:8.8.10.0", "::ffff:10.0.0.1"), + ("2002:808:a00::1", "2002:a00:1::1"), + ("64:ff9b::808:a00", "64:ff9b::a00:1"), + ] { + assert!( + is_public_ip(allowed.parse().unwrap()), + "{allowed} must be allowed" + ); + assert!( + !is_public_ip(rejected.parse().unwrap()), + "{rejected} must be rejected" + ); + } + } + + #[test] + fn is_public_ip_treats_only_global_unicast_ipv6_as_public() { + // Special-purpose IPv6 beyond the embedded-IPv4 forms: local-use and + // out-of-/96 NAT64, SIIT, discard-only, 2001::/23 (Teredo, + // benchmarking), documentation and SRv6. + let rejected = [ + "64:ff9b:1::a00:1", + "64:ff9b::1:a00:1", + "::ffff:0:a00:1", + "100::1", + "100:0:0:1::1", + "2001::1", + "2001:2::1", + "2001:db8::1", + "3fff::1", + "5f00::1", + ]; + let judged_public: Vec<&str> = rejected + .into_iter() + .filter(|ip| is_public_ip(ip.parse().unwrap())) + .collect(); + assert!( + judged_public.is_empty(), + "must be rejected: {judged_public:?}" + ); + // 2001:4860:: sits just past 2001::/23: carving out the special + // ranges must not swallow their public neighbours. + for ip in ["2a00:1450::1", "2001:4860:4860::8888"] { + assert!(is_public_ip(ip.parse().unwrap()), "{ip} must be allowed"); + } + } + + #[test] + fn public_only_is_all_or_nothing() { + let p: SocketAddr = "8.8.8.8:0".parse().unwrap(); + let l: SocketAddr = "127.0.0.1:0".parse().unwrap(); + assert!(public_only(vec![]).is_err()); + assert!(public_only(vec![p, l]).is_err()); + assert_eq!(public_only(vec![p]).unwrap(), vec![p]); + } + + #[tokio::test] + async fn resolver_refuses_a_name_that_resolves_to_loopback() { + let name: reqwest::dns::Name = "localhost".parse().unwrap(); + assert!(PublicOnlyResolver.resolve(name).await.is_err()); + } + + /// A local TCP listener that counts every connection and hangs up at + /// once, so a fetch through it fails fast and each dial is observable. + async fn hang_up_listener() -> (SocketAddr, Arc) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let dials = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&dials); + tokio::spawn(async move { + while let Ok((conn, _)) = listener.accept().await { + seen.fetch_add(1, Ordering::SeqCst); + drop(conn); + } + }); + (addr, dials) + } + + /// Whether vetting `found` ended in a refusal. Panics if it was let + /// through, since every caller expects an error. + fn refused(found: Result) -> bool { + match found { + Ok(_) => panic!("the lookup was let through"), + Err(err) => is_refusal(&*err), + } + } + + /// Only an answer `public_only` rejects is a refusal. A lookup that + /// fails, or outlasts `DNS_TIMEOUT`, is transient: the icon keeps its + /// URL and is tried again later. + #[tokio::test(start_paused = true)] + async fn the_resolver_refuses_only_a_non_public_answer() { + type Found = std::vec::IntoIter; + let answer = |ip: &str| -> std::io::Result { + Ok(vec![SocketAddr::new(ip.parse().unwrap(), 0)].into_iter()) + }; + + assert!(refused(vet_lookup(async { answer("127.0.0.1") }).await)); + assert!(refused(vet_lookup(async { answer("10.0.0.1") }).await)); + let none: std::io::Result = Ok(Vec::new().into_iter()); + assert!(refused(vet_lookup(async { none }).await)); + + let failed: std::io::Result = Err(std::io::Error::other("no such host")); + assert!(!refused(vet_lookup(async { failed }).await)); + let started = tokio::time::Instant::now(); + let hung = std::future::pending::>(); + assert!(!refused(vet_lookup(hung).await)); + assert_eq!(started.elapsed(), DNS_TIMEOUT); + + let public: Vec<_> = vet_lookup(async { answer("8.8.8.8") }) + .await + .expect("a public answer passes") + .collect(); + assert_eq!(public, [SocketAddr::new("8.8.8.8".parse().unwrap(), 0)]); + } + + /// The resolver is what the icon client's connector dials through, so a + /// name that resolves to loopback never gets a connection at all. + #[tokio::test] + async fn icon_client_never_dials_a_name_that_resolves_to_loopback() { + let (addr, dials) = hang_up_listener().await; + let client = icon_client().unwrap(); + let sent = client + .get(format!("https://localhost:{}/icon.svg", addr.port())) + .send() + .await; + assert!(sent.is_err()); + assert_eq!( + dials.load(Ordering::SeqCst), + 0, + "a loopback address was dialled" + ); + } + + /// Past `fetch_target`, the resolver is the policy. Its refusal reaches + /// `inline_one` through reqwest's error, and comes back `Refused`, not + /// `Failed`, without a connection. + #[tokio::test] + async fn inline_one_reports_a_resolver_refusal_as_refused() { + let (addr, dials) = hang_up_listener().await; + // `fetch_target` would refuse this name too. `inline_one` is handed + // it directly, so the resolver is the check that refuses it. + let url = reqwest::Url::parse(&format!("https://localhost:{}/i.png", addr.port())).unwrap(); + let outcome = inline_one(icon_client().unwrap(), url).await; + assert_eq!(outcome, Outcome::Refused); + assert_eq!( + dials.load(Ordering::SeqCst), + 0, + "a loopback address was dialled" + ); + } + #[test] fn to_data_uri_encodes_an_svg() { let uri = to_data_uri("image/svg+xml; charset=utf-8", SVG).unwrap(); @@ -342,6 +846,492 @@ mod tests { assert!(read_cached(dir.path(), url, Duration::ZERO).is_none()); } + /// Writers racing on one URL must each put a whole file in place, so a + /// reader sees one complete value or another, never a prefix or a mix. + #[test] + fn write_cached_concurrent_writers_never_expose_partial_files() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let url = "https://api.iconify.design/logos:aws.svg"; + // A length and a filler of its own per writer, so a torn or + // interleaved file cannot pass for any whole value. + let values: Vec = (0..16u8) + .map(|i| { + let fill = char::from(b'A' + i).to_string(); + let body = fill.repeat((usize::from(i) + 1) * 4096); + format!("data:image/png;base64,{body}") + }) + .collect(); + let writers_done = AtomicBool::new(false); + let torn = std::thread::scope(|s| { + let reader = s.spawn(|| loop { + let finished = writers_done.load(Ordering::SeqCst); + if let Some(got) = read_cached(dir, url, CACHE_TTL) { + if !values.contains(&got) { + return Some(got.len()); + } + } + if finished { + return None; + } + }); + let writers: Vec<_> = values + .iter() + .map(|v| s.spawn(move || (0..50).for_each(|_| write_cached(dir, url, v)))) + .collect(); + for w in writers { + w.join().unwrap(); + } + writers_done.store(true, Ordering::SeqCst); + reader.join().unwrap() + }); + assert_eq!(torn, None, "a reader saw a torn file of that many bytes"); + assert!(values.contains(&read_cached(dir, url, CACHE_TTL).unwrap())); + let left: Vec<_> = std::fs::read_dir(dir).unwrap().flatten().collect(); + assert_eq!(left.len(), 1, "temp files left behind: {left:?}"); + } + + /// Temp names are unique, so one a failed write leaves behind would never + /// be reused: every failure would add a file. + #[test] + fn write_cached_removes_its_temp_file_when_the_rename_fails() { + let tmp = tempfile::tempdir().unwrap(); + let url = "https://api.iconify.design/logos:aws.svg"; + // A directory where the cache file belongs, so the rename fails. + std::fs::create_dir(cache_path(tmp.path(), url)).unwrap(); + write_cached(tmp.path(), url, "data:image/png;base64,AAAA"); + let left: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().flatten().collect(); + assert_eq!(left.len(), 1, "temp files left behind: {left:?}"); + } + + #[test] + fn failure_cache_suppresses_retries_within_ttl() { + let c = FailureCache::new(Duration::from_secs(600)); + let t0 = Instant::now(); + c.record("https://x.test/i.png", t0); + assert!(c.is_recent("https://x.test/i.png", t0 + Duration::from_secs(599))); + assert!(!c.is_recent("https://x.test/i.png", t0 + Duration::from_secs(601))); + assert!(!c.is_recent("https://y.test/i.png", t0)); + } + + /// One dead icon host must not cost every catalog load a fresh timeout. + #[tokio::test] + async fn inline_one_skips_the_network_for_a_recently_failed_url() { + let (addr, dials) = hang_up_listener().await; + let host = "failing-icons.example"; + // No proxy: an HTTPS_PROXY in the environment would bypass `resolve`. + let client = reqwest::Client::builder() + .no_proxy() + .resolve(host, addr) + .build() + .unwrap(); + let icon = format!("https://{host}/logo.svg"); + let url = fetch_target(&icon).unwrap(); + let dir = tempfile::tempdir().unwrap(); + + // A connection that drops is transient, not a refusal. + assert_eq!(inline_one(client.clone(), url).await, Outcome::Failed); + assert_eq!(dials.load(Ordering::SeqCst), 1); + assert!(FAILURES.is_recent(&icon, Instant::now())); + + // Within FAILURE_TTL the host is not dialled again, yet an expired + // copy is still served rather than a blank tile. + write_expired_copy(dir.path(), &icon, "data:image/png;base64,AAAA"); + let mut m = manifest("failing", &icon); + inline_all_with(dir.path(), &mut [&mut m], |url| { + inline_one(client.clone(), url) + }) + .await; + assert_eq!(m.icon.as_deref(), Some("data:image/png;base64,AAAA")); + assert_eq!(dials.load(Ordering::SeqCst), 1); + } + + fn manifest(name: &str, icon: &str) -> PluginManifest { + serde_json::from_value(serde_json::json!({ + "name": name, "version": "1.0.0", "providers": ["claude"], "declares": {}, + "icon": icon, + })) + .unwrap() + } + + /// A cached copy of `url` that is already past `CACHE_TTL`. + fn write_expired_copy(dir: &Path, url: &str, data_uri: &str) { + write_cached(dir, url, data_uri); + std::fs::File::options() + .write(true) + .open(cache_path(dir, url)) + .unwrap() + .set_modified(SystemTime::now() - CACHE_TTL - Duration::from_secs(60)) + .unwrap(); + } + + #[tokio::test] + async fn inline_all_fetches_each_url_once() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://icons.example.com/shared.svg"; + let uri = to_data_uri("image/svg+xml", SVG).unwrap(); + let mut ms: Vec<_> = (0..3).map(|i| manifest(&format!("p{i}"), icon)).collect(); + let calls = AtomicUsize::new(0); + let mut refs: Vec<_> = ms.iter_mut().collect(); + inline_all_with(dir.path(), &mut refs, |_| { + calls.fetch_add(1, Ordering::SeqCst); + let uri = uri.clone(); + async move { Outcome::Inlined(uri) } + }) + .await; + assert_eq!(calls.load(Ordering::SeqCst), 1); + for m in &ms { + assert_eq!(m.icon.as_deref(), Some(uri.as_str())); + } + } + + #[tokio::test] + async fn inline_all_uses_a_fresh_cached_copy_without_fetching() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://icons.example.com/cached.svg"; + write_cached(dir.path(), icon, "data:image/png;base64,AAAA"); + let mut m = manifest("cached", icon); + let calls = AtomicUsize::new(0); + inline_all_with(dir.path(), &mut [&mut m], |_| { + calls.fetch_add(1, Ordering::SeqCst); + async { Outcome::Failed } + }) + .await; + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(m.icon.as_deref(), Some("data:image/png;base64,AAAA")); + } + + /// The SSRF policy lives in `fetch_target`, ahead of any fetcher: an IP + /// literal never reaches the resolver that would otherwise vet it. + #[tokio::test] + async fn inline_all_only_fetches_what_fetch_target_accepts() { + let dir = tempfile::tempdir().unwrap(); + let inline = "data:image/png;base64,AAAA"; + let icons = [ + "https://icons.example.com/ok.svg", + "http://icons.example.com/plain.svg", + "https://10.0.0.1/i.png", + "https://localhost/i.png", + inline, + ]; + let mut ms: Vec<_> = icons.iter().map(|icon| manifest("p", icon)).collect(); + let asked = Mutex::new(Vec::new()); + let mut refs: Vec<_> = ms.iter_mut().collect(); + inline_all_with(dir.path(), &mut refs, |url| { + asked.lock().push(url.to_string()); + async { Outcome::Failed } + }) + .await; + assert_eq!(*asked.lock(), ["https://icons.example.com/ok.svg"]); + assert_eq!(ms[4].icon.as_deref(), Some(inline)); + } + + /// `fetch_target` refuses an IP literal outright. Left as a URL, the + /// icon would send the WebView to that address instead. + #[tokio::test] + async fn inline_all_drops_an_icon_at_a_non_public_ip_literal() { + let dir = tempfile::tempdir().unwrap(); + assert!(!is_public_ip("10.0.0.1".parse().unwrap())); + let mut m = manifest("private", "https://10.0.0.1/i.png"); + let calls = AtomicUsize::new(0); + inline_all_with(dir.path(), &mut [&mut m], |_| { + calls.fetch_add(1, Ordering::SeqCst); + async { Outcome::Failed } + }) + .await; + assert_eq!(m.icon, None); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + /// Whatever `fetch_target` refuses is dropped, except an icon that is + /// already inline: a `data:` URI loads nothing. + #[tokio::test] + async fn inline_all_drops_every_refused_icon_but_keeps_inline_ones() { + let dir = tempfile::tempdir().unwrap(); + let refused = [ + "http://icons.example.com/plain.svg", + "https://[::1]/i.png", + "https://user:pw@icons.example.com/i.png", + "https://printer.local/i.png", + "//10.0.0.1/i.png", + "icons/logo.svg", + // Not inline to the WebView: with anything in front of `data:` + // it reads a relative URL. + "\u{a0}data:image/png;base64,AAAA", + ]; + let inline = "data:image/png;base64,AAAA"; + let mut ms: Vec<_> = refused + .iter() + .chain([&inline]) + .map(|icon| manifest("p", icon)) + .collect(); + let calls = AtomicUsize::new(0); + let mut refs: Vec<_> = ms.iter_mut().collect(); + inline_all_with(dir.path(), &mut refs, |_| { + calls.fetch_add(1, Ordering::SeqCst); + async { Outcome::Failed } + }) + .await; + for (icon, m) in refused.iter().zip(&ms) { + assert_eq!(m.icon, None, "{icon} should be dropped"); + } + assert_eq!(ms[refused.len()].icon.as_deref(), Some(inline)); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + /// The production wiring end to end. The icon names `localhost` at the + /// port of a listener that counts dials: it is dropped, and nothing is + /// dialled. `fetch_target` refuses `localhost` before any lookup, so this + /// pins that outcome, not the resolver; the resolver's refusal is + /// `inline_one_reports_a_resolver_refusal_as_refused`. + #[tokio::test] + async fn inline_all_drops_a_name_that_resolves_to_loopback_without_dialling() { + let (addr, dials) = hang_up_listener().await; + let dir = tempfile::tempdir().unwrap(); + let icon = format!("https://localhost:{}/i.png", addr.port()); + let mut m = manifest("loopback", &icon); + inline_all_in(dir.path(), &mut [&mut m], icon_client()).await; + assert_eq!(m.icon, None); + assert_eq!( + dials.load(Ordering::SeqCst), + 0, + "a loopback address was dialled" + ); + } + + /// A failed fetch leaves no URL behind either, since a host can fail the + /// backend's fetch on purpose and then redirect the WebView. Without an + /// expired copy the icon is dropped. + #[tokio::test] + async fn inline_all_drops_an_icon_whose_fetch_failed() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://flaky-icons.example/logo.svg"; + let mut m = manifest("flaky", icon); + inline_all_with(dir.path(), &mut [&mut m], |_| async { Outcome::Failed }).await; + assert_eq!(m.icon, None); + } + + /// Should the icon client ever fail to build, nothing is fetched, yet the + /// icons are settled all the same: a cached copy stays, a URL does not. + #[tokio::test] + async fn inline_all_in_leaves_no_url_without_a_client() { + let dir = tempfile::tempdir().unwrap(); + let aged = "https://no-client-icons.example/aged.svg"; + write_expired_copy(dir.path(), aged, "data:image/png;base64,AAAA"); + let mut new = manifest("new", "https://no-client-icons.example/new.svg"); + let mut old = manifest("old", aged); + inline_all_in(dir.path(), &mut [&mut new, &mut old], None).await; + assert_eq!(new.icon, None); + assert_eq!(old.icon.as_deref(), Some("data:image/png;base64,AAAA")); + } + + /// A refusal is remembered: the next load drops the icon without + /// fetching it, so not even DNS is asked again. + #[tokio::test] + async fn inline_all_drops_a_refused_icon_again_without_fetching() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://rebinding-icons.example/logo.svg"; + let mut first = manifest("first", icon); + inline_all_with(dir.path(), &mut [&mut first], |_| async { + Outcome::Refused + }) + .await; + assert_eq!(first.icon, None); + + let mut second = manifest("second", icon); + let calls = AtomicUsize::new(0); + inline_all_with(dir.path(), &mut [&mut second], |_| { + calls.fetch_add(1, Ordering::SeqCst); + async { Outcome::Failed } + }) + .await; + assert_eq!(second.icon, None); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + /// An expired copy is a local `data:` URI, so it may stand in for a + /// refused icon. The URL may not. + #[tokio::test] + async fn inline_all_serves_a_refused_icon_from_an_expired_copy() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://refused-icons.example/old.svg"; + write_expired_copy(dir.path(), icon, "data:image/png;base64,AAAA"); + let mut m = manifest("refused", icon); + inline_all_with(dir.path(), &mut [&mut m], |_| async { Outcome::Refused }).await; + assert_eq!(m.icon.as_deref(), Some("data:image/png;base64,AAAA")); + } + + /// A refusal that lands after the budget is too late for that load, which + /// shows no icon, but the background fetch still records it, so the next + /// load does not fetch the icon again. + #[tokio::test(start_paused = true)] + async fn inline_all_remembers_a_refusal_that_lands_after_the_budget() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://late-refusal-icons.example/logo.svg"; + let mut first = manifest("first", icon); + inline_all_with(dir.path(), &mut [&mut first], |_| async { + tokio::time::sleep(Duration::from_secs(10)).await; + Outcome::Refused + }) + .await; + assert_eq!(first.icon, None); + + tokio::time::sleep(Duration::from_secs(10)).await; + let mut second = manifest("second", icon); + let calls = AtomicUsize::new(0); + inline_all_with(dir.path(), &mut [&mut second], |_| { + calls.fetch_add(1, Ordering::SeqCst); + async { Outcome::Failed } + }) + .await; + assert_eq!(second.icon, None); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + /// Tokio's clock is paused, so the fetcher sleeps and the budget runs + /// out in virtual time: no real waiting, and nothing to race. + #[tokio::test(start_paused = true)] + async fn inline_all_returns_within_budget() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://slow-icons.example/logo.svg"; + let mut m = manifest("slow", icon); + let started = tokio::time::Instant::now(); + inline_all_with(dir.path(), &mut [&mut m], |_| async { + tokio::time::sleep(Duration::from_secs(10)).await; + Outcome::Inlined(to_data_uri("image/svg+xml", SVG).unwrap()) + }) + .await; + let waited = started.elapsed(); + assert!(waited < Duration::from_secs(4), "waited {waited:?}"); + assert!(waited >= INLINE_BUDGET, "gave up after only {waited:?}"); + assert_eq!(m.icon, None); + } + + /// A fetch still running when the budget runs out leaves the icon its + /// expired copy, if there is one, rather than its URL. + #[tokio::test(start_paused = true)] + async fn inline_all_serves_an_expired_copy_when_the_budget_runs_out() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://slow-icons.example/aged.svg"; + write_expired_copy(dir.path(), icon, "data:image/png;base64,AAAA"); + let mut m = manifest("aged", icon); + inline_all_with(dir.path(), &mut [&mut m], |_| async { + tokio::time::sleep(Duration::from_secs(10)).await; + Outcome::Inlined(to_data_uri("image/svg+xml", SVG).unwrap()) + }) + .await; + assert_eq!(m.icon.as_deref(), Some("data:image/png;base64,AAAA")); + } + + /// Whatever became of each icon, none is handed to the WebView as a URL: + /// each one ends as a `data:` URI or as nothing. + #[tokio::test(start_paused = true)] + async fn inline_all_leaves_every_icon_inline_or_none() { + let dir = tempfile::tempdir().unwrap(); + let base = "https://mixed-icons.example"; + let cached_refusal = format!("{base}/cached-refusal.svg"); + REFUSALS.record(&cached_refusal, Instant::now()); + let aged = format!("{base}/aged.svg"); + write_expired_copy(dir.path(), &aged, "data:image/png;base64,AAAA"); + let icons = [ + format!("{base}/inlined.svg"), + format!("{base}/failed.svg"), + format!("{base}/slow.svg"), + format!("{base}/refused.svg"), + cached_refusal, + aged, + "data:image/png;base64,BBBB".to_owned(), + "https://10.0.0.1/i.png".to_owned(), + ]; + let mut ms: Vec<_> = icons.iter().map(|icon| manifest("p", icon)).collect(); + let mut refs: Vec<_> = ms.iter_mut().collect(); + inline_all_with(dir.path(), &mut refs, |url| async move { + match url.path() { + "/inlined.svg" => Outcome::Inlined(to_data_uri("image/svg+xml", SVG).unwrap()), + "/slow.svg" => { + tokio::time::sleep(Duration::from_secs(10)).await; + Outcome::Inlined(to_data_uri("image/svg+xml", SVG).unwrap()) + } + "/refused.svg" => Outcome::Refused, + _ => Outcome::Failed, + } + }) + .await; + for (icon, m) in icons.iter().zip(&ms) { + if let Some(got) = &m.icon { + assert!(got.starts_with("data:"), "{icon} was left as {got}"); + } + } + let got: Vec<_> = ms.iter().map(|m| m.icon.as_deref()).collect(); + let inlined = to_data_uri("image/svg+xml", SVG).unwrap(); + assert_eq!( + got, + [ + Some(inlined.as_str()), + None, + None, + None, + None, + Some("data:image/png;base64,AAAA"), + Some("data:image/png;base64,BBBB"), + None, + ] + ); + } + + #[tokio::test(start_paused = true)] + async fn inline_all_keeps_filling_the_cache_after_the_budget() { + let dir = tempfile::tempdir().unwrap(); + let icon = "https://slow-icons.example/late.svg"; + let uri = to_data_uri("image/svg+xml", SVG).unwrap(); + let mut m = manifest("late", icon); + inline_all_with(dir.path(), &mut [&mut m], |_| { + let uri = uri.clone(); + async move { + tokio::time::sleep(Duration::from_secs(10)).await; + Outcome::Inlined(uri) + } + }) + .await; + assert_eq!(m.icon, None); + assert_eq!(read_cached(dir.path(), icon, CACHE_TTL), None); + + // The fetch outlives the load that gave up on it, so the next load + // finds the icon in the cache. + tokio::time::sleep(Duration::from_secs(10)).await; + assert_eq!(read_cached(dir.path(), icon, CACHE_TTL), Some(uri)); + } + + #[tokio::test(start_paused = true)] + async fn inline_all_runs_at_most_icon_concurrency_fetches_at_once() { + let dir = tempfile::tempdir().unwrap(); + let mut ms: Vec<_> = (0..ICON_CONCURRENCY + 2) + .map(|i| format!("https://icons.example.com/{i}.svg")) + .map(|icon| manifest("p", &icon)) + .collect(); + let in_flight = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let mut refs: Vec<_> = ms.iter_mut().collect(); + inline_all_with(dir.path(), &mut refs, |_| { + let (in_flight, peak) = (Arc::clone(&in_flight), Arc::clone(&peak)); + async move { + let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(Duration::from_secs(1)).await; + in_flight.fetch_sub(1, Ordering::SeqCst); + Outcome::Inlined(to_data_uri("image/svg+xml", SVG).unwrap()) + } + }) + .await; + // In parallel but never past the cap. Two one-second rounds fit the + // budget, so every icon arrives. + assert_eq!(peak.load(Ordering::SeqCst), ICON_CONCURRENCY); + for m in &ms { + let icon = m.icon.as_deref().unwrap(); + assert!(icon.starts_with("data:image/svg+xml;"), "kept {icon}"); + } + } + /// Live network. Proves the premise of this module end to end: the /// backend's client is NOT blocked by the CDN that blocks the WebView. /// Run with `cargo test -p fleetify-backend --lib icons -- --ignored`. @@ -354,7 +1344,7 @@ mod tests { "icon": "https://api.iconify.design/logos:asana-icon.svg", })) .unwrap(); - inline_all_in(cache.path(), &mut [&mut m]).await; + inline_all_in(cache.path(), &mut [&mut m], icon_client()).await; let icon = m.icon.unwrap(); assert!( icon.starts_with("data:image/svg+xml;base64,"), @@ -365,6 +1355,12 @@ mod tests { } } + /// A client that ignores any proxy set in the environment, so a test + /// talks to its local server and nothing else. + fn direct_client() -> reqwest::Client { + reqwest::Client::builder().no_proxy().build().unwrap() + } + #[tokio::test] async fn fetch_data_uri_inlines_an_image_response() { let server = MockServer::start().await; @@ -374,8 +1370,11 @@ mod tests { .mount(&server) .await; let url = reqwest::Url::parse(&format!("{}/logo.svg", server.uri())).unwrap(); - let uri = fetch_data_uri(&reqwest::Client::new(), url).await.unwrap(); - assert!(uri.starts_with("data:image/svg+xml;base64,")); + let got = fetch_data_uri(&direct_client(), url).await; + assert!( + matches!(&got, Outcome::Inlined(uri) if uri.starts_with("data:image/svg+xml;base64,")), + "got {got:?}" + ); } #[tokio::test] @@ -389,6 +1388,8 @@ mod tests { .mount(&server) .await; let url = reqwest::Url::parse(&format!("{}/blocked.svg", server.uri())).unwrap(); - assert!(fetch_data_uri(&reqwest::Client::new(), url).await.is_none()); + // An HTTP error is transient, not a refusal. + let got = fetch_data_uri(&direct_client(), url).await; + assert_eq!(got, Outcome::Failed); } } diff --git a/crates/fleetify-backend/src/services/plugins/rule_merge.rs b/crates/fleetify-backend/src/services/plugins/rule_merge.rs index 469f2c0..ccede3a 100644 --- a/crates/fleetify-backend/src/services/plugins/rule_merge.rs +++ b/crates/fleetify-backend/src/services/plugins/rule_merge.rs @@ -174,10 +174,39 @@ mod tests { assert_eq!(after.matches("fleetify:rule:x START").count(), 1); } + /// Pins `USERPROFILE` under the shared `home_lock`, so it cannot land in + /// the middle of a sibling test that pinned its own home. The old value + /// comes back on drop, so also when the test panics, and before the lock + /// is released. + struct PinnedUserProfile { + prev: Option, + _lock: std::sync::MutexGuard<'static, ()>, + } + + impl PinnedUserProfile { + fn new(value: &str) -> Self { + let lock = crate::test_support::home_lock() + .lock() + .unwrap_or_else(|p| p.into_inner()); + let prev = std::env::var_os("USERPROFILE"); + std::env::set_var("USERPROFILE", value); + Self { prev, _lock: lock } + } + } + + impl Drop for PinnedUserProfile { + fn drop(&mut self) { + match self.prev.take() { + Some(v) => std::env::set_var("USERPROFILE", v), + None => std::env::remove_var("USERPROFILE"), + } + } + } + #[test] fn rule_file_targets_per_provider() { // provider_home reads USERPROFILE/HOME; just assert the file name logic. - std::env::set_var("USERPROFILE", "/tmp/fakehome"); + let _home = PinnedUserProfile::new("/tmp/fakehome"); assert!(rule_file("claude-code").unwrap().ends_with("CLAUDE.md")); assert!(rule_file("codex-cli").unwrap().ends_with("AGENTS.md")); assert!(rule_file("github-copilot") diff --git a/crates/fleetify-backend/src/services/telemetry/cloud_gate.rs b/crates/fleetify-backend/src/services/telemetry/cloud_gate.rs new file mode 100644 index 0000000..b0e40d6 --- /dev/null +++ b/crates/fleetify-backend/src/services/telemetry/cloud_gate.rs @@ -0,0 +1,138 @@ +//! Runtime gate for the Fleetify-cloud channel: the account-authenticated +//! WebSocket that feeds the user's fleetify.dev dashboard. Settings → +//! Privacy flips it through the shell's `telemetry_set_cloud_enabled` +//! command, and the shell restores the saved choice at startup. +//! +//! The gate starts closed, so nothing is queued or sent before the shell +//! has restored the user's choice. While it is closed: +//! - `emitters::enqueue_payload` writes nothing to the cloud outbox; +//! - `ws_client::run_ws_client_loop` fetches no bearer, requests no ticket +//! and holds no socket. +//! +//! Closing it purges the outbox, so nothing queued is sent later. Rows an +//! older build queued (without consent, unminimised) never depend on that: +//! the outbox drops them itself when it opens (`outbox::migrate`). +//! +//! The PostHog sink has its own consent gate (`posthog::set_enabled`); +//! this one does not touch it. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; + +use tokio::sync::Notify; + +use super::outbox; + +static CLOUD_ENABLED: AtomicBool = AtomicBool::new(false); + +pub fn cloud_enabled() -> bool { + CLOUD_ENABLED.load(Ordering::SeqCst) +} + +/// Turn cloud sync on or off: store the flag, purge the outbox when off, +/// then wake the WS loop so it connects or drops its socket. +/// +/// Every `false` purges, not only an on→off change, so the startup restore +/// of a closed gate also clears whatever this build queued earlier — when +/// the outbox is open by then. Nothing orders that restore after the +/// backend opens the outbox; see `purge_outbox`. +pub async fn set_cloud_enabled(on: bool) { + CLOUD_ENABLED.store(on, Ordering::SeqCst); + if !on { + purge_outbox().await; + } + gate_changed().notify_waiters(); + tracing::info!(target: "fleetify.telemetry", enabled = on, "cloud sync gate set"); +} + +async fn purge_outbox() { + if !outbox::is_initialised() { + // Not open yet (the startup restore can run before the backend + // opens it), or never (no-auth dev mode, failed init). Nothing can + // be read or sent without it, and when it opens it drops what older + // builds queued before any reader sees it (`outbox::migrate`). + tracing::debug!( + target: "fleetify.telemetry", + "cloud sync off: outbox not open, nothing to purge" + ); + return; + } + if let Err(e) = outbox::reset().await { + tracing::warn!( + target: "fleetify.telemetry", + "cloud sync off: purging the outbox failed: {e}" + ); + } +} + +/// Pulsed with `notify_waiters()` after every gate change. A `notified()` +/// future receives that pulse from the moment it is created, so create it +/// before checking `cloud_enabled()`: a change landing between the check +/// and the await then still wakes the waiter. +pub(crate) fn gate_changed() -> &'static Notify { + static N: OnceLock = OnceLock::new(); + N.get_or_init(Notify::new) +} + +#[cfg(test)] +pub(crate) mod test_support { + use super::*; + + /// Puts the gate back the way it was when the guard was made. It does + /// so on drop, so also when the test panics: a failing test can't + /// leave the gate open for the next one. A plain store, no purge. + pub(crate) struct GateGuard(bool); + + impl GateGuard { + pub(crate) fn new() -> Self { + Self(cloud_enabled()) + } + } + + impl Drop for GateGuard { + fn drop(&mut self) { + CLOUD_ENABLED.store(self.0, Ordering::SeqCst); + gate_changed().notify_waiters(); + } + } +} + +#[cfg(test)] +mod tests { + use super::test_support::GateGuard; + use super::*; + use crate::services::telemetry::emitters; + + async fn pending_for(session_id: &str) -> usize { + outbox::peek_pending(1_000) + .await + .unwrap() + .iter() + .filter(|(_, p)| p["local_session_id"] == session_id) + .count() + } + + #[tokio::test] + async fn closing_the_gate_purges_pending_events() { + let _g = outbox::tests::TEST_LOCK.lock().await; + outbox::tests::ensure_inited().await; + let _gate = GateGuard::new(); + + set_cloud_enabled(true).await; + let now = chrono::Utc::now(); + emitters::emit_status_change("s-purge", "running", now) + .await + .unwrap(); + emitters::emit_status_change("s-purge", "idle", now) + .await + .unwrap(); + assert_eq!(pending_for("s-purge").await, 2, "both events queued"); + + set_cloud_enabled(false).await; + assert_eq!( + outbox::count().await.unwrap(), + 0, + "turning sync off leaves nothing queued" + ); + } +} diff --git a/crates/fleetify-backend/src/services/telemetry/emitters.rs b/crates/fleetify-backend/src/services/telemetry/emitters.rs index f4f7fff..93f0022 100644 --- a/crates/fleetify-backend/src/services/telemetry/emitters.rs +++ b/crates/fleetify-backend/src/services/telemetry/emitters.rs @@ -4,14 +4,16 @@ //! Each `emit_*` function: //! 1. Truncates user-supplied strings to wire-safe lengths. //! 2. Generates a client-assigned UUID v4 to identify the event. -//! 3. Persists the event via `outbox::enqueue`. -//! 4. Pulses `event_available` so the (eventual) WS client flushes -//! the new event immediately instead of waiting on its poll -//! cadence. +//! 3. While cloud sync is on (`cloud_gate`), persists the event's +//! `cloud_view` via `outbox::enqueue`. +//! 4. Pulses `event_available` so the WS client flushes the new event +//! immediately instead of waiting on its poll cadence. //! -//! Privacy tier: titles + paths allowed, never prompt / file content / -//! command stdio. +//! Privacy tier for the cloud: session titles and project folder names +//! allowed; never activity summaries, full paths, prompt / file content +//! or command stdio. +use std::path::Path; use std::sync::OnceLock; use anyhow::Result; @@ -53,6 +55,118 @@ fn iso_utc(dt: DateTime) -> String { dt.to_rfc3339() } +/// The copy of a payload the Fleetify cloud gets. Drops +/// `activity_summary` (agent shell commands, file paths, URLs, search +/// queries, sub-agent prompts, todo text), which the dashboard never +/// shows. Cuts `project_path` to its last component: the full path +/// carries the OS user name, and the dashboard shows only a short label. +/// The home folder itself becomes `~`, since its own name is usually the +/// OS user name. A path with no component left (empty, `null`, not a +/// string) becomes `null`; a payload without the key stays without it. +/// Every other key is unchanged. +pub(crate) fn cloud_view(payload: &Value) -> Value { + cloud_view_for_home(payload, &fleetify_core::user_home()) +} + +/// `cloud_view` against a given home folder. The home folder counts as +/// given and in its canonical form: `HOME` may be a symlink while project +/// paths are stored canonical (`validate_project_path`). +fn cloud_view_for_home(payload: &Value, home: &Path) -> Value { + let canonical = fleetify_core::canonicalize_or_keep(home); + let homes = [home, canonical.as_path()]; + let rules = PathRules::current(); + let mut view = payload.clone(); + if let Some(fields) = view.as_object_mut() { + fields.remove("activity_summary"); + let path = fields + .get("project_path") + .and_then(Value::as_str) + .map(str::to_owned); + let at_home = path + .as_deref() + .is_some_and(|p| homes.iter().any(|h| is_home_folder(p, h, rules))); + if let Some(project_path) = fields.get_mut("project_path") { + *project_path = if at_home { + Value::from("~") + } else { + project_folder(path.as_deref()).map_or(Value::Null, Value::from) + }; + } + if at_home { + // An untitled session is named after its folder, so a session + // in the home folder would carry the OS user name as its title. + let names: Vec = homes + .iter() + .map(|h| h.to_string_lossy().into_owned()) + .chain(path) + .filter_map(|p| project_folder(Some(&p)).map(str::to_owned)) + .collect(); + if let Some(title) = fields.get_mut("session_title") { + if title + .as_str() + .is_some_and(|t| names.iter().any(|n| rules.same(t, n))) + { + *title = Value::from("~"); + } + } + } + } + view +} + +/// How this OS's file system compares paths. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PathRules { + /// Linux: case and separators count. + Exact, + /// macOS (APFS, HFS+ by default): case doesn't count; `\` is a + /// character, not a separator. + IgnoreCase, + /// Windows: case doesn't count and `/` matches `\`. + Windows, +} + +impl PathRules { + fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else if cfg!(target_os = "macos") { + Self::IgnoreCase + } else { + Self::Exact + } + } + + fn normalise(self, path: &str) -> String { + match self { + Self::Exact => path.to_string(), + Self::IgnoreCase => path.to_lowercase(), + Self::Windows => path.replace('\\', "/").to_lowercase(), + } + } + + fn same(self, a: &str, b: &str) -> bool { + self.normalise(a) == self.normalise(b) + } +} + +/// Whether `path` is the home folder itself, trailing separators ignored. +fn is_home_folder(path: &str, home: &Path, rules: PathRules) -> bool { + let trim = |p: &str| p.trim_end_matches(['/', '\\']).to_string(); + let path = trim(path); + !path.is_empty() && rules.same(&path, &trim(&home.to_string_lossy())) +} + +/// Last component of a path, split on `/` and `\` alike, trailing +/// separators ignored. `None` when nothing is left. +fn project_folder(path: Option<&str>) -> Option<&str> { + path? + .trim_end_matches(['/', '\\']) + .rsplit(['/', '\\']) + .next() + .filter(|folder| !folder.is_empty()) +} + async fn enqueue_payload(payload: Value) -> Result<()> { // No-auth dev mode: never enqueue. The WS client and heartbeat loop // are also skipped at startup, so without this guard the outbox @@ -60,11 +174,29 @@ async fn enqueue_payload(payload: Value) -> Result<()> { if crate::auth::is_no_auth() { return Ok(()); } - let event_id = uuid::Uuid::new_v4().to_string(); - outbox::enqueue(&event_id, &payload).await?; - // Fan out to the PostHog sink. No-op when the runtime gate is - // closed or POSTHOG_API_KEY was unset at build time. + let cloud = if super::cloud_enabled() { + enqueue_for_cloud(&payload).await + } else { + Ok(()) + }; + // Fan out to the PostHog sink whatever the cloud gate says: it has its + // own consent gate, and its mapper hashes the full project path and + // drops summaries, so it gets the original payload. No-op when its + // gate is closed or POSTHOG_API_KEY is unset. super::posthog::enqueue_if_enabled(&payload).await; + cloud +} + +async fn enqueue_for_cloud(payload: &Value) -> Result<()> { + let event_id = uuid::Uuid::new_v4().to_string(); + outbox::enqueue(&event_id, &cloud_view(payload)).await?; + if !super::cloud_enabled() { + // Sync was turned off while this row was being written, and the + // purge may have run before it landed. Drop it so nothing stays + // queued. + outbox::mark_acked(&event_id).await?; + return Ok(()); + } tracing::info!( target: "fleetify.telemetry.emit", "telemetry: enqueued kind={} id={} session={}", @@ -560,20 +692,231 @@ mod tests { } } +#[cfg(test)] +mod cloud_sync_tests { + use super::*; + use crate::services::telemetry::cloud_gate::test_support::GateGuard; + use crate::services::telemetry::set_cloud_enabled; + + async fn pending_for(session_id: &str) -> Vec { + outbox::peek_pending(1_000) + .await + .unwrap() + .into_iter() + .map(|(_, p)| p) + .filter(|p| p["local_session_id"] == session_id) + .collect() + } + + #[test] + fn cloud_view_drops_activity_summary_and_keeps_only_the_project_folder() { + let activity = json!({ + "kind": "activity", + "activity_kind": "bash", + "activity_summary": "export TOKEN=x", + }); + let v = cloud_view(&activity); + assert!(v.get("activity_summary").is_none(), "summary sent: {v}"); + assert_eq!(v["activity_kind"], "bash"); + assert_eq!(v["kind"], "activity"); + + let folder = + |path: Value| cloud_view(&json!({ "project_path": path }))["project_path"].clone(); + assert_eq!(folder(json!("/home/u/work/fleetify")), json!("fleetify")); + assert_eq!(folder(json!("/home/u/work/fleetify/")), json!("fleetify")); + assert_eq!(folder(json!("C:\\Users\\u\\proj")), json!("proj")); + assert_eq!(folder(json!("")), Value::Null); + assert_eq!(folder(Value::Null), Value::Null); + + // The home folder itself goes out as `~`: its name is usually the + // OS user name, and the Fleet hub's own session runs there. + let label = |path: Value| { + cloud_view_for_home(&json!({ "project_path": path }), Path::new("/home/u")) + ["project_path"] + .clone() + }; + assert_eq!(label(json!("/home/u")), json!("~")); + assert_eq!(label(json!("/home/u/")), json!("~")); + // Folders under home keep their names, even one named like the user. + assert_eq!(label(json!("/home/u/work/fleetify")), json!("fleetify")); + assert_eq!(label(json!("/home/u/u")), json!("u")); + // Only the home folder itself: not a sibling that starts the same. + assert_eq!(label(json!("/home/user")), json!("user")); + assert_eq!(label(json!("")), Value::Null); + // Case and separator style count on Linux. Windows ignores both; + // macOS (APFS, HFS+) ignores case but keeps `\` as a character. + let exact = PathRules::Exact; + let mac = PathRules::IgnoreCase; + let win = PathRules::Windows; + assert!(!is_home_folder("/home/U", Path::new("/home/u"), exact)); + assert!(is_home_folder("/Users/U", Path::new("/Users/u"), mac)); + assert!(!is_home_folder("/Users/u/x", Path::new("/Users/u\\x"), mac)); + assert!(is_home_folder( + "C:\\Users\\U\\", + Path::new("c:\\users\\u"), + win + )); + assert!(is_home_folder("C:/Users/U", Path::new("C:\\Users\\U"), win)); + assert!(!is_home_folder( + "C:\\Users\\U\\proj", + Path::new("C:\\Users\\U"), + win + )); + assert!(!is_home_folder("", Path::new(""), exact)); + // `cloud_view` compares against the real home folder. + let home = fleetify_core::user_home(); + assert_eq!(folder(json!(home.to_string_lossy())), json!("~")); + + let start = json!({ + "kind": "session_start", + "local_session_id": "s1", + "tool": "claude-code", + "model": "claude-sonnet-4-6", + "status": "running", + "session_title": "Fix the flaky build", + "project_path": "/home/u/work/fleetify", + "occurred_at": "2026-11-17T10:00:00+00:00", + }); + let v = cloud_view(&start); + for key in [ + "kind", + "local_session_id", + "tool", + "model", + "status", + "session_title", + "occurred_at", + ] { + assert_eq!(v[key], start[key], "{key} changed"); + } + assert_eq!( + v.as_object().unwrap().len(), + start.as_object().unwrap().len(), + "keys added or lost: {v}" + ); + } + + #[cfg(unix)] + #[test] + fn a_symlinked_home_folder_is_sent_as_tilde() { + // HOME may be a symlink while project paths are stored canonical + // (`validate_project_path`), so the canonical home counts too. + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real-home"); + std::fs::create_dir(&real).unwrap(); + let link = dir.path().join("home-link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let stored = fleetify_core::canonicalize_or_keep(&real); + + let view = cloud_view_for_home(&json!({ "project_path": stored.to_string_lossy() }), &link); + assert_eq!(view["project_path"], json!("~")); + // A folder under the real home keeps its name. + let under = stored.join("work"); + let view = cloud_view_for_home(&json!({ "project_path": under.to_string_lossy() }), &link); + assert_eq!(view["project_path"], json!("work")); + } + + #[test] + fn a_session_named_after_the_home_folder_is_sent_as_tilde() { + // The composer names an untitled session after its folder, so a + // session in the home folder would carry the OS user name. + let home = Path::new("/home/u"); + let view = |path: &str, title: &str| { + cloud_view_for_home( + &json!({ "project_path": path, "session_title": title }), + home, + ) + }; + let at_home = view("/home/u", "u"); + assert_eq!(at_home["project_path"], json!("~")); + assert_eq!(at_home["session_title"], json!("~")); + // Other titles of a home session are kept. + assert_eq!( + view("/home/u", "Staff Agent")["session_title"], + json!("Staff Agent") + ); + assert_eq!( + view("/home/u", "u notes")["session_title"], + json!("u notes") + ); + // A folder named like the user, but not home, keeps both. + let elsewhere = view("/home/u/u", "u"); + assert_eq!(elsewhere["project_path"], json!("u")); + assert_eq!(elsewhere["session_title"], json!("u")); + // No title, no project: nothing is added. + let bare = cloud_view_for_home(&json!({ "project_path": "/home/u" }), home); + assert!(bare.get("session_title").is_none()); + } + + #[tokio::test] + async fn enqueue_skips_the_cloud_outbox_while_the_gate_is_closed() { + let _g = outbox::tests::TEST_LOCK.lock().await; + outbox::tests::ensure_inited().await; + let _gate = GateGuard::new(); + + set_cloud_enabled(false).await; + let before = outbox::count().await.unwrap(); + emit_status_change("s-gate-closed", "running", Utc::now()) + .await + .unwrap(); + assert_eq!( + outbox::count().await.unwrap(), + before, + "a closed gate must not queue cloud events" + ); + + set_cloud_enabled(true).await; + emit_status_change("s-gate-open", "running", Utc::now()) + .await + .unwrap(); + // Count this test's row rather than the whole table: other modules' + // tests may emit while the gate is open here. + assert_eq!( + pending_for("s-gate-open").await.len(), + 1, + "an open gate queues the event once" + ); + assert!(outbox::count().await.unwrap() > before); + } + + #[tokio::test] + async fn cloud_outbox_rows_never_contain_activity_summaries() { + let _g = outbox::tests::TEST_LOCK.lock().await; + outbox::tests::ensure_inited().await; + let _gate = GateGuard::new(); + + set_cloud_enabled(true).await; + emit_activity("s-summary", "command", Some("rm -rf secret"), Utc::now()) + .await + .unwrap(); + + let rows = pending_for("s-summary").await; + assert_eq!(rows.len(), 1, "the activity event was queued"); + assert_eq!(rows[0]["activity_kind"], "command"); + assert!( + rows[0].get("activity_summary").is_none(), + "summary queued for the cloud: {}", + rows[0] + ); + } +} + #[cfg(test)] mod routing_emitter_tests { use super::*; + use crate::services::telemetry::cloud_gate::test_support::GateGuard; + use crate::services::telemetry::set_cloud_enabled; use chrono::TimeZone; - use tokio::sync::Mutex; fn ts() -> DateTime { Utc.with_ymd_and_hms(2026, 5, 22, 12, 0, 0).unwrap() } - // Same rationale as `outbox::tests::TEST_LOCK` — these tests share a - // process-wide POOL OnceLock; serialise them through a tokio Mutex so - // a `reset()` in one test doesn't race another's assertions. - static TEST_LOCK: Mutex<()> = Mutex::const_new(()); + // These tests share the process-wide POOL OnceLock and the cloud-sync + // gate with the outbox and gate tests, so they take the same lock + // (`outbox::tests::TEST_LOCK`): a `reset()` or a gate flip in one test + // must not race another's assertions. + use super::outbox::tests::TEST_LOCK; async fn ensure_outbox_inited() { let dir = tempfile::tempdir().unwrap(); @@ -743,6 +1086,9 @@ mod routing_emitter_tests { async fn cost_with_decision_id_does_not_panic() { let _g = TEST_LOCK.lock().await; ensure_outbox_inited().await; + // Open the cloud gate so the event still reaches the outbox write. + let _gate = GateGuard::new(); + set_cloud_enabled(true).await; let r = emit_cost( "s1", "claude-sonnet-4-6", @@ -762,6 +1108,9 @@ mod routing_emitter_tests { async fn cost_without_decision_id_does_not_panic() { let _g = TEST_LOCK.lock().await; ensure_outbox_inited().await; + // Open the cloud gate so the event still reaches the outbox write. + let _gate = GateGuard::new(); + set_cloud_enabled(true).await; let r = emit_cost( "s1", "claude-sonnet-4-6", diff --git a/crates/fleetify-backend/src/services/telemetry/mod.rs b/crates/fleetify-backend/src/services/telemetry/mod.rs index 61972cf..ef3342f 100644 --- a/crates/fleetify-backend/src/services/telemetry/mod.rs +++ b/crates/fleetify-backend/src/services/telemetry/mod.rs @@ -17,9 +17,15 @@ //! - `heartbeat::run_heartbeat_loop` (50 LOC — 60 s timer calling //! `emit_heartbeat`). //! -//! Privacy tier: "Standard + identifying" — titles + paths allowed, -//! never prompt content / file content / command stdio. +//! Consent: the whole cloud channel sits behind `cloud_gate` — closed +//! until the shell restores the user's Settings → Privacy choice, and +//! every close purges the outbox. +//! +//! Privacy tier: session titles + project folder names allowed (see +//! `emitters::cloud_view`); never activity summaries, full paths, +//! prompt content, file content or command stdio. +mod cloud_gate; pub mod device_id; pub mod emitters; pub mod heartbeat; @@ -27,6 +33,8 @@ pub mod outbox; pub mod posthog; pub mod ws_client; +pub(crate) use cloud_gate::gate_changed; +pub use cloud_gate::{cloud_enabled, set_cloud_enabled}; pub use device_id::{get_or_create, DeviceInfo}; pub use emitters::{ emit_activity, emit_cost, emit_heartbeat, emit_router_health_change, emit_routing_decision, diff --git a/crates/fleetify-backend/src/services/telemetry/outbox.rs b/crates/fleetify-backend/src/services/telemetry/outbox.rs index 7abfca6..100970e 100644 --- a/crates/fleetify-backend/src/services/telemetry/outbox.rs +++ b/crates/fleetify-backend/src/services/telemetry/outbox.rs @@ -6,7 +6,7 @@ //! Path: `/.fleetify/telemetry-outbox.sqlite`. Created lazily on //! first use; same directory as device.json. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::OnceLock; use anyhow::Result; @@ -50,6 +50,51 @@ pub async fn init_at(path: PathBuf) -> Result<()> { if POOL.get().is_some() { return Ok(()); } + let pool = open(&path).await?; + let _ = POOL.set(pool); + Ok(()) +} + +/// `PRAGMA user_version` of an outbox whose rows were all queued under the +/// cloud-sync consent gate, already minimised (`emitters::cloud_view`). +/// A database at 0 comes from an older build, which queued every event, +/// whatever the user chose, with activity summaries and full project paths. +const OUTBOX_VERSION: i64 = 1; + +/// One-time data migrations. 0 → 1 drops every row: an older build queued +/// them without consent and unminimised. Idempotent: a database already at +/// `OUTBOX_VERSION` keeps its rows. Runs in `open`, so before `init_at` +/// publishes the pool: no reader can see what it drops, whatever order +/// startup runs in. +async fn migrate(pool: &SqlitePool) -> Result<()> { + let mut tx = pool.begin().await?; + let (version,): (i64,) = sqlx::query_as("PRAGMA user_version") + .fetch_one(&mut *tx) + .await?; + if version >= OUTBOX_VERSION { + return Ok(()); + } + let dropped = sqlx::query("DELETE FROM telemetry_outbox") + .execute(&mut *tx) + .await? + .rows_affected(); + sqlx::query(&format!("PRAGMA user_version = {OUTBOX_VERSION}")) + .execute(&mut *tx) + .await?; + tx.commit().await?; + if dropped > 0 { + tracing::info!( + target: "fleetify.telemetry", + dropped, + "outbox: dropped events queued by builds without the cloud-sync consent gate" + ); + } + Ok(()) +} + +/// Open the outbox at `path`: schema, legacy prune, one-time migrations. +/// `init_at` publishes the pool only after this returns. +async fn open(path: &Path) -> Result { let url = format!("sqlite://{}", path.to_string_lossy().replace('\\', "/")); let opts = SqliteConnectOptions::from_str(&url)? .create_if_missing(true) @@ -85,8 +130,15 @@ pub async fn init_at(path: PathBuf) -> Result<()> { ); } - let _ = POOL.set(pool); - Ok(()) + migrate(&pool).await?; + Ok(pool) +} + +/// Whether `init()` / `init_at()` has opened the pool. False until the +/// backend's startup gets there, in no-auth dev mode and after a failed +/// init. Nothing can be queued or read then. +pub(crate) fn is_initialised() -> bool { + POOL.get().is_some() } fn pool_or_err() -> Result<&'static SqlitePool> { @@ -157,8 +209,10 @@ pub async fn count() -> Result { Ok(n) } -/// Drop everything. Tests + diagnostics ONLY — losing the outbox loses -/// unacked events. +/// Drop every queued event, unacked ones included. Serves opt-out: +/// turning cloud sync off (`set_cloud_enabled(false)`) calls this so +/// nothing stays queued to be sent later. Tests and diagnostics use it +/// too. Anywhere else, losing the outbox loses unacked events. pub async fn reset() -> Result<()> { sqlx::query("DELETE FROM telemetry_outbox") .execute(pool_or_err()?) @@ -167,24 +221,27 @@ pub async fn reset() -> Result<()> { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use serde_json::json; use tokio::sync::Mutex; - // Tests in this module share one process-wide OnceLock. + // Every telemetry test that touches the process-wide + // OnceLock or the cloud-sync gate takes this one lock: + // the tests here, the emitter tests and the gate / WS-loop tests. // cargo test runs #[tokio::test] cases in parallel by default, so a - // sibling test calling `reset()` mid-roundtrip would wipe the events - // this test just enqueued and assertions would race. Serialise them + // sibling test calling `reset()` or flipping the gate mid-roundtrip + // would wipe the events this test just enqueued, or let them in when + // it expects them kept out, and assertions would race. Serialise them // through a tokio Mutex (held across awaits) — cheaper than a - // per-test pool, and the two tests run in <100 ms anyway. - static TEST_LOCK: Mutex<()> = Mutex::const_new(()); + // per-test pool, and these tests run in well under a second. + pub(crate) static TEST_LOCK: Mutex<()> = Mutex::const_new(()); // Each test must use its OWN sqlite file because POOL is a process- // wide OnceLock — once initialised, subsequent init_at() calls are // no-ops. We initialise in the first test that runs (via // ensure_inited) and then mutate via the public API. - async fn ensure_inited() { + pub(crate) async fn ensure_inited() { let dir = tempfile::tempdir().unwrap(); let _ = init_at(dir.path().join("ob.sqlite")).await; let _ = reset().await; @@ -224,6 +281,128 @@ mod tests { assert_eq!(pending[0].0, "evt-2"); } + // The migration tests below run on their own scratch databases, never + // on the process-wide POOL, so they need no TEST_LOCK. + + /// An outbox file with the schema and no migrations: user_version 0, + /// like the database an older build leaves behind. + async fn unmigrated(path: &Path) -> SqlitePool { + let opts = SqliteConnectOptions::new() + .filename(path) + .create_if_missing(true); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(opts) + .await + .unwrap(); + sqlx::query(DDL).execute(&pool).await.unwrap(); + pool + } + + async fn insert_row(pool: &SqlitePool, id: &str, payload: Value) { + sqlx::query("INSERT INTO telemetry_outbox (id, payload, enqueued_at) VALUES (?, ?, 0)") + .bind(id) + .bind(payload.to_string()) + .execute(pool) + .await + .unwrap(); + } + + async fn rows(pool: &SqlitePool) -> i64 { + let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM telemetry_outbox") + .fetch_one(pool) + .await + .unwrap(); + n + } + + async fn user_version(pool: &SqlitePool) -> i64 { + let (v,): (i64,) = sqlx::query_as("PRAGMA user_version") + .fetch_one(pool) + .await + .unwrap(); + v + } + + #[tokio::test] + async fn migration_clears_rows_left_by_older_builds() { + let dir = tempfile::tempdir().unwrap(); + let pool = unmigrated(&dir.path().join("ob.sqlite")).await; + insert_row( + &pool, + "old-1", + json!({ "kind": "activity", "activity_summary": "export TOKEN=x" }), + ) + .await; + insert_row( + &pool, + "old-2", + json!({ "kind": "session_start", "project_path": "/home/u/work/fleetify" }), + ) + .await; + assert_eq!(user_version(&pool).await, 0); + + migrate(&pool).await.unwrap(); + assert_eq!(rows(&pool).await, 0, "rows from older builds dropped"); + assert_eq!(user_version(&pool).await, 1); + pool.close().await; + } + + #[tokio::test] + async fn rows_queued_after_the_migration_survive_the_next_start() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ob.sqlite"); + let pool = unmigrated(&path).await; + migrate(&pool).await.unwrap(); + insert_row(&pool, "new-1", json!({ "kind": "status_change" })).await; + pool.close().await; + + // Next launch: the same file is opened and migrated again. + let pool = unmigrated(&path).await; + migrate(&pool).await.unwrap(); + assert_eq!( + rows(&pool).await, + 1, + "a row queued after the migration survives" + ); + assert_eq!(user_version(&pool).await, 1); + pool.close().await; + } + + #[tokio::test] + async fn migration_marks_a_fresh_outbox_current() { + let dir = tempfile::tempdir().unwrap(); + let pool = unmigrated(&dir.path().join("ob.sqlite")).await; + migrate(&pool).await.unwrap(); + assert_eq!(user_version(&pool).await, 1); + assert_eq!(rows(&pool).await, 0); + pool.close().await; + } + + #[tokio::test] + async fn the_outbox_init_at_publishes_holds_no_rows_from_older_builds() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ob.sqlite"); + let legacy = unmigrated(&path).await; + insert_row( + &legacy, + "old-1", + json!({ "kind": "activity", "activity_summary": "rm -rf secret" }), + ) + .await; + legacy.close().await; + + // `open` is everything `init_at` does before it publishes the pool. + let pool = open(&path).await.unwrap(); + assert_eq!( + rows(&pool).await, + 0, + "older builds' rows visible to readers" + ); + assert_eq!(user_version(&pool).await, 1); + pool.close().await; + } + #[tokio::test] async fn bump_attempt_increments_per_event() { let _g = TEST_LOCK.lock().await; diff --git a/crates/fleetify-backend/src/services/telemetry/posthog/client.rs b/crates/fleetify-backend/src/services/telemetry/posthog/client.rs index f210c00..fb968b5 100644 --- a/crates/fleetify-backend/src/services/telemetry/posthog/client.rs +++ b/crates/fleetify-backend/src/services/telemetry/posthog/client.rs @@ -41,8 +41,7 @@ impl Client { } /// POST a batch of events. Each event is already a PostHog-shaped - /// payload from `mapper::to_posthog_event` (or a synthesised - /// `$identify` from `mod::identify_local`). + /// payload from `mapper::to_posthog_event`. pub async fn send_batch(&self, events: Vec) -> BatchOutcome { if events.is_empty() { return BatchOutcome::Acked; diff --git a/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs b/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs index df87579..f25118b 100644 --- a/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs +++ b/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs @@ -17,11 +17,11 @@ //! tick so flipping the gate off stops sends within ~10 s. //! //! The frontend's posthog-js handles its own consent / opt-out via the -//! same flag echoed through the `telemetry_get_config` Tauri command. +//! same gate, reported by the `telemetry_get_config` Tauri command. //! Distinct IDs are kept in sync: backend uses the persisted `device_id`; //! the frontend bootstraps posthog-js with the same id and calls -//! `posthog.identify(user_id, ...)` after OAuth so PostHog merges the -//! anonymous person into the authenticated one. +//! `posthog.identify(user_id)` (the id only) for a signed-in user, so +//! PostHog links the device's events to the account. mod client; mod mapper; @@ -126,30 +126,6 @@ pub async fn enqueue_if_enabled(fleetify_payload: &Value) { worker::event_available().notify_one(); } -/// Server-side `$identify`. Fires when the backend learns about an -/// authenticated user_id (post-OAuth). The frontend posthog-js also -/// calls identify(); both flow into the same PostHog person via the -/// `$anon_distinct_id` link. -pub async fn identify_local(user_id: &str, props: serde_json::Map) { - if !is_enabled() || project_key().is_none() { - return; - } - let event = serde_json::json!({ - "event": "$identify", - "distinct_id": user_id, - "properties": { - "$set": Value::Object(props), - "$anon_distinct_id": distinct_id(), - }, - }); - let event_id = uuid::Uuid::new_v4().to_string(); - if let Err(e) = outbox::enqueue(&event_id, &event).await { - tracing::warn!(target: "fleetify.posthog", "identify enqueue failed: {e}"); - return; - } - worker::event_available().notify_one(); -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/fleetify-backend/src/services/telemetry/ws_client.rs b/crates/fleetify-backend/src/services/telemetry/ws_client.rs index 809dcb2..52bb4bf 100644 --- a/crates/fleetify-backend/src/services/telemetry/ws_client.rs +++ b/crates/fleetify-backend/src/services/telemetry/ws_client.rs @@ -10,7 +10,17 @@ //! client → server: `{ "v":1, "type":"event", "id":"", "payload":{…} }` //! server → client: `{ "v":1, "type":"ack", "id":"" }` //! +//! Consent: nothing here runs while cloud sync is off (`cloud_gate`). The +//! loop idles without a bearer, a ticket or a socket, and a connected +//! socket is closed as soon as the gate closes. +//! +//! Logging: the bearer and the ticket appear only as `redact_token` +//! previews. Request and response bodies, response header values and frame +//! contents are never logged, and the errors the loop logs carry none of +//! them either. +//! //! Failure modes: +//! - cloud sync off → idle until it is turned on; no requests //! - bearer not signed in → long pause; no requests //! - bearer fetch / ticket fail → exponential backoff //! - WS upgrade 401 → backoff + refresh @@ -24,21 +34,28 @@ use futures_util::{SinkExt, StreamExt}; use serde_json::{json, Value}; use tokio_tungstenite::tungstenite::Message; -use super::{device_id, emitters, outbox}; +use super::{cloud_enabled, device_id, emitters, gate_changed, outbox}; pub const WIRE_VERSION: u32 = 1; const BACKOFF_INITIAL_S: u64 = 1; const BACKOFF_MAX_S: u64 = 30; const MAX_EVENTS_PER_FLUSH: i64 = 200; +/// How long a close frame may take when sync is turned off mid-connection. +const CLOSE_TIMEOUT: Duration = Duration::from_secs(2); +/// The realtime endpoints live on the identity provider's origin: +/// production in release builds, `FLEETIFY_ISSUER` (default: the local +/// IdP) in debug builds — the same origin the shell signs in against. fn issuer() -> String { - std::env::var("FLEETIFY_ISSUER").unwrap_or_else(|_| "https://fleetify.dev".to_string()) + fleetify_core::endpoints::issuer_origin() } fn ticket_url() -> String { format!("{}/api/realtime/ticket", issuer().trim_end_matches('/')) } fn ws_url() -> String { - let base = issuer(); + ws_url_for(&issuer()) +} +fn ws_url_for(base: &str) -> String { let trimmed = base.trim_end_matches('/'); let url = if let Some(rest) = trimmed.strip_prefix("https://") { format!("wss://{rest}") @@ -59,16 +76,18 @@ pub type BearerSource = Arc< + Sync, >; -/// Long-running task. Connects to the realtime endpoint, replays the -/// outbox, listens for acks, reconnects with exponential backoff. +/// Long-running task. While cloud sync is on: connects to the realtime +/// endpoint, replays the outbox, listens for acks, reconnects with +/// exponential backoff. While it is off: waits for it to be turned on. /// Never returns (cancellation expected on shutdown). pub async fn run_ws_client_loop(bearer_source: BearerSource) { let mut backoff_secs = BACKOFF_INITIAL_S; loop { + wait_until_cloud_enabled().await; match one_connection_attempt(&bearer_source).await { Ok(_) => { - // Clean disconnect (e.g. server closed). Reset backoff so - // we reconnect quickly. + // Clean disconnect (server closed, or sync turned off). + // Reset backoff so we reconnect quickly. backoff_secs = BACKOFF_INITIAL_S; } Err(e) => { @@ -83,6 +102,20 @@ pub async fn run_ws_client_loop(bearer_source: BearerSource) { } } +/// Returns once cloud sync is on. The `notified()` future is created +/// before the flag is checked: it receives `notify_waiters()` from the +/// moment it exists, so a gate change landing between the check and the +/// await still wakes it. +async fn wait_until_cloud_enabled() { + loop { + let changed = gate_changed().notified(); + if cloud_enabled() { + return; + } + changed.await; + } +} + async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { let bearer = match bearer_source().await { Some(b) => b, @@ -97,6 +130,10 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { target: "fleetify.telemetry.ws", "→ bearer acquired (len={}, prefix={})", bearer.len(), bearer_preview ); + // Sync may have been turned off while the bearer was being fetched. + if !cloud_enabled() { + return Ok(()); + } // 1. Fetch a ticket. let device = device_id::get_or_create(); @@ -111,6 +148,9 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { "← ticket acquired (len={}, prefix={})", ticket.len(), redact_token(&ticket) ); + if !cloud_enabled() { + return Ok(()); + } // 2. Open the WS. Ticket is sent as the SECOND value in the // `Sec-WebSocket-Protocol` subprotocol list (cloud's auth @@ -144,14 +184,15 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { return Err(anyhow!("WS upgrade failed: {e}")); } }; + // Header names only: a value could echo the ticket subprotocol. tracing::info!( target: "fleetify.telemetry.ws", "← ws handshake response status={} headers={:?}", handshake_resp.status(), handshake_resp .headers() - .iter() - .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())) + .keys() + .map(|k| k.as_str()) .collect::>() ); let (mut write, mut read) = ws_stream.split(); @@ -165,8 +206,22 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { let ping_interval = Duration::from_secs(30); loop { + // Created before the check, like in `wait_until_cloud_enabled`: a + // close landing after the check still wakes the select below. + let gate = gate_changed().notified(); + tokio::pin!(gate); + if !cloud_enabled() { + tracing::info!( + target: "fleetify.telemetry.ws", + "cloud sync turned off; closing the socket" + ); + let _ = tokio::time::timeout(CLOSE_TIMEOUT, write.close()).await; + return Ok(()); + } tokio::select! { biased; + // Gate change: the check at the top of the loop acts on it. + _ = &mut gate => {} // Outbox drainer _ = notify.notified() => { let pending = outbox::peek_pending(MAX_EVENTS_PER_FLUSH).await?; @@ -175,18 +230,16 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { } tracing::info!(target: "fleetify.telemetry.ws", "→ sending {} events", pending.len()); for (event_id, payload) in pending { - let envelope = json!({ - "v": WIRE_VERSION, - "type": "event", - "id": event_id, - "payload": payload, - }); - let frame = serde_json::to_string(&envelope)?; + // Turned off mid-batch: stop here. The purge has + // dropped the rest; the loop top closes the socket. + if !cloud_enabled() { + break; + } + let frame = event_frame(&event_id, &payload)?; tracing::info!( target: "fleetify.telemetry.ws", - "→ send event id={} frame={}", - event_id, - truncate(&frame, 2000) + "→ send {}", + frame_log(&frame) ); write.send(Message::Text(frame)).await .map_err(|e| anyhow!("ws send failed: {e}"))?; @@ -202,7 +255,7 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { Message::Text(t) => { tracing::info!( target: "fleetify.telemetry.ws", - "← recv text frame={}", truncate(&t, 2000) + "← recv {}", frame_log(&t) ); handle_inbound(&t).await } @@ -240,6 +293,20 @@ async fn one_connection_attempt(bearer_source: &BearerSource) -> Result<()> { } } +/// The wire frame for one outbox row. Sends the row's cloud view: new rows +/// are minimised when queued (and the view leaves them unchanged), but rows +/// queued by older builds may still carry activity summaries and full +/// project paths. +fn event_frame(event_id: &str, payload: &Value) -> Result { + let envelope = json!({ + "v": WIRE_VERSION, + "type": "event", + "id": event_id, + "payload": emitters::cloud_view(payload), + }); + Ok(serde_json::to_string(&envelope)?) +} + async fn handle_inbound(text: &str) { let Ok(msg): Result = serde_json::from_str(text) else { return; @@ -286,14 +353,19 @@ async fn handle_inbound(text: &str) { } async fn fetch_ticket(bearer: &str, device_id: &str) -> Result { - let url = ticket_url(); + fetch_ticket_at(&ticket_url(), bearer, device_id).await +} + +/// [`fetch_ticket`] against `url`, so tests can point it at a local server. +/// +/// Logs and errors carry the status and, at most, the ticket's redacted +/// preview: never the body (a server may echo the bearer in an error) or +/// the response headers. +async fn fetch_ticket_at(url: &str, bearer: &str, device_id: &str) -> Result { let payload = json!({ "deviceId": device_id }); - tracing::info!( - target: "fleetify.telemetry.ws", - "→ ticket POST url={} body={}", url, payload - ); + tracing::info!(target: "fleetify.telemetry.ws", "→ ticket POST url={url}"); let r = reqwest::Client::new() - .post(&url) + .post(url) .header("Authorization", format!("Bearer {bearer}")) .json(&payload) .timeout(Duration::from_secs(10)) @@ -301,35 +373,38 @@ async fn fetch_ticket(bearer: &str, device_id: &str) -> Result { .await .map_err(|e| anyhow!("ticket POST failed: {e}"))?; let status = r.status(); - let headers: Vec<(String, String)> = r - .headers() - .iter() - .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())) - .collect(); let body_text = r.text().await.unwrap_or_default(); + let body = serde_json::from_str::(&body_text); + let ticket = body + .as_ref() + .ok() + .and_then(|b| b.get("ticket")) + .and_then(Value::as_str) + .map(String::from); tracing::info!( target: "fleetify.telemetry.ws", - "← ticket response status={} headers={:?} body={}", - status, headers, truncate(&body_text, 2000) + "← ticket response {}", + ticket_response_log(status, ticket.as_deref()) ); if !status.is_success() { return Err(anyhow!( - "ticket POST returned {} ({}); body={}", + "ticket POST returned {} ({})", status.as_u16(), - status.canonical_reason().unwrap_or(""), - truncate(&body_text, 500) + status.canonical_reason().unwrap_or("") )); } - let body: Value = serde_json::from_str(&body_text).map_err(|e| { - anyhow!( - "ticket response decode failed: {e}; raw={}", - truncate(&body_text, 500) - ) - })?; - body.get("ticket") - .and_then(|v| v.as_str()) - .map(String::from) - .ok_or_else(|| anyhow!("ticket response missing `ticket` field; got {body}")) + // serde_json's message is a position, never the text. + body.map_err(|e| anyhow!("ticket response decode failed: {e}"))?; + ticket.ok_or_else(|| anyhow!("ticket response has no `ticket` field")) +} + +/// How the ticket endpoint's answer appears in the log: its status and, +/// when it holds a ticket, that ticket's redacted preview. +fn ticket_response_log(status: reqwest::StatusCode, ticket: Option<&str>) -> String { + match ticket { + Some(ticket) => format!("status={} ticket={}", status.as_u16(), redact_token(ticket)), + None => format!("status={}", status.as_u16()), + } } /// Redact a token/ticket to a `…` preview so logs never @@ -351,6 +426,28 @@ fn redact_token(s: &str) -> String { format!("{head}…{tail}") } +/// How a WebSocket frame appears in the log: its `type`, its `id` and, for +/// an event, the payload's `kind`. Never the rest: an event carries session +/// titles and folder names. +fn frame_log(text: &str) -> String { + let Ok(frame) = serde_json::from_str::(text) else { + return format!("<{} bytes, not JSON>", text.len()); + }; + let field = |v: Option<&Value>| { + v.and_then(Value::as_str) + .map_or_else(|| "-".to_string(), |s| truncate(s, 64)) + }; + let mut line = format!( + "type={} id={}", + field(frame.get("type")), + field(frame.get("id")) + ); + if let Some(kind) = frame.get("payload").and_then(|p| p.get("kind")) { + line.push_str(&format!(" kind={}", field(Some(kind)))); + } + line +} + /// Cap log lines at `max` chars so a 2 MB body doesn't fill the /// terminal scrollback. fn truncate(s: &str, max: usize) -> String { @@ -362,27 +459,17 @@ fn truncate(s: &str, max: usize) -> String { } } -/// Surface every detail of a tungstenite::Error so the user sees the -/// 400's response body, headers, and underlying cause. +/// Log why the WebSocket upgrade failed: the HTTP status, or the +/// underlying cause when there was no HTTP answer. fn log_ws_error(e: &tokio_tungstenite::tungstenite::Error) { use tokio_tungstenite::tungstenite::Error as WsErr; match e { + // The status only: the body or a header could echo the ticket. WsErr::Http(resp) => { - let status = resp.status(); - let headers: Vec<(String, String)> = resp - .headers() - .iter() - .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())) - .collect(); - let body = resp - .body() - .as_ref() - .map(|b| String::from_utf8_lossy(b).into_owned()) - .unwrap_or_default(); tracing::warn!( target: "fleetify.telemetry.ws", - "← ws upgrade HTTP {} headers={:?} body={}", - status, headers, truncate(&body, 2000) + "← ws upgrade refused: HTTP {}", + resp.status() ); } other => { @@ -415,17 +502,266 @@ fn urlencoding_minimal(s: &str) -> String { #[cfg(test)] mod tests { use super::*; + use crate::services::telemetry::cloud_gate::test_support::GateGuard; + use crate::services::telemetry::set_cloud_enabled; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[tokio::test] + async fn ws_loop_stays_idle_while_the_gate_is_closed() { + let _g = outbox::tests::TEST_LOCK.lock().await; + let _gate = GateGuard::new(); + set_cloud_enabled(false).await; + + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + let source: BearerSource = Arc::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + Box::pin(async { None }) + }); + + let run = + tokio::time::timeout(Duration::from_millis(300), run_ws_client_loop(source)).await; + assert!( + run.is_err(), + "the loop never returns; the timeout must fire" + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "no bearer may be fetched while cloud sync is off" + ); + } + + #[tokio::test] + async fn ws_loop_wakes_up_when_the_gate_opens() { + let _g = outbox::tests::TEST_LOCK.lock().await; + let _gate = GateGuard::new(); + set_cloud_enabled(false).await; + + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + // Not signed in: the loop then pauses for BACKOFF_MAX_S, so it asks once. + let source: BearerSource = Arc::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + Box::pin(async { None }) + }); + let task = tokio::spawn(run_ws_client_loop(source)); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(calls.load(Ordering::SeqCst), 0); + + set_cloud_enabled(true).await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + while calls.load(Ordering::SeqCst) == 0 && tokio::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(10)).await; + } + task.abort(); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "opening the gate must wake the idle loop" + ); + } + + #[test] + fn event_frames_send_only_the_cloud_view() { + // A row an older build queued: it still has the summary and the full path. + let frame = event_frame( + "evt-1", + &json!({ + "kind": "activity", + "local_session_id": "s1", + "activity_kind": "command", + "activity_summary": "export TOKEN=x", + "project_path": "/home/u/work/fleetify", + }), + ) + .unwrap(); + let v: Value = serde_json::from_str(&frame).unwrap(); + assert_eq!(v["v"], WIRE_VERSION); + assert_eq!(v["type"], "event"); + assert_eq!(v["id"], "evt-1"); + assert_eq!(v["payload"]["activity_kind"], "command"); + assert!( + v["payload"].get("activity_summary").is_none(), + "summary on the wire: {frame}" + ); + assert_eq!(v["payload"]["project_path"], "fleetify"); + } #[test] fn ws_url_translates_http_to_ws_and_https_to_wss() { - std::env::set_var("FLEETIFY_ISSUER", "https://fleetify.dev"); - assert_eq!(ws_url(), "wss://fleetify.dev/api/realtime/connect"); - std::env::set_var("FLEETIFY_ISSUER", "http://localhost:3001"); - assert_eq!(ws_url(), "ws://localhost:3001/api/realtime/connect"); + assert_eq!( + ws_url_for("https://fleetify.dev"), + "wss://fleetify.dev/api/realtime/connect" + ); + assert_eq!( + ws_url_for("http://localhost:3001"), + "ws://localhost:3001/api/realtime/connect" + ); // Trailing slash + no scheme = ws://. - std::env::set_var("FLEETIFY_ISSUER", "127.0.0.1:3001/"); - assert_eq!(ws_url(), "ws://127.0.0.1:3001/api/realtime/connect"); - std::env::remove_var("FLEETIFY_ISSUER"); + assert_eq!( + ws_url_for("127.0.0.1:3001/"), + "ws://127.0.0.1:3001/api/realtime/connect" + ); + } + + /// Everything logged on this thread while the guard lives, as plain text. + struct LogCapture { + lines: Arc>>, + _guard: tracing::subscriber::DefaultGuard, + } + + impl LogCapture { + fn start() -> Self { + let lines = Arc::new(std::sync::Mutex::new(Vec::new())); + let sink = Arc::clone(&lines); + let subscriber = tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_ansi(false) + .with_writer(move || CaptureWriter(Arc::clone(&sink))) + .finish(); + Self { + lines, + _guard: tracing::subscriber::set_default(subscriber), + } + } + + fn text(&self) -> String { + String::from_utf8_lossy(&self.lines.lock().unwrap()).into_owned() + } + } + + struct CaptureWriter(Arc>>); + + impl std::io::Write for CaptureWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + const BEARER: &str = "bearer-0123456789-SECRET-abcdef"; + const TICKET: &str = "tkt_0123456789-SECRET-ticket-wxyz"; + + #[tokio::test] + async fn the_ticket_response_is_logged_as_its_status_and_a_redacted_preview() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/realtime/ticket")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("set-cookie", "session=cookie-SECRET") + .set_body_json(json!({ "ticket": TICKET, "note": "body-SECRET" })), + ) + .mount(&server) + .await; + + let logs = LogCapture::start(); + let ticket = fetch_ticket_at( + &format!("{}/api/realtime/ticket", server.uri()), + BEARER, + "device-1", + ) + .await + .unwrap(); + let text = logs.text(); + + assert_eq!(ticket, TICKET); + assert!(text.contains("status=200"), "{text}"); + assert!(text.contains(&redact_token(TICKET)), "{text}"); + assert!( + !text.contains("SECRET"), + "a secret or the body was logged: {text}" + ); + } + + #[tokio::test] + async fn a_refused_ticket_request_logs_and_reports_only_its_status() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + // A server that echoes the request back in its error. + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(401) + .set_body_json(json!({ "error": format!("bad token {BEARER}") })), + ) + .mount(&server) + .await; + + let logs = LogCapture::start(); + let err = fetch_ticket_at(&server.uri(), BEARER, "device-1") + .await + .unwrap_err() + .to_string(); + let text = logs.text(); + + // The loop logs this error as is. + assert!(err.contains("401"), "{err}"); + assert!(!err.contains("SECRET"), "{err}"); + assert!(text.contains("status=401"), "{text}"); + assert!(!text.contains("SECRET"), "{text}"); + } + + #[tokio::test] + async fn an_unreadable_ticket_response_never_shows_its_body() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + for body in [ + format!("ticket={TICKET}"), // not JSON + json!({ "token": TICKET }).to_string(), // no `ticket` field + ] { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200).set_body_string(body.clone())) + .mount(&server) + .await; + + let logs = LogCapture::start(); + let err = fetch_ticket_at(&server.uri(), BEARER, "device-1") + .await + .unwrap_err() + .to_string(); + let text = logs.text(); + assert!(!err.contains("SECRET"), "{body}: {err}"); + assert!(!text.contains("SECRET"), "{body}: {text}"); + } + } + + #[test] + fn frames_are_logged_by_type_id_and_kind_only() { + let event = event_frame( + "evt-1", + &json!({ + "kind": "session_start", + "session_title": "title-SECRET", + "project_path": "/home/u/folder-SECRET", + }), + ) + .unwrap(); + let line = frame_log(&event); + assert!(line.contains("type=event"), "{line}"); + assert!(line.contains("id=evt-1"), "{line}"); + assert!(line.contains("kind=session_start"), "{line}"); + assert!(!line.contains("SECRET"), "{line}"); + + let ack = frame_log(r#"{"v":1,"type":"ack","id":"evt-1"}"#); + assert!( + ack.contains("type=ack") && ack.contains("id=evt-1"), + "{ack}" + ); + + let raw = frame_log("not json SECRET"); + assert!(!raw.contains("SECRET"), "{raw}"); + assert!(raw.contains("15 bytes"), "{raw}"); } #[test] diff --git a/crates/fleetify-core/Cargo.toml b/crates/fleetify-core/Cargo.toml index 464dc47..99c6f61 100644 --- a/crates/fleetify-core/Cargo.toml +++ b/crates/fleetify-core/Cargo.toml @@ -5,5 +5,11 @@ edition.workspace = true license.workspace = true [dependencies] -serde.workspace = true thiserror.workspace = true +# `loopback::http_client_builder`, the one builder every client of the app's +# own backend uses (the shell and the MCP sidecars). No features: each user +# brings its own TLS and json features. +reqwest = { version = "0.12", default-features = false } + +[dev-dependencies] +tokio.workspace = true diff --git a/crates/fleetify-core/src/endpoints.rs b/crates/fleetify-core/src/endpoints.rs new file mode 100644 index 0000000..7d00352 --- /dev/null +++ b/crates/fleetify-core/src/endpoints.rs @@ -0,0 +1,100 @@ +//! Auth endpoints shared by the desktop shell and the embedded backend. +//! +//! The shell's OAuth client and the backend's token validator must agree: +//! the shell asks the identity provider for an access token whose `aud` is +//! the API resource it names, and the backend accepts only tokens whose +//! `iss` is `{issuer}/api/auth` and whose `aud` is that same resource. +//! Both sides resolve the values here so they cannot drift apart. +//! +//! Release builds pin production `fleetify.dev` and ignore the environment, +//! so a variable left in a user's shell can neither break sign-in nor point +//! the app at another identity provider. Debug builds read the environment +//! (`npm run dev:tauri` sets it) so development can use a local IdP. + +/// Production identity-provider origin. better-auth serves under +/// `{origin}/api/auth` and stamps that base into every token's `iss`. +pub const PROD_ISSUER: &str = "https://fleetify.dev"; + +/// Production API resource indicator (RFC 8707): the `aud` of every access +/// token the shell requests and the embedded backend accepts. +pub const PROD_API_RESOURCE: &str = "https://fleetify.dev/api"; + +/// Debug default issuer: a local identity provider. +const DEV_ISSUER: &str = "http://localhost:3001"; + +/// Debug default resource: the embedded backend's loopback origin. +const DEV_API_RESOURCE: &str = "http://127.0.0.1:8765"; + +/// Identity-provider origin, without the `/api/auth` suffix. Release builds +/// return [`PROD_ISSUER`]; debug builds read `FLEETIFY_ISSUER` through `env` +/// and fall back to a local IdP. +pub fn issuer_origin_for(release: bool, env: &dyn Fn(&str) -> Option) -> String { + if release { + return PROD_ISSUER.to_string(); + } + env("FLEETIFY_ISSUER").unwrap_or_else(|| DEV_ISSUER.to_string()) +} + +/// API resource indicator, which is also the expected token audience. +/// Release builds return [`PROD_API_RESOURCE`]; debug builds read +/// `FLEETIFY_RESOURCE`, then `FLEETIFY_AUDIENCE`, through `env` and fall +/// back to the embedded backend's loopback origin. +pub fn api_resource_for(release: bool, env: &dyn Fn(&str) -> Option) -> String { + if release { + return PROD_API_RESOURCE.to_string(); + } + env("FLEETIFY_RESOURCE") + .or_else(|| env("FLEETIFY_AUDIENCE")) + .unwrap_or_else(|| DEV_API_RESOURCE.to_string()) +} + +/// [`issuer_origin_for`] for this build profile and the process environment. +pub fn issuer_origin() -> String { + issuer_origin_for(!cfg!(debug_assertions), &|k| std::env::var(k).ok()) +} + +/// [`api_resource_for`] for this build profile and the process environment. +pub fn api_resource() -> String { + api_resource_for(!cfg!(debug_assertions), &|k| std::env::var(k).ok()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_pins_prod_issuer_even_when_env_is_set() { + let env = |k: &str| (k == "FLEETIFY_ISSUER").then(|| "http://evil.test".to_string()); + assert_eq!(issuer_origin_for(true, &env), "https://fleetify.dev"); + } + + #[test] + fn debug_issuer_defaults_to_local_idp_and_honours_env() { + assert_eq!(issuer_origin_for(false, &|_| None), "http://localhost:3001"); + assert_eq!( + issuer_origin_for(false, &|_| Some("http://idp.test".into())), + "http://idp.test" + ); + } + + #[test] + fn release_pins_prod_resource() { + assert_eq!( + api_resource_for(true, &|_| Some("http://evil.test".into())), + "https://fleetify.dev/api" + ); + } + + #[test] + fn debug_resource_prefers_resource_then_audience_then_default() { + let both = |k: &str| match k { + "FLEETIFY_RESOURCE" => Some("a".into()), + "FLEETIFY_AUDIENCE" => Some("b".into()), + _ => None, + }; + let aud = |k: &str| (k == "FLEETIFY_AUDIENCE").then(|| "b".to_string()); + assert_eq!(api_resource_for(false, &both), "a"); + assert_eq!(api_resource_for(false, &aud), "b"); + assert_eq!(api_resource_for(false, &|_| None), "http://127.0.0.1:8765"); + } +} diff --git a/crates/fleetify-core/src/lib.rs b/crates/fleetify-core/src/lib.rs index b80eddd..acf1328 100644 --- a/crates/fleetify-core/src/lib.rs +++ b/crates/fleetify-core/src/lib.rs @@ -1,7 +1,13 @@ -//! Shared, I/O-free domain types for the Fleetify backend + shell. +//! Shared, I/O-free domain types for the Fleetify backend + shell, and the +//! HTTP client builder for calls to the app's own loopback services +//! ([`loopback`]), shared with the MCP sidecars. use std::path::{Path, PathBuf}; +pub mod endpoints; +pub mod loopback; +pub mod text; + /// Backend wire-protocol version. Bumped only on breaking WS/REST changes. pub const PROTOCOL_VERSION: u32 = 1; diff --git a/crates/fleetify-core/src/loopback.rs b/crates/fleetify-core/src/loopback.rs new file mode 100644 index 0000000..953863e --- /dev/null +++ b/crates/fleetify-core/src/loopback.rs @@ -0,0 +1,116 @@ +//! HTTP clients for the services the app runs on this machine: its embedded +//! backend, and in debug builds the Vite dev server. +//! +//! reqwest sends requests through the proxy named in `HTTP_PROXY`, +//! `HTTPS_PROXY` or `ALL_PROXY` (or their lowercase forms), and hyper-util's +//! proxy matcher exempts no loopback address: only `NO_PROXY` does. With a +//! proxy set that isn't running, the startup poll would never reach the +//! backend and the window would stay on "Starting Fleetify…"; with one that +//! is, provider keys and the internal secret would cross it in plaintext. +//! +//! Every client that talks to the app's own backend, in the shell and in the +//! MCP sidecars, starts from [`http_client_builder`]. Clients that reach the +//! internet (providers, the issuer, GitHub) don't: they keep honouring the +//! user's proxy. + +/// A reqwest client builder for calls to a service the app runs on this +/// machine. It never uses a proxy, whatever the environment says. +pub fn http_client_builder() -> reqwest::ClientBuilder { + reqwest::Client::builder().no_proxy() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// Set in the child process the proxy test re-runs itself in. + const CHILD: &str = "FLEETIFY_LOOPBACK_PROXY_TEST_CHILD"; + + /// The test the child process runs, by its full name. + const CHILD_TEST: &str = "loopback::tests::child_requests_through_the_builder_with_a_proxy_set"; + + /// A port on 127.0.0.1 nothing listens on. + fn closed_port() -> u16 { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + } + + #[test] + fn a_proxy_in_the_environment_is_never_used() { + // The proxy variables are set only in a child process (this test + // binary, running the one test below), so no other test sees them. + let proxy = format!("http://127.0.0.1:{}", closed_port()); + let mut child = Command::new(std::env::current_exe().unwrap()); + child + .args(["--exact", CHILD_TEST, "--ignored", "--test-threads=1"]) + .env(CHILD, "1"); + for name in [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] { + child.env(name, &proxy); + } + // An exemption or a CGI environment would turn the proxy off. + for name in ["NO_PROXY", "no_proxy", "REQUEST_METHOD"] { + child.env_remove(name); + } + let out = child.output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + out.status.success(), + "with HTTP_PROXY={proxy}, a request through the builder failed:\n{stdout}\n{stderr}" + ); + assert!( + stdout.contains("1 passed"), + "the child process didn't run {CHILD_TEST}:\n{stdout}\n{stderr}" + ); + } + + /// Run by [`a_proxy_in_the_environment_is_never_used`] in a child process + /// whose proxy variables point at a closed port. Run any other way, it + /// checks nothing. + #[test] + #[ignore = "run by a_proxy_in_the_environment_is_never_used, with a proxy set"] + fn child_requests_through_the_builder_with_a_proxy_set() { + if std::env::var_os(CHILD).is_none() { + return; + } + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://127.0.0.1:{}/", listener.local_addr().unwrap().port()); + tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let mut request = [0u8; 1024]; + let _ = socket.read(&mut request).await; + let _ = socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\nloopback") + .await; + } + }); + + // reqwest's default client goes through the proxy, which isn't + // there: otherwise this test would prove nothing. + let default = reqwest::Client::builder().build().unwrap(); + assert!( + default.get(&url).send().await.is_err(), + "reqwest didn't use the proxy in the environment" + ); + + let client = http_client_builder().build().unwrap(); + let response = client.get(&url).send().await.expect("the request failed"); + assert_eq!(response.text().await.unwrap(), "loopback"); + }); + } +} diff --git a/crates/fleetify-core/src/text.rs b/crates/fleetify-core/src/text.rs new file mode 100644 index 0000000..5756abe --- /dev/null +++ b/crates/fleetify-core/src/text.rs @@ -0,0 +1,78 @@ +//! Shortening text without splitting a character. +//! +//! `String::truncate(n)` and `&s[..n]` take a byte index and panic when it +//! falls inside a multi-byte character. Turkish letters (ş ı ğ ü ö ç) are two +//! bytes each and emoji four, so a byte cut on user- or model-supplied text +//! crashes as soon as that text is not ASCII. These helpers always cut on a +//! character boundary. + +/// Keep at most `max_chars` characters (Unicode scalar values) of `s`. +/// +/// For limits stated in characters, such as the 72-character commit subject. +/// Text that is already short enough is left untouched. +pub fn truncate_chars(s: &mut String, max_chars: usize) { + if let Some((cut, _)) = s.char_indices().nth(max_chars) { + s.truncate(cut); + } +} + +/// The longest prefix of `s` that is at most `max_bytes` bytes long and ends +/// on a character boundary. +/// +/// For limits stated in bytes, such as a log-line budget: a cut that lands +/// inside a character backs off to the start of that character, so the +/// prefix can come out up to three bytes shorter than `max_bytes`. +pub fn prefix_within_bytes(s: &str, max_bytes: usize) -> &str { + // Stable since Rust 1.91; returns `s.len()` when `max_bytes` is past the end. + &s[..s.floor_char_boundary(max_bytes)] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncate_chars_cuts_turkish_text_to_72_characters() { + let mut s = format!("{}şğ", "a".repeat(71)); + truncate_chars(&mut s, 72); + assert_eq!(s.chars().count(), 72); + assert!(s.ends_with('ş'), "last kept character is ş: {s:?}"); + } + + #[test] + fn truncate_chars_leaves_short_text_unchanged() { + let mut s = "kısa metin".to_string(); + assert_eq!(s.chars().count(), 10); + truncate_chars(&mut s, 72); + assert_eq!(s, "kısa metin"); + } + + #[test] + fn truncate_chars_keeps_whole_emoji() { + let mut s = "👍".repeat(80); + truncate_chars(&mut s, 72); + assert_eq!(s.chars().count(), 72); + // 72 whole four-byte emoji: no partial character survives the cut. + assert_eq!(s.len(), 72 * 4); + assert_eq!(s, "👍".repeat(72)); + } + + #[test] + fn prefix_within_bytes_backs_off_to_the_previous_boundary() { + // "ş" is two bytes, so the boundaries are 0, 1 and 3. + assert_eq!(prefix_within_bytes("aş", 2), "a"); + } + + #[test] + fn prefix_within_bytes_keeps_a_cut_that_is_already_a_boundary() { + let s = "ı".repeat(1500); // two bytes each + assert_eq!(s.len(), 3000); + assert_eq!(prefix_within_bytes(&s, 2048).len(), 2048); + assert_eq!(prefix_within_bytes(&s, 2047).len(), 2046); + } + + #[test] + fn prefix_within_bytes_leaves_short_ascii_unchanged() { + assert_eq!(prefix_within_bytes("hello", 2048), "hello"); + } +} diff --git a/crates/memory-mcp/Cargo.toml b/crates/memory-mcp/Cargo.toml index 888e76e..5d608dd 100644 --- a/crates/memory-mcp/Cargo.toml +++ b/crates/memory-mcp/Cargo.toml @@ -18,4 +18,6 @@ tokio = { version = "1", default-features = false, features = ["rt", "macros", " serde.workspace = true serde_json.workspace = true anyhow.workspace = true +# fleetify_core::loopback: the no-proxy client builder for calls to the backend. +fleetify-core.workspace = true reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } diff --git a/crates/memory-mcp/src/main.rs b/crates/memory-mcp/src/main.rs index d75b4f7..bea63e6 100644 --- a/crates/memory-mcp/src/main.rs +++ b/crates/memory-mcp/src/main.rs @@ -153,6 +153,14 @@ fn env_or(k: &str, default: &str) -> String { std::env::var(k).unwrap_or_else(|_| default.to_string()) } +/// The client for calls to the backend: never through a proxy, which would +/// see the bearer token (`fleetify_core::loopback`). +fn backend_client() -> Result { + fleetify_core::loopback::http_client_builder() + .build() + .map_err(|e| format!("HTTP client: {e}")) +} + async fn remember(args: Value) -> Result { let session_id = std::env::var("FLEETIFY_SESSION_ID") .map_err(|_| "FLEETIFY_SESSION_ID env var missing".to_string())?; @@ -166,7 +174,7 @@ async fn remember(args: Value) -> Result { return Err("title and content are required".into()); } let url = format!("{backend}/api/sessions/{session_id}/memory"); - let r = reqwest::Client::new() + let r = backend_client()? .post(&url) .bearer_auth(&bearer) .json(&json!({ "title": title, "content": content, "kind": kind })) @@ -191,7 +199,7 @@ async fn recall(args: Value) -> Result { .unwrap_or(10) .clamp(1, 50); let url = format!("{backend}/api/sessions/{session_id}/memory?limit={limit}"); - let r = reqwest::Client::new() + let r = backend_client()? .get(&url) .bearer_auth(&bearer) .send() diff --git a/crates/reveng-mcp/src/main.rs b/crates/reveng-mcp/src/main.rs index eeeeb31..c911945 100644 --- a/crates/reveng-mcp/src/main.rs +++ b/crates/reveng-mcp/src/main.rs @@ -255,26 +255,7 @@ async fn discover_assets(args: Value) -> Result { ("data-src", "script_or_image"), ("href", "link_or_stylesheet"), ] { - let mut i = 0usize; - while i < body.len() { - let needle = format!("{attr}="); - let Some(rel) = body[i..].find(&needle) else { - break; - }; - let start = i + rel + needle.len(); - if start >= body.len() { - break; - } - let quote = body.as_bytes()[start]; - if quote != b'"' && quote != b'\'' { - i = start + 1; - continue; - } - let body_start = start + 1; - let Some(rel_end) = body[body_start..].find(quote as char) else { - break; - }; - let raw = &body[body_start..body_start + rel_end]; + for raw in quoted_attr_values(&body, attr) { let abs = resolve_url(raw, &origin, &dir); if !abs.is_empty() && !seen.contains(&abs) { seen.insert(abs.clone()); @@ -305,7 +286,6 @@ async fn discover_assets(args: Value) -> Result { }; bucket.push(abs); } - i = body_start + rel_end + 1; } } @@ -319,6 +299,40 @@ async fn discover_assets(args: Value) -> Result { })) } +/// Values of every quoted `attr="…"` / `attr='…'` in `body`, in document +/// order. Unquoted values are skipped. Plain substring match, so `src` also +/// sees `data-src=`; discover_assets dedups. +fn quoted_attr_values<'a>(body: &'a str, attr: &str) -> Vec<&'a str> { + let needle = format!("{attr}="); + let mut values = Vec::new(); + let mut i = 0usize; + while i < body.len() { + let Some(rel) = body[i..].find(&needle) else { + break; + }; + let start = i + rel + needle.len(); + if start >= body.len() { + break; + } + let quote = body.as_bytes()[start]; + if quote != b'"' && quote != b'\'' { + // Resume at `start`, right after the ASCII `=`, so always a char + // boundary. `start + 1` can land inside a multi-byte letter, + // where the next `body[i..]` would panic. The needle ends before + // `start`, so the next `find` cannot match it again. + i = start; + continue; + } + let body_start = start + 1; + let Some(rel_end) = body[body_start..].find(quote as char) else { + break; + }; + values.push(&body[body_start..body_start + rel_end]); + i = body_start + rel_end + 1; + } + values +} + fn split_origin_and_dir(url: &str) -> (String, String) { // Returns (origin, dirname-of-path). Best-effort lex split. let after_scheme = if let Some(rest) = url.strip_prefix("https://") { @@ -531,8 +545,10 @@ fn push_hit( return; } seen.insert(url.to_string()); - let ctx_start = start.saturating_sub(60); - let ctx_end = std::cmp::min(content.len(), end + 60); + // ~60 bytes either side, each edge backed off to a character boundary: + // slicing inside a multi-byte letter panics. Past the end clamps to len. + let ctx_start = content.floor_char_boundary(start.saturating_sub(60)); + let ctx_end = content.floor_char_boundary(end + 60); let context: String = content[ctx_start..ctx_end] .chars() .map(|c| if c == '\n' { ' ' } else { c }) @@ -593,3 +609,66 @@ fn _ensure_write_in_scope() { } // (base64 is a direct dep — pinned in Cargo.toml. No marker needed.) + +#[cfg(test)] +mod tests { + use super::*; + + /// Regression: each hit's context window reaches 60 bytes either side + /// of the URL, and a window edge inside a multi-byte letter panicked. + /// Fetched bundles are full of Turkish, CJK and emoji string literals. + #[test] + fn find_endpoints_context_never_splits_a_letter() { + let url = "https://api.example.com/v1/items"; + let content = format!("{}a{url} {}", "ş".repeat(40), "ğ".repeat(40)); + let start = content.find(url).unwrap(); + let end = start + url.len(); + assert!( + !content.is_char_boundary(start - 60) && !content.is_char_boundary(end + 60), + "fixture must put both window edges inside a letter" + ); + + let out = find_endpoints(json!({ "content": content })).unwrap(); + + assert_eq!(out["count"], 1); + assert_eq!(out["endpoints"][0]["url"], url); + let context = out["endpoints"][0]["context"].as_str().unwrap(); + assert!(context.contains(url), "{context}"); + } + + /// Regression: an unquoted value made the scan resume one byte past the + /// `=`, inside the first letter here, and slicing there panicked. Tool + /// calls run inline, so the panic took the whole sidecar down. + #[test] + fn quoted_attr_values_skips_unquoted_non_ascii_value() { + assert!(quoted_attr_values("", "href").is_empty()); + } + + /// Same crash from a Windows-1254 page: fetch_url's lossy decode turns + /// `\xFC` into U+FFFD, which is 3 bytes. + #[test] + fn quoted_attr_values_skips_unquoted_replacement_char_value() { + assert!(quoted_attr_values("", "href").is_empty()); + } + + #[test] + fn quoted_attr_values_extracts_quoted_non_ascii_value() { + assert_eq!( + quoted_attr_values(r#""#, "href"), + vec!["ürünler.html"] + ); + } + + /// discover_assets buckets values in the order they come back and keeps + /// the first sighting of a URL, so document order is part of the contract. + #[test] + fn quoted_attr_values_keeps_document_order_past_unquoted_values() { + assert_eq!( + quoted_attr_values( + r#"\n`, + "assets/auth.js": `const clientId = "fleetify-desktop";\n`, + }); + const result = runCli(dir); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout, ""); + }); + + test("exits 2 with a usage line when given no path", () => { + const result = runCli(); + assert.equal(result.status, 2); + assert.match(result.stderr, /usage/i); + }); + + test("exits 2 when a path does not exist, even if the others are clean", () => { + const clean = tree("cli-missing", { "index.html": "ok\n" }); + const missing = join(ROOT, "no-such-dir"); + const result = runCli(clean, missing); + assert.equal(result.status, 2); + assert.ok(result.stderr.includes(missing), result.stderr); + }); + + test("exits 2 when a path holds no files to scan", () => { + const empty = tree("cli-empty", {}); + const result = runCli(empty); + assert.equal(result.status, 2); + assert.match(result.stderr, /no files/); + }); +}); diff --git a/scripts/wipe.mjs b/scripts/wipe.mjs index 90837be..d970716 100644 --- a/scripts/wipe.mjs +++ b/scripts/wipe.mjs @@ -19,18 +19,20 @@ * ~/.cache, which is just cache). * 3. OS credential store — every entry whose service is `Fleetify` * or `Fleetify-*` (OIDC refresh token, - * `Fleetify-GitHub`, `Fleetify-Provider-`, + * `Fleetify-GitHub`, `Fleetify-Voice`, + * `Fleetify-Provider-`, * `Fleetify-Router-`). Backend differs by * OS: macOS Keychain (`security`), Windows * Credential Manager (`cmdkey`), and on Linux - * the KERNEL keyring (linux-keyutils) cleared - * via the `fleet-wipe` helper — secret-tool - * targets the Secret Service, the wrong store. + * the Secret Service (GNOME Keyring, KWallet, + * ...) cleared via the `fleet-wipe` helper, + * which also sweeps the kernel keyring that + * builds before the Secret Service used. * * Idempotent: missing paths are skipped silently. Logs every action so * you can audit what was touched. * - * Pass `--keep-keychain` to skip step 4 (useful when you want to reset + * Pass `--keep-keychain` to skip step 3 (useful when you want to reset * onboarding state without re-running OAuth). */ @@ -46,7 +48,6 @@ import { fileURLToPath } from "node:url"; import { isFleetifyKeychainTarget, parseMacKeychainDump, - parseSecretToolDump, } from "./wipe/keychain-filter.mjs"; const ARGS = new Set(process.argv.slice(2)); @@ -249,43 +250,18 @@ function wipeKeychainMac() { } } +// Linux — the app's `keyring` crate keeps credentials in the Secret Service +// (GNOME Keyring, KWallet, ...). We shell out to the `fleet-wipe` Rust helper: +// it deletes every Secret Service item keyring created whose service is +// `Fleetify` / `Fleetify-*` (the OIDC refresh token plus GitHub / voice / +// provider / router keys), and invalidates the `keyring-rs:*@Fleetify*` keys +// that builds before the Secret Service store left in the kernel keyring. No +// secret-tool needed. fleet-wipe exits non-zero when its Secret Service sweep +// fails (unreachable, left locked, or an item can't be deleted). function wipeKeychainLinux() { - // `secret-tool search --all` lists every secret with attributes; - // we never look at the secret value, only `attribute.service`. - const dump = spawnSync("secret-tool", ["search", "--all"], { encoding: "utf8" }); - if (dump.status !== 0) { - // Missing secret-tool is the common fresh-install case — log, - // don't error. - console.log(" · keychain skip secret-tool unavailable (status", dump.status, ")"); - return; - } - const services = parseSecretToolDump(dump.stdout); - if (services.length === 0) { - console.log(" · keychain skip no Fleetify* services found"); - return; - } - for (const service of services) { - const r = spawnSync("secret-tool", ["clear", "service", service], { encoding: "utf8" }); - if (r.status === 0) { - console.log(` ✓ keychain cleared service=${service}`); - } else { - console.log(` ✗ keychain FAILED service=${service}`); - if (r.stderr) console.log(` ${r.stderr.trim()}`); - } - } -} - -// Linux kernel keyring (linux-keyutils) — the store the app's `keyring` crate -// ACTUALLY uses on Linux (verified: `/proc/keys` holds -// `keyring-rs:refresh_token@Fleetify`). secret-tool / the Secret Service never -// see these keys, which is why a wipe left the user signed in. We shell out to -// the `fleet-wipe` Rust helper — it links the same backend the app does and -// invalidates every `keyring-rs:*@Fleetify*` key (the OIDC refresh token plus -// provider / github / router keys). -function wipeKeychainLinuxKernel() { const run = spawnSync("cargo", ["run", "-q", "-p", "fleet-wipe"], { encoding: "utf8" }); if (run.error) { - console.log(" ✗ keychain (kernel) FAILED could not run fleet-wipe via cargo"); + console.log(" ✗ keychain FAILED could not run fleet-wipe via cargo"); console.log(` ${run.error.message}`); console.log(" The OIDC refresh token may persist — install Rust/cargo, then re-run `npm run wipe`."); return; @@ -294,9 +270,9 @@ function wipeKeychainLinuxKernel() { if (line.trim()) console.log(` ${line.trimEnd()}`); } if (run.status === 0) { - console.log(" ✓ keychain (kernel) cleared via fleet-wipe (linux-keyutils)"); + console.log(" ✓ keychain cleared via fleet-wipe (Secret Service + kernel keyring)"); } else { - console.log(" ✗ keychain (kernel) FAILED fleet-wipe exited", run.status); + console.log(" ✗ keychain FAILED fleet-wipe exited", run.status); if (run.stderr) console.log(` ${run.stderr.trim()}`); } } @@ -320,11 +296,8 @@ if (KEEP_KEYCHAIN) { } else if (plat === "darwin") { wipeKeychainMac(); } else { - // Linux: the app's keyring backend is the KERNEL keyring (linux-keyutils), - // which secret-tool can't reach — clear it via the fleet-wipe helper. Still - // run secret-tool too (harmless) in case an older build wrote to the Secret - // Service. - wipeKeychainLinuxKernel(); + // Linux: fleet-wipe clears the Secret Service (the app's keyring store) and + // the kernel keyring older builds used. wipeKeychainLinux(); } diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 2abf046..ce87c59 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -14,9 +14,6 @@ crate-type = ["cdylib", "rlib"] [build-dependencies] tauri-build = { version = "2", features = [] } -# Read POSTHOG_* keys from `.env` at compile time so the renderer never -# sees the API key and the literal string doesn't sit in tracked source. -dotenvy = "0.15" [dependencies] fleetify-core.workspace = true @@ -35,14 +32,13 @@ zip = { version = "2", default-features = false, features = ["deflate"] } serde.workspace = true serde_json.workspace = true anyhow.workspace = true -# Windows is the current build/dev target; per-OS backends (apple-native / -# sync-secret-service) get added behind cfg in Phase 5 packaging. -keyring = { version = "3", features = ["windows-native"] } +# Same feature set as fleetify-backend (rationale there): the Secret Service +# store keeps Linux sign-in and provider keys across reboots. +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "multipart"] } sha2 = "0.10" base64 = "0.22" rand = "0.8" -open = "5" tiny_http = "0.12" url = "2" arboard = "3" @@ -90,6 +86,10 @@ x11-dl = "2" [dev-dependencies] tempfile = "3" +# The vendored runtime (root Cargo.toml's [patch.crates-io]), for the tests of +# its postMessage IPC patch (vendor/tauri-runtime-wry/FLEETIFY_PATCH.md). +# No features: tauri enables the ones it needs. +tauri-runtime-wry = { version = "2", default-features = false } [features] # On-device Whisper ships by DEFAULT so the offline voice engine works out diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 261851f..a53d89e 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,3 +1,44 @@ +// The app's commands (`APP_COMMANDS`) and the check against lib.rs, shared +// with the crate's tests. +include!("src/app_commands.rs"); + fn main() { - tauri_build::build(); + // Every command lib.rs registers must be in the manifest: one that isn't + // is refused at runtime, and the test that says so doesn't block a + // merge. Checked here, so a mismatch fails the build. Including lib.rs + // makes Cargo rebuild and rerun this script whenever it changes. + let registered = + registered_commands(include_str!("src/lib.rs")).unwrap_or_else(|error| panic!("{error}")); + if let Some(drift) = manifest_drift(®istered) { + panic!("{drift}"); + } + + // The release UI ships as a bundled resource: `bundle.resources` in + // tauri.conf.json maps the built `../dist` to `dist` in the install's + // resource folder, the only place a release build serves it from + // (shell::ui_files). tauri-build copies the resources into the target + // folder on every build, debug ones too, and fails when a path is + // missing; `../dist` exists only after a frontend build, which + // `tauri build` runs first. Make sure the folder is there, empty if need + // be, so a build without one (CI's Rust job, `tauri dev` on a fresh + // clone) still compiles. A release binary built that way has no UI files + // and says so at startup. Watching the folder copies it again once a + // frontend build fills it. + std::fs::create_dir_all("../dist").expect("creating ../dist for bundle.resources"); + println!("cargo:rerun-if-changed=../dist"); + + // The app's ACL manifest. tauri-build generates an `allow-*` and a + // `deny-*` permission for every app command, in + // `permissions/autogenerated/` (rewritten on every build, not committed). + // `capabilities/default.json` grants them to the main webview through + // the `app-commands` set (`permissions/app-commands.toml`), and setup + // grants the same to the app's own origin. Without a manifest, app + // commands have no permissions to grant, and Tauri refuses them from any + // remote origin: the release UI, which the embedded backend serves on + // `http://127.0.0.1:`, is one. + tauri_build::try_build( + tauri_build::Attributes::new() + .app_manifest(tauri_build::AppManifest::new().commands(APP_COMMANDS)), + ) + .expect("failed to run tauri-build"); } diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 4468f14..15b8076 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,10 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Core perms + IPC on the embedded-backend origin (dev Vite + prod axum)", - "windows": ["main"], - "remote": { - "urls": ["http://localhost:3000", "http://127.0.0.1:8765"] - }, - "permissions": ["core:default", "core:event:default", "dialog:allow-open"] + "description": "Core perms + the app's commands from local origins only (devUrl in dev mode), for the main webview only: never the browser panel's child webview. The app's own http origin gets the same at setup (src/shell/startup_window.rs); no other remote origin gets anything", + "webviews": ["main"], + "permissions": ["core:default", "core:event:default", "dialog:allow-open", "app-commands"] } diff --git a/src-tauri/permissions/app-commands.toml b/src-tauri/permissions/app-commands.toml new file mode 100644 index 0000000..dfadd25 --- /dev/null +++ b/src-tauri/permissions/app-commands.toml @@ -0,0 +1,144 @@ +# Every app command. capabilities/default.json grants this set to the main +# webview from local origins, and the capability setup adds grants it from +# the app's own origin (src/shell/startup_window.rs). tauri-build generates +# each allow-* from the command list in src/app_commands.rs; a test keeps +# this set equal to it. + +[[set]] +identifier = "app-commands" +description = "Allows every command the app registers." +permissions = [ + "allow-auth-sign-in", + "allow-auth-sign-out", + "allow-auth-userinfo", + "allow-auth-get-access-token", + "allow-auth-get-state", + "allow-config-get", + "allow-config-set", + "allow-telemetry-get-config", + "allow-telemetry-set-posthog-enabled", + "allow-telemetry-set-cloud-enabled", + "allow-shell-open-external", + "allow-shell-show-item-in-folder", + "allow-shell-open-path", + "allow-detect-editors", + "allow-open-in-editor", + "allow-clipboard-write", + "allow-browser-embed-create", + "allow-browser-embed-navigate", + "allow-browser-embed-set-bounds", + "allow-browser-embed-set-select", + "allow-browser-embed-nav", + "allow-browser-embed-devtools", + "allow-browser-embed-clear-data", + "allow-browser-embed-close", + "allow-window-start-dragging", + "allow-window-minimize", + "allow-window-maximize", + "allow-window-close", + "allow-window-set-size", + "allow-window-set-taskbar-icon", + "allow-fs-read-directory", + "allow-fs-read-file", + "allow-fs-get-extension", + "allow-fs-get-project-root", + "allow-fs-scaffold-plugin", + "allow-dialog-open-folder", + "allow-dialog-open-file", + "allow-git-get-context", + "allow-git-working-diff", + "allow-git-has-gh-cli", + "allow-git-has-git", + "allow-git-list-branches", + "allow-git-set-base-branch", + "allow-git-checkout", + "allow-git-commit", + "allow-git-push", + "allow-pty-spawn", + "allow-pty-write", + "allow-pty-resize", + "allow-pty-kill", + "allow-pty-buffer", + "allow-git-ensure-repo", + "allow-git-pull-latest", + "allow-git-diff-summary", + "allow-git-open-pr", + "allow-git-create-pr", + "allow-git-get-pr-status", + "allow-git-list-prs", + "allow-git-merge-pr", + "allow-git-rerun-check-job", + "allow-git-rerun-failed-checks", + "allow-git-delete-remote-branch", + "allow-git-pr-ready", + "allow-git-sync-main", + "allow-git-fetch-base", + "allow-git-carve-next-round", + "allow-git-preflight-check", + "allow-shell-check-github-auth", + "allow-gh-auth-login-launch", + "allow-gh-auth-login-capture", + "allow-gh-auth-login-cancel", + "allow-shell-install-provider", + "allow-shell-check-python-runtime", + "allow-shell-install-ollama", + "allow-git-watch-head", + "allow-git-unwatch-head", + "allow-github-get-link", + "allow-github-begin-oauth", + "allow-github-cancel-oauth", + "allow-github-refresh-link", + "allow-github-disconnect", + "allow-github-open-installation", + "allow-github-list-repos", + "allow-github-list-installations", + "allow-voice-list-devices", + "allow-voice-start-recording", + "allow-voice-stop-recording", + "allow-voice-transcribe", + "allow-voice-set-byok-key", + "allow-voice-has-byok-key", + "allow-voice-list-models", + "allow-voice-download-model", + "allow-voice-cancel-download", + "allow-routers-list-routers", + "allow-routers-connect", + "allow-routers-disconnect", + "allow-routers-set-active", + "allow-routers-set-master-toggle", + "allow-routers-test-router", + "allow-routers-get-key-preview", + "allow-providers-list-catalog", + "allow-providers-set-key", + "allow-providers-get-key-preview", + "allow-providers-delete-key", + "allow-providers-set-enabled", + "allow-providers-set-default", + "allow-providers-set-connected-bulk", + "allow-providers-test-connection", + "allow-providers-ollama-probe", + "allow-providers-ollama-ps", + "allow-providers-ollama-pull", + "allow-providers-ollama-pull-cancel", + "allow-providers-ollama-delete", + "allow-providers-set-enabled-models", + "allow-providers-set-ollama-base-url", + "allow-providers-set-ollama-cloud-base-url", + "allow-providers-set-cloudflare-account-id", + "allow-providers-set-account-key", + "allow-providers-get-account-key-preview", + "allow-providers-delete-account-key", + "allow-providers-open-account-login", + "allow-agent-login-default", + "allow-git-generate-commit-message", + "allow-git-generate-pr-summary", + "allow-git-review-diff", + "allow-git-diagnose-failure", + "allow-git-apply-recovery", + "allow-git-apply-preflight-fix", + "allow-git-diff-summary-simple", + "allow-app-log", + "allow-logs-export", + "allow-logs-open-folder", + "allow-feedback-send", +] diff --git a/src-tauri/src/app_commands.rs b/src-tauri/src/app_commands.rs new file mode 100644 index 0000000..5ff0a14 --- /dev/null +++ b/src-tauri/src/app_commands.rs @@ -0,0 +1,281 @@ +// The app's own Tauri commands, by name: every command `lib.rs` registers +// with `tauri::generate_handler!`. +// +// This list is the app's ACL manifest. `build.rs` includes this file and +// hands the list to tauri-build (`AppManifest::commands`), which generates an +// `allow-` and a `deny-` permission for each, with +// underscores turned into hyphens. `permissions/app-commands.toml` gathers +// every `allow-*` into the `app-commands` set, and +// `capabilities/default.json` grants that set to the main webview only. +// +// With a manifest declared, Tauri checks every app command against the ACL, +// from local origins too: a command missing here is refused at runtime. +// build.rs checks this list against the `generate_handler!` block +// ([`manifest_drift`]) and fails the build when they differ; a test runs the +// same check. +// +// No `//!` docs here: build.rs pulls this file in with `include!`. + +use std::collections::BTreeSet; + +/// Every command registered in `lib.rs`'s `tauri::generate_handler!`. +pub const APP_COMMANDS: &[&str] = &[ + "auth_sign_in", + "auth_sign_out", + "auth_userinfo", + "auth_get_access_token", + "auth_get_state", + "config_get", + "config_set", + "telemetry_get_config", + "telemetry_set_posthog_enabled", + "telemetry_set_cloud_enabled", + "shell_open_external", + "shell_show_item_in_folder", + "shell_open_path", + "detect_editors", + "open_in_editor", + "clipboard_write", + "browser_embed_create", + "browser_embed_navigate", + "browser_embed_set_bounds", + "browser_embed_set_select", + "browser_embed_nav", + "browser_embed_devtools", + "browser_embed_clear_data", + "browser_embed_close", + "window_start_dragging", + "window_minimize", + "window_maximize", + "window_close", + "window_set_size", + "window_set_taskbar_icon", + "fs_read_directory", + "fs_read_file", + "fs_get_extension", + "fs_get_project_root", + "fs_scaffold_plugin", + "dialog_open_folder", + "dialog_open_file", + "git_get_context", + "git_working_diff", + "git_has_gh_cli", + "git_has_git", + "git_list_branches", + "git_set_base_branch", + "git_checkout", + "git_commit", + "git_push", + "pty_spawn", + "pty_write", + "pty_resize", + "pty_kill", + "pty_buffer", + "git_ensure_repo", + "git_pull_latest", + "git_diff_summary", + "git_open_pr", + "git_create_pr", + "git_get_pr_status", + "git_list_prs", + "git_merge_pr", + "git_rerun_check_job", + "git_rerun_failed_checks", + "git_delete_remote_branch", + "git_pr_ready", + "git_sync_main", + "git_fetch_base", + "git_carve_next_round", + "git_preflight_check", + "shell_check_github_auth", + "gh_auth_login_launch", + "gh_auth_login_capture", + "gh_auth_login_cancel", + "shell_install_provider", + "shell_check_python_runtime", + "shell_install_ollama", + "git_watch_head", + "git_unwatch_head", + "github_get_link", + "github_begin_oauth", + "github_cancel_oauth", + "github_refresh_link", + "github_disconnect", + "github_open_installation", + "github_list_repos", + "github_list_installations", + "voice_list_devices", + "voice_start_recording", + "voice_stop_recording", + "voice_transcribe", + "voice_set_byok_key", + "voice_has_byok_key", + "voice_list_models", + "voice_download_model", + "voice_cancel_download", + "routers_list_routers", + "routers_connect", + "routers_disconnect", + "routers_set_active", + "routers_set_master_toggle", + "routers_test_router", + "routers_get_key_preview", + "providers_list_catalog", + "providers_set_key", + "providers_get_key_preview", + "providers_delete_key", + "providers_set_enabled", + "providers_set_default", + "providers_set_connected_bulk", + "providers_test_connection", + "providers_ollama_probe", + "providers_ollama_ps", + "providers_ollama_pull", + "providers_ollama_pull_cancel", + "providers_ollama_delete", + "providers_set_enabled_models", + "providers_set_ollama_base_url", + "providers_set_ollama_cloud_base_url", + "providers_set_cloudflare_account_id", + "providers_set_account_key", + "providers_get_account_key_preview", + "providers_delete_account_key", + "providers_open_account_login", + "agent_login_default", + "git_generate_commit_message", + "git_generate_pr_summary", + "git_review_diff", + "git_diagnose_failure", + "git_apply_recovery", + "git_apply_preflight_fix", + "git_diff_summary_simple", + "app_log", + "logs_export", + "logs_open_folder", + "feedback_send", +]; + +/// The commands `lib_rs`, the text of `lib.rs`, registers in its one +/// `generate_handler!` block, by name (the last segment of each path), in +/// order. An error says what it couldn't read. +pub fn registered_commands(lib_rs: &str) -> Result, String> { + const OPEN: &str = "generate_handler!["; + let mut blocks = lib_rs.match_indices(OPEN); + let (Some((at, _)), None) = (blocks.next(), blocks.next()) else { + return Err( + "lib.rs must register its commands in exactly one generate_handler! block".into(), + ); + }; + let start = at + OPEN.len(); + let len = lib_rs[start..] + .find(']') + .ok_or("the generate_handler! block in lib.rs never closes")?; + lib_rs[start..start + len] + .lines() + .map(|line| line.find("//").map_or(line, |comment| &line[..comment])) + .flat_map(|line| line.split(',')) + .map(str::trim) + .filter(|path| !path.is_empty()) + .map(|path| { + if path + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':') + { + Ok(path.rsplit("::").next().unwrap_or(path)) + } else { + Err(format!("not a command path in generate_handler!: {path}")) + } + }) + .collect() +} + +/// How `registered` (from [`registered_commands`]) and [`APP_COMMANDS`] +/// differ, as a message that says what to fix; `None` when they list the same +/// commands, each once. +pub fn manifest_drift(registered: &[&str]) -> Option { + let registered_set: BTreeSet<&str> = registered.iter().copied().collect(); + let listed: BTreeSet<&str> = APP_COMMANDS.iter().copied().collect(); + let mut problems = Vec::new(); + if registered_set.len() != registered.len() { + problems.push("lib.rs registers a command twice".to_string()); + } + if listed.len() != APP_COMMANDS.len() { + problems.push("APP_COMMANDS lists a command twice".to_string()); + } + let unlisted: Vec<_> = registered_set.difference(&listed).collect(); + if !unlisted.is_empty() { + problems.push(format!( + "registered in lib.rs but missing from APP_COMMANDS, so refused at runtime: {unlisted:?}" + )); + } + let unregistered: Vec<_> = listed.difference(®istered_set).collect(); + if !unregistered.is_empty() { + problems.push(format!( + "in APP_COMMANDS but not registered in lib.rs: {unregistered:?}" + )); + } + (!problems.is_empty()).then(|| { + format!( + "src/app_commands.rs must list exactly the commands lib.rs registers in \ + generate_handler!. Add a new command to APP_COMMANDS and its allow- \ + to permissions/app-commands.toml.\n{}", + problems.join("\n") + ) + }) +} + +#[cfg(test)] +mod tests { + use super::{manifest_drift, registered_commands, APP_COMMANDS}; + + #[test] + fn the_app_manifest_lists_every_registered_command() { + // build.rs runs the same check and fails the build on a mismatch. + let registered = registered_commands(include_str!("lib.rs")).unwrap(); + assert!(registered.contains(&"auth_sign_in"), "{registered:?}"); + if let Some(drift) = manifest_drift(®istered) { + panic!("{drift}"); + } + } + + #[test] + fn a_drift_says_which_commands_to_fix() { + let mut registered: Vec<&str> = APP_COMMANDS + .iter() + .copied() + .filter(|command| *command != "config_get") + .collect(); + registered.push("a_new_command"); + let drift = manifest_drift(®istered).expect("the lists differ"); + assert!( + drift.contains(r#"so refused at runtime: ["a_new_command"]"#), + "{drift}" + ); + assert!( + drift.contains(r#"not registered in lib.rs: ["config_get"]"#), + "{drift}" + ); + registered.push("a_new_command"); + let twice = manifest_drift(®istered).expect("a command twice"); + assert!( + twice.contains("lib.rs registers a command twice"), + "{twice}" + ); + assert_eq!(manifest_drift(APP_COMMANDS), None); + } + + #[test] + fn the_generate_handler_block_is_read_by_command_name() { + let lib_rs = "builder\n .invoke_handler(tauri::generate_handler![\n \ + shell::ipc::config_get, // a comment\n app_log,\n ])\n"; + assert_eq!( + registered_commands(lib_rs), + Ok(vec!["config_get", "app_log"]) + ); + // Anything it can't read is an error, not a silently shorter list. + assert!(registered_commands("no handler block").is_err()); + assert!(registered_commands("generate_handler![a] generate_handler![b]").is_err()); + assert!(registered_commands("generate_handler![#[cfg(unix)] a]").is_err()); + assert!(registered_commands("generate_handler![a").is_err()); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1f8e48d..afea434 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -4,8 +4,12 @@ mod shell; +// The app's commands, by name: its ACL manifest. build.rs compiles this file +// in for tauri-build; the crate itself only needs it for tests. +#[cfg(test)] +mod app_commands; + use std::net::SocketAddr; -use std::path::PathBuf; use tauri::webview::WebviewWindowBuilder; #[cfg(target_os = "macos")] @@ -17,46 +21,16 @@ use tauri::{Manager, WebviewUrl}; /// Boot shim reconstructing `window.electronAPI` / `window.fleetify`. const PRELOAD: &str = include_str!("preload.js"); -/// URL the main webview is pointed at. Debug builds load the Vite dev -/// server (`VITE_PORT`, default 3000); release builds load the -/// embedded backend serving the bundled dist (`FLEETIFY_BACKEND_PORT`, -/// default 8765). Honouring the env vars is what lets the -/// `dev:tauri:wt` script (and the parallel-worktree workflow it -/// enables) run two app instances on different ports side-by-side. -fn webview_url() -> String { - if cfg!(debug_assertions) { - let port = std::env::var("VITE_PORT").unwrap_or_else(|_| "3000".into()); - format!("http://localhost:{port}") - } else { - let port = std::env::var("FLEETIFY_BACKEND_PORT").unwrap_or_else(|_| "8765".into()); - format!("http://127.0.0.1:{port}") - } -} - -/// Parse `FLEETIFY_BACKEND_PORT` with a hard-coded 8765 fallback. The -/// embedded backend binds this port; the webview URL in release mode -/// (and the Vite dev proxy in debug mode) target the same port. -fn backend_port() -> u16 { - match std::env::var("FLEETIFY_BACKEND_PORT") { +/// Parse `VITE_PORT` with a 3000 fallback, as `vite.config.ts` does. Debug +/// builds load the app from the Vite dev server on this port (see +/// `shell::startup_window::app_origin`). +fn vite_port() -> u16 { + match std::env::var("VITE_PORT") { Ok(s) => s.parse().unwrap_or_else(|_| { - // Surface the misconfiguration instead of silently binding 8765 — - // a typo'd port otherwise looks like "the backend won't connect". - tracing::warn!(value = %s, "FLEETIFY_BACKEND_PORT is not a valid port; falling back to 8765"); - 8765 + tracing::warn!(value = %s, "VITE_PORT is not a valid port; falling back to 3000"); + 3000 }), - Err(_) => 8765, - } -} - -fn static_dir() -> Option { - if cfg!(debug_assertions) { - None - } else { - let beside_exe = std::env::current_exe() - .ok() - .and_then(|p| p.parent().map(|d| d.join("dist"))) - .filter(|p| p.exists()); - Some(beside_exe.unwrap_or_else(|| PathBuf::from("dist"))) + Err(_) => 3000, } } @@ -129,8 +103,10 @@ pub fn run() { shell::ipc::config_set, shell::ipc::telemetry_get_config, shell::ipc::telemetry_set_posthog_enabled, + shell::ipc::telemetry_set_cloud_enabled, shell::ipc::shell_open_external, shell::ipc::shell_show_item_in_folder, + shell::ipc::shell_open_path, shell::ipc::detect_editors, shell::ipc::open_in_editor, shell::ipc::clipboard_write, @@ -258,6 +234,12 @@ pub fn run() { .manage(shell::voice::DownloadCancelState(std::sync::Arc::new( std::sync::atomic::AtomicBool::new(false), ))) + // The page the main window starts on, until the app answers (see + // shell::startup_window). + .register_uri_scheme_protocol( + shell::startup_window::PLACEHOLDER_SCHEME, + |ctx, _request| shell::startup_window::placeholder_response(ctx.webview_label()), + ) .setup(|app| { // X errors are FATAL in GDK by default: one async BadWindow (e.g. // a GDK XTranslateCoordinates racing a webview teardown, or the @@ -299,6 +281,19 @@ pub fn run() { // Auth module emits `fleet:auth-event` via this handle. shell::auth::set_app_handle(app.handle().clone()); + // Decide Fleetify cloud sync for this launch before anything + // else reads or writes fleet.config.json: ahead of the key + // migration below, and of the renderer (no command runs until + // setup returns). A file that is there but can't be read or + // parsed keeps sync off and gets an explicit opt-out saved, so + // no later save can drop the user's earlier choice. The early + // open and the final restore below both follow this decision. + let cloud_open_at_launch = app + .path() + .app_data_dir() + .map(|dir| shell::config::startup_cloud_decision(&dir)) + .unwrap_or(false); + // One-shot lift of any plaintext `cfg.apiKeys` entries into // the OS keychain. Idempotent — empty / already-migrated // configs are a no-op. Runs on the async runtime so a slow @@ -309,20 +304,87 @@ pub fn run() { shell::migration::migrate_api_keys_to_keychain(&app_for_migration).await; }); + // The ports, parsed once: the main window loads the app from + // one of them (shell::startup_window::app_origin), and the + // embedded backend binds `backend` below. FLEETIFY_BACKEND_PORT + // is read here only; everything else gets that port from + // shell::backend_ready. + let release = !cfg!(debug_assertions); + let backend = shell::backend_ready::port_from_env( + std::env::var("FLEETIFY_BACKEND_PORT").ok().as_deref(), + ); + let vite = vite_port(); + + // The backend's start: the main window loads the app only after + // its bind and says so when it can't start (see + // shell::startup_window::load_app_when_ready), and the shell + // sends it keys or the internal secret only once it is bound + // (shell::backend_ready::bound_port). + let (backend_start_tx, backend_start_rx) = + tokio::sync::watch::channel(shell::backend_ready::BackendStart::Pending); + shell::backend_ready::track(backend, backend_start_rx.clone()); + + // IPC from the app's origin. capabilities/default.json covers + // only local origins (devUrl in dev mode). The origin the window + // loads the app from gets the same permissions here, for that + // origin alone and the main webview: always in release (the + // embedded backend on http://127.0.0.1:), and in debug only + // when Vite isn't the local devUrl. No other remote origin can + // call anything. Added before the window is built. A release + // build has no other grant, so a failed one stops the start: the + // backend task below reports it instead of starting the backend, + // and the window shows the error dialog, then the app quits. + let local_app_url = + shell::startup_window::local_app_url(app.config(), tauri::is_dev()); + let grant = match shell::startup_window::runtime_remote_origin( + release, + backend, + vite, + local_app_url.as_ref(), + ) { + Some(origin) => { + let grant = shell::startup_window::grant_app_origin(app, &origin); + match &grant { + Ok(()) => tracing::info!(%origin, "IPC allowed from the app origin"), + Err(e) => tracing::error!( + %origin, + "allowing IPC from the app origin failed, so the app can't call its own commands: {e}" + ), + } + grant + } + None => Ok(()), + }; + // No splash — by explicit user preference. The main - // window is built `.visible(false)` and stays hidden until - // both the embedded backend AND the webview's target URL - // (Vite in debug, the backend in release) are reachable. - // Direct WebviewWindow handle clone (no get_webview_window - // lookup) avoids the AppHandle race the earlier version - // hit on Windows. Trade-off: from t=0 to URL-ready (~3-7s - // depending on Vite cold-start) the user sees nothing on - // screen. That's the price of "no visible loading state". + // window is built `.visible(false)` on a local placeholder + // page and stays hidden until the app's URL (Vite in debug, + // the embedded backend in release) answers and the app page + // has loaded in it. It never loads that URL before then: the + // engine doesn't retry a first navigation that failed, so a + // slow backend bind used to leave its error page on screen. + // A start slower than 15s shows the window with the + // placeholder ("Starting Fleetify…") until the app loads. + // See shell::startup_window. Direct WebviewWindow handle + // clone (no get_webview_window lookup) avoids the AppHandle + // race the earlier version hit on Windows. + let app_url: tauri::Url = shell::startup_window::app_origin(release, backend, vite) + .parse() + .expect("valid webview url"); + let app_page_loaded = std::sync::Arc::new(tokio::sync::Notify::new()); let builder = WebviewWindowBuilder::new( app, - "main", - WebviewUrl::External(webview_url().parse().expect("valid webview url")), + shell::startup_window::MAIN_WINDOW, + WebviewUrl::CustomProtocol( + shell::startup_window::PLACEHOLDER_URL + .parse() + .expect("valid placeholder url"), + ), ) + .on_page_load(shell::startup_window::signal_app_page_loaded( + app_url.clone(), + app_page_loaded.clone(), + )) .title("Fleetify") // Cold-start at the ONBOARDING size (760×740) rather than // the MAIN size (1500×960). Reveal-when-ready paints the @@ -387,10 +449,41 @@ pub fn run() { // Weave, LiteLLM) already registered when the user had them // connected. Fresh installs hand over an empty setup and // the backend boots with builtin + DirectGateway only. - let addr: SocketAddr = format!("127.0.0.1:{}", backend_port()).parse().unwrap(); - let sd = static_dir(); + let addr: SocketAddr = format!("127.0.0.1:{backend}").parse().unwrap(); + // The UI files it serves: in release, `dist` in the install's + // resource folder and nowhere else (shell::ui_files); in debug + // none, as Vite serves the UI. With no UI files to serve, the + // backend never starts: its task reports that as a failed + // start, so the window shows the error dialog and the app quits + // (shell::startup_window). + let ui_files = + shell::ui_files::served_ui_dir(release, || app.path().resource_dir()); let app_data_dir = app.path().app_data_dir().ok(); tauri::async_runtime::spawn(async move { + if let Err(error) = grant { + tracing::error!( + "the interface has no permissions, so the backend won't start: {error}" + ); + let _ = backend_start_tx.send(shell::backend_ready::BackendStart::Failed( + shell::backend_ready::StartFailure::Permissions(error), + )); + return; + } + let sd = match ui_files { + Ok(sd) => sd, + Err(missing) => { + tracing::error!( + "the UI files are missing, so the backend won't start: {missing}" + ); + let _ = backend_start_tx.send(shell::backend_ready::BackendStart::Failed( + shell::backend_ready::StartFailure::UiFilesMissing(missing), + )); + return; + } + }; + if let Some(dir) = &sd { + tracing::info!("serving the UI files from {}", dir.display()); + } let routing_setup = match app_data_dir { Some(dir) => { let uid = shell::auth::get_user_id().await; @@ -414,9 +507,13 @@ pub fn run() { backend_bind_ms = boot_start.elapsed().as_millis() as u64, "embedded backend up on {addr}" ); + let _ = backend_start_tx.send(shell::backend_ready::BackendStart::Bound); } Err(e) => { - tracing::error!("backend failed to start: {e}"); + tracing::error!("backend failed to start: {e:#}"); + let _ = backend_start_tx.send(shell::backend_ready::BackendStart::Failed( + shell::backend_ready::StartFailure::Backend(format!("{e:#}")), + )); } } }); @@ -442,41 +539,80 @@ pub fn run() { // the keychain and prime HttpHealthCache so the first chat // turn doesn't hit "No API key" and Settings → Models // opens with final pills instead of the "Testing…" flash. - // Waits for the embedded backend to bind before hitting it - // (200ms × 20 = 4s upper bound covers a cold Rust startup). + // Runs only once the embedded backend has reported its bind + // and answers its health route; otherwise it is skipped. let handle = app.handle().clone(); + let warm_up_start = backend_start_rx.clone(); tauri::async_runtime::spawn(async move { - // Wait for the embedded backend to bind its port before - // we try to reach it. 200ms × 20 = 4s upper bound covers - // a cold Rust startup on a slow disk. - let port = std::env::var("FLEETIFY_BACKEND_PORT").unwrap_or_else(|_| "8765".into()); - let health_url = format!("http://127.0.0.1:{port}/health"); - for _ in 0..20 { - if let Ok(r) = reqwest::get(&health_url).await { - if r.status().is_success() { - break; - } - } - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - } - crate::shell::providers_setup::warm_providers_at_boot(&handle).await; - // Hydrate the backend clone service with the linked GitHub - // token so private-repo clones authenticate from the first try. - crate::shell::github_link::push_clone_token().await; - - // Restore the persisted PostHog opt-in. The backend's - // posthog::init already ran inside serve(), so the - // outbox + worker are wired; we just need to flip the - // runtime gate to match what the user previously - // consented to. Fresh installs land on default-off - // because telemetry_from returns Default on missing. + // Both telemetry gates start closed in the backend. Open the + // ones that are on right away rather than after the warm-up + // below: `telemetry_get_config` reports the live gates, and + // the renderer reads it as soon as it loads (it decides then + // whether to start posthog-js). It also keeps the backend's + // first heartbeat and early session events. The PostHog gate + // is only a flag, so it can open before serve() has set up + // the PostHog sink. The cloud gate follows the launch + // decision made at the top of setup; closing it waits for + // the restore at the end of this task. Rows older builds + // queued depend on neither: the outbox drops them itself + // when it opens, before anything can read them. if let Ok(dir) = handle.path().app_data_dir() { let cfg = crate::shell::config::load_config_from(&dir); - let telem = crate::shell::config::telemetry_from(&cfg); - if telem.posthog_enabled { + if crate::shell::config::telemetry_from(&cfg).posthog_enabled { fleetify_backend::services::telemetry::posthog::set_enabled(true); } } + if cloud_open_at_launch { + fleetify_backend::services::telemetry::set_cloud_enabled(true).await; + } + + // The warm-up sends provider keys and the internal secret, so + // it talks only to the app's own backend: it waits for the + // bind, then for the health route (200ms × 20 = 4s covers a + // cold Rust startup on a slow disk). A backend that fails, + // never reports, or doesn't answer gets nothing: before the + // bind, whatever answers on the port is something else. The + // next reload trigger (a Settings change) sends the keys. + if crate::shell::backend_ready::wait_until_bound(warm_up_start).await { + let ready = crate::shell::backend_ready::wait_for_backend( + &crate::shell::backend_ready::health_url(&backend.to_string()), + 20, + std::time::Duration::from_millis(200), + ) + .await; + if ready { + crate::shell::providers_setup::warm_providers_at_boot(&handle).await; + // Hydrate the backend clone service with the linked + // GitHub token so private-repo clones authenticate + // from the first try. + crate::shell::github_link::push_clone_token().await; + } else { + tracing::warn!( + "backend health check timed out; skipping the provider warm-up" + ); + } + } else { + tracing::warn!("the embedded backend didn't start; skipping the provider warm-up"); + } + + // Finish the Fleetify cloud sync restore: close the gate if + // the launch decision kept sync off, or if the saved choice + // is off now (a file that can't be read or parsed counts as + // off). Closing also purges what is still queued, if the + // backend has opened its outbox by now. Nothing orders this + // after that, so rows older builds queued are dropped by the + // outbox itself. It never opens the gate, and it does + // nothing if Settings changed it since launch: reapplying + // the saved choice here would undo a switch whose save + // failed. (The PostHog gate was restored at the top of this + // task, for the same reason.) + let saved_on = cloud_open_at_launch + && handle + .path() + .app_data_dir() + .map(|dir| crate::shell::config::saved_cloud_choice(&dir)) + .unwrap_or(false); + crate::shell::ipc::finish_cloud_sync_restore(saved_on).await; }); // Prime the integrations cache in parallel — only needs the @@ -488,39 +624,23 @@ pub fn run() { crate::shell::integrations_cache::prime_gh_cli().await; }); - // Reveal-when-ready: poll the webview URL until it - // answers HTTP, then show + focus. Any non-connection- - // error response counts as "up" (even 404 → renderer can - // surface the failure). 15s wall-clock cap so a stuck - // dev server doesn't leave the user with a permanently - // invisible app. 120ms grace before show() lets the - // first React frame paint so we don't flash white. - let webview_url_owned: String = webview_url(); - let main_for_reveal = main_window.clone(); - tauri::async_runtime::spawn(async move { - let client = reqwest::Client::builder() - .timeout(std::time::Duration::from_millis(500)) - .build() - .expect("reqwest client"); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15); - while std::time::Instant::now() < deadline { - if client.get(&webview_url_owned).send().await.is_ok() { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(150)).await; - } - tokio::time::sleep(std::time::Duration::from_millis(120)).await; - if let Err(e) = main_for_reveal.show() { - tracing::warn!("show main window failed: {e}"); - } else { - tracing::info!( - target: "fleetify::startup", - cold_start_ms = boot_start.elapsed().as_millis() as u64, - "main window revealed" - ); - } - let _ = main_for_reveal.set_focus(); - }); + // Reveal-when-ready: once the backend reports its bind, poll the + // webview URL until it answers HTTP (any response counts, even a + // 404 the renderer can surface), then load the app in the window + // and show + focus it once the app page has loaded, so it + // doesn't flash white. Past 15s the window shows the placeholder + // and the wait goes on with no cap. A backend that can't start, + // has no UI files to serve, or wasn't started because the + // interface got no permissions, ends it: an error dialog, then + // the app quits. + tauri::async_runtime::spawn(shell::startup_window::load_app_when_ready( + main_window, + app_url, + app_page_loaded, + backend_start_rx, + backend, + boot_start, + )); // Loopback bearer bridge :8770 (telemetry token source / parity). // FLEETIFY_NOAUTH=1 has no consumer to feed and no token to @@ -533,6 +653,7 @@ pub fn run() { // Telemetry WS client → fleetify.dev. Bearer pulled from // shell::auth.get_access_token() lazily per attempt so a // mid-flow refresh is picked up at the next reconnect. + // Idles (no bearer, no socket) while cloud sync is off. tauri::async_runtime::spawn(async { let source: fleetify_backend::services::telemetry::BearerSource = std::sync::Arc::new(|| { diff --git a/src-tauri/src/preload.js b/src-tauri/src/preload.js index 4c3607a..924472c 100644 --- a/src-tauri/src/preload.js +++ b/src-tauri/src/preload.js @@ -83,8 +83,14 @@ document.addEventListener("mousedown", function (e) { telemetrySetPosthogEnabled: function (enabled) { return invoke("telemetry_set_posthog_enabled", { enabled: !!enabled }); }, + telemetrySetCloudEnabled: function (enabled) { + return invoke("telemetry_set_cloud_enabled", { enabled: !!enabled }); + }, openExternal: function (url) { return invoke("shell_open_external", { url: String(url || "") }); }, showItemInFolder: function (p) { return invoke("shell_show_item_in_folder", { path: String(p || "") }); }, + // A local folder or document file (never a link): shell_open_path + // opens only those, as ShellExecute on Windows runs anything else. + openPath: function (p) { return invoke("shell_open_path", { path: String(p || "") }); }, writeText: function (t) { return invoke("clipboard_write", { text: String(t || "") }); }, minimizeWindow: function () { return invoke("window_minimize"); }, maximizeWindow: function () { return invoke("window_maximize"); }, diff --git a/src-tauri/src/shell/ai_git.rs b/src-tauri/src/shell/ai_git.rs index 0c151c5..ed42ac6 100644 --- a/src-tauri/src/shell/ai_git.rs +++ b/src-tauri/src/shell/ai_git.rs @@ -14,6 +14,7 @@ use std::path::{Path, PathBuf}; use std::time::Duration; +use fleetify_core::text::{prefix_within_bytes, truncate_chars}; use serde_json::{json, Value}; use crate::shell::git; @@ -165,6 +166,18 @@ async fn git_out(folder: &Path, args: &[&str], timeout: Duration) -> (bool, Stri (rc == 0, out) } +/// Cut a diff to at most `max_bytes` for a prompt, marking the cut. The cut +/// backs off to a character boundary: diffs carry whatever the user's files +/// contain, and slicing inside a character panics. +fn cap_diff(diff: String, max_bytes: usize) -> String { + let head = prefix_within_bytes(&diff, max_bytes); + if head.len() == diff.len() { + diff + } else { + format!("{head}\n…[truncated]") + } +} + // ── generateCommitMessage ─────────────────────────────────────── pub async fn generate_commit_message( folder: String, @@ -217,10 +230,8 @@ pub async fn generate_commit_message( Duration::from_secs(8), ) .await; - let truncated = if df_ok && df_out.len() > 30_000 { - format!("{}\n…[truncated]", &df_out[..30_000]) - } else if df_ok { - df_out + let truncated = if df_ok { + cap_diff(df_out, 30_000) } else { String::new() }; @@ -240,7 +251,18 @@ pub async fn generate_commit_message( if !ok { return json!({ "ok": false, "error": err }); } - // First non-empty trimmed line, strip wrapping quotes, truncate to 72. + let message = clean_commit_message(&out); + if message.is_empty() { + return json!({ "ok": false, "error": format!("{cli} returned an empty message") }); + } + json!({ "ok": true, "message": message }) +} + +/// Turn the CLI's raw output into a commit subject: the first non-empty +/// trimmed line, wrapping quotes stripped, at most 72 characters. The limit +/// counts characters, not bytes, and never splits one: the subject is often +/// Turkish. +fn clean_commit_message(out: &str) -> String { let mut message: String = out .split('\n') .map(|s| s.trim().to_string()) @@ -252,13 +274,8 @@ pub async fn generate_commit_message( while message.ends_with('"') || message.ends_with('\'') || message.ends_with('`') { message.pop(); } - if message.len() > 72 { - message.truncate(72); - } - if message.is_empty() { - return json!({ "ok": false, "error": format!("{cli} returned an empty message") }); - } - json!({ "ok": true, "message": message }) + truncate_chars(&mut message, 72); + message } // ── generatePRSummary ─────────────────────────────────────────── @@ -376,11 +393,7 @@ pub async fn generate_pr_summary( diff, uncommitted, } = ctx; - let truncated = if diff.len() > 60_000 { - format!("{}\n…[truncated]", &diff[..60_000]) - } else { - diff - }; + let truncated = cap_diff(diff, 60_000); let prompt = format!( "You are drafting a GitHub pull request. Read the diff below and emit STRICT JSON with two keys:\n\ @@ -471,16 +484,8 @@ pub async fn review_diff( let committed = if cd_ok { cd_out } else { String::new() }; let working = if wd_ok { wd_out } else { String::new() }; - let trunc_committed = if committed.len() > 50_000 { - format!("{}\n…[truncated]", &committed[..50_000]) - } else { - committed.clone() - }; - let trunc_working = if working.len() > 20_000 { - format!("{}\n…[truncated]", &working[..20_000]) - } else { - working.clone() - }; + let trunc_committed = cap_diff(committed, 50_000); + let trunc_working = cap_diff(working, 20_000); if trunc_committed.is_empty() && trunc_working.is_empty() { return json!({ "ok": false, "error": format!("No diff to review against {base}.") }); @@ -857,6 +862,49 @@ mod tests { assert!(!ctx.log.trim().is_empty(), "commit log should be populated"); } + /// Regression: Fleetify is Türkiye-first, so AI-written subjects are often + /// Turkish. Cutting at byte 72 landed inside a two-byte letter and + /// panicked, crashing "generate commit message" and "Create PR". + #[test] + fn commit_message_keeps_72_characters_of_a_turkish_subject() { + let subject = + "fix(git): uzun Türkçe commit başlığı kısaltılırken uygulama çökmesin güvenle kes"; + assert_eq!(subject.chars().count(), 80); + assert!( + !subject.is_char_boundary(72), + "fixture must put byte 72 inside a letter" + ); + + let message = clean_commit_message(&format!("\n `{subject}` \nbody text\n")); + + assert_eq!(message.chars().count(), 72); + assert_eq!( + message, + "fix(git): uzun Türkçe commit başlığı kısaltılırken uygulama çökmesin güv" + ); + } + + /// Diffs carry whatever the user's files contain, Turkish comments + /// included, so the prompt budget must not cut through a letter either. + #[test] + fn diff_cap_never_splits_a_turkish_letter() { + let diff = "+// çğış\n".repeat(3000); // 13 bytes a line, 39 000 in all + assert!( + !diff.is_char_boundary(30_000), + "fixture must put byte 30 000 inside a letter" + ); + + let capped = cap_diff(diff.clone(), 30_000); + + let head = capped + .strip_suffix("\n…[truncated]") + .expect("cut is marked"); + // Backs off one byte, to the start of the ı that byte 30 000 is in. + assert_eq!(head.len(), 29_999); + assert!(diff.starts_with(head)); + assert_eq!(cap_diff("+kısa\n".to_string(), 30_000), "+kısa\n"); + } + #[test] fn cli_for_picks_per_tool() { assert_eq!(cli_for(Some("claude-code")).0, "claude"); diff --git a/src-tauri/src/shell/auth.rs b/src-tauri/src/shell/auth.rs index 164074c..8c1096f 100644 --- a/src-tauri/src/shell/auth.rs +++ b/src-tauri/src/shell/auth.rs @@ -61,12 +61,10 @@ fn noauth_tokens() -> Tokens { scope: DEFAULT_SCOPES.into(), } } +/// Identity-provider origin; production in release builds. Shared with the +/// embedded backend's token validation via `fleetify_core::endpoints`. pub fn issuer() -> String { - if is_prod() { - "https://fleetify.dev".into() - } else { - env_or("FLEETIFY_ISSUER", "http://localhost:3001") - } + fleetify_core::endpoints::issuer_origin() } pub fn auth_base() -> String { format!("{}/api/auth", issuer()) @@ -78,12 +76,10 @@ fn dashboard_url() -> String { env_or("FLEETIFY_DASHBOARD_URL", "http://localhost:5174") } } +/// RFC 8707 resource indicator: the audience the embedded backend expects +/// (`fleetify_core::endpoints`); production in release builds. fn resource() -> String { - if is_prod() { - "https://fleetify.dev/api".into() - } else { - env_or("FLEETIFY_RESOURCE", "http://127.0.0.1:8765") - } + fleetify_core::endpoints::api_resource() } #[derive(Clone, Serialize)] @@ -163,9 +159,25 @@ fn keyring_entry() -> keyring::Result { fn keyring_get() -> Option { keyring_entry().ok().and_then(|e| e.get_password().ok()) } -fn keyring_set(v: &str) { - if let Ok(e) = keyring_entry() { - let _ = e.set_password(v); +fn keyring_set(v: &str) -> keyring::Result<()> { + keyring_entry()?.set_password(v) +} + +/// Auth event for a refresh token that could not be saved; the renderer +/// shows a warning banner on it. +fn keychain_failure_event() -> serde_json::Value { + serde_json::json!({"kind": "keychain-unavailable"}) +} + +/// Saves the refresh token so the next launch starts signed in. When the +/// keychain refuses it (Linux without an unlocked Secret Service, a +/// dismissed unlock prompt), sign-in still succeeds for this session (the +/// access token is cached in-process), but the next launch would silently +/// start signed out: log it and tell the renderer. +fn save_refresh_token(token: &str) { + if let Err(e) = keyring_set(token) { + tracing::warn!(error = %e, "could not save the refresh token to the system keychain"); + emit_event(keychain_failure_event()); } } fn keyring_del() { @@ -303,26 +315,45 @@ fn capture_code() -> Result { }) } -pub async fn sign_in() -> Result { - if is_no_auth() { - return Ok(noauth_tokens()); - } - let (verifier, challenge) = new_pkce(); - let cb = capture_code()?; - - let mut u = url::Url::parse(&format!("{}/oauth2/authorize", auth_base())) +/// The identity provider's authorize page that sign-in opens in the +/// browser: `base` is [`auth_base`], with the PKCE `challenge`, the loopback +/// `redirect_uri` and `state` from [`capture_code`], and the API `resource`. +fn authorize_url( + base: &str, + redirect_uri: &str, + state: &str, + challenge: &str, + resource: &str, +) -> Result { + let mut u = url::Url::parse(&format!("{base}/oauth2/authorize")) .map_err(|e| AuthError::new(e.to_string(), "auth"))?; u.query_pairs_mut() .append_pair("client_id", CLIENT_ID) - .append_pair("redirect_uri", &cb.redirect_uri) + .append_pair("redirect_uri", redirect_uri) .append_pair("response_type", "code") .append_pair("scope", DEFAULT_SCOPES) - .append_pair("state", &cb.state) - .append_pair("code_challenge", &challenge) + .append_pair("state", state) + .append_pair("code_challenge", challenge) .append_pair("code_challenge_method", "S256") - .append_pair("resource", &resource()); + .append_pair("resource", resource); + Ok(u) +} - open::that(u.as_str()) +pub async fn sign_in() -> Result { + if is_no_auth() { + return Ok(noauth_tokens()); + } + let (verifier, challenge) = new_pkce(); + let cb = capture_code()?; + + let u = authorize_url( + &auth_base(), + &cb.redirect_uri, + &cb.state, + &challenge, + &resource(), + )?; + fleetify_backend::open_external::open_url(u.as_str()) .map_err(|e| AuthError::new(format!("browser-failed: {e}"), "browser"))?; let rx = cb.rx; @@ -348,7 +379,7 @@ pub async fn sign_in() -> Result { .map_err(|e| AuthError::new(e.to_string(), "auth"))?; let tokens = decode_token_response(r).await?; *cached().lock().unwrap() = Some(tokens.clone()); - keyring_set(&tokens.refresh_token); + save_refresh_token(&tokens.refresh_token); Ok(tokens) } @@ -394,7 +425,7 @@ pub async fn refresh_if_needed(force: bool) -> Result { .map_err(|e| AuthError::new(e.to_string(), "auth"))?; let tokens = decode_token_response(r).await?; *cached().lock().unwrap() = Some(tokens.clone()); - keyring_set(&tokens.refresh_token); + save_refresh_token(&tokens.refresh_token); emit_event(serde_json::json!({"kind":"refreshed","expiresAt":tokens.expires_at})); Ok(tokens) } @@ -516,3 +547,54 @@ pub async fn get_access_token(force: bool) -> Option { Err(_) => None, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_sign_in_page_is_a_link_the_opener_accepts() { + // Sign-in opens the authorize page through open_external, which + // refuses anything but a clean web link: it must not refuse this one. + let (_verifier, challenge) = new_pkce(); + for (base, resource) in [ + ("https://fleetify.dev/api/auth", "https://fleetify.dev/api"), + ("http://localhost:3001/api/auth", "http://127.0.0.1:8765"), + ] { + let url = authorize_url( + base, + "http://127.0.0.1:53682/callback", + "c3RhdGUtd2l0aC1zb21lLWJ5dGVz", + &challenge, + resource, + ) + .unwrap(); + let opened = fleetify_backend::open_external::validate_external_url(url.as_str()) + .unwrap_or_else(|e| panic!("{url}: {e}")); + assert_eq!(opened.as_str(), url.as_str()); + assert!(opened + .as_str() + .starts_with(&format!("{base}/oauth2/authorize?"))); + } + } + + /// Tokens the shell requests must pass the embedded backend's checks: + /// the backend expects `iss` = the shell's auth base and `aud` = the + /// `resource` the shell names. Both read the same environment here. + #[test] + fn shell_requests_tokens_the_embedded_backend_accepts() { + let backend = fleetify_backend::auth::AuthConfig::from_env(); + assert_eq!(auth_base(), backend.auth_base); + assert_eq!(resource(), backend.expected_audience); + } + + /// The renderer raises its keychain warning banner on exactly this + /// payload (`src/lib/auth-events.ts`). + #[test] + fn keychain_failure_event_is_the_payload_the_renderer_handles() { + assert_eq!( + keychain_failure_event(), + serde_json::json!({"kind": "keychain-unavailable"}) + ); + } +} diff --git a/src-tauri/src/shell/backend_ready.rs b/src-tauri/src/shell/backend_ready.rs new file mode 100644 index 0000000..504d2bb --- /dev/null +++ b/src-tauri/src/shell/backend_ready.rs @@ -0,0 +1,514 @@ +//! The embedded backend this process starts: its one parsed port, whether +//! it has bound (the only condition under which the shell sends it secrets), +//! and the wait for its health route before the boot warm-up talks to it. +//! +//! The health wait used to poll `/health`, which the backend never served, +//! so every launch sat out the whole timeout. It now polls the backend's own +//! health route, `fleetify_backend::HEALTH_PATH`, and counts the backend up +//! when that answers `{"status":"ok"}`. The warm-up no longer runs anyway +//! when it times out, nor before the backend has reported its bind. + +use std::sync::OnceLock; +use std::time::Duration; + +use tokio::sync::watch; + +use crate::shell::ui_files::UiDirError; + +/// How long one poll may take. The backend answers its health route at +/// once; this only bounds a port that accepts and never answers. +const POLL_TIMEOUT: Duration = Duration::from_millis(500); + +// ── The backend this process starts ── +// +// The shell sends the backend secrets: provider and router keys, and the +// internal secret on every internal call. They go only to the backend this +// process started, and only once it has reported its bind. Before that, or +// after a failed bind, whatever answers on the port is something else +// (AnkiConnect listens on 127.0.0.1:8765 by default), and the backend sets +// FLEETIFY_INTERNAL_SECRET before it binds, so that variable proves nothing. + +/// What the embedded backend's task has reported about its start. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BackendStart { + /// No report yet: `serve_with_routing_setup` is still running. + Pending, + /// It returned `Ok`: the backend listens on its port. + Bound, + /// It didn't start, and won't: see [`StartFailure`]. + Failed(StartFailure), +} + +/// Why the embedded backend didn't start. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StartFailure { + /// `serve_with_routing_setup` returned `Err` (the error and its causes), + /// or its task ended without a report. + Backend(String), + /// A release build found no UI files to serve, so the backend was never + /// started: it would have served a blank window (see `shell::ui_files`). + UiFilesMissing(UiDirError), + /// The window's app origin couldn't be granted its IPC permissions (the + /// error, or the panic's message), so the backend was never started: the + /// release UI could call none of the app's commands (see + /// `startup_window::grant_app_origin`). + Permissions(String), +} + +/// The embedded backend's port when `FLEETIFY_BACKEND_PORT` is unset or not +/// a port. +pub const DEFAULT_PORT: u16 = 8765; + +/// The port the embedded backend binds, from `FLEETIFY_BACKEND_PORT`'s +/// value: [`DEFAULT_PORT`] when it is unset or not a port. A typo'd port is +/// logged rather than ignored: it otherwise looks like "the backend won't +/// connect". lib.rs reads the variable once and passes it here; everything +/// else gets the port from [`bound_port`]. +pub fn port_from_env(value: Option<&str>) -> u16 { + match value { + None => DEFAULT_PORT, + Some(value) => value.parse().unwrap_or_else(|_| { + tracing::warn!( + value = %value, + "FLEETIFY_BACKEND_PORT is not a valid port; falling back to {DEFAULT_PORT}" + ); + DEFAULT_PORT + }), + } +} + +/// The backend's `port` once it has reported its bind; `None` before that or +/// after a failed start. Everything that sends provider keys or the internal +/// secret asks this first, so nothing goes to another program holding the +/// port. Those calls stay on loopback: `backend_url` is always `127.0.0.1`. +pub fn port_if_bound(start: &BackendStart, port: u16) -> Option { + (*start == BackendStart::Bound).then_some(port) +} + +/// The URL of `path` on the backend at `port`. +pub fn backend_url(port: u16, path: &str) -> String { + format!("http://127.0.0.1:{port}{path}") +} + +/// The backend this process starts: the port it binds, and its start +/// reports. +#[derive(Debug)] +pub struct TrackedBackend { + port: u16, + start: watch::Receiver, +} + +impl TrackedBackend { + /// Its port while it is bound (see [`port_if_bound`]). + pub fn bound_port(&self) -> Option { + port_if_bound(&self.start.borrow(), self.port) + } +} + +/// The backend this process starts. Set once, at setup. +static BACKEND: OnceLock = OnceLock::new(); + +/// Records the backend this process starts: the port it binds (from +/// [`port_from_env`]) and the receiver of its start reports. Called once, in +/// setup, before anything could send it a secret. +pub fn track(port: u16, start: watch::Receiver) { + let _ = BACKEND.set(TrackedBackend { port, start }); +} + +/// The port to send secrets to: the app's own backend's, once it has +/// reported its bind. `None` before that, after a failed start, or when no +/// backend is tracked. Every sender returns without sending on `None`. +pub fn bound_port() -> Option { + BACKEND.get().and_then(TrackedBackend::bound_port) +} + +/// Waits for the backend's start to be decided: true once it reports its +/// bind, false when it fails or its task ends without reporting (it +/// panicked). The boot warm-up runs only on true. +pub async fn wait_until_bound(mut start: watch::Receiver) -> bool { + loop { + match &*start.borrow_and_update() { + BackendStart::Bound => return true, + BackendStart::Failed(_) => return false, + BackendStart::Pending => {} + } + // Err only once the sender is gone with nothing new: no bind came. + if start.changed().await.is_err() { + return false; + } + } +} + +/// The backend's health URL on `port`. +pub fn health_url(port: &str) -> String { + format!("http://127.0.0.1:{port}{}", fleetify_backend::HEALTH_PATH) +} + +/// Polls `url` up to `attempts` times, `interval` apart, until the backend +/// answers. True once it did; false when the time ran out. Never through a +/// proxy (`fleetify_core::loopback`): one that isn't running would make the +/// backend look down. +pub async fn wait_for_backend(url: &str, attempts: u32, interval: Duration) -> bool { + let client = match fleetify_core::loopback::http_client_builder() + .timeout(POLL_TIMEOUT) + .build() + { + Ok(client) => client, + Err(e) => { + tracing::warn!("can't build the HTTP client that polls the backend: {e}"); + return false; + } + }; + for _ in 0..attempts { + if answers_ok(&client, url).await { + return true; + } + tokio::time::sleep(interval).await; + } + false +} + +/// True when `url` answers 2xx with the backend's `{"status":"ok"}`: a +/// 200 from something else on the port doesn't count. +async fn answers_ok(client: &reqwest::Client, url: &str) -> bool { + let Ok(response) = client.get(url).send().await else { + return false; + }; + if !response.status().is_success() { + return false; + } + response + .json::() + .await + .is_ok_and(|body| body["status"] == "ok") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// How a stub server answers each request. + #[derive(Clone, Copy)] + enum Stub { + /// As the backend does: `{"status":"ok",…}` on its health route, + /// 404 elsewhere. + Backend, + /// 200 with a web page on every path: something else on the port. + WebPage, + /// Accepts the connection and never answers. + Silent, + } + + /// A local HTTP server answering like `stub`. Returns its port and a + /// count of the requests it got. + async fn serve(stub: Stub) -> (u16, Arc) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&requests); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + let count = Arc::clone(&count); + tokio::spawn(async move { + let mut buf = vec![0u8; 4096]; + let n = socket.read(&mut buf).await.unwrap_or(0); + count.fetch_add(1, Ordering::SeqCst); + let request = String::from_utf8_lossy(&buf[..n]).into_owned(); + let path = request.split_whitespace().nth(1).unwrap_or("").to_string(); + let (status, body) = match stub { + Stub::Silent => { + tokio::time::sleep(Duration::from_secs(30)).await; + return; + } + Stub::Backend if path == "/healthz" => { + ("200 OK", r#"{"status":"ok","version":"0.1.0"}"#) + } + Stub::Backend => ("404 Not Found", ""), + Stub::WebPage => ("200 OK", "other"), + }; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + }); + } + }); + (port, requests) + } + + #[test] + fn polls_the_route_the_backend_serves() { + assert_eq!(health_url("8765"), "http://127.0.0.1:8765/healthz"); + assert!(health_url("8765").ends_with(fleetify_backend::HEALTH_PATH)); + } + + #[tokio::test] + async fn returns_as_soon_as_the_backend_answers() { + let (port, requests) = serve(Stub::Backend).await; + let started = std::time::Instant::now(); + let ready = wait_for_backend( + &health_url(&port.to_string()), + 5, + Duration::from_millis(200), + ) + .await; + assert!(ready, "the backend answered, so the wait must end ready"); + assert_eq!(requests.load(Ordering::SeqCst), 1, "one poll was enough"); + assert!( + started.elapsed() < Duration::from_millis(200), + "{:?}", + started.elapsed() + ); + } + + #[tokio::test] + async fn a_200_from_something_else_is_not_the_backend() { + let (port, requests) = serve(Stub::WebPage).await; + let ready = + wait_for_backend(&health_url(&port.to_string()), 3, Duration::from_millis(10)).await; + assert!(!ready); + assert_eq!(requests.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn gives_up_after_its_attempts_when_the_health_route_is_missing() { + // The old startup polled /health, which the backend never served: + // every launch waited out the whole timeout. Here the stub serves + // only /healthz and the wait asks a path it doesn't serve. + let (port, requests) = serve(Stub::Backend).await; + let ready = wait_for_backend( + &format!("http://127.0.0.1:{port}/health"), + 3, + Duration::from_millis(10), + ) + .await; + assert!(!ready); + assert_eq!(requests.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn a_backend_that_never_answers_is_given_up_on() { + let (port, _) = serve(Stub::Silent).await; + let url = health_url(&port.to_string()); + let wait = wait_for_backend(&url, 2, Duration::from_millis(10)); + let ready = tokio::time::timeout(Duration::from_secs(5), wait) + .await + .expect("each poll must time out on its own"); + assert!(!ready); + } + + // ── The backend this process starts ── + + fn tracked(port: u16, start: BackendStart) -> (watch::Sender, TrackedBackend) { + let (tx, rx) = watch::channel(start); + (tx, TrackedBackend { port, start: rx }) + } + + #[test] + fn secrets_go_only_to_a_backend_that_reported_its_bind() { + // Before the bind, or after a failed one, whatever answers on the + // port is something else (AnkiConnect listens on 127.0.0.1:8765). + assert_eq!(port_if_bound(&BackendStart::Pending, 8765), None); + let failed = BackendStart::Failed(StartFailure::Backend( + "Address already in use (os error 98)".into(), + )); + assert_eq!(port_if_bound(&failed, 8765), None); + assert_eq!(port_if_bound(&ui_files_missing(), 8765), None); + assert_eq!(port_if_bound(&BackendStart::Bound, 8765), Some(8765)); + } + + /// The report when a release build has no UI files: the backend is + /// never started. + fn ui_files_missing() -> BackendStart { + BackendStart::Failed(StartFailure::UiFilesMissing(UiDirError::NoIndexHtml( + "/usr/lib/Fleetify/dist".into(), + ))) + } + + #[test] + fn the_reloads_send_nothing_until_the_backend_reports_its_bind() { + // What every sender asks before it sends: pending, nothing is sent. + let (tx, backend) = tracked(8899, BackendStart::Pending); + assert_eq!(backend.bound_port(), None); + // Bound: the reload runs, to the backend's own port. + tx.send(BackendStart::Bound).unwrap(); + assert_eq!(backend.bound_port(), Some(8899)); + + let (tx, backend) = tracked(8899, BackendStart::Pending); + tx.send(BackendStart::Failed(StartFailure::Backend( + "database is locked".into(), + ))) + .unwrap(); + assert_eq!(backend.bound_port(), None, "failed: nothing is sent"); + drop(tx); + assert_eq!(backend.bound_port(), None); + } + + #[test] + fn nothing_is_sent_while_no_backend_is_tracked() { + // No test tracks a backend: setup does, once, in the app. + assert_eq!(bound_port(), None); + } + + #[tokio::test] + async fn the_warm_up_waits_for_the_bind() { + let (tx, rx) = watch::channel(BackendStart::Pending); + let wait = tokio::spawn(wait_until_bound(rx)); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!wait.is_finished(), "still pending: no warm-up yet"); + tx.send(BackendStart::Bound).unwrap(); + assert!(wait.await.unwrap(), "bound: the warm-up runs"); + } + + #[tokio::test] + async fn the_warm_up_is_skipped_when_the_backend_fails_to_start() { + let (tx, rx) = watch::channel(BackendStart::Pending); + let wait = tokio::spawn(wait_until_bound(rx)); + tx.send(BackendStart::Failed(StartFailure::Backend( + "Address already in use (os error 98)".into(), + ))) + .unwrap(); + assert!(!wait.await.unwrap()); + } + + #[tokio::test] + async fn the_warm_up_is_skipped_when_the_ui_files_are_missing() { + // The backend's task reports it and ends without starting it. + let (tx, rx) = watch::channel(BackendStart::Pending); + let wait = tokio::spawn(wait_until_bound(rx)); + tx.send(ui_files_missing()).unwrap(); + drop(tx); + assert!(!wait.await.unwrap()); + } + + #[tokio::test] + async fn the_warm_up_is_skipped_when_the_backend_never_reports() { + // Its task panicked: the sender went away with the start pending. + let (tx, rx) = watch::channel(BackendStart::Pending); + drop(tx); + let bound = tokio::time::timeout(Duration::from_secs(5), wait_until_bound(rx)) + .await + .expect("the wait ends once nothing can report any more"); + assert!(!bound); + } + + #[tokio::test] + async fn a_bind_reported_just_before_the_task_ended_still_counts() { + let (tx, rx) = watch::channel(BackendStart::Pending); + tx.send(BackendStart::Bound).unwrap(); + drop(tx); + assert!(wait_until_bound(rx).await); + } + + // ── One parsed port ── + + #[test] + fn the_port_comes_from_the_env_value_with_8765_as_the_fallback() { + assert_eq!(port_from_env(None), 8765); + assert_eq!(port_from_env(Some("8899")), 8899); + for invalid in ["", "not-a-port", "70000", "-1", " 8899"] { + assert_eq!(port_from_env(Some(invalid)), 8765, "{invalid:?}"); + } + } + + #[test] + fn an_invalid_port_sends_every_caller_to_the_port_the_backend_binds() { + // lib.rs binds port_from_env(FLEETIFY_BACKEND_PORT) and tracks that + // same port; every sender takes it from bound_port() and builds its + // URL with backend_url. + let (_tx, backend) = tracked(port_from_env(Some("not-a-port")), BackendStart::Bound); + let port = backend.bound_port().unwrap(); + assert_eq!(port, 8765); + for path in [ + "/api/internal/providers/reload", + "/api/internal/accounts/http", + "/api/internal/providers/warm-health", + "/api/internal/routing/reload", + ] { + assert_eq!( + backend_url(port, path), + format!("http://127.0.0.1:8765{path}") + ); + } + } + + #[test] + fn only_lib_rs_reads_the_backend_port_from_the_environment() { + // Built at run time so this test's own source doesn't match. + let read = format!("env::var(\"{}\")", "FLEETIFY_BACKEND_PORT"); + for (file, source) in [ + ( + "shell/providers_setup.rs", + include_str!("providers_setup.rs"), + ), + ("shell/routing_setup.rs", include_str!("routing_setup.rs")), + ("shell/migration.rs", include_str!("migration.rs")), + ("shell/startup_window.rs", include_str!("startup_window.rs")), + ("shell/backend_ready.rs", include_str!("backend_ready.rs")), + ("shell/ipc/mod.rs", include_str!("ipc/mod.rs")), + ] { + assert!( + !source.contains(&read), + "{file} reads the port itself: use backend_ready::bound_port()" + ); + } + assert_eq!( + include_str!("../lib.rs").matches(&read).count(), + 1, + "lib.rs reads FLEETIFY_BACKEND_PORT once, into port_from_env" + ); + } + + #[test] + fn the_clients_of_the_apps_own_backend_never_use_a_proxy() { + // reqwest's own builders use the proxy in HTTP_PROXY / ALL_PROXY, + // with no exemption for loopback. Built at run time so this test's + // own source doesn't match. + let shared = format!("fleetify_core::loopback::{}()", "http_client_builder"); + let proxied = [ + format!("reqwest::Client::{}()", "new"), + format!("reqwest::Client::{}()", "builder"), + format!("Client::{}()", "default"), + ]; + for (file, source) in [ + ( + "shell/providers_setup.rs", + include_str!("providers_setup.rs"), + ), + ("shell/routing_setup.rs", include_str!("routing_setup.rs")), + ("shell/backend_ready.rs", include_str!("backend_ready.rs")), + ("shell/startup_window.rs", include_str!("startup_window.rs")), + ( + "crates/memory-mcp/src/main.rs", + include_str!("../../../crates/memory-mcp/src/main.rs"), + ), + ( + "crates/dispatch-mcp/src/main.rs", + include_str!("../../../crates/dispatch-mcp/src/main.rs"), + ), + ( + "crates/browser-mcp/src/main.rs", + include_str!("../../../crates/browser-mcp/src/main.rs"), + ), + ] { + assert!( + source.contains(&shared), + "{file} doesn't build its client with {shared}" + ); + for builder in &proxied { + assert!( + !source.contains(builder.as_str()), + "{file} builds a client with {builder}, which sends the app's \ + secrets through a proxy from the environment: use {shared}" + ); + } + } + } +} diff --git a/src-tauri/src/shell/config.rs b/src-tauri/src/shell/config.rs index e6282ef..34432d0 100644 --- a/src-tauri/src/shell/config.rs +++ b/src-tauri/src/shell/config.rs @@ -3,31 +3,164 @@ //! JSON-on-disk used by the original. use std::collections::HashMap; +use std::io::Write; use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; const CONFIG_FILE: &str = "fleet.config.json"; -/// Load JSON config; returns `{}` when the file doesn't exist or fails to -/// parse (parity with the Electron store's "no file = empty object"). +/// What [`load_config_with_status`] found at `fleet.config.json`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConfigLoad { + /// There is no file: a fresh install, or a reset one. + Missing, + /// The file parsed to a JSON object. + Ok, + /// The file was read but isn't a JSON object; a copy was kept. + Corrupt, + /// The file is there but couldn't be read. + Unreadable, +} + +/// Load JSON config; `{}` when the file doesn't exist (parity with the +/// Electron store's "no file = empty object") or can't be read. One leading +/// UTF-8 BOM, which some Windows editors write, is ignored. +/// +/// A file that reads but isn't a JSON object (a hand edit with a stray +/// comma, say) also gives `{}`, after a copy of the bytes read is kept as +/// `fleet.config.json.corrupt-`. Every setter reads, merges +/// and writes the whole file, so the next save replaces it and would +/// otherwise silently drop every other setting. The file itself is never +/// touched here: by now it may hold something other than what was read. +/// +/// [`load_config_with_status`] also says which of these it found. pub fn load_config_from(path: &Path) -> Value { + load_config_with_status(path).0 +} + +/// [`load_config_from`], plus what it found. Both a missing file and a +/// broken one load as `{}`; a caller for which they must differ reads the +/// status. +pub fn load_config_with_status(path: &Path) -> (Value, ConfigLoad) { let file = path.join(CONFIG_FILE); - match std::fs::read_to_string(&file) { - Ok(text) => serde_json::from_str(&text).unwrap_or_else(|_| json!({})), - Err(_) => json!({}), + // Bytes, not a String: a file that isn't UTF-8 isn't JSON either, and + // must be kept like any other corrupt config. + let bytes = match std::fs::read(&file) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return (json!({}), ConfigLoad::Missing) + } + Err(e) => { + tracing::warn!(error = %e, "couldn't read {CONFIG_FILE}; using defaults"); + return (json!({}), ConfigLoad::Unreadable); + } + }; + let content = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes); + let problem = match serde_json::from_slice::(content) { + Ok(cfg @ Value::Object(_)) => return (cfg, ConfigLoad::Ok), + Ok(_) => "not a JSON object".to_string(), + // A position and a fixed message, never the file's text. + Err(e) => e.to_string(), + }; + back_up_corrupt_config(path, &bytes, &problem); + (json!({}), ConfigLoad::Corrupt) +} + +/// Keep `bytes`, read from a corrupt config, in `dir` as +/// `fleet.config.json.corrupt-`. +/// Named by content, so loading the same bytes again finds the copy already +/// kept and stays quiet, and no other copy is ever overwritten. Logs the +/// backup's file name only: not the folder (its path usually holds the +/// user's name), and never the content. +fn back_up_corrupt_config(dir: &Path, bytes: &[u8], problem: &str) { + let hash: String = Sha256::digest(bytes)[..8] + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + let name = format!("{CONFIG_FILE}.corrupt-{hash}"); + let backup = dir.join(&name); + let written = match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&backup) + { + Ok(mut out) => { + let wrote = out.write_all(bytes); + drop(out); + if wrote.is_err() { + // A partial copy would pass for a kept one at the next load. + let _ = std::fs::remove_file(&backup); + } + wrote + } + // These exact bytes are already kept. + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return, + Err(e) => Err(e), + }; + match written { + Ok(()) => tracing::warn!( + problem = %problem, + backup = %name, + "{CONFIG_FILE} isn't a JSON object; kept a copy and used defaults" + ), + Err(error) => tracing::warn!( + problem = %problem, + error = %error, + "{CONFIG_FILE} isn't a JSON object and no copy could be kept; used defaults" + ), } } -/// Save JSON config atomically (write `.tmp` then rename, so a crash -/// mid-write doesn't corrupt the existing config file). +/// Milliseconds since the Unix epoch, or 0 when the clock is set before it. +fn unix_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +/// Numbers this process's config temp files. With the pid in the name too, +/// no two saves share a temp file, even across processes sharing the folder. +static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// Held around each save's write and rename. The privacy setters and the +/// renderer's `config_set` can save at the same time; one at a time, the +/// last rename wins whole. +static SAVE_LOCK: Mutex<()> = Mutex::new(()); + +/// Save JSON config atomically: fill a temp file of this save's own +/// (`fleet.config.json...tmp`), flush it to disk, then rename it over +/// the live file. A crash mid-save leaves the old file whole, and a save +/// never renames a temp file another save is still filling. A failed save +/// removes its temp file. pub fn save_config_to(path: &Path, cfg: &Value) -> std::io::Result<()> { std::fs::create_dir_all(path)?; let file = path.join(CONFIG_FILE); - let tmp = path.join(format!("{CONFIG_FILE}.tmp")); - std::fs::write(&tmp, serde_json::to_string_pretty(cfg).unwrap_or_default())?; - std::fs::rename(&tmp, &file)?; - Ok(()) + let n = TMP_COUNTER.fetch_add(1, Ordering::Relaxed); + let tmp = path.join(format!("{CONFIG_FILE}.{}.{n}.tmp", std::process::id())); + let body = serde_json::to_string_pretty(cfg).unwrap_or_default(); + // A save that panicked while holding the lock left nothing half-done + // that the next one depends on. + let _guard = SAVE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let saved = write_synced(&tmp, body.as_bytes()).and_then(|()| std::fs::rename(&tmp, &file)); + if saved.is_err() { + let _ = std::fs::remove_file(&tmp); + } + saved +} + +/// Write `bytes` to a new file at `path` and flush it to disk, so the rename +/// that follows can never publish an empty or partial file after a crash. +fn write_synced(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let mut out = std::fs::File::create(path)?; + out.write_all(bytes)?; + out.sync_all() } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -154,22 +287,65 @@ pub fn providers_set(cfg: &mut Value, providers: &ProvidersConfig) { } } -/// PostHog product-analytics opt-in. Default `posthog_enabled` is `false` — +/// Whether the commits and pull requests the app makes credit Fleetify (a +/// `Co-Authored-By` trailer and a PR footer). Settings → General → +/// Attribution writes the flat `gitAttribution` key; absent or non-boolean +/// means on, the default. +pub fn git_attribution_from(cfg: &Value) -> bool { + cfg.get("gitAttribution") + .and_then(Value::as_bool) + .unwrap_or(true) +} + +/// The two telemetry switches, at `fleet.config.json::telemetry` (parallel +/// to `routing` / `providers`). +/// +/// PostHog product analytics: default `posthog_enabled` is `false` — /// flipped only by explicit user consent in the onboarding step or in /// Settings → Privacy. `posthog_enabled_at` records the first opt-in /// timestamp (Unix ms) so funnels can distinguish fresh consenters from /// users who've been enabled for ages. /// -/// Lives at `fleet.config.json::telemetry` (parallel to `routing` / -/// `providers`). The Fleetify cloud telemetry path is independent and -/// remains gated by `FLEETIFY_NOAUTH` + the existing privacy-card -/// `telemetryEnabled` flag; this struct only controls the PostHog sink. +/// Fleetify cloud sync (the fleetify.dev dashboard): `cloud_sync_enabled` +/// is the saved switch — `None` until the user flips it; read it through +/// [`cloud_sync_from`], which also covers the legacy flag and the default +/// (on). `cloud_sync_enabled_at` records the first opt-in (Unix ms): the +/// first time a saved opt-out is turned back on. #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct TelemetryConfig { #[serde(default)] pub posthog_enabled: bool, #[serde(default)] pub posthog_enabled_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cloud_sync_enabled: Option, + #[serde(default)] + pub cloud_sync_enabled_at: Option, +} + +/// Whether Fleetify cloud sync is on for a user who never flipped the +/// switch: on, disclosed at onboarding, and turned off in Settings → +/// Privacy. The owner's decision; nothing else may hard-code it. +pub const CLOUD_SYNC_DEFAULT: bool = true; + +/// Whether Fleetify cloud sync is on. In order: +/// 1. `telemetry.cloud_sync_enabled`, when it is a bool; +/// 2. `false` when the legacy top-level `telemetryEnabled` is exactly +/// `false` — an explicit opt-out from the old switch still counts (its +/// `true` does not: that switch was never read and defaulted to on); +/// 3. [`CLOUD_SYNC_DEFAULT`]. +pub fn cloud_sync_from(cfg: &Value) -> bool { + if let Some(on) = cfg + .get("telemetry") + .and_then(|t| t.get("cloud_sync_enabled")) + .and_then(Value::as_bool) + { + return on; + } + if cfg.get("telemetryEnabled").and_then(Value::as_bool) == Some(false) { + return false; + } + CLOUD_SYNC_DEFAULT } pub fn telemetry_from(cfg: &Value) -> TelemetryConfig { @@ -178,26 +354,233 @@ pub fn telemetry_from(cfg: &Value) -> TelemetryConfig { .unwrap_or_default() } +/// Write `telem` into the `"telemetry"` section field by field, so keys the +/// struct doesn't know, or couldn't parse, survive: a malformed sibling +/// (which sends [`telemetry_from`] to its defaults) must not cost the user +/// their saved cloud sync choice. `None` fields are skipped; they neither +/// write `null` nor remove a saved value. pub fn telemetry_set(cfg: &mut Value, telem: &TelemetryConfig) { - let val = serde_json::to_value(telem).unwrap_or_else(|_| json!({})); - match cfg { - Value::Object(map) => { - map.insert("telemetry".into(), val); + let Ok(Value::Object(fields)) = serde_json::to_value(telem) else { + return; + }; + if !cfg.is_object() { + *cfg = json!({}); + } + let section = &mut cfg["telemetry"]; + if !section.is_object() { + *section = json!({}); + } + if let Some(section) = section.as_object_mut() { + for (key, value) in fields { + if !value.is_null() { + section.insert(key, value); + } } - _ => { - *cfg = json!({ "telemetry": val }); + } +} + +/// Save the Fleetify cloud sync switch in `dir`'s `fleet.config.json`: +/// read-merge-write `telemetry.cloud_sync_enabled`, stamping +/// `cloud_sync_enabled_at` on the first opt-in only (turning it off, or on +/// again later, keeps that time). Saving `true` while the saved setting is +/// already on, as it is by default, records the choice but is no opt-in, so +/// it stamps nothing: also onboarding's "Keep it on" on a new install, whose +/// gate opens only then. `Err` carries a message fit for the user. +pub fn persist_cloud_choice(dir: &Path, enabled: bool) -> Result<(), String> { + let mut cfg = load_config_from(dir); + let was_enabled = cloud_sync_from(&cfg); + let mut telem = telemetry_from(&cfg); + telem.cloud_sync_enabled = Some(enabled); + if enabled && !was_enabled && telem.cloud_sync_enabled_at.is_none() { + telem.cloud_sync_enabled_at = Some(unix_ms()); + } + telemetry_set(&mut cfg, &telem); + save_config_to(dir, &cfg).map_err(|e| format!("Couldn't save the cloud sync setting: {e}")) +} + +/// Whether this launch may open the cloud sync gate, decided once at +/// startup from `dir`'s `fleet.config.json`. +/// +/// A new install keeps sync off until the user answers onboarding's +/// dashboard step, whose buttons save the choice and set the gate: with no +/// file, or a file that holds neither a saved choice nor +/// `onboardingComplete: true`, sync stays off and nothing is written. Past +/// either, the saved choice decides ([`cloud_sync_from`], so with none, the +/// default). +/// +/// A file that is there but can't be read or parsed fails closed, since an +/// earlier opt-out may be what it no longer shows: sync stays off for this +/// launch, and an explicit opt-out is saved ([`persist_cloud_choice`]) so +/// later launches stay off too, until the user turns sync back on. An +/// unreadable file is moved aside first, so its bytes are kept. If the save +/// fails, the file is put back, and sync still stays off for this launch. +pub fn startup_cloud_decision(dir: &Path) -> bool { + decide_cloud_at_startup(dir, |dir| persist_cloud_choice(dir, false)) +} + +/// [`startup_cloud_decision`], with the opt-out save passed in so a test +/// can make it fail. +fn decide_cloud_at_startup( + dir: &Path, + save_opt_out: impl FnOnce(&Path) -> Result<(), String>, +) -> bool { + let (cfg, status) = load_config_with_status(dir); + let condition = match status { + ConfigLoad::Missing => return false, + ConfigLoad::Ok => return cloud_choice_or_onboarded(&cfg) && cloud_sync_from(&cfg), + ConfigLoad::Corrupt => "corrupt", + ConfigLoad::Unreadable => "unreadable", + }; + // A file that can't be read can't be copied either, so it is moved + // aside whole before the opt-out takes its place. A corrupt file was + // read, and the load already kept a copy. + let aside = match status { + ConfigLoad::Unreadable => move_unreadable_aside(dir), + _ => None, + }; + // The condition and the aside's file name only: never the file's + // content, nor its folder (whose path usually holds the user's name). + match (save_opt_out(dir), &aside) { + (Ok(()), Some(kept)) => tracing::warn!( + condition, + kept = %kept, + "{CONFIG_FILE} is {condition}; moved it aside, and cloud sync is off \ + until it is turned back on" + ), + (Ok(()), None) => tracing::warn!( + condition, + "{CONFIG_FILE} is {condition}; cloud sync is off until it is turned back on" + ), + (Err(error), _) => { + // Put the file back: with none there, the next launch would take + // this for a new install. + if let Some(kept) = &aside { + if let Err(e) = std::fs::rename(dir.join(kept), dir.join(CONFIG_FILE)) { + tracing::warn!( + condition, + kept = %kept, + error = %e, + "{CONFIG_FILE} was moved aside and couldn't be put back" + ); + } + } + tracing::warn!( + condition, + error = %error, + "{CONFIG_FILE} is {condition}; cloud sync stays off for this launch, \ + but turning it off couldn't be saved" + ); } } + false +} + +/// Whether `cfg` holds a saved cloud sync choice (`telemetry.cloud_sync_enabled` +/// is a bool) or says onboarding is finished (top-level `onboardingComplete` +/// is `true`, which the renderer writes). Until one of them does, a new +/// install keeps sync off. +fn cloud_choice_or_onboarded(cfg: &Value) -> bool { + let chose = cfg + .get("telemetry") + .and_then(|t| t.get("cloud_sync_enabled")) + .is_some_and(Value::is_boolean); + let onboarded = cfg.get("onboardingComplete").and_then(Value::as_bool) == Some(true); + chose || onboarded +} + +/// Moves `dir`'s unreadable `fleet.config.json` aside, to a name of its own +/// ([`free_aside_name`]). A rename needs only write access to the folder and +/// keeps the file whole: its bytes, owner and mode. A folder is never moved; +/// a link is moved itself, never what it points to. Returns the new name, or +/// `None` when nothing was moved. +fn move_unreadable_aside(dir: &Path) -> Option { + let live = dir.join(CONFIG_FILE); + let movable = std::fs::symlink_metadata(&live).is_ok_and(|m| !m.is_dir()); + if !movable { + return None; + } + let name = free_aside_name(dir, unix_ms()); + std::fs::rename(&live, dir.join(&name)).ok()?; + Some(name) +} + +/// `fleet.config.json.unreadable-`, or the same with `-` added when +/// `dir` already has a file by that name, so no earlier copy is replaced +/// (the clock can repeat, or sit at 0 when it is set before 1970). +fn free_aside_name(dir: &Path, ms: i64) -> String { + let base = format!("{CONFIG_FILE}.unreadable-{ms}"); + let mut name = base.clone(); + let mut n = 1u32; + while std::fs::symlink_metadata(dir.join(&name)).is_ok() { + name = format!("{base}-{n}"); + n += 1; + } + name +} + +/// What `dir`'s `fleet.config.json` says about cloud sync now, for the end +/// of the startup restore: the saved choice when the file loads or isn't +/// there, and off when it is there but can't be read or parsed. Saves +/// nothing. +pub fn saved_cloud_choice(dir: &Path) -> bool { + let (cfg, status) = load_config_with_status(dir); + matches!(status, ConfigLoad::Missing | ConfigLoad::Ok) && cloud_sync_from(&cfg) +} + +/// Save the PostHog product analytics switch in `dir`'s `fleet.config.json`: +/// read-merge-write `telemetry.posthog_enabled`, stamping +/// `posthog_enabled_at` on the first opt-in only (turning it off, or on +/// again later, keeps that time). `Err` carries a message fit for the user. +pub fn persist_posthog_choice(dir: &Path, enabled: bool) -> Result<(), String> { + let mut cfg = load_config_from(dir); + let mut telem = telemetry_from(&cfg); + let was_enabled = telem.posthog_enabled; + telem.posthog_enabled = enabled; + if enabled && !was_enabled && telem.posthog_enabled_at.is_none() { + telem.posthog_enabled_at = Some(unix_ms()); + } + telemetry_set(&mut cfg, &telem); + save_config_to(dir, &cfg) + .map_err(|e| format!("Couldn't save the product analytics setting: {e}")) } #[cfg(test)] mod tests { use super::*; + /// The `fleet.config.json.corrupt-*` backups in `dir`. Each must be + /// named by 16 lowercase hex characters (its content hash). + fn corrupt_backups(dir: &Path) -> Vec { + let prefix = format!("{CONFIG_FILE}.corrupt-"); + let backups: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + let name = path.file_name().unwrap().to_str().unwrap(); + name.starts_with(&prefix) + }) + .collect(); + for path in &backups { + let name = path.file_name().unwrap().to_str().unwrap(); + let hash = &name[prefix.len()..]; + assert!( + hash.len() == 16 && hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), + "backup not named by 16 lowercase hex characters: {name}" + ); + } + backups + } + + /// What `fleet.config.json` in `dir` holds now; `None` once it's gone. + fn live_bytes(dir: &Path) -> Option> { + std::fs::read(dir.join(CONFIG_FILE)).ok() + } + #[test] - fn load_empty_when_missing() { + fn a_missing_file_loads_as_empty_without_a_backup() { let tmp = tempfile::tempdir().unwrap(); assert_eq!(load_config_from(tmp.path()), json!({})); + assert!(corrupt_backups(tmp.path()).is_empty()); } #[test] @@ -208,11 +591,627 @@ mod tests { assert_eq!(load_config_from(tmp.path()), v); } + /// Temp files left in `dir`. + fn temp_files(dir: &Path) -> Vec { + std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".tmp")) + .collect() + } + + /// Reads `dir`'s live config over and over until stopped, as the app + /// does on every load, and lists each read that found it torn. Unix + /// only: there a rename replaces the file atomically even while a reader + /// has it open. On Windows an open reader can make the rename itself + /// fail, which is not what the test below asks. + #[cfg(unix)] + struct TornReader { + done: std::sync::Arc, + reads: std::thread::JoinHandle>, + } + + #[cfg(unix)] + impl TornReader { + fn start(dir: std::sync::Arc, filler_len: usize) -> Self { + let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop = std::sync::Arc::clone(&done); + let reads = std::thread::spawn(move || { + let mut torn = Vec::new(); + while !stop.load(Ordering::Relaxed) { + let Ok(bytes) = std::fs::read(dir.join(CONFIG_FILE)) else { + torn.push("missing".to_string()); + continue; + }; + match serde_json::from_slice::(&bytes) { + Ok(cfg) if cfg["filler"].as_str().map(str::len) == Some(filler_len) => {} + _ => torn.push(format!("{} bytes", bytes.len())), + } + } + torn + }); + Self { done, reads } + } + + fn stop(self) -> Vec { + self.done.store(true, Ordering::Relaxed); + self.reads.join().unwrap() + } + } + #[test] - fn corrupt_file_falls_back_to_empty() { + fn concurrent_saves_all_succeed_and_the_live_file_always_parses() { + use std::sync::Arc; + + // The privacy setters and the renderer's config_set can save at the + // same time. Large enough that one write takes a while, so they + // overlap. + const FILLER: usize = 256 * 1024; + let tmp = tempfile::tempdir().unwrap(); + let dir = Arc::new(tmp.path().to_path_buf()); + let filler = Arc::new("x".repeat(FILLER)); + save_config_to(&dir, &json!({ "writer": -1, "filler": *filler })).unwrap(); + + #[cfg(unix)] + let reader = TornReader::start(Arc::clone(&dir), FILLER); + + let writers: Vec<_> = (0..8) + .map(|writer| { + let (dir, filler) = (Arc::clone(&dir), Arc::clone(&filler)); + std::thread::spawn(move || { + (0..12) + .map(|i| { + save_config_to( + &dir, + &json!({ "writer": writer, "i": i, "filler": *filler }), + ) + .map_err(|e| e.to_string()) + }) + .collect::>() + }) + }) + .collect(); + let failed: Vec = writers + .into_iter() + .flat_map(|w| w.join().unwrap()) + .filter_map(Result::err) + .collect(); + #[cfg(unix)] + let torn = reader.stop(); + + assert!(failed.is_empty(), "saves that failed: {failed:?}"); + #[cfg(unix)] + assert!(torn.is_empty(), "reads of a torn live file: {torn:?}"); + let cfg = load_config_from(&dir); + assert_eq!(cfg["filler"].as_str().map(str::len), Some(FILLER)); + assert!(temp_files(&dir).is_empty(), "{:?}", temp_files(&dir)); + assert!(corrupt_backups(&dir).is_empty()); + } + + #[test] + fn a_failed_save_leaves_no_temp_file_and_the_old_file_whole() { + let tmp = tempfile::tempdir().unwrap(); + // A folder where the live file should be: the write works, the rename + // over it fails. + let live = tmp.path().join(CONFIG_FILE); + std::fs::create_dir(&live).unwrap(); + std::fs::write(live.join("keep"), "x").unwrap(); + + assert!(save_config_to(tmp.path(), &json!({ "theme": "dark" })).is_err()); + + assert!( + temp_files(tmp.path()).is_empty(), + "{:?}", + temp_files(tmp.path()) + ); + assert_eq!(std::fs::read(live.join("keep")).unwrap(), b"x"); + } + + #[test] + fn a_save_never_writes_through_another_saves_temp_file() { + // The old fixed temp name, as a save from another writer would be + // filling it. Each save now has a temp file of its own. let tmp = tempfile::tempdir().unwrap(); - std::fs::write(tmp.path().join(CONFIG_FILE), "{not valid json").unwrap(); + let other = tmp.path().join(format!("{CONFIG_FILE}.tmp")); + std::fs::write(&other, "half-written").unwrap(); + + save_config_to(tmp.path(), &json!({ "theme": "dark" })).unwrap(); + + assert_eq!(std::fs::read(&other).unwrap(), b"half-written"); + assert_eq!(load_config_from(tmp.path()), json!({ "theme": "dark" })); + } + + #[test] + fn a_valid_file_loads_unchanged_without_a_backup() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write( + tmp.path().join(CONFIG_FILE), + r#"{"theme": "dark", "providers": {"a": 1}}"#, + ) + .unwrap(); + assert_eq!( + load_config_from(tmp.path()), + json!({"theme": "dark", "providers": {"a": 1}}) + ); + assert!(corrupt_backups(tmp.path()).is_empty()); + assert!(tmp.path().join(CONFIG_FILE).exists()); + } + + #[test] + fn a_corrupt_file_is_backed_up_and_loads_as_empty() { + let tmp = tempfile::tempdir().unwrap(); + let original = br#"{"providers": {"a": 1},"#; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&original[..]), + "live file untouched" + ); + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), original); + // Named by the first 16 hex characters of the bytes' SHA-256 + // (`printf '%s' '{"providers": {"a": 1},' | sha256sum`). + assert_eq!( + backups[0].file_name().unwrap(), + "fleet.config.json.corrupt-16e4fbebb8eabfec" + ); + } + + #[test] + fn a_file_that_is_not_an_object_is_backed_up_too() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(CONFIG_FILE), "[1,2]").unwrap(); + + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&b"[1,2]"[..]), + "live file untouched" + ); + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), b"[1,2]"); + } + + #[test] + fn a_file_that_is_not_utf8_is_backed_up_too() { + // JSON must be UTF-8, so these bytes are a corrupt config like any + // other, not an unreadable file to leave for the next save. + let tmp = tempfile::tempdir().unwrap(); + let original = b"{\"theme\": \"\xff\xfe\"}"; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&original[..]), + "live file untouched" + ); + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), original); + } + + #[test] + fn loading_the_same_corrupt_file_twice_keeps_one_backup() { + let tmp = tempfile::tempdir().unwrap(); + let original = br#"{"providers": {"a": 1},"#; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&original[..]), + "live file untouched" + ); + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), original); + } + + #[test] + fn a_changed_corrupt_file_gets_a_second_backup() { + let tmp = tempfile::tempdir().unwrap(); + let first = br#"{"providers": {"a": 1},"#; + let second = br#"{"providers": {"a": 2},"#; + std::fs::write(tmp.path().join(CONFIG_FILE), first).unwrap(); + assert_eq!(load_config_from(tmp.path()), json!({})); + + std::fs::write(tmp.path().join(CONFIG_FILE), second).unwrap(); + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&second[..]), + "live file untouched" + ); + let mut kept: Vec> = corrupt_backups(tmp.path()) + .iter() + .map(|path| std::fs::read(path).unwrap()) + .collect(); + kept.sort(); + assert_eq!(kept, [first.to_vec(), second.to_vec()]); + } + + #[test] + fn a_valid_file_with_a_bom_loads_without_a_backup() { + let tmp = tempfile::tempdir().unwrap(); + let original = b"\xEF\xBB\xBF{\"theme\": \"dark\", \"providers\": {\"a\": 1}}"; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + + assert_eq!( + load_config_from(tmp.path()), + json!({"theme": "dark", "providers": {"a": 1}}) + ); + assert!(corrupt_backups(tmp.path()).is_empty()); + assert_eq!(live_bytes(tmp.path()).as_deref(), Some(&original[..])); + } + + #[test] + fn a_corrupt_file_with_a_bom_is_backed_up_whole() { + let tmp = tempfile::tempdir().unwrap(); + let original = b"\xEF\xBB\xBF{\"providers\": {\"a\": 1},"; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + assert_eq!(load_config_from(tmp.path()), json!({})); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&original[..]), + "live file untouched" + ); + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), original, "BOM kept"); + // Named by the hash of the raw bytes, BOM included. + assert_eq!( + backups[0].file_name().unwrap(), + "fleet.config.json.corrupt-421aca0a03c1d36a" + ); + } + + #[test] + fn a_save_after_a_corrupt_load_leaves_the_backup_alone() { + let tmp = tempfile::tempdir().unwrap(); + let original = br#"{"providers": {"a": 1},"#; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + + persist_cloud_choice(tmp.path(), true).unwrap(); + + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), original); + // The live file now holds only what the setter wrote. + let cfg: Value = serde_json::from_slice(&live_bytes(tmp.path()).unwrap()).unwrap(); + assert_eq!( + cfg.as_object().unwrap().keys().collect::>(), + ["telemetry"], + "{cfg}" + ); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(true)); + } + + #[test] + fn the_load_status_says_what_was_found() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join(CONFIG_FILE); + assert_eq!( + load_config_with_status(tmp.path()), + (json!({}), ConfigLoad::Missing) + ); + + std::fs::write(&file, b"\xEF\xBB\xBF{\"theme\": \"dark\"}").unwrap(); + assert_eq!( + load_config_with_status(tmp.path()), + (json!({"theme": "dark"}), ConfigLoad::Ok) + ); + + std::fs::write(&file, "{\"theme\": ").unwrap(); + assert_eq!( + load_config_with_status(tmp.path()), + (json!({}), ConfigLoad::Corrupt) + ); + std::fs::write(&file, "[1,2]").unwrap(); + assert_eq!( + load_config_with_status(tmp.path()), + (json!({}), ConfigLoad::Corrupt) + ); + + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir(&file).unwrap(); + assert_eq!( + load_config_with_status(tmp.path()), + (json!({}), ConfigLoad::Unreadable) + ); + } + + #[test] + fn a_corrupt_config_keeps_sync_off_and_saves_the_opt_out() { + let tmp = tempfile::tempdir().unwrap(); + // An opt-out cut short: the saved choice can't be read back. + let original = br#"{"telemetry": {"cloud_sync_enabled": false"#; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + + assert!( + !startup_cloud_decision(tmp.path()), + "a corrupt config keeps sync off" + ); + + // The opt-out is saved, so later launches stay off as well... + let cfg: Value = serde_json::from_slice(&live_bytes(tmp.path()).unwrap()).unwrap(); + assert_eq!( + cfg["telemetry"]["cloud_sync_enabled"], + json!(false), + "{cfg}" + ); + assert!( + !startup_cloud_decision(tmp.path()), + "the next launch stays off" + ); + // ...and the corrupt bytes are still kept, as a copy: a file that + // could be read is never moved aside. + let backups = corrupt_backups(tmp.path()); + assert_eq!(backups.len(), 1, "{backups:?}"); + assert_eq!(std::fs::read(&backups[0]).unwrap(), original); + assert!(unreadable_asides(tmp.path()).is_empty()); + } + + /// The `fleet.config.json.unreadable-*` files in `dir`, each named by + /// a time in Unix ms, maybe with `-` added. + fn unreadable_asides(dir: &Path) -> Vec { + let prefix = format!("{CONFIG_FILE}.unreadable-"); + let asides: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + let name = path.file_name().unwrap().to_str().unwrap(); + name.starts_with(&prefix) + }) + .collect(); + for path in &asides { + let name = path.file_name().unwrap().to_str().unwrap(); + let suffix = &name[prefix.len()..]; + assert!( + suffix + .split('-') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())), + "aside not named by a time: {name}" + ); + } + asides + } + + #[test] + fn an_unreadable_config_keeps_sync_off() { + let tmp = tempfile::tempdir().unwrap(); + // A folder where the file belongs: it is there but can't be read. A + // folder is never moved aside, and nothing can replace it, so the + // opt-out can't be saved either. + std::fs::create_dir(tmp.path().join(CONFIG_FILE)).unwrap(); + + assert!(!startup_cloud_decision(tmp.path())); + assert!( + tmp.path().join(CONFIG_FILE).is_dir(), + "the save failed, and sync still stays off" + ); + assert!( + unreadable_asides(tmp.path()).is_empty(), + "a folder is never moved" + ); + assert!(corrupt_backups(tmp.path()).is_empty()); + } + + #[cfg(unix)] + #[test] + fn an_unreadable_config_is_moved_aside_and_gets_the_opt_out() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join(CONFIG_FILE); + let original = br#"{"theme": "dark", "telemetry": {"cloud_sync_enabled": false}}"#; + std::fs::write(&file, original).unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000)).unwrap(); + if std::fs::read(&file).is_ok() { + eprintln!("skipped: permissions don't stop this user's reads (root?)"); + return; + } + + assert!(!startup_cloud_decision(tmp.path())); + + // The opt-out took the file's place... + let cfg = load_config_from(tmp.path()); + assert_eq!( + cfg["telemetry"]["cloud_sync_enabled"], + json!(false), + "{cfg}" + ); + // ...and the unreadable file is kept whole beside it, mode and all. + let asides = unreadable_asides(tmp.path()); + assert_eq!(asides.len(), 1, "{asides:?}"); + let kept = std::fs::metadata(&asides[0]).unwrap(); + assert_eq!(kept.len(), original.len() as u64); + assert_eq!(kept.permissions().mode() & 0o777, 0o000, "mode kept"); + std::fs::set_permissions(&asides[0], std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&asides[0]).unwrap(), original); + } + + /// Makes `dir`'s `fleet.config.json` a link to a folder, which nobody + /// can read, root included, and which isn't a folder itself. Returns the + /// folder. + #[cfg(unix)] + fn link_to_a_folder(dir: &Path) -> std::path::PathBuf { + let target = dir.join("elsewhere"); + std::fs::create_dir(&target).unwrap(); + std::os::unix::fs::symlink(&target, dir.join(CONFIG_FILE)).unwrap(); + target + } + + #[cfg(unix)] + #[test] + fn an_unreadable_link_is_moved_aside_and_its_folder_stays() { + let tmp = tempfile::tempdir().unwrap(); + let target = link_to_a_folder(tmp.path()); + + assert!(!startup_cloud_decision(tmp.path())); + + let cfg = load_config_from(tmp.path()); + assert_eq!( + cfg["telemetry"]["cloud_sync_enabled"], + json!(false), + "{cfg}" + ); + let asides = unreadable_asides(tmp.path()); + assert_eq!(asides.len(), 1, "{asides:?}"); + assert_eq!( + std::fs::read_link(&asides[0]).unwrap(), + target, + "the link itself was moved" + ); + assert!(target.is_dir(), "the folder stays where it was"); + } + + #[cfg(unix)] + #[test] + fn an_unreadable_config_is_put_back_when_the_opt_out_cant_be_saved() { + let tmp = tempfile::tempdir().unwrap(); + let target = link_to_a_folder(tmp.path()); + + let open = decide_cloud_at_startup(tmp.path(), |dir| { + assert!( + std::fs::symlink_metadata(dir.join(CONFIG_FILE)).is_err(), + "moved aside before the save" + ); + Err("Couldn't save the cloud sync setting: disk full".to_string()) + }); + + assert!(!open, "sync stays off for this launch"); + assert_eq!( + std::fs::read_link(tmp.path().join(CONFIG_FILE)).unwrap(), + target, + "put back, so the next launch doesn't take it for a new install" + ); + assert!(unreadable_asides(tmp.path()).is_empty()); + } + + #[test] + fn an_aside_name_never_replaces_an_earlier_one() { + let tmp = tempfile::tempdir().unwrap(); + assert_eq!( + free_aside_name(tmp.path(), 42), + "fleet.config.json.unreadable-42" + ); + std::fs::write(tmp.path().join("fleet.config.json.unreadable-42"), "kept").unwrap(); + std::fs::write(tmp.path().join("fleet.config.json.unreadable-42-1"), "kept").unwrap(); + assert_eq!( + free_aside_name(tmp.path(), 42), + "fleet.config.json.unreadable-42-2" + ); + } + + #[test] + fn a_missing_config_keeps_sync_off_and_writes_nothing() { + let tmp = tempfile::tempdir().unwrap(); + assert!( + !startup_cloud_decision(tmp.path()), + "a new install waits for the onboarding notice" + ); + assert!( + !tmp.path().join(CONFIG_FILE).exists(), + "a new install saves no choice" + ); + } + + /// The startup decision for a readable `fleet.config.json` holding + /// `cfg`, which it must leave as it was. + fn decide_on(cfg: &Value) -> bool { + let tmp = tempfile::tempdir().unwrap(); + save_config_to(tmp.path(), cfg).unwrap(); + let open = startup_cloud_decision(tmp.path()); + assert_eq!(&load_config_from(tmp.path()), cfg, "left as it was"); + open + } + + #[test] + fn a_config_with_no_choice_before_onboarding_keeps_sync_off() { + assert!(!decide_on(&json!({"theme": "dark"}))); + assert!(!decide_on( + &json!({"userName": "Mira", "onboardingComplete": false}) + )); + // Only `true` counts as finished. + assert!(!decide_on(&json!({"onboardingComplete": "true"}))); + } + + #[test] + fn an_onboarded_config_with_no_choice_gets_the_default() { + assert_eq!( + decide_on(&json!({"theme": "dark", "onboardingComplete": true})), + CLOUD_SYNC_DEFAULT + ); + // An opt-out from the old switch still counts. + assert!(!decide_on( + &json!({"onboardingComplete": true, "telemetryEnabled": false}) + )); + } + + #[test] + fn an_explicit_opt_in_opens_sync_before_onboarding() { + assert!(decide_on( + &json!({"telemetry": {"cloud_sync_enabled": true}}) + )); + assert!(decide_on(&json!({ + "telemetry": {"cloud_sync_enabled": true}, + "onboardingComplete": false + }))); + } + + #[test] + fn an_explicit_opt_out_keeps_sync_off_after_onboarding() { + assert!(!decide_on(&json!({ + "telemetry": {"cloud_sync_enabled": false}, + "onboardingComplete": true + }))); + assert!(!decide_on( + &json!({"telemetry": {"cloud_sync_enabled": false}}) + )); + } + + #[test] + fn the_restore_reads_a_broken_config_as_off_and_saves_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let original = br#"{"telemetry": {"cloud_sync_enabled": true}"#; + std::fs::write(tmp.path().join(CONFIG_FILE), original).unwrap(); + assert!(!saved_cloud_choice(tmp.path())); + assert_eq!( + live_bytes(tmp.path()).as_deref(), + Some(&original[..]), + "nothing saved" + ); + + let unreadable = tempfile::tempdir().unwrap(); + std::fs::create_dir(unreadable.path().join(CONFIG_FILE)).unwrap(); + assert!(!saved_cloud_choice(unreadable.path())); + } + + #[test] + fn the_restore_reads_a_missing_or_readable_config_as_saved() { + let tmp = tempfile::tempdir().unwrap(); + assert_eq!(saved_cloud_choice(tmp.path()), CLOUD_SYNC_DEFAULT); + assert!(!tmp.path().join(CONFIG_FILE).exists(), "nothing saved"); + + save_config_to( + tmp.path(), + &json!({"telemetry": {"cloud_sync_enabled": true}}), + ) + .unwrap(); + assert!(saved_cloud_choice(tmp.path())); + save_config_to( + tmp.path(), + &json!({"telemetry": {"cloud_sync_enabled": false}}), + ) + .unwrap(); + assert!(!saved_cloud_choice(tmp.path())); } #[test] @@ -327,6 +1326,7 @@ mod tests { let t = TelemetryConfig { posthog_enabled: true, posthog_enabled_at: Some(1_700_000_000_000), + ..Default::default() }; telemetry_set(&mut cfg, &t); let back = telemetry_from(&cfg); @@ -367,6 +1367,7 @@ mod tests { let t = TelemetryConfig { posthog_enabled: true, posthog_enabled_at: Some(42), + ..Default::default() }; telemetry_set(&mut cfg, &t); @@ -379,6 +1380,232 @@ mod tests { assert_eq!(telemetry_from(&cfg).posthog_enabled_at, Some(42)); } + #[test] + fn cloud_sync_falls_back_to_the_default_when_unset_or_not_a_bool() { + assert_eq!(cloud_sync_from(&json!({})), CLOUD_SYNC_DEFAULT); + assert_eq!(cloud_sync_from(&Value::Null), CLOUD_SYNC_DEFAULT); + assert_eq!(cloud_sync_from(&json!("on")), CLOUD_SYNC_DEFAULT); + assert_eq!( + cloud_sync_from(&json!({"telemetry": {"cloud_sync_enabled": null}})), + CLOUD_SYNC_DEFAULT + ); + assert_eq!( + cloud_sync_from(&json!({"telemetry": {"cloud_sync_enabled": "true"}})), + CLOUD_SYNC_DEFAULT + ); + } + + #[test] + fn sync_is_on_unless_the_user_turned_it_off() { + assert!(cloud_sync_from(&json!({})), "on for a user who never chose"); + assert!( + !cloud_sync_from(&json!({"telemetry": {"cloud_sync_enabled": false}})), + "an explicit opt-out" + ); + assert!( + !cloud_sync_from(&json!({"telemetryEnabled": false})), + "an opt-out from the old switch" + ); + } + + #[test] + fn cloud_sync_honours_the_saved_choice() { + assert!(cloud_sync_from( + &json!({"telemetry": {"cloud_sync_enabled": true}}) + )); + assert!(!cloud_sync_from( + &json!({"telemetry": {"cloud_sync_enabled": false}}) + )); + } + + #[test] + fn cloud_sync_honours_an_old_explicit_opt_out() { + assert!(!cloud_sync_from(&json!({"telemetryEnabled": false}))); + // The old switch was never read and defaulted to on, so `true` + // there is not a choice the user made. + assert_eq!( + cloud_sync_from(&json!({"telemetryEnabled": true})), + CLOUD_SYNC_DEFAULT + ); + } + + #[test] + fn saved_cloud_sync_choice_wins_over_the_old_flag() { + assert!(cloud_sync_from(&json!({ + "telemetry": {"cloud_sync_enabled": true}, + "telemetryEnabled": false + }))); + } + + #[test] + fn telemetry_set_merges_into_the_saved_section() { + let mut cfg = json!({ + "theme": "dark", + "telemetry": {"future_flag": 1, "posthog_enabled_at": 42} + }); + let t = TelemetryConfig { + posthog_enabled: true, + ..Default::default() + }; + telemetry_set(&mut cfg, &t); + // Unknown keys stay; `None` fields neither write `null` nor remove + // a saved value. + assert_eq!( + cfg, + json!({ + "theme": "dark", + "telemetry": {"future_flag": 1, "posthog_enabled_at": 42, "posthog_enabled": true} + }) + ); + } + + #[test] + fn posthog_toggle_keeps_the_cloud_sync_choice() { + // persist_posthog_choice reads the telemetry section into + // TelemetryConfig and merges the struct back. + let mut cfg = json!({ + "telemetry": {"cloud_sync_enabled": true, "cloud_sync_enabled_at": 42} + }); + let mut t = telemetry_from(&cfg); + t.posthog_enabled = true; + telemetry_set(&mut cfg, &t); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(true)); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled_at"], json!(42)); + } + + #[test] + fn persisting_the_cloud_choice_writes_the_key() { + let tmp = tempfile::tempdir().unwrap(); + // Sync is on by default, so an opt-in needs an earlier opt-out. + save_config_to( + tmp.path(), + &json!({"theme": "dark", "telemetry": {"cloud_sync_enabled": false}}), + ) + .unwrap(); + + persist_cloud_choice(tmp.path(), true).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(true)); + assert!( + cfg["telemetry"]["cloud_sync_enabled_at"].is_i64(), + "first opt-in stamped: {cfg}" + ); + assert_eq!(cfg["theme"], json!("dark"), "other settings kept"); + let first_opt_in = cfg["telemetry"]["cloud_sync_enabled_at"].clone(); + + persist_cloud_choice(tmp.path(), false).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(false)); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled_at"], first_opt_in); + + // Opting in again keeps the first opt-in time. + persist_cloud_choice(tmp.path(), true).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(true)); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled_at"], first_opt_in); + } + + #[test] + fn keeping_sync_on_saves_the_choice_without_an_opt_in_time() { + // Onboarding's "Keep it on" saves an explicit choice. The saved + // setting was already on (the default), so it isn't an opt-in, even + // on a new install whose gate opens only then: only turning a saved + // opt-out back on is stamped. + let tmp = tempfile::tempdir().unwrap(); + save_config_to(tmp.path(), &json!({"theme": "dark"})).unwrap(); + + persist_cloud_choice(tmp.path(), true).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(true)); + assert_eq!(cfg["telemetry"].get("cloud_sync_enabled_at"), None, "{cfg}"); + assert_eq!(cfg["theme"], json!("dark"), "other settings kept"); + } + + #[test] + fn persisting_the_cloud_choice_reports_a_failed_save() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("a-file"); + std::fs::write(&file, "not a folder").unwrap(); + // The settings folder would have to live under a regular file. + let err = persist_cloud_choice(&file.join("settings"), false).unwrap_err(); + assert!( + err.starts_with("Couldn't save the cloud sync setting: "), + "{err}" + ); + } + + #[test] + fn persisting_the_posthog_choice_writes_the_key() { + let tmp = tempfile::tempdir().unwrap(); + save_config_to( + tmp.path(), + &json!({"theme": "dark", "telemetry": {"cloud_sync_enabled": false}}), + ) + .unwrap(); + + persist_posthog_choice(tmp.path(), true).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["posthog_enabled"], json!(true)); + assert!( + cfg["telemetry"]["posthog_enabled_at"].is_i64(), + "first opt-in stamped: {cfg}" + ); + assert_eq!( + cfg["telemetry"]["cloud_sync_enabled"], + json!(false), + "cloud choice kept" + ); + assert_eq!(cfg["theme"], json!("dark"), "other settings kept"); + let first_opt_in = cfg["telemetry"]["posthog_enabled_at"].clone(); + + persist_posthog_choice(tmp.path(), false).unwrap(); + let mut cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["posthog_enabled"], json!(false)); + assert_eq!(cfg["telemetry"]["posthog_enabled_at"], first_opt_in); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(false)); + + // Opting in again keeps the first opt-in time. A stamp no clock + // would write shows a fresh one even within the same millisecond. + cfg["telemetry"]["posthog_enabled_at"] = json!(42); + save_config_to(tmp.path(), &cfg).unwrap(); + persist_posthog_choice(tmp.path(), true).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!(cfg["telemetry"]["posthog_enabled"], json!(true)); + assert_eq!(cfg["telemetry"]["posthog_enabled_at"], json!(42)); + assert_eq!(cfg["telemetry"]["cloud_sync_enabled"], json!(false)); + } + + #[test] + fn a_malformed_telemetry_field_does_not_cost_the_cloud_choice() { + let tmp = tempfile::tempdir().unwrap(); + save_config_to( + tmp.path(), + &json!({"telemetry": {"posthog_enabled": "yes", "cloud_sync_enabled": false}}), + ) + .unwrap(); + + persist_posthog_choice(tmp.path(), true).unwrap(); + let cfg = load_config_from(tmp.path()); + assert_eq!( + cfg["telemetry"]["cloud_sync_enabled"], + json!(false), + "{cfg}" + ); + assert_eq!(cfg["telemetry"]["posthog_enabled"], json!(true), "{cfg}"); + } + + #[test] + fn persisting_the_posthog_choice_reports_a_failed_save() { + let tmp = tempfile::tempdir().unwrap(); + // A folder where the config file belongs can't be replaced by one. + std::fs::create_dir(tmp.path().join(CONFIG_FILE)).unwrap(); + let err = persist_posthog_choice(tmp.path(), false).unwrap_err(); + assert!( + err.starts_with("Couldn't save the product analytics setting: "), + "{err}" + ); + } + #[test] fn providers_round_trip_cloudflare_account_id() { let mut cfg = json!({}); @@ -396,6 +1623,34 @@ mod tests { assert!(ProvidersConfig::default().cloudflare_account_id.is_none()); } + #[test] + fn attribution_defaults_on() { + assert!(git_attribution_from(&json!({}))); + } + + #[test] + fn attribution_respects_false() { + assert!(!git_attribution_from(&json!({"gitAttribution": false}))); + } + + #[test] + fn attribution_ignores_non_boolean_values() { + assert!(git_attribution_from(&json!({"gitAttribution": "false"}))); + assert!(git_attribution_from(&json!({"gitAttribution": 0}))); + assert!(git_attribution_from(&json!({"gitAttribution": null}))); + } + + #[test] + fn attribution_opt_out_survives_save_and_reload() { + let tmp = tempfile::tempdir().unwrap(); + save_config_to( + tmp.path(), + &json!({"theme": "dark", "gitAttribution": false}), + ) + .unwrap(); + assert!(!git_attribution_from(&load_config_from(tmp.path()))); + } + #[test] fn providers_and_routing_coexist_in_same_config() { // Sanity check that the two sections don't clobber each other — diff --git a/src-tauri/src/shell/git.rs b/src-tauri/src/shell/git.rs index eec76e6..1d2341d 100644 --- a/src-tauri/src/shell/git.rs +++ b/src-tauri/src/shell/git.rs @@ -408,9 +408,11 @@ pub async fn get_context(folder: &Path) -> Value { json!(branch) }; + // The renderer gets this URL: without the credentials an origin remote + // can hold (`https://user:token@…`). let (rc_r, remote, _) = git(&["remote", "get-url", "origin"], folder).await; let remote_https = if rc_r == 0 { - Some(ssh_to_https(remote.trim())) + Some(without_credentials(&ssh_to_https(remote.trim()))) } else { None }; @@ -737,14 +739,29 @@ pub async fn diff_summary(folder: &Path, base: &str) -> Value { /// Browser target for "Open PR": the exact `/pull/` page when the /// caller knows the PR number, the repo's `/pulls` list as the last -/// resort (no PR exists yet, or resolution failed). +/// resort (no PR exists yet, or resolution failed). Built without the +/// credentials an origin remote can hold (`https://user:token@…`): the page +/// is opened in the browser and handed back to the renderer. fn pr_page_url(repo_url: &str, pr_number: Option) -> String { + let repo_url = without_credentials(repo_url); match pr_number { Some(n) => format!("{repo_url}/pull/{n}"), None => format!("{repo_url}/pulls"), } } +/// `url` without its username and password, when it has any. +fn without_credentials(url: &str) -> String { + match url::Url::parse(url) { + Ok(mut parsed) if !parsed.username().is_empty() || parsed.password().is_some() => { + let _ = parsed.set_username(""); + let _ = parsed.set_password(None); + parsed.to_string() + } + _ => url.to_string(), + } +} + pub async fn open_pr(folder: &Path, pr_number: Option) -> Value { let (rc, remote, _) = git(&["remote", "get-url", "origin"], folder).await; if rc != 0 { @@ -769,27 +786,49 @@ pub async fn open_pr(folder: &Path, pr_number: Option) -> Value { pr_page_url(&url, None) } }; - match ::open::that(&target) { - Ok(_) => json!({ "ok": true, "url": target }), + open_pr_page(target) +} + +/// Opens the PR page at `target` in the browser. It is built from the +/// repository's remote URL or from `gh` output, so the repository controls +/// it: `open_external` refuses anything but a clean web link. +fn open_pr_page(target: String) -> Value { + match fleetify_backend::open_external::open_url(&target) { + Ok(()) => json!({ "ok": true, "url": target }), Err(e) => json!({ "ok": false, "error": e.to_string() }), } } // ── Fleetify attribution helpers ───────────────────────────────── +// `enabled` is the user's Settings → General → Attribution choice (config +// key `gitAttribution`, on by default), read once per IPC command. When it is +// off, both helpers return the trimmed input unchanged. const FLEETIFY_CO_AUTHOR: &str = "Co-Authored-By: Fleetify "; const FLEETIFY_PR_FOOTER: &str = "\n\n---\nCreated with [Fleetify](https://fleetify.dev)"; -fn with_fleetify_trailer(message: &str) -> String { +/// True when `message` already has a `Co-Authored-By: Fleetify <…>` trailer, +/// matched case-insensitively on the key and name whatever the address, so a +/// commit never credits Fleetify twice. +fn has_fleetify_co_author(message: &str) -> bool { + message.lines().any(|line| { + line.trim_start() + .to_ascii_lowercase() + .strip_prefix("co-authored-by:") + .is_some_and(|rest| rest.trim_start().starts_with("fleetify <")) + }) +} + +fn with_fleetify_trailer(message: &str, enabled: bool) -> String { let trimmed = message.trim_end(); - if trimmed.contains("Fleetify ") { + if !enabled || has_fleetify_co_author(trimmed) { return trimmed.to_string(); } format!("{trimmed}\n\n{FLEETIFY_CO_AUTHOR}") } -fn with_fleetify_footer(body: &str) -> String { +fn with_fleetify_footer(body: &str, enabled: bool) -> String { let trimmed = body.trim_end(); - if trimmed.contains("fleetify.dev") || trimmed.contains("github.com/fleetifyai") { + if !enabled || trimmed.contains("fleetify.dev") || trimmed.contains("github.com/fleetifyai") { return trimmed.to_string(); } format!("{trimmed}{FLEETIFY_PR_FOOTER}") @@ -870,7 +909,9 @@ fn write_gitignore_if_missing(folder: &Path) -> bool { // `localStorage["fleet:github-auth-method"]` so the onboarding choice is // honoured exactly — picking "Use GitHub CLI" never silently routes // through OAuth, and vice versa. -// 8 args is one over the default 7; refactor to a struct is out of scope for this cleanup. +// `attribution` is the user's `gitAttribution` setting: whether the commits +// this flow makes (both paths) and the PR footer (gh path) credit Fleetify. +// 9 args is two over the default 7; refactor to a struct is out of scope for this cleanup. #[allow(clippy::too_many_arguments)] pub async fn create_pr( folder: &Path, @@ -881,6 +922,7 @@ pub async fn create_pr( feature_branch: Option<&str>, tool: Option<&str>, method: Option<&str>, + attribution: bool, ) -> Value { let want_gh = matches!(method, Some("gh") | Some("cli")); let want_oauth = matches!(method, Some("oauth") | Some("link")); @@ -914,7 +956,17 @@ pub async fn create_pr( }); } tracing::info!(target: "createPR", "dispatch-gh (requested)"); - return create_pr_via_gh(folder, title, body, base, draft, feature_branch, tool).await; + return create_pr_via_gh( + folder, + title, + body, + base, + draft, + feature_branch, + tool, + attribution, + ) + .await; } if want_oauth { let Some(token) = oauth_token else { @@ -925,7 +977,8 @@ pub async fn create_pr( }); }; tracing::info!(target: "createPR", "dispatch-link (requested)"); - let preflight = ensure_repo_for_link(folder, title, base, feature_branch, tool).await; + let preflight = + ensure_repo_for_link(folder, title, base, feature_branch, tool, attribution).await; if let Some(err) = preflight { return err; } @@ -943,11 +996,22 @@ pub async fn create_pr( // No preference — legacy gh-first then link fallback. if gh_authed { tracing::info!(target: "createPR", "dispatch-gh (fallback)"); - return create_pr_via_gh(folder, title, body, base, draft, feature_branch, tool).await; + return create_pr_via_gh( + folder, + title, + body, + base, + draft, + feature_branch, + tool, + attribution, + ) + .await; } if let Some(token) = oauth_token { tracing::info!(target: "createPR", "dispatch-link (fallback)"); - let preflight = ensure_repo_for_link(folder, title, base, feature_branch, tool).await; + let preflight = + ensure_repo_for_link(folder, title, base, feature_branch, tool, attribution).await; if let Some(err) = preflight { return err; } @@ -980,6 +1044,7 @@ async fn ensure_repo_for_link( base: Option<&str>, feature_branch: Option<&str>, tool: Option<&str>, + attribution: bool, ) -> Option { let _ = (title, base); if !folder.exists() { @@ -1084,7 +1149,7 @@ async fn ensure_repo_for_link( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1125,7 +1190,7 @@ async fn ensure_repo_for_link( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1192,7 +1257,7 @@ async fn ensure_repo_for_link( .and_then(|v| v.as_str()) .map(str::to_string) .unwrap_or_else(|| "Working session updates".to_string()); - let commit_msg = with_fleetify_trailer(&msg); + let commit_msg = with_fleetify_trailer(&msg, attribution); let (rc, _, err) = run( "git", &["commit", "-m", &commit_msg], @@ -1217,7 +1282,9 @@ async fn ensure_repo_for_link( /// PR-summary fallback when body is empty, and finally invokes /// `gh pr create`. Every step gets a trace line in the error message /// and a tracing breadcrumb so the user can diagnose without log -/// spelunking. +/// spelunking. `attribution` gates the Fleetify commit trailer and PR footer. +// 8 args is one over the default 7; refactor to a struct is out of scope for this cleanup. +#[allow(clippy::too_many_arguments)] pub async fn create_pr_via_gh( folder: &Path, title: &str, @@ -1226,6 +1293,7 @@ pub async fn create_pr_via_gh( draft: bool, feature_branch: Option<&str>, tool: Option<&str>, + attribution: bool, ) -> Value { const HANDLER_VERSION: &str = "rust-v1-2026-05-20"; if title.trim().is_empty() { @@ -1412,7 +1480,7 @@ pub async fn create_pr_via_gh( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1441,7 +1509,7 @@ pub async fn create_pr_via_gh( // static "Initial commit"). } else { let (_, _, _) = run("git", &["add", "-A"], folder, Duration::from_secs(120)).await; - let init_msg = with_fleetify_trailer("Initial commit"); + let init_msg = with_fleetify_trailer("Initial commit", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &init_msg], @@ -1499,7 +1567,7 @@ pub async fn create_pr_via_gh( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1608,7 +1676,7 @@ pub async fn create_pr_via_gh( _ => "Working session updates".to_string(), }; note("commit message", true, &msg); - let commit_msg = with_fleetify_trailer(&msg); + let commit_msg = with_fleetify_trailer(&msg, attribution); let (rc, _, err) = run( "git", &["commit", "-m", &commit_msg], @@ -1849,7 +1917,7 @@ pub async fn create_pr_via_gh( } } - let body_with_footer = with_fleetify_footer(&final_body); + let body_with_footer = with_fleetify_footer(&final_body, attribution); // 7. gh pr create. let mut args: Vec = vec![ @@ -2661,6 +2729,21 @@ fn ssh_to_https(url: &str) -> String { mod tests { use super::*; + #[test] + fn a_pr_page_a_remote_crafted_is_refused_not_opened() { + // A remote URL can carry a `"` into the host; on Windows the old + // opener handed it to `cmd`. Refused before anything is launched. + let crafted = r#"https://x"&calc.exe&"y.com/owner/repo/pull/1"#.to_string(); + let answer = open_pr_page(crafted); + assert_eq!(answer["ok"], false, "{answer}"); + assert!( + answer["error"] + .as_str() + .is_some_and(|error| error.contains("can't be opened")), + "{answer}" + ); + } + #[test] fn parse_actions_run_job_extracts_ids() { assert_eq!( @@ -2687,6 +2770,48 @@ mod tests { assert_eq!(parse_actions_run_job("garbage"), (None, None)); } + #[test] + fn trailer_added_when_enabled() { + assert_eq!( + with_fleetify_trailer("feat: x", true), + "feat: x\n\nCo-Authored-By: Fleetify " + ); + } + + #[test] + fn trailer_skipped_when_disabled() { + assert_eq!(with_fleetify_trailer("feat: x\n", false), "feat: x"); + } + + #[test] + fn trailer_not_duplicated_when_any_fleetify_coauthor_is_present() { + let m = "feat: x\n\nCo-authored-by: Fleetify "; + assert_eq!(with_fleetify_trailer(m, true), m); + } + + #[test] + fn trailer_dedupe_ignores_case_and_address() { + // Any existing Fleetify co-author line counts, whatever its casing or + // address, so a commit never ends up crediting Fleetify twice. + let lower = "feat: x\n\nco-authored-by: fleetify "; + assert_eq!(with_fleetify_trailer(lower, true), lower); + let other = "feat: x\n\nCo-Authored-By: Fleetify "; + assert_eq!(with_fleetify_trailer(other, true), other); + } + + #[test] + fn footer_skipped_when_disabled() { + assert_eq!(with_fleetify_footer("body", false), "body"); + } + + #[test] + fn footer_added_when_enabled() { + assert_eq!( + with_fleetify_footer("body\n", true), + "body\n\n---\nCreated with [Fleetify](https://fleetify.dev)" + ); + } + #[test] fn dedupe_ids_keeps_first_order() { assert_eq!(dedupe_ids(&[3, 1, 3, 2, 1]), vec![3, 1, 2]); @@ -3011,6 +3136,19 @@ mod tests { assert_eq!(parse_pr_number(""), None); } + #[test] + fn a_pr_page_carries_no_credentials_from_the_remote() { + // An origin remote can hold a token: https://user:token@github.com/… + assert_eq!( + pr_page_url("https://user:tok@github.com/foo/bar", Some(1)), + "https://github.com/foo/bar/pull/1" + ); + assert_eq!( + pr_page_url("https://tok@github.com/foo/bar", None), + "https://github.com/foo/bar/pulls" + ); + } + #[test] fn pr_page_url_targets_exact_pr_or_pulls_list() { assert_eq!( @@ -3052,6 +3190,22 @@ mod tests { assert!(v.get("error").is_none()); } + #[tokio::test] + async fn the_context_carries_no_credentials_from_the_remote() { + // The renderer gets remoteHttpsUrl: an origin remote like + // https://user:token@host/… must not hand it the token. + if !git_available() { + return; + } + let tmp = tempfile::tempdir().unwrap(); + fresh_repo(tmp.path()).await; + let remote = "https://user:tok@github.com/foo/bar.git"; + let (rc, _, err) = git(&["remote", "add", "origin", remote], tmp.path()).await; + assert_eq!(rc, 0, "git remote add: {err}"); + let v = get_context(tmp.path()).await; + assert_eq!(v["remoteHttpsUrl"], "https://github.com/foo/bar.git"); + } + #[test] fn behind_if_fast_forward_counts_only_when_pure_ff() { // "\t" from `rev-list --left-right --count base...origin/base`. @@ -3185,6 +3339,7 @@ mod tests { Some("main"), Some("fleet/x-ab12"), None, + true, ) .await; assert!(res.is_none(), "bootstrap should succeed: {res:?}"); @@ -3211,6 +3366,41 @@ mod tests { ); } + /// The link-path bootstrap commits honour the attribution setting: the + /// baseline commit credits Fleetify only while attribution is on. + #[tokio::test] + async fn link_bootstrap_trailer_follows_attribution_setting() { + if !git_available() { + return; + } + for attribution in [true, false] { + let tmp = tempfile::tempdir().unwrap(); + // Skip if an ancestor repo would mask our fresh-init state. + if fleetify_backend::services::worktree::is_git_repo(&tmp.path().to_string_lossy()) + .await + { + return; + } + let res = ensure_repo_for_link( + tmp.path(), + "My Feature", + Some("main"), + Some("fleet/x-ab12"), + None, + attribution, + ) + .await; + assert!(res.is_none(), "bootstrap should succeed: {res:?}"); + let (_, log, _) = git(&["log", "--all", "--format=%B"], tmp.path()).await; + assert_eq!( + log.to_ascii_lowercase() + .contains("co-authored-by: fleetify <"), + attribution, + "attribution={attribution}, commit messages: {log:?}" + ); + } + } + #[tokio::test] async fn ensure_repo_on_empty_dir_creates_repo() { if !git_available() { diff --git a/src-tauri/src/shell/github_link.rs b/src-tauri/src/shell/github_link.rs index 40ae1f6..c0121c8 100644 --- a/src-tauri/src/shell/github_link.rs +++ b/src-tauri/src/shell/github_link.rs @@ -309,7 +309,7 @@ pub async fn begin_oauth(app: AppHandle, mode: &str) -> Value { // 2. Open browser (clipboard fallback). We surface the URL via a // broadcast event so the dialog can show a copy-link toast. - let open_ok = ::open::that(&authorize_url).is_ok(); + let open_ok = browser_opened(&authorize_url); if !open_ok { tracing::warn!(target: LOG_TARGET, "begin_oauth: browser launch failed, falling back to clipboard"); let clip_ok = arboard::Clipboard::new() @@ -608,12 +608,19 @@ pub async fn open_installation() -> Value { .unwrap_or_else(|| "https://github.com/settings/installations".to_string()), None => "https://github.com/settings/installations".to_string(), }; - match ::open::that(&url) { - Ok(_) => json!({ "ok": true }), + match fleetify_backend::open_external::open_url(&url) { + Ok(()) => json!({ "ok": true }), Err(e) => json!({ "ok": false, "error": e.to_string() }), } } +/// Opens GitHub's authorize page in the browser. False when that failed, +/// or the URL the cloud sent is not a web link `open_external` accepts: +/// begin_oauth then copies it to the clipboard and shows it instead. +fn browser_opened(authorize_url: &str) -> bool { + fleetify_backend::open_external::open_url(authorize_url).is_ok() +} + /// Parse `gh api user/repos …` output (a raw GitHub REST repo array) into /// the renderer's `GhRepo` shape: map each element via `map_gh_repo`, dedupe /// by `nameWithOwner`, and sort newest-first. Returns an empty array on any @@ -886,6 +893,14 @@ fn urlencoding_minimal(s: &str) -> String { mod tests { use super::*; + #[test] + fn an_authorize_url_that_cant_be_opened_takes_the_clipboard_fallback() { + // Refused before anything is launched: no browser starts here. + for url in ["javascript:alert(1)", "https://x%22&calc.exe&%22y.com/", ""] { + assert!(!browser_opened(url), "{url:?}"); + } + } + #[test] fn urlencoding_matches_js_encodeuricomponent() { assert_eq!(urlencoding_minimal("abc-_.~"), "abc-_.~"); diff --git a/src-tauri/src/shell/ipc/mod.rs b/src-tauri/src/shell/ipc/mod.rs index b8535d2..382b74a 100644 --- a/src-tauri/src/shell/ipc/mod.rs +++ b/src-tauri/src/shell/ipc/mod.rs @@ -61,68 +61,180 @@ pub async fn config_get(app: tauri::AppHandle) -> serde_json::Value { } } +/// Replaces `fleet.config.json` with `config`. A failed save answers +/// `{ ok: false, error }`. #[tauri::command] pub async fn config_set(app: tauri::AppHandle, config: serde_json::Value) -> serde_json::Value { - if let Ok(dir) = app.path().app_data_dir() { - let _ = config::save_config_to(&dir, &config); + let saved = match app.path().app_data_dir() { + Ok(dir) => config::save_config_to(&dir, &config) + .map_err(|e| format!("Couldn't save Fleetify's settings: {e}")), + Err(e) => Err(format!("Couldn't find Fleetify's settings folder: {e}")), + }; + match saved { + Ok(()) => serde_json::json!({ "ok": true }), + Err(error) => { + tracing::warn!(error = %error, "settings not saved"); + serde_json::json!({ "ok": false, "error": error }) + } } - serde_json::json!({ "ok": true }) } -// ── PostHog telemetry config ────────────────────────────────────── -// Renderer fetches `{ distinct_id, posthog_enabled }` at boot to -// initialise posthog-js with the same device_id the Rust backend uses, -// so frontend + backend events flow to one PostHog person. Setter both -// persists the flag AND flips the backend's runtime gate live so the -// worker stops / starts without a restart. +// ── Telemetry config (PostHog + Fleetify cloud sync) ────────────── +// Renderer fetches `{ distinct_id, posthog_enabled, cloud_enabled }` at +// boot; `distinct_id` initialises posthog-js with the same device_id the +// Rust backend uses, so frontend + backend events flow to one PostHog +// person. Each setter both persists its flag AND flips the matching +// backend runtime gate live, so the PostHog worker / the cloud WS loop +// stops or starts without a restart. #[tauri::command] -pub async fn telemetry_get_config(app: tauri::AppHandle) -> serde_json::Value { - let posthog_enabled = match app.path().app_data_dir() { - Ok(dir) => config::telemetry_from(&config::load_config_from(&dir)).posthog_enabled, - Err(_) => false, - }; +pub async fn telemetry_get_config() -> serde_json::Value { let device = fleetify_backend::services::telemetry::device_id::get_or_create(); + telemetry_config_now(device.device_id) +} + +/// The two flags are the backend's live gates, not the saved choices. They +/// differ after a failed save (the gate still follows the switch for this +/// session), and the Settings card has to show what is actually on. The +/// shell sets both gates from the saved choices as soon as it starts +/// (lib.rs), before the warm-up, so the renderer's launch read sees them. +fn telemetry_config_now(distinct_id: String) -> serde_json::Value { serde_json::json!({ - "distinct_id": device.device_id, - "posthog_enabled": posthog_enabled, + "distinct_id": distinct_id, + "posthog_enabled": fleetify_backend::services::telemetry::posthog::is_enabled(), + "cloud_enabled": fleetify_backend::services::telemetry::cloud_enabled(), }) } +/// Whether Settings has set cloud sync since launch. The startup restore +/// (lib.rs) ends seconds after launch, after the warm-up, and must not undo +/// a choice the user made meanwhile, including one whose save failed. The +/// setter and the restore both hold this lock while they touch the gate, so +/// whichever runs second sees the other. +static CLOUD_SYNC_SET_SINCE_LAUNCH: tokio::sync::Mutex = tokio::sync::Mutex::const_new(false); + +/// Settings' change to the cloud gate: records that the user chose, then +/// applies it. +async fn set_cloud_sync(set_since_launch: &tokio::sync::Mutex, enabled: bool) { + let mut set = set_since_launch.lock().await; + *set = true; + fleetify_backend::services::telemetry::set_cloud_enabled(enabled).await; +} + +/// The end of the startup restore. It can only close the gate: when the +/// saved choice is off (closing also purges what is still queued), and only +/// if Settings hasn't set it since launch. It never opens the gate; the +/// early restore already opened it when the saved choice is on. +async fn finish_cloud_sync_restore_with( + set_since_launch: &tokio::sync::Mutex, + saved_on: bool, +) { + let set = set_since_launch.lock().await; + if !*set && !saved_on { + fleetify_backend::services::telemetry::set_cloud_enabled(false).await; + } +} + +pub(crate) async fn finish_cloud_sync_restore(saved_on: bool) { + finish_cloud_sync_restore_with(&CLOUD_SYNC_SET_SINCE_LAUNCH, saved_on).await; +} + +/// Settings → Privacy's Fleetify-cloud sync switch. Saves the choice +/// (`config::persist_cloud_choice`), then sets the backend gate: turning it +/// off purges anything still queued and drops the dashboard socket. +/// +/// The gate follows the switch for this session even when the save fails, +/// but the saved choice then still decides the next launch, so the failure +/// is reported: `{ ok: false, error }`. +#[tauri::command] +pub async fn telemetry_set_cloud_enabled( + app: tauri::AppHandle, + enabled: bool, +) -> serde_json::Value { + let saved = match app.path().app_data_dir() { + Ok(dir) => config::persist_cloud_choice(&dir, enabled), + Err(e) => Err(format!("Couldn't find Fleetify's settings folder: {e}")), + }; + if let Err(error) = &saved { + tracing::warn!( + error = %error, + enabled, + "cloud sync setting not saved; it applies until Fleetify restarts" + ); + } + set_cloud_sync(&CLOUD_SYNC_SET_SINCE_LAUNCH, enabled).await; + match saved { + Ok(()) => serde_json::json!({ "ok": true }), + Err(error) => serde_json::json!({ + "ok": false, + "error": format!("{error}. The change applies until Fleetify restarts."), + }), + } +} + +/// Settings → Privacy's product analytics (PostHog) switch. Saves the +/// choice (`config::persist_posthog_choice`), then flips the backend's +/// PostHog gate live. +/// +/// The gate follows the switch for this session even when the save fails, +/// but the saved choice then still decides the next launch, so the failure +/// is reported: `{ ok: false, error }`. #[tauri::command] pub async fn telemetry_set_posthog_enabled( app: tauri::AppHandle, enabled: bool, ) -> serde_json::Value { - if let Ok(dir) = app.path().app_data_dir() { - let mut cfg = config::load_config_from(&dir); - let mut telem = config::telemetry_from(&cfg); - let was_enabled = telem.posthog_enabled; - telem.posthog_enabled = enabled; - // Stamp the first opt-in time so funnels can split "fresh" - // consenters from long-standing users. Clearing the flag does - // NOT wipe the timestamp — useful for support if the user - // toggles off then back on. - if enabled && !was_enabled { - telem.posthog_enabled_at = Some( - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as i64) - .unwrap_or(0), - ); - } - config::telemetry_set(&mut cfg, &telem); - let _ = config::save_config_to(&dir, &cfg); + let saved = match app.path().app_data_dir() { + Ok(dir) => config::persist_posthog_choice(&dir, enabled), + Err(e) => Err(format!("Couldn't find Fleetify's settings folder: {e}")), + }; + if let Err(error) = &saved { + tracing::warn!( + error = %error, + enabled, + "product analytics setting not saved; it applies until Fleetify restarts" + ); } fleetify_backend::services::telemetry::posthog::set_enabled(enabled); - serde_json::json!({ "ok": true }) + match saved { + Ok(()) => serde_json::json!({ "ok": true }), + Err(error) => serde_json::json!({ + "ok": false, + "error": format!("{error}. The change applies until Fleetify restarts."), + }), + } } // ── shell ───────────────────────────────────────────────────────── +/// What the renderer is told for a link `shell_open_external` won't open: +/// anything but a web or email link (see `fleetify_backend::open_external`). +const LINK_REFUSED: &str = "This link can't be opened: only web and email links are supported."; + #[tauri::command] pub async fn shell_open_external(url: String) -> serde_json::Value { - match ::open::that(&url) { - Ok(_) => serde_json::json!({ "ok": true }), + use fleetify_backend::open_external::{open_url, OpenError}; + match open_url(&url) { + Ok(()) => serde_json::json!({ "ok": true }), + Err(OpenError::Rejected(_)) => serde_json::json!({ "ok": false, "error": LINK_REFUSED }), + Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), + } +} + +/// What the renderer is told for a path `shell_open_path` won't open. +const PATH_REFUSED: &str = "This file can't be opened from Fleetify."; + +/// Opens a local folder, or a document file, with the system's default +/// handler: Library → "Open raw file" and the "Open in" menu's "Open folder". +/// `open_external::open_ui_path` resolves the path and opens it only when it +/// is an existing folder, or a file with a document extension: on Windows, +/// ShellExecute runs executables, scripts and shortcuts. A Windows network +/// path is refused before anything looks at it. +#[tauri::command] +pub async fn shell_open_path(path: String) -> serde_json::Value { + use fleetify_backend::open_external::{open_ui_path, OpenPathError}; + match open_ui_path(std::path::Path::new(&path)) { + Ok(()) => serde_json::json!({ "ok": true }), + Err(OpenPathError::Refused(_)) => serde_json::json!({ "ok": false, "error": PATH_REFUSED }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), } } @@ -146,13 +258,22 @@ pub async fn shell_show_item_in_folder(path: String) -> serde_json::Value { // which Nautilus/Nemo/Dolphin/Caja all implement. Falls back to // `xdg-open ` (no selection) when the D-Bus service is // unavailable — better than failing entirely on a minimal WM. - let p = std::path::PathBuf::from(&path); - if !p.exists() { - return serde_json::json!({ - "ok": false, - "error": format!("path does not exist: {}", p.display()) - }); - } + // + // The path is checked and resolved first (`open_external::path_to_reveal`): + // a Windows network path is refused before anything looks at it, since + // even checking that it exists signs in to the host, and the file manager + // is handed the resolved path. + use fleetify_backend::open_external::{path_to_reveal, PathRefused}; + let p = match path_to_reveal(std::path::Path::new(&path)) { + Ok(resolved) => resolved, + Err(PathRefused::Unresolvable(_)) => { + return serde_json::json!({ + "ok": false, + "error": format!("path does not exist: {path}") + }); + } + Err(_) => return serde_json::json!({ "ok": false, "error": PATH_REFUSED }), + }; let result = reveal_in_file_manager(&p); match result { Ok(()) => serde_json::json!({ "ok": true }), @@ -207,16 +328,14 @@ fn reveal_in_file_manager(path: &std::path::Path) -> Result<(), String> { // erroring out on a box without a FileManager1 // implementation (sway+thunar<4.18, headless CI, etc.). let parent = path.parent().unwrap_or(path); - ::open::that(parent) - .map(|_| ()) + fleetify_backend::open_external::open_path(parent) .map_err(|e| format!("dbus-send unavailable and xdg-open fallback failed: {e}")) } } } #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] { - ::open::that(path.parent().unwrap_or(path)) - .map(|_| ()) + fleetify_backend::open_external::open_path(path.parent().unwrap_or(path)) .map_err(|e| e.to_string()) } } @@ -299,7 +418,7 @@ pub async fn clipboard_write(text: String) -> serde_json::Value { // panel reports its slot's logical rect; we position the child webview // there and keep it in sync on scroll / resize. Login state + a site's // remembered theme PERSIST across launches via a fixed profile id. -const BROWSER_EMBED_LABEL: &str = "browser-embed"; +pub(crate) const BROWSER_EMBED_LABEL: &str = "browser-embed"; const BROWSER_EMBED_PROFILE: [u8; 16] = *b"fleetbrowser0001"; // A CURRENT Safari UA so sites (Google) serve their MODERN layout instead of // the legacy fallback the bare WKWebView UA gets. Kept as Safari (NOT Chrome) @@ -1557,10 +1676,11 @@ pub async fn git_open_pr(folder: String, pr_number: Option) -> serde_json:: /// link only, omitted → legacy gh-first / link-fallback. Renderer /// pulls the value from `localStorage["fleet:github-auth-method"]` /// so the onboarding choice is honoured exactly. -// 8 args is one over the default 7; refactor to a struct is out of scope for this cleanup. +// 9 args is two over the default 7; refactor to a struct is out of scope for this cleanup. #[allow(clippy::too_many_arguments)] #[tauri::command] pub async fn git_create_pr( + app: tauri::AppHandle, folder: String, title: String, body: Option, @@ -1570,6 +1690,13 @@ pub async fn git_create_pr( tool: Option, method: Option, ) -> serde_json::Value { + // Settings → General → Attribution, read fresh for every PR so a change + // applies without a restart. No data dir → the default (on). + let attribution = app + .path() + .app_data_dir() + .map(|dir| config::git_attribution_from(&config::load_config_from(&dir))) + .unwrap_or(true); git::create_pr( &PathBuf::from(folder), &title, @@ -1579,6 +1706,7 @@ pub async fn git_create_pr( featureBranch.as_deref(), tool.as_deref(), method.as_deref(), + attribution, ) .await } @@ -2446,7 +2574,9 @@ fn strip_ansi(s: &str) -> String { // One-time device codes are formatted "XXXX-XXXX" — 4 alphanumerics, a // dash, then 4 more. gh prints them after "code:" so we anchor on that. fn parse_device_code(line: &str) -> Option { - let lower = line.to_lowercase(); + // ASCII-only lowercasing keeps every byte offset, so `pos` is valid in + // `line` too. Unicode lowercasing can change lengths (`İ` 2 → 3 bytes). + let lower = line.to_ascii_lowercase(); let pos = lower.find("code:")?; let rest = &line[pos + 5..]; let candidate: String = rest @@ -2739,7 +2869,7 @@ pub async fn shell_install_ollama() -> serde_json::Value { match res { Ok(o) if o.status.success() => serde_json::json!({ "ok": true }), _ => { - let _ = ::open::that(download_url); + let _ = fleetify_backend::open_external::open_url(download_url); serde_json::json!({ "ok": false, "error": "installer did not complete; opened ollama.com/download" @@ -3039,7 +3169,7 @@ pub fn logs_open_folder() -> serde_json::Value { // Reuse the same OS-correct opener `shell_show_item_in_folder` // uses for files: passing the directory reveals it. let path_str = log_dir.to_string_lossy().to_string(); - if let Err(e) = open::that(&path_str) { + if let Err(e) = fleetify_backend::open_external::open_path(log_dir) { return serde_json::json!({ "ok": false, "error": format!("open log folder: {e}") @@ -4531,6 +4661,63 @@ pub async fn providers_set_cloudflare_account_id( mod tests { use super::*; + #[tokio::test] + async fn a_path_that_isnt_a_folder_or_document_is_refused_with_a_message() { + // Refused before anything is launched: nothing opens here. + let dir = tempfile::tempdir().unwrap(); + let exe = dir.path().join("setup.exe"); + std::fs::write(&exe, b"").unwrap(); + for path in [ + exe.to_string_lossy().into_owned(), + dir.path().join("missing.md").to_string_lossy().into_owned(), + "notes.md".to_string(), + String::new(), + ] { + assert_eq!( + shell_open_path(path.clone()).await, + serde_json::json!({ "ok": false, "error": PATH_REFUSED }), + "{path:?}" + ); + } + } + + #[tokio::test] + async fn an_item_that_cant_be_shown_is_refused_before_the_file_manager_starts() { + // The path is checked and resolved first: nothing is revealed here. + // (A relative path is refused even when it exists: it would be + // resolved against the working directory.) + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.md").to_string_lossy().into_owned(); + assert_eq!( + shell_show_item_in_folder(missing.clone()).await, + serde_json::json!({ "ok": false, "error": format!("path does not exist: {missing}") }) + ); + for path in ["notes.md", ""] { + assert_eq!( + shell_show_item_in_folder(path.to_string()).await, + serde_json::json!({ "ok": false, "error": PATH_REFUSED }), + "{path:?}" + ); + } + } + + #[tokio::test] + async fn a_link_that_isnt_web_or_mail_is_refused_with_a_message() { + // Refused before anything is launched: no browser starts here. + for url in [ + "javascript:alert(1)", + "file:///C:/Windows/System32/calc.exe", + "https://x%22&calc.exe&%22y.com/", + "", + ] { + assert_eq!( + shell_open_external(url.to_string()).await, + serde_json::json!({ "ok": false, "error": LINK_REFUSED }), + "{url:?}" + ); + } + } + #[test] fn ollama_auth_header_only_when_key_present() { assert_eq!( @@ -4698,6 +4885,42 @@ mod tests { let v4 = scaffold_plugin_impl(&parent, "other-plugin", &bad); assert!(v4["error"].as_str().unwrap().contains("unsafe path")); } + + #[test] + fn parse_device_code_reads_the_gh_prompt() { + assert_eq!( + parse_device_code("! First copy your one-time code: ABCD-1234"), + Some("ABCD-1234".to_string()) + ); + assert_eq!( + parse_device_code("code: abcd-1234"), + Some("ABCD-1234".to_string()) + ); + assert_eq!( + parse_device_code("Press Enter to open github.com in your browser..."), + None + ); + assert_eq!(parse_device_code("code: ABCD1234"), None); + } + + /// Regression: the offset of `code:` came from a Unicode-lowercased copy + /// of the line. `İ` lowercases from 2 bytes to 3, so the slice of the + /// original line started 5 bytes too far and missed the code. + #[test] + fn parse_device_code_after_non_ascii_text() { + assert_eq!( + parse_device_code("İİİİİ code: ABCD-1234"), + Some("ABCD-1234".to_string()) + ); + } + + /// The same stale offset could land inside a letter or past the end of + /// the line, and the panic failed the whole sign-in. + #[test] + fn parse_device_code_does_not_panic_after_non_ascii_text() { + assert_eq!(parse_device_code("İİ code: İİİİ"), None); + assert_eq!(parse_device_code("İİİİİİİİİİ code:"), None); + } } #[cfg(test)] @@ -4732,3 +4955,103 @@ mod editor_tests { assert_eq!(r["ok"], false); } } + +#[cfg(test)] +mod telemetry_config_tests { + use super::*; + use fleetify_backend::services::telemetry::{cloud_enabled, posthog, set_cloud_enabled}; + + use tauri::async_runtime::block_on; + + /// The gates are process-wide, so the tests that flip them take turns. + static GATES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// Puts both gates back as they were, also when the test fails. + struct RestoreGates { + posthog: bool, + cloud: bool, + } + + impl RestoreGates { + fn now() -> Self { + Self { + posthog: posthog::is_enabled(), + cloud: cloud_enabled(), + } + } + } + + impl Drop for RestoreGates { + fn drop(&mut self) { + posthog::set_enabled(self.posthog); + block_on(set_cloud_enabled(self.cloud)); + } + } + + #[test] + fn telemetry_config_reports_the_live_gates() { + let _turn = GATES.lock().unwrap_or_else(|e| e.into_inner()); + let _restore = RestoreGates::now(); + + // After a failed save the gates differ from the saved choices, and a + // re-mounted Settings card has to show the gates. + posthog::set_enabled(true); + block_on(set_cloud_enabled(false)); + assert_eq!( + telemetry_config_now("device-1".into()), + serde_json::json!({ + "distinct_id": "device-1", + "posthog_enabled": true, + "cloud_enabled": false, + }) + ); + + posthog::set_enabled(false); + block_on(set_cloud_enabled(true)); + assert_eq!( + telemetry_config_now("device-1".into()), + serde_json::json!({ + "distinct_id": "device-1", + "posthog_enabled": false, + "cloud_enabled": true, + }) + ); + } + #[test] + fn startup_restore_closes_sync_when_the_saved_choice_is_off() { + let _turn = GATES.lock().unwrap_or_else(|e| e.into_inner()); + let _restore = RestoreGates::now(); + let set_since_launch = tokio::sync::Mutex::new(false); + block_on(set_cloud_enabled(true)); + block_on(finish_cloud_sync_restore_with(&set_since_launch, false)); + assert!(!cloud_enabled()); + } + + #[test] + fn startup_restore_never_opens_sync() { + // The early restore opens the gate when the saved choice is on; the + // late one only ever closes it. + let _turn = GATES.lock().unwrap_or_else(|e| e.into_inner()); + let _restore = RestoreGates::now(); + let set_since_launch = tokio::sync::Mutex::new(false); + block_on(set_cloud_enabled(false)); + block_on(finish_cloud_sync_restore_with(&set_since_launch, true)); + assert!(!cloud_enabled()); + } + + #[test] + fn startup_restore_keeps_a_choice_made_in_settings_since_launch() { + // The save failed, so the saved choice still says the opposite of + // what the user picked this session. The restore must not undo it. + let _turn = GATES.lock().unwrap_or_else(|e| e.into_inner()); + let _restore = RestoreGates::now(); + let set_since_launch = tokio::sync::Mutex::new(false); + block_on(set_cloud_sync(&set_since_launch, true)); + block_on(finish_cloud_sync_restore_with(&set_since_launch, false)); + assert!(cloud_enabled(), "a turned-on gate stays on"); + + block_on(set_cloud_sync(&set_since_launch, false)); + block_on(finish_cloud_sync_restore_with(&set_since_launch, true)); + assert!(!cloud_enabled(), "a turned-off gate stays off"); + } +} diff --git a/src-tauri/src/shell/migration.rs b/src-tauri/src/shell/migration.rs index 758aaab..24cb797 100644 --- a/src-tauri/src/shell/migration.rs +++ b/src-tauri/src/shell/migration.rs @@ -145,11 +145,10 @@ pub async fn migrate_api_keys_to_keychain(app: &tauri::AppHandle) { // Hydrate the backend key cache so the freshly-migrated keys are // usable on the very next chat turn, not after the next restart. - // Race-tolerant: providers_setup::reload_backend logs + skips when - // the backend's not listening yet, which happens during the - // startup window between serve() spawning and the listener - // binding. The reload that fires on the first Settings mutation - // (or the next reload trigger) will catch up. + // Race-tolerant: providers_setup::reload_backend sends nothing until + // the app's backend has reported its bind. When this runs first, the + // boot warm-up after the bind reads the keychain, migrated keys + // included; the next reload trigger catches anything later. crate::shell::providers_setup::reload_backend(app).await; } diff --git a/src-tauri/src/shell/mod.rs b/src-tauri/src/shell/mod.rs index 972eaa6..0fccc55 100644 --- a/src-tauri/src/shell/mod.rs +++ b/src-tauri/src/shell/mod.rs @@ -4,6 +4,7 @@ pub mod ai_git; pub mod auth; +pub mod backend_ready; pub mod bearer; pub mod config; pub mod feedback; @@ -21,4 +22,6 @@ pub mod providers_setup; pub mod pty; pub mod routers_link; pub mod routing_setup; +pub mod startup_window; +pub mod ui_files; pub mod voice; diff --git a/src-tauri/src/shell/providers_setup.rs b/src-tauri/src/shell/providers_setup.rs index 19d82c1..c303e83 100644 --- a/src-tauri/src/shell/providers_setup.rs +++ b/src-tauri/src/shell/providers_setup.rs @@ -9,16 +9,27 @@ //! Fire-and-forget: failures land in tracing, never propagate to the //! IPC caller. Config + keychain are the source of truth regardless, so //! the next boot will rebuild the cache cleanly even if this fails. +//! +//! Keys go only to the app's own backend, once it has reported its bind +//! (`backend_ready::bound_port`): until then nothing is sent, not even the +//! request for its account list, whose answer decides which keychain +//! entries go out. use std::collections::HashMap; use serde_json::json; use tauri::Manager; -use crate::shell::{auth, config, providers_link}; +use crate::shell::{auth, backend_ready, config, providers_link}; pub async fn reload_backend(app: &tauri::AppHandle) { - let port = std::env::var("FLEETIFY_BACKEND_PORT").unwrap_or_else(|_| "8765".into()); + let Some(port) = backend_ready::bound_port() else { + tracing::warn!( + target: "fleet-shell", + "providers reload: the app's backend hasn't reported its bind; not sending keys" + ); + return; + }; let secret = match std::env::var("FLEETIFY_INTERNAL_SECRET") { Ok(s) => s, Err(_) => { @@ -68,18 +79,29 @@ pub async fn reload_backend(app: &tauri::AppHandle) { } } - let client = reqwest::Client::builder() + // Never through a proxy: these are the keys (fleetify_core::loopback). + let client = match fleetify_core::loopback::http_client_builder() .timeout(std::time::Duration::from_secs(5)) .build() - .unwrap_or_default(); + { + Ok(client) => client, + Err(e) => { + tracing::warn!( + target: "fleet-shell", + error = %e, + "providers reload: couldn't build the HTTP client; not sending keys" + ); + return; + } + }; // Multi-account: enumerate HTTP provider accounts from the backend, read // each labeled key from the keychain, and push them as `account_keys` // alongside the legacy System keys above. CLI agents need nothing here — // their isolation is a HOME override resolved from the DB at dispatch. - let account_keys = build_account_keys(&client, &port, &secret).await; + let account_keys = build_account_keys(&client, port, &secret).await; - let url = format!("http://127.0.0.1:{port}/api/internal/providers/reload"); + let url = backend_ready::backend_url(port, "/api/internal/providers/reload"); let payload = json!({ "keys": keys, "cloudflare_account_id": cloudflare_account_id, @@ -124,10 +146,10 @@ pub async fn reload_backend(app: &tauri::AppHandle) { /// System keys still load. async fn build_account_keys( client: &reqwest::Client, - port: &str, + port: u16, secret: &str, ) -> Vec { - let url = format!("http://127.0.0.1:{port}/api/internal/accounts/http"); + let url = backend_ready::backend_url(port, "/api/internal/accounts/http"); let resp = match client .get(&url) .header("X-Fleet-Internal", secret) @@ -174,17 +196,25 @@ async fn build_account_keys( /// HttpHealthCache so the first chat turn doesn't see a "No API key" /// error and Settings → Models doesn't flash a "Testing…" state. /// -/// Fire-and-forget. If the backend isn't listening yet, the inner -/// HTTP calls fail and log — the next user-driven IPC will rerun -/// reload_backend, and the user can hit Test in Settings to refresh -/// health manually. No retry loop: the boot path stays simple. +/// Fire-and-forget. lib.rs runs it only once the backend has reported its +/// bind and answered its health route; without that it sends nothing +/// (`backend_ready::bound_port`). The next user-driven IPC reruns +/// reload_backend, and the user can hit Test in Settings to refresh health +/// manually. No retry loop: the boot path stays simple. pub async fn warm_providers_at_boot(app: &tauri::AppHandle) { + let Some(port) = backend_ready::bound_port() else { + tracing::warn!( + target: "fleet-shell", + "warm-health: the app's backend hasn't reported its bind; not sending anything" + ); + return; + }; + // 1) hydrate PROVIDER_KEYS from the keychain. reload_backend(app).await; // 2) hit /api/internal/providers/warm-health to fan-out health // probes against every keyed provider. - let port = std::env::var("FLEETIFY_BACKEND_PORT").unwrap_or_else(|_| "8765".into()); let secret = match std::env::var("FLEETIFY_INTERNAL_SECRET") { Ok(s) => s, Err(_) => { @@ -195,11 +225,21 @@ pub async fn warm_providers_at_boot(app: &tauri::AppHandle) { return; } }; - let url = format!("http://127.0.0.1:{port}/api/internal/providers/warm-health"); - let client = reqwest::Client::builder() + let url = backend_ready::backend_url(port, "/api/internal/providers/warm-health"); + let client = match fleetify_core::loopback::http_client_builder() .timeout(std::time::Duration::from_secs(15)) .build() - .unwrap_or_default(); + { + Ok(client) => client, + Err(e) => { + tracing::warn!( + target: "fleet-shell", + error = %e, + "warm-health: couldn't build the HTTP client (next manual Test will refresh)" + ); + return; + } + }; match client .post(&url) .header("X-Fleet-Internal", &secret) diff --git a/src-tauri/src/shell/routing_setup.rs b/src-tauri/src/shell/routing_setup.rs index 2e200ed..cd2d525 100644 --- a/src-tauri/src/shell/routing_setup.rs +++ b/src-tauri/src/shell/routing_setup.rs @@ -97,10 +97,20 @@ pub fn build(app_data_dir: &Path, user_id: Option<&str>) -> RoutingSetup { /// Fire-and-forget: failures are logged but never propagated to the IPC /// caller. The config + keychain are already updated regardless, so the /// next backend boot will pick up the change even if this round-trip -/// fails (e.g. backend not yet listening, transient I/O hiccup). +/// fails (e.g. a transient I/O hiccup). +/// +/// The router keys go only to the app's own backend, once it has reported +/// its bind (`backend_ready::bound_port`); before that nothing is sent. pub async fn reload_backend(app: &tauri::AppHandle) { use tauri::Manager; + let Some(port) = crate::shell::backend_ready::bound_port() else { + tracing::warn!( + target: "fleet-shell", + "routing reload: the app's backend hasn't reported its bind; not sending keys" + ); + return; + }; let Ok(dir) = app.path().app_data_dir() else { tracing::warn!(target: "fleet-shell", "routing reload: app_data_dir unavailable"); return; @@ -108,7 +118,6 @@ pub async fn reload_backend(app: &tauri::AppHandle) { let uid = crate::shell::auth::get_user_id().await; let setup = build(&dir, uid.as_deref()); - let port = std::env::var("FLEETIFY_BACKEND_PORT").unwrap_or_else(|_| "8765".into()); let secret = match std::env::var("FLEETIFY_INTERNAL_SECRET") { Ok(s) => s, Err(_) => { @@ -119,12 +128,23 @@ pub async fn reload_backend(app: &tauri::AppHandle) { return; } }; - let url = format!("http://127.0.0.1:{port}/api/internal/routing/reload"); + let url = crate::shell::backend_ready::backend_url(port, "/api/internal/routing/reload"); - let client = reqwest::Client::builder() + // Never through a proxy: these are the router keys (fleetify_core::loopback). + let client = match fleetify_core::loopback::http_client_builder() .timeout(std::time::Duration::from_secs(5)) .build() - .unwrap_or_default(); + { + Ok(client) => client, + Err(e) => { + tracing::warn!( + target: "fleet-shell", + error = %e, + "routing reload: couldn't build the HTTP client; not sending keys" + ); + return; + } + }; match client .post(&url) .header("X-Fleet-Internal", &secret) diff --git a/src-tauri/src/shell/startup_window.rs b/src-tauri/src/shell/startup_window.rs new file mode 100644 index 0000000..b962355 --- /dev/null +++ b/src-tauri/src/shell/startup_window.rs @@ -0,0 +1,1685 @@ +//! The main window at startup: what it shows before the app can load, and +//! when it loads the app and shows itself. +//! +//! The window used to load the app's URL the moment it was built. When the +//! embedded backend was not listening yet, the engine showed its error page +//! ("Could not connect to 127.0.0.1: Connection refused") and never retried, +//! so a slow start left a dead window. Now the window starts, hidden, on a +//! placeholder page that Tauri serves itself (scheme [`PLACEHOLDER_SCHEME`]). +//! It loads the app once the embedded backend has reported its bind and the +//! app's URL answers, and is shown when the app page has finished loading. If +//! the app is not ready within [`SLOW_START`], the window is shown with the +//! placeholder, "Starting Fleetify…", and the app loads as soon as it can. If +//! the backend can't start at all, or a release build has no UI files to +//! serve (see `shell::ui_files`), an error dialog says why and the app quits. +//! +//! It also works out the app's origin ([`app_origin`]) and, when that origin +//! is remote, the capability that grants it IPC at setup +//! ([`runtime_remote_origin`], [`runtime_capability`]). +//! `capabilities/default.json` covers local origins only, so the app's own +//! origin is the one remote origin that can call anything. + +use std::any::Any; +use std::panic::AssertUnwindSafe; +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use tauri::http::{header, Response, StatusCode}; +use tauri::ipc::CapabilityBuilder; +use tauri::utils::config::FrontendDist; +use tauri::webview::{PageLoadEvent, PageLoadPayload}; +use tauri::{Manager, Url, WebviewWindow}; +use tauri_plugin_dialog::{DialogExt, MessageDialogKind}; +use tokio::sync::{watch, Notify}; + +use crate::shell::backend_ready::{BackendStart, StartFailure}; +use crate::shell::ui_files::UiDirError; + +/// Label of the main window. +pub const MAIN_WINDOW: &str = "main"; + +/// Label of the main window's webview: a webview window's webview takes the +/// window's label (`WebviewWindowBuilder::new`). The browser panel is another +/// webview in the same window, with a label of its own. +pub const MAIN_WEBVIEW: &str = MAIN_WINDOW; + +/// The custom URI scheme the placeholder page is served on. Tauri registers +/// a scheme for every webview; only the main window is served the page. +pub const PLACEHOLDER_SCHEME: &str = "fleetify-startup"; + +/// The placeholder page's URL. Windows has no custom schemes: wry loads this +/// first URL as `http://fleetify-startup.localhost/` there. +pub const PLACEHOLDER_URL: &str = "fleetify-startup://localhost/"; + +/// How long the app may take to answer before the window is shown with the +/// placeholder. It is the cap the old reveal waited before showing the +/// window regardless. +pub const SLOW_START: Duration = Duration::from_secs(15); + +/// How long the window waits for the app page to finish loading before it is +/// shown anyway, so a missed page-load event can never leave it hidden. +pub const PAGE_LOAD_FALLBACK: Duration = Duration::from_secs(5); + +/// How often the app's URL is polled. +const POLL_INTERVAL: Duration = Duration::from_millis(150); + +/// How long one poll may take: bounds a port that accepts and never answers. +const POLL_TIMEOUT: Duration = Duration::from_millis(500); + +/// Pause between the app page loading and the window showing, so the first +/// React frame paints before the window appears. +const PAINT_GRACE: Duration = Duration::from_millis(120); + +/// The page the main window shows until the app loads. It loads nothing: +/// inline styles only, colours from the system scheme (the app's own light +/// theme and its default dark theme, from `src/globals.css`). +pub const PLACEHOLDER_HTML: &str = r#" + + + + +Fleetify + + + +

Starting Fleetify…

+ + +"#; + +/// The placeholder's Content-Security-Policy: its inline styles and nothing +/// else, so the engine itself refuses any resource. +const PLACEHOLDER_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'"; + +/// The placeholder scheme's answer to a request from `webview_label`: the +/// page for the main window, an empty 404 for any other webview (the +/// embedded browser panel included). +pub fn placeholder_response(webview_label: &str) -> Response> { + let response = if webview_label == MAIN_WINDOW { + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .header(header::CONTENT_SECURITY_POLICY, PLACEHOLDER_CSP) + .body(PLACEHOLDER_HTML.as_bytes().to_vec()) + } else { + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Vec::new()) + }; + // Only fixed, valid status codes and headers go in above. + response.unwrap_or_else(|_| Response::new(Vec::new())) +} + +/// True when `page` is a page of the app at `app_url`: same origin. The +/// placeholder never is (it has its own scheme, or its own host on Windows). +pub fn is_app_page(page: &Url, app_url: &Url) -> bool { + page.origin() == app_url.origin() +} + +/// Tells a finished load of the app from the engine's other load events. +/// +/// Only a `Finished` for an app page that follows a `Started` for one counts. +/// WebKitGTK reports a cancelled navigation as load-failed and then +/// `Finished`, with the URL already the app's but no `Started` (Committed): +/// that one must not show a window the app hasn't painted. wry reports +/// `Started` at commit on every engine (WebKitGTK Committed, WebView2 +/// ContentLoading, WKWebView didCommitNavigation). +#[derive(Debug, Default)] +pub struct AppLoadGuard { + /// Whether the load in progress began with a `Started` for an app page. + app_load_started: AtomicBool, +} + +impl AppLoadGuard { + /// Takes one page-load event, for an app page or not. True when it + /// finishes a load of the app that began with a `Started` for it. Each + /// `Finished` ends the load in progress, so the next one needs a new + /// `Started`. + pub fn finished_app_load(&self, event: PageLoadEvent, app_page: bool) -> bool { + match event { + PageLoadEvent::Started => { + self.app_load_started.store(app_page, Ordering::SeqCst); + false + } + PageLoadEvent::Finished => { + let started = self.app_load_started.swap(false, Ordering::SeqCst); + app_page && started + } + } + } +} + +/// A page-load handler for the main window: signals `app_page_loaded` each +/// time a page of the app at `app_url` finishes loading, as +/// [`AppLoadGuard`] tells it. A signal sent before anyone waits is kept, so +/// an early load is never missed. +pub fn signal_app_page_loaded( + app_url: Url, + app_page_loaded: Arc, +) -> impl Fn(WebviewWindow, PageLoadPayload<'_>) + Send + Sync + 'static { + let guard = AppLoadGuard::default(); + move |_window, payload| { + if guard.finished_app_load(payload.event(), is_app_page(payload.url(), &app_url)) { + app_page_loaded.notify_one(); + } + } +} + +/// The backend's start as the startup task sees it: `reported` is the last +/// report, and `reporter_gone` says its task has ended. A task that ended +/// without a report (it panicked) counts as failed, or the wait would never +/// end. +pub fn backend_start_seen(reported: &BackendStart, reporter_gone: bool) -> BackendStart { + match reported { + BackendStart::Pending if reporter_gone => BackendStart::Failed(StartFailure::Backend( + "its startup task stopped before it reported".to_string(), + )), + other => other.clone(), + } +} + +/// The two reads the startup task makes of the backend's start reports. +trait StartReports { + /// Whether the reporting task has ended. + fn reporter_gone(&self) -> bool; + /// The last report. + fn last_report(&self) -> BackendStart; +} + +impl StartReports for watch::Receiver { + fn reporter_gone(&self) -> bool { + self.has_changed().is_err() + } + + fn last_report(&self) -> BackendStart { + self.borrow().clone() + } +} + +/// The backend's start now, from `reports`: whether the reporter is gone, +/// read first, then its last report. The other order could read a pending +/// report, then find the task gone because it reported its bind and ended in +/// between: a false "can't start". Read this way, a reporter seen gone has +/// sent all it ever will, so the report read after is final. +fn observe_start(reports: &impl StartReports) -> BackendStart { + let gone = reports.reporter_gone(); + let last = reports.last_report(); + backend_start_seen(&last, gone) +} + +/// Title of the dialog shown when the backend can't start. +pub const BACKEND_FAILURE_TITLE: &str = "Fleetify can't start"; + +/// The text of that dialog: what failed (`error`, with its causes), on which +/// port, and where the log files are: `logs_dir`, from +/// `shell::logging::logs_dir()`, when that folder exists; otherwise it says +/// the logs could not be written. +pub fn backend_failure_message(error: &str, port: u16, logs_dir: Option<&Path>) -> String { + let logs = logs_line(logs_dir); + format!("Fleetify couldn't start its local server on port {port}:\n\n{error}\n\n{logs}") +} + +/// The text of that dialog when a release build has no UI files to serve +/// (`missing`, from `shell::ui_files`): reinstall, where it looked for them, +/// and where the log files are, as [`backend_failure_message`] says it. +pub fn ui_files_missing_message(missing: &UiDirError, logs_dir: Option<&Path>) -> String { + let looked = match missing { + UiDirError::NoIndexHtml(dir) => format!("Fleetify looked for them in {}", dir.display()), + UiDirError::NoResourceDir(error) => { + format!("Fleetify couldn't find its install folder: {error}") + } + }; + let logs = logs_line(logs_dir); + format!( + "Fleetify's interface files are missing. Please reinstall Fleetify.\n\n{looked}\n\n{logs}" + ) +} + +/// The text of the dialog for a start that failed: the backend's error +/// ([`backend_failure_message`]), no UI files to serve +/// ([`ui_files_missing_message`]), or no IPC permissions for the window's +/// app origin ([`permissions_failure_message`]). +pub fn start_failure_message(failure: &StartFailure, port: u16, logs_dir: Option<&Path>) -> String { + match failure { + StartFailure::Backend(error) => backend_failure_message(error, port, logs_dir), + StartFailure::UiFilesMissing(missing) => ui_files_missing_message(missing, logs_dir), + StartFailure::Permissions(error) => permissions_failure_message(error, logs_dir), + } +} + +/// The text of that dialog when the window's app origin couldn't get its +/// IPC permissions (`error`, from [`grant_app_origin`]): what went wrong, and +/// where the log files are, as [`backend_failure_message`] says it. +pub fn permissions_failure_message(error: &str, logs_dir: Option<&Path>) -> String { + let logs = logs_line(logs_dir); + format!("Fleetify couldn't give its interface the permissions it needs:\n\n{error}\n\n{logs}") +} + +/// The dialogs' last line: where the log files are (`logs_dir`, from +/// `shell::logging::logs_dir()`) when that folder exists, otherwise that +/// they could not be written. +fn logs_line(logs_dir: Option<&Path>) -> String { + // logging::init records its folder even when creating it failed: name it + // only when it is there. + match logs_dir.filter(|dir| dir.is_dir()) { + Some(dir) => format!("The log files are in {}", dir.display()), + None => "Fleetify could not write its log files.".to_string(), + } +} + +/// What the startup task does after one poll of the app's URL. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Step { + /// The backend is bound and the app answered: load it in the window. + LoadApp, + /// The app is slow to answer: show the window with the placeholder. + ShowPlaceholder, + /// The backend can't start: stop polling and say so. + ReportFailure, + /// Poll again. + KeepWaiting, +} + +/// The next step after one poll: the backend's start, whether the app +/// answered, how long the task has waited, and whether the placeholder is on +/// screen already. +/// +/// The app loads only once the backend has reported its bind *and* the app +/// answers: before the bind, an answer comes from something else on the port. +/// A backend that failed to start ends the wait. Otherwise polling has no +/// cap: past [`SLOW_START`] the placeholder goes up once, and the app still +/// loads the moment it can. +pub fn next_step( + backend: &BackendStart, + app_answered: bool, + waited: Duration, + placeholder_shown: bool, +) -> Step { + match backend { + BackendStart::Failed(_) => Step::ReportFailure, + BackendStart::Bound if app_answered => Step::LoadApp, + _ if waited >= SLOW_START && !placeholder_shown => Step::ShowPlaceholder, + _ => Step::KeepWaiting, + } +} + +/// Loads the app in `window` once the embedded backend has bound and +/// `app_url` answers, then shows the window. +/// +/// The window was built hidden on the placeholder page. `backend` carries the +/// backend task's report (see [`BackendStart`]); `app_url` is polled only +/// once it reports the bind, and any HTTP answer counts then, as before: even +/// a 404 lets the renderer show the failure. The window then loads the app +/// and is shown when the app page has finished loading (`app_page_loaded`, +/// from [`signal_app_page_loaded`]), or after [`PAGE_LOAD_FALLBACK`]. Past +/// [`SLOW_START`] it is shown with the placeholder, and the app loads once it +/// can. If the backend can't start, or has no UI files to serve, polling +/// stops and an error dialog says so; the app quits when it is dismissed. +/// +/// The poll never goes through a proxy (`fleetify_core::loopback`): a proxy +/// in the environment that isn't running would otherwise keep the window on +/// the placeholder for good. +pub async fn load_app_when_ready( + window: WebviewWindow, + app_url: Url, + app_page_loaded: Arc, + backend: watch::Receiver, + backend_port: u16, + boot_start: Instant, +) { + let client = fleetify_core::loopback::http_client_builder() + .timeout(POLL_TIMEOUT) + .build() + .inspect_err(|e| { + tracing::error!( + target: "fleetify::startup", + "can't build the HTTP client that polls {app_url} ({e}); \ + loading the app once the backend reports its bind" + ); + }) + .ok(); + let started = Instant::now(); + let mut placeholder_shown = false; + loop { + // observe_start clones the report at once: a watch borrow must not + // be held across an await. + let start = observe_start(&backend); + let answered = start == BackendStart::Bound && app_answers(client.as_ref(), &app_url).await; + match next_step(&start, answered, started.elapsed(), placeholder_shown) { + Step::LoadApp => break, + Step::ReportFailure => { + // No "Starting Fleetify…" behind the error: the start is over. + // The dialog has no parent, so it shows without the window. + if let Err(e) = window.hide() { + tracing::warn!("hide main window failed: {e}"); + } + if let BackendStart::Failed(failure) = &start { + report_start_failure(&window, failure, backend_port); + } + return; + } + Step::ShowPlaceholder => { + tracing::warn!( + target: "fleetify::startup", + waited_ms = started.elapsed().as_millis() as u64, + backend_bound = start == BackendStart::Bound, + "the app is not ready at {app_url} yet; showing the startup placeholder" + ); + reveal(&window, boot_start); + placeholder_shown = true; + } + Step::KeepWaiting => {} + } + tokio::time::sleep(POLL_INTERVAL).await; + } + + if let Err(e) = window.navigate(app_url.clone()) { + tracing::warn!("loading {app_url} in the main window failed: {e}"); + } + if placeholder_shown { + tracing::info!( + target: "fleetify::startup", + app_ready_ms = boot_start.elapsed().as_millis() as u64, + "{app_url} answered after a slow start; loading the app" + ); + return; + } + if tokio::time::timeout(PAGE_LOAD_FALLBACK, app_page_loaded.notified()) + .await + .is_err() + { + tracing::warn!( + target: "fleetify::startup", + "the app page did not report loading; showing the main window anyway" + ); + } + tokio::time::sleep(PAINT_GRACE).await; + reveal(&window, boot_start); +} + +/// Whether `app_url` gives any HTTP answer, asked with `client`. Without a +/// client (one that can't be built, which only a TLS backend that can't start +/// causes) nothing can be asked, and the backend's bind has to do. +async fn app_answers(client: Option<&reqwest::Client>, app_url: &Url) -> bool { + match client { + Some(client) => client.get(app_url.as_str()).send().await.is_ok(), + None => true, + } +} + +/// Says the backend can't start, that there are no UI files to serve, or +/// that the interface couldn't get its permissions, then quits: a native +/// error dialog with the text from [`start_failure_message`], and the app +/// exits once it is dismissed. +/// Without the backend the app can't work, and a placeholder that never ends +/// would hide why. +/// +/// The quit is a handled one, so it marks the shutdown clean: exiting skips +/// the main window's `Destroyed` event, which otherwise does, and the next +/// launch would report a crash. Tauri 2.11.2's wry runtime ends the event +/// loop with `ControlFlow::Exit` whatever code `exit` gets, so the process +/// status is 0 even though 1 is asked for. +fn report_start_failure(window: &WebviewWindow, failure: &StartFailure, port: u16) { + let what = match failure { + StartFailure::Backend(_) => "the embedded backend can't start", + StartFailure::UiFilesMissing(_) => "the UI files are missing", + StartFailure::Permissions(_) => "the interface couldn't get its permissions", + }; + tracing::error!( + target: "fleetify::startup", + port, + "{what}; showing the error, then quitting" + ); + let app = window.app_handle().clone(); + let on_dismiss = app.clone(); + app.dialog() + .message(start_failure_message( + failure, + port, + crate::shell::logging::logs_dir(), + )) + .title(BACKEND_FAILURE_TITLE) + .kind(MessageDialogKind::Error) + .show(move |_| { + crate::shell::logging::mark_clean_shutdown(); + on_dismiss.exit(1); + }); +} + +/// Shows and focuses the window, and logs the cold start: setup() entry to +/// the first reveal. +fn reveal(window: &WebviewWindow, boot_start: Instant) { + if let Err(e) = window.show() { + tracing::warn!("show main window failed: {e}"); + } else { + tracing::info!( + target: "fleetify::startup", + cold_start_ms = boot_start.elapsed().as_millis() as u64, + "main window revealed" + ); + } + let _ = window.set_focus(); +} + +// ── IPC from the app's origin ── +// +// `capabilities/default.json` covers local origins only: the ones Tauri +// treats as the app's own (`devUrl` in dev mode, its custom schemes). The +// origin the main window loads the app from, when it is remote, gets the same +// permissions at setup, for that origin alone. No other remote origin can +// call anything: the main webview has no navigation guard, so a page it ends +// up on elsewhere must find no IPC. + +/// The permissions `capabilities/default.json` grants: the core ones, and +/// every app command (the `app-commands` set, `permissions/app-commands.toml`). +const IPC_PERMISSIONS: [&str; 4] = [ + "core:default", + "core:event:default", + "dialog:allow-open", + "app-commands", +]; + +/// Identifier of the capability added at runtime for the app's origin. +const RUNTIME_CAPABILITY: &str = "app-origin"; + +/// The origin the main window loads the app from. Debug builds load the Vite +/// dev server (`VITE_PORT`, default 3000); release builds load the embedded +/// backend serving the bundled dist (`FLEETIFY_BACKEND_PORT`, default 8765). +/// Honouring the ports is what lets the `dev:tauri:wt` script (and the +/// parallel-worktree workflow it enables) run two app instances side by side. +pub fn app_origin(release: bool, backend_port: u16, vite_port: u16) -> String { + if release { + format!("http://127.0.0.1:{backend_port}") + } else { + format!("http://localhost:{vite_port}") + } +} + +/// The http(s) URL Tauri treats as the app's own, local origin, besides its +/// `tauri://` assets and custom schemes: `devUrl` in dev mode (`dev` is +/// `tauri::is_dev()`: a build without Tauri's `custom-protocol` feature, such +/// as `tauri dev`), and otherwise `frontendDist` when it is a URL. It mirrors +/// Tauri's `get_app_url`, which `Webview::is_local_url` checks an IPC +/// request's origin against. +pub fn local_app_url(config: &tauri::Config, dev: bool) -> Option { + if dev { + config.build.dev_url.clone() + } else { + match &config.build.frontend_dist { + Some(FrontendDist::Url(url)) => Some(url.clone()), + _ => None, + } + } +} + +/// The origin setup grants IPC at runtime: the one the main window loads the +/// app from ([`app_origin`]), unless it is the origin of `local_app_url` (see +/// [`local_app_url`]), which Tauri treats as local and `default.json` covers. +/// A release build always gets one, for its embedded backend on +/// `http://127.0.0.1:`. A debug build gets one only when Vite is +/// not the local `devUrl`. +pub fn runtime_remote_origin( + release: bool, + backend_port: u16, + vite_port: u16, + local_app_url: Option<&Url>, +) -> Option { + let origin = app_origin(release, backend_port, vite_port); + let local = match (local_app_url, Url::parse(&origin)) { + (Some(local), Ok(app)) => local.origin() == app.origin(), + _ => false, + }; + (!local).then_some(origin) +} + +/// Grants `origin` its IPC permissions ([`runtime_capability`]), at setup, +/// before the window is built. A release build has no other grant, so a +/// failure stops the start (`StartFailure::Permissions`). It comes back as +/// its text, from an `Err` or from a panic: tauri 2.11.2 panics instead of +/// erring when it can't resolve the capability (`ipc/authority.rs`). The app +/// exits right after, so the lock that panic poisons is never used again. +pub fn grant_app_origin( + manager: &impl Manager, + origin: &str, +) -> Result<(), String> { + grant_outcome(std::panic::catch_unwind(AssertUnwindSafe(|| { + manager.add_capability(runtime_capability(origin)) + }))) +} + +/// The grant's outcome, from what `add_capability` returned or how it +/// panicked: `Ok`, or what went wrong, as text. +pub fn grant_outcome(caught: std::thread::Result>) -> Result<(), String> { + match caught { + Ok(Ok(())) => Ok(()), + Ok(Err(error)) => Err(error.to_string()), + Err(panic) => Err(panic_message(panic.as_ref())), + } +} + +/// A panic's message: its payload when that is text. +fn panic_message(panic: &(dyn Any + Send)) -> String { + match (panic.downcast_ref::<&str>(), panic.downcast_ref::()) { + (Some(message), _) => (*message).to_string(), + (None, Some(message)) => message.clone(), + (None, None) => "it panicked without a message".to_string(), + } +} + +/// What `capabilities/default.json` grants, for `origin` alone and the main +/// webview only, as there: a window scope would also match the browser +/// panel, a child webview in the main window. Added at setup, before the +/// window is built. +pub fn runtime_capability(origin: &str) -> CapabilityBuilder { + IPC_PERMISSIONS.iter().fold( + CapabilityBuilder::new(RUNTIME_CAPABILITY) + .remote(origin.to_string()) + .local(false) + .webview(MAIN_WEBVIEW), + |capability, permission| capability.permission(*permission), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn url(s: &str) -> Url { + s.parse().unwrap() + } + + /// The CSS rules inside the `@media (prefers-color-scheme: …)` block for + /// `scheme`. + fn scheme_block(scheme: &str) -> &'static str { + let start = format!("@media (prefers-color-scheme: {scheme})"); + let at = PLACEHOLDER_HTML + .find(&start) + .unwrap_or_else(|| panic!("no {start} block")); + let rest = &PLACEHOLDER_HTML[at + start.len()..]; + let open = rest.find('{').expect("block opens"); + let mut depth = 0; + for (i, c) in rest[open..].char_indices() { + match c { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + return &rest[open..open + i + 1]; + } + } + _ => {} + } + } + panic!("{start} block never closes"); + } + + #[test] + fn the_placeholder_says_fleetify_is_starting() { + assert!(PLACEHOLDER_HTML.contains("Starting Fleetify…")); + // The ellipsis is not ASCII: the page declares its encoding. + assert!(PLACEHOLDER_HTML.contains(r#""#)); + } + + #[test] + fn the_placeholder_loads_nothing() { + for reference in [ + "http://", "https://", "//", "src=", "href=", "url(", "@import", + ] { + assert!( + !PLACEHOLDER_HTML.contains(reference), + "the placeholder references a resource: {reference}" + ); + } + } + + #[test] + fn the_placeholder_colours_follow_the_system_colour_scheme() { + // The app's background and foreground: the light theme, and the + // default dark theme (zinc), from src/globals.css. + let light = scheme_block("light"); + assert!(light.contains("background: #ffffff"), "{light}"); + assert!(light.contains("color: #111111"), "{light}"); + let dark = scheme_block("dark"); + assert!(dark.contains("background: #0c0c0c"), "{dark}"); + assert!(dark.contains("color: #d8d8d8"), "{dark}"); + } + + #[test] + fn the_main_window_gets_the_placeholder_page() { + let response = placeholder_response(MAIN_WINDOW); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers()[header::CONTENT_TYPE], + "text/html; charset=utf-8" + ); + // The engine itself refuses anything but the inline styles. + assert_eq!( + response.headers()[header::CONTENT_SECURITY_POLICY], + "default-src 'none'; style-src 'unsafe-inline'" + ); + assert_eq!(response.body().as_slice(), PLACEHOLDER_HTML.as_bytes()); + } + + #[test] + fn other_webviews_get_nothing_from_the_placeholder_scheme() { + // The scheme is registered for every webview, the embedded browser + // panel included; only the main window is served. + let response = placeholder_response("browser-embed-1"); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert!(response.body().is_empty()); + } + + #[test] + fn the_placeholder_url_uses_the_placeholder_scheme() { + let placeholder = url(PLACEHOLDER_URL); + assert_eq!(placeholder.scheme(), PLACEHOLDER_SCHEME); + assert_eq!(placeholder.host_str(), Some("localhost")); + } + + #[test] + fn app_pages_are_told_apart_from_the_placeholder() { + let app = url("http://127.0.0.1:8765"); + assert!(is_app_page(&url("http://127.0.0.1:8765/"), &app)); + assert!(is_app_page( + &url("http://127.0.0.1:8765/settings?tab=privacy#top"), + &app + )); + // The placeholder, as Linux and macOS load it and as Windows does. + assert!(!is_app_page(&url(PLACEHOLDER_URL), &app)); + assert!(!is_app_page( + &url("http://fleetify-startup.localhost/"), + &app + )); + assert!(!is_app_page(&url("http://127.0.0.1:8899/"), &app)); + assert!(!is_app_page(&url("about:blank"), &app)); + let dev = url("http://localhost:3000"); + assert!(is_app_page(&url("http://localhost:3000/"), &dev)); + assert!(!is_app_page(&url("http://127.0.0.1:3000/"), &dev)); + } + + #[test] + fn the_app_loads_as_soon_as_it_answers() { + let bound = BackendStart::Bound; + let soon = Duration::from_millis(300); + assert_eq!(next_step(&bound, true, soon, false), Step::LoadApp); + assert_eq!( + next_step(&bound, true, SLOW_START * 4, false), + Step::LoadApp + ); + // After the placeholder went up, too. + assert_eq!(next_step(&bound, true, SLOW_START * 4, true), Step::LoadApp); + } + + #[test] + fn the_window_stays_hidden_while_startup_is_quick() { + for backend in [BackendStart::Pending, BackendStart::Bound] { + assert_eq!( + next_step(&backend, false, Duration::from_millis(300), false), + Step::KeepWaiting + ); + assert_eq!( + next_step( + &backend, + false, + SLOW_START - Duration::from_millis(1), + false + ), + Step::KeepWaiting + ); + } + } + + #[test] + fn a_slow_start_shows_the_placeholder_once_and_keeps_waiting() { + // Slow either way: the backend still binding (a keychain prompt), or + // bound while the app doesn't answer yet (Vite in debug builds). + for backend in [BackendStart::Pending, BackendStart::Bound] { + assert_eq!( + next_step(&backend, false, SLOW_START, false), + Step::ShowPlaceholder + ); + assert_eq!( + next_step(&backend, false, SLOW_START + Duration::from_secs(1), false), + Step::ShowPlaceholder + ); + // Already on screen: no cap, just keep polling. + assert_eq!( + next_step(&backend, false, SLOW_START, true), + Step::KeepWaiting + ); + assert_eq!( + next_step(&backend, false, Duration::from_secs(600), true), + Step::KeepWaiting + ); + } + } + + #[test] + fn the_slow_start_threshold_is_the_old_reveal_cap() { + assert_eq!(SLOW_START, Duration::from_secs(15)); + } + + // ── the backend's start ── + + #[test] + fn an_answer_before_the_backend_reports_its_bind_is_not_the_app() { + // Something else on the port answers before, or instead of, the + // backend: AnkiConnect listens on 127.0.0.1:8765 by default. + let pending = BackendStart::Pending; + assert_eq!( + next_step(&pending, true, Duration::from_millis(300), false), + Step::KeepWaiting + ); + assert_eq!( + next_step(&pending, true, SLOW_START, false), + Step::ShowPlaceholder + ); + assert_eq!( + next_step(&pending, true, SLOW_START * 4, true), + Step::KeepWaiting + ); + } + + #[test] + fn a_backend_that_fails_to_start_ends_the_wait() { + let failed = BackendStart::Failed(StartFailure::Backend( + "Address already in use (os error 98)".into(), + )); + for (answered, waited, placeholder_shown) in [ + (false, Duration::ZERO, false), + (true, Duration::from_millis(300), false), + (false, SLOW_START, false), + (false, SLOW_START * 40, true), + ] { + assert_eq!( + next_step(&failed, answered, waited, placeholder_shown), + Step::ReportFailure, + "answered {answered}, waited {waited:?}, placeholder {placeholder_shown}" + ); + } + } + + /// The report when a release build has no UI files to serve. + fn ui_files_missing() -> BackendStart { + BackendStart::Failed(StartFailure::UiFilesMissing(UiDirError::NoIndexHtml( + "/usr/lib/Fleetify/dist".into(), + ))) + } + + #[test] + fn missing_ui_files_end_the_wait_like_a_backend_that_fails() { + // The same path: the error dialog, then the app quits. Nothing is + // loaded, and a report outlives the task that sent it. + let missing = ui_files_missing(); + for (answered, waited, placeholder_shown) in [ + (false, Duration::ZERO, false), + (false, SLOW_START, false), + (false, SLOW_START * 40, true), + ] { + assert_eq!( + next_step(&missing, answered, waited, placeholder_shown), + Step::ReportFailure, + "waited {waited:?}, placeholder {placeholder_shown}" + ); + } + assert_eq!(backend_start_seen(&missing, true), missing); + } + + #[test] + fn a_backend_task_that_ends_without_reporting_counts_as_failed() { + // Its task panicked: the sender went away with the start still pending. + let BackendStart::Failed(StartFailure::Backend(error)) = + backend_start_seen(&BackendStart::Pending, true) + else { + panic!("a start nobody can report any more is a failed one"); + }; + assert!(!error.is_empty()); + assert_eq!( + backend_start_seen(&BackendStart::Pending, false), + BackendStart::Pending + ); + // A report outlives the task that sent it. + assert_eq!( + backend_start_seen(&BackendStart::Bound, true), + BackendStart::Bound + ); + let failed = BackendStart::Failed(StartFailure::Backend("database is locked".into())); + assert_eq!(backend_start_seen(&failed, true), failed); + } + + #[test] + fn the_failure_message_names_the_error_the_port_and_the_logs() { + let logs = tempfile::tempdir().unwrap(); + let message = backend_failure_message( + "Address already in use (os error 98)", + 8765, + Some(logs.path()), + ); + assert!( + message.contains("Address already in use (os error 98)"), + "{message}" + ); + assert!(message.contains("8765"), "{message}"); + assert!( + message.contains(&format!("The log files are in {}", logs.path().display())), + "{message}" + ); + } + + #[test] + fn the_failure_message_without_a_log_folder_still_names_the_error_and_port() { + // logging::init records its folder even when creating it failed: a + // folder that isn't there is never named. + let parent = tempfile::tempdir().unwrap(); + let never_created = parent.path().join("logs"); + for logs_dir in [Some(never_created.as_path()), None] { + let message = backend_failure_message("loading config: invalid TOML", 8899, logs_dir); + assert!( + message.contains("loading config: invalid TOML"), + "{message}" + ); + assert!(message.contains("8899"), "{message}"); + assert!( + message.contains("Fleetify could not write its log files."), + "{message}" + ); + assert!(!message.contains("The log files are in"), "{message}"); + assert!(!message.contains("None"), "{message}"); + } + } + + /// The first line of the dialog when the UI files are missing. + const REINSTALL: &str = "Fleetify's interface files are missing. Please reinstall Fleetify."; + + #[test] + fn the_missing_ui_files_message_says_to_reinstall_and_names_the_folder_and_the_logs() { + let logs = tempfile::tempdir().unwrap(); + let dist = Path::new("/usr/lib/Fleetify/dist"); + let message = ui_files_missing_message( + &UiDirError::NoIndexHtml(dist.to_path_buf()), + Some(logs.path()), + ); + assert!(message.starts_with(REINSTALL), "{message}"); + assert!( + message.contains(&format!("Fleetify looked for them in {}", dist.display())), + "{message}" + ); + assert!( + message.contains(&format!("The log files are in {}", logs.path().display())), + "{message}" + ); + // Not the backend's message: no server, no port. + assert!(!message.contains("local server"), "{message}"); + } + + #[test] + fn the_missing_ui_files_message_without_a_resource_folder_or_a_log_folder() { + let parent = tempfile::tempdir().unwrap(); + let never_created = parent.path().join("logs"); + for logs_dir in [Some(never_created.as_path()), None] { + let message = ui_files_missing_message( + &UiDirError::NoResourceDir("unknown path".into()), + logs_dir, + ); + assert!(message.starts_with(REINSTALL), "{message}"); + assert!( + message.contains("Fleetify couldn't find its install folder: unknown path"), + "{message}" + ); + assert!( + message.contains("Fleetify could not write its log files."), + "{message}" + ); + assert!(!message.contains("The log files are in"), "{message}"); + } + } + + #[test] + fn each_start_failure_gets_its_own_message() { + let logs = tempfile::tempdir().unwrap(); + let error = "Address already in use (os error 98)"; + assert_eq!( + start_failure_message( + &StartFailure::Backend(error.into()), + 8765, + Some(logs.path()) + ), + backend_failure_message(error, 8765, Some(logs.path())) + ); + let missing = UiDirError::NoIndexHtml("/usr/lib/Fleetify/dist".into()); + assert_eq!( + start_failure_message( + &StartFailure::UiFilesMissing(missing.clone()), + 8765, + Some(logs.path()) + ), + ui_files_missing_message(&missing, Some(logs.path())) + ); + assert_eq!( + start_failure_message( + &StartFailure::Permissions("app-commands not found".into()), + 8765, + Some(logs.path()) + ), + permissions_failure_message("app-commands not found", Some(logs.path())) + ); + } + + // ── a failed grant ── + + #[test] + fn a_grant_that_works_lets_the_start_go_on() { + assert_eq!(grant_outcome(Ok(Ok(()))), Ok(())); + } + + #[test] + fn a_grant_that_fails_is_a_start_failure_with_its_error() { + let error = grant_outcome(Ok(Err(tauri::Error::AssetNotFound("app-origin".into())))) + .expect_err("an Err from add_capability"); + assert!(error.contains("app-origin"), "{error}"); + } + + #[test] + fn a_grant_that_panics_is_a_start_failure_with_the_panic_message() { + // tauri 2.11.2 panics, not errs, when it can't resolve a capability + // (ipc/authority.rs: `Resolved::resolve(..).unwrap()`). + let caught = std::panic::catch_unwind(|| -> tauri::Result<()> { + panic!("UnknownPermission: app-commands") + }); + let error = grant_outcome(caught).expect_err("a panic"); + assert!(error.contains("UnknownPermission: app-commands"), "{error}"); + let caught = std::panic::catch_unwind(|| -> tauri::Result<()> { + panic!("{} not found", "app-commands") + }); + let error = grant_outcome(caught).expect_err("a formatted panic"); + assert!(error.contains("app-commands not found"), "{error}"); + // A panic whose payload isn't text still stops the start. + let caught = + std::panic::catch_unwind(|| -> tauri::Result<()> { std::panic::panic_any(7_u8) }); + assert!(grant_outcome(caught).is_err()); + } + + #[test] + fn a_failed_grant_ends_the_wait_like_a_backend_that_fails() { + // The same path: the backend never starts, the window never loads + // the app, and the error dialog shows before the app quits. + let failed = BackendStart::Failed(StartFailure::Permissions("resolve failed".into())); + for (answered, waited, placeholder_shown) in [ + (false, Duration::ZERO, false), + (true, Duration::from_millis(300), false), + (false, SLOW_START * 40, true), + ] { + assert_eq!( + next_step(&failed, answered, waited, placeholder_shown), + Step::ReportFailure, + "answered {answered}, waited {waited:?}, placeholder {placeholder_shown}" + ); + } + assert_eq!(backend_start_seen(&failed, true), failed); + } + + #[test] + fn the_failed_grant_message_names_the_error_and_the_logs() { + let logs = tempfile::tempdir().unwrap(); + let message = permissions_failure_message("resolve failed", Some(logs.path())); + assert!( + message.starts_with("Fleetify couldn't give its interface the permissions it needs"), + "{message}" + ); + assert!(message.contains("\n\nresolve failed\n\n"), "{message}"); + assert!( + message.contains(&format!("The log files are in {}", logs.path().display())), + "{message}" + ); + // Not the backend's message: no server, no port. + assert!(!message.contains("local server"), "{message}"); + let without_logs = permissions_failure_message("resolve failed", None); + assert!( + without_logs.ends_with("Fleetify could not write its log files."), + "{without_logs}" + ); + } + + // ── reading the backend's start ── + + /// Start reports that change between the startup task's two reads: the + /// backend reports its bind, and its task ends, right after the first. + struct BindsBetweenTheReads(std::cell::Cell); + + impl BindsBetweenTheReads { + /// True for the first read only. + fn first_read(&self) -> bool { + !self.0.replace(true) + } + } + + impl StartReports for BindsBetweenTheReads { + fn reporter_gone(&self) -> bool { + !self.first_read() + } + + fn last_report(&self) -> BackendStart { + if self.first_read() { + BackendStart::Pending + } else { + BackendStart::Bound + } + } + } + + #[test] + fn a_bind_reported_between_the_two_reads_is_not_a_failed_start() { + // Liveness is read first: the reporter was alive then, so the report + // read after it, the bind, stands. Read the other way round, the + // pending report and the ended task would make a false "can't start". + let reports = BindsBetweenTheReads(std::cell::Cell::new(false)); + assert_eq!(observe_start(&reports), BackendStart::Bound); + } + + #[test] + fn the_start_is_read_from_the_reports_as_they_stand() { + let (tx, rx) = watch::channel(BackendStart::Pending); + assert_eq!(observe_start(&rx), BackendStart::Pending); + tx.send(BackendStart::Bound).unwrap(); + drop(tx); + assert_eq!( + observe_start(&rx), + BackendStart::Bound, + "a bind outlives its task" + ); + let (tx, rx) = watch::channel(BackendStart::Pending); + drop(tx); + assert!( + matches!(observe_start(&rx), BackendStart::Failed(_)), + "a task that ended without a report never bound" + ); + } + + // ── the app page's load ── + + #[test] + fn a_finished_load_of_the_app_after_it_started_counts() { + let guard = AppLoadGuard::default(); + assert!(!guard.finished_app_load(PageLoadEvent::Started, true)); + assert!(guard.finished_app_load(PageLoadEvent::Finished, true)); + } + + #[test] + fn a_cancelled_navigation_to_the_app_does_not_count() { + // WebKitGTK reports it as load-failed, then Finished with the URL + // already the app's, and no Started (Committed) for it. + let guard = AppLoadGuard::default(); + assert!(!guard.finished_app_load(PageLoadEvent::Finished, true)); + // After the placeholder's own load, too. + let guard = AppLoadGuard::default(); + assert!(!guard.finished_app_load(PageLoadEvent::Started, false)); + assert!(!guard.finished_app_load(PageLoadEvent::Finished, false)); + assert!(!guard.finished_app_load(PageLoadEvent::Finished, true)); + } + + #[test] + fn each_finished_load_of_the_app_needs_its_own_start() { + let guard = AppLoadGuard::default(); + assert!(!guard.finished_app_load(PageLoadEvent::Started, true)); + assert!(guard.finished_app_load(PageLoadEvent::Finished, true)); + assert!(!guard.finished_app_load(PageLoadEvent::Finished, true)); + // A load of another page started since: its Finished isn't the app's. + assert!(!guard.finished_app_load(PageLoadEvent::Started, true)); + assert!(!guard.finished_app_load(PageLoadEvent::Started, false)); + assert!(!guard.finished_app_load(PageLoadEvent::Finished, true)); + } + + // ── IPC from the app's origin ── + + use std::collections::{BTreeMap, BTreeSet}; + + use tauri::ipc::{Origin, RuntimeAuthority, RuntimeCapability}; + use tauri::utils::acl::capability::{Capability, CapabilityFile}; + use tauri::utils::acl::manifest::Manifest; + use tauri::utils::acl::resolved::Resolved; + use tauri::utils::acl::APP_ACL_KEY; + use tauri::utils::platform::Target; + + use crate::app_commands::APP_COMMANDS; + use crate::shell::ipc::BROWSER_EMBED_LABEL; + + /// `capabilities/default.json`, which the runtime capability mirrors. + fn default_capability() -> serde_json::Value { + serde_json::from_str(include_str!("../../capabilities/default.json")).unwrap() + } + + /// The app's `tauri.conf.json`. + fn app_config() -> tauri::Config { + serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap() + } + + /// Its `devUrl`. + fn dev_url() -> Url { + url("http://localhost:3000") + } + + fn remote(s: &str) -> Origin { + Origin::Remote { url: url(s) } + } + + /// The ACL tauri-build compiled for this crate, as `generate_context!` + /// embeds it: the plugin and app manifests, and the capability files. + fn compiled_acl() -> (BTreeMap, BTreeMap) { + let manifests = include_str!(concat!(env!("OUT_DIR"), "/acl-manifests.json")); + let capabilities = include_str!(concat!(env!("OUT_DIR"), "/capabilities.json")); + ( + serde_json::from_str(manifests).unwrap(), + serde_json::from_str(capabilities).unwrap(), + ) + } + + /// The IPC authority of one app run: the compiled ACL, resolved and built + /// the way `generate_context!` does it (`runtime_authority!`), plus the + /// capability setup adds for `runtime_origin`, when there is one. + fn authority_with(runtime_origin: Option) -> RuntimeAuthority { + let (acl, capabilities) = compiled_acl(); + let resolved = Resolved::resolve(&acl, capabilities, Target::current()).unwrap(); + let mut authority = tauri::runtime_authority!(acl, resolved); + if let Some(origin) = runtime_origin { + authority + .add_capability(runtime_capability(&origin)) + .unwrap(); + } + authority + } + + /// A release build with its backend on `backend_port`, as setup sets up + /// its IPC. + fn release_authority(backend_port: u16) -> RuntimeAuthority { + authority_with(runtime_remote_origin(true, backend_port, 3000, None)) + } + + /// Each way the app runs: its IPC authority, and the origin its main + /// webview loads the app from. + fn app_runs() -> Vec<(&'static str, RuntimeAuthority, Origin)> { + let debug = + |vite| authority_with(runtime_remote_origin(false, 8765, vite, Some(&dev_url()))); + vec![ + ("debug, Vite on devUrl", debug(3000), Origin::Local), + ( + "debug, Vite on another port", + debug(3017), + remote("http://localhost:3017/"), + ), + ( + "release", + release_authority(8765), + remote("http://127.0.0.1:8765/"), + ), + ( + "release, backend on another port", + release_authority(8899), + remote("http://127.0.0.1:8899/settings"), + ), + ] + } + + /// Checked by name on top of every app command: commands the UI can't do + /// without, and core ones from `default.json`'s other permissions. + const SPOT_CHECKS: [&str; 6] = [ + "auth_sign_in", + "config_get", + "window_start_dragging", + "plugin:app|version", + "plugin:event|listen", + "plugin:dialog|open", + ]; + + /// `allow-`: the permission tauri-build generates for an app + /// command, underscores turned into hyphens. + fn allow_permission(command: &str) -> String { + format!("allow-{}", command.replace('_', "-")) + } + + #[test] + fn the_app_loads_from_the_backend_in_release_and_from_vite_in_debug() { + assert_eq!(app_origin(true, 8765, 3000), "http://127.0.0.1:8765"); + assert_eq!(app_origin(true, 8899, 3017), "http://127.0.0.1:8899"); + assert_eq!(app_origin(false, 8765, 3000), "http://localhost:3000"); + assert_eq!(app_origin(false, 8899, 3017), "http://localhost:3017"); + } + + #[test] + fn a_release_build_gets_its_backend_origin_on_every_port() { + // Flipped from Task 14: the default port gets the runtime capability + // too, now that default.json allows no remote origin. + assert_eq!( + runtime_remote_origin(true, 8765, 3000, None), + Some("http://127.0.0.1:8765".to_string()) + ); + assert_eq!( + runtime_remote_origin(true, 8899, 3017, None), + Some("http://127.0.0.1:8899".to_string()) + ); + // A release build without Tauri's custom-protocol feature (`cargo + // build --release`) treats devUrl as local; the backend isn't it. + assert_eq!( + runtime_remote_origin(true, 8765, 3000, Some(&dev_url())), + Some("http://127.0.0.1:8765".to_string()) + ); + } + + #[test] + fn a_debug_build_on_the_local_dev_url_needs_no_runtime_capability() { + // Tauri treats devUrl as local, and default.json covers local origins. + assert_eq!( + runtime_remote_origin(false, 8765, 3000, Some(&dev_url())), + None + ); + assert_eq!( + runtime_remote_origin(false, 8899, 3000, Some(&url("http://localhost:3000/"))), + None + ); + // dev:tauri:wt moves devUrl to the worktree's Vite port. + assert_eq!( + runtime_remote_origin(false, 8765, 3017, Some(&url("http://localhost:3017"))), + None + ); + } + + #[test] + fn a_debug_build_off_the_local_dev_url_gets_its_vite_origin() { + assert_eq!( + runtime_remote_origin(false, 8765, 3017, Some(&dev_url())), + Some("http://localhost:3017".to_string()) + ); + // No local devUrl: a debug build of the bundle (`tauri build --debug`). + assert_eq!( + runtime_remote_origin(false, 8765, 3000, None), + Some("http://localhost:3000".to_string()) + ); + // The same port on another host is another origin. + assert_eq!( + runtime_remote_origin(false, 8765, 3000, Some(&url("http://127.0.0.1:3000"))), + Some("http://localhost:3000".to_string()) + ); + } + + #[test] + fn the_runtime_origin_is_where_the_window_loads_the_app() { + for (release, backend, vite, local) in [ + (true, 8765, 3000, None), + (true, 8899, 3000, None), + (false, 8765, 3017, Some(dev_url())), + (true, 9000, 4000, None), + ] { + let origin = runtime_remote_origin(release, backend, vite, local.as_ref()).unwrap(); + assert_eq!(origin, app_origin(release, backend, vite)); + let app_url: Url = origin.parse().unwrap(); + assert!(is_app_page(&app_url.join("/settings").unwrap(), &app_url)); + } + } + + #[test] + fn the_local_app_url_is_dev_url_in_dev_mode_only() { + // Mirrors Tauri's get_app_url, which is_local_url checks origins + // against: devUrl in dev mode, a frontendDist URL otherwise. + let mut config = app_config(); + assert_eq!(local_app_url(&config, true), Some(dev_url())); + // A release bundle serves the bundled dist (`../dist`) on tauri://. + assert_eq!(local_app_url(&config, false), None); + config.build.frontend_dist = Some(FrontendDist::Url(url("http://127.0.0.1:9000"))); + assert_eq!( + local_app_url(&config, false), + Some(url("http://127.0.0.1:9000")) + ); + } + + #[test] + fn the_runtime_capability_is_default_json_for_one_origin() { + let default = default_capability(); + let CapabilityFile::Capability(capability) = + runtime_capability("http://127.0.0.1:8899").build() + else { + panic!("a single capability"); + }; + assert_eq!( + capability.remote.map(|remote| remote.urls), + Some(vec!["http://127.0.0.1:8899".to_string()]) + ); + assert!(!capability.local, "it allows that one remote origin only"); + assert_eq!(serde_json::json!(capability.webviews), default["webviews"]); + assert_eq!(capability.webviews, [MAIN_WEBVIEW]); + assert!( + capability.windows.is_empty(), + "scoped by webview, as default.json is: {:?}", + capability.windows + ); + let permissions: Vec<&str> = capability + .permissions + .iter() + .map(|permission| permission.identifier().get()) + .collect(); + assert_eq!(serde_json::json!(permissions), default["permissions"]); + assert_ne!( + serde_json::json!(capability.identifier), + default["identifier"] + ); + } + + #[test] + fn default_json_grants_the_core_permissions_and_the_app_commands() { + let default = default_capability(); + let permissions = default["permissions"].as_array().unwrap(); + for permission in [ + "core:default", + "core:event:default", + "dialog:allow-open", + "app-commands", + ] { + assert!( + permissions.contains(&serde_json::json!(permission)), + "default.json doesn't grant {permission}: {permissions:?}" + ); + } + assert_eq!(default["permissions"], serde_json::json!(IPC_PERMISSIONS)); + } + + #[test] + fn default_json_applies_to_the_main_webview_only() { + let default = default_capability(); + assert_eq!(default["webviews"], serde_json::json!([MAIN_WEBVIEW])); + // A window scope matches every webview in that window: the browser + // panel's child webview in the main window too. + assert!( + default.get("windows").is_none(), + "default.json is scoped by window: {}", + default["windows"] + ); + } + + #[test] + fn default_json_allows_local_origins_only() { + let default = default_capability(); + // No remote origin at all: setup grants the app's own at runtime + // (runtime_capability), and nothing else is ever allowed. + assert!( + default.get("remote").is_none(), + "default.json allows remote origins: {}", + default["remote"] + ); + // Local origins (devUrl in dev mode) are covered: with an app + // manifest, Tauri checks app commands from them too. + let capability: Capability = serde_json::from_value(default).unwrap(); + assert!(capability.remote.is_none()); + assert!(capability.local); + } + + #[test] + fn the_app_commands_set_allows_exactly_the_app_commands() { + let (acl, _) = compiled_acl(); + let app = acl + .get(APP_ACL_KEY) + .expect("build.rs declares the app's ACL manifest"); + let set = app + .permission_sets + .get("app-commands") + .expect("permissions/app-commands.toml defines the app-commands set"); + let listed: BTreeSet = set.permissions.iter().cloned().collect(); + assert_eq!( + listed.len(), + set.permissions.len(), + "the app-commands set lists a permission twice" + ); + let expected: BTreeSet = APP_COMMANDS.iter().map(|c| allow_permission(c)).collect(); + let missing: Vec<_> = expected.difference(&listed).collect(); + let extra: Vec<_> = listed.difference(&expected).collect(); + assert!( + missing.is_empty() && extra.is_empty(), + "permissions/app-commands.toml must list allow- for exactly APP_COMMANDS.\n\ + missing: {missing:?}\n\ + not an app command: {extra:?}" + ); + for command in APP_COMMANDS { + let permission = &app.permissions[&allow_permission(command)]; + assert_eq!(permission.commands.allow, [command.to_string()]); + assert!(permission.commands.deny.is_empty()); + } + } + + #[test] + fn the_main_webview_can_call_every_app_command_from_the_app_origin() { + for (run, authority, origin) in app_runs() { + for command in SPOT_CHECKS.iter().chain(APP_COMMANDS) { + assert!( + authority + .resolve_access(command, MAIN_WINDOW, MAIN_WEBVIEW, &origin) + .is_some(), + "{run}: {command} is refused to the main webview from {origin}" + ); + } + } + } + + #[test] + fn the_browser_panel_can_call_no_command_at_all() { + // The browser panel is a child webview in the main window. Even on a + // page from the app's own origin it gets nothing: no app command and + // no core one. + for (run, authority, origin) in app_runs() { + for command in SPOT_CHECKS.iter().chain(APP_COMMANDS) { + assert!( + authority + .resolve_access(command, MAIN_WINDOW, BROWSER_EMBED_LABEL, &origin) + .is_none(), + "{run}: {command} is allowed to the browser panel from {origin}" + ); + } + } + } + + #[test] + fn a_release_build_refuses_the_dev_server_origin() { + // The main webview has no navigation guard: a page it ends up on at + // http://localhost:3000, a user's own dev server say, gets nothing. + let authority = release_authority(8765); + let refused = |origin: &Origin| { + authority + .resolve_access("pty_spawn", MAIN_WINDOW, MAIN_WEBVIEW, origin) + .is_none() + }; + assert!(refused(&remote("http://localhost:3000/"))); + // Its own origin still gets it: the refusal is about the origin. + assert!(!refused(&remote("http://127.0.0.1:8765/"))); + } + + #[test] + fn a_release_build_on_another_port_refuses_the_default_backend_origin() { + // Something else may answer on 8765 (AnkiConnect listens there). + let authority = release_authority(8899); + let refused = |origin: &Origin| { + authority + .resolve_access("pty_spawn", MAIN_WINDOW, MAIN_WEBVIEW, origin) + .is_none() + }; + assert!(refused(&remote("http://127.0.0.1:8765/"))); + assert!(!refused(&remote("http://127.0.0.1:8899/"))); + } + + // ── IPC from frames inside the app (WebKitGTK postMessage) ── + // + // wry's WebKitGTK backend tags every postMessage IPC request with the + // main frame's URL, whichever frame sent it, and Tauri checks the ACL + // against that URL. A cross-origin frame in the main webview holding the + // invoke key (the Preview pane) would get the app page's permissions. + // The vendored runtime gives those requests an origin no capability + // matches (vendor/tauri-runtime-wry/FLEETIFY_PATCH.md). + + use tauri_runtime_wry::{postmessage_ipc_request, POSTMESSAGE_IPC_ORIGIN, WEBKITGTK}; + + /// A postMessage IPC request as wry's WebKitGTK backend hands it over: + /// the main frame's URL, and the message the page posted. + fn posted_request(main_frame_url: &str, body: &str) -> tauri::http::Request { + tauri::http::Request::builder() + .uri(main_frame_url) + .body(body.to_string()) + .unwrap() + } + + /// A message with the invoke key, as `ipc-protocol.js` posts it. + const POSTED_PTY_SPAWN: &str = r#"{"cmd":"pty_spawn","callback":1,"error":2,"payload":{},"options":{},"__TAURI_INVOKE_KEY__":"key"}"#; + + /// Where Tauri takes an IPC request's origin from: the request's URI + /// (`ipc/protocol.rs`, `handle_ipc_message`). + fn request_url(request: &tauri::http::Request) -> Url { + Url::parse(&request.uri().to_string()).unwrap() + } + + /// The origin Tauri checks an IPC request from `url` as, for an http URL + /// (`Webview::is_local_url`): local when it shares the origin of the + /// run's local app URL (`devUrl` in dev mode), remote otherwise. + fn acl_origin(url: &Url, local_app_url: Option<&Url>) -> Origin { + match local_app_url { + Some(local) if local.origin() == url.origin() => Origin::Local, + _ => Origin::Remote { url: url.clone() }, + } + } + + #[test] + fn postmessage_ipc_requests_get_an_origin_of_their_own_on_webkitgtk() { + let rewritten = postmessage_ipc_request( + posted_request("http://127.0.0.1:8765/settings", POSTED_PTY_SPAWN), + true, + ); + assert_eq!(rewritten.uri().to_string(), POSTMESSAGE_IPC_ORIGIN); + assert_eq!( + rewritten.body(), + POSTED_PTY_SPAWN, + "the message is untouched" + ); + + // wry reports the sending frame's own URL on macOS, and iframes + // can't post at all on Windows: nothing changes there. + let kept = postmessage_ipc_request( + posted_request("http://127.0.0.1:8765/settings", POSTED_PTY_SPAWN), + false, + ); + assert_eq!(kept.uri().to_string(), "http://127.0.0.1:8765/settings"); + assert_eq!(kept.body(), POSTED_PTY_SPAWN); + + // This build: WebKitGTK on Linux and the BSDs (wry's gtk targets). + let gtk = cfg!(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + )); + assert_eq!(WEBKITGTK, gtk); + let here = postmessage_ipc_request( + posted_request("http://localhost:3000/", POSTED_PTY_SPAWN), + WEBKITGTK, + ); + let expected = if gtk { + POSTMESSAGE_IPC_ORIGIN + } else { + "http://localhost:3000/" + }; + assert_eq!(here.uri().to_string(), expected); + } + + #[test] + fn a_frame_cant_borrow_the_app_pages_permissions_through_postmessage_ipc() { + // The origin is never one Tauri treats as the app's own: not its + // tauri:// or custom schemes, not devUrl, and `.invalid` never + // resolves (RFC 6761), so no page can ever have it. + let sentinel = url(POSTMESSAGE_IPC_ORIGIN); + assert_eq!(sentinel.scheme(), "http"); + assert_eq!(sentinel.host_str(), Some("postmessage-ipc.invalid")); + assert_ne!(sentinel.origin(), dev_url().origin()); + // pty_spawn, the command that runs a shell, is checked with the rest. + assert!(APP_COMMANDS.contains(&"pty_spawn")); + + let debug = + |vite| authority_with(runtime_remote_origin(false, 8765, vite, Some(&dev_url()))); + // Each way the app runs: its authority, the main page's URL (what + // wry tags a frame's message with) and the run's local app URL. + let runs = [ + ( + "debug, Vite on devUrl", + debug(3000), + "http://localhost:3000/", + Some(dev_url()), + ), + ( + "debug, Vite on another port", + debug(3017), + "http://localhost:3017/", + Some(dev_url()), + ), + ( + "release", + release_authority(8765), + "http://127.0.0.1:8765/", + None, + ), + ( + "release, backend on another port", + release_authority(8899), + "http://127.0.0.1:8899/settings", + None, + ), + ]; + for (run, authority, main_frame_url, local_app_url) in runs { + // As on WebKitGTK, whatever this test runs on: which builds + // rewrite is the test above's and the next one's business. + let request = + postmessage_ipc_request(posted_request(main_frame_url, POSTED_PTY_SPAWN), true); + let origin = acl_origin(&request_url(&request), local_app_url.as_ref()); + for webview in [MAIN_WEBVIEW, BROWSER_EMBED_LABEL] { + for command in SPOT_CHECKS.iter().chain(APP_COMMANDS) { + assert!( + authority + .resolve_access(command, MAIN_WINDOW, webview, &origin) + .is_none(), + "{run}: a postMessage request from a frame on {main_frame_url} \ + can call {command} in webview {webview:?} (origin {origin})" + ); + } + } + } + } + + #[test] + fn the_vendored_runtime_rewrites_every_postmessage_ipc_request() { + // A re-vendor must keep the patch: the handler wry calls for every + // postMessage request hands Tauri the rewritten request. (A Windows + // checkout may have CRLF line endings.) + let runtime = + include_str!("../../../vendor/tauri-runtime-wry/src/lib.rs").replace("\r\n", "\n"); + let start = runtime + .find("fn create_ipc_handler") + .expect("the vendored runtime has create_ipc_handler"); + let handler = &runtime[start..]; + let handler = &handler[..handler.find("\n}\n").expect("the function ends")]; + assert!( + handler.contains("postmessage_ipc_request(request, WEBKITGTK)"), + "create_ipc_handler must pass every request through \ + postmessage_ipc_request(request, WEBKITGTK):\n{handler}" + ); + } +} diff --git a/src-tauri/src/shell/ui_files.rs b/src-tauri/src/shell/ui_files.rs new file mode 100644 index 0000000..23d2fed --- /dev/null +++ b/src-tauri/src/shell/ui_files.rs @@ -0,0 +1,291 @@ +//! The UI files a release build serves, and the one place they come from. +//! +//! Release builds load the app from the embedded backend, which serves the +//! built UI (`npm run build` → `dist/`) on `http://127.0.0.1:`. That +//! origin holds every app command (see +//! `startup_window::runtime_capability`). The bundle ships the UI as a +//! resource: `bundle.resources` in `tauri.conf.json` maps `../dist` to +//! [`UI_DIR`] in the install's resource folder, and that is the only place +//! it is served from ([`ui_dir`]). +//! +//! It used to be served from `dist` beside the executable, or else from +//! `dist` in the working directory. No bundle had either, so an installed +//! copy showed a blank window, and a `dist` folder in whatever directory +//! Fleetify was launched from (a cloned repository, say) was served as the +//! app, with all of its IPC. Missing UI files now end the start like a +//! backend that can't start: an error dialog, then the app quits (see +//! `startup_window`). +//! +//! Debug builds load the UI from the Vite dev server and serve none. + +use std::fmt; +use std::path::{Path, PathBuf}; + +/// The UI's folder in the install's resource folder: where +/// `bundle.resources` puts the built `../dist`. +pub const UI_DIR: &str = "dist"; + +/// Why a release build has no UI files to serve. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UiDirError { + /// The install's resource folder is unknown: Tauri couldn't work it out + /// (its error), or it is not an absolute path, which every file system + /// call would resolve against the working directory. + NoResourceDir(String), + /// The UI folder ([`UI_DIR`] in the resource folder) has no + /// `index.html`: the folder is missing, or it is there without the file. + NoIndexHtml(PathBuf), +} + +impl fmt::Display for UiDirError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoResourceDir(error) => { + write!(f, "the install's resource folder is unknown: {error}") + } + Self::NoIndexHtml(dir) => write!(f, "{} has no index.html", dir.display()), + } + } +} + +impl std::error::Error for UiDirError {} + +/// The UI folder in `resource_dir`, the install's resource folder +/// (`app.path().resource_dir()`): [`UI_DIR`] there, when it holds +/// `index.html`. Nowhere else: not beside the executable, and never the +/// working directory. A relative `resource_dir` is refused, since it would +/// be resolved against the working directory. +pub fn ui_dir(resource_dir: &Path) -> Result { + if !resource_dir.is_absolute() { + return Err(UiDirError::NoResourceDir(format!( + "{resource_dir:?} is not an absolute path" + ))); + } + let dir = resource_dir.join(UI_DIR); + if dir.join("index.html").is_file() { + Ok(dir) + } else { + Err(UiDirError::NoIndexHtml(dir)) + } +} + +/// The UI folder the embedded backend serves: none in a debug build, which +/// loads the UI from Vite and never asks for `resource_dir`; in release, the +/// one [`ui_dir`] finds in the install's resource folder. An error is a +/// release build with no UI to serve, which is a start failure. +pub fn served_ui_dir( + release: bool, + resource_dir: impl FnOnce() -> tauri::Result, +) -> Result, UiDirError> { + if !release { + return Ok(None); + } + let resource_dir = resource_dir().map_err(|e| UiDirError::NoResourceDir(e.to_string()))?; + ui_dir(&resource_dir).map(Some) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + /// A folder holding `files` (paths relative to it), each with a line of + /// content. + fn folder_with(files: &[&str]) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + for file in files { + let path = dir.path().join(file); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, format!("")).unwrap(); + } + dir + } + + #[test] + fn the_ui_is_dist_in_the_resource_folder_when_it_has_index_html() { + let resources = folder_with(&["dist/index.html", "dist/assets/index.js"]); + assert_eq!(ui_dir(resources.path()), Ok(resources.path().join("dist"))); + } + + #[test] + fn no_dist_folder_means_no_ui() { + let resources = folder_with(&[]); + assert_eq!( + ui_dir(resources.path()), + Err(UiDirError::NoIndexHtml(resources.path().join("dist"))) + ); + } + + #[test] + fn a_dist_folder_without_index_html_means_no_ui() { + let resources = folder_with(&["dist/assets/index.js"]); + let dist = resources.path().join("dist"); + assert_eq!( + ui_dir(resources.path()), + Err(UiDirError::NoIndexHtml(dist.clone())) + ); + // A folder named index.html isn't the page. + fs::create_dir(dist.join("index.html")).unwrap(); + assert_eq!(ui_dir(resources.path()), Err(UiDirError::NoIndexHtml(dist))); + } + + #[test] + fn an_index_html_outside_dist_does_not_count() { + // At the root of the resource folder, or in a dist folder one level + // down: only /dist/index.html is the UI. + let resources = folder_with(&["index.html", "lib/dist/index.html"]); + assert_eq!( + ui_dir(resources.path()), + Err(UiDirError::NoIndexHtml(resources.path().join("dist"))) + ); + } + + #[test] + fn a_relative_resource_folder_is_refused() { + // It would be resolved against the working directory. + for relative in ["", ".", "resources", "../lib/Fleetify"] { + assert!( + matches!( + ui_dir(Path::new(relative)), + Err(UiDirError::NoResourceDir(_)) + ), + "{relative:?}: {:?}", + ui_dir(Path::new(relative)) + ); + } + } + + /// Set in the child process [`the_working_directory_is_never_consulted`] + /// starts: the resource folder the child checks. + const PROBE_RESOURCE_DIR: &str = "FLEETIFY_TEST_UI_FILES_RESOURCE_DIR"; + + #[test] + fn the_working_directory_is_never_consulted() { + // The working directory is the whole process's, and tests run on + // parallel threads: the check runs in a child process of this test + // binary, started in that directory and running this test alone. + if let Some(resources) = std::env::var_os(PROBE_RESOURCE_DIR) { + // The child. Its working directory has dist/index.html; the + // resource folder doesn't. + assert!( + Path::new("dist/index.html").is_file(), + "the launch directory has the UI files" + ); + let resources = Path::new(&resources); + assert_eq!( + ui_dir(resources), + Err(UiDirError::NoIndexHtml(resources.join("dist"))) + ); + return; + } + // Launched from a directory with a dist folder (a cloned repository, + // say), from an install without its UI files. + let launch_dir = folder_with(&["dist/index.html", "dist/assets/evil.js"]); + let resources = folder_with(&[]); + let (_crate, module) = module_path!().split_once("::").unwrap(); + let this_test = format!("{module}::the_working_directory_is_never_consulted"); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([this_test.as_str(), "--exact", "--test-threads=1"]) + .env(PROBE_RESOURCE_DIR, resources.path()) + .current_dir(launch_dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "{stdout}\n{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(stdout.contains("1 passed"), "the child ran it: {stdout}"); + } + + #[test] + fn a_debug_build_serves_no_ui_and_never_asks_for_the_resource_folder() { + assert_eq!( + served_ui_dir(false, || panic!("a debug build loads the UI from Vite")), + Ok(None) + ); + } + + #[test] + fn a_release_build_serves_the_ui_from_the_resource_folder() { + let resources = folder_with(&["dist/index.html"]); + let dir = resources.path().to_path_buf(); + assert_eq!( + served_ui_dir(true, || Ok(dir)), + Ok(Some(resources.path().join("dist"))) + ); + } + + #[test] + fn a_release_build_without_its_ui_files_has_nothing_to_serve() { + let resources = folder_with(&[]); + let dir = resources.path().to_path_buf(); + assert_eq!( + served_ui_dir(true, || Ok(dir)), + Err(UiDirError::NoIndexHtml(resources.path().join("dist"))) + ); + assert!(matches!( + served_ui_dir(true, || Err(tauri::Error::UnknownPath)), + Err(UiDirError::NoResourceDir(_)) + )); + } + + #[test] + fn the_error_says_which_folder_or_why_there_is_none() { + let dir = Path::new("/usr/lib/Fleetify/dist"); + assert_eq!( + UiDirError::NoIndexHtml(dir.to_path_buf()).to_string(), + format!("{} has no index.html", dir.display()) + ); + assert_eq!( + UiDirError::NoResourceDir("unknown path".into()).to_string(), + "the install's resource folder is unknown: unknown path" + ); + } + + // ── The bundle ── + + /// The app's `tauri.conf.json`. + fn tauri_conf() -> serde_json::Value { + serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap() + } + + #[test] + fn the_bundle_ships_the_built_ui_as_dist() { + // The map form, source → target: a directory source keeps its + // structure under the target, so the frontend build's dist/index.html + // lands at /dist/index.html. The list form would + // put `../dist` under `_up_/dist` instead. + let config = tauri_conf(); + let resources = &config["bundle"]["resources"]; + assert!( + resources.is_object(), + "bundle.resources must be a source → target map: {resources}" + ); + assert_eq!( + resources["../dist"], UI_DIR, + "bundle.resources must map ../dist to {UI_DIR}: {resources}" + ); + } + + #[test] + fn the_bundled_folder_is_the_one_the_frontend_build_fills() { + // `tauri build` runs beforeBuildCommand, the frontend build among + // it, before it compiles and bundles; Vite writes dist/ at the repo + // root, `../dist` from src-tauri, which frontendDist names too. + let config = tauri_conf(); + assert_eq!( + config["build"]["frontendDist"], "../dist", + "bundle.resources ships ../dist: the frontend build's output, \ + which frontendDist names" + ); + let before_build = config["build"]["beforeBuildCommand"].as_str().unwrap(); + assert!( + before_build + .split("&&") + .any(|command| command.trim() == "npm run build"), + "beforeBuildCommand must run the frontend build: {before_build}" + ); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index bc01ced..75a6e23 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -31,6 +31,9 @@ "binaries/fleet-reveng-mcp", "binaries/fleet-browser-mcp" ], + "resources": { + "../dist": "dist" + }, "icon": [ "icons/32x32.png", "icons/128x128.png", @@ -39,7 +42,7 @@ "icons/icon.ico" ], "publisher": "Fleetify", - "copyright": "© 2026 Fleetify. All rights reserved.", + "copyright": "Copyright © 2026 The Fleetify Authors", "category": "DeveloperTool", "shortDescription": "Local agent fleet for Claude, Codex, Gemini.", "longDescription": "Fleetify is a desktop control plane for Claude, Codex, and Gemini agent sessions — Fleet, the in-app orchestrator, dispatches work to many agents on real projects in parallel, watches progress live, and ships PRs through the same workflow you already use on the command line.", diff --git a/src/App.tsx b/src/App.tsx index e472a27..84d5bf8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -7,8 +7,10 @@ import { SetupScreen } from "@/components/onboarding/setup-screen"; import { useAppStore } from "@/stores/app-store"; import { usePluginStore } from "@/stores/plugin-store"; import { clearToken, type AuthUser } from "@/lib/api"; +import { handleAuthEvent } from "@/lib/auth-events"; import { identifyUser, initPostHog, pageview } from "@/lib/posthog"; import { isIntroComplete } from "@/lib/onboarding-gate"; +import { showsLogoGallery } from "@/lib/dev-gallery"; // Heavy routes that are rarely the first surface a user sees — pulled // out of the initial bundle so cold-start ships fewer KB of JS and the @@ -169,11 +171,9 @@ export function App() { useEffect(() => { if (!window.fleetify) { setScreen("splash"); return; } - // Bootstrap PostHog as soon as we know the backend is wired — - // before the auth gate so the anonymous funnel (welcome → sign-in) - // is also captured under the same device_id. SDK is no-op while - // opt-out: `posthog_enabled = false` (the default) → SDK loads but - // suppresses sends; consent flips it via `telemetrySetPosthogEnabled`. + // Product analytics: hand the wrapper the backend's device id and the + // live opt-in. posthog-js starts only when that is on (off by default); + // otherwise it isn't loaded until the user opts in. void window.electronAPI?.telemetryGetConfig?.() .then((cfg) => initPostHog({ distinctId: cfg.distinct_id, @@ -205,6 +205,10 @@ export function App() { }; localStorage.setItem("fleet:user", JSON.stringify(user)); setAuthedUser(user); + // Product analytics: link this launch to the account too, with the id + // only. Sends nothing while product analytics is off; the id is used + // if the user opts in later in this session. + identifyUser(user.id); // Returning users who haven't completed the intro yet land in the // chat-style onboarding once; everyone who already finished it (on // any port / run mode) goes straight to main. @@ -223,12 +227,14 @@ export function App() { setScreen("splash"); }); - const off = window.fleetify.onAuthEvent((event) => { - if (event.kind === "signed-out") { - clearToken(); - setScreen("welcome"); - } - }); + const off = window.fleetify.onAuthEvent((event) => + handleAuthEvent(event, { + onSignedOut: () => { + clearToken(); + setScreen("welcome"); + }, + }), + ); return off; }, []); @@ -240,11 +246,10 @@ export function App() { localStorage.setItem("fleet:onboarded", "1"); localStorage.setItem("fleet:user", JSON.stringify(user)); setAuthedUser(user); - // PostHog identity merge — frontend was emitting under the anonymous - // device_id; calling identify(user_id) fires $identify with - // $anon_distinct_id set, so PostHog server-side merges the two - // persons. No-op when SDK isn't initialised (opt-out or no key). - identifyUser(user.id, { is_new: isNew, name: user.name, email: user.email }); + // Product analytics: link the device's events to the account, with the + // user id only. Sends nothing while product analytics is off; the id is + // used if the user opts in later in this session. + identifyUser(user.id); // Read the durable config once. We persist the display name with a // read-merge-write (config_set is a full replace), and crucially we do @@ -371,13 +376,14 @@ export function App() { // Dev-only logo gallery — navigate to /#logos to compare every // brand-mark candidate side-by-side at four sizes against light + dark - // surfaces. Pure dev surface; never renders in production paths. + // surfaces. Dev builds only (showsLogoGallery): a release build never + // shows it, whatever the hash says. // Re-checks on hashchange so the gallery toggles without a refresh. const [showLogos, setShowLogos] = useState( - typeof window !== "undefined" && window.location.hash === "#logos", + typeof window !== "undefined" && showsLogoGallery(window.location.hash), ); useEffect(() => { - const onHash = () => setShowLogos(window.location.hash === "#logos"); + const onHash = () => setShowLogos(showsLogoGallery(window.location.hash)); window.addEventListener("hashchange", onHash); return () => window.removeEventListener("hashchange", onHash); }, []); diff --git a/src/__tests__/app-analytics-identity.test.tsx b/src/__tests__/app-analytics-identity.test.tsx new file mode 100644 index 0000000..b7e1694 --- /dev/null +++ b/src/__tests__/app-analytics-identity.test.tsx @@ -0,0 +1,80 @@ +import { it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, waitFor } from "@testing-library/react"; + +// Product analytics is linked to the account. A user who was already signed +// in when Fleetify started must be linked too, once they opt in, with their +// id only. The analytics wrapper is real here; posthog-js is mocked. + +const ph = vi.hoisted(() => ({ + init: vi.fn(), + register: vi.fn(), + identify: vi.fn(), + capture: vi.fn(), + opt_in_capturing: vi.fn(), + opt_out_capturing: vi.fn(), + has_opted_out_capturing: vi.fn(() => false), + resetPersonPropertiesForFlags: vi.fn(), + _send_request: vi.fn(), +})); +vi.mock("posthog-js", () => ({ default: ph })); + +// The screens themselves don't matter here. +vi.mock("@/components/layout/app-shell", () => ({ AppShell: () => null })); +vi.mock("@/components/onboarding/splash-screen", () => ({ SplashScreen: () => null })); +vi.mock("@/components/onboarding/welcome-screen", () => ({ WelcomeScreen: () => null })); +vi.mock("@/components/onboarding/setup-screen", () => ({ SetupScreen: () => null })); +vi.mock("@/components/onboarding/onboarding-chat", () => ({ OnboardingChat: () => null })); + +import { App } from "@/App"; +import { optIn } from "@/lib/posthog"; + +type Mock = ReturnType; +let api: Record; + +beforeEach(() => { + vi.stubEnv("VITE_POSTHOG_KEY", "phc_test"); + ph.init.mockImplementation((_key: string, config: { loaded?: (p: typeof ph) => void }) => { + config.loaded?.(ph); + return ph; + }); + localStorage.setItem("fleet:onboarded", "1"); + (window as unknown as { fleetify: unknown }).fleetify = { + getState: vi.fn(async () => ({ + signedIn: true, + user: { sub: "user-1", name: "Mira Tester", email: "mira@example.com" }, + })), + onAuthEvent: vi.fn(() => () => {}), + }; + api = { + telemetryGetConfig: vi.fn(async () => ({ + distinct_id: "device-1", + posthog_enabled: false, + cloud_enabled: false, + })), + getConfig: vi.fn(async () => ({ onboardingComplete: false, apiKeys: {} })), + setConfig: vi.fn(async () => ({ ok: true })), + setWindowSize: vi.fn(async () => true), + }; + (window as unknown as { electronAPI: unknown }).electronAPI = api; +}); + +afterEach(() => { + vi.unstubAllEnvs(); + localStorage.clear(); +}); + +it("links a user signed in at launch once they opt in from Settings, with the id only", async () => { + render(); + // The signed-in launch path has run (it reads the config right after + // taking the user). + await waitFor(() => expect(api.getConfig).toHaveBeenCalled()); + // Product analytics is off: nothing has reached posthog-js. + expect(ph.init).not.toHaveBeenCalled(); + expect(ph.identify).not.toHaveBeenCalled(); + + // What Settings → Privacy → Product analytics does when switched on. + optIn(); + await waitFor(() => expect(ph.init).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(ph.identify).toHaveBeenCalled()); + expect(ph.identify.mock.calls).toEqual([["user-1"]]); +}); diff --git a/src/components/__tests__/app-error-boundary.test.tsx b/src/components/__tests__/app-error-boundary.test.tsx new file mode 100644 index 0000000..d7db096 --- /dev/null +++ b/src/components/__tests__/app-error-boundary.test.tsx @@ -0,0 +1,61 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent } from "@testing-library/react"; + +// A render error anywhere in the app used to unmount the whole tree and +// leave a blank window. The root boundary shows a recovery screen instead +// and hands the error to the logger, which keeps the details local. + +const logger = vi.hoisted(() => ({ logRenderError: vi.fn() })); +vi.mock("@/lib/log", () => logger); + +import { AppErrorBoundary } from "../app-error-boundary"; + +const failure = new TypeError("render failed"); + +function Broken(): never { + throw failure; +} + +beforeEach(() => { + logger.logRenderError.mockClear(); + // React reports every error a boundary catches on the console. + vi.spyOn(console, "error").mockImplementation(() => {}); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("AppErrorBoundary", () => { + it("renders the app while nothing throws", () => { + render(

the app

); + expect(screen.getByText("the app")).toBeInTheDocument(); + expect(screen.queryByText("Something went wrong")).toBeNull(); + expect(logger.logRenderError).not.toHaveBeenCalled(); + }); + + it("shows the recovery screen when a child throws while rendering", () => { + render(); + expect(screen.getByText("Something went wrong")).toBeInTheDocument(); + expect( + screen.getByText("Fleetify hit an unexpected error. Reload to continue — your sessions are saved."), + ).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument(); + }); + + it("reloads the window from the Reload button", () => { + const reload = vi.fn(); + vi.spyOn(window, "location", "get").mockReturnValue({ ...window.location, reload } as Location); + render(); + fireEvent.click(screen.getByRole("button", { name: "Reload" })); + expect(reload).toHaveBeenCalledTimes(1); + }); + + it("hands the error and where it happened to the logger", () => { + render(); + expect(logger.logRenderError).toHaveBeenCalledTimes(1); + const [error, componentStack] = logger.logRenderError.mock.calls[0]!; + expect(error).toBe(failure); + expect(componentStack).toContain("Broken"); + }); +}); diff --git a/src/components/__tests__/markdown-links.test.tsx b/src/components/__tests__/markdown-links.test.tsx new file mode 100644 index 0000000..a4defde --- /dev/null +++ b/src/components/__tests__/markdown-links.test.tsx @@ -0,0 +1,132 @@ +/** + * Links in rendered markdown never navigate the app's window. A page from + * another site would replace the app: there is no back button, and since the + * app's commands answer only its own origin, the page could do nothing but + * strand the user. A link to another site opens in the system browser; a + * link to another page of the app's origin does nothing; a fragment + * (`#usage`) still scrolls in place, without touching the app's URL. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent, createEvent } from "@testing-library/react"; +import ReactMarkdown from "react-markdown"; + +const { gitMock } = vi.hoisted(() => ({ + gitMock: { reviewDiff: vi.fn(), diagnoseFailure: vi.fn() }, +})); +vi.mock("@/lib/git-api", async () => { + const actual = await vi.importActual("@/lib/git-api"); + return { ...actual, git: gitMock }; +}); +vi.mock("@/lib/git-log", () => ({ glog: () => {} })); + +import { MarkdownPreview, planMdComponents } from "@/components/workspace/workspace-panel"; +import { ReviewDialog } from "@/components/git/review-dialog"; +import { RecoveryDialog } from "@/components/git/recovery-dialog"; +import { markdownComponents } from "@/components/marketplace/detail/markdown-image"; + +/** Markdown with one link of each kind. */ +const MARKDOWN = + "Read [the docs](https://example.com/docs), open [the dev server](http://localhost:3000/), " + + "see [setup](docs/setup.md), or jump to [usage](#usage)."; + +const win = window as unknown as { + electronAPI?: unknown; + happyDOM?: { setURL(url: string): void }; +}; +let openExternal: ReturnType; + +beforeEach(() => { + // The release app's page: the embedded backend's origin. + win.happyDOM?.setURL("http://127.0.0.1:8765/"); + openExternal = vi.fn(() => Promise.resolve(true)); + win.electronAPI = { openExternal }; +}); +afterEach(() => { + delete win.electronAPI; +}); + +/** Clicks the link named `name`, and says whether the webview would follow + * it in place: whether nothing in the app cancelled the click. */ +function followedInPlace(name: string): boolean { + const link = screen.getByRole("link", { name }); + const click = createEvent.click(link); + // happy-dom follows an uncancelled link click with window.open(href, + // "_self"); stub it so the test environment never navigates. + const open = vi.spyOn(window, "open").mockReturnValue(null); + try { + fireEvent(link, click); + } finally { + open.mockRestore(); + } + return !click.defaultPrevented; +} + +function expectLinksToStayInTheApp() { + expect(followedInPlace("the docs")).toBe(false); + expect(openExternal).toHaveBeenLastCalledWith("https://example.com/docs"); + expect(followedInPlace("the dev server")).toBe(false); + expect(openExternal).toHaveBeenLastCalledWith("http://localhost:3000/"); + // Another page of the app's own origin: nothing happens. + expect(followedInPlace("setup")).toBe(false); + // A fragment scrolls to its element; the app's URL and hash stay as they + // are (the app reads its own hash: `#logos` shows a dev-only gallery). + const target = document.createElement("h2"); + target.id = "usage"; + const scroll = vi.fn(); + target.scrollIntoView = scroll; + document.body.appendChild(target); + const before = window.location.href; + expect(followedInPlace("usage")).toBe(false); + expect(scroll).toHaveBeenCalledTimes(1); + expect(window.location.href).toBe(before); + target.remove(); + expect(openExternal).toHaveBeenCalledTimes(2); +} + +describe("markdown links never navigate the app's window", () => { + it("in a project's markdown preview", () => { + render(); + expectLinksToStayInTheApp(); + }); + + it("in the agent's plan", () => { + render({MARKDOWN}); + expectLinksToStayInTheApp(); + }); + + it("in the AI code review", async () => { + gitMock.reviewDiff.mockResolvedValue({ ok: true, review: MARKDOWN, cli: "claude" }); + render(); + await screen.findByRole("link", { name: "the docs" }); + expectLinksToStayInTheApp(); + }); + + it("in the AI failure diagnosis", async () => { + gitMock.diagnoseFailure.mockResolvedValue({ + ok: true, + summary: MARKDOWN, + action: "manual", + rationale: "", + command: null, + risk: "low", + cli: "claude", + }); + render( + , + ); + await screen.findByRole("link", { name: "the docs" }); + expectLinksToStayInTheApp(); + }); + + it("in a plugin's README and changelog", () => { + render({MARKDOWN}); + expectLinksToStayInTheApp(); + }); +}); diff --git a/src/components/__tests__/modal-escape-claim.test.tsx b/src/components/__tests__/modal-escape-claim.test.tsx new file mode 100644 index 0000000..6d47c50 --- /dev/null +++ b/src/components/__tests__/modal-escape-claim.test.tsx @@ -0,0 +1,63 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, fireEvent } from "@testing-library/react"; + +// The prompts picker loads the saved prompts when it opens. +vi.mock("@/lib/prompts-api", async (importOriginal) => ({ + ...(await importOriginal()), + listPrompts: vi.fn(async () => []), +})); + +import { ConfirmDialog } from "../ui/confirm-dialog"; +import { HelpDialog } from "../chat/help-dialog"; +import { PromptsPicker } from "../chat/prompts-picker"; +import { GithubAuthChoiceDialog } from "../git/github-auth-choice-dialog"; +import { escapeOwnedElsewhere, escapeWasClaimed } from "@/hooks/use-escape-to-stop"; + +const modalSurfaces = () => document.querySelectorAll("[aria-modal='true']"); + +/** A modal drawn over the chat owns the Escape that closes it, whichever + * window listener runs first. Before its handler runs, the open modal is an + * aria-modal surface, which Escape-to-stop and the permission cards leave + * alone. After it runs, the handler has claimed the key (claimEscape): the + * stop sees it handled, and a pending card sees it used. In a real browser + * the modal may already be unmounted by then, so only the claim is left. */ +function expectClaimsEscape(close: () => void) { + expect(modalSurfaces()).toHaveLength(1); + expect(escapeOwnedElsewhere(new KeyboardEvent("keydown", { key: "Escape" }))).toBe(true); + const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }); + fireEvent(document.body, escape); + expect(escape.defaultPrevented).toBe(true); + expect(escapeWasClaimed(escape)).toBe(true); + expect(close).toHaveBeenCalledTimes(1); +} + +describe("Modals claim the Escape that closes them", () => { + it("ConfirmDialog", () => { + const onCancel = vi.fn(); + render(); + expectClaimsEscape(onCancel); + }); + + it("HelpDialog", () => { + const onClose = vi.fn(); + render(); + expectClaimsEscape(onClose); + }); + + it("PromptsPicker, which is a modal surface while open and leaves none behind when closed", () => { + // Like Help, it covers the window with a scrim. As a modal surface it also + // keeps a pending permission card from taking ⌘↵ (its Enter picks a prompt). + const onClose = vi.fn(); + const { rerender } = render(); + expect(modalSurfaces()[0]).toHaveAccessibleName("Prompts"); + expectClaimsEscape(onClose); + rerender(); + expect(modalSurfaces()).toHaveLength(0); + }); + + it("GithubAuthChoiceDialog, while no sign-in is in flight", () => { + const onDismiss = vi.fn(); + render(); + expectClaimsEscape(onDismiss); + }); +}); diff --git a/src/components/__tests__/open-local-paths.test.tsx b/src/components/__tests__/open-local-paths.test.tsx new file mode 100644 index 0000000..eaa1b7a --- /dev/null +++ b/src/components/__tests__/open-local-paths.test.tsx @@ -0,0 +1,63 @@ +/** + * Local files and folders the app opens from its own UI go through the + * local-path bridge (`shell_open_path`), not the link opener, which refuses + * anything but a web or mail link: Library → "Open raw file" and the "Open + * in" menu's "Open folder". + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent } from "@testing-library/react"; +import { RowMenu } from "@/components/library-page"; +import { OpenInMenu } from "@/components/layout/open-in-menu"; +import type { LibraryItem } from "@/lib/library-api"; + +const win = window as unknown as { electronAPI?: unknown; fleetify?: unknown }; +let openPath: ReturnType; +let openExternal: ReturnType; + +beforeEach(() => { + openPath = vi.fn(() => Promise.resolve({ ok: true })); + openExternal = vi.fn(() => Promise.resolve({ ok: true })); + win.electronAPI = { + openPath, + openExternal, + showItemInFolder: vi.fn(() => Promise.resolve(true)), + }; + win.fleetify = { + detectEditors: vi.fn(() => Promise.resolve({ editors: [] })), + openInEditor: vi.fn(() => Promise.resolve({ ok: true })), + }; +}); +afterEach(() => { + delete win.electronAPI; + delete win.fleetify; +}); + +const prompt = { + id: "item-1", + kind: "prompt", + name: "Greet", + slug: "greet", + providers: [], + materialized: [], + created_at: "", + updated_at: "", + primary_path: "/home/u/.fleetify/prompts/greet.md", +} as unknown as LibraryItem; + +describe("local files and folders open through the local-path bridge", () => { + it("Library: Open raw file", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Actions" })); + fireEvent.click(screen.getByRole("menuitem", { name: /Open raw file/ })); + expect(openPath).toHaveBeenCalledWith("/home/u/.fleetify/prompts/greet.md"); + expect(openExternal).not.toHaveBeenCalled(); + }); + + it("Open in: Open folder", async () => { + render(); + fireEvent.click(screen.getByRole("button", { name: /Open in/ })); + fireEvent.click(await screen.findByRole("button", { name: "Open folder" })); + expect(openPath).toHaveBeenCalledWith("/home/u/repo"); + expect(openExternal).not.toHaveBeenCalled(); + }); +}); diff --git a/src/components/__tests__/overlay-escape.test.tsx b/src/components/__tests__/overlay-escape.test.tsx new file mode 100644 index 0000000..9151e7e --- /dev/null +++ b/src/components/__tests__/overlay-escape.test.tsx @@ -0,0 +1,56 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, fireEvent } from "@testing-library/react"; +import { CommandPalette } from "../command-palette"; +import { FeedbackModal } from "../feedback-modal"; +import { escapeOwnedElsewhere, escapeWasClaimed } from "@/hooks/use-escape-to-stop"; + +const modalSurfaces = () => document.querySelectorAll("[aria-modal='true']"); + +/** The one aria-modal element on the page. */ +function modalSurface(): Element { + expect(modalSurfaces()).toHaveLength(1); + return modalSurfaces()[0]!; +} + +/** Escape-to-stop and the permission cards leave alone an Escape that an + * overlay owns. That holds whichever window listener runs first: + * - before the overlay's handler runs, the open overlay is an aria-modal surface; + * - after it runs, the handler has claimed the key (claimEscape), which marks + * it handled for the stop and tells the cards it was used. */ +function expectOwnsEscape(close: () => void) { + expect(escapeOwnedElsewhere(new KeyboardEvent("keydown", { key: "Escape" }))).toBe(true); + const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }); + fireEvent(document.body, escape); + expect(escape.defaultPrevented).toBe(true); + expect(escapeWasClaimed(escape)).toBe(true); + expect(close).toHaveBeenCalledTimes(1); +} + +describe("CommandPalette owns Escape", () => { + it("is a modal surface while open and marks Escape handled when it closes", () => { + const onClose = vi.fn(); + render(); + expect(modalSurface()).toHaveAccessibleName("Command palette"); + expectOwnsEscape(onClose); + }); + + it("leaves no modal surface behind while closed", () => { + // App.tsx keeps the palette mounted after its first open. + render(); + expect(modalSurfaces()).toHaveLength(0); + }); +}); + +describe("FeedbackModal owns Escape", () => { + it("is a modal surface while open and marks Escape handled when it closes", () => { + const onClose = vi.fn(); + render(); + expect(modalSurface()).toHaveTextContent("Send Feedback"); + expectOwnsEscape(onClose); + }); + + it("leaves no modal surface behind while closed", () => { + render(); + expect(modalSurfaces()).toHaveLength(0); + }); +}); diff --git a/src/components/agent/__tests__/new-agent-dialog.test.tsx b/src/components/agent/__tests__/new-agent-dialog.test.tsx index ba40003..c18fd99 100644 --- a/src/components/agent/__tests__/new-agent-dialog.test.tsx +++ b/src/components/agent/__tests__/new-agent-dialog.test.tsx @@ -6,6 +6,7 @@ */ import { describe, it, expect, vi, beforeEach } from "vitest"; import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { escapeOwnedElsewhere, escapeWasClaimed } from "@/hooks/use-escape-to-stop"; const { createSessionMock } = vi.hoisted(() => ({ createSessionMock: vi.fn().mockResolvedValue({ id: "s1" }), @@ -158,3 +159,26 @@ describe("NewAgentDialog — use_worktree wiring + folderInGit", () => { Object.defineProperty(window, "electronAPI", { configurable: true, value: original }); }); }); + +// The dialog is drawn over the chat. Escape-to-stop must leave alone the Escape +// that closes it, whichever listener runs first. Before the dialog's handler +// runs, the open dialog is an aria-modal surface. After it runs, the key is +// marked handled. +describe("NewAgentDialog owns Escape", () => { + it("is a modal surface while open and marks Escape handled when it closes", async () => { + const { NewAgentDialog } = await loadDialog(); + const onClose = vi.fn(); + render(); + const modal = document.querySelectorAll("[aria-modal='true']"); + expect(modal).toHaveLength(1); + expect(modal[0]).toHaveAccessibleName("New Agent"); + expect(escapeOwnedElsewhere(new KeyboardEvent("keydown", { key: "Escape" }))).toBe(true); + // The handler claims the key: marked handled for the stop, and used as far + // as a pending permission card is concerned. + const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }); + fireEvent(document.body, escape); + expect(escape.defaultPrevented).toBe(true); + expect(escapeWasClaimed(escape)).toBe(true); + expect(onClose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/components/agent/new-agent-dialog.tsx b/src/components/agent/new-agent-dialog.tsx index 2756d06..9713d1a 100644 --- a/src/components/agent/new-agent-dialog.tsx +++ b/src/components/agent/new-agent-dialog.tsx @@ -1,4 +1,5 @@ import { useState, useEffect, useRef } from "react"; +import { claimEscape } from "@/hooks/use-escape-to-stop"; import { X, FolderOpen, Clock, ChevronDown, Check, Sparkles, Wand2 } from "lucide-react"; import { ClaudeLogo, OpenAILogo, KimiLogo } from "@/components/ui/provider-logo"; import { createSession, fetchClaudeSessions, fetchCodexSessions, apiFetch, type ClaudeSession } from "@/lib/api"; @@ -307,7 +308,9 @@ export function NewAgentView({ onClose }: Props) { }, [showTpl]); useEffect(() => { setTimeout(() => pathRef.current?.focus(), 80); }, []); useEffect(() => { - const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }; + // Claim the key, so the chat underneath neither stops its stream nor + // answers a pending permission card with it. + const h = (e: KeyboardEvent) => { if (e.key === "Escape") { claimEscape(e); onClose(); } }; document.addEventListener("keydown", h); return () => document.removeEventListener("keydown", h); }, [onClose]); useEffect(() => { @@ -598,7 +601,7 @@ export function NewAgentView({ onClose }: Props) { {/* Center wrapper */}
-
{ + state: State = { failed: false }; + + static getDerivedStateFromError(): State { + return { failed: true }; + } + + componentDidCatch(error: unknown, info: ErrorInfo): void { + logRenderError(error, info.componentStack); + } + + render(): ReactNode { + return this.state.failed ? : this.props.children; + } +} + +function RecoveryScreen() { + return ( +
+
+

+ Something went wrong +

+

+ Fleetify hit an unexpected error. Reload to continue — your sessions are saved. +

+ +
+
+ ); +} diff --git a/src/components/chat/__tests__/card-shortcuts.test.tsx b/src/components/chat/__tests__/card-shortcuts.test.tsx new file mode 100644 index 0000000..d0a3389 --- /dev/null +++ b/src/components/chat/__tests__/card-shortcuts.test.tsx @@ -0,0 +1,186 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import type { Platform } from "@/lib/utils"; + +// Permission cards answer Mod+Enter (allow) and Mod+Shift+Enter (always +// allow), where Mod is the key their labels show: ⌘ on macOS, Ctrl on +// Windows and Linux (`formatShortcut`, from `getPlatform`). They leave the +// key alone when another handler already acted on it, or when it was typed +// in any field: while a card waits the composer is locked and the card has +// no fields, so a field with focus is another box whose own Mod+Enter sends, +// such as the Fleet dispatch reply box. + +const platform = vi.hoisted(() => ({ current: "linux" as Platform })); +vi.mock("@/lib/utils", async (importOriginal) => ({ + ...(await importOriginal()), + getPlatform: () => platform.current, +})); +// The composer needs these stubbed to mount in happy-dom; the dispatch +// reply box sends through dispatchFollowUp. +vi.mock("@/lib/posthog", () => ({ capture: vi.fn(), optIn: vi.fn(), optOut: vi.fn() })); +const api = vi.hoisted(() => ({ dispatchFollowUp: vi.fn(async () => ({ ok: true })) })); +vi.mock("@/lib/api", async (importOriginal) => ({ + ...(await importOriginal()), + enhancePrompt: vi.fn(async () => ({ no_op: true, enhanced: "", rationale: null })), + apiFetch: vi.fn(async () => new Response("[]", { status: 200 })), + dispatchFollowUp: api.dispatchFollowUp, +})); + +import { ChatInput } from "../chat-input"; +import { PermissionDialog } from "../permission-dialog"; +import { MessageContent } from "../message-content"; +import { useAppStore } from "@/stores/app-store"; +import type { PermissionRequest } from "@/stores/chat-store"; +import type { ChatMessage } from "@/types/chat"; + +const bash: PermissionRequest = { id: "req-1", tool_name: "Bash", command: "ls" }; + +type Card = "the composer's inline card" | "the permission dialog"; +const CARDS: Card[] = ["the composer's inline card", "the permission dialog"]; + +const DISPATCH_RESULT: ChatMessage = { + id: "m-1", + role: "system", + timestamp: "2026-11-17T00:00:00Z", + content: [{ + type: "dispatch_result", + agent_id: "agent-x", + agent_name: "Worker", + task: "Run the tests", + success: true, + summary: "All green.", + }], +}; + +/** A pending card inside its chat, as ChatView renders it: the chat also + * holds a dispatch result with its reply box, a field of its own (the + * title rename) and a button whose own handler acts on Mod+Enter. */ +function renderCard(card: Card) { + const answer = { deny: vi.fn(), allow: vi.fn(), allowAlways: vi.fn() }; + render( +
+ + + + {card === "the composer's inline card" ? ( + + ) : ( + + )} +
, + ); + return answer; +} + +function expectPending(answer: ReturnType) { + expect(answer.allow).not.toHaveBeenCalled(); + expect(answer.allowAlways).not.toHaveBeenCalled(); + expect(answer.deny).not.toHaveBeenCalled(); +} + +beforeEach(() => { + vi.clearAllMocks(); + useAppStore.setState({ + splitPaneIds: [], focusedPaneIdx: 0, activeSessionId: "agent-a", staffSessionId: "staff-1", + }); +}); + +describe.each(CARDS)("%s", (card) => { + describe.each(["windows", "linux"] as const)("on %s", (os) => { + beforeEach(() => { platform.current = os; }); + + it("Ctrl+Enter allows and Ctrl+Shift+Enter always allows", () => { + const answer = renderCard(card); + fireEvent.keyDown(document.body, { key: "Enter", ctrlKey: true }); + expect(answer.allow).toHaveBeenCalledTimes(1); + expect(answer.allow).toHaveBeenCalledWith("req-1", "Bash"); + fireEvent.keyDown(document.body, { key: "Enter", ctrlKey: true, shiftKey: true }); + expect(answer.allowAlways).toHaveBeenCalledTimes(1); + expect(answer.allow).toHaveBeenCalledTimes(1); + }); + + it("the Windows/Super key with Enter answers nothing", () => { + const answer = renderCard(card); + fireEvent.keyDown(document.body, { key: "Enter", metaKey: true }); + fireEvent.keyDown(document.body, { key: "Enter", metaKey: true, shiftKey: true }); + expectPending(answer); + }); + }); + + describe("on macOS", () => { + beforeEach(() => { platform.current = "mac"; }); + + it("⌘↵ allows and ⌘⇧↵ always allows", () => { + const answer = renderCard(card); + fireEvent.keyDown(document.body, { key: "Enter", metaKey: true }); + expect(answer.allow).toHaveBeenCalledTimes(1); + fireEvent.keyDown(document.body, { key: "Enter", metaKey: true, shiftKey: true }); + expect(answer.allowAlways).toHaveBeenCalledTimes(1); + }); + + it("Ctrl+Enter and Ctrl+Shift+Enter do nothing", () => { + const answer = renderCard(card); + fireEvent.keyDown(document.body, { key: "Enter", ctrlKey: true }); + fireEvent.keyDown(document.body, { key: "Enter", ctrlKey: true, shiftKey: true }); + expectPending(answer); + }); + }); + + describe.each([ + ["mac", { metaKey: true }], + ["linux", { ctrlKey: true }], + ] as const)("on %s, the card's own shortcut", (os, mod) => { + beforeEach(() => { platform.current = os; }); + + it("typed in the Fleet dispatch reply box sends the reply and leaves the card pending", async () => { + const answer = renderCard(card); + fireEvent.click(screen.getByTitle("Reply to this agent without leaving Fleetify")); + const reply = screen.getByPlaceholderText("Follow-up to Worker…"); + // Nothing typed yet: the box keeps the key and sends nothing. + fireEvent.keyDown(reply, { key: "Enter", ...mod }); + fireEvent.keyDown(reply, { key: "Enter", shiftKey: true, ...mod }); + expectPending(answer); + + fireEvent.change(reply, { target: { value: "rerun with --verbose" } }); + fireEvent.keyDown(reply, { key: "Enter", ...mod }); + await waitFor(() => + expect(api.dispatchFollowUp).toHaveBeenCalledWith("agent-x", "rerun with --verbose", "staff-1"), + ); + expectPending(answer); + }); + + it("typed in a field inside the chat leaves the card pending, while Escape there still denies", () => { + const answer = renderCard(card); + const title = screen.getByLabelText("chat title"); + fireEvent.keyDown(title, { key: "Enter", ...mod }); + fireEvent.keyDown(title, { key: "Enter", shiftKey: true, ...mod }); + expectPending(answer); + // Escape keeps its own rules: a field inside the chat doesn't own it. + fireEvent.keyDown(title, { key: "Escape" }); + expect(answer.deny).toHaveBeenCalledTimes(1); + }); + + it("that another handler already acted on leaves the card pending", () => { + const answer = renderCard(card); + const button = screen.getByRole("button", { name: "acts on Enter" }); + fireEvent.keyDown(button, { key: "Enter", ...mod }); + fireEvent.keyDown(button, { key: "Enter", shiftKey: true, ...mod }); + expectPending(answer); + // Control: pressed on the page, it answers. + fireEvent.keyDown(document.body, { key: "Enter", ...mod }); + expect(answer.allow).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/src/components/chat/__tests__/chat-links.test.tsx b/src/components/chat/__tests__/chat-links.test.tsx new file mode 100644 index 0000000..e0098c9 --- /dev/null +++ b/src/components/chat/__tests__/chat-links.test.tsx @@ -0,0 +1,109 @@ +/** + * Links in chat messages, and citation cards. A chat link to a web page used + * to be a `target="_blank"` link, and Tauri's webview swallows those: it + * opened nothing. Now it opens in the system browser, like every markdown + * link the app shows. A link to a project file still opens the file in the + * app, and a fragment never changes the app's URL. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent, createEvent } from "@testing-library/react"; +import { MarkdownBody } from "@/components/chat/message-content"; +import { CitationCard } from "@/components/chat/citation-card"; +import { useAppStore } from "@/stores/app-store"; +import type { Session } from "@/types/session"; + +const MARKDOWN = + "Read [the docs](https://example.com/docs), jump to [usage](#usage), " + + "or open [main](src/main.rs:10)."; + +const win = window as unknown as { + electronAPI?: unknown; + happyDOM?: { setURL(url: string): void }; +}; +let openExternal: ReturnType; +let openFile: ReturnType; + +beforeEach(() => { + // The release app's page: the embedded backend's origin. + win.happyDOM?.setURL("http://127.0.0.1:8765/"); + openExternal = vi.fn(() => Promise.resolve(true)); + win.electronAPI = { openExternal }; + openFile = vi.fn(); + useAppStore.setState({ + sessions: [{ id: "s1", project_path: "/repo" } as Session], + activeSessionId: "s1", + openFile, + }); +}); +afterEach(() => { + delete win.electronAPI; +}); + +/** Clicks the link named `name`, and says whether the webview would follow + * it itself: whether nothing in the app cancelled the click. */ +function followedInPlace(name: string): boolean { + const link = screen.getByRole("link", { name }); + const click = createEvent.click(link); + // happy-dom follows an uncancelled link click with window.open; stub it so + // the test environment never navigates. + const open = vi.spyOn(window, "open").mockReturnValue(null); + try { + fireEvent(link, click); + } finally { + open.mockRestore(); + } + return !click.defaultPrevented; +} + +describe("chat links", () => { + it("open a web link in the system browser", () => { + render(); + expect(followedInPlace("the docs")).toBe(false); + expect(openExternal).toHaveBeenCalledWith("https://example.com/docs"); + expect(openFile).not.toHaveBeenCalled(); + }); + + it("keep a fragment link in the app: no browser, no URL change", () => { + render(); + const before = window.location.href; + followedInPlace("usage"); + expect(window.location.href).toBe(before); + expect(openExternal).not.toHaveBeenCalled(); + expect(openFile).not.toHaveBeenCalled(); + }); + + it("still open a project file in the app", () => { + render(); + expect(followedInPlace("main")).toBe(false); + expect(openFile).toHaveBeenCalledWith("/repo/src/main.rs"); + expect(openExternal).not.toHaveBeenCalled(); + }); +}); + +describe("citation cards", () => { + it("open their source in the system browser", () => { + render( + , + ); + fireEvent.click(screen.getByRole("button", { name: /The source/ })); + expect(openExternal).toHaveBeenCalledWith("https://example.com/source"); + }); + + it("open nothing for a source that isn't a web link", () => { + render( + , + ); + fireEvent.click(screen.getByRole("button", { name: /A script/ })); + expect(openExternal).not.toHaveBeenCalled(); + }); +}); diff --git a/src/components/chat/__tests__/chat-view-escape.test.tsx b/src/components/chat/__tests__/chat-view-escape.test.tsx new file mode 100644 index 0000000..f5d7348 --- /dev/null +++ b/src/components/chat/__tests__/chat-view-escape.test.tsx @@ -0,0 +1,77 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { useRef } from "react"; +import { render, fireEvent, act } from "@testing-library/react"; +import { usePaneEscapeToStop } from "../chat-view"; +import { useAppStore } from "@/stores/app-store"; + +/** One chat as ChatView renders it: a surface with its composer inside, + * registering Escape-to-stop exactly once. */ +function Chat({ paneIdx, streaming, onStop }: { + paneIdx?: number; + streaming: boolean; + onStop: () => void; +}) { + const surface = useRef(null); + usePaneEscapeToStop(surface, paneIdx, streaming, onStop); + return ( +
+ "), + add(""), + add(""), + add(""), + add("

draft

").firstElementChild!, + ]; + for (const field of fields) { + expect(isTextEntry(field), field.outerHTML).toBe(true); + for (const types of [TEXT, LINK, HTML]) { + for (const type of DRAG_TYPES) { + expect(drag(type, field, types).defaultPrevented, `${type} ${types} on ${field.outerHTML}`).toBe(false); + } + } + } + }); + + it("cancels a file drop nothing handles, even over a text field", () => { + // A text field can't take a file, and the engine may load it instead. + for (const field of [add(""), add("")]) { + for (const type of DRAG_TYPES) { + expect(drag(type, field, FILE).defaultPrevented, `${type} on ${field.outerHTML}`).toBe(true); + } + } + }); + + it("takes a drop on a field you can't type in", () => { + // The engine loads what's dropped on these, as on any other element. + for (const field of [ + add(""), + add(""), + add(""), + add(""), + ]) { + expect(isTextEntry(field), field.outerHTML).toBe(false); + expect(drag("drop", field, LINK).defaultPrevented, field.outerHTML).toBe(true); + } + }); + + it("stops when it is uninstalled", () => { + uninstall(); + const panel = add("
"); + expect(drag("drop", panel, LINK).defaultPrevented).toBe(false); + }); +}); diff --git a/src/lib/__tests__/links.test.ts b/src/lib/__tests__/links.test.ts new file mode 100644 index 0000000..2f38689 --- /dev/null +++ b/src/lib/__tests__/links.test.ts @@ -0,0 +1,128 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { linkTarget, openExternalUrl, openLink, scrollToFragment } from "@/lib/links"; + +/** The page a release build shows: the embedded backend's origin. */ +const APP = "http://127.0.0.1:8765/"; +/** The page a debug build shows: Vite on devUrl. */ +const DEV = "http://localhost:3000/"; + +describe("linkTarget", () => { + it("reads a fragment of the current page as the element to scroll to", () => { + expect(linkTarget("#usage", APP)).toEqual({ kind: "anchor", id: "usage" }); + expect(linkTarget("#", APP)).toEqual({ kind: "anchor", id: "" }); + expect(linkTarget("http://127.0.0.1:8765/#usage", APP)).toEqual({ kind: "anchor", id: "usage" }); + expect(linkTarget("#caf%C3%A9", APP)).toEqual({ kind: "anchor", id: "café" }); + // A fragment that doesn't decode is kept as it is. + expect(linkTarget("#100%", APP)).toEqual({ kind: "anchor", id: "100%" }); + }); + + it("sends a link to another site to the system browser", () => { + expect(linkTarget("https://example.com/docs?q=1", APP)).toEqual({ + kind: "external", + url: "https://example.com/docs?q=1", + }); + // A dev server is another site to the release app. + expect(linkTarget("http://localhost:3000/", APP)).toEqual({ + kind: "external", + url: "http://localhost:3000/", + }); + // So is the same host on another port. + expect(linkTarget("http://127.0.0.1:8899/", APP)).toEqual({ + kind: "external", + url: "http://127.0.0.1:8899/", + }); + expect(linkTarget("mailto:team@example.com", APP)).toEqual({ + kind: "external", + url: "mailto:team@example.com", + }); + }); + + it("never follows a link to another page of the app's own origin", () => { + // A relative link in a README resolves against the app's page. + expect(linkTarget("docs/setup.md", APP)).toEqual({ kind: "blocked" }); + expect(linkTarget("/settings", APP)).toEqual({ kind: "blocked" }); + expect(linkTarget("http://localhost:3000/other", DEV)).toEqual({ kind: "blocked" }); + }); + + it("hands no other scheme to the system", () => { + for (const href of [ + "file:///etc/hosts", + "javascript:alert(1)", + "data:text/html,hi", + "vscode://file/tmp/x", + "tauri://localhost/", + "http://[not a host", + "", + undefined, + null, + ]) { + expect(linkTarget(href, APP), String(href)).toEqual({ kind: "blocked" }); + } + }); +}); + +describe("scrollToFragment", () => { + afterEach(() => { + document.body.innerHTML = ""; + }); + + it("scrolls to the element and leaves the page's URL alone", () => { + // The app reads its own hash (`#logos` swaps the app for a dev gallery): + // a link must never set it. + const heading = document.createElement("h2"); + heading.id = "logos"; + document.body.appendChild(heading); + const scroll = vi.fn(); + heading.scrollIntoView = scroll; + const before = window.location.href; + scrollToFragment("logos"); + expect(scroll).toHaveBeenCalledTimes(1); + expect(window.location.href).toBe(before); + expect(window.location.hash).toBe(""); + }); + + it("does nothing when no element has that id", () => { + expect(() => scrollToFragment("nowhere")).not.toThrow(); + expect(() => scrollToFragment("")).not.toThrow(); + expect(window.location.hash).toBe(""); + }); +}); + +describe("openLink", () => { + const win = window as unknown as { electronAPI?: unknown }; + afterEach(() => { + delete win.electronAPI; + }); + + it("opens a web or mail link in the system browser, and nothing else", () => { + const openExternal = vi.fn(() => Promise.resolve(true)); + win.electronAPI = { openExternal }; + openLink("https://example.com/source"); + openLink("mailto:team@example.com"); + for (const href of ["javascript:alert(1)", "file:///etc/hosts", "#usage", "/settings", "", undefined]) { + openLink(href); + } + expect(openExternal.mock.calls).toEqual([["https://example.com/source"], ["mailto:team@example.com"]]); + }); +}); + +describe("openExternalUrl", () => { + const win = window as unknown as { electronAPI?: unknown }; + afterEach(() => { + delete win.electronAPI; + vi.restoreAllMocks(); + }); + + it("opens the URL through the app's bridge", () => { + const openExternal = vi.fn(() => Promise.resolve(true)); + win.electronAPI = { openExternal }; + openExternalUrl("https://example.com/"); + expect(openExternal).toHaveBeenCalledWith("https://example.com/"); + }); + + it("opens a new tab where there is no bridge (the renderer in a browser)", () => { + const open = vi.spyOn(window, "open").mockReturnValue(null); + openExternalUrl("https://example.com/"); + expect(open).toHaveBeenCalledWith("https://example.com/", "_blank", "noopener,noreferrer"); + }); +}); diff --git a/src/lib/__tests__/log.test.ts b/src/lib/__tests__/log.test.ts new file mode 100644 index 0000000..cd0bfd5 --- /dev/null +++ b/src/lib/__tests__/log.test.ts @@ -0,0 +1,100 @@ +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; + +// frontend_error goes to PostHog. An error's message and stack can carry +// file paths, message text or tokens, so the event keeps only what kind of +// error it was. The local log keeps the details. + +const analytics = vi.hoisted(() => ({ + capture: vi.fn(), + isReady: vi.fn(() => true), +})); +vi.mock("@/lib/posthog", () => analytics); + +import { installGlobalErrorCapture, logRenderError } from "../log"; + +beforeAll(() => { + vi.spyOn(console, "error").mockImplementation(() => {}); + installGlobalErrorCapture(); +}); + +beforeEach(() => { + analytics.capture.mockClear(); +}); + +/** Wait until the lazy analytics import has delivered `count` events. */ +async function captured(count: number) { + await vi.waitFor(() => expect(analytics.capture).toHaveBeenCalledTimes(count)); + return analytics.capture.mock.calls; +} + +function rejectUnhandled(reason: unknown) { + const event = new Event("unhandledrejection"); + Object.defineProperty(event, "reason", { value: reason }); + window.dispatchEvent(event); +} + +describe("frontend_error", () => { + it("sends an uncaught error's class, never its message, file or stack", async () => { + const error = new TypeError("could not read /home/u/notes/secret.md"); + window.dispatchEvent( + new ErrorEvent("error", { + error, + message: error.message, + filename: "tauri://localhost/assets/index.js", + lineno: 3, + colno: 7, + }), + ); + expect(await captured(1)).toEqual([ + ["frontend_error", { source: "uncaught", error_type: "TypeError" }], + ]); + }); + + it("sends a rejection's class, or its JS type when it isn't an Error", async () => { + // One at a time: when several lazy imports of a mocked module are in + // flight at once, only the first gets vitest's mock. + rejectUnhandled(new RangeError("token sk-test-123 was rejected")); + await captured(1); + rejectUnhandled("prompt: refactor the auth module"); + await captured(2); + rejectUnhandled(undefined); + expect(await captured(3)).toEqual([ + ["frontend_error", { source: "unhandled-rejection", error_type: "RangeError" }], + ["frontend_error", { source: "unhandled-rejection", error_type: "string" }], + ["frontend_error", { source: "unhandled-rejection", error_type: "unknown" }], + ]); + }); +}); + +describe("render errors from the root error boundary", () => { + it("keeps the details in the local log and sends only the error's class", async () => { + const appLog = vi.fn(async () => {}); + (window as unknown as { electronAPI: unknown }).electronAPI = { appLog }; + try { + const error = new TypeError("could not read /home/u/notes/secret.md"); + logRenderError(error, "\n at Broken\n at App"); + + // Local log: the message, stack and component stack, at error level. + expect(appLog).toHaveBeenCalledWith( + "error", + "renderer.render-error", + "could not read /home/u/notes/secret.md", + { stack: error.stack, componentStack: "\n at Broken\n at App" }, + ); + // Product analytics: the class only. + expect(await captured(1)).toEqual([ + ["frontend_error", { source: "render", error_type: "TypeError" }], + ]); + } finally { + delete (window as unknown as { electronAPI?: unknown }).electronAPI; + } + }); + + it("sends nothing to product analytics while it is off", async () => { + analytics.isReady.mockReturnValueOnce(false); + logRenderError(new Error("boom"), null); + // Give the lazy import time to run. + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(analytics.capture).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/__tests__/posthog-network.test.ts b/src/lib/__tests__/posthog-network.test.ts new file mode 100644 index 0000000..6a2f264 --- /dev/null +++ b/src/lib/__tests__/posthog-network.test.ts @@ -0,0 +1,96 @@ +/** + * The real posthog-js, started by the wrapper with Fleetify's real options, + * makes no request once product analytics is turned off: not the batch it + * had queued, not the 3 s flush, not the beacon it sends when the page + * hides. fetch, XMLHttpRequest and navigator.sendBeacon are all stubbed + * before posthog-js loads, so nothing here can reach the network. + * + * One test, because posthog-js is a singleton that `vi.resetModules()` + * doesn't reload. + */ +import { it, expect, vi, beforeEach, afterEach } from "vitest"; + +let fetches: unknown[][]; +let xhrSends: number; +let beacons: unknown[][]; + +class FakeXMLHttpRequest { + withCredentials = false; + readyState = 0; + status = 0; + open = vi.fn(); + setRequestHeader = vi.fn(); + abort = vi.fn(); + send = vi.fn(() => { + xhrSends += 1; + }); +} + +const sent = () => ({ fetch: fetches.length, xhr: xhrSends, beacon: beacons.length }); + +/** Run posthog-js's timers, then let its async compression finish. */ +async function runFor(ms: number) { + await vi.advanceTimersByTimeAsync(ms); + vi.useRealTimers(); + await new Promise((resolve) => setTimeout(resolve, 100)); + vi.useFakeTimers(); +} + +beforeEach(() => { + fetches = []; + xhrSends = 0; + beacons = []; + vi.stubGlobal( + "fetch", + vi.fn(async (...args: unknown[]) => { + fetches.push(args); + return new Response("{}", { status: 200 }); + }), + ); + vi.stubGlobal("XMLHttpRequest", FakeXMLHttpRequest); + Object.defineProperty(navigator, "sendBeacon", { + configurable: true, + writable: true, + value: vi.fn((...args: unknown[]) => { + beacons.push(args); + return true; + }), + }); + // happy-dom reports webdriver, which posthog-js treats as a bot and drops + // every event for. A real WebView doesn't. + Object.defineProperty(navigator, "webdriver", { configurable: true, value: false }); + vi.stubEnv("VITE_POSTHOG_KEY", "phc_dummy_test_key"); + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + delete (navigator as unknown as { sendBeacon?: unknown }).sendBeacon; + delete (navigator as unknown as { webdriver?: unknown }).webdriver; + localStorage.clear(); +}); + +it("sends nothing after an opt-out: not the queued batch, the 3 s flush or the pagehide beacon", async () => { + const analytics = await import("@/lib/posthog"); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + expect(analytics.isReady()).toBe(true); + // Starting it fetched nothing: no remote config, no flags, no scripts. + expect(sent()).toEqual({ fetch: 0, xhr: 0, beacon: 0 }); + expect(document.querySelectorAll("script[src]")).toHaveLength(0); + + // Control: while opted in, the 3 s flush does reach the stubbed transport, + // so the checks below can see a request if one is made. + analytics.capture("message_sent", { text_length: 3 }); + await runFor(3_500); + expect(sent().fetch).toBeGreaterThan(0); + const beforeOptOut = sent(); + + analytics.capture("message_sent", { text_length: 4 }); + analytics.optOut(); + await runFor(3_500); + window.dispatchEvent(new Event("pagehide")); + await runFor(1_000); + expect(sent()).toEqual(beforeOptOut); +}); diff --git a/src/lib/__tests__/posthog-person-properties.test.ts b/src/lib/__tests__/posthog-person-properties.test.ts new file mode 100644 index 0000000..a40b4b5 --- /dev/null +++ b/src/lib/__tests__/posthog-person-properties.test.ts @@ -0,0 +1,77 @@ +/** + * The real posthog-js, started by the wrapper with Fleetify's real options, + * identifies with the account id only. On its own, posthog-js attaches + * `$set_once` person properties to `$identify` (the first address and + * referrer it saw on this device and in this session); none of them, and no + * `$set`, may reach PostHog. + * + * Events are read from posthog-js's `eventCaptured` hook, which sees each + * event as it is queued for sending. fetch, XMLHttpRequest and + * navigator.sendBeacon are stubbed before posthog-js loads, so nothing here + * can reach the network. + * + * Its own file: posthog-js is a singleton that `vi.resetModules()` doesn't + * reload. + */ +import { it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { CaptureResult } from "posthog-js"; + +class FakeXMLHttpRequest { + withCredentials = false; + readyState = 0; + status = 0; + open = vi.fn(); + setRequestHeader = vi.fn(); + abort = vi.fn(); + send = vi.fn(); +} + +beforeEach(() => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 }))); + vi.stubGlobal("XMLHttpRequest", FakeXMLHttpRequest); + Object.defineProperty(navigator, "sendBeacon", { + configurable: true, + writable: true, + value: vi.fn(() => true), + }); + // happy-dom reports webdriver, which posthog-js treats as a bot and drops + // every event for. A real WebView doesn't. + Object.defineProperty(navigator, "webdriver", { configurable: true, value: false }); + vi.stubEnv("VITE_POSTHOG_KEY", "phc_dummy_test_key"); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + delete (navigator as unknown as { sendBeacon?: unknown }).sendBeacon; + delete (navigator as unknown as { webdriver?: unknown }).webdriver; + localStorage.clear(); +}); + +it("sends $identify with the account id and no person properties", async () => { + const analytics = await import("@/lib/posthog"); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + expect(analytics.isReady()).toBe(true); + + const { default: posthog } = await import("posthog-js"); + const queued: CaptureResult[] = []; + posthog.on("eventCaptured", (event: CaptureResult) => queued.push(event)); + + analytics.capture("message_sent", { text_length: 3 }); + analytics.identifyUser("user-1"); + analytics.capture("message_sent", { text_length: 4 }); + + const identify = queued.find((e) => e.event === "$identify"); + expect(identify).toBeDefined(); + // What identify is for: linking the device's events to the account. + expect(identify!.properties.distinct_id).toBe("user-1"); + expect(identify!.properties.$anon_distinct_id).toBe("device-1"); + + expect(queued.map((e) => e.event)).toEqual(["message_sent", "$identify", "message_sent"]); + for (const event of queued) { + expect(event.$set_once).toBeUndefined(); + expect(event.$set).toBeUndefined(); + expect(event.properties.$set_once).toBeUndefined(); + expect(event.properties.$set).toBeUndefined(); + } +}); diff --git a/src/lib/__tests__/posthog-sign-out.test.ts b/src/lib/__tests__/posthog-sign-out.test.ts new file mode 100644 index 0000000..5ef49fa --- /dev/null +++ b/src/lib/__tests__/posthog-sign-out.test.ts @@ -0,0 +1,94 @@ +/** + * Signing out with the real posthog-js, started by the wrapper with + * Fleetify's real options. After `resetIdentity()` the app's events no + * longer carry the account that signed out (on a shared machine, the next + * account must not be linked to it), Fleetify's own `platform` property is + * back, no flags are fetched (reset() asks for them again), and an opt-out + * made in this session survives (reset() clears posthog-js's stored consent). + * + * Events are read from posthog-js's `eventCaptured` hook. fetch, + * XMLHttpRequest and navigator.sendBeacon are stubbed before posthog-js + * loads, so nothing here can reach the network. + * + * Its own file: posthog-js is a singleton that `vi.resetModules()` doesn't + * reload. + */ +import { it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { CaptureResult } from "posthog-js"; + +class FakeXMLHttpRequest { + withCredentials = false; + readyState = 0; + status = 0; + open = vi.fn(); + setRequestHeader = vi.fn(); + abort = vi.fn(); + send = vi.fn(); +} + +let fetched: string[]; + +beforeEach(() => { + fetched = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: unknown) => { + fetched.push(String(input)); + return new Response("{}", { status: 200 }); + }), + ); + vi.stubGlobal("XMLHttpRequest", FakeXMLHttpRequest); + Object.defineProperty(navigator, "sendBeacon", { + configurable: true, + writable: true, + value: vi.fn(() => true), + }); + // happy-dom reports webdriver, which posthog-js treats as a bot and drops + // every event for. A real WebView doesn't. + Object.defineProperty(navigator, "webdriver", { configurable: true, value: false }); + vi.stubEnv("VITE_POSTHOG_KEY", "phc_dummy_test_key"); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + delete (navigator as unknown as { sendBeacon?: unknown }).sendBeacon; + delete (navigator as unknown as { webdriver?: unknown }).webdriver; + localStorage.clear(); +}); + +it("drops the signed-out account from later events, fetches no flags and keeps an opt-out", async () => { + const analytics = await import("@/lib/posthog"); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + const { default: posthog } = await import("posthog-js"); + const queued: CaptureResult[] = []; + posthog.on("eventCaptured", (event: CaptureResult) => queued.push(event)); + + analytics.identifyUser("user-1"); + analytics.capture("message_sent", { text_length: 1 }); + const signedIn = queued.at(-1)!; + expect(signedIn.properties.distinct_id).toBe("user-1"); + expect(signedIn.properties.$user_id).toBe("user-1"); + + analytics.resetIdentity(); + analytics.capture("message_sent", { text_length: 2 }); + const signedOut = queued.at(-1)!; + // A new anonymous id: not the account, and not the device id, which + // PostHog has linked to the account. + expect(signedOut.properties.distinct_id).not.toBe("user-1"); + expect(signedOut.properties.distinct_id).not.toBe("device-1"); + expect(signedOut.properties.$user_id).toBeUndefined(); + expect(signedOut.properties.$device_id).toBe("device-1"); + expect(signedOut.properties.platform).toBe(signedIn.properties.platform); + + // reset() schedules a flags reload; advanced_disable_flags must keep it + // from fetching. Wait out its debounce. Only events may have gone out + // ($identify is sent at once, not batched). + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(fetched.filter((url) => !new URL(url).pathname.startsWith("/e/"))).toEqual([]); + + // Turned off in this session, then signed out: posthog-js stays opted out. + analytics.optOut(); + analytics.resetIdentity(); + expect(posthog.has_opted_out_capturing()).toBe(true); +}); diff --git a/src/lib/__tests__/posthog.test.ts b/src/lib/__tests__/posthog.test.ts index 17042e7..b94a658 100644 --- a/src/lib/__tests__/posthog.test.ts +++ b/src/lib/__tests__/posthog.test.ts @@ -1,43 +1,328 @@ /** - * posthog wrapper smoke tests. + * Product analytics wrapper. posthog-js is mocked: these tests pin when it + * may start and what it is told, not PostHog itself. * - * `VITE_POSTHOG_KEY` is unset in the vitest env, so `initPostHog` - * short-circuits before importing the SDK. These tests lock in that - * the public surface stays no-throw + no-op in that state — the - * default mode for any contributor running tests locally without a - * PostHog project key. + * - While product analytics is off, posthog-js is never initialised, so it + * makes no request at all. + * - Once the user opts in, it starts with automatic capture, remote config, + * feature flags and external scripts all off. + * - identify sends the account id only, and no event carries the person + * properties posthog-js would add on its own. + * - After an opt-out in the same session, nothing it would still send gets + * through. + * - Signing out forgets the account, without loading posthog-js to do it. */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { describe, it, expect } from "vitest"; - -import { - capture, - identifyUser, - initPostHog, - isReady, - optIn, - optOut, - pageview, -} from "@/lib/posthog"; - -describe("posthog wrapper (no key in env)", () => { - it("is not ready before init", () => { - expect(isReady()).toBe(false); - }); - - it("initPostHog without VITE_POSTHOG_KEY resolves without loading the SDK", async () => { - await expect( - initPostHog({ distinctId: "device-test", enabled: true }), - ).resolves.toBeUndefined(); - // Still not ready — the key gate short-circuited. - expect(isReady()).toBe(false); - }); - - it("capture / identifyUser / pageview / optIn / optOut never throw when not ready", () => { - expect(() => capture("test_event", { k: "v" })).not.toThrow(); - expect(() => identifyUser("user-1", { plan: "pro" })).not.toThrow(); - expect(() => pageview("/main/fleet", "Fleet")).not.toThrow(); - expect(() => optIn()).not.toThrow(); - expect(() => optOut()).not.toThrow(); +const ph = vi.hoisted(() => ({ + init: vi.fn(), + register: vi.fn(), + identify: vi.fn(), + capture: vi.fn(), + opt_in_capturing: vi.fn(), + opt_out_capturing: vi.fn(), + has_opted_out_capturing: vi.fn(), + resetPersonPropertiesForFlags: vi.fn(), + reset: vi.fn(), + _send_request: vi.fn(), +})); +/** How many times posthog-js was loaded (once per fresh module registry). */ +const loads = vi.hoisted(() => ({ count: 0 })); +vi.mock("posthog-js", () => { + loads.count += 1; + return { default: ph }; +}); + +let analytics: typeof import("@/lib/posthog"); +/** posthog-js's own request function, which every request goes through. */ +let send: ReturnType; + +const EXPECTED_OPTIONS = { + api_host: "https://us.i.posthog.com", + autocapture: false, + capture_pageview: false, + capture_pageleave: false, + capture_dead_clicks: false, + capture_exceptions: false, + capture_heatmaps: false, + capture_performance: false, + disable_session_recording: true, + disable_surveys: true, + disable_conversations: true, + disable_product_tours: true, + disable_web_experiments: true, + advanced_disable_flags: true, + disable_external_dependency_loading: true, + persistence: "localStorage", + bootstrap: { distinctID: "device-1" }, + loaded: expect.any(Function), + before_send: expect.any(Function), +}; + +/** Let the wrapper's dynamic import of posthog-js finish. */ +async function settle() { + await vi.dynamicImportSettled(); + await new Promise((resolve) => setTimeout(resolve, 0)); +} + +beforeEach(async () => { + vi.resetModules(); + vi.clearAllMocks(); + loads.count = 0; + ph.has_opted_out_capturing.mockReturnValue(false); + ph.init.mockImplementation((_key: string, config: { loaded?: (p: typeof ph) => void }) => { + config.loaded?.(ph); + return ph; + }); + send = vi.fn(); + ph._send_request = send; + vi.stubEnv("VITE_POSTHOG_KEY", "phc_test"); + vi.stubEnv("VITE_POSTHOG_HOST", ""); + analytics = await import("@/lib/posthog"); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + localStorage.clear(); +}); + +describe("product analytics while it is off", () => { + it("never initialises posthog-js", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + analytics.identifyUser("user-1"); + analytics.capture("message_sent", { text_length: 3 }); + analytics.pageview("/main", "main"); + analytics.optOut(); + await settle(); + // Not even loaded, let alone started. + expect(loads.count).toBe(0); + expect(ph.init).not.toHaveBeenCalled(); + expect(ph.identify).not.toHaveBeenCalled(); + expect(ph.capture).not.toHaveBeenCalled(); + expect(analytics.isReady()).toBe(false); + }); + + it("does nothing without a project key, even after an opt-in", async () => { + vi.stubEnv("VITE_POSTHOG_KEY", ""); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + analytics.optIn(); + await settle(); + expect(ph.init).not.toHaveBeenCalled(); + expect(analytics.isReady()).toBe(false); + }); +}); + +describe("what older builds left behind", () => { + it("removes posthog-js's stored state at launch while product analytics is off, and nothing else", async () => { + localStorage.setItem("ph_phc_test_posthog", JSON.stringify({ $stored_person_properties: { name: "Mira" } })); + localStorage.setItem("__ph_opt_in_out_phc_test", "0"); + localStorage.setItem("ph_phc_other_posthog", "{}"); + localStorage.setItem("fleet:onboarded", "1"); + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + expect(localStorage.getItem("ph_phc_test_posthog")).toBeNull(); + expect(localStorage.getItem("__ph_opt_in_out_phc_test")).toBe("0"); + expect(localStorage.getItem("ph_phc_other_posthog")).toBe("{}"); + expect(localStorage.getItem("fleet:onboarded")).toBe("1"); + // Without loading posthog-js to do it. + expect(loads.count).toBe(0); + }); + + it("names the entry the way posthog-js does", async () => { + vi.stubEnv("VITE_POSTHOG_KEY", "phc_a+b/c="); + localStorage.setItem("ph_phc_aPLbSLcEQ_posthog", "{}"); + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + expect(localStorage.getItem("ph_phc_aPLbSLcEQ_posthog")).toBeNull(); + }); + + it("keeps posthog-js's stored state when product analytics is on", async () => { + localStorage.setItem("ph_phc_test_posthog", "{}"); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + expect(localStorage.getItem("ph_phc_test_posthog")).toBe("{}"); + }); +}); + +describe("opting in", () => { + it("starts posthog-js at launch when the saved choice is on, with only Fleetify's own events", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + expect(ph.init).toHaveBeenCalledTimes(1); + expect(ph.init).toHaveBeenCalledWith("phc_test", EXPECTED_OPTIONS); + expect(analytics.isReady()).toBe(true); + }); + + it("starts posthog-js when the user opts in later, with the same options", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + analytics.optIn(); + await settle(); + expect(ph.init).toHaveBeenCalledTimes(1); + expect(ph.init).toHaveBeenCalledWith("phc_test", EXPECTED_OPTIONS); + // No $opt_in event: it isn't one of the events Fleetify documents. + expect(ph.capture).not.toHaveBeenCalled(); + }); + + it("clears an opt-out an older build stored, without an $opt_in event", async () => { + ph.has_opted_out_capturing.mockReturnValue(true); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + expect(ph.opt_in_capturing.mock.calls).toEqual([[{ captureEventName: false }]]); + }); + + it("drops the person properties older builds stored", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + expect(ph.resetPersonPropertiesForFlags).toHaveBeenCalledTimes(1); + }); + + it("keeps an opt-in the user made before the launch read arrived", async () => { + analytics.optIn(); + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + expect(ph.init).toHaveBeenCalledTimes(1); + }); + + it("keeps an opt-out the user made before the launch read arrived", async () => { + analytics.optOut(); + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + await settle(); + expect(ph.init).not.toHaveBeenCalled(); + }); + + it("does not start when the user opts out again while posthog-js loads", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + analytics.optIn(); + analytics.optOut(); + await settle(); + expect(ph.init).not.toHaveBeenCalled(); + }); +}); + +describe("identify", () => { + it("sends the account id only", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + analytics.identifyUser("user-1"); + expect(ph.identify.mock.calls).toEqual([["user-1"]]); + }); + + it("removes the person properties posthog-js adds before any event is sent", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + const { before_send } = ph.init.mock.calls[0][1] as { + before_send: (event: unknown) => unknown; + }; + // What posthog-js 1.376 builds for identify: the account id and the + // anonymous id, plus $set_once with the first address and referrer it saw. + const identify = { + uuid: "u-1", + event: "$identify", + properties: { + distinct_id: "user-1", + $anon_distinct_id: "device-1", + $os: "Linux", + $set: { name: "Mira" }, + $set_once: { plan: "pro" }, + }, + $set: {}, + $set_once: { + $initial_current_url: "http://127.0.0.1:8765/", + $initial_referrer: "$direct", + $current_url: "http://127.0.0.1:8765/", + }, + timestamp: new Date(0), + }; + expect(before_send(identify)).toEqual({ + uuid: "u-1", + event: "$identify", + properties: { distinct_id: "user-1", $anon_distinct_id: "device-1", $os: "Linux" }, + timestamp: new Date(0), + }); + // The event posthog-js handed over is left as it was. + expect(identify.$set_once).toBeDefined(); + // posthog-js passes null on to the next hook once one drops an event. + expect(before_send(null)).toBeNull(); + }); + + it("links a sign-in made before the opt-in once the user opts in", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + analytics.identifyUser("user-1"); + await settle(); + expect(ph.identify).not.toHaveBeenCalled(); + analytics.optIn(); + await settle(); + expect(ph.identify.mock.calls).toEqual([["user-1"]]); + }); +}); + +describe("opting out in the same session", () => { + it("stops capturing, and no queued or retried request gets through", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + ph._send_request({ url: "/e/", data: {} }); + expect(send).toHaveBeenCalledTimes(1); + + analytics.optOut(); + expect(ph.opt_out_capturing).toHaveBeenCalledTimes(1); + // What posthog-js still had queued, or was retrying, goes nowhere. + ph._send_request({ url: "/e/", data: {} }); + ph._send_request({ url: "/flags/?v=2", data: {} }); + analytics.capture("message_sent", { text_length: 3 }); + analytics.pageview("/main", "main"); + analytics.identifyUser("user-1"); + expect(send).toHaveBeenCalledTimes(1); + expect(ph.capture).not.toHaveBeenCalled(); + expect(ph.identify).not.toHaveBeenCalled(); + expect(analytics.isReady()).toBe(false); + }); + + it("opting back in lets requests through again, without an $opt_in event", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + analytics.optOut(); + analytics.optIn(); + expect(ph.opt_in_capturing).toHaveBeenLastCalledWith({ captureEventName: false }); + ph._send_request({ url: "/e/", data: {} }); + expect(send).toHaveBeenCalledTimes(1); + expect(ph.init).toHaveBeenCalledTimes(1); + }); +}); + +describe("signing out", () => { + it("resets a running posthog-js to a new anonymous id and keeps Fleetify's platform property", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + analytics.identifyUser("user-1"); + ph.register.mockClear(); + analytics.resetIdentity(); + // Not reset(true): $device_id stays this install's id. + expect(ph.reset.mock.calls).toEqual([[]]); + // reset() clears every super property, Fleetify's own included. + expect(ph.register).toHaveBeenCalledWith({ platform: expect.any(String) }); + expect(ph.opt_out_capturing).not.toHaveBeenCalled(); + }); + + it("forgets an account that was waiting for posthog-js to load", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + analytics.optIn(); // posthog-js starts loading + analytics.identifyUser("user-1"); // kept until it runs + analytics.resetIdentity(); + await settle(); + expect(ph.init).toHaveBeenCalledTimes(1); + expect(ph.identify).not.toHaveBeenCalled(); + }); + + it("loads nothing while product analytics is off, and still forgets the account", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: false }); + analytics.identifyUser("user-1"); + analytics.resetIdentity(); + await settle(); + expect(loads.count).toBe(0); + expect(ph.reset).not.toHaveBeenCalled(); + // Opting in later in this session identifies no one. + analytics.optIn(); + await settle(); + expect(ph.init).toHaveBeenCalledTimes(1); + expect(ph.identify).not.toHaveBeenCalled(); + }); + + it("keeps posthog-js opted out when the user turned product analytics off in this session", async () => { + await analytics.initPostHog({ distinctId: "device-1", enabled: true }); + analytics.optOut(); + ph.opt_out_capturing.mockClear(); + analytics.resetIdentity(); + expect(ph.reset).toHaveBeenCalledTimes(1); + // reset() also clears posthog-js's stored consent. + expect(ph.opt_out_capturing).toHaveBeenCalledTimes(1); + expect(analytics.isReady()).toBe(false); }); }); diff --git a/src/lib/__tests__/session-eviction.test.ts b/src/lib/__tests__/session-eviction.test.ts index fed0973..7cadbf4 100644 --- a/src/lib/__tests__/session-eviction.test.ts +++ b/src/lib/__tests__/session-eviction.test.ts @@ -1,7 +1,8 @@ -import { describe, it, expect, beforeEach } from "vitest"; +import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { useAppStore } from "@/stores/app-store"; import { useChatStore } from "@/stores/chat-store"; import { sweepInactiveSessions, visibleSessionIds } from "../session-eviction"; +import { pinSession } from "../session-pins"; const msg = (id: string) => ({ id, @@ -64,3 +65,56 @@ describe("sweepInactiveSessions", () => { expect(transcript("agent-1")).toHaveLength(1); }); }); + +describe("sweepInactiveSessions — pinned sessions", () => { + // Pins are module state: release every one a test takes, even after a + // failed assertion, so none leaks into the next test. + const held: Array<() => void> = []; + const pin = (id: string) => { + const release = pinSession(id); + held.push(release); + return release; + }; + afterEach(() => { + for (const release of held.splice(0)) release(); + }); + + it("keeps a pinned session that no chat view shows, alongside the visible one", () => { + // Regression: a Workflows run detail went blank about 20s after it opened. + // It fetches the run's transcript once, and the sweep emptied it because + // only chat views counted as "on screen". + pin("run-1"); + useChatStore.getState().addMessage("staff", msg("m-1")); + useChatStore.getState().addMessage("run-1", msg("m-2")); + useChatStore.getState().addMessage("agent-1", msg("m-3")); + + sweepInactiveSessions(); + + expect(transcript("staff")).toHaveLength(1); // visible + expect(transcript("run-1")).toHaveLength(1); // pinned + expect(transcript("agent-1")).toHaveLength(0); // neither: still reclaimed + }); + + it("evicts the session on the next sweep once its pin is released", () => { + const release = pin("run-1"); + useChatStore.getState().addMessage("run-1", msg("m-1")); + sweepInactiveSessions(); + expect(transcript("run-1")).toHaveLength(1); + + release(); + sweepInactiveSessions(); + + expect(transcript("run-1")).toHaveLength(0); + }); + + it("keeps a session pinned twice and released once", () => { + const first = pin("run-1"); + pin("run-1"); + useChatStore.getState().addMessage("run-1", msg("m-1")); + + first(); + sweepInactiveSessions(); + + expect(transcript("run-1")).toHaveLength(1); + }); +}); diff --git a/src/lib/__tests__/session-messages.test.ts b/src/lib/__tests__/session-messages.test.ts new file mode 100644 index 0000000..def04b4 --- /dev/null +++ b/src/lib/__tests__/session-messages.test.ts @@ -0,0 +1,54 @@ +import { describe, it, expect } from "vitest"; +import { parseStoredMessage, parseStoredMessages } from "../session-messages"; +import type { ContentBlock } from "@/types/chat"; + +/** A row exactly as GET /sessions/:id/messages returns it: the backend's + * `messages` table (crates/fleetify-backend/src/models/message.rs) keeps + * `content` as the JSON-encoded block array, stored as TEXT. */ +const row = (content: string | ContentBlock[], role = "assistant", id = "m-1") => ({ + id, + session_id: "s-1", + role, + content, + model: "claude-sonnet", + usage_json: null, + cost_usd: 0.25, + timestamp: "2026-11-17T06:00:00.000Z", +}); +const json = (t: string) => JSON.stringify([{ type: "text", text: t }]); + +describe("parseStoredMessage", () => { + it("parses the JSON content into blocks and keeps every other field as is", () => { + expect(parseStoredMessage(row(json("hello")))).toEqual({ + ...row(json("hello")), + content: [{ type: "text", text: "hello" }], + }); + }); + + it("keeps content that is not valid JSON as one text block, as chat-view always has", () => { + expect(parseStoredMessage(row("plain text, not JSON")).content) + .toEqual([{ type: "text", text: "plain text, not JSON" }]); + expect(parseStoredMessage(row("")).content).toEqual([{ type: "text", text: "" }]); + }); + + it("passes content that is already parsed through untouched", () => { + const blocks: ContentBlock[] = [{ type: "text", text: "already parsed" }]; + expect(parseStoredMessage(row(blocks)).content).toBe(blocks); + }); +}); + +describe("parseStoredMessages", () => { + it("parses user, assistant and system rows alike and keeps each role", () => { + const parsed = parseStoredMessages([ + row(json("do it"), "user", "u"), + row(json("done"), "assistant", "a"), + row(json("dispatched"), "system", "s"), + ]); + expect(parsed.map(m => [m.id, m.role])).toEqual([["u", "user"], ["a", "assistant"], ["s", "system"]]); + expect(parsed.map(m => m.content)).toEqual([ + [{ type: "text", text: "do it" }], + [{ type: "text", text: "done" }], + [{ type: "text", text: "dispatched" }], + ]); + }); +}); diff --git a/src/lib/__tests__/session-pins.test.ts b/src/lib/__tests__/session-pins.test.ts new file mode 100644 index 0000000..c16f2d5 --- /dev/null +++ b/src/lib/__tests__/session-pins.test.ts @@ -0,0 +1,104 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { renderHook } from "@testing-library/react"; +import { pinSession, pinnedSessionIds, usePinnedSession, usePinnedSessions } from "../session-pins"; + +// The registry is module state. Give back every pin a test takes — even one +// whose assertions failed halfway — so no test inherits another's pins. +const held: Array<() => void> = []; +const pin = (id: string) => { + const release = pinSession(id); + held.push(release); + return release; +}; +afterEach(() => { + for (const release of held.splice(0)) release(); +}); + +const pinned = () => pinnedSessionIds().sort(); + +describe("pinSession", () => { + it("pins a session until the returned function releases it", () => { + const release = pin("run-1"); + expect(pinned()).toEqual(["run-1"]); + release(); + expect(pinned()).toEqual([]); + }); + + it("is reference-counted: pinned twice and released once, it stays pinned", () => { + const first = pin("run-1"); + const second = pin("run-1"); + first(); + expect(pinned()).toEqual(["run-1"]); + second(); + expect(pinned()).toEqual([]); + }); + + it("unpins once: calling one release twice cannot drop another holder's pin", () => { + const first = pin("run-1"); + pin("run-1"); + first(); + first(); + expect(pinned()).toEqual(["run-1"]); + }); +}); + +describe("usePinnedSession", () => { + it("pins the session while mounted and unpins it on unmount", () => { + const { unmount } = renderHook(() => usePinnedSession("run-1")); + expect(pinned()).toEqual(["run-1"]); + unmount(); + expect(pinned()).toEqual([]); + }); + + it("moves the pin when the id changes, and drops it when the id goes away", () => { + const { rerender } = renderHook( + ({ id }) => usePinnedSession(id), + { initialProps: { id: "run-1" } }, + ); + expect(pinned()).toEqual(["run-1"]); + rerender({ id: "run-2" }); + expect(pinned()).toEqual(["run-2"]); + rerender({ id: null }); + expect(pinned()).toEqual([]); + }); + + it("pins nothing without an id", () => { + renderHook(() => usePinnedSession(null)); + renderHook(() => usePinnedSession(undefined)); + expect(pinned()).toEqual([]); + }); + + it("leaves another holder's pin on the same session in place", () => { + pin("run-1"); + const { unmount } = renderHook(() => usePinnedSession("run-1")); + unmount(); + expect(pinned()).toEqual(["run-1"]); + }); +}); + +describe("usePinnedSessions", () => { + it("pins every listed session while mounted and releases them all on unmount", () => { + const { unmount } = renderHook(() => usePinnedSessions(["a", "b"])); + expect(pinned()).toEqual(["a", "b"]); + unmount(); + expect(pinned()).toEqual([]); + }); + + it("releases the sessions that leave the list and pins the ones that join it", () => { + const { rerender } = renderHook( + ({ ids }: { ids: string[] }) => usePinnedSessions(ids), + { initialProps: { ids: ["a", "b"] } }, + ); + rerender({ ids: ["b", "c"] }); + expect(pinned()).toEqual(["b", "c"]); + rerender({ ids: [] }); + expect(pinned()).toEqual([]); + }); + + it("releases a listed-twice session only as often as it pinned it", () => { + pin("a"); + const { unmount } = renderHook(() => usePinnedSessions(["a", "a"])); + unmount(); + expect(pinned()).toEqual(["a"]); + }); +}); diff --git a/src/lib/api.ts b/src/lib/api.ts index c24dc7c..321af87 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -34,8 +34,6 @@ declare global { detectEditors(): Promise<{ editors: { id: string; label: string }[] }>; /** Launch a project directory in the chosen editor (id from detectEditors). */ openInEditor(editorId: string, path: string): Promise<{ ok: boolean; error?: string }>; - /** Open a URL or local path in the system's default handler. */ - openExternal(target: string): Promise<{ ok: boolean; error?: string }>; }; } } diff --git a/src/lib/auth-events.ts b/src/lib/auth-events.ts new file mode 100644 index 0000000..26bf333 --- /dev/null +++ b/src/lib/auth-events.ts @@ -0,0 +1,37 @@ +import { useAppStore } from "@/stores/app-store"; +import { resetIdentity } from "@/lib/posthog"; + +/** Payload of the shell's `fleet:auth-event` (src-tauri/src/shell/auth.rs). */ +export interface AuthEvent { + kind: string; + [k: string]: unknown; +} + +export interface AuthEventHandlers { + /** The shell ended the session: the user signed out, or a refresh failed. */ + onSignedOut: () => void; +} + +/** + * Routes one shell auth event from `window.fleetify.onAuthEvent`. Lives + * outside App.tsx so it can be tested without mounting the whole app. + * + * - `signed-out`: hands off to `onSignedOut`, drops the keychain warning, + * which was about the sign-in that just ended, and makes product analytics + * forget the account (`resetIdentity`), so on a shared machine the next + * account isn't linked to it. + * - `keychain-unavailable`: the shell could not save the sign-in to the OS + * keychain, so the next launch starts signed out. Raises the warning + * banner (). + * + * Other kinds (`refreshed`, ...) need nothing here. + */ +export function handleAuthEvent(event: AuthEvent, { onSignedOut }: AuthEventHandlers): void { + if (event.kind === "signed-out") { + onSignedOut(); + useAppStore.getState().setKeychainWarning(false); + resetIdentity(); + } else if (event.kind === "keychain-unavailable") { + useAppStore.getState().setKeychainWarning(true); + } +} diff --git a/src/lib/dev-gallery.ts b/src/lib/dev-gallery.ts new file mode 100644 index 0000000..869576d --- /dev/null +++ b/src/lib/dev-gallery.ts @@ -0,0 +1,11 @@ +/** + * The dev-only logo gallery: `#logos` swaps the whole app for it, to compare + * brand-mark candidates. A release build never shows it: a link or a drop + * that sets the hash must not strand the user there. + */ + +/** Whether the window shows the logo gallery in place of the app: only in a + * dev build (`dev`, Vite's `import.meta.env.DEV`), and only for `#logos`. */ +export function showsLogoGallery(hash: string, dev: boolean = import.meta.env.DEV): boolean { + return dev && hash === "#logos"; +} diff --git a/src/lib/drop-guard.ts b/src/lib/drop-guard.ts new file mode 100644 index 0000000..32c9baf --- /dev/null +++ b/src/lib/drop-guard.ts @@ -0,0 +1,115 @@ +/** + * Keeps a drop that nothing on the page handles from navigating the app's + * window. + * + * The main window turns Tauri's own drag-and-drop handler off (lib.rs, + * `disable_drag_drop_handler`, so HTML5 drag-and-drop works on Windows). That + * leaves drops to the webview: a file, link, text or HTML dropped where no + * element takes it makes the engine load it in place of the app. These + * window listeners take such a drop, and do nothing with it. + * + * - An element that handles a drop (the composer's files, the sidebar, split + * panes) cancels the event itself, before it reaches the window: the guard + * leaves it alone, and the element's handlers run as before. + * - The app's own drags (sidebar sessions, workspace panes) are left to their + * targets. The sidebar leaves an illegal target uncancelled on purpose, so + * the cursor says no-drop. Only a drag that started in this document with + * an app type counts as the app's own, until it ends: WebView2 carries a + * web page's custom types across processes, so a drag from a browser can + * carry them too. + * - Text or a link dropped into a field you can type in is left to the + * engine, which inserts it there. A file is cancelled even there: a text + * field can't take it, and the engine may load it instead. + * - The dragover's drop effect is left as it is: setting "none" can make an + * engine treat the drop as unhandled again. + */ + +/** Types the app sets on its own drags: a sidebar session, a workspace + * pane. */ +const APP_DRAG_TYPES = ["application/x-fleet-session-id", "application/fleet-pane"]; + +/** Types of what the engine loads when nothing takes the drop. */ +const LOADABLE_TYPES = ["Files", "text/uri-list", "text/plain", "text/html"]; + +/** Input types the engine drops into itself: text fields, and file pickers. */ +const ENGINE_DROP_INPUTS = new Set([ + "text", + "search", + "url", + "tel", + "email", + "password", + "number", + "file", +]); + +/** True for a field the engine drops into itself: a textarea, a text input + * or file picker, or contenteditable content, when it can be edited. */ +export function isTextEntry(target: EventTarget | null): boolean { + if (target instanceof HTMLTextAreaElement) return !target.disabled && !target.readOnly; + if (target instanceof HTMLInputElement) { + return !target.disabled && !target.readOnly && ENGINE_DROP_INPUTS.has(target.type); + } + return target instanceof HTMLElement && target.isContentEditable; +} + +/** Whether the guard takes a drag carrying `types` over `target`, when + * nothing on the page has: one the engine would load, unless it is text or + * a link over a field you can type in, or the app's own drag (`fromApp`, + * started in this document, carrying an app type). */ +export function guardTakes( + types: readonly string[], + target: EventTarget | null, + fromApp: boolean, +): boolean { + if (fromApp && types.some((type) => APP_DRAG_TYPES.includes(type))) return false; + if (types.includes("Files")) return true; + return types.some((type) => LOADABLE_TYPES.includes(type)) && !isTextEntry(target); +} + +/** The types a drag event carries. */ +function dragTypes(event: Event): string[] { + return Array.from((event as DragEvent).dataTransfer?.types ?? []); +} + +/** Installs the guard on `target`'s window events. Returns what removes it. */ +export function installDropGuard(target: Window = window): () => void { + // Whether one of the app's own drags is in flight: the engine fires + // dragstart on its source, after the source's handler set an app type, and + // dragend when it ends. + // - Only a dragstart carrying an app type counts. One the app cancelled + // starts no drag (a workspace pane cancels one while it isn't armed), and + // no dragend follows it. + // - A source that left the document mid-drag still gets its dragend, but + // the event no longer reaches the window: the source itself is listened + // to as well. + // - A drop ends it, and so does the next press, should no dragend come. + let dragFromApp = false; + const ended = () => { + dragFromApp = false; + }; + const started = (event: Event) => { + if (event.defaultPrevented) return; + if (!dragTypes(event).some((type) => APP_DRAG_TYPES.includes(type))) return; + dragFromApp = true; + event.target?.addEventListener("dragend", ended, { once: true }); + }; + const take = (event: Event) => { + if (event.defaultPrevented) return; + if (guardTakes(dragTypes(event), event.target, dragFromApp)) event.preventDefault(); + }; + const events = ["dragenter", "dragover", "drop"] as const; + target.addEventListener("dragstart", started); + target.addEventListener("dragend", ended); + target.addEventListener("pointerdown", ended); + for (const type of events) target.addEventListener(type, take); + // After `take`, so the drop is judged before the flag clears. + target.addEventListener("drop", ended); + return () => { + target.removeEventListener("dragstart", started); + target.removeEventListener("dragend", ended); + target.removeEventListener("pointerdown", ended); + for (const type of events) target.removeEventListener(type, take); + target.removeEventListener("drop", ended); + }; +} diff --git a/src/lib/links.ts b/src/lib/links.ts new file mode 100644 index 0000000..0748ae8 --- /dev/null +++ b/src/lib/links.ts @@ -0,0 +1,78 @@ +/** + * Where a link the app shows may take the user. The main window must stay on + * the app: a page from another site loaded in its place has no way back and + * no use of the app's commands, which answer the app's own origin only. So a + * link to another site opens in the system browser, a link to another page of + * the app's origin does nothing, and a fragment of the current page + * (`#usage`) scrolls to its element without touching the page's URL. + */ + +/** Schemes the system may open for a link: web pages and mail. */ +const EXTERNAL_PROTOCOLS = new Set(["http:", "https:", "mailto:"]); + +export type LinkTarget = + /** A fragment of the current page: scroll to the element with this `id`. */ + | { kind: "anchor"; id: string } + /** Another site: open `url` in the system browser (or mail client). */ + | { kind: "external"; url: string } + /** Anything else: the app's own pages, other schemes, unreadable links. + * Following it does nothing. */ + | { kind: "blocked" }; + +/** What following a link to `href` does, on the page at `page`. */ +export function linkTarget(href: string | null | undefined, page: string): LinkTarget { + if (!href) return { kind: "blocked" }; + if (href.startsWith("#")) return { kind: "anchor", id: fragmentId(href.slice(1)) }; + let url: URL; + let here: URL; + try { + here = new URL(page); + url = new URL(href, here); + } catch { + return { kind: "blocked" }; + } + const sameOrigin = url.origin === here.origin; + if (sameOrigin && url.pathname === here.pathname && url.search === here.search && url.hash) { + return { kind: "anchor", id: fragmentId(url.hash.slice(1)) }; + } + if (EXTERNAL_PROTOCOLS.has(url.protocol) && (url.protocol === "mailto:" || !sameOrigin)) { + return { kind: "external", url: url.href }; + } + return { kind: "blocked" }; +} + +/** The element id a fragment names: percent-decoded, or as it is when it + * doesn't decode. */ +function fragmentId(fragment: string): string { + try { + return decodeURIComponent(fragment); + } catch { + return fragment; + } +} + +/** Scrolls to the element a fragment link names, when the page has one. The + * page's URL is left alone: the app reads its own hash (`#logos` swaps the + * app for a dev-only gallery), so a link must never set it. */ +export function scrollToFragment(id: string): void { + if (id) document.getElementById(id)?.scrollIntoView({ block: "start" }); +} + +/** Opens `url` with the system's default handler, through the app's bridge + * (the `shell_open_external` command). Where there is no bridge, the + * renderer in a plain browser, it opens a new tab instead. */ +export function openExternalUrl(url: string): void { + if (window.electronAPI?.openExternal) { + window.electronAPI.openExternal(url).catch(() => {}); + } else { + window.open(url, "_blank", "noopener,noreferrer"); + } +} + +/** Opens `href` in the system browser when it links to another site or is a + * mail link, as following it would (`linkTarget`); anything else does + * nothing. For links the app shows as buttons, such as citation cards. */ +export function openLink(href: string | null | undefined): void { + const target = linkTarget(href, window.location.href); + if (target.kind === "external") openExternalUrl(target.url); +} diff --git a/src/lib/log.ts b/src/lib/log.ts index 8efd905..4d66df8 100644 --- a/src/lib/log.ts +++ b/src/lib/log.ts @@ -134,28 +134,28 @@ export const log = { }; /** - * Wire global error capture. Call once from the renderer entry point. - * • `window.onerror` — synchronous throws that escape every - * React error boundary AND non-React - * code (raw script errors, image - * onload throws, …). - * • `unhandledrejection` — promise rejections without a .catch. - * Common cause of silent UI freezes. - * • `beforeunload` — last-ditch flush so the final batch - * lands before the window dies. + * What kind of error it was: the class name (`TypeError`, `AbortError`, …) + * for an Error, otherwise its JS type. Never its message or stack, which can + * carry file paths, message text or tokens. Product analytics events use it + * instead of the error itself. */ -// Lazy import keeps the posthog SDK chunk out of the cold-start path -// even before `initPostHog` runs. `capture()` itself is a no-op until -// the SDK has been initialised by `App.tsx`. +export function errorType(value: unknown): string { + if (value instanceof Error) return (value.name || "Error").slice(0, 64); + if (value === null || value === undefined) return "unknown"; + return typeof value; +} + +// Product analytics gets only the error's type; `installGlobalErrorCapture` +// keeps the details in the local log. `capture()` is a no-op unless the user +// opted in. async function capturePostHogFrontendError( - source: "uncaught" | "unhandled-rejection", - message: string, - fields: Record, + source: "uncaught" | "unhandled-rejection" | "render", + error: unknown, ): Promise { try { const { capture, isReady } = await import("./posthog"); if (!isReady()) return; - capture("frontend_error", { source, message, ...fields }); + capture("frontend_error", { source, error_type: errorType(error) }); } catch { // Don't let analytics tip the renderer over — if the dynamic // import itself fails, the original `log.error` call above @@ -163,6 +163,33 @@ async function capturePostHogFrontendError( } } +/** + * A render error that the root error boundary (`AppErrorBoundary`) caught. + * React doesn't pass those on to `window.onerror`, so the boundary reports + * them here. Like the global capture, the local log gets the details (the + * message, the stack and where in the component tree it happened) and + * product analytics, when the user opted in, only the error's type. + */ +export function logRenderError(error: unknown, componentStack?: string | null): void { + const message = error instanceof Error ? error.message : String(error); + log.error("renderer.render-error", message, { + stack: error instanceof Error ? (error.stack ?? null) : null, + componentStack: componentStack ?? null, + }); + void capturePostHogFrontendError("render", error); +} + +/** + * Wire global error capture. Call once from the renderer entry point. + * • `window.onerror` — synchronous throws that escape every + * React error boundary AND non-React + * code (raw script errors, image + * onload throws, …). + * • `unhandledrejection` — promise rejections without a .catch. + * Common cause of silent UI freezes. + * • `beforeunload` — last-ditch flush so the final batch + * lands before the window dies. + */ export function installGlobalErrorCapture(): void { if (typeof window === "undefined") return; window.addEventListener("error", (ev) => { @@ -174,12 +201,7 @@ export function installGlobalErrorCapture(): void { col: ev.colno ?? null, stack: err instanceof Error ? err.stack : null, }); - void capturePostHogFrontendError("uncaught", message, { - filename: ev.filename ?? null, - line: ev.lineno ?? null, - col: ev.colno ?? null, - stack: err instanceof Error ? err.stack : null, - }); + void capturePostHogFrontendError("uncaught", err); }); window.addEventListener("unhandledrejection", (ev) => { const reason = ev.reason; @@ -191,9 +213,7 @@ export function installGlobalErrorCapture(): void { log.error("renderer.unhandled-rejection", message, { stack: reason instanceof Error ? reason.stack : null, }); - void capturePostHogFrontendError("unhandled-rejection", message, { - stack: reason instanceof Error ? reason.stack : null, - }); + void capturePostHogFrontendError("unhandled-rejection", reason); }); window.addEventListener("beforeunload", () => { // Best-effort sync flush. The promise it returns may not resolve diff --git a/src/lib/posthog.ts b/src/lib/posthog.ts index b7284a0..4b6282e 100644 --- a/src/lib/posthog.ts +++ b/src/lib/posthog.ts @@ -1,31 +1,84 @@ /** * PostHog product analytics — thin wrapper around posthog-js. * - * Three-tier gating mirrors the Rust backend: - * 1. Compile-time: `VITE_POSTHOG_KEY` unset at build → every function - * is a no-op, `isReady()` returns false. The SDK isn't even loaded. - * 2. Initial state: `opts.enabled === false` on `initPostHog()` → SDK - * starts opted-out, so autocapture is suppressed until `optIn()`. - * 3. Live opt-out: `optOut()` flips the SDK off without re-initing. + * posthog-js is not loaded until the user opts in (Settings → Privacy → + * Product analytics, or the last onboarding question). While product + * analytics is off nothing here imports or starts it, so the renderer makes + * no request to PostHog: no events, no remote config, no feature flags. * - * `distinct_id` comes from the Rust backend's persisted `device_id` - * (via the `telemetry_get_config` Tauri command). After OAuth sign-in, - * `identifyUser(user_id, props)` merges the anonymous person into the - * authenticated person via PostHog's `$anon_distinct_id` link — that - * way pre-signin events stay attached to the same user post-signin. + * Once started, it sends only the events Fleetify captures itself + * (`INIT_OPTIONS`). Everything posthog-js would otherwise do on its own is + * off: autocapture, exception, dead-click, heatmap and web-vitals capture, + * session replay, surveys, product tours and conversations. It also never + * fetches remote config or flags from PostHog or loads scripts from it. * - * The SDK is lazy-loaded via dynamic import so cold-start ships fewer - * KB of JS when the user opts out (or builds without a key). + * Turning it off again in the same session opts posthog-js out and drops + * every request it would still make (see `guardRequests`). + * + * `distinct_id` is the Rust backend's persisted `device_id` (from the + * `telemetry_get_config` command), so renderer and backend events land on + * one PostHog person. `identifyUser(user_id)` links that person to the + * account, with the id only: no event carries person properties + * (`dropPersonProperties`). + * + * `VITE_POSTHOG_KEY` unset at build → every function is a no-op. */ -import type { PostHog } from "posthog-js"; +import type { CaptureResult, PostHog, PostHogConfig } from "posthog-js"; + +const projectKey = () => (import.meta.env.VITE_POSTHOG_KEY as string | undefined) || undefined; +const apiHost = () => + (import.meta.env.VITE_POSTHOG_HOST as string | undefined) || "https://us.i.posthog.com"; -const KEY = import.meta.env.VITE_POSTHOG_KEY as string | undefined; -const HOST = - (import.meta.env.VITE_POSTHOG_HOST as string | undefined) ?? - "https://us.i.posthog.com"; +/** + * Everything posthog-js would send or fetch beyond Fleetify's own events + * is off. Each of these is checked against the posthog-js source: + * remote config and `/flags` are skipped with `advanced_disable_flags`; + * the explicit `capture_*` / `disable_*` values also beat server-side + * settings that older builds may have stored locally; and no extension + * script is fetched from PostHog's asset host. + */ +const INIT_OPTIONS = { + autocapture: false, + capture_pageview: false, + capture_pageleave: false, + capture_dead_clicks: false, + capture_exceptions: false, + capture_heatmaps: false, + capture_performance: false, + disable_session_recording: true, + disable_surveys: true, + disable_conversations: true, + disable_product_tours: true, + disable_web_experiments: true, + advanced_disable_flags: true, + disable_external_dependency_loading: true, + persistence: "localStorage", +} satisfies Partial; + +/** + * posthog-js adds person properties of its own: `$identify`, and the first + * event after each launch once the user is identified, get `$set_once` with + * the first address and referrer it saw on this device and in this session + * (`$initial_current_url`, `$initial_referrer`, `$current_url`, …, and every + * campaign key). Fleetify identifies with the id only, so `before_send` + * strips `$set` and `$set_once` from every event before it is queued. + */ +function dropPersonProperties(event: CaptureResult | null): CaptureResult | null { + if (!event) return event; + const { $set: _set, $set_once: _setOnce, ...rest } = event; + const { $set: _propsSet, $set_once: _propsSetOnce, ...properties } = event.properties; + return { ...rest, properties }; +} -let phPromise: Promise | null = null; +/** The user's current choice. */ +let enabled = false; +/** Set once the user chooses in this session; the launch read can't undo it. */ +let chosen = false; +let distinctId: string | null = null; +/** An account to identify once posthog-js runs (sign-in before opt-in). */ +let pendingUserId: string | null = null; +let loading: Promise | null = null; let phInstance: PostHog | null = null; function platformHint(): string { @@ -37,76 +90,143 @@ function platformHint(): string { return "unknown"; } +/** True while posthog-js runs and the user has it on. */ export function isReady(): boolean { - return phInstance !== null; + return phInstance !== null && enabled; } /** - * Lazy-init posthog-js with the backend-supplied distinct_id and the - * user's persisted opt-in state. Idempotent — second call returns the - * same instance. No-op when `VITE_POSTHOG_KEY` was unset at build time. + * Called once at launch with the backend's device id and the saved choice. + * Starts posthog-js only when that choice is on; otherwise it isn't loaded, + * and what an older build stored for it is removed. */ export async function initPostHog(opts: { distinctId: string; enabled: boolean; }): Promise { - if (!KEY) return; - if (phInstance) return; - if (!phPromise) { - phPromise = import("posthog-js") - .then((mod) => { - const posthog = mod.default; - posthog.init(KEY, { - api_host: HOST, - autocapture: true, - // No router — we emit $pageview manually on screen/mainView - // changes from App.tsx (PR 3). - capture_pageview: false, - persistence: "localStorage", - // Session replay is excluded in v1 (privacy surface + extra - // PostHog quota). Considered for a separate later PR with - // its own re-consent step. - disable_session_recording: true, - opt_out_capturing_by_default: !opts.enabled, - bootstrap: { distinctID: opts.distinctId }, + distinctId = opts.distinctId; + if (!chosen) enabled = opts.enabled; + if (enabled) { + await start(); + } else if (!phInstance) { + removeStoredState(); + } +} + +/** + * Older builds started posthog-js for everyone, and it kept its state in + * localStorage, including the name and email they identified users with. + * Remove that entry (named as posthog-js names it) and nothing else, + * without loading posthog-js to do it. + */ +function removeStoredState(): void { + const key = projectKey(); + if (!key) return; + const token = key.replace(/\+/g, "PL").replace(/\//g, "SL").replace(/=/g, "EQ"); + try { + localStorage.removeItem(`ph_${token}_posthog`); + } catch { + /* storage unavailable: nothing to remove */ + } +} + +function start(): Promise { + const key = projectKey(); + if (phInstance || !key || !distinctId) return Promise.resolve(); + if (!loading) { + const bootstrapId = distinctId; + loading = import("posthog-js") + .then(({ default: posthog }) => { + // Turned off again while it was loading: don't start it. + if (!enabled || phInstance) return; + posthog.init(key, { + ...INIT_OPTIONS, + api_host: apiHost(), + bootstrap: { distinctID: bootstrapId }, loaded: (ph) => { ph.register({ platform: platformHint() }); }, + before_send: dropPersonProperties, }); + guardRequests(posthog); + // An older build may have stored an opt-out, which would keep + // posthog-js silent despite this opt-in. No $opt_in event: it isn't + // one of the events we document. + if (posthog.has_opted_out_capturing()) { + posthog.opt_in_capturing({ captureEventName: false }); + } + // Older builds identified users with their name and email, which + // posthog-js keeps for flag requests. Drop them. + posthog.resetPersonPropertiesForFlags(); phInstance = posthog; - return posthog; + identifyPending(); }) .catch((e) => { // Don't tank the renderer if the SDK chunk fails to load — - // capture/identify/pageview become no-ops, the rest of the app - // continues normally. + // capture/identify/pageview stay no-ops. console.warn("[posthog] SDK load failed:", e); - return null; + }) + .finally(() => { + loading = null; }); } - await phPromise; + return loading; } /** - * Tell PostHog the current user is `userId` and set person properties. - * Fires a `$identify` event whose payload includes the previous - * `distinct_id` as `$anon_distinct_id` — PostHog merges the two - * persons server-side so pre-signin events stay attached. + * posthog-js's own opt-out stops new captures, but it still flushes the + * events it has queued and retries failed sends. Every request it makes + * goes through `_send_request` (posthog-js 1.376), so drop them there while + * the user has product analytics off. */ -export function identifyUser( - userId: string, - props?: Record, -): void { +function guardRequests(posthog: PostHog): void { + const send = posthog._send_request.bind(posthog); + posthog._send_request = (options) => { + if (enabled) send(options); + }; +} + +function identifyPending(): void { + if (!phInstance || !enabled || !pendingUserId) return; + phInstance.identify(pendingUserId); + pendingUserId = null; +} + +/** + * Link product analytics to the signed-in account: the user id only, no + * name, email or other person properties. While product analytics is off + * nothing is sent; the id is kept in memory and used if the user opts in + * later in this session. + */ +export function identifyUser(userId: string): void { + pendingUserId = userId; + identifyPending(); +} + +/** + * The user signed out. Forget the account, so whoever signs in next on this + * machine isn't linked to it: the id kept for a later opt-in goes, and a + * running posthog-js resets to a new anonymous id. posthog-js isn't loaded + * for this; when it isn't running, it holds no account to forget. + */ +export function resetIdentity(): void { + pendingUserId = null; if (!phInstance) return; - phInstance.identify(userId, props ?? {}); + // Not reset(true): $device_id stays this install's id. + phInstance.reset(); + // reset() clears every super property, Fleetify's own included… + phInstance.register({ platform: platformHint() }); + // …and posthog-js's stored consent, so an opt-out made in this session + // has to be stored again. + if (!enabled) phInstance.opt_out_capturing(); } export function capture( event: string, props?: Record, ): void { - if (!phInstance) return; - phInstance.capture(event, props ?? {}); + if (!isReady()) return; + phInstance?.capture(event, props ?? {}); } /** @@ -114,19 +234,28 @@ export function capture( * so screen / mainView subscribers call this directly (PR 3). */ export function pageview(path: string, title?: string): void { - if (!phInstance) return; - phInstance.capture("$pageview", { + if (!isReady()) return; + phInstance?.capture("$pageview", { $current_url: path, ...(title ? { title } : {}), }); } +/** The user turned product analytics on: start posthog-js, or resume it. */ export function optIn(): void { - if (!phInstance) return; - phInstance.opt_in_capturing(); + enabled = true; + chosen = true; + if (!phInstance) { + void start(); + return; + } + phInstance.opt_in_capturing({ captureEventName: false }); + identifyPending(); } +/** The user turned product analytics off: nothing more leaves the renderer. */ export function optOut(): void { - if (!phInstance) return; - phInstance.opt_out_capturing(); + enabled = false; + chosen = true; + phInstance?.opt_out_capturing(); } diff --git a/src/lib/privacy-choice.ts b/src/lib/privacy-choice.ts new file mode 100644 index 0000000..f6f41b4 --- /dev/null +++ b/src/lib/privacy-choice.ts @@ -0,0 +1,41 @@ +/** + * Sending a privacy choice (dashboard sync, product analytics) to the shell. + * + * `telemetry_set_cloud_enabled` and `telemetry_set_posthog_enabled` save the + * choice, then apply it to the backend's live gate, also when the save + * failed. They resolve to `{ ok: true }`, or to `{ ok: false, error }` when + * the save failed: the choice then holds only until Fleetify restarts. A + * call that throws, or a bridge that isn't there, never reached the backend, + * so nothing changed. + * + * Settings → Privacy and the onboarding questions both go through here. + */ + +/** What both privacy commands resolve to. */ +export type PrivacySaveResult = { ok: true } | { ok: false; error: string }; + +export interface PrivacyChoiceOutcome { + /** False when the call never reached the backend, so nothing changed. */ + applied: boolean; + /** What to tell the user when the choice wasn't saved; null when it was. */ + error: string | null; +} + +/** Shown when the call never reached the backend. */ +export const PRIVACY_CHOICE_FAILED = "Couldn't change this setting."; + +/** + * Runs one privacy command. `send` returns undefined when the bridge is + * missing (`window.electronAPI?.telemetrySet…?.(enabled)`). Never throws. + */ +export async function sendPrivacyChoice( + send: () => Promise | undefined, +): Promise { + try { + const result = await send(); + if (!result) return { applied: false, error: PRIVACY_CHOICE_FAILED }; + return { applied: true, error: result.ok === false ? result.error : null }; + } catch { + return { applied: false, error: PRIVACY_CHOICE_FAILED }; + } +} diff --git a/src/lib/session-eviction.ts b/src/lib/session-eviction.ts index 7a820d7..b901d24 100644 --- a/src/lib/session-eviction.ts +++ b/src/lib/session-eviction.ts @@ -1,5 +1,6 @@ import { useAppStore } from "@/stores/app-store"; import { useChatStore } from "@/stores/chat-store"; +import { pinnedSessionIds } from "@/lib/session-pins"; type VisibilityState = { activeSessionId: string | null; @@ -22,7 +23,15 @@ export function visibleSessionIds(app: VisibilityState): string[] { /** Renderer-memory sweep: drop the re-fetchable transcript of every session * that is neither visible nor streaming. Lossless for a hidden session * (chat-view re-fetches from SQLite when it is opened) — but NOT for a visible - * one, because chat-view only re-fetches when the session id changes. */ + * one, because chat-view only re-fetches when the session id changes. + * + * "Visible" also covers the pinned sessions (session-pins.ts): the ones a + * surface outside chat-view has on screen, such as a Workflows run detail. + * Nothing reloads a transcript for those surfaces, so emptying it would blank + * them. */ export function sweepInactiveSessions(): void { - useChatStore.getState().evictInactive(visibleSessionIds(useAppStore.getState())); + useChatStore.getState().evictInactive([ + ...visibleSessionIds(useAppStore.getState()), + ...pinnedSessionIds(), + ]); } diff --git a/src/lib/session-messages.ts b/src/lib/session-messages.ts new file mode 100644 index 0000000..3d68051 --- /dev/null +++ b/src/lib/session-messages.ts @@ -0,0 +1,30 @@ +import type { ChatMessage, ContentBlock } from "@/types/chat"; + +/** A message row as GET /sessions/:id/messages returns it. The backend keeps + * `content` as JSON-encoded text (crates/fleetify-backend/src/models/message.rs), + * so it arrives as a string, not as content blocks. */ +export type StoredMessageRow = { content: string | ContentBlock[]; [k: string]: unknown }; + +/** Turn one row from GET /sessions/:id/messages into a chat-store message. + * `content` is JSON-parsed. Content that is not valid JSON is kept as a single + * text block, content that is already parsed passes through, and every other + * field is copied as is. + * + * Anything that stores rows from that endpoint must parse them first: + * MessageContent throws on a string `content`, and with no error boundary + * that blanks the whole app. Moved verbatim from chat-view, which has always + * parsed its rows this way. */ +export function parseStoredMessage(m: StoredMessageRow): ChatMessage { + let content: ContentBlock[]; + try { + content = typeof m.content === "string" ? JSON.parse(m.content as string) : (m.content as ContentBlock[]); + } catch { + content = [{ type: "text" as const, text: typeof m.content === "string" ? m.content : "" }]; + } + return { ...m, content } as ChatMessage; +} + +/** {@link parseStoredMessage} over a whole response. */ +export function parseStoredMessages(rows: StoredMessageRow[]): ChatMessage[] { + return rows.map(parseStoredMessage); +} diff --git a/src/lib/session-pins.ts b/src/lib/session-pins.ts new file mode 100644 index 0000000..fcdb3b8 --- /dev/null +++ b/src/lib/session-pins.ts @@ -0,0 +1,58 @@ +import { useLayoutEffect } from "react"; + +/** Sessions held on screen by a surface other than chat-view. + * + * The inactive-session sweep (session-eviction.ts) counts a transcript as on + * screen only when a chat view shows it. Other surfaces read transcripts too, + * and nothing reloads one for them once the sweep has emptied it: the + * Workflows run detail fetches its run's transcript once, and the dashboard + * widgets read only what is already in memory. A pin keeps the sweep off a + * session while such a surface shows it. + * + * Reference-counted, because two surfaces can show the same session and one + * of them closing must not release the other's hold. */ +const pins = new Map(); + +/** Pin a session until the returned function is called. That function + * releases this one pin, once: calling it again does nothing, so a doubled + * cleanup cannot release another holder's pin. */ +export function pinSession(id: string): () => void { + pins.set(id, (pins.get(id) ?? 0) + 1); + let released = false; + return () => { + if (released) return; + released = true; + const left = (pins.get(id) ?? 0) - 1; + if (left > 0) pins.set(id, left); + else pins.delete(id); + }; +} + +/** Every session at least one holder has pinned. */ +export function pinnedSessionIds(): string[] { + return [...pins.keys()]; +} + +/** Pin `id` while the calling component is mounted. The pin follows the id, + * and there is none while the id is null or undefined. + * + * A layout effect, not a passive one, because it runs inside the commit, so + * the pin exists before any sweep can see the new screen. A passive effect + * can be flushed a task later, and the sweep timer can fire in that gap and + * empty a transcript the surface will not fetch again. */ +export function usePinnedSession(id: string | null | undefined): void { + useLayoutEffect(() => (id ? pinSession(id) : undefined), [id]); +} + +/** {@link usePinnedSession} for a component that reads a list of sessions. + * Keyed on the set of ids rather than the array, so a re-render with a fresh + * array of the same sessions neither releases nor re-takes a pin. */ +export function usePinnedSessions(ids: readonly string[]): void { + const key = JSON.stringify([...new Set(ids)].sort()); + useLayoutEffect(() => { + const releases = (JSON.parse(key) as string[]).map((id) => pinSession(id)); + return () => { + for (const release of releases) release(); + }; + }, [key]); +} diff --git a/src/main.tsx b/src/main.tsx index 0d18954..1414492 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -2,7 +2,9 @@ import "@fontsource-variable/geist"; import "./globals.css"; import { createRoot } from "react-dom/client"; import { App } from "./App"; +import { AppErrorBoundary } from "./components/app-error-boundary"; import { installGlobalErrorCapture, log } from "./lib/log"; +import { installDropGuard } from "./lib/drop-guard"; // Initialize theme from localStorage const saved = localStorage.getItem("fleet-theme"); @@ -34,7 +36,16 @@ log.info("renderer.boot", "renderer mounted", { // stays reachable via F12 / Ctrl+Shift+I. window.addEventListener("contextmenu", e => e.preventDefault()); -createRoot(document.getElementById("root")!).render(); +// A link, URL or file dropped where nothing handles it would load in the +// window in place of the app. Elements that take drops still get theirs. +installDropGuard(window); + +// A render error shows a recovery screen instead of a blank window. +createRoot(document.getElementById("root")!).render( + + + , +); // Cold-start marker — pair with sinceNavMs above to measure mount cost. if (typeof performance !== "undefined") performance.mark("fleet:react-render"); diff --git a/src/services/__tests__/ws-message-error.test.ts b/src/services/__tests__/ws-message-error.test.ts new file mode 100644 index 0000000..9de9ad5 --- /dev/null +++ b/src/services/__tests__/ws-message-error.test.ts @@ -0,0 +1,24 @@ +import { it, expect, vi } from "vitest"; + +// message_error goes to product analytics. An error's message can carry +// paths, URLs or tokens, so the event keeps only what kind of error it was. + +const analytics = vi.hoisted(() => ({ capture: vi.fn() })); +vi.mock("@/lib/posthog", () => analytics); + +import { wsManager } from "@/services/ws-manager"; + +it("message_error sends the error's class, never its message", async () => { + const manager = wsManager as unknown as { ensureConnected: (sid: string) => Promise }; + vi.spyOn(manager, "ensureConnected").mockRejectedValue( + new TypeError("connect failed: /home/u/.fleetify/run.sock token=sk-test-123"), + ); + + await expect(wsManager.send("sess-1234abcd-ef", "hello")).rejects.toThrow(TypeError); + + await vi.waitFor(() => + expect(analytics.capture).toHaveBeenCalledWith("message_error", expect.anything()), + ); + const [, props] = analytics.capture.mock.calls.find(([name]) => name === "message_error")!; + expect(props).toEqual({ session_id_short: "sess-123", error_type: "TypeError" }); +}); diff --git a/src/services/ws-manager.ts b/src/services/ws-manager.ts index 6ac0515..0a34f02 100644 --- a/src/services/ws-manager.ts +++ b/src/services/ws-manager.ts @@ -1,5 +1,6 @@ import { createSessionsWebSocket } from "@/lib/api"; import { awaitConfigPatch } from "@/lib/session-config-sync"; +import { errorType } from "@/lib/log"; import { useChatStore, pushChatAuthRequired, markAuthSignedIn, pushChatError, pushGrokLogin } from "@/stores/chat-store"; import { useAppStore } from "@/stores/app-store"; import type { WSServerMessage, ImageBlock } from "@/types/chat"; @@ -1875,9 +1876,10 @@ class WSManager { } catch (err) { useChatStore.getState().clearStreaming(sessionId); void import("@/lib/posthog").then(({ capture }) => { + // The error's class only: its message can carry paths or tokens. capture("message_error", { session_id_short: sessionId.slice(0, 8), - error_message: err instanceof Error ? err.message : String(err), + error_type: errorType(err), }); }); throw err; diff --git a/src/stores/app-store.ts b/src/stores/app-store.ts index 14b2ca0..665f80e 100644 --- a/src/stores/app-store.ts +++ b/src/stores/app-store.ts @@ -281,6 +281,10 @@ interface AppState { pendingGeneration: PendingGeneration | null; newAgentDialogOpen: boolean; fleetAutoMode: boolean; + /** The shell could not save the sign-in to the OS keychain (shell auth + * event `keychain-unavailable`): this session works, but the next launch + * starts signed out. Drives . In memory only. */ + keychainWarning: boolean; _removedIds: Set; /** Compose surface state — see ComposerState docs. `open: false` means * the user is either on the Control Center (`activeSessionId === null`) @@ -347,6 +351,7 @@ interface AppState { setMainView: (view: MainView) => void; setAppMode: (mode: AppMode) => void; setNewAgentDialogOpen: (open: boolean) => void; + setKeychainWarning: (v: boolean) => void; /** Open the compose surface — pure client-side, no DB write, no * Session entry in `sessions[]`. Sets `composer.open = true` and * `activeSessionId = null`; chat-view detects the combination and @@ -455,6 +460,7 @@ export const useAppStore = create((set, get) => ({ pendingGeneration: null, newAgentDialogOpen: false, fleetAutoMode: localStorage.getItem("fleet:autoMode") === "true", + keychainWarning: false, composer: { open: false, projectPath: "", @@ -886,6 +892,7 @@ export const useAppStore = create((set, get) => ({ setPendingGeneration: (p) => set({ pendingGeneration: p }), clearPendingGeneration: () => set({ pendingGeneration: null }), setNewAgentDialogOpen: (open) => set({ newAgentDialogOpen: open }), + setKeychainWarning: (v) => set({ keychainWarning: v }), // ── Composer state (new) ── // The compose surface is NOT a session. Opening it sets composer.open // and clears activeSessionId; chat-view renders the welcome / folder diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index b5c25ed..3057e84 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -128,10 +128,17 @@ interface FleetConfig { updatesAuto?: boolean; /** Update channel — Stable / Beta / Canary. Default "stable". */ updatesChannel?: "stable" | "beta" | "canary"; - /** Anonymous usage analytics opt-out. Default true (opt-in by install). */ + /** Legacy: written by the old privacy card's analytics switch; nothing + * writes it now. An explicit `false` still means dashboard sync off + * while no newer choice is saved (`cloud_sync_from` in the shell). */ telemetryEnabled?: boolean; - /** Crash report opt-out. Default true (opt-in by install). */ + /** Legacy: written by the old "Crash reports" switch. Nothing reads it. */ crashReportsEnabled?: boolean; + /** Credit Fleetify in the commits it makes (`Co-Authored-By: Fleetify` + * trailer) and the pull requests it opens (footer). Default true; + * anything but `false` counts as on. Read by the shell on every + * Create-PR. Settings → General → Attribution. */ + gitAttribution?: boolean; } interface Window { @@ -147,21 +154,32 @@ interface Window { files: Record; }) => Promise<{ path?: string; written?: string[]; error?: string }>; getConfig: () => Promise; - setConfig: (config: FleetConfig) => Promise; + /** Replaces fleet.config.json. A save that failed answers + * `{ ok: false, error }` instead of throwing. */ + setConfig: (config: FleetConfig) => Promise<{ ok: boolean; error?: string }>; /** Read backend-owned telemetry config: stable per-machine - * distinct_id (= device.json device_id) and persisted PostHog - * opt-in flag. Called once at boot to bootstrap posthog-js with - * the same id the Rust sink uses. */ + * distinct_id (= device.json device_id), and whether product + * analytics (PostHog) and Fleetify cloud sync are on right now (the + * backend's live gates). Called at boot to decide whether to start + * posthog-js, with the same id the Rust sink uses. */ telemetryGetConfig?: () => Promise<{ distinct_id: string; posthog_enabled: boolean; + cloud_enabled: boolean; }>; /** Flip the persisted PostHog opt-in AND the backend's live * runtime gate. Used by the onboarding consent step and the - * Privacy settings toggle. */ + * Privacy settings toggle. `ok: false` means the gate changed but + * the choice wasn't saved, so it lasts until Fleetify restarts. */ telemetrySetPosthogEnabled?: ( enabled: boolean - ) => Promise<{ ok: boolean }>; + ) => Promise; + /** Flip the persisted Fleetify cloud sync switch AND the backend's + * live gate. Turning it off purges anything still queued. Resolves + * like `telemetrySetPosthogEnabled`. */ + telemetrySetCloudEnabled?: ( + enabled: boolean + ) => Promise; openFolderDialog: () => Promise; setWindowSize: ( width: number, @@ -283,6 +301,9 @@ interface Window { ) => () => void; openExternal: (url: string) => Promise; showItemInFolder: (path: string) => Promise; + /** Open a local folder, or a document file (Markdown, JSON, TOML, YAML, + * text…), with the system's default handler. Anything else is refused. */ + openPath: (path: string) => Promise<{ ok: boolean; error?: string }>; writeText: (text: string) => Promise; // ── PTY bridge ── diff --git a/vendor/tauri-runtime-wry/FLEETIFY_PATCH.md b/vendor/tauri-runtime-wry/FLEETIFY_PATCH.md index 56ebbd3..6e18e0e 100644 --- a/vendor/tauri-runtime-wry/FLEETIFY_PATCH.md +++ b/vendor/tauri-runtime-wry/FLEETIFY_PATCH.md @@ -1,9 +1,18 @@ -# Vendored `tauri-runtime-wry` — Fleetify patch (v2) +# Vendored `tauri-runtime-wry` — Fleetify patches This directory is a **verbatim copy of `tauri-runtime-wry` 2.11.2** from crates.io -with one behavioural change (in two parts). It exists only so we can carry that -change via `[patch.crates-io]` (see the workspace root `Cargo.toml`). Everything -else is upstream, unmodified. +with two changes. It exists only so we can carry them via `[patch.crates-io]` +(see the workspace root `Cargo.toml`). Everything else is upstream, unmodified. +Each change is marked in `src/lib.rs`: + +1. `FLEETIFY PATCH v2`: positioned child webviews on Linux (the right-panel + browser). See [Patch v2](#patch-v2-positioned-child-webviews-on-linux). +2. `FLEETIFY PATCH postmessage-ipc` (security): on WebKitGTK, every + postMessage IPC request gets an origin no capability matches, so a frame + inside the app can't use the app page's permissions. See + [Patch postmessage-ipc](#patch-postmessage-ipc-frames-cant-use-the-app-pages-permissions). + +# Patch v2: positioned child webviews on Linux ## Why @@ -93,7 +102,60 @@ instead. Only `WindowChild` is changed. `WindowContent` (the non-`unstable` main webview path) is byte-for-byte upstream. -## How to refresh on a Tauri bump +# Patch postmessage-ipc: frames can't use the app page's permissions + +## Why + +Tauri 2.11.2 accepts IPC two ways: the `ipc://` custom protocol, and wry's +postMessage channel (`window.ipc.postMessage`, on WebKitGTK +`window.webkit.messageHandlers.ipc`). On WebKitGTK the postMessage channel +can't tell frames apart: + +1. **wry tags every message with the main frame's URL.** wry 0.55's WebKitGTK + backend builds each request with `webview.uri()`, whichever frame posted it + (`src/webkitgtk/mod.rs`, `attach_ipc_handler`). +2. **Tauri takes that URL as the origin and checks only the invoke key.** + `ipc/protocol.rs` (`handle_ipc_message`) uses the request's URI as the + origin; `Webview::on_message` compares the key, then resolves the ACL for + that origin. +3. **The key isn't a secret from pages.** Tauri injects `ipc-protocol.js`, + which holds the app's one invoke key, into every webview it builds, the + right-panel browser included, so a page loaded there can capture it. +4. **So a frame gets the app page's permissions.** A cross-origin frame + inside the main webview (the Preview pane, showing a project's dev server + or any typed URL) that holds the key can post a request for any command + the app page has: since the release grant, every app command, `pty_spawn` + included. + +macOS and Windows are not affected: wry reports the sending frame's own URL +on macOS (`WKScriptMessage.frameInfo`), and WebView2 tags messages with the +top document's URL, where frames can't post. The `ipc://` path isn't either: +its requests carry the sending frame's own `Origin`, which the ACL refuses. + +## The change + +In `src/lib.rs` (search `FLEETIFY PATCH postmessage-ipc`): + +- `postmessage_ipc_request(request, webkitgtk)`: on WebKitGTK it replaces the + request's URI with `POSTMESSAGE_IPC_ORIGIN` + (`http://postmessage-ipc.invalid/`) and leaves the message alone; elsewhere + it returns the request unchanged. `WEBKITGTK` says which builds rewrite. +- `create_ipc_handler` passes every request through it before handing it to + Tauri. + +No capability matches that origin and `.invalid` never resolves, so Tauri +refuses every command such a request asks for, with its usual "not allowed" +error through the caller's error callback. The app's own IPC keeps working +through `ipc://`. All three are `#[doc(hidden)] pub` so the app's tests +(`src-tauri/src/shell/startup_window.rs`, "IPC from frames inside the app") +can check the rewrite, check the origin against the app's real ACL, and check +that `create_ipc_handler` still calls it. + +**Rewritten, not dropped:** `ipc-protocol.js` moves a page to postMessage for +good after one failed custom-protocol request. A dropped message would leave +the caller's promise pending forever; a refusal surfaces as an error. + +# How to refresh on a Tauri bump `[patch.crates-io]` requires this copy's version to equal the `tauri-runtime-wry` that `tauri` depends on, otherwise Cargo silently ignores @@ -103,18 +165,32 @@ the patch. 2. Re-copy that version's `Cargo.toml`, `build.rs`, `README.md`, `LICENSE_*`, and `src/` from `~/.cargo/registry/src/.../tauri-runtime-wry-/` over this directory. -3. Re-apply the v2 changes (search upstream for the - `// only way to account for menu bar height` comment for the WindowChild - arm; grep this repo's git history for `FLEETIFY PATCH v2` to recover the - full diff). +3. Re-apply both patches. Grep this repo's git history for `FLEETIFY PATCH` + to recover the full diffs. + - v2: search upstream for the `// only way to account for menu bar height` + comment for the WindowChild arm. + - postmessage-ipc: the three items go before `create_ipc_handler`, and its + closure starts with `let request = postmessage_ipc_request(request, + WEBKITGTK);`. First check that the new wry still tags WebKitGTK messages + with `webview.uri()` and that Tauri still takes the request's URI as + the origin; if either changed, re-assess rather than re-apply blindly. 4. Update the version note in the root `Cargo.toml` patch comment. -5. `cargo check -p fleetify-app`, then run the app and drive the right-panel - browser: position/resize, element-select typing + cursor, close panel (no - zombie frame), open the page inspector (no crash). - -## How to remove (once upstream is fixed) - -When a Tauri release positions Linux child webviews correctly **with working -keyboard focus and cursor updates**, delete this `vendor/` directory and the -`[patch.crates-io]` block in the root `Cargo.toml`. No application code changes -are needed — `add_child` / `set_bounds` are already the right calls. +5. `cargo test -p fleetify-app startup_window`: the postmessage-ipc tests + don't compile without the patch's items and fail if the handler stops + calling the rewrite. +6. Run the app and drive the right-panel browser: position/resize, + element-select typing + cursor, close panel (no zombie frame), open the + page inspector (no crash). Check that the app's own IPC still works on + Linux (it goes through `ipc://`). + +# How to remove (once upstream is fixed) + +- **v2:** when a Tauri release positions Linux child webviews correctly + **with working keyboard focus and cursor updates**. No application code + changes are needed: `add_child` / `set_bounds` are already the right calls. +- **postmessage-ipc:** when wry's WebKitGTK backend reports the sending + frame's own URL (or Tauri stops trusting the postMessage URL), and the + app's tests are moved to whatever upstream offers. + +Once both are gone, delete this `vendor/` directory and the +`[patch.crates-io]` block in the root `Cargo.toml`. diff --git a/vendor/tauri-runtime-wry/src/lib.rs b/vendor/tauri-runtime-wry/src/lib.rs index 0eaebd4..d26c22d 100644 --- a/vendor/tauri-runtime-wry/src/lib.rs +++ b/vendor/tauri-runtime-wry/src/lib.rs @@ -5539,6 +5539,56 @@ You may have it installed on another user account, but it is not available for t }) } +/// FLEETIFY PATCH postmessage-ipc (see vendor/tauri-runtime-wry/FLEETIFY_PATCH.md): +/// the URL every postMessage IPC request carries on WebKitGTK instead of the +/// one wry gives it. No capability matches it, and `.invalid` never resolves +/// (RFC 6761), so no page can have it: Tauri refuses whatever command such a +/// request asks for, with its usual "not allowed" error. +#[doc(hidden)] +pub const POSTMESSAGE_IPC_ORIGIN: &str = "http://postmessage-ipc.invalid/"; + +/// FLEETIFY PATCH postmessage-ipc: whether this build's webviews are +/// WebKitGTK (wry's `gtk` targets: Linux and the BSDs). +#[doc(hidden)] +pub const WEBKITGTK: bool = cfg!(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +)); + +/// FLEETIFY PATCH postmessage-ipc: a postMessage IPC request as Tauri gets +/// it. On WebKitGTK (`webkitgtk`) its URI becomes [`POSTMESSAGE_IPC_ORIGIN`]; +/// the message itself is untouched. Elsewhere the request is unchanged. +/// +/// Why: wry's WebKitGTK backend tags every postMessage request with +/// `webview.uri()`, the main frame's URL, whichever frame posted it. Tauri +/// takes that URL as the request's origin and checks only the invoke key, +/// which it injects into every webview it builds, the browser panel +/// included, so any page there can learn it. A cross-origin frame inside the +/// main webview that holds the key (the Preview pane) would then get every +/// command the app page has. The app's own IPC goes through the `ipc://` +/// custom protocol, whose requests carry the sending frame's own `Origin`. +/// +/// The request is rewritten, not dropped: `ipc-protocol.js` moves a page to +/// postMessage for good after one failed custom-protocol request, and a +/// dropped message would leave its promise pending forever. A refusal reaches +/// the caller's error callback instead. +/// +/// macOS is unchanged because wry reports the sending frame's own URL there +/// (`WKScriptMessage.frameInfo`), Windows because WebView2 tags messages with +/// the top document's URL and frames can't reach `chrome.webview`. +#[doc(hidden)] +pub fn postmessage_ipc_request(request: Request, webkitgtk: bool) -> Request { + if !webkitgtk { + return request; + } + let (mut parts, body) = request.into_parts(); + parts.uri = http::Uri::from_static(POSTMESSAGE_IPC_ORIGIN); + Request::from_parts(parts, body) +} + /// Create a wry ipc handler from a tauri ipc handler. fn create_ipc_handler( _kind: WebviewKind, @@ -5549,6 +5599,9 @@ fn create_ipc_handler( ipc_handler: Option>>, ) -> Box { Box::new(move |request| { + // FLEETIFY PATCH postmessage-ipc: on WebKitGTK the request's URL is the + // main frame's, not the sender's; give it an origin nothing matches. + let request = postmessage_ipc_request(request, WEBKITGTK); if let Some(handler) = &ipc_handler { handler( DetachedWebview {