diff --git a/.gitignore b/.gitignore index 86c991d..c5c5041 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,9 @@ *.swo *~ +# Local opencode agent configuration +/.opencode/ + # Operating-system metadata .DS_Store Thumbs.db diff --git a/Cargo.lock b/Cargo.lock index 57828fe..f5da1ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,46 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[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-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "bitflags" version = "2.13.1" @@ -34,6 +74,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + [[package]] name = "bytes" version = "1.12.1" @@ -46,6 +92,39 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[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.119", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "errno" version = "0.3.14" @@ -56,6 +135,26 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "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.5.0" @@ -76,6 +175,49 @@ dependencies = [ "xdg", ] +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[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-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + [[package]] name = "gdextension-api" version = "0.5.1" @@ -173,18 +315,51 @@ dependencies = [ "venial", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -224,6 +399,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "mio" version = "1.2.2" @@ -265,12 +449,37 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[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 = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -325,6 +534,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "serde" version = "1.0.229" @@ -368,6 +583,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -387,6 +613,12 @@ dependencies = [ "libc", ] +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.15.2" @@ -480,6 +712,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys", ] @@ -494,6 +727,36 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + [[package]] name = "tracing" version = "0.1.44" @@ -555,6 +818,17 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys", +] + [[package]] name = "unicase" version = "2.9.0" @@ -567,6 +841,17 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "uuid" +version = "1.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -587,6 +872,7 @@ version = "0.2.0" dependencies = [ "anyhow", "freedesktop-desktop-entry", + "futures-core", "serde_json", "tempfile", "thiserror", @@ -594,6 +880,7 @@ dependencies = [ "tracing", "tracing-subscriber", "velora-protocol", + "zbus", ] [[package]] @@ -621,6 +908,51 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.3", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -636,14 +968,129 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "xdg" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fb433233f2df9344722454bc7e96465c9d03bff9d77c248f9e7523fe79585b5" +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tokio", + "tracing", + "uds_windows", + "uuid", + "windows-sys", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.3", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.3", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.3", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml index 35e3352..9e38449 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,3 +16,4 @@ thiserror = "2.0" tokio = { version = "1.0", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } +zbus = { version = "5.19.0", default-features = false, features = ["tokio"] } diff --git a/README.md b/README.md index 24d96f3..fa86d76 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ > visual direction, and Linux integrations are expected to change. [![Status: work in progress](https://img.shields.io/badge/status-work_in_progress-f59e0b)](#project-status) -[![Phase: 4 complete](https://img.shields.io/badge/phase-4_complete-22c55e)](#current-status) +[![Phase: 5 local gate passed](https://img.shields.io/badge/phase-5_local_gate_passed-22c55e)](#current-status) [![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-22c55e)](LICENSE) [![CI](https://github.com/MoazMustafa-stack/Velora/actions/workflows/ci.yml/badge.svg)](https://github.com/MoazMustafa-stack/Velora/actions/workflows/ci.yml) [![Buy me a coffee](https://img.shields.io/badge/Support-Ko--fi-ff5e5b)](https://ko-fi.com/moazmustafa) @@ -30,8 +30,9 @@ normal desktop remains available if Velora exits. ## Current status -Phase 3 is complete. Phase 4 (system telemetry) is complete and merged to -`main` via PR #7. +Phases 1–4 are complete and merged to `main`. Phase 5 (D-Bus media and +notifications) is implemented on `dbus-media-core`; its cumulative local +release gate passes, and the work is awaiting commit/review/merge. Phase 1.01–1.10 provides a Godot 4.7 pixel-perfect foundation, a 16 px tile hub, eight-direction movement with four-direction facing, sprinting, physical @@ -61,6 +62,15 @@ HUD in the frontend. All sampling honors a user-facing privacy toggle (`VELORA_TELEMETRY_ENABLED`), and the Phase 4 release gate enforces strict CPU/RSS budgets so idle telemetry stays near zero cost. +Phase 5 upgrades the contract to protocol v5 and adds capability-gated MPRIS +media plus a memory-only notification feed. Core discovers players, publishes +changed-only snapshots, and accepts only six fixed media verbs against opaque +snapshot-issued handles. Notifications are disabled by default because +monitoring is privacy-sensitive; when explicitly enabled, Core observes only +the Notifications interface and retains at most 32 entries within a 4 KiB +serialized feed. Media and notifications are pushed live after the frontend's +initial request, without polling or blocking rendering. + ## Run For normal development, start the complete system with one command: @@ -82,6 +92,16 @@ You can still start the core and frontend in separate terminals: The default window is 960 × 540, rendered from a 320 × 180 internal canvas with integer nearest-neighbour scaling. Install Godot 4.7 and Rust first if needed. +Media observation is enabled by default and can be disabled with +`VELORA_MEDIA_ENABLED=false`. Notification observation is opt-in: + +```bash +VELORA_NOTIFICATIONS_ENABLED=true ./scripts/velora.sh dev +``` + +Automated runners disable both integrations or provide a private session bus; +they never contact the user's live D-Bus session. + The unified development runner exposes the common workflows: ```bash diff --git a/core/Cargo.toml b/core/Cargo.toml index af1b33b..74e7db8 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -8,11 +8,13 @@ description = "Safe Linux integration daemon for Velora" [dependencies] anyhow.workspace = true freedesktop-desktop-entry.workspace = true +futures-core = "0.3" serde_json.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true tracing-subscriber.workspace = true +zbus.workspace = true velora-protocol = { path = "../crates/velora-protocol" } [dev-dependencies] diff --git a/core/src/config.rs b/core/src/config.rs index 300281f..f1f804a 100644 --- a/core/src/config.rs +++ b/core/src/config.rs @@ -7,6 +7,8 @@ use velora_protocol::{ const TELEMETRY_INTERVAL_ENV: &str = "VELORA_TELEMETRY_INTERVAL_MS"; const TELEMETRY_ENABLED_ENV: &str = "VELORA_TELEMETRY_ENABLED"; +const MEDIA_ENABLED_ENV: &str = "VELORA_MEDIA_ENABLED"; +const NOTIFICATIONS_ENABLED_ENV: &str = "VELORA_NOTIFICATIONS_ENABLED"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TelemetryPolicy { @@ -67,10 +69,67 @@ impl TelemetryPolicy { } } +/// Privacy gate for the notification observer. Monitoring every notification +/// is the most privacy-sensitive capability Core has, so it is explicitly +/// toggleable; when disabled Core never opens a monitor connection and answers +/// notification requests with a typed unavailable result. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct NotificationsPolicy { + pub enabled: bool, +} + +impl NotificationsPolicy { + fn from_environment() -> Result { + Ok(Self { + enabled: match env::var(NOTIFICATIONS_ENABLED_ENV) { + Ok(value) => value.parse::().with_context(|| { + format!("{NOTIFICATIONS_ENABLED_ENV} must be true or false") + })?, + Err(env::VarError::NotPresent) => Self::default().enabled, + Err(env::VarError::NotUnicode(_)) => { + bail!("{NOTIFICATIONS_ENABLED_ENV} must contain valid UTF-8") + } + }, + }) + } +} + +/// Capability gate for MPRIS media observation and control. Media remains +/// enabled by default for the desktop experience, but tests and privacy-aware +/// sessions can disable every session-bus media connection explicitly. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MediaPolicy { + pub enabled: bool, +} + +impl Default for MediaPolicy { + fn default() -> Self { + Self { enabled: true } + } +} + +impl MediaPolicy { + fn from_environment() -> Result { + Ok(Self { + enabled: match env::var(MEDIA_ENABLED_ENV) { + Ok(value) => value + .parse::() + .with_context(|| format!("{MEDIA_ENABLED_ENV} must be true or false"))?, + Err(env::VarError::NotPresent) => Self::default().enabled, + Err(env::VarError::NotUnicode(_)) => { + bail!("{MEDIA_ENABLED_ENV} must contain valid UTF-8") + } + }, + }) + } +} + #[derive(Debug, Clone)] pub struct CoreConfig { pub socket_path: PathBuf, pub telemetry: TelemetryPolicy, + pub media: MediaPolicy, + pub notifications: NotificationsPolicy, } impl CoreConfig { @@ -78,6 +137,8 @@ impl CoreConfig { Ok(Self { socket_path: default_socket_path()?, telemetry: TelemetryPolicy::from_environment()?, + media: MediaPolicy::from_environment()?, + notifications: NotificationsPolicy::from_environment()?, }) } } @@ -143,4 +204,51 @@ mod tests { env::remove_var(TELEMETRY_ENABLED_ENV); } } + + #[test] + fn notifications_policy_defaults_to_disabled() { + let policy = NotificationsPolicy::default(); + assert!(!policy.enabled); + } + + #[test] + fn notifications_env_var_parses_true_and_false() { + unsafe { + env::remove_var(NOTIFICATIONS_ENABLED_ENV); + let policy = NotificationsPolicy::from_environment().unwrap(); + assert!(!policy.enabled); + + env::set_var(NOTIFICATIONS_ENABLED_ENV, "false"); + let policy = NotificationsPolicy::from_environment().unwrap(); + assert!(!policy.enabled); + + env::set_var(NOTIFICATIONS_ENABLED_ENV, "true"); + let policy = NotificationsPolicy::from_environment().unwrap(); + assert!(policy.enabled); + + env::set_var(NOTIFICATIONS_ENABLED_ENV, "maybe"); + assert!(NotificationsPolicy::from_environment().is_err()); + + env::remove_var(NOTIFICATIONS_ENABLED_ENV); + } + } + + #[test] + fn media_policy_defaults_to_enabled_and_parses_the_environment() { + unsafe { + env::remove_var(MEDIA_ENABLED_ENV); + assert!(MediaPolicy::from_environment().unwrap().enabled); + + env::set_var(MEDIA_ENABLED_ENV, "false"); + assert!(!MediaPolicy::from_environment().unwrap().enabled); + + env::set_var(MEDIA_ENABLED_ENV, "true"); + assert!(MediaPolicy::from_environment().unwrap().enabled); + + env::set_var(MEDIA_ENABLED_ENV, "maybe"); + assert!(MediaPolicy::from_environment().is_err()); + + env::remove_var(MEDIA_ENABLED_ENV); + } + } } diff --git a/core/src/dbus.rs b/core/src/dbus.rs new file mode 100644 index 0000000..a057025 --- /dev/null +++ b/core/src/dbus.rs @@ -0,0 +1,426 @@ +//! Session-bus-only D-Bus capability probe. +//! +//! Velora observes media (MPRIS) and notification state strictly through the +//! user session bus. This module connects using environment/address data (with +//! a `VELORA_SESSION_BUS_ADDRESS` override so automated tests never touch the +//! live session bus), reports whether the bus is reachable, reads the +//! Notifications daemon's `GetServerInformation`, and lists MPRIS player names +//! via `org.freedesktop.DBus.ListNames` filtered to +//! `org.mpris.MediaPlayer2.*`. +//! +//! A missing bus or a denied read is never fatal: every failure degrades to a +//! typed `Unavailable` (or `Restricted`) result. This module never contacts the +//! system bus, never takes over a bus name, and never opens a full-bus monitor. + +use std::{env, ffi::OsStr, time::Duration}; +use thiserror::Error; +use tokio::time::timeout; +use velora_protocol::MAX_MEDIA_PLAYERS; +use zbus::{Connection, Proxy, names::OwnedBusName, names::OwnedUniqueName}; + +/// Session-bus address override used by tests, mirroring the `VELORA_SOCKET` +/// rule. Production falls back to `DBUS_SESSION_BUS_ADDRESS` via zbus. +const SESSION_BUS_ADDRESS_ENV: &str = "VELORA_SESSION_BUS_ADDRESS"; + +/// Maximum length of a reported MPRIS player name. +const MAX_MPRIS_NAME_CHARS: usize = 256; +/// Maximum length of a Notifications daemon server-information field. +const MAX_NOTIFICATION_FIELD_CHARS: usize = 256; +/// Maximum wall-clock time allowed for the entire startup probe (connect plus +/// both read-only observations). A present but hung session-bus socket must +/// never block Core startup indefinitely. +const PROBE_TIMEOUT: Duration = Duration::from_secs(5); + +const NOTIFICATIONS_DESTINATION: &str = "org.freedesktop.Notifications"; +const NOTIFICATIONS_PATH: &str = "/org/freedesktop/Notifications"; +const NOTIFICATIONS_INTERFACE: &str = "org.freedesktop.Notifications"; +const MPRIS_NAME_PREFIX: &str = "org.mpris.MediaPlayer2."; +const ACCESS_DENIED_ERROR: &str = "org.freedesktop.DBus.Error.AccessDenied"; + +/// Whether the session bus is reachable. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BusAvailability { + Available, + Unavailable, +} + +/// Whether MPRIS media observation is possible. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum MediaAvailability { + Available, + Unavailable, +} + +/// Whether notification observation is possible. `Restricted` means the bus +/// reached us but denied the observation attempt (monitoring access). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum NotificationAvailability { + Available, + Unavailable, + /// The broker/daemon refused the observation attempt (denied monitoring). + Restricted, +} + +/// The Notifications daemon's reported server information. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct NotificationsServerInfo { + pub name: String, + pub vendor: String, + pub version: String, + pub spec_version: String, +} + +/// The result of the D-Bus capability probe. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct DbusCapabilities { + pub bus: BusAvailability, + pub media: MediaAvailability, + pub notifications: NotificationAvailability, + pub notifications_daemon: Option, + pub mpris_players: Vec, +} + +impl DbusCapabilities { + pub(crate) fn unavailable() -> Self { + Self { + bus: BusAvailability::Unavailable, + media: MediaAvailability::Unavailable, + notifications: NotificationAvailability::Unavailable, + notifications_daemon: None, + mpris_players: Vec::new(), + } + } +} + +/// Typed failure of the read-only session-bus probe. +#[derive(Debug, Error)] +pub(crate) enum DbusError { + #[error("session bus address override is not valid UTF-8")] + InvalidAddress, + #[error("failed to connect to the session bus: {0}")] + Connect(#[source] zbus::Error), + #[error("D-Bus probe call failed: {0}")] + Call(#[source] zbus::Error), + #[error("access to notification observation was denied")] + AccessDenied, +} + +/// Probe the session bus from environment/address data. Never fatal. +pub(crate) async fn probe_from_environment() -> DbusCapabilities { + probe_with_address(env::var_os(SESSION_BUS_ADDRESS_ENV).as_deref()).await +} + +async fn probe_with_address(override_address: Option<&OsStr>) -> DbusCapabilities { + probe_with_address_and_timeout(override_address, PROBE_TIMEOUT).await +} + +async fn probe_with_address_and_timeout( + override_address: Option<&OsStr>, + budget: Duration, +) -> DbusCapabilities { + timeout(budget, probe_with_address_inner(override_address)) + .await + .unwrap_or_else(|_| DbusCapabilities::unavailable()) +} + +async fn probe_with_address_inner(override_address: Option<&OsStr>) -> DbusCapabilities { + let Ok(connection) = connect_session(override_address).await else { + return DbusCapabilities::unavailable(); + }; + + let (notifications, media) = + tokio::join!(probe_notifications(&connection), probe_media(&connection),); + + DbusCapabilities { + bus: BusAvailability::Available, + media: media.availability, + notifications: notifications.availability, + notifications_daemon: notifications.daemon, + mpris_players: media.players, + } +} + +async fn connect_session(override_address: Option<&OsStr>) -> Result { + match override_address { + Some(address) => { + let address = address.to_str().ok_or(DbusError::InvalidAddress)?; + zbus::connection::Builder::address(address) + .map_err(DbusError::Connect)? + .build() + .await + .map_err(DbusError::Connect) + } + None => Connection::session().await.map_err(DbusError::Connect), + } +} + +struct NotificationsProbe { + availability: NotificationAvailability, + daemon: Option, +} + +async fn probe_notifications(connection: &Connection) -> NotificationsProbe { + match read_server_information(connection).await { + Ok(info) => NotificationsProbe { + availability: NotificationAvailability::Available, + daemon: Some(info), + }, + Err(error) => NotificationsProbe { + availability: classify_notifications_error(&error), + daemon: None, + }, + } +} + +async fn read_server_information( + connection: &Connection, +) -> Result { + let proxy = Proxy::new( + connection, + NOTIFICATIONS_DESTINATION, + NOTIFICATIONS_PATH, + NOTIFICATIONS_INTERFACE, + ) + .await + .map_err(map_call_error)?; + + let (name, vendor, version, spec_version): (String, String, String, String) = proxy + .call("GetServerInformation", &()) + .await + .map_err(map_call_error)?; + + Ok(NotificationsServerInfo { + name: bounded_string(&name, MAX_NOTIFICATION_FIELD_CHARS), + vendor: bounded_string(&vendor, MAX_NOTIFICATION_FIELD_CHARS), + version: bounded_string(&version, MAX_NOTIFICATION_FIELD_CHARS), + spec_version: bounded_string(&spec_version, MAX_NOTIFICATION_FIELD_CHARS), + }) +} + +struct MediaProbe { + availability: MediaAvailability, + players: Vec, +} + +async fn probe_media(connection: &Connection) -> MediaProbe { + match list_names(connection).await { + Ok(names) => MediaProbe { + availability: MediaAvailability::Available, + players: mpris_player_names(names.iter().map(|name| name.as_str())), + }, + Err(_) => MediaProbe { + availability: MediaAvailability::Unavailable, + players: Vec::new(), + }, + } +} + +async fn list_names(connection: &Connection) -> Result, DbusError> { + let proxy = zbus::fdo::DBusProxy::new(connection) + .await + .map_err(map_call_error)?; + proxy.list_names().await.map_err(map_fdo_error) +} + +/// List the `org.mpris.MediaPlayer2.*` well-known names currently owned on the +/// session bus. This is the media store's discovery half (P5.05): filtered and +/// bounded to [`MAX_MEDIA_PLAYERS`], so a hostile or overflowing name list can +/// never grow the snapshot unboundedly. +pub(crate) async fn list_players(connection: &Connection) -> Result, DbusError> { + let names = list_names(connection).await?; + Ok(mpris_player_names(names.iter().map(|name| name.as_str()))) +} + +/// Resolve a player well-known name to its current unique owner. The media +/// store records this at refresh time and re-checks it at control-dispatch time +/// (P5.06), so a vanished player (no owner) or a replaced player (different +/// owner) always fails closed instead of dispatching to the wrong connection. +pub(crate) async fn player_owner( + connection: &Connection, + player_name: &str, +) -> Result { + let proxy = Proxy::new( + connection, + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + ) + .await + .map_err(map_call_error)?; + + proxy + .call("GetNameOwner", &(player_name,)) + .await + .map_err(map_call_error) +} + +/// Keep only `org.mpris.MediaPlayer2.*` well-known names, bounded and trimmed. +fn mpris_player_names<'a>(names: impl IntoIterator) -> Vec { + names + .into_iter() + .filter(|name| name.starts_with(MPRIS_NAME_PREFIX)) + .map(|name| bounded_string(name, MAX_MPRIS_NAME_CHARS)) + .take(MAX_MEDIA_PLAYERS) + .collect() +} + +fn map_call_error(error: zbus::Error) -> DbusError { + if is_access_denied(&error) { + DbusError::AccessDenied + } else { + DbusError::Call(error) + } +} + +fn map_fdo_error(error: zbus::fdo::Error) -> DbusError { + match error { + zbus::fdo::Error::AccessDenied(_) => DbusError::AccessDenied, + other => DbusError::Call(other.into()), + } +} + +fn is_access_denied(error: &zbus::Error) -> bool { + matches!( + error, + zbus::Error::MethodError(name, _, _) if name.as_str() == ACCESS_DENIED_ERROR + ) +} + +fn classify_notifications_error(error: &DbusError) -> NotificationAvailability { + match error { + DbusError::AccessDenied => NotificationAvailability::Restricted, + _ => NotificationAvailability::Unavailable, + } +} + +fn bounded_string(value: &str, max_chars: usize) -> String { + value.trim().chars().take(max_chars).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::ffi::OsStrExt; + + /// A well-formed but unreachable session-bus address. Connecting fails + /// immediately (no socket at this path), so no live bus is ever contacted. + const BOGUS_BUS_ADDRESS: &str = "unix:path=/nonexistent/velora-test-bus"; + + #[tokio::test] + async fn unreachable_bus_reports_everything_unavailable() { + let capabilities = probe_with_address(Some(OsStr::new(BOGUS_BUS_ADDRESS))).await; + + assert_eq!(capabilities.bus, BusAvailability::Unavailable); + assert_eq!(capabilities.media, MediaAvailability::Unavailable); + assert_eq!( + capabilities.notifications, + NotificationAvailability::Unavailable + ); + assert!(capabilities.notifications_daemon.is_none()); + assert!(capabilities.mpris_players.is_empty()); + } + + #[tokio::test] + async fn non_utf8_override_is_a_typed_unavailable() { + let address = OsStr::from_bytes(&[0xff, 0xfe, 0xfd]); + let capabilities = probe_with_address(Some(address)).await; + + assert_eq!(capabilities.bus, BusAvailability::Unavailable); + } + + #[tokio::test] + async fn hung_bus_socket_times_out_to_unavailable() { + use std::os::unix::net::UnixListener as StdUnixListener; + + let directory = tempfile::tempdir().unwrap(); + let socket_path = directory.path().join("hung-bus"); + let listener = StdUnixListener::bind(&socket_path).unwrap(); + + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + // Accept the client and hold the stream open without answering the + // auth handshake, so the probe must time out instead of blocking. + let (_stream, _address) = listener.accept().unwrap(); + let _ = stop_rx.recv(); + }); + + let address = format!("unix:path={}", socket_path.display()); + let capabilities = + probe_with_address_and_timeout(Some(OsStr::new(&address)), Duration::from_millis(100)) + .await; + + let _ = stop_tx.send(()); + server.join().unwrap(); + + assert_eq!(capabilities.bus, BusAvailability::Unavailable); + } + + #[test] + fn filters_only_mpris_player_names_within_bounds() { + let long: String = "y".repeat(MAX_MPRIS_NAME_CHARS + 100); + let names = [ + "org.mpris.MediaPlayer2.spotify".to_string(), + "org.freedesktop.Notifications".to_string(), + ":1.42".to_string(), + format!("org.mpris.MediaPlayer2.{long}"), + ]; + + let players = mpris_player_names(names.iter().map(String::as_str)); + + assert_eq!(players.len(), 2); + assert_eq!(players[0], "org.mpris.MediaPlayer2.spotify"); + assert!(players[1].starts_with("org.mpris.MediaPlayer2.")); + assert_eq!(players[1].chars().count(), MAX_MPRIS_NAME_CHARS); + } + + #[test] + fn caps_mpris_players_at_the_probe_limit() { + let names: Vec = (0..MAX_MEDIA_PLAYERS + 5) + .map(|i| format!("org.mpris.MediaPlayer2.player{i}")) + .collect(); + + let players = mpris_player_names(names.iter().map(String::as_str)); + + assert_eq!(players.len(), MAX_MEDIA_PLAYERS); + } + + #[test] + fn denied_access_classifies_as_restricted() { + assert_eq!( + classify_notifications_error(&DbusError::AccessDenied), + NotificationAvailability::Restricted + ); + } + + #[test] + fn other_call_failures_classify_as_unavailable() { + let io = std::io::Error::other("boom"); + let call_error = DbusError::Call(zbus::Error::InputOutput(std::sync::Arc::new(io))); + + assert_eq!( + classify_notifications_error(&call_error), + NotificationAvailability::Unavailable + ); + assert_eq!( + classify_notifications_error(&DbusError::InvalidAddress), + NotificationAvailability::Unavailable + ); + assert_eq!( + classify_notifications_error(&DbusError::Connect(zbus::Error::Unsupported)), + NotificationAvailability::Unavailable + ); + } + + #[test] + fn strings_are_trimmed_and_char_bounded() { + assert_eq!(bounded_string(" padded ", 8), "padded"); + + let long = "🦀".repeat(MAX_NOTIFICATION_FIELD_CHARS + 50); + assert_eq!( + bounded_string(&long, MAX_NOTIFICATION_FIELD_CHARS) + .chars() + .count(), + MAX_NOTIFICATION_FIELD_CHARS + ); + } +} diff --git a/core/src/ipc.rs b/core/src/ipc.rs index 1d61bfe..5034e53 100644 --- a/core/src/ipc.rs +++ b/core/src/ipc.rs @@ -21,12 +21,17 @@ use tokio::{ use tracing::{info, warn}; use velora_protocol::{ Application, HANDSHAKE_TIMEOUT_SECONDS, HyprlandAvailability, HyprlandCapabilities, - MAX_APPLICATION_PAGE_SIZE, MAX_MESSAGE_BYTES, PROTOCOL_VERSION, Request, Response, SERVER_NAME, + MAX_APPLICATION_PAGE_SIZE, MAX_MESSAGE_BYTES, MediaControlError, MediaControlVerb, + MediaSnapshotError, NotificationsError, PROTOCOL_VERSION, Request, Response, SERVER_NAME, TelemetrySnapshotError, WindowFocusError, WorkspaceSnapshotError, WorkspaceSwitchError, }; -use crate::{session_store::SessionStore, telemetry::runtime::TelemetryStore}; +use crate::{ + dbus::NotificationAvailability, media_store::MediaStore, notifications::NotificationStore, + session_store::SessionStore, telemetry::runtime::TelemetryStore, +}; +#[allow(clippy::too_many_arguments)] pub(crate) async fn serve( config: CoreConfig, applications: Arc<[Application]>, @@ -35,6 +40,9 @@ pub(crate) async fn serve( session: Option>, telemetry: Arc, telemetry_enabled: bool, + notifications: Arc, + notifications_enabled: bool, + media: Option>, ) -> Result<()> { serve_until( config, @@ -44,6 +52,9 @@ pub(crate) async fn serve( session, telemetry, telemetry_enabled, + notifications, + notifications_enabled, + media, async { tokio::signal::ctrl_c() .await @@ -62,6 +73,9 @@ async fn serve_until( session: Option>, telemetry: Arc, telemetry_enabled: bool, + notifications: Arc, + notifications_enabled: bool, + media: Option>, shutdown: F, ) -> Result<()> where @@ -86,6 +100,8 @@ where let hyprland_capabilities = hyprland_capabilities.clone(); let session = session.clone(); let telemetry = Arc::clone(&telemetry); + let notifications = Arc::clone(¬ifications); + let media = media.clone(); tokio::spawn(async move { if let Err(error) = handle_connection_with_services( stream, @@ -95,6 +111,9 @@ where session, telemetry, telemetry_enabled, + notifications, + notifications_enabled, + media, ) .await { @@ -189,10 +208,14 @@ where session, Arc::new(TelemetryStore::default()), true, + Arc::new(NotificationStore::new()), + false, + None, ) .await } +#[allow(clippy::too_many_arguments)] async fn handle_connection_with_services( stream: UnixStream, applications: Arc<[Application]>, @@ -201,6 +224,9 @@ async fn handle_connection_with_services( session: Option>, telemetry: Arc, telemetry_enabled: bool, + notifications: Arc, + notifications_enabled: bool, + media: Option>, ) -> Result<()> where L: ApplicationLauncher + 'static, @@ -208,10 +234,12 @@ where info!("frontend connected"); let (reader, mut writer) = stream.into_split(); let mut reader = BufReader::new(reader); + // Keep partial frames across cancellation by unsolicited snapshot updates. + let mut frame_bytes = Vec::new(); let first_frame = match timeout( Duration::from_secs(HANDSHAKE_TIMEOUT_SECONDS), - read_frame(&mut reader), + read_frame(&mut reader, &mut frame_bytes), ) .await { @@ -290,13 +318,17 @@ where } let mut snapshot_updates = session.as_ref().map(|store| store.subscribe()); + let mut media_updates = media.as_ref().map(|store| store.subscribe()); + let mut notification_updates = notifications_enabled.then(|| notifications.subscribe()); // Do not interleave a pushed snapshot into a client that has not yet // requested its initial state. Once it has, every later changed snapshot // is delivered with request ID zero. let mut session_updates_enabled = false; + let mut media_updates_enabled = false; + let mut notification_updates_enabled = false; loop { let line = tokio::select! { - frame = read_frame(&mut reader) => { + frame = read_frame(&mut reader, &mut frame_bytes) => { let Some(line) = frame_to_line(frame?, &mut writer).await? else { break; }; @@ -327,6 +359,54 @@ where .await?; continue; } + changed = wait_for_media_update(&mut media_updates) => { + if changed.is_err() { + break; + } + let snapshot = media_updates + .as_mut() + .and_then(|receiver| receiver.borrow_and_update().clone()); + if !media_updates_enabled { + continue; + } + let Some(snapshot) = snapshot else { + continue; + }; + write_response( + &mut writer, + &Response::MediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 0, + snapshot: (*snapshot).clone(), + }, + ) + .await?; + continue; + } + changed = wait_for_notification_update(&mut notification_updates) => { + if changed.is_err() { + break; + } + let feed = notification_updates + .as_mut() + .and_then(|receiver| receiver.borrow_and_update().clone()); + if !notification_updates_enabled { + continue; + } + let Some(feed) = feed else { + continue; + }; + write_response( + &mut writer, + &Response::Notifications { + protocol_version: PROTOCOL_VERSION, + request_id: 0, + feed: (*feed).clone(), + }, + ) + .await?; + continue; + } }; let response = match serde_json::from_str::(&line) { Ok(request) if request.protocol_version() != PROTOCOL_VERSION => { @@ -430,6 +510,28 @@ where retryable: true, }, }, + // The media store serves the cached authoritative snapshot and + // falls back to one on-demand refresh when nothing is cached yet. + Ok(Request::GetMediaSnapshot { request_id, .. }) => { + media_snapshot_response(request_id, media.as_deref()).await + } + Ok(Request::GetNotifications { request_id, .. }) if !notifications_enabled => { + Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + code: NotificationsError::NotificationsUnavailable, + retryable: false, + } + } + Ok(Request::GetNotifications { request_id, .. }) => { + notifications_response(request_id, ¬ifications) + } + Ok(Request::SendMediaControl { + request_id, + player_handle, + verb, + .. + }) => media_control_response(request_id, &player_handle, verb, media.as_deref()).await, Ok(Request::Hello { .. }) => { Response::error("already_handshaken", "hello has already completed", false) } @@ -449,6 +551,24 @@ where } session_updates_enabled = true; } + if matches!( + response, + Response::MediaSnapshot { .. } | Response::MediaSnapshotRejected { .. } + ) { + if let Some(receiver) = &mut media_updates { + receiver.borrow_and_update(); + } + media_updates_enabled = true; + } + if matches!( + response, + Response::Notifications { .. } | Response::NotificationsRejected { .. } + ) { + if let Some(receiver) = &mut notification_updates { + receiver.borrow_and_update(); + } + notification_updates_enabled = true; + } write_response(&mut writer, &response).await?; if should_close { break; @@ -467,6 +587,124 @@ async fn wait_for_snapshot_update( } } +async fn wait_for_media_update( + receiver: &mut Option>>>, +) -> Result<(), watch::error::RecvError> { + match receiver { + Some(receiver) => receiver.changed().await, + None => std::future::pending().await, + } +} + +async fn wait_for_notification_update( + receiver: &mut Option>>>, +) -> Result<(), watch::error::RecvError> { + match receiver { + Some(receiver) => receiver.changed().await, + None => std::future::pending().await, + } +} + +/// Serve the bounded notification feed with typed, fail-closed outcomes. +/// `Restricted` (denied monitoring) never serves a feed; `Unavailable` means +/// the monitor could not observe; an empty-but-available monitor reports +/// `FeedNotReady` so the frontend can distinguish "no notifications yet". +fn notifications_response(request_id: u64, store: &NotificationStore) -> Response { + match store.availability() { + NotificationAvailability::Restricted => Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + code: NotificationsError::MonitorRestricted, + retryable: false, + }, + NotificationAvailability::Unavailable => Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + code: NotificationsError::NotificationsUnavailable, + retryable: true, + }, + NotificationAvailability::Available => match store.current() { + Some(feed) => Response::Notifications { + protocol_version: PROTOCOL_VERSION, + request_id, + feed: (*feed).clone(), + }, + None => Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + code: NotificationsError::FeedNotReady, + retryable: true, + }, + }, + } +} + +/// Serve the authoritative cached media snapshot; when nothing is cached yet +/// and media observation is available, fall back to one on-demand refresh. +/// Any failure degrades to the typed rejection instead of an error response. +async fn media_snapshot_response(request_id: u64, media: Option<&MediaStore>) -> Response { + let Some(store) = media else { + return Response::MediaSnapshotRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + code: MediaSnapshotError::MediaUnavailable, + retryable: false, + }; + }; + + if store.current().is_none() { + let _ = store.refresh().await; + } + + match store.current() { + Some(snapshot) => Response::MediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id, + snapshot: (*snapshot).clone(), + }, + None => Response::MediaSnapshotRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + code: MediaSnapshotError::SnapshotNotReady, + retryable: true, + }, + } +} + +/// Fail-closed media control: dispatch only through a snapshot-issued opaque +/// handle plus one allowlisted verb. The store re-validates the handle against +/// the live bus and maps the verb to a fixed MPRIS method; the IPC layer never +/// supplies a bus name, method name, or argument. +async fn media_control_response( + request_id: u64, + player_handle: &str, + verb: MediaControlVerb, + media: Option<&MediaStore>, +) -> Response { + let Some(store) = media else { + return Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + player_handle: player_handle.to_owned(), + code: MediaControlError::MediaUnavailable, + }; + }; + + match store.control(player_handle, verb).await { + Ok(()) => Response::MediaControlAccepted { + protocol_version: PROTOCOL_VERSION, + request_id, + player_handle: player_handle.to_owned(), + }, + Err(code) => Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id, + player_handle: player_handle.to_owned(), + code, + }, + } +} + fn workspace_snapshot_rejection(request_id: u64, capabilities: &HyprlandCapabilities) -> Response { let code = match capabilities.availability { HyprlandAvailability::Unavailable => WorkspaceSnapshotError::HyprlandUnavailable, @@ -699,11 +937,10 @@ enum Frame { InvalidUtf8, } -async fn read_frame(reader: &mut R) -> io::Result +async fn read_frame(reader: &mut R, bytes: &mut Vec) -> io::Result where R: AsyncBufRead + Unpin, { - let mut bytes = Vec::new(); loop { let available = reader.fill_buf().await?; if available.is_empty() { @@ -721,7 +958,7 @@ where } bytes.extend_from_slice(&available[..newline_index]); reader.consume(newline_index + 1); - return Ok(match String::from_utf8(bytes) { + return Ok(match String::from_utf8(std::mem::take(bytes)) { Ok(line) => Frame::Line(line), Err(_) => Frame::InvalidUtf8, }); @@ -818,7 +1055,7 @@ impl Drop for SocketGuard { #[cfg(test)] mod tests { use super::*; - use crate::launch::LaunchError; + use crate::{launch::LaunchError, notifications::NotifyObservation}; use std::{ future::ready, os::unix::fs::symlink, os::unix::net::UnixListener as StdUnixListener, sync::Mutex, @@ -826,6 +1063,33 @@ mod tests { use tempfile::tempdir; use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; use tokio::sync::oneshot; + use velora_protocol::{MediaControlVerb, MediaPlayer, NotificationUrgency, PlaybackStatus}; + + #[tokio::test] + async fn partial_frame_survives_snapshot_cancellation() { + let (mut client, server) = tokio::io::duplex(128); + let mut reader = BufReader::new(server); + let mut bytes = Vec::new(); + client.write_all(b"{\"type\":").await.unwrap(); + + // Poll the read first, then simulate a ready snapshot branch cancelling it. + tokio::select! { + biased; + _ = read_frame(&mut reader, &mut bytes) => panic!("incomplete frame completed"), + _ = ready(()) => {} + } + assert_eq!(bytes, b"{\"type\":"); + client.write_all(b"\"ping\"}\nnext\n").await.unwrap(); + let Frame::Line(line) = read_frame(&mut reader, &mut bytes).await.unwrap() else { + panic!("expected complete frame"); + }; + assert_eq!(line, "{\"type\":\"ping\"}"); + assert!(bytes.is_empty()); + let Frame::Line(line) = read_frame(&mut reader, &mut bytes).await.unwrap() else { + panic!("expected subsequent frame"); + }; + assert_eq!(line, "next"); + } #[derive(Clone, Copy)] enum MockLaunchOutcome { @@ -873,6 +1137,10 @@ mod tests { .write_all(format!("{request}\n").as_bytes()) .await .unwrap(); + read_response(reader).await + } + + async fn read_response(reader: &mut BufReader) -> Response { let mut line = String::new(); reader.read_line(&mut line).await.unwrap(); serde_json::from_str(line.trim()).unwrap() @@ -1340,6 +1608,8 @@ mod tests { let config = CoreConfig { socket_path: socket_path.clone(), telemetry: crate::config::TelemetryPolicy::default(), + media: crate::config::MediaPolicy::default(), + notifications: crate::config::NotificationsPolicy::default(), }; let launcher = Arc::new(MockLauncher::new(MockLaunchOutcome::Accepted( 5000 + generation, @@ -1353,6 +1623,9 @@ mod tests { dead_session_store(), Arc::new(TelemetryStore::default()), true, + Arc::new(NotificationStore::new()), + false, + None, async move { shutdown_rx.await.context("test shutdown sender dropped")?; Ok(()) @@ -1518,6 +1791,9 @@ mod tests { dead_session_store(), Arc::new(TelemetryStore::default()), false, + Arc::new(NotificationStore::new()), + false, + None, )); let mut reader = BufReader::new(client); @@ -1553,6 +1829,754 @@ mod tests { server_task.await.unwrap().unwrap(); } + #[tokio::test] + async fn answers_media_and_notification_requests_with_typed_unavailable_paths() { + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + )); + let mut reader = BufReader::new(client); + + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::GetMediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 101, + }, + ) + .await, + Response::MediaSnapshotRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 101, + code: MediaSnapshotError::MediaUnavailable, + retryable: false, + } + ); + + assert_eq!( + send_request( + &mut reader, + &Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 102, + }, + ) + .await, + Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 102, + code: NotificationsError::NotificationsUnavailable, + retryable: false, + } + ); + + // Control is rejected without ever touching a bus name or D-Bus method. + assert_eq!( + send_request( + &mut reader, + &Request::SendMediaControl { + protocol_version: PROTOCOL_VERSION, + request_id: 103, + player_handle: "player:opaque-1".to_owned(), + verb: MediaControlVerb::PlayPause, + }, + ) + .await, + Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 103, + player_handle: "player:opaque-1".to_owned(), + code: MediaControlError::MediaUnavailable, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + fn populated_notification_store() -> Arc { + let store = Arc::new(NotificationStore::new()); + store.set_availability(NotificationAvailability::Available); + store.observe( + NotifyObservation { + app_name: "Chat".to_owned(), + summary: "Hello".to_owned(), + body: "World".to_owned(), + urgency: NotificationUrgency::Normal, + }, + 1_000, + ); + store + } + + #[tokio::test] + async fn notifications_disabled_returns_typed_unavailable() { + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + None, + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 111, + }, + ) + .await, + Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 111, + code: NotificationsError::NotificationsUnavailable, + retryable: false, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn denied_monitoring_returns_typed_restricted() { + let store = Arc::new(NotificationStore::new()); + store.set_availability(NotificationAvailability::Restricted); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + store, + true, + None, + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 112, + }, + ) + .await, + Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 112, + code: NotificationsError::MonitorRestricted, + retryable: false, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn serves_the_bounded_notification_feed() { + let store = populated_notification_store(); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + store, + true, + None, + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + let response = send_request( + &mut reader, + &Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 113, + }, + ) + .await; + let Response::Notifications { + request_id, feed, .. + } = response + else { + panic!("expected a notification feed"); + }; + assert_eq!(request_id, 113); + assert_eq!(feed.sequence, 1); + assert_eq!(feed.notifications.len(), 1); + assert_eq!(feed.notifications[0].app_name, "Chat"); + assert_eq!(feed.notifications[0].handle, "notification:1"); + feed.validate().unwrap(); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn pushes_changed_notification_feeds_after_the_initial_request() { + let store = populated_notification_store(); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::clone(&store), + true, + None, + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + let initial = send_request( + &mut reader, + &Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 115, + }, + ) + .await; + assert!(matches!( + initial, + Response::Notifications { + request_id: 115, + .. + } + )); + + store.observe( + NotifyObservation { + app_name: "Mail".to_owned(), + summary: "New message".to_owned(), + body: "Bounded preview".to_owned(), + urgency: NotificationUrgency::Low, + }, + 2_000, + ); + let pushed = timeout(Duration::from_secs(1), read_response(&mut reader)) + .await + .unwrap(); + let Response::Notifications { + request_id, feed, .. + } = pushed + else { + panic!("expected a pushed notification feed"); + }; + assert_eq!(request_id, 0); + assert_eq!(feed.sequence, 2); + assert_eq!(feed.notifications.last().unwrap().app_name, "Mail"); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn available_monitor_without_feed_reports_not_ready() { + let store = Arc::new(NotificationStore::new()); + store.set_availability(NotificationAvailability::Available); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + store, + true, + None, + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 114, + }, + ) + .await, + Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 114, + code: NotificationsError::FeedNotReady, + retryable: true, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + fn test_media_player(handle: &str, status: PlaybackStatus) -> MediaPlayer { + MediaPlayer { + handle: handle.to_owned(), + identity: "Spotify".to_owned(), + status, + title: Some("Velora Theme".to_owned()), + artist: Some("Velora".to_owned()), + album: Some("Phase 5".to_owned()), + length_micros: Some(250_000_000), + position_micros: 12_500_000, + can_play: true, + can_pause: true, + can_go_next: true, + can_go_previous: true, + can_seek: true, + can_control: true, + } + } + + fn populated_media_store() -> Arc { + let store = Arc::new(MediaStore::new(None)); + store + .apply(vec![test_media_player( + "player:opaque-1", + PlaybackStatus::Playing, + )]) + .unwrap(); + store + } + + #[tokio::test] + async fn serves_the_authoritative_media_snapshot() { + let store = populated_media_store(); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + Some(store), + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + let response = send_request( + &mut reader, + &Request::GetMediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 121, + }, + ) + .await; + let Response::MediaSnapshot { + request_id, + snapshot, + .. + } = response + else { + panic!("expected a media snapshot"); + }; + assert_eq!(request_id, 121); + assert_eq!(snapshot.sequence, 1); + assert_eq!(snapshot.players.len(), 1); + assert_eq!(snapshot.players[0].handle, "player:opaque-1"); + assert_eq!( + snapshot.active_player_handle.as_deref(), + Some("player:opaque-1") + ); + snapshot.validate().unwrap(); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn pushes_changed_media_snapshots_after_the_initial_request() { + let store = populated_media_store(); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + Some(Arc::clone(&store)), + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + let initial = send_request( + &mut reader, + &Request::GetMediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 124, + }, + ) + .await; + assert!(matches!( + initial, + Response::MediaSnapshot { + request_id: 124, + .. + } + )); + + store + .apply(vec![test_media_player( + "player:opaque-1", + PlaybackStatus::Paused, + )]) + .unwrap(); + let pushed = timeout(Duration::from_secs(1), read_response(&mut reader)) + .await + .unwrap(); + let Response::MediaSnapshot { + request_id, + snapshot, + .. + } = pushed + else { + panic!("expected a pushed media snapshot"); + }; + assert_eq!(request_id, 0); + assert_eq!(snapshot.sequence, 2); + assert_eq!(snapshot.players[0].status, PlaybackStatus::Paused); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn media_control_rejects_unknown_and_stale_handles() { + let store = populated_media_store(); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + Some(store), + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + // A handle that was never issued cannot control anything. + assert_eq!( + send_request( + &mut reader, + &Request::SendMediaControl { + protocol_version: PROTOCOL_VERSION, + request_id: 131, + player_handle: "player:never-issued".to_owned(), + verb: MediaControlVerb::Play, + }, + ) + .await, + Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 131, + player_handle: "player:never-issued".to_owned(), + code: MediaControlError::UnknownPlayer, + } + ); + + // A handle present in the snapshot but with no live target is stale. + assert_eq!( + send_request( + &mut reader, + &Request::SendMediaControl { + protocol_version: PROTOCOL_VERSION, + request_id: 132, + player_handle: "player:opaque-1".to_owned(), + verb: MediaControlVerb::Play, + }, + ) + .await, + Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 132, + player_handle: "player:opaque-1".to_owned(), + code: MediaControlError::StaleHandle, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn media_control_rejects_a_non_controllable_player() { + let store = Arc::new(MediaStore::new(None)); + let mut player = test_media_player("player:opaque-1", PlaybackStatus::Playing); + player.can_control = false; + store.apply(vec![player]).unwrap(); + + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + Some(store), + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::SendMediaControl { + protocol_version: PROTOCOL_VERSION, + request_id: 133, + player_handle: "player:opaque-1".to_owned(), + verb: MediaControlVerb::Play, + }, + ) + .await, + Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 133, + player_handle: "player:opaque-1".to_owned(), + code: MediaControlError::ControlUnavailable, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn media_unavailable_returns_typed_unavailable() { + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + None, + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::GetMediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 122, + }, + ) + .await, + Response::MediaSnapshotRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 122, + code: MediaSnapshotError::MediaUnavailable, + retryable: false, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn available_media_without_snapshot_reports_not_ready() { + // A store with no cached snapshot and an unreachable bus: the on-demand + // refresh fails fast and the handler reports a typed not-ready result. + let store = Arc::new(MediaStore::new(Some(std::ffi::OsString::from( + "unix:path=/nonexistent/velora-test-media-bus", + )))); + let (server, client) = UnixStream::pair().unwrap(); + let server_task = tokio::spawn(handle_connection_with_services( + server, + Arc::from([]), + Arc::new(LaunchService::empty()), + HyprlandCapabilities::unavailable(), + dead_session_store(), + Arc::new(TelemetryStore::default()), + true, + Arc::new(NotificationStore::new()), + false, + Some(store), + )); + let mut reader = BufReader::new(client); + let hello = send_request( + &mut reader, + &Request::Hello { + protocol_version: PROTOCOL_VERSION, + client_name: "test-client".to_owned(), + client_version: "0.3.0".to_owned(), + }, + ) + .await; + assert!(matches!(hello, Response::Welcome { .. })); + + assert_eq!( + send_request( + &mut reader, + &Request::GetMediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 123, + }, + ) + .await, + Response::MediaSnapshotRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 123, + code: MediaSnapshotError::SnapshotNotReady, + retryable: true, + } + ); + + drop(reader); + server_task.await.unwrap().unwrap(); + } + #[tokio::test] async fn serves_live_workspace_snapshots_from_the_session_store() { use crate::hyprland::{ diff --git a/core/src/main.rs b/core/src/main.rs index b8504a0..85822ac 100644 --- a/core/src/main.rs +++ b/core/src/main.rs @@ -1,11 +1,16 @@ mod apps; mod config; +mod dbus; mod hyprland; mod hyprland_events; #[cfg(test)] mod hyprland_integration; mod ipc; mod launch; +mod media_store; +mod mpris; +mod mpris_events; +mod notifications; mod session_store; pub mod telemetry; @@ -24,6 +29,11 @@ async fn main() -> Result<()> { let config = config::CoreConfig::from_environment()?; let hyprland_capabilities = hyprland::probe_from_environment().await; + let dbus_capabilities = if config.media.enabled || config.notifications.enabled { + dbus::probe_from_environment().await + } else { + dbus::DbusCapabilities::unavailable() + }; let application_directories = apps::application_directories()?; let desktop_files = apps::discover_desktop_files(&application_directories)?; let applications = apps::load_applications(&desktop_files); @@ -55,10 +65,19 @@ async fn main() -> Result<()> { ?hyprland_capabilities, "Hyprland capability probe completed" ); + info!(?dbus_capabilities, "D-Bus capability probe completed"); + info!( + media_enabled = config.media.enabled, + notifications_enabled = config.notifications.enabled, + "D-Bus integration policy resolved" + ); let session_runtime = start_session_store(&hyprland_capabilities); let telemetry_enabled = config.telemetry.enabled; let telemetry_runtime = start_telemetry_sampler(config.telemetry); + let notifications_enabled = config.notifications.enabled; + let notifications_runtime = start_notification_monitor(config.notifications); + let media_runtime = start_media_store(&dbus_capabilities, config.media); let result = ipc::serve( config, applications.into(), @@ -69,10 +88,17 @@ async fn main() -> Result<()> { .map(|runtime| Arc::clone(&runtime.store)), Arc::clone(&telemetry_runtime.store), telemetry_enabled, + Arc::clone(¬ifications_runtime.store), + notifications_enabled, + media_runtime + .as_ref() + .map(|runtime| Arc::clone(&runtime.store)), ) .await; drop(session_runtime); drop(telemetry_runtime); + drop(notifications_runtime); + drop(media_runtime); result } @@ -89,6 +115,36 @@ fn start_telemetry_sampler(policy: config::TelemetryPolicy) -> TelemetryRuntime TelemetryRuntime { store, shutdown_tx } } +/// When the privacy gate is open, keep the narrow notification monitor active +/// for Core's lifetime. The monitor's typed availability is published into the +/// shared store so the IPC handler can report Restricted/Unavailable. +fn start_notification_monitor(policy: config::NotificationsPolicy) -> NotificationRuntime { + let store = Arc::new(notifications::NotificationStore::new()); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + if policy.enabled { + tokio::spawn(notifications::run(Arc::clone(&store), shutdown_rx)); + } + NotificationRuntime { store, shutdown_tx } +} + +/// When MPRIS media observation is available, keep the authoritative snapshot +/// warm in the background (discovery/signal listener plus the media store), +/// mirroring `start_telemetry_sampler`. A missing or unavailable bus leaves the +/// runtime absent so the IPC handler answers with the typed unavailable path. +fn start_media_store( + dbus: &dbus::DbusCapabilities, + policy: config::MediaPolicy, +) -> Option { + if !policy.enabled || dbus.media != dbus::MediaAvailability::Available { + return None; + } + let store = Arc::new(media_store::MediaStore::from_environment()); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let runner = Arc::clone(&store); + tokio::spawn(runner.run_with_listener(shutdown_rx, mpris_events::ListenerConfig::production())); + Some(MediaRuntime { store, shutdown_tx }) +} + /// When Hyprland is fully available, keep an authoritative snapshot warm in /// the background. The shutdown sender is held by Core for its lifetime. fn start_session_store( @@ -131,3 +187,25 @@ impl Drop for TelemetryRuntime { let _ = self.shutdown_tx.send(true); } } + +struct NotificationRuntime { + store: Arc, + shutdown_tx: watch::Sender, +} + +impl Drop for NotificationRuntime { + fn drop(&mut self) { + let _ = self.shutdown_tx.send(true); + } +} + +struct MediaRuntime { + store: Arc, + shutdown_tx: watch::Sender, +} + +impl Drop for MediaRuntime { + fn drop(&mut self) { + let _ = self.shutdown_tx.send(true); + } +} diff --git a/core/src/media_store.rs b/core/src/media_store.rs new file mode 100644 index 0000000..dc7a4df --- /dev/null +++ b/core/src/media_store.rs @@ -0,0 +1,1483 @@ +//! Authoritative media snapshot store. +//! +//! The MPRIS listener (P5.04) only marks state dirty; this store is the single +//! place that rebuilds the authoritative [`MediaSnapshot`] by re-reading every +//! player with `Properties.GetAll` (`mpris::read_player`). It keeps exactly one +//! snapshot — no history, no unbounded collection — and publishes it only when +//! its content actually changed, so a player whose state is unchanged (same +//! metadata, status, flags, and playback position) never churns the frontend. +//! +//! Failures retain the last-good snapshot and record explicit health +//! (successful/failed refresh counts plus the most recent error) exactly like +//! the Hyprland session store. A full disconnect is handled cleanly: the next +//! successful refresh lists whatever players remain, so a vanished player is +//! dropped and an empty bus publishes an empty snapshot rather than stale +//! players lingering forever. +//! +//! Live serving is on-demand: the IPC handler reads the cached snapshot and, +//! when none exists yet, triggers one refresh. Signal-driven refreshes are +//! coalesced by the capacity-1 invalidation channel and retried with capped +//! backoff, mirroring `session_store`. +//! +//! Every refresh is bounded by [`REFRESH_TIMEOUT`] (connect, discovery, and +//! per-player reads together), so a hung bus or wedged player can never hold +//! the refresh lock forever and block shutdown or the on-demand IPC path. Every +//! published snapshot is also bounded to [`MAX_MEDIA_PAYLOAD_BYTES`] by +//! truncating metadata and the human-readable identity (longest first); an +//! unfittable candidate is rejected rather than ever emitting an oversized +//! snapshot. + +use std::{ + collections::HashMap, + env, + ffi::OsStr, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; + +use thiserror::Error; +use tokio::sync::{mpsc, watch}; +use tracing::{debug, info, warn}; +use velora_protocol::{ + MAX_MEDIA_PAYLOAD_BYTES, MAX_MEDIA_PLAYERS, MediaControlError, MediaControlVerb, MediaPlayer, + MediaSnapshot, PlaybackStatus, +}; +use zbus::{Connection, names::OwnedUniqueName}; + +use crate::{dbus, mpris, mpris_events}; + +/// Session-bus address override used by tests, mirroring the `VELORA_SOCKET` +/// and `VELORA_SESSION_BUS_ADDRESS` rules in the D-Bus probe. +const SESSION_BUS_ADDRESS_ENV: &str = "VELORA_SESSION_BUS_ADDRESS"; +/// Maximum wall-clock time allowed for one full refresh (connect, discovery, +/// and per-player reads). Bounds how long the refresh lock can be held, so a +/// hung bus or a wedged player can never block shutdown or the on-demand IPC +/// path indefinitely. +const REFRESH_TIMEOUT: Duration = Duration::from_secs(5); +/// Maximum wall-clock time allowed for one control dispatch (connect, owner +/// re-validation, and the method call). A hung bus or a wedged player can +/// never block the IPC handler indefinitely. +const CONTROL_TIMEOUT: Duration = Duration::from_secs(5); +/// Base and ceiling for the capped refresh-retry backoff, mirroring the +/// session store so a flapping bus never produces a busy loop. +const REFRESH_BACKOFF_BASE: Duration = Duration::from_millis(250); +const REFRESH_BACKOFF_MAX: Duration = Duration::from_secs(4); + +/// Explicit store health, recorded on every refresh. Kept out of the wire +/// model: the snapshot stays pure state, and health is diagnostics-only. +#[derive(Debug, Default, Clone)] +pub(crate) struct StoreHealth { + pub has_state: bool, + pub successful_refreshes: u64, + pub failed_refreshes: u64, + pub last_success: Option, + pub last_error: Option, +} + +/// Typed failure of the media store. A missing bus, a denied read, or an +/// invalid snapshot never panics and never publishes partial state. +#[derive(Debug, Error)] +pub(crate) enum MediaStoreError { + #[error("session bus address override is not valid UTF-8")] + InvalidAddress, + #[error("failed to connect to the session bus: {0}")] + Connect(#[source] zbus::Error), + #[error("failed to list MPRIS players: {0}")] + ListPlayers(#[source] dbus::DbusError), + #[error("built media snapshot failed validation: {0}")] + InvalidSnapshot(#[source] velora_protocol::MediaSnapshotValidationError), + #[error("media snapshot exceeds the {MAX_MEDIA_PAYLOAD_BYTES}-byte payload budget")] + PayloadTooLarge, + #[error("media snapshot refresh timed out")] + TimedOut, +} + +pub(crate) struct MediaStore { + address: Option, + /// Serializes the entire read-and-apply refresh. The slow D-Bus reads + /// (`connect`, `list_players`, `read_player`) happen outside the state + /// mutex, so without this guard two concurrent refreshes (the signal loop + /// and the on-demand IPC path) could interleave and apply out of order, + /// regressing the published sequence. + refresh_lock: tokio::sync::Mutex<()>, + state: Mutex, + /// Latest changed snapshot for IPC clients. `watch` deliberately coalesces + /// intermediate changes: clients only need the newest authoritative state + /// and the sequence fences stale data. + updates: watch::Sender>>, +} + +/// The Core-private live target of an opaque player handle. Rebuilt atomically +/// with the snapshot and never serialized to any frontend; it exists only so a +/// control dispatch can re-validate the handle against the current bus owner. +#[derive(Debug, Clone)] +struct PlayerAddress { + bus_name: String, + owner: OwnedUniqueName, +} + +#[derive(Default)] +struct MediaState { + sequence: u64, + snapshot: Option>, + /// Opaque handle -> live bus target. Bounded to the players in the current + /// snapshot (at most [`MAX_MEDIA_PLAYERS`]); never crosses IPC. + targets: HashMap, + health: StoreHealth, +} + +impl MediaStore { + /// Build a store for a specific session-bus address. `None` falls back to + /// the default session bus via zbus. + pub(crate) fn new(address: Option) -> Self { + let (updates, _) = watch::channel(None); + Self { + address, + refresh_lock: tokio::sync::Mutex::new(()), + state: Mutex::new(MediaState::default()), + updates, + } + } + + /// Production entry point: read the `VELORA_SESSION_BUS_ADDRESS` override. + pub(crate) fn from_environment() -> Self { + Self::new(env::var_os(SESSION_BUS_ADDRESS_ENV)) + } + + /// The cached authoritative snapshot, or `None` before the first refresh. + pub(crate) fn current(&self) -> Option> { + self.state.lock().unwrap().snapshot.clone() + } + + /// Subscribe to changed snapshots for one IPC client. The receiver holds + /// the most recent snapshot and coalesces bursts safely. + pub(crate) fn subscribe(&self) -> watch::Receiver>> { + self.updates.subscribe() + } + + /// Diagnostics-only health record. Last-good state is independent of it. + #[allow(dead_code)] + pub(crate) fn health(&self) -> StoreHealth { + self.state.lock().unwrap().health.clone() + } + + /// One full refresh: connect, list players, re-read each, and replace the + /// authoritative snapshot. Returns whether the published content changed. + /// The whole read-and-apply cycle is serialized so concurrent refreshes + /// cannot publish out of order, and bounded by [`REFRESH_TIMEOUT`] so a + /// hung bus or wedged player can never block shutdown or the on-demand IPC + /// path while holding the refresh lock. Failures record health and retain + /// last-good state; an unreadable individual player is skipped (fail + /// closed: omit rather than guess), so a vanished player is dropped cleanly. + pub(crate) async fn refresh(&self) -> Result { + self.refresh_with_timeout(REFRESH_TIMEOUT).await + } + + /// Like [`MediaStore::refresh`] but with an explicit bound, so tests can + /// shrink the budget instead of waiting out the production timeout. + async fn refresh_with_timeout(&self, budget: Duration) -> Result { + // Hold the refresh lock across the slow reads AND the apply, so the + // signal loop and the on-demand IPC path can never interleave. + let _guard = self.refresh_lock.lock().await; + match tokio::time::timeout(budget, self.refresh_inner()).await { + Ok(result) => result, + Err(_) => { + self.record_failure(&MediaStoreError::TimedOut.to_string()); + Err(MediaStoreError::TimedOut) + } + } + } + + async fn refresh_inner(&self) -> Result { + let connection = match connect(self.address.as_deref()).await { + Ok(connection) => connection, + Err(error) => { + self.record_failure(&error.to_string()); + return Err(error); + } + }; + let result = self.read_and_apply(&connection).await; + if let Err(error) = &result + && matches!(error, MediaStoreError::ListPlayers(_)) + { + // Discovery is connection-level; an unreadable player never + // reaches here (it is skipped), and a validation failure records + // its own health. + self.record_failure(&error.to_string()); + } + result + } + + async fn read_and_apply(&self, connection: &Connection) -> Result { + let mut names = dbus::list_players(connection) + .await + .map_err(MediaStoreError::ListPlayers)?; + // Deterministic order: sorted names give a stable snapshot and a + // stable focused-player choice across refreshes. + names.sort(); + names.truncate(MAX_MEDIA_PLAYERS); + + let mut players = Vec::with_capacity(names.len()); + let mut targets = HashMap::with_capacity(names.len()); + for name in &names { + // Resolve the owner before reading so a player that vanishes mid- + // refresh is dropped cleanly (fail closed) and every published + // player carries a re-validatable control target. + let Ok(owner) = dbus::player_owner(connection, name).await else { + debug!(player = %name, "skipping MPRIS player without an owner"); + continue; + }; + match mpris::read_player(connection, name).await { + Ok(player) => { + targets.insert( + player.handle.clone(), + PlayerAddress { + bus_name: name.clone(), + owner, + }, + ); + players.push(player); + } + Err(error) => debug!(%error, player = %name, "skipping unreadable MPRIS player"), + } + } + self.apply_with_targets(players, targets) + } + + /// Replace the authoritative snapshot from a freshly-read player list. + /// Returns true only when the published content changed. Pure and + /// side-effect free except for publication, so tests exercise it directly. + /// Production always supplies live targets; tests use this snapshot-only + /// path (no control targets). + #[cfg(test)] + pub(crate) fn apply(&self, players: Vec) -> Result { + self.apply_with_targets(players, HashMap::new()) + } + + fn apply_with_targets( + &self, + mut players: Vec, + targets: HashMap, + ) -> Result { + // A stable sort key makes changed-only detection order-insensitive. + players.sort_by(|left, right| left.handle.cmp(&right.handle)); + + let mut state = self.state.lock().unwrap(); + let next_sequence = state.sequence + 1; + let previous_focused = state + .snapshot + .as_ref() + .and_then(|snapshot| snapshot.active_player_handle.as_deref()); + let active_player_handle = select_focused(&players, previous_focused); + + let fresh = MediaSnapshot { + sequence: next_sequence, + players, + active_player_handle, + }; + if let Err(error) = fresh.validate() { + state.health.failed_refreshes += 1; + state.health.last_error = Some(error.to_string()); + return Err(MediaStoreError::InvalidSnapshot(error)); + } + + // Enforce the 4 KiB Core payload budget before anything is published or + // served. Metadata and the human-readable identity are truncated + // (longest first) to fit; a snapshot that cannot fit even when fully + // truncated fails closed and retains the last-good snapshot. + let Some(fresh) = bound_payload(fresh) else { + let error = MediaStoreError::PayloadTooLarge; + state.health.failed_refreshes += 1; + state.health.last_error = Some(error.to_string()); + return Err(error); + }; + + let changed = state + .snapshot + .as_ref() + .is_none_or(|current| !content_eq(current, &fresh)); + // The live targets are rebuilt on every successful apply — even when the + // wire content is unchanged — because a player may have been replaced by + // an identical-looking connection whose owner differs. + state.targets = targets; + if changed { + state.sequence = next_sequence; + let fresh = Arc::new(fresh); + state.snapshot = Some(Arc::clone(&fresh)); + self.updates.send_replace(Some(fresh)); + debug!(sequence = next_sequence, "published new media snapshot"); + } else { + debug!(sequence = next_sequence - 1, "media content unchanged"); + } + state.health.has_state = true; + state.health.successful_refreshes += 1; + state.health.last_success = Some(Instant::now()); + state.health.last_error = None; + Ok(changed) + } + + /// Dispatch one allowlisted control verb to a snapshot-issued player handle. + /// The handle is resolved against the authoritative snapshot, its live bus + /// target is re-validated (the name must still be owned by the connection + /// that issued the handle), and the verb is mapped to a fixed MPRIS method. + /// Every uncertainty — an unknown handle, a vanished or replaced player, a + /// missing capability, a failed method call — degrades to a typed error and + /// never guesses at a destination. + pub(crate) async fn control( + &self, + handle: &str, + verb: MediaControlVerb, + ) -> Result<(), MediaControlError> { + // Resolve and gate under the state lock, cloning the live target before + // any D-Bus traffic. The lock is not held across `.await`. + let target = { + let state = self.state.lock().unwrap(); + let Some(snapshot) = state.snapshot.as_ref() else { + return Err(MediaControlError::ControlUnavailable); + }; + let Some(player) = snapshot.players.iter().find(|p| p.handle == handle) else { + return Err(MediaControlError::UnknownPlayer); + }; + if !player.can_control || !verb_supported(player, verb) { + return Err(MediaControlError::ControlUnavailable); + } + state + .targets + .get(handle) + .cloned() + .ok_or(MediaControlError::StaleHandle)? + }; + + let dispatch = tokio::time::timeout(CONTROL_TIMEOUT, async { + let connection = connect(self.address.as_deref()) + .await + .map_err(|_| MediaControlError::ControlUnavailable)?; + + // Re-validate the handle-to-bus-name mapping against the live bus: + // a vanished player has no owner and a replaced player has a + // different owner than the one the snapshot was built from. + let owner = dbus::player_owner(&connection, &target.bus_name) + .await + .map_err(|_| MediaControlError::StaleHandle)?; + if owner != target.owner { + return Err(MediaControlError::StaleHandle); + } + + mpris::control_player(&connection, &target.bus_name, verb) + .await + .map_err(|_| MediaControlError::ControlFailed) + }) + .await; + + match dispatch { + Ok(result) => result, + Err(_) => Err(MediaControlError::ControlUnavailable), + } + } + + /// Record a failed refresh while retaining the last-good snapshot. + fn record_failure(&self, error: &str) { + let mut state = self.state.lock().unwrap(); + state.health.failed_refreshes += 1; + state.health.last_error = Some(error.to_owned()); + } + + /// Consume coalesced invalidation signals forever, refreshing on each and + /// retrying with capped backoff so one dirty mark always converges even + /// across outages. The read connection is re-established per refresh, so a + /// dropped bus is replaced by whatever players are present next time. + pub(crate) async fn run( + self: Arc, + mut invalidation_rx: mpsc::Receiver<()>, + mut shutdown: watch::Receiver, + ) { + 'signals: loop { + tokio::select! { + _ = shutdown.changed() => return, + signal = invalidation_rx.recv() => { + if signal.is_none() { + return; + } + // Drain any signals that piled up behind this one. + while invalidation_rx.try_recv().is_ok() {} + + let mut backoff = REFRESH_BACKOFF_BASE; + loop { + match self.refresh().await { + Ok(_) => continue 'signals, + Err(error) => { + warn!(%error, "media snapshot refresh failed"); + tokio::select! { + _ = shutdown.changed() => return, + _ = tokio::time::sleep(backoff) => {} + } + backoff = (backoff * 2).min(REFRESH_BACKOFF_MAX); + } + } + } + } + } + } + } + + /// One initial refresh plus signal-driven refreshes until shutdown. Spawns + /// the MPRIS discovery/signal listener (P5.04) against the same bus address + /// and consumes its coalesced invalidation hints. + pub(crate) async fn run_with_listener( + self: Arc, + shutdown: watch::Receiver, + listener_config: mpris_events::ListenerConfig, + ) { + if let Err(error) = self.refresh().await { + info!(%error, "initial media snapshot refresh failed"); + } + + let (invalidation_tx, invalidation_rx) = mpsc::channel(1); + let address = self.address.clone(); + let listener_shutdown = shutdown.clone(); + let listener = tokio::spawn(async move { + mpris_events::run_listener( + address.as_deref(), + invalidation_tx, + listener_shutdown, + listener_config, + ) + .await; + }); + + self.run(invalidation_rx, shutdown).await; + listener.abort(); + } +} + +/// Choose the focused player deterministically. Preference order: a player +/// that is currently `Playing`; otherwise the previously focused player if it +/// is still present; otherwise the first player (already in a stable order). +fn select_focused(players: &[MediaPlayer], previous_focused: Option<&str>) -> Option { + if let Some(playing) = players + .iter() + .find(|player| player.status == PlaybackStatus::Playing) + { + return Some(playing.handle.clone()); + } + if let Some(handle) = previous_focused + && players.iter().any(|player| player.handle == handle) + { + return Some(handle.to_owned()); + } + players.first().map(|player| player.handle.clone()) +} + +/// Whether a player advertises support for a specific verb, on top of the +/// master `CanControl` gate checked by the caller. The MPRIS spec has no +/// `CanStop` flag, so `Stop` is gated by `CanControl` alone. +fn verb_supported(player: &MediaPlayer, verb: MediaControlVerb) -> bool { + match verb { + MediaControlVerb::Play => player.can_play, + MediaControlVerb::Pause => player.can_pause, + MediaControlVerb::PlayPause => player.can_play && player.can_pause, + MediaControlVerb::Stop => true, + MediaControlVerb::Next => player.can_go_next, + MediaControlVerb::Previous => player.can_go_previous, + } +} + +/// Two snapshots are equal only when every field that the wire model exposes is +/// identical. This intentionally includes [`MediaPlayer::position_micros`]: +/// playback position is authoritative state in the protocol snapshot, so a +/// position change (track advancing) is a meaningful publication, not noise. +fn content_eq(current: &MediaSnapshot, fresh: &MediaSnapshot) -> bool { + current.players == fresh.players && current.active_player_handle == fresh.active_player_handle +} + +/// A truncatable string field on a [`MediaPlayer`]. [`StringField::Identity`] +/// is a required (non-optional) but purely human-readable string, while +/// `Title`/`Artist`/`Album` are genuinely optional metadata; all four are safe +/// to shrink to fit the payload budget. Handles, status, and numeric/bool +/// fields are authoritative and never touched. +#[derive(Clone, Copy, PartialEq, Eq)] +enum StringField { + Identity, + Title, + Artist, + Album, +} + +impl StringField { + fn len(self, player: &MediaPlayer) -> usize { + match self { + StringField::Identity => player.identity.len(), + StringField::Title => player.title.as_ref().map_or(0, String::len), + StringField::Artist => player.artist.as_ref().map_or(0, String::len), + StringField::Album => player.album.as_ref().map_or(0, String::len), + } + } + + fn shrink(self, player: &mut MediaPlayer) { + let text: &mut String = match self { + StringField::Identity => &mut player.identity, + StringField::Title => player.title.as_mut().expect("non-empty metadata field"), + StringField::Artist => player.artist.as_mut().expect("non-empty metadata field"), + StringField::Album => player.album.as_mut().expect("non-empty metadata field"), + }; + let half = text.len() / 2; + let mut end = half; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + } +} + +/// Bound a snapshot to [`MAX_MEDIA_PAYLOAD_BYTES`] by repeatedly halving the +/// longest truncatable string (optional metadata or the human-readable +/// identity) until it fits. Deterministic for identical input, so changed-only +/// detection stays stable. Returns `None` when even a fully-truncated snapshot +/// cannot fit — callers must fail closed rather than ever emit an oversized +/// snapshot. +fn bound_payload(mut snapshot: MediaSnapshot) -> Option { + while encoded_len(&snapshot) > MAX_MEDIA_PAYLOAD_BYTES { + let (index, field) = longest_optional_field(&snapshot)?; + field.shrink(&mut snapshot.players[index]); + } + Some(snapshot) +} + +fn longest_optional_field(snapshot: &MediaSnapshot) -> Option<(usize, StringField)> { + let mut longest: Option<(usize, StringField, usize)> = None; + for (index, player) in snapshot.players.iter().enumerate() { + for field in [ + StringField::Identity, + StringField::Title, + StringField::Artist, + StringField::Album, + ] { + let len = field.len(player); + if len > 0 && longest.is_none_or(|(_, _, max)| len > max) { + longest = Some((index, field, len)); + } + } + } + longest.map(|(index, field, _)| (index, field)) +} + +fn encoded_len(snapshot: &MediaSnapshot) -> usize { + serde_json::to_string(snapshot).map_or(usize::MAX, |encoded| encoded.len()) +} + +async fn connect(address: Option<&OsStr>) -> Result { + match address { + Some(address) => { + let address = address.to_str().ok_or(MediaStoreError::InvalidAddress)?; + zbus::connection::Builder::address(address) + .map_err(MediaStoreError::Connect)? + .build() + .await + .map_err(MediaStoreError::Connect) + } + None => Connection::session() + .await + .map_err(MediaStoreError::Connect), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + collections::HashMap, + io::{BufRead, BufReader}, + process::{Child, Command, Stdio}, + sync::atomic::{AtomicBool, AtomicU64, Ordering}, + }; + use tokio::sync::mpsc; + use velora_protocol::MAX_STRING_BYTES; + use zbus::zvariant::{OwnedValue, Value}; + + fn player(handle: &str, status: PlaybackStatus) -> MediaPlayer { + MediaPlayer { + handle: handle.to_owned(), + identity: format!("Player {handle}"), + status, + title: None, + artist: None, + album: None, + length_micros: None, + position_micros: 0, + can_play: true, + can_pause: true, + can_go_next: true, + can_go_previous: true, + can_seek: true, + can_control: true, + } + } + + #[test] + fn apply_populates_a_monotonic_snapshot() { + let store = MediaStore::new(None); + assert!( + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap() + ); + let snapshot = store.current().unwrap(); + assert_eq!(snapshot.sequence, 1); + assert_eq!(snapshot.players.len(), 1); + assert_eq!(snapshot.active_player_handle.as_deref(), Some("player:1")); + snapshot.validate().unwrap(); + assert!(store.health().has_state); + assert_eq!(store.health().successful_refreshes, 1); + } + + #[test] + fn unchanged_content_keeps_the_published_sequence() { + let store = MediaStore::new(None); + assert!( + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap() + ); + assert!( + !store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap() + ); + assert_eq!(store.current().unwrap().sequence, 1); + assert_eq!(store.health().successful_refreshes, 2); + } + + #[test] + fn changed_content_bumps_the_sequence_and_publishes() { + let store = MediaStore::new(None); + let mut updates = store.subscribe(); + assert!( + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap() + ); + assert!(updates.has_changed().unwrap()); + updates.borrow_and_update(); + + assert!( + store + .apply(vec![player("player:1", PlaybackStatus::Paused)]) + .unwrap() + ); + assert!(updates.has_changed().unwrap()); + + assert_eq!(store.current().unwrap().sequence, 2); + assert_eq!( + store.current().unwrap().players[0].status, + PlaybackStatus::Paused + ); + } + + #[test] + fn identical_content_is_not_republished() { + let store = MediaStore::new(None); + let mut updates = store.subscribe(); + assert!( + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap() + ); + assert!(updates.has_changed().unwrap()); + updates.borrow_and_update(); + + // Same content, different input order: still suppressed. + assert!( + !store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap() + ); + assert!(!updates.has_changed().unwrap()); + } + + #[test] + fn vanished_players_are_replaced_cleanly() { + let store = MediaStore::new(None); + store + .apply(vec![ + player("player:1", PlaybackStatus::Playing), + player("player:2", PlaybackStatus::Paused), + ]) + .unwrap(); + assert_eq!(store.current().unwrap().players.len(), 2); + + // One player disconnects: the next refresh drops it. + store + .apply(vec![player("player:2", PlaybackStatus::Paused)]) + .unwrap(); + let snapshot = store.current().unwrap(); + assert_eq!(snapshot.players.len(), 1); + assert_eq!(snapshot.players[0].handle, "player:2"); + + // Everything disconnects: the snapshot becomes empty, not stale. + store.apply(vec![]).unwrap(); + let snapshot = store.current().unwrap(); + assert!(snapshot.players.is_empty()); + assert_eq!(snapshot.active_player_handle, None); + snapshot.validate().unwrap(); + } + + #[test] + fn invalid_snapshot_retains_last_good_and_records_health() { + let store = MediaStore::new(None); + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap(); + + // Duplicate handles violate protocol validation and must fail closed. + let error = store + .apply(vec![ + player("player:dup", PlaybackStatus::Playing), + player("player:dup", PlaybackStatus::Paused), + ]) + .unwrap_err(); + assert!(matches!(error, MediaStoreError::InvalidSnapshot(_))); + + // Last good snapshot retained, failure recorded. + assert_eq!(store.current().unwrap().sequence, 1); + assert_eq!(store.health().failed_refreshes, 1); + assert!(store.health().last_error.is_some()); + } + + #[test] + fn record_failure_retains_last_good_state() { + let store = MediaStore::new(None); + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap(); + + store.record_failure("boom"); + assert_eq!(store.current().unwrap().sequence, 1); + assert_eq!(store.health().failed_refreshes, 1); + assert_eq!(store.health().last_error.as_deref(), Some("boom")); + } + + #[test] + fn focused_player_prefers_playing_then_previous_then_first() { + let paused = player("player:a", PlaybackStatus::Paused); + let playing = player("player:b", PlaybackStatus::Playing); + + // Playing wins over previous focus and order. + assert_eq!( + select_focused(&[paused.clone(), playing.clone()], Some("player:a")).as_deref(), + Some("player:b") + ); + + // Nothing playing: keep the previously focused player. + assert_eq!( + select_focused( + &[paused.clone(), player("player:c", PlaybackStatus::Stopped)], + Some("player:c") + ) + .as_deref(), + Some("player:c") + ); + + // Previous focus gone: fall back to the first player. + assert_eq!( + select_focused(std::slice::from_ref(&paused), Some("player:missing")).as_deref(), + Some("player:a") + ); + + // No players: no focus. + assert_eq!(select_focused(&[], None), None); + } + + #[tokio::test] + async fn unreachable_bus_refresh_is_a_typed_failure_and_retains_last_good() { + use std::os::unix::ffi::OsStringExt; + let address = + std::ffi::OsString::from_vec(b"unix:path=/nonexistent/velora-test-media-bus".to_vec()); + let store = MediaStore::new(Some(address)); + + assert!(store.refresh().await.is_err()); + assert!(store.current().is_none()); + assert_eq!(store.health().failed_refreshes, 1); + assert!(store.health().last_error.is_some()); + } + + #[tokio::test] + async fn non_utf8_address_is_a_typed_unavailable() { + use std::os::unix::ffi::OsStringExt; + let address = std::ffi::OsString::from_vec(vec![0xff, 0xfe, 0xfd]); + let store = MediaStore::new(Some(address)); + + assert!(matches!( + store.refresh().await.unwrap_err(), + MediaStoreError::InvalidAddress + )); + } + + #[tokio::test] + async fn hung_bus_refresh_times_out_and_records_health() { + use std::os::unix::net::UnixListener as StdUnixListener; + + let directory = tempfile::tempdir().unwrap(); + let socket_path = directory.path().join("hung-media-bus"); + let listener = StdUnixListener::bind(&socket_path).unwrap(); + + // Accept the client and hold the stream open without completing the + // D-Bus auth handshake, so the refresh must time out instead of + // blocking forever while holding the refresh lock. + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (_stream, _address) = listener.accept().unwrap(); + let _ = stop_rx.recv(); + }); + + let address = format!("unix:path={}", socket_path.display()); + let store = MediaStore::new(Some(std::ffi::OsString::from(address))); + + let result = store.refresh_with_timeout(Duration::from_millis(100)).await; + + let _ = stop_tx.send(()); + server.join().unwrap(); + + assert!(matches!(result, Err(MediaStoreError::TimedOut))); + assert_eq!(store.health().failed_refreshes, 1); + assert!(store.health().last_error.is_some()); + } + + #[test] + fn store_is_bounded_to_a_single_snapshot() { + // The store keeps exactly one snapshot; there is no history to grow. + let store = MediaStore::new(None); + for index in 0..100 { + store + .apply(vec![player( + &format!("player:{index}"), + PlaybackStatus::Playing, + )]) + .unwrap(); + } + assert_eq!(store.current().unwrap().players.len(), 1); + assert_eq!(store.health().successful_refreshes, 100); + } + + #[test] + fn position_changes_are_meaningful_publications() { + // `position_micros` is authoritative wire state, so a position change + // is a real change and must bump the sequence (see `content_eq`). + let store = MediaStore::new(None); + let mut track = player("player:1", PlaybackStatus::Playing); + track.position_micros = 1_000; + assert!(store.apply(vec![track.clone()]).unwrap()); + + let mut advanced = track; + advanced.position_micros = 2_000; + assert!( + store.apply(vec![advanced]).unwrap(), + "a position change must republish" + ); + assert_eq!(store.current().unwrap().sequence, 2); + assert_eq!(store.current().unwrap().players[0].position_micros, 2_000); + } + + #[test] + fn capability_gate_maps_each_verb_to_its_flags() { + let controllable = player("player:1", PlaybackStatus::Playing); + assert!(verb_supported(&controllable, MediaControlVerb::Play)); + assert!(verb_supported(&controllable, MediaControlVerb::Pause)); + assert!(verb_supported(&controllable, MediaControlVerb::PlayPause)); + assert!(verb_supported(&controllable, MediaControlVerb::Stop)); + assert!(verb_supported(&controllable, MediaControlVerb::Next)); + assert!(verb_supported(&controllable, MediaControlVerb::Previous)); + + let mut limited = player("player:1", PlaybackStatus::Playing); + limited.can_play = false; + limited.can_go_next = false; + assert!(!verb_supported(&limited, MediaControlVerb::Play)); + assert!(!verb_supported(&limited, MediaControlVerb::PlayPause)); + assert!(!verb_supported(&limited, MediaControlVerb::Next)); + // Pause and Previous are still advertised, and Stop is gated only by + // `CanControl`. + assert!(verb_supported(&limited, MediaControlVerb::Pause)); + assert!(verb_supported(&limited, MediaControlVerb::Previous)); + assert!(verb_supported(&limited, MediaControlVerb::Stop)); + } + + #[tokio::test] + async fn control_without_a_snapshot_is_unavailable() { + let store = MediaStore::new(None); + assert_eq!( + store + .control("player:1", MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::ControlUnavailable + ); + } + + #[tokio::test] + async fn control_rejects_unknown_handles_without_touching_the_bus() { + let store = MediaStore::new(None); + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap(); + + assert_eq!( + store + .control("player:missing", MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::UnknownPlayer + ); + } + + #[tokio::test] + async fn control_rejects_a_raw_bus_name_or_malformed_handle() { + let store = MediaStore::new(None); + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap(); + + // A raw well-known name can never act as a handle: it fails closed as + // unknown rather than dispatching to the named connection. + assert_eq!( + store + .control("org.mpris.MediaPlayer2.spotify", MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::UnknownPlayer + ); + + // An oversized/malformed handle is rejected the same way. + let garbage = "x".repeat(MAX_STRING_BYTES + 1); + assert_eq!( + store + .control(&garbage, MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::UnknownPlayer + ); + } + + #[tokio::test] + async fn control_rejects_a_known_handle_without_a_live_target() { + // `apply` publishes the snapshot-only path (no control targets), so a + // handle present in the snapshot but with no live bus target is stale. + let store = MediaStore::new(None); + store + .apply(vec![player("player:1", PlaybackStatus::Playing)]) + .unwrap(); + + assert_eq!( + store + .control("player:1", MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::StaleHandle + ); + } + + #[tokio::test] + async fn control_requires_a_controllable_player() { + let store = MediaStore::new(None); + let mut track = player("player:1", PlaybackStatus::Playing); + track.can_control = false; + store.apply(vec![track]).unwrap(); + + assert_eq!( + store + .control("player:1", MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::ControlUnavailable + ); + } + + #[tokio::test] + async fn control_requires_the_specific_transport_capability() { + let store = MediaStore::new(None); + let mut track = player("player:1", PlaybackStatus::Playing); + track.can_go_next = false; + store.apply(vec![track]).unwrap(); + + assert_eq!( + store + .control("player:1", MediaControlVerb::Next) + .await + .unwrap_err(), + MediaControlError::ControlUnavailable + ); + } + + fn full_width_player(handle: &str) -> MediaPlayer { + MediaPlayer { + handle: handle.to_owned(), + identity: "i".repeat(MAX_STRING_BYTES), + status: PlaybackStatus::Playing, + title: Some("t".repeat(MAX_STRING_BYTES)), + artist: Some("a".repeat(MAX_STRING_BYTES)), + album: Some("l".repeat(MAX_STRING_BYTES)), + length_micros: Some(250_000_000), + position_micros: 0, + can_play: true, + can_pause: true, + can_go_next: true, + can_go_previous: true, + can_seek: true, + can_control: true, + } + } + + #[test] + fn payload_budget_truncates_optional_metadata() { + let store = MediaStore::new(None); + let players: Vec = (0..MAX_MEDIA_PLAYERS) + .map(|index| full_width_player(&format!("player:{index}"))) + .collect(); + // Sixteen full-width players far exceed the 4 KiB budget. + assert!(store.apply(players).unwrap()); + + let snapshot = store.current().unwrap(); + let encoded = serde_json::to_string(&*snapshot).unwrap(); + assert!( + encoded.len() <= MAX_MEDIA_PAYLOAD_BYTES, + "served snapshot must never exceed the payload budget" + ); + // Optional metadata was truncated (strictly below the 256-byte ceiling). + assert!( + snapshot.players[0].title.as_ref().unwrap().len() < MAX_STRING_BYTES, + "oversized metadata must be truncated to fit" + ); + snapshot.validate().unwrap(); + } + + #[test] + fn payload_budget_leaves_small_snapshots_untouched() { + let store = MediaStore::new(None); + let mut track = player("player:1", PlaybackStatus::Playing); + track.title = Some("Velora Theme".to_owned()); + track.artist = Some("Velora".to_owned()); + assert!(store.apply(vec![track]).unwrap()); + + let snapshot = store.current().unwrap(); + assert_eq!(snapshot.players[0].title.as_deref(), Some("Velora Theme")); + assert_eq!(snapshot.players[0].artist.as_deref(), Some("Velora")); + assert!(serde_json::to_string(&*snapshot).unwrap().len() <= MAX_MEDIA_PAYLOAD_BYTES); + } + + #[test] + fn bound_payload_rejects_a_candidate_that_cannot_fit() { + // `bound_payload` is agnostic to the structural player ceiling. Feed it + // a candidate whose non-truncatable fields alone overflow the budget + // (empty identity, no metadata to shrink) to prove the fail-closed + // `None` path. + let players: Vec = (0..64) + .map(|index| MediaPlayer { + handle: format!("player:{index:04x}"), + identity: String::new(), + status: PlaybackStatus::Stopped, + title: None, + artist: None, + album: None, + length_micros: None, + position_micros: 0, + can_play: true, + can_pause: true, + can_go_next: true, + can_go_previous: true, + can_seek: true, + can_control: true, + }) + .collect(); + let snapshot = MediaSnapshot { + sequence: 1, + players, + active_player_handle: None, + }; + assert!( + encoded_len(&snapshot) > MAX_MEDIA_PAYLOAD_BYTES, + "fixture must actually overflow the budget" + ); + assert!(bound_payload(snapshot).is_none()); + } + + /// A private `dbus-daemon` on a temporary address. Never the live session + /// bus. The child is killed and reaped on drop. + struct PrivateBus { + address: String, + child: Child, + } + + impl PrivateBus { + fn spawn() -> Option { + let mut child = Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let stdout = child.stdout.take()?; + let mut reader = BufReader::new(stdout); + let mut address = String::new(); + reader.read_line(&mut address).ok()?; + let address = address.trim().to_owned(); + if address.is_empty() { + return None; + } + Some(PrivateBus { address, child }) + } + + async fn connect(&self) -> Connection { + zbus::connection::Builder::address(self.address.as_str()) + .unwrap() + .build() + .await + .unwrap() + } + } + + impl Drop for PrivateBus { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + const TEST_PLAYER: &str = "org.mpris.MediaPlayer2.velora_test"; + + struct MediaPlayer2Props; + + #[zbus::interface(name = "org.mpris.MediaPlayer2")] + impl MediaPlayer2Props { + #[zbus(property)] + fn identity(&self) -> String { + "Test Player".to_owned() + } + } + + struct PlayerProps { + served: mpsc::UnboundedSender<()>, + release: tokio::sync::Mutex>>, + calls: AtomicU64, + } + + #[zbus::interface(name = "org.mpris.MediaPlayer2.Player")] + impl PlayerProps { + #[zbus(property)] + fn playback_status(&self) -> String { + "Playing".to_owned() + } + + #[zbus(property)] + async fn metadata(&self) -> HashMap { + let call = self.calls.fetch_add(1, Ordering::SeqCst); + // Block the very first Player read so the test can prove a second + // refresh queues behind the first instead of applying out of order. + if call == 0 { + let receiver = self.release.lock().await.take(); + if let Some(mut receiver) = receiver { + let _ = self.served.send(()); + let _ = receiver.recv().await; + } + } + let mut map = HashMap::new(); + let title: OwnedValue = Value::from(format!("title-{call}")).try_into().unwrap(); + map.insert("xesam:title".to_owned(), title); + map + } + } + + #[tokio::test] + async fn concurrent_refreshes_are_serialized() { + let Some(bus) = PrivateBus::spawn() else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + let player = bus.connect().await; + let (served_tx, mut served_rx) = mpsc::unbounded_channel(); + let (release_tx, release_rx) = mpsc::channel(1); + let player_props = PlayerProps { + served: served_tx, + release: tokio::sync::Mutex::new(Some(release_rx)), + calls: AtomicU64::new(0), + }; + let server = player.object_server(); + server + .at("/org/mpris/MediaPlayer2", MediaPlayer2Props) + .await + .unwrap(); + server + .at("/org/mpris/MediaPlayer2", player_props) + .await + .unwrap(); + player.request_name(TEST_PLAYER).await.unwrap(); + + let store = Arc::new(MediaStore::new(Some(std::ffi::OsString::from( + bus.address.clone(), + )))); + + // Refresh A: blocks inside the first Player `GetAll`. + let refresh_a = tokio::spawn({ + let store = Arc::clone(&store); + async move { store.refresh().await } + }); + + // Wait until A's blocking read has been reached. + tokio::time::timeout(Duration::from_secs(2), served_rx.recv()) + .await + .unwrap() + .unwrap(); + + // Refresh B: must queue behind A's refresh lock, not apply first. + let refresh_b = tokio::spawn({ + let store = Arc::clone(&store); + async move { store.refresh().await } + }); + + // B cannot publish while A holds the lock. + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + store.current().is_none(), + "refresh B must wait for A instead of applying out of order" + ); + + // Release A: it publishes `title-0`, then B publishes `title-1`. + release_tx.send(()).await.unwrap(); + let changed_a = tokio::time::timeout(Duration::from_secs(2), refresh_a) + .await + .unwrap() + .unwrap() + .unwrap(); + let changed_b = tokio::time::timeout(Duration::from_secs(2), refresh_b) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(changed_a && changed_b); + + // The last-applied snapshot is B's (`title-1`), never the stale A read. + let snapshot = store.current().unwrap(); + assert_eq!(snapshot.sequence, 2); + assert_eq!(snapshot.players.len(), 1); + assert_eq!(snapshot.players[0].title.as_deref(), Some("title-1")); + } + + /// A controllable fake player: serves the read properties the store needs + /// (identity plus the `Player` transport flags) and records which transport + /// method was invoked, optionally failing the next call. + struct ControlProps { + calls: Arc>>, + fail_next: Arc, + } + + impl ControlProps { + fn record(&self, method: &str) -> zbus::fdo::Result<()> { + self.calls.lock().unwrap().push(method.to_owned()); + if self.fail_next.swap(false, Ordering::SeqCst) { + Err(zbus::fdo::Error::Failed( + "player refused control".to_owned(), + )) + } else { + Ok(()) + } + } + } + + #[zbus::interface(name = "org.mpris.MediaPlayer2.Player")] + impl ControlProps { + #[zbus(property)] + fn playback_status(&self) -> String { + "Paused".to_owned() + } + + #[zbus(property)] + fn metadata(&self) -> HashMap { + HashMap::new() + } + + #[zbus(property)] + fn position(&self) -> i64 { + 0 + } + + #[zbus(property)] + fn can_play(&self) -> bool { + true + } + + #[zbus(property)] + fn can_pause(&self) -> bool { + true + } + + #[zbus(property)] + fn can_go_next(&self) -> bool { + true + } + + #[zbus(property)] + fn can_go_previous(&self) -> bool { + true + } + + #[zbus(property)] + fn can_seek(&self) -> bool { + true + } + + #[zbus(property)] + fn can_control(&self) -> bool { + true + } + + #[zbus(name = "Play")] + async fn play(&self) -> zbus::fdo::Result<()> { + self.record("Play") + } + + #[zbus(name = "Pause")] + async fn pause(&self) -> zbus::fdo::Result<()> { + self.record("Pause") + } + + #[zbus(name = "PlayPause")] + async fn play_pause(&self) -> zbus::fdo::Result<()> { + self.record("PlayPause") + } + + #[zbus(name = "Stop")] + async fn stop(&self) -> zbus::fdo::Result<()> { + self.record("Stop") + } + + #[zbus(name = "Next")] + async fn next(&self) -> zbus::fdo::Result<()> { + self.record("Next") + } + + #[zbus(name = "Previous")] + async fn previous(&self) -> zbus::fdo::Result<()> { + self.record("Previous") + } + } + + struct ControlFixture { + bus: PrivateBus, + player: Connection, + calls: Arc>>, + fail_next: Arc, + store: Arc, + handle: String, + } + + /// Spin up a private bus with one controllable player and warm the store so + /// the handle maps to a live, re-validatable target. + async fn spawn_controllable_player() -> Option { + let bus = PrivateBus::spawn()?; + let player = bus.connect().await; + let calls = Arc::new(Mutex::new(Vec::new())); + let fail_next = Arc::new(AtomicBool::new(false)); + let control_props = ControlProps { + calls: Arc::clone(&calls), + fail_next: Arc::clone(&fail_next), + }; + let server = player.object_server(); + server + .at("/org/mpris/MediaPlayer2", MediaPlayer2Props) + .await + .unwrap(); + server + .at("/org/mpris/MediaPlayer2", control_props) + .await + .unwrap(); + player.request_name(TEST_PLAYER).await.unwrap(); + + let store = Arc::new(MediaStore::new(Some(std::ffi::OsString::from( + bus.address.clone(), + )))); + store.refresh().await.unwrap(); + let handle = store.current().unwrap().players[0].handle.clone(); + + Some(ControlFixture { + bus, + player, + calls, + fail_next, + store, + handle, + }) + } + + #[tokio::test] + async fn control_dispatches_only_fixed_player_methods() { + let Some(fixture) = spawn_controllable_player().await else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + for verb in [ + MediaControlVerb::Play, + MediaControlVerb::Pause, + MediaControlVerb::PlayPause, + MediaControlVerb::Stop, + MediaControlVerb::Next, + MediaControlVerb::Previous, + ] { + fixture.store.control(&fixture.handle, verb).await.unwrap(); + } + let calls = fixture.calls.lock().unwrap().clone(); + assert_eq!( + calls, + vec!["Play", "Pause", "PlayPause", "Stop", "Next", "Previous",] + ); + } + + #[tokio::test] + async fn control_reports_a_typed_failure_when_the_player_refuses() { + let Some(fixture) = spawn_controllable_player().await else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + fixture.fail_next.store(true, Ordering::SeqCst); + assert_eq!( + fixture + .store + .control(&fixture.handle, MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::ControlFailed + ); + } + + #[tokio::test] + async fn control_fails_closed_when_the_player_vanishes() { + let Some(fixture) = spawn_controllable_player().await else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + fixture.player.release_name(TEST_PLAYER).await.unwrap(); + assert_eq!( + fixture + .store + .control(&fixture.handle, MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::StaleHandle + ); + } + + #[tokio::test] + async fn control_fails_closed_when_the_player_is_replaced() { + let Some(fixture) = spawn_controllable_player().await else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + fixture.player.release_name(TEST_PLAYER).await.unwrap(); + let replacement = fixture.bus.connect().await; + replacement.request_name(TEST_PLAYER).await.unwrap(); + assert_eq!( + fixture + .store + .control(&fixture.handle, MediaControlVerb::Play) + .await + .unwrap_err(), + MediaControlError::StaleHandle + ); + } +} diff --git a/core/src/mpris.rs b/core/src/mpris.rs new file mode 100644 index 0000000..2f70723 --- /dev/null +++ b/core/src/mpris.rs @@ -0,0 +1,564 @@ +//! Read-only MPRIS adapter. +//! +//! Velora observes media players strictly through the user session bus. This +//! module is the only place raw `org.mpris.MediaPlayer2` and +//! `org.mpris.MediaPlayer2.Player` properties are parsed: it reads both +//! interfaces with `Properties.GetAll`, normalizes `Identity`, `PlaybackStatus`, +//! the `xesam:` metadata triplet (`title`/`artist`/`album`), `mpris:length`, +//! `Position`, and the `Can*` transport flags into the shared, validated +//! protocol model, and issues an opaque hashed handle so a raw D-Bus bus name +//! never crosses Velora IPC. +//! +//! Reading is the only capability that exists here: there is no state-changing +//! method call. Missing, mistyped, and additional metadata fields are tolerated +//! and normalized to defaults; a metadata value that is not a string-variant +//! dictionary (malformed or hostile) yields a typed error instead of a guess. + +use std::{ + collections::HashMap, + hash::{Hash, Hasher}, +}; +use thiserror::Error; +use velora_protocol::{MAX_STRING_BYTES, MediaControlVerb, MediaPlayer, PlaybackStatus}; +use zbus::{ + Connection, Proxy, + zvariant::{OwnedValue, Value}, +}; + +/// Standard MPRIS object path every player exposes. +const MPRIS_OBJECT_PATH: &str = "/org/mpris/MediaPlayer2"; +/// Standard D-Bus properties interface used for `Properties.GetAll`. +const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties"; +/// The identity interface (Identity, desktop entry, quit/raise). +const MEDIA_PLAYER2_INTERFACE: &str = "org.mpris.MediaPlayer2"; +/// The transport interface (PlaybackStatus, Metadata, Position, Can* flags). +const PLAYER_INTERFACE: &str = "org.mpris.MediaPlayer2.Player"; +/// Maximum length of a player bus name accepted for hashing. +const MAX_PLAYER_NAME_CHARS: usize = 256; +/// Maximum number of `xesam:artist` entries normalized into the single +/// protocol `artist` string. +const MAX_ARTIST_ENTRIES: usize = 16; + +/// Typed failure of the read-only MPRIS adapter. Malformed player properties +/// never panic and never publish a partial player. +#[derive(Debug, Error)] +pub(crate) enum MprisError { + #[error("MPRIS player name is empty or exceeds {MAX_PLAYER_NAME_CHARS} characters")] + InvalidPlayerName, + #[error("MPRIS read failed for {player}: {source}")] + Call { + player: String, + #[source] + source: Box, + }, + #[error("MPRIS metadata for {player} is not a string-variant dictionary")] + MalformedMetadata { player: String }, +} + +/// Read one MPRIS player's normalized state from both interfaces. This is the +/// only entry point for the rest of Core; it never writes to the bus. +pub(crate) async fn read_player( + connection: &Connection, + player_name: &str, +) -> Result { + validate_player_name(player_name)?; + + let (media2, player) = tokio::try_join!( + read_properties(connection, player_name, MEDIA_PLAYER2_INTERFACE), + read_properties(connection, player_name, PLAYER_INTERFACE), + ) + .map_err(|source| MprisError::Call { + player: player_name.to_owned(), + source: Box::new(source), + })?; + + normalize_player(player_name, &media2, &player) +} + +/// The fixed `org.mpris.MediaPlayer2.Player` method each allowlisted control +/// verb maps to. This is the complete write surface: every verb resolves to +/// exactly one no-argument method, so a raw method name or an arbitrary +/// argument can never reach the bus from IPC. +pub(crate) fn player_method(verb: MediaControlVerb) -> &'static str { + match verb { + MediaControlVerb::Play => "Play", + MediaControlVerb::Pause => "Pause", + MediaControlVerb::PlayPause => "PlayPause", + MediaControlVerb::Stop => "Stop", + MediaControlVerb::Next => "Next", + MediaControlVerb::Previous => "Previous", + } +} + +/// Dispatch one allowlisted control verb to a player. The verb is mapped to a +/// fixed, no-argument method on `org.mpris.MediaPlayer2.Player`; neither the +/// method name nor any argument crosses IPC. This is the only state-changing +/// call the adapter ever makes. +pub(crate) async fn control_player( + connection: &Connection, + player_name: &str, + verb: MediaControlVerb, +) -> Result<(), MprisError> { + validate_player_name(player_name)?; + + let proxy = Proxy::new(connection, player_name, MPRIS_OBJECT_PATH, PLAYER_INTERFACE) + .await + .map_err(|source| MprisError::Call { + player: player_name.to_owned(), + source: Box::new(source), + })?; + + proxy + .call::<_, _, ()>(player_method(verb), &()) + .await + .map_err(|source| MprisError::Call { + player: player_name.to_owned(), + source: Box::new(source), + }) +} + +/// Reject an empty or oversized player name before it is hashed or used as a +/// bus destination. Fail closed rather than guessing at a hostile name. +fn validate_player_name(player_name: &str) -> Result<(), MprisError> { + if player_name.is_empty() || player_name.len() > MAX_PLAYER_NAME_CHARS { + Err(MprisError::InvalidPlayerName) + } else { + Ok(()) + } +} + +async fn read_properties( + connection: &Connection, + player_name: &str, + interface: &str, +) -> Result, zbus::Error> { + let proxy = Proxy::new( + connection, + player_name, + MPRIS_OBJECT_PATH, + PROPERTIES_INTERFACE, + ) + .await?; + proxy.call("GetAll", &(interface,)).await +} + +/// Pure normalization boundary: raw property dictionaries in, a validated +/// protocol `MediaPlayer` out. Kept synchronous and side-effect free so the +/// tolerance rules are directly testable without a live bus. +fn normalize_player( + player_name: &str, + media2: &HashMap, + player: &HashMap, +) -> Result { + let metadata = match player.get("Metadata") { + None => HashMap::new(), + Some(value) => HashMap::::try_from(value.clone()).map_err(|_| { + MprisError::MalformedMetadata { + player: player_name.to_owned(), + } + })?, + }; + + Ok(MediaPlayer { + handle: opaque_player_handle(player_name), + identity: string_field(media2, "Identity").unwrap_or_default(), + status: playback_status(player), + title: string_field(&metadata, "xesam:title"), + artist: artist_field(&metadata), + album: string_field(&metadata, "xesam:album"), + length_micros: metadata + .get("mpris:length") + .and_then(micros_value) + .filter(|micros| *micros > 0), + position_micros: player.get("Position").and_then(micros_value).unwrap_or(0), + can_play: bool_field(player, "CanPlay"), + can_pause: bool_field(player, "CanPause"), + can_go_next: bool_field(player, "CanGoNext"), + can_go_previous: bool_field(player, "CanGoPrevious"), + can_seek: bool_field(player, "CanSeek"), + can_control: bool_field(player, "CanControl"), + }) +} + +/// A trimmed, byte-bounded string (`MAX_STRING_BYTES`) that always satisfies +/// the protocol `MediaPlayer` validation ceiling. Truncation lands on a UTF-8 +/// character boundary, so it never splits a code point. +fn bounded_string(value: &str) -> String { + let mut output = String::new(); + for character in value.trim().chars() { + if output.len() + character.len_utf8() > MAX_STRING_BYTES { + break; + } + output.push(character); + } + output +} + +/// Read a string field, tolerating a missing or mistyped value as `None`. +fn string_field(props: &HashMap, key: &str) -> Option { + let value = props.get(key)?; + let text = <&str>::try_from(value).ok()?; + Some(bounded_string(text)) +} + +/// Normalize `xesam:artist` (an array of strings in the spec, but players +/// sometimes send a single string or the wrong type) into the single bounded +/// protocol `artist` string. Missing or mistyped values become `None`. +fn artist_field(metadata: &HashMap) -> Option { + let value = metadata.get("xesam:artist")?; + let artists: Vec = match &**value { + Value::Array(array) => array + .iter() + .filter_map(|element| element.downcast_ref::<&str>().ok()) + .map(bounded_string) + .filter(|artist| !artist.is_empty()) + .take(MAX_ARTIST_ENTRIES) + .collect(), + Value::Str(text) => { + let bounded = bounded_string(text.as_str()); + if bounded.is_empty() { + return None; + } + vec![bounded] + } + _ => return None, + }; + + if artists.is_empty() { + None + } else { + Some(bounded_string(&artists.join(", "))) + } +} + +/// Normalize `PlaybackStatus`. Any unrecognized or missing status collapses to +/// `Stopped` rather than inventing a fourth variant. +fn playback_status(player: &HashMap) -> PlaybackStatus { + match player + .get("PlaybackStatus") + .and_then(|value| <&str>::try_from(value).ok()) + .map(str::trim) + { + Some("Playing") => PlaybackStatus::Playing, + Some("Paused") => PlaybackStatus::Paused, + _ => PlaybackStatus::Stopped, + } +} + +/// Read a `Can*` flag, tolerating a missing or mistyped value as `false` +/// (fail closed: an unreadable transport flag never claims control). +fn bool_field(props: &HashMap, key: &str) -> bool { + props + .get(key) + .and_then(|value| bool::try_from(value).ok()) + .unwrap_or(false) +} + +/// Parse a microsecond value with type tolerance. The MPRIS spec declares +/// `mpris:length` and `Position` as `x` (int64), but players have shipped +/// `u` (uint64) and `d` (double) instead. Negative, non-finite, and mistyped +/// values normalize to `None`. +fn micros_value(value: &OwnedValue) -> Option { + if let Ok(micros) = i64::try_from(value) + && let Ok(micros) = u64::try_from(micros) + { + return Some(micros); + } + if let Ok(micros) = u64::try_from(value) { + return Some(micros); + } + if let Ok(micros) = f64::try_from(value) + && micros.is_finite() + && micros >= 0.0 + { + return Some(micros as u64); + } + None +} + +/// Players are referenced only through a one-way hash of their bus name, so no +/// raw bus name can ever reach or return from Godot. +fn opaque_player_handle(player_name: &str) -> String { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + player_name.hash(&mut hasher); + format!("player:{:016x}", hasher.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn owned(value: Value<'static>) -> OwnedValue { + value.try_into().unwrap() + } + + fn str_value(text: &str) -> OwnedValue { + owned(Value::from(text.to_owned())) + } + + fn bool_value(value: bool) -> OwnedValue { + owned(Value::from(value)) + } + + fn i64_value(value: i64) -> OwnedValue { + owned(Value::from(value)) + } + + fn u64_value(value: u64) -> OwnedValue { + owned(Value::from(value)) + } + + fn string_array(items: &[&str]) -> OwnedValue { + owned(Value::from( + items + .iter() + .map(|item| item.to_string()) + .collect::>(), + )) + } + + fn metadata_dict(entries: Vec<(&str, OwnedValue)>) -> OwnedValue { + let map: HashMap> = entries + .into_iter() + .map(|(key, value)| (key.to_owned(), value.into())) + .collect(); + owned(Value::from(map)) + } + + fn full_props(metadata: OwnedValue) -> HashMap { + let mut props = HashMap::new(); + props.insert("PlaybackStatus".to_owned(), str_value("Playing")); + props.insert("Metadata".to_owned(), metadata); + props.insert("Position".to_owned(), i64_value(12_500_000)); + props.insert("CanPlay".to_owned(), bool_value(true)); + props.insert("CanPause".to_owned(), bool_value(true)); + props.insert("CanGoNext".to_owned(), bool_value(true)); + props.insert("CanGoPrevious".to_owned(), bool_value(true)); + props.insert("CanSeek".to_owned(), bool_value(true)); + props.insert("CanControl".to_owned(), bool_value(true)); + props + } + + fn media2_props(identity: &str) -> HashMap { + let mut props = HashMap::new(); + props.insert("Identity".to_owned(), str_value(identity)); + props + } + + fn well_formed_metadata() -> OwnedValue { + metadata_dict(vec![ + ("xesam:title", str_value("Velora Theme")), + ("xesam:artist", string_array(&["Velora", "Guest"])), + ("xesam:album", str_value("Phase 5")), + ("mpris:length", i64_value(250_000_000)), + ]) + } + + #[test] + fn normalizes_a_well_formed_player() { + let player = normalize_player( + "org.mpris.MediaPlayer2.spotify", + &media2_props("Spotify"), + &full_props(well_formed_metadata()), + ) + .unwrap(); + + assert_eq!(player.identity, "Spotify"); + assert_eq!(player.status, PlaybackStatus::Playing); + assert_eq!(player.title.as_deref(), Some("Velora Theme")); + assert_eq!(player.artist.as_deref(), Some("Velora, Guest")); + assert_eq!(player.album.as_deref(), Some("Phase 5")); + assert_eq!(player.length_micros, Some(250_000_000)); + assert_eq!(player.position_micros, 12_500_000); + assert!(player.can_play); + assert!(player.can_pause); + assert!(player.can_go_next); + assert!(player.can_go_previous); + assert!(player.can_seek); + assert!(player.can_control); + } + + #[test] + fn tolerates_missing_metadata_and_flags() { + let player = normalize_player( + "org.mpris.MediaPlayer2.spotify", + &HashMap::new(), + &HashMap::new(), + ) + .unwrap(); + + assert_eq!(player.identity, ""); + assert_eq!(player.status, PlaybackStatus::Stopped); + assert_eq!(player.title, None); + assert_eq!(player.artist, None); + assert_eq!(player.album, None); + assert_eq!(player.length_micros, None); + assert_eq!(player.position_micros, 0); + assert!(!player.can_play); + assert!(!player.can_pause); + assert!(!player.can_go_next); + assert!(!player.can_go_previous); + assert!(!player.can_seek); + assert!(!player.can_control); + } + + #[test] + fn tolerates_mistyped_fields_without_error() { + let mut player_props = HashMap::new(); + player_props.insert("PlaybackStatus".to_owned(), i64_value(42)); + player_props.insert( + "Metadata".to_owned(), + metadata_dict(vec![ + ("xesam:title", i64_value(7)), + ("xesam:artist", bool_value(true)), + ("xesam:album", u64_value(9)), + ("mpris:length", str_value("not-a-number")), + ]), + ); + player_props.insert("Position".to_owned(), str_value("also-not-a-number")); + player_props.insert("CanPlay".to_owned(), str_value("yes")); + player_props.insert("CanControl".to_owned(), i64_value(1)); + + let player = normalize_player( + "org.mpris.MediaPlayer2.spotify", + &HashMap::new(), + &player_props, + ) + .unwrap(); + + assert_eq!(player.status, PlaybackStatus::Stopped); + assert_eq!(player.title, None); + assert_eq!(player.artist, None); + assert_eq!(player.album, None); + assert_eq!(player.length_micros, None); + assert_eq!(player.position_micros, 0); + assert!(!player.can_play); + assert!(!player.can_control); + } + + #[test] + fn ignores_additional_metadata_fields() { + let metadata = metadata_dict(vec![ + ("xesam:title", str_value("Velora Theme")), + ("xesam:url", str_value("https://example.com/track")), + ("xesam:trackNumber", i64_value(3)), + ("mpris:artUrl", str_value("https://example.com/art.png")), + ]); + + let player = normalize_player( + "org.mpris.MediaPlayer2.spotify", + &media2_props("Spotify"), + &full_props(metadata), + ) + .unwrap(); + + assert_eq!(player.title.as_deref(), Some("Velora Theme")); + assert_eq!(player.album, None); + assert_eq!(player.length_micros, None); + } + + #[test] + fn malformed_metadata_is_a_typed_error() { + let mut player_props = HashMap::new(); + player_props.insert("Metadata".to_owned(), str_value("not-a-dictionary")); + + let error = normalize_player( + "org.mpris.MediaPlayer2.spotify", + &HashMap::new(), + &player_props, + ) + .unwrap_err(); + + assert!(matches!(error, MprisError::MalformedMetadata { .. })); + } + + #[test] + fn playback_status_normalizes_unknown_and_known_values() { + let statuses = [ + ("Playing", PlaybackStatus::Playing), + ("Paused", PlaybackStatus::Paused), + ("Stopped", PlaybackStatus::Stopped), + ]; + for (raw, expected) in statuses { + let mut props = HashMap::new(); + props.insert("PlaybackStatus".to_owned(), str_value(raw)); + assert_eq!(playback_status(&props), expected, "raw status {raw}"); + } + + let mut unknown = HashMap::new(); + unknown.insert("PlaybackStatus".to_owned(), str_value("Buffering")); + assert_eq!(playback_status(&unknown), PlaybackStatus::Stopped); + assert_eq!(playback_status(&HashMap::new()), PlaybackStatus::Stopped); + } + + #[test] + fn length_requires_a_positive_value_but_position_accepts_zero() { + assert_eq!(micros_value(&i64_value(250_000_000)), Some(250_000_000)); + assert_eq!(micros_value(&i64_value(0)), Some(0)); + assert_eq!(micros_value(&i64_value(-5)), None); + assert_eq!(micros_value(&u64_value(250_000_000)), Some(250_000_000)); + assert_eq!(micros_value(&str_value("nope")), None); + } + + #[test] + fn artist_arrays_are_bounded_and_single_strings_are_accepted() { + let mut metadata = HashMap::new(); + metadata.insert("xesam:artist".to_owned(), str_value("Solo Artist")); + assert_eq!(artist_field(&metadata).as_deref(), Some("Solo Artist")); + + let many: Vec = (0..(MAX_ARTIST_ENTRIES + 10)) + .map(|index| format!("Artist {index}")) + .collect(); + let mut metadata = HashMap::new(); + metadata.insert("xesam:artist".to_owned(), owned(Value::from(many))); + let joined = artist_field(&metadata).unwrap(); + assert!(joined.len() <= MAX_STRING_BYTES); + // Only the first MAX_ARTIST_ENTRIES artists can appear. + assert!(!joined.contains(&format!("Artist {MAX_ARTIST_ENTRIES}"))); + } + + #[test] + fn strings_are_trimmed_and_byte_bounded() { + assert_eq!(bounded_string(" padded "), "padded"); + + let long = "🦀".repeat(MAX_STRING_BYTES + 50); + let bounded = bounded_string(&long); + assert!(bounded.len() <= MAX_STRING_BYTES); + assert!(bounded.chars().count() < long.chars().count()); + } + + #[test] + fn player_handles_are_opaque_stable_and_collision_free() { + let spotify = opaque_player_handle("org.mpris.MediaPlayer2.spotify"); + let vlc = opaque_player_handle("org.mpris.MediaPlayer2.vlc"); + + assert!(spotify.starts_with("player:")); + assert!(!spotify.contains("org.mpris")); + assert_eq!( + spotify, + opaque_player_handle("org.mpris.MediaPlayer2.spotify") + ); + assert_ne!(spotify, vlc); + } + + #[test] + fn player_names_are_validated() { + assert!(validate_player_name("org.mpris.MediaPlayer2.spotify").is_ok()); + assert!(validate_player_name("").is_err()); + let too_long = "x".repeat(MAX_PLAYER_NAME_CHARS + 1); + assert!(validate_player_name(&too_long).is_err()); + } + + #[test] + fn control_verbs_map_to_exactly_the_fixed_player_methods() { + // The allowlist is exhaustive and maps each verb to one fixed, + // no-argument MPRIS Player method. There is no verb outside this set + // and no way to reach any other method. + assert_eq!(player_method(MediaControlVerb::Play), "Play"); + assert_eq!(player_method(MediaControlVerb::Pause), "Pause"); + assert_eq!(player_method(MediaControlVerb::PlayPause), "PlayPause"); + assert_eq!(player_method(MediaControlVerb::Stop), "Stop"); + assert_eq!(player_method(MediaControlVerb::Next), "Next"); + assert_eq!(player_method(MediaControlVerb::Previous), "Previous"); + } +} diff --git a/core/src/mpris_events.rs b/core/src/mpris_events.rs new file mode 100644 index 0000000..5195132 --- /dev/null +++ b/core/src/mpris_events.rs @@ -0,0 +1,769 @@ +//! MPRIS player discovery and signal listener. +//! +//! Velora observes `org.mpris.MediaPlayer2.*` players strictly through the +//! user session bus, never taking over a bus name and never opening a +//! full-bus monitor. This module is the discovery/observation half of the +//! MPRIS adapter: it subscribes to two signal families and reduces every +//! observation to a single "state is stale" mark on a capacity-1 dirty slot. +//! It never reads or builds player state itself — that is the media store's +//! job (P5.05), which consumes the dirty slot and re-reads authority with +//! `Properties.GetAll`. +//! +//! Two signal families are watched, both narrowed broker-side so unrelated +//! desktop traffic never reaches Core: +//! +//! * `NameOwnerChanged` (from `org.freedesktop.DBus`, arg0 namespace +//! `org.mpris.MediaPlayer2`) detects players appearing, disappearing, and +//! changing owners. +//! * `PropertiesChanged` (from `org.freedesktop.DBus.Properties`, path +//! namespace `/org/mpris`, arg0 namespace `org.mpris.MediaPlayer2`) is a +//! per-player invalidation hint. +//! +//! Signals are hints, never truth: the listener only marks the slot dirty, +//! and bursts coalesce into the single slot. Every disconnect re-marks the +//! slot because signals may have been missed while disconnected. Reconnection +//! is paced with bounded exponential backoff plus jitter so a flapping bus can +//! never produce a busy loop, and a missing bus is never fatal. + +use std::{ + collections::HashMap, + ffi::OsStr, + future::poll_fn, + pin::Pin, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use futures_core::Stream; +use thiserror::Error; +use tokio::{ + sync::{mpsc, watch}, + time::{sleep, timeout}, +}; +use tracing::{debug, warn}; +use zbus::{Connection, MatchRule, Message, MessageStream, message::Type, zvariant::OwnedValue}; + +/// The bus-driver interface and well-known name that emits `NameOwnerChanged`. +const DBUS_INTERFACE: &str = "org.freedesktop.DBus"; +const DBUS_NAME: &str = "org.freedesktop.DBus"; +const NAME_OWNER_CHANGED_MEMBER: &str = "NameOwnerChanged"; + +/// The standard D-Bus properties interface that emits `PropertiesChanged`. +const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties"; +const PROPERTIES_CHANGED_MEMBER: &str = "PropertiesChanged"; + +/// Namespace of every MPRIS player well-known name (`org.mpris.MediaPlayer2.*`). +const MPRIS_NAME_PREFIX: &str = "org.mpris.MediaPlayer2."; +/// Namespace of every MPRIS interface (`org.mpris.MediaPlayer2` and `.Player`). +const MPRIS_INTERFACE_NAMESPACE: &str = "org.mpris.MediaPlayer2"; +/// Path namespace under which every MPRIS player publishes its object. +const MPRIS_PATH_NAMESPACE: &str = "/org/mpris"; + +/// Maximum length of a bus or interface name accepted before it is ignored. +const MAX_NAME_CHARS: usize = 256; + +/// Bounded message queue per signal stream. A burst beyond this coalesces +/// inside zbus before it ever reaches the listener. +const MAX_QUEUED_SIGNALS: usize = 1; + +/// Maximum wall-clock time allowed to connect. A present but hung session-bus +/// socket must never keep the listener task stuck forever. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +/// A recognized MPRIS invalidation hint. Both variants are hints only: they +/// mark the shared dirty slot and never carry player state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum MprisSignal { + /// A player appeared, disappeared, or changed owners. + PlayerChurn, + /// A player reported changed properties. + PlayerProperties, +} + +/// Reconnect pacing. Production uses the default; tests shrink the delays. +#[derive(Debug, Clone, Copy)] +pub(crate) struct ListenerConfig { + pub initial_backoff: Duration, + pub max_backoff: Duration, +} + +impl ListenerConfig { + pub(crate) fn production() -> Self { + Self { + initial_backoff: Duration::from_millis(500), + max_backoff: Duration::from_secs(8), + } + } +} + +/// Typed failure of the MPRIS listener. A missing bus, a denied read, or a +/// malformed signal never panics and never marks the slot spuriously. +#[derive(Debug, Error)] +pub(crate) enum ListenerError { + #[error("session bus address override is not valid UTF-8")] + InvalidAddress, + #[error("failed to connect to the session bus: {0}")] + Connect(#[source] zbus::Error), + #[error("MPRIS signal subscription failed: {0}")] + Subscribe(#[source] zbus::Error), + #[error("MPRIS listener connection timed out")] + TimedOut, +} + +/// Long-running listener loop. Connects, subscribes, and marks the dirty slot +/// on every relevant signal until the streams close or shutdown is requested, +/// then reconnects with bounded exponential backoff plus jitter. +pub(crate) async fn run_listener( + address: Option<&OsStr>, + invalidation_tx: mpsc::Sender<()>, + mut shutdown: watch::Receiver, + config: ListenerConfig, +) { + let mut backoff = config.initial_backoff; + loop { + if *shutdown.borrow_and_update() { + return; + } + + match connect_with_timeout(address).await { + Ok(connection) => { + debug!("MPRIS listener connected to the session bus"); + backoff = config.initial_backoff; + match subscribe(&connection).await { + Ok((name_stream, props_stream)) => { + run_streams(name_stream, props_stream, &invalidation_tx, &mut shutdown) + .await; + // A disconnect may have dropped signals, so mark dirty + // before reconnecting. + invalidate(&invalidation_tx); + } + Err(error) => warn!(%error, "MPRIS signal subscription failed"), + } + } + Err(error) => warn!(%error, "MPRIS session bus unavailable"), + } + + let delay = reconnect_delay(backoff); + tokio::select! { + _ = shutdown.changed() => return, + _ = sleep(delay) => {} + } + backoff = next_backoff(backoff, config.max_backoff); + } +} + +async fn connect_with_timeout(address: Option<&OsStr>) -> Result { + match timeout(CONNECT_TIMEOUT, connect(address)).await { + Ok(result) => result, + Err(_) => Err(ListenerError::TimedOut), + } +} + +async fn connect(address: Option<&OsStr>) -> Result { + match address { + Some(address) => { + let address = address.to_str().ok_or(ListenerError::InvalidAddress)?; + zbus::connection::Builder::address(address) + .map_err(ListenerError::Connect)? + .build() + .await + .map_err(ListenerError::Connect) + } + None => Connection::session().await.map_err(ListenerError::Connect), + } +} + +/// Subscribe to both signal families with bounded queues. Each returned stream +/// registers its match rule with the bus and deregisters it on drop. +async fn subscribe( + connection: &Connection, +) -> Result<(MessageStream, MessageStream), ListenerError> { + let name_stream = MessageStream::for_match_rule( + name_owner_changed_rule(), + connection, + Some(MAX_QUEUED_SIGNALS), + ) + .await + .map_err(ListenerError::Subscribe)?; + let props_stream = MessageStream::for_match_rule( + properties_changed_rule(), + connection, + Some(MAX_QUEUED_SIGNALS), + ) + .await + .map_err(ListenerError::Subscribe)?; + Ok((name_stream, props_stream)) +} + +async fn run_streams( + mut name_stream: MessageStream, + mut props_stream: MessageStream, + invalidation_tx: &mpsc::Sender<()>, + shutdown: &mut watch::Receiver, +) { + loop { + tokio::select! { + _ = shutdown.changed() => return, + message = next_message(&mut name_stream) => match message { + Some(Ok(message)) => { + if parse_name_owner_changed(&message).is_some() { + invalidate(invalidation_tx); + } + } + Some(Err(error)) => { + warn!(%error, "MPRIS name-owner stream failed"); + return; + } + None => { + debug!("MPRIS name-owner stream closed"); + return; + } + }, + message = next_message(&mut props_stream) => match message { + Some(Ok(message)) => { + if parse_properties_changed(&message).is_some() { + invalidate(invalidation_tx); + } + } + Some(Err(error)) => { + warn!(%error, "MPRIS properties stream failed"); + return; + } + None => { + debug!("MPRIS properties stream closed"); + return; + } + }, + } + } +} + +/// Poll the next message from a stream. `MessageStream` implements +/// `futures_core::Stream`, so this avoids pulling in `futures-util`. +async fn next_message(stream: &mut MessageStream) -> Option> { + poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)).await +} + +fn invalidate(invalidation_tx: &mpsc::Sender<()>) { + // Full means the slot is already marked dirty; Closed means the consumer + // stopped. Both are safe to ignore. + let _ = invalidation_tx.try_send(()); +} + +/// The match rule for `NameOwnerChanged`, narrowed broker-side to the +/// bus-driver sender and the MPRIS well-known-name namespace. +fn name_owner_changed_rule() -> MatchRule<'static> { + MatchRule::builder() + .msg_type(Type::Signal) + .sender(DBUS_NAME) + .expect("org.freedesktop.DBus is a valid well-known name") + .interface(DBUS_INTERFACE) + .expect("org.freedesktop.DBus is a valid interface name") + .member(NAME_OWNER_CHANGED_MEMBER) + .expect("NameOwnerChanged is a valid member name") + .arg0ns(MPRIS_INTERFACE_NAMESPACE) + .expect("org.mpris.MediaPlayer2 is a valid bus-name namespace") + .build() +} + +/// The match rule for `PropertiesChanged`, narrowed broker-side to the MPRIS +/// object-path namespace and interface namespace. +fn properties_changed_rule() -> MatchRule<'static> { + MatchRule::builder() + .msg_type(Type::Signal) + .interface(PROPERTIES_INTERFACE) + .expect("org.freedesktop.DBus.Properties is a valid interface name") + .member(PROPERTIES_CHANGED_MEMBER) + .expect("PropertiesChanged is a valid member name") + .path_namespace(MPRIS_PATH_NAMESPACE) + .expect("/org/mpris is a valid object-path namespace") + .arg0ns(MPRIS_INTERFACE_NAMESPACE) + .expect("org.mpris.MediaPlayer2 is a valid bus-name namespace") + .build() +} + +/// Recognize an MPRIS `NameOwnerChanged` signal. `None` means the message is +/// unrelated or malformed and carries no invalidation. +fn parse_name_owner_changed(message: &Message) -> Option { + if message.message_type() != Type::Signal { + return None; + } + if message + .header() + .member() + .is_none_or(|member| member.as_str() != NAME_OWNER_CHANGED_MEMBER) + { + return None; + } + if message + .header() + .interface() + .is_none_or(|interface| interface.as_str() != DBUS_INTERFACE) + { + return None; + } + + let (name, _old_owner, _new_owner): (String, String, String) = + message.body().deserialize().ok()?; + if !is_mpris_player_name(&name) { + return None; + } + Some(MprisSignal::PlayerChurn) +} + +/// Recognize an MPRIS `PropertiesChanged` signal. `None` means the message is +/// unrelated or malformed and carries no invalidation. +fn parse_properties_changed(message: &Message) -> Option { + if message.message_type() != Type::Signal { + return None; + } + if message + .header() + .member() + .is_none_or(|member| member.as_str() != PROPERTIES_CHANGED_MEMBER) + { + return None; + } + if message + .header() + .interface() + .is_none_or(|interface| interface.as_str() != PROPERTIES_INTERFACE) + { + return None; + } + + let (interface, _changed, _invalidated): (String, HashMap, Vec) = + message.body().deserialize().ok()?; + if !is_mpris_interface(&interface) { + return None; + } + Some(MprisSignal::PlayerProperties) +} + +fn is_mpris_player_name(name: &str) -> bool { + !name.is_empty() && name.len() <= MAX_NAME_CHARS && name.starts_with(MPRIS_NAME_PREFIX) +} + +fn is_mpris_interface(interface: &str) -> bool { + !interface.is_empty() + && interface.len() <= MAX_NAME_CHARS + && (interface == MPRIS_INTERFACE_NAMESPACE || interface.starts_with(MPRIS_NAME_PREFIX)) +} + +/// The sleep before the next reconnect attempt: half the current backoff plus +/// a jittered second half, so the delay lands in `[backoff/2, backoff]` and is +/// never zero (no busy loop). +fn reconnect_delay(backoff: Duration) -> Duration { + let half = backoff.div_f64(2.0); + half + jitter(half) +} + +/// Grow the backoff exponentially, capped at `max`. A value that has already +/// reached the cap (or would overflow) stays at the cap. +fn next_backoff(backoff: Duration, max: Duration) -> Duration { + backoff + .checked_mul(2) + .map(|doubled| doubled.min(max)) + .unwrap_or(max) +} + +/// Jitter in `[0, half]` derived from the wall clock's sub-second nanos. Never +/// negative and never above `half`, so the combined delay stays within bounds. +fn jitter(half: Duration) -> Duration { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|since| since.subsec_nanos()) + .unwrap_or(0) as u64; + let spread = half.as_millis() as u64; + Duration::from_millis(nanos % (spread + 1)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::ffi::OsStrExt; + + const TEST_PLAYER_NAME: &str = "org.mpris.MediaPlayer2.testplayer"; + + fn name_owner_changed_message(name: &str) -> Message { + Message::signal( + "/org/freedesktop/DBus", + DBUS_INTERFACE, + NAME_OWNER_CHANGED_MEMBER, + ) + .unwrap() + .build(&(name.to_owned(), String::new(), String::from(":1.42"))) + .unwrap() + } + + fn properties_changed_message(interface: &str) -> Message { + Message::signal( + "/org/mpris/MediaPlayer2", + PROPERTIES_INTERFACE, + PROPERTIES_CHANGED_MEMBER, + ) + .unwrap() + .build(&( + interface.to_owned(), + HashMap::::new(), + Vec::::new(), + )) + .unwrap() + } + + fn fast_config() -> ListenerConfig { + ListenerConfig { + initial_backoff: Duration::from_millis(5), + max_backoff: Duration::from_millis(40), + } + } + + #[test] + fn recognizes_mpris_name_owner_changes() { + assert_eq!( + parse_name_owner_changed(&name_owner_changed_message(TEST_PLAYER_NAME)), + Some(MprisSignal::PlayerChurn) + ); + } + + #[test] + fn ignores_non_mpris_and_malformed_name_owner_changes() { + assert_eq!( + parse_name_owner_changed(&name_owner_changed_message("org.freedesktop.Notifications")), + None + ); + assert_eq!( + parse_name_owner_changed(&name_owner_changed_message("")), + None + ); + + let long = format!("org.mpris.MediaPlayer2.{}", "x".repeat(MAX_NAME_CHARS)); + assert_eq!( + parse_name_owner_changed(&name_owner_changed_message(&long)), + None + ); + + // Wrong member and wrong message type are ignored. + let method_call = Message::method_call("/org/freedesktop/DBus", "ListNames") + .unwrap() + .interface(DBUS_INTERFACE) + .unwrap() + .build(&()) + .unwrap(); + assert_eq!(parse_name_owner_changed(&method_call), None); + } + + #[test] + fn recognizes_mpris_properties_changes_for_both_interfaces() { + assert_eq!( + parse_properties_changed(&properties_changed_message("org.mpris.MediaPlayer2.Player")), + Some(MprisSignal::PlayerProperties) + ); + assert_eq!( + parse_properties_changed(&properties_changed_message("org.mpris.MediaPlayer2")), + Some(MprisSignal::PlayerProperties) + ); + } + + #[test] + fn ignores_non_mpris_and_malformed_properties_changes() { + assert_eq!( + parse_properties_changed(&properties_changed_message("org.freedesktop.Notifications")), + None + ); + assert_eq!( + parse_properties_changed(&properties_changed_message( + "org.mpris.MediaPlayer2NotAPlayer" + )), + None + ); + + // A mistyped body fails closed rather than guessing. + let malformed = Message::signal( + "/org/mpris/MediaPlayer2", + PROPERTIES_INTERFACE, + PROPERTIES_CHANGED_MEMBER, + ) + .unwrap() + .build(&(42_u32, "not-a-dictionary")) + .unwrap(); + assert_eq!(parse_properties_changed(&malformed), None); + } + + #[test] + fn match_rules_narrow_broker_side() { + let name_rule = name_owner_changed_rule().to_string(); + assert!(name_rule.contains("type='signal'")); + assert!(name_rule.contains("sender='org.freedesktop.DBus'")); + assert!(name_rule.contains("member='NameOwnerChanged'")); + assert!(name_rule.contains("arg0namespace='org.mpris.MediaPlayer2'")); + + let props_rule = properties_changed_rule().to_string(); + assert!(props_rule.contains("type='signal'")); + assert!(props_rule.contains("interface='org.freedesktop.DBus.Properties'")); + assert!(props_rule.contains("member='PropertiesChanged'")); + assert!(props_rule.contains("path_namespace='/org/mpris'")); + assert!(props_rule.contains("arg0namespace='org.mpris.MediaPlayer2'")); + } + + #[test] + fn backoff_grows_exponentially_and_is_bounded() { + let max = Duration::from_millis(8); + let mut backoff = Duration::from_millis(1); + for _ in 0..10 { + let next = next_backoff(backoff, max); + assert!(next >= backoff); + assert!(next <= max); + backoff = next; + } + assert_eq!(backoff, max); + } + + #[test] + fn reconnect_delay_stays_within_bounds_and_is_never_zero() { + for backoff in [ + Duration::from_millis(5), + Duration::from_millis(40), + Duration::from_secs(8), + ] { + let delay = reconnect_delay(backoff); + assert!(delay >= backoff.div_f64(2.0)); + assert!(delay <= backoff); + assert!(delay > Duration::ZERO); + } + } + + #[test] + fn invalidations_coalesce_into_a_single_slot() { + let (tx, mut rx) = mpsc::channel(1); + for _ in 0..500 { + invalidate(&tx); + } + // The capacity-1 slot collapses the burst into exactly one dirty mark. + let mut received = 0; + while rx.try_recv().is_ok() { + received += 1; + } + assert_eq!(received, 1, "burst must coalesce into a single slot"); + } + + mod listener { + use super::*; + use std::io::{BufRead, BufReader}; + use std::process::{Child, Command, Stdio}; + + /// A private `dbus-daemon` on a temporary address. Never the live + /// session bus. The child is killed and reaped on drop. + struct PrivateBus { + address: String, + child: Child, + } + + impl PrivateBus { + /// Spawn a foreground `dbus-daemon` and wait until it prints its + /// address (which also means the socket is bound and listening). + fn spawn() -> Option { + let mut child = Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + + let stdout = child.stdout.take()?; + let mut reader = BufReader::new(stdout); + let mut address = String::new(); + reader.read_line(&mut address).ok()?; + let address = address.trim().to_owned(); + if address.is_empty() { + return None; + } + Some(PrivateBus { address, child }) + } + + async fn connect(&self) -> Connection { + zbus::connection::Builder::address(self.address.as_str()) + .unwrap() + .build() + .await + .unwrap() + } + } + + impl Drop for PrivateBus { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + fn spawn_listener( + address: &str, + ) -> ( + mpsc::Receiver<()>, + watch::Sender, + tokio::task::JoinHandle<()>, + ) { + let address = std::ffi::OsString::from(address); + let (tx, rx) = mpsc::channel(1); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let handle = tokio::spawn(async move { + run_listener(Some(&address), tx, shutdown_rx, fast_config()).await; + }); + (rx, shutdown_tx, handle) + } + + async fn recv_invalidation(rx: &mut mpsc::Receiver<()>, budget: Duration) -> bool { + matches!(timeout(budget, rx.recv()).await, Ok(Some(()))) + } + + /// Acquire/release the test name until the listener reports an + /// invalidation, proving it has connected and subscribed. Drains the + /// slot so the caller starts from a clean, quiet channel. + async fn wait_until_live(player: &Connection, rx: &mut mpsc::Receiver<()>) { + for _ in 0..200 { + let _ = player.request_name(TEST_PLAYER_NAME).await; + let _ = player.release_name(TEST_PLAYER_NAME).await; + if recv_invalidation(rx, Duration::from_millis(30)).await { + while rx.try_recv().is_ok() {} + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("MPRIS listener never became live"); + } + + #[tokio::test] + async fn name_owner_appearance_and_disappearance_invalidate() { + let Some(bus) = PrivateBus::spawn() else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + let (mut rx, shutdown, handle) = spawn_listener(&bus.address); + let player = bus.connect().await; + wait_until_live(&player, &mut rx).await; + + player.request_name(TEST_PLAYER_NAME).await.unwrap(); + assert!( + recv_invalidation(&mut rx, Duration::from_secs(2)).await, + "player appearance must invalidate" + ); + + player.release_name(TEST_PLAYER_NAME).await.unwrap(); + assert!( + recv_invalidation(&mut rx, Duration::from_secs(2)).await, + "player disappearance must invalidate" + ); + + let _ = shutdown.send(true); + handle.abort(); + } + + #[tokio::test] + async fn properties_changes_invalidate() { + let Some(bus) = PrivateBus::spawn() else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + let (mut rx, shutdown, handle) = spawn_listener(&bus.address); + let player = bus.connect().await; + player.request_name(TEST_PLAYER_NAME).await.unwrap(); + wait_until_live(&player, &mut rx).await; + + player + .emit_signal( + None::<&str>, + "/org/mpris/MediaPlayer2", + PROPERTIES_INTERFACE, + PROPERTIES_CHANGED_MEMBER, + &( + "org.mpris.MediaPlayer2.Player".to_owned(), + HashMap::::new(), + Vec::::new(), + ), + ) + .await + .unwrap(); + + assert!( + recv_invalidation(&mut rx, Duration::from_secs(2)).await, + "PropertiesChanged must invalidate" + ); + + let _ = shutdown.send(true); + handle.abort(); + } + + #[tokio::test] + async fn player_churn_is_harmless() { + let Some(bus) = PrivateBus::spawn() else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + let (mut rx, shutdown, handle) = spawn_listener(&bus.address); + let player = bus.connect().await; + wait_until_live(&player, &mut rx).await; + + // Rapid acquisition/release cycles must not wedge the listener. + for _ in 0..50 { + let _ = player.request_name(TEST_PLAYER_NAME).await; + let _ = player.release_name(TEST_PLAYER_NAME).await; + } + while rx.try_recv().is_ok() {} + + // The listener still observes a subsequent change. + let _ = player.request_name(TEST_PLAYER_NAME).await; + while rx.try_recv().is_ok() {} + player + .emit_signal( + None::<&str>, + "/org/mpris/MediaPlayer2", + PROPERTIES_INTERFACE, + PROPERTIES_CHANGED_MEMBER, + &( + "org.mpris.MediaPlayer2.Player".to_owned(), + HashMap::::new(), + Vec::::new(), + ), + ) + .await + .unwrap(); + + assert!( + recv_invalidation(&mut rx, Duration::from_secs(2)).await, + "listener must survive player churn" + ); + + let _ = shutdown.send(true); + handle.abort(); + } + + #[tokio::test] + async fn unreachable_bus_still_yields_to_shutdown() { + let (tx, _rx) = mpsc::channel(1); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let handle = tokio::spawn(run_listener( + Some(OsStr::new("unix:path=/nonexistent/velora-mpris-test-bus")), + tx, + shutdown_rx, + fast_config(), + )); + + // The listener should be in its backoff sleep and respond to + // shutdown promptly instead of spinning in a busy loop. + let _ = shutdown_tx.send(true); + timeout(Duration::from_secs(2), handle) + .await + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn non_utf8_address_is_a_typed_unavailable() { + let address = OsStr::from_bytes(&[0xff, 0xfe, 0xfd]); + assert!(matches!( + connect(Some(address)).await.unwrap_err(), + ListenerError::InvalidAddress + )); + } + } +} diff --git a/core/src/notifications.rs b/core/src/notifications.rs new file mode 100644 index 0000000..8e578be --- /dev/null +++ b/core/src/notifications.rs @@ -0,0 +1,862 @@ +//! Narrow notification observer and privacy-gated, memory-only feed. +//! +//! Core observes notifications strictly through a `BecomeMonitor` eavesdrop +//! connection whose match rule is narrowed to +//! `interface='org.freedesktop.Notifications'`. The broker filters +//! non-matching traffic before it ever reaches Core, so unrelated desktop +//! traffic is never read — the narrowing is an architectural privacy control, +//! not a client-side filter. +//! +//! What is observed: +//! +//! * `Notify` method calls: the positional `app_name`, `summary`, and `body` +//! strings plus the `urgency` hint (byte `0` low, `1` normal, `2` critical). +//! `replaces_id`, `app_icon`, `actions`, and `expire_timeout` are never +//! retained, and the raw daemon id never crosses Velora IPC. +//! * `NotificationClosed` / `ActionInvoked` signals are unicast daemon replies +//! with no display content; they are recognized and ignored. +//! +//! The feed is memory-only (nothing is written to disk), bounded to +//! [`MAX_NOTIFICATIONS`] entries and [`MAX_NOTIFICATION_PAYLOAD_BYTES`] encoded +//! bytes with drop-oldest semantics, and every string is bounded to +//! [`MAX_STRING_BYTES`] bytes. Each entry carries an opaque, feed-issued handle +//! and a Core-generated timestamp. +//! +//! The observer is gated behind `VELORA_NOTIFICATIONS_ENABLED` (see +//! [`crate::config::NotificationsPolicy`]). A broker that refuses `BecomeMonitor` +//! degrades to the typed [`NotificationAvailability::Restricted`] result with no +//! retry storm; any other setup failure degrades to +//! [`NotificationAvailability::Unavailable`]. + +use std::{ + collections::{HashMap, VecDeque}, + env, + ffi::OsStr, + future::poll_fn, + pin::Pin, + sync::{Arc, Mutex}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use futures_core::Stream; +use thiserror::Error; +use tokio::{sync::watch, time::timeout}; +use tracing::{debug, info, warn}; +use velora_protocol::{ + MAX_NOTIFICATION_PAYLOAD_BYTES, MAX_NOTIFICATIONS, MAX_STRING_BYTES, Notification, + NotificationFeed, NotificationUrgency, +}; +use zbus::{ + Connection, MatchRule, Message, MessageStream, fdo::MonitoringProxy, message::Type, + zvariant::OwnedValue, +}; + +use crate::dbus::NotificationAvailability; + +/// Session-bus address override used by tests, mirroring the `VELORA_SOCKET` +/// and `VELORA_SESSION_BUS_ADDRESS` rules in the D-Bus probe. +const SESSION_BUS_ADDRESS_ENV: &str = "VELORA_SESSION_BUS_ADDRESS"; +const NOTIFICATIONS_INTERFACE: &str = "org.freedesktop.Notifications"; +const NOTIFY_MEMBER: &str = "Notify"; +/// Maximum wall-clock time allowed to connect and become a monitor. A present +/// but hung session-bus socket must never keep a monitor task stuck forever. +const MONITOR_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +/// One normalized notification observation extracted from a `Notify` call. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct NotifyObservation { + pub app_name: String, + pub summary: String, + pub body: String, + pub urgency: NotificationUrgency, +} + +/// The bounded, memory-only notification feed served to the frontend. +pub(crate) struct NotificationStore { + inner: Mutex, + /// Latest bounded feed for IPC clients. A watch channel coalesces bursts, + /// so a slow frontend consumes constant memory and receives only the most + /// recent authoritative state. + updates: watch::Sender>>, +} + +struct FeedState { + sequence: u64, + next_handle: u64, + notifications: VecDeque, + availability: NotificationAvailability, +} + +impl NotificationStore { + pub(crate) fn new() -> Self { + let (updates, _) = watch::channel(None); + Self { + inner: Mutex::new(FeedState { + sequence: 0, + next_handle: 1, + notifications: VecDeque::new(), + availability: NotificationAvailability::Unavailable, + }), + updates, + } + } + + /// The current feed, or `None` when no notification has been observed yet. + /// The last-good feed is retained in memory even across a monitor failure, + /// but it is only served while the monitor reports `Available`. + pub(crate) fn current(&self) -> Option> { + self.updates.borrow().clone() + } + + /// Subscribe to changed feeds for one IPC client. Intermediate bursts are + /// intentionally coalesced by `watch`; sequence fencing makes this safe. + pub(crate) fn subscribe(&self) -> watch::Receiver>> { + self.updates.subscribe() + } + + pub(crate) fn availability(&self) -> NotificationAvailability { + self.inner.lock().unwrap().availability + } + + pub(crate) fn set_availability(&self, availability: NotificationAvailability) { + self.inner.lock().unwrap().availability = availability; + } + + /// Insert one observed notification: issue an opaque feed handle, bound its + /// strings, and drop oldest entries until both structural and encoded-size + /// limits hold. + pub(crate) fn observe(&self, observation: NotifyObservation, timestamp_unix_ms: u64) { + let mut state = self.inner.lock().unwrap(); + state.sequence += 1; + let handle = format!("notification:{}", state.next_handle); + state.next_handle += 1; + let notification = Notification { + handle, + app_name: bounded_string(&observation.app_name, MAX_STRING_BYTES), + summary: bounded_string(&observation.summary, MAX_STRING_BYTES), + body: bounded_string(&observation.body, MAX_STRING_BYTES), + urgency: observation.urgency, + timestamp_unix_ms, + }; + state.notifications.push_back(notification); + while state.notifications.len() > MAX_NOTIFICATIONS + || encoded_feed_len(state.sequence, &state.notifications) + > MAX_NOTIFICATION_PAYLOAD_BYTES + { + state.notifications.pop_front(); + } + let feed = Arc::new(NotificationFeed { + sequence: state.sequence, + notifications: state.notifications.iter().cloned().collect(), + }); + drop(state); + self.updates.send_replace(Some(feed)); + } +} + +fn encoded_feed_len(sequence: u64, notifications: &VecDeque) -> usize { + serde_json::to_vec(&NotificationFeed { + sequence, + notifications: notifications.iter().cloned().collect(), + }) + .map_or(usize::MAX, |encoded| encoded.len()) +} + +/// Run the narrow monitor until shutdown. Spawned only when the privacy gate +/// (`VELORA_NOTIFICATIONS_ENABLED`) is open; every failure degrades to a typed +/// availability with no retry storm. +pub(crate) async fn run(store: Arc, shutdown: watch::Receiver) { + let address = env::var_os(SESSION_BUS_ADDRESS_ENV); + let connection = + match establish_monitor_with_timeout(address.as_deref(), MONITOR_CONNECT_TIMEOUT).await { + Ok(connection) => connection, + Err(error) => { + warn!(%error, "notification monitor could not start"); + store.set_availability(monitor_error_availability(&error)); + return; + } + }; + + store.set_availability(NotificationAvailability::Available); + info!("notification monitor active (match rule narrowed to the Notifications interface)"); + run_stream(store, connection, shutdown).await; +} + +async fn run_stream( + store: Arc, + connection: Connection, + mut shutdown: watch::Receiver, +) { + let mut stream = MessageStream::from(connection); + loop { + tokio::select! { + _ = shutdown.changed() => return, + message = next_message(&mut stream) => match message { + Some(Ok(message)) => handle_message(&store, message), + Some(Err(error)) => { + warn!(%error, "notification monitor stream failed"); + store.set_availability(NotificationAvailability::Unavailable); + return; + } + None => { + // The bus closed the monitor connection. + store.set_availability(NotificationAvailability::Unavailable); + info!("notification monitor stream closed"); + return; + } + }, + } + } +} + +/// Poll the next monitor message. `MessageStream` implements +/// `futures_core::Stream`, so this avoids pulling in `futures-util`. +async fn next_message(stream: &mut MessageStream) -> Option> { + poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)).await +} + +fn handle_message(store: &NotificationStore, message: Message) { + match parse_notify(&message) { + Ok(Some(observation)) => { + let timestamp_unix_ms = unix_time_millis(); + store.observe(observation, timestamp_unix_ms); + debug!("notification observed and appended to the feed"); + } + Ok(None) => { + // NotificationClosed / ActionInvoked / unrelated traffic: ignored. + } + Err(error) => { + // Fail closed: malformed external notification data is dropped + // rather than guessed at, and never reaches the feed. + warn!(%error, "dropping malformed notification"); + } + } +} + +/// Extract a normalized observation from a `Notify` method call. `Ok(None)` +/// means the message is not a `Notify` call and carries no feed content. +fn parse_notify(message: &Message) -> Result, NotifyParseError> { + if message.message_type() != Type::MethodCall { + return Ok(None); + } + if message + .header() + .member() + .is_none_or(|member| member.as_str() != NOTIFY_MEMBER) + { + return Ok(None); + } + // Defense in depth: the match rule already narrows the interface, but a + // non-conforming broker could deliver other traffic. + if message + .header() + .interface() + .is_none_or(|interface| interface.as_str() != NOTIFICATIONS_INTERFACE) + { + return Ok(None); + } + + let (app_name, _replaces_id, _app_icon, summary, body, _actions, hints, _expire_timeout) = + message + .body() + .deserialize::<( + String, + u32, + String, + String, + String, + Vec, + HashMap, + i32, + )>() + .map_err(NotifyParseError::MalformedBody)?; + + let urgency = urgency_from_hints(&hints)?; + + Ok(Some(NotifyObservation { + app_name, + summary, + body, + urgency, + })) +} + +fn urgency_from_hints( + hints: &HashMap, +) -> Result { + let Some(hint) = hints.get("urgency") else { + // Per the spec the hint is optional; absence defaults to normal. + return Ok(NotificationUrgency::Normal); + }; + match hint.downcast_ref::() { + Ok(0) => Ok(NotificationUrgency::Low), + Ok(1) => Ok(NotificationUrgency::Normal), + Ok(2) => Ok(NotificationUrgency::Critical), + _ => Err(NotifyParseError::MalformedUrgency), + } +} + +async fn establish_monitor_with_timeout( + address: Option<&OsStr>, + budget: Duration, +) -> Result { + match timeout(budget, establish_monitor(address)).await { + Ok(result) => result, + Err(_) => Err(MonitorError::TimedOut), + } +} + +async fn establish_monitor(address: Option<&OsStr>) -> Result { + let connection = connect(address).await?; + become_monitor(&connection).await?; + Ok(connection) +} + +async fn connect(address: Option<&OsStr>) -> Result { + match address { + Some(address) => { + let address = address.to_str().ok_or(MonitorError::InvalidAddress)?; + zbus::connection::Builder::address(address) + .map_err(MonitorError::Connect)? + .build() + .await + .map_err(MonitorError::Connect) + } + None => Connection::session().await.map_err(MonitorError::Connect), + } +} + +async fn become_monitor(connection: &Connection) -> Result<(), MonitorError> { + let proxy = MonitoringProxy::new(connection) + .await + .map_err(MonitorError::Call)?; + let rules = [monitor_match_rule()]; + proxy + .become_monitor(&rules, 0) + .await + .map_err(map_fdo_error)?; + Ok(()) +} + +/// The monitor match rule: narrowed to the Notifications interface only. The +/// broker enforces this before any message reaches Core. +fn monitor_match_rule() -> MatchRule<'static> { + MatchRule::builder() + .interface(NOTIFICATIONS_INTERFACE) + .expect("org.freedesktop.Notifications is a valid interface name") + .build() +} + +fn map_fdo_error(error: zbus::fdo::Error) -> MonitorError { + match error { + zbus::fdo::Error::AccessDenied(_) => MonitorError::AccessDenied, + other => MonitorError::Call(other.into()), + } +} + +fn monitor_error_availability(error: &MonitorError) -> NotificationAvailability { + match error { + MonitorError::AccessDenied => NotificationAvailability::Restricted, + _ => NotificationAvailability::Unavailable, + } +} + +fn bounded_string(value: &str, max_bytes: usize) -> String { + let trimmed = value.trim(); + if trimmed.len() <= max_bytes { + return trimmed.to_owned(); + } + // Step back to a UTF-8 character boundary so the slice stays valid. + let mut end = max_bytes; + while end > 0 && !trimmed.is_char_boundary(end) { + end -= 1; + } + trimmed[..end].to_owned() +} + +fn unix_time_millis() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok()) + .unwrap_or(u64::MAX) +} + +#[derive(Debug, Error)] +enum MonitorError { + #[error("session bus address override is not valid UTF-8")] + InvalidAddress, + #[error("failed to connect to the session bus: {0}")] + Connect(#[source] zbus::Error), + #[error("monitoring call failed: {0}")] + Call(#[source] zbus::Error), + #[error("monitoring was denied by the bus")] + AccessDenied, + #[error("notification monitor setup timed out")] + TimedOut, +} + +#[derive(Debug, Error)] +enum NotifyParseError { + #[error("notification body could not be decoded: {0}")] + MalformedBody(#[source] zbus::Error), + #[error("notification urgency hint is malformed")] + MalformedUrgency, +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + io::{BufRead, BufReader}, + os::unix::ffi::OsStrExt, + process::{Child, Command, Stdio}, + }; + + /// A private `dbus-daemon` used only by notification tests. The child is + /// killed and reaped on drop, so failures cannot leave a daemon behind or + /// fall back to the user's live session bus. + struct PrivateBus { + address: String, + child: Child, + _directory: Option, + } + + impl PrivateBus { + fn spawn() -> Option { + Self::spawn_with_args(&["--session", "--nofork", "--print-address=1"], None) + } + + fn spawn_monitor_denied() -> Option { + let directory = tempfile::tempdir().ok()?; + let config_path = directory.path().join("monitor-denied.conf"); + std::fs::write( + &config_path, + r#" + + session + unix:tmpdir=/tmp + + + + + + + + +"#, + ) + .ok()?; + let config_arg = format!("--config-file={}", config_path.display()); + Self::spawn_with_args( + &[config_arg.as_str(), "--nofork", "--print-address=1"], + Some(directory), + ) + } + + fn spawn_with_args(args: &[&str], directory: Option) -> Option { + let mut child = Command::new("dbus-daemon") + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let stdout = child.stdout.take()?; + let mut reader = BufReader::new(stdout); + let mut address = String::new(); + reader.read_line(&mut address).ok()?; + let address = address.trim().to_owned(); + if address.is_empty() { + return None; + } + Some(Self { + address, + child, + _directory: directory, + }) + } + + async fn connect(&self) -> Connection { + zbus::connection::Builder::address(self.address.as_str()) + .unwrap() + .build() + .await + .unwrap() + } + } + + impl Drop for PrivateBus { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + fn observation(app_name: &str) -> NotifyObservation { + NotifyObservation { + app_name: app_name.to_owned(), + summary: "Summary".to_owned(), + body: "Body".to_owned(), + urgency: NotificationUrgency::Normal, + } + } + + fn notify_message(app_name: &str, summary: &str, body: &str, urgency: Option) -> Message { + let mut hints = HashMap::::new(); + if let Some(urgency) = urgency { + hints.insert("urgency".to_owned(), OwnedValue::from(urgency)); + } + let payload = ( + app_name.to_owned(), + 0u32, + String::new(), + summary.to_owned(), + body.to_owned(), + Vec::::new(), + hints, + -1i32, + ); + Message::method_call("/org/freedesktop/Notifications", NOTIFY_MEMBER) + .unwrap() + .interface(NOTIFICATIONS_INTERFACE) + .unwrap() + .build(&payload) + .unwrap() + } + + #[test] + fn feed_is_bounded_with_drop_oldest() { + let store = NotificationStore::new(); + for index in 0..(MAX_NOTIFICATIONS + 5) { + store.observe(observation(&format!("app-{index}")), index as u64); + } + + let feed = store.current().unwrap(); + assert!(feed.notifications.len() <= MAX_NOTIFICATIONS); + // At least the oldest five entries were dropped by the count bound; + // the byte budget may conservatively drop more. + assert_ne!(feed.notifications[0].app_name, "app-0"); + assert_eq!( + feed.notifications.last().unwrap().app_name, + format!("app-{}", MAX_NOTIFICATIONS + 4) + ); + assert!(serde_json::to_vec(&*feed).unwrap().len() <= MAX_NOTIFICATION_PAYLOAD_BYTES); + feed.validate().unwrap(); + } + + #[test] + fn payload_budget_drops_oldest_full_width_notifications() { + let store = NotificationStore::new(); + for index in 0..MAX_NOTIFICATIONS { + store.observe( + NotifyObservation { + app_name: format!("app-{index}"), + summary: "s".repeat(MAX_STRING_BYTES), + body: "b".repeat(MAX_STRING_BYTES), + urgency: NotificationUrgency::Normal, + }, + index as u64, + ); + } + + let feed = store.current().unwrap(); + assert!(feed.notifications.len() < MAX_NOTIFICATIONS); + assert!(serde_json::to_vec(&*feed).unwrap().len() <= MAX_NOTIFICATION_PAYLOAD_BYTES); + assert_eq!( + feed.notifications.last().unwrap().app_name, + format!("app-{}", MAX_NOTIFICATIONS - 1) + ); + } + + #[tokio::test] + async fn subscribers_receive_only_the_latest_bounded_feed() { + let store = NotificationStore::new(); + let mut updates = store.subscribe(); + for index in 0..100 { + store.observe(observation(&format!("app-{index}")), index); + } + + updates.changed().await.unwrap(); + let feed = updates.borrow_and_update().clone().unwrap(); + assert_eq!(feed.sequence, 100); + assert_eq!(feed.notifications.last().unwrap().app_name, "app-99"); + assert!(serde_json::to_vec(&*feed).unwrap().len() <= MAX_NOTIFICATION_PAYLOAD_BYTES); + } + + #[test] + fn handles_are_feed_issued_and_unique() { + let store = NotificationStore::new(); + store.observe(observation("a"), 1); + store.observe(observation("b"), 2); + + let feed = store.current().unwrap(); + assert_eq!(feed.notifications[0].handle, "notification:1"); + assert_eq!(feed.notifications[1].handle, "notification:2"); + assert_ne!(feed.notifications[0].handle, feed.notifications[1].handle); + } + + #[test] + fn observation_strings_are_bounded() { + let store = NotificationStore::new(); + let mut observation = observation("app"); + observation.summary = "s".repeat(MAX_STRING_BYTES + 100); + store.observe(observation, 1); + + let feed = store.current().unwrap(); + assert_eq!(feed.notifications[0].summary.len(), MAX_STRING_BYTES); + feed.validate().unwrap(); + } + + #[test] + fn empty_feed_has_no_current() { + let store = NotificationStore::new(); + assert!(store.current().is_none()); + } + + #[test] + fn availability_transitions() { + let store = NotificationStore::new(); + assert_eq!(store.availability(), NotificationAvailability::Unavailable); + + store.set_availability(NotificationAvailability::Available); + assert_eq!(store.availability(), NotificationAvailability::Available); + + store.set_availability(NotificationAvailability::Restricted); + assert_eq!(store.availability(), NotificationAvailability::Restricted); + } + + #[test] + fn parses_a_valid_notify_method_call() { + let message = notify_message("App", "Summary", "Body", Some(2)); + let observation = parse_notify(&message).unwrap().unwrap(); + assert_eq!(observation.app_name, "App"); + assert_eq!(observation.summary, "Summary"); + assert_eq!(observation.body, "Body"); + assert_eq!(observation.urgency, NotificationUrgency::Critical); + } + + #[test] + fn missing_urgency_defaults_to_normal() { + let message = notify_message("App", "Summary", "Body", None); + let observation = parse_notify(&message).unwrap().unwrap(); + assert_eq!(observation.urgency, NotificationUrgency::Normal); + } + + #[test] + fn urgency_boundaries_map_to_typed_levels() { + for (byte, expected) in [ + (0, NotificationUrgency::Low), + (1, NotificationUrgency::Normal), + (2, NotificationUrgency::Critical), + ] { + let message = notify_message("App", "Summary", "Body", Some(byte)); + assert_eq!(parse_notify(&message).unwrap().unwrap().urgency, expected); + } + } + + #[test] + fn ignores_non_notify_members_and_signals() { + let method_call = Message::method_call("/org/freedesktop/Notifications", "GetCapabilities") + .unwrap() + .interface(NOTIFICATIONS_INTERFACE) + .unwrap() + .build(&()) + .unwrap(); + assert!(parse_notify(&method_call).unwrap().is_none()); + + let signal = Message::signal( + "/org/freedesktop/Notifications", + NOTIFICATIONS_INTERFACE, + "NotificationClosed", + ) + .unwrap() + .build(&(0u32, 1u32)) + .unwrap(); + assert!(parse_notify(&signal).unwrap().is_none()); + } + + #[test] + fn malformed_body_fails_closed() { + let message = Message::method_call("/org/freedesktop/Notifications", NOTIFY_MEMBER) + .unwrap() + .interface(NOTIFICATIONS_INTERFACE) + .unwrap() + .build(&(1u32, "wrong shape")) + .unwrap(); + assert!(matches!( + parse_notify(&message), + Err(NotifyParseError::MalformedBody(_)) + )); + } + + #[test] + fn malformed_urgency_fails_closed() { + let mut hints = HashMap::::new(); + hints.insert( + "urgency".to_owned(), + zbus::zvariant::Value::from("high").try_into().unwrap(), + ); + let payload = ( + "App".to_owned(), + 0u32, + String::new(), + "Summary".to_owned(), + "Body".to_owned(), + Vec::::new(), + hints, + -1i32, + ); + let message = Message::method_call("/org/freedesktop/Notifications", NOTIFY_MEMBER) + .unwrap() + .interface(NOTIFICATIONS_INTERFACE) + .unwrap() + .build(&payload) + .unwrap(); + assert_eq!( + parse_notify(&message).unwrap_err().to_string(), + NotifyParseError::MalformedUrgency.to_string() + ); + } + + #[tokio::test] + async fn unreachable_bus_is_a_typed_unavailable() { + let error = establish_monitor(Some(OsStr::new( + "unix:path=/nonexistent/velora-test-notifications-bus", + ))) + .await + .unwrap_err(); + assert_eq!( + monitor_error_availability(&error), + NotificationAvailability::Unavailable + ); + } + + #[tokio::test] + async fn non_utf8_address_is_a_typed_unavailable() { + let address = OsStr::from_bytes(&[0xff, 0xfe, 0xfd]); + let error = establish_monitor(Some(address)).await.unwrap_err(); + assert!(matches!(error, MonitorError::InvalidAddress)); + assert_eq!( + monitor_error_availability(&error), + NotificationAvailability::Unavailable + ); + } + + #[tokio::test] + async fn denied_monitoring_classifies_as_restricted() { + assert_eq!( + monitor_error_availability(&MonitorError::AccessDenied), + NotificationAvailability::Restricted + ); + } + + #[tokio::test] + async fn private_bus_synthetic_notify_reaches_the_memory_only_feed() { + let Some(bus) = PrivateBus::spawn() else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + let monitor = establish_monitor(Some(OsStr::new(&bus.address))) + .await + .unwrap(); + let sender = bus.connect().await; + let store = Arc::new(NotificationStore::new()); + store.set_availability(NotificationAvailability::Available); + let mut updates = store.subscribe(); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let monitor_task = tokio::spawn(run_stream(Arc::clone(&store), monitor, shutdown_rx)); + + let mut hints = HashMap::::new(); + hints.insert("urgency".to_owned(), OwnedValue::from(2u8)); + let message = Message::method_call("/org/freedesktop/Notifications", NOTIFY_MEMBER) + .unwrap() + .destination(NOTIFICATIONS_INTERFACE) + .unwrap() + .interface(NOTIFICATIONS_INTERFACE) + .unwrap() + .build(&( + "Private Test".to_owned(), + 0u32, + String::new(), + "Synthetic summary".to_owned(), + "Synthetic body".to_owned(), + Vec::::new(), + hints, + -1i32, + )) + .unwrap(); + sender.send(&message).await.unwrap(); + + timeout(Duration::from_secs(2), updates.changed()) + .await + .unwrap() + .unwrap(); + let feed = updates.borrow_and_update().clone().unwrap(); + assert_eq!(feed.notifications.len(), 1); + assert_eq!(feed.notifications[0].app_name, "Private Test"); + assert_eq!(feed.notifications[0].summary, "Synthetic summary"); + assert_eq!(feed.notifications[0].urgency, NotificationUrgency::Critical); + assert!(serde_json::to_vec(&*feed).unwrap().len() <= MAX_NOTIFICATION_PAYLOAD_BYTES); + + let _ = shutdown_tx.send(true); + timeout(Duration::from_secs(1), monitor_task) + .await + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn private_bus_denial_is_typed_restricted_without_retrying() { + let Some(bus) = PrivateBus::spawn_monitor_denied() else { + eprintln!("dbus-daemon unavailable; skipping"); + return; + }; + let error = establish_monitor(Some(OsStr::new(&bus.address))) + .await + .unwrap_err(); + assert!(matches!(error, MonitorError::AccessDenied)); + assert_eq!( + monitor_error_availability(&error), + NotificationAvailability::Restricted + ); + } + + #[tokio::test] + async fn hung_bus_socket_times_out() { + use std::os::unix::net::UnixListener as StdUnixListener; + + let directory = tempfile::tempdir().unwrap(); + let socket_path = directory.path().join("hung-notifications-bus"); + let listener = StdUnixListener::bind(&socket_path).unwrap(); + + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (_stream, _address) = listener.accept().unwrap(); + let _ = stop_rx.recv(); + }); + + let address = format!("unix:path={}", socket_path.display()); + let result = + establish_monitor_with_timeout(Some(OsStr::new(&address)), Duration::from_millis(100)) + .await; + + let _ = stop_tx.send(()); + server.join().unwrap(); + + assert!(matches!(result, Err(MonitorError::TimedOut))); + } + + #[test] + fn strings_are_trimmed_and_byte_bounded() { + assert_eq!(bounded_string(" padded ", 8), "padded"); + assert_eq!(bounded_string("short", 100), "short"); + + let multibyte = "🦀".repeat(MAX_STRING_BYTES); + let bounded = bounded_string(&multibyte, MAX_STRING_BYTES); + assert!(bounded.len() <= MAX_STRING_BYTES); + assert!(std::str::from_utf8(bounded.as_bytes()).is_ok()); + } +} diff --git a/crates/velora-protocol/src/lib.rs b/crates/velora-protocol/src/lib.rs index dea05d4..4fc9a3e 100644 --- a/crates/velora-protocol/src/lib.rs +++ b/crates/velora-protocol/src/lib.rs @@ -3,8 +3,11 @@ use std::{env, path::PathBuf}; use thiserror::Error; /// Core, the native bridge, and Godot intentionally require an exact match. -/// Phase 4 adds the typed system-telemetry contract. -pub const PROTOCOL_VERSION: u8 = 4; +/// Phase 5 bumps the contract to v5 for the typed media and notification +/// contract. v5 is not backward compatible with v4: the exact-match handshake +/// rejects any client that does not advertise `PROTOCOL_VERSION`, so Core, +/// the bridge fixtures, and Godot move together (see the Phase 5 plan). +pub const PROTOCOL_VERSION: u8 = 5; pub const MAX_MESSAGE_BYTES: usize = 64 * 1024; pub const HANDSHAKE_TIMEOUT_SECONDS: u64 = 5; pub const DEFAULT_APPLICATION_PAGE_SIZE: u16 = 32; @@ -17,6 +20,21 @@ pub const MAX_TELEMETRY_INTERVAL_MS: u32 = 10_000; pub const MAX_TELEMETRY_DEVICES: u16 = 64; pub const MAX_TELEMETRY_INTERFACES: u16 = 64; pub const MAX_TELEMETRY_PAYLOAD_BYTES: usize = 4 * 1024; +/// Maximum number of MPRIS players carried in one media snapshot. +pub const MAX_MEDIA_PLAYERS: usize = 16; +/// Maximum number of notifications carried in one bounded notification feed. +pub const MAX_NOTIFICATIONS: usize = 32; +/// Maximum byte length (UTF-8) of any media/notification string field. +pub const MAX_STRING_BYTES: usize = 256; +/// Frame budget for a serialized media snapshot. This is a Core-enforced +/// production budget, not a consequence of the structural ceilings: sixteen +/// players at full-width strings can exceed 4 KiB, so Core bounds the payload +/// independently (truncating metadata) when it serves a snapshot. +pub const MAX_MEDIA_PAYLOAD_BYTES: usize = 4 * 1024; +/// Frame budget for a serialized notification feed, enforced by Core via +/// drop-oldest/truncation. The structural ceiling (`MAX_NOTIFICATIONS`) does +/// not by itself guarantee a frame fits this budget. +pub const MAX_NOTIFICATION_PAYLOAD_BYTES: usize = 4 * 1024; pub const CLIENT_NAME: &str = "velora-godot"; pub const SERVER_NAME: &str = "velora-core"; @@ -283,6 +301,202 @@ impl TelemetrySnapshot { } } +/// MPRIS `PlaybackStatus` values. A player that has not reported a status yet +/// is normalized to `Stopped` by Core rather than inventing a fourth variant. +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum PlaybackStatus { + Playing, + Paused, + Stopped, +} + +/// One MPRIS player normalized for the media console. The handle is opaque and +/// snapshot-issued; a raw D-Bus well-known name never crosses Velora IPC. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct MediaPlayer { + /// Opaque, snapshot-issued identifier. Never a raw bus name. + pub handle: String, + /// Human-readable player identity (for example "Spotify"). Never a bus name. + pub identity: String, + pub status: PlaybackStatus, + pub title: Option, + pub artist: Option, + pub album: Option, + /// Track length in microseconds, when known. + pub length_micros: Option, + /// Playback position in microseconds. + pub position_micros: u64, + pub can_play: bool, + pub can_pause: bool, + pub can_go_next: bool, + pub can_go_previous: bool, + pub can_seek: bool, + pub can_control: bool, +} + +/// The single authoritative media snapshot Core serves to the frontend. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct MediaSnapshot { + /// Monotonically increasing within one Core session. Clients ignore older + /// values so a reconnecting or stale reader can never regress state. + pub sequence: u64, + pub players: Vec, + pub active_player_handle: Option, +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum MediaSnapshotValidationError { + #[error("media snapshot contains more than {MAX_MEDIA_PLAYERS} players")] + TooManyPlayers, + #[error("media snapshot contains an empty or duplicate player handle")] + InvalidPlayerHandle, + #[error("media snapshot string exceeds {MAX_STRING_BYTES} bytes")] + StringTooLong, + #[error("active player handle is not in the snapshot")] + UnknownActivePlayer, +} + +impl MediaSnapshot { + pub fn is_newer_than(&self, sequence: u64) -> bool { + self.sequence > sequence + } + + pub fn validate(&self) -> Result<(), MediaSnapshotValidationError> { + if self.players.len() > MAX_MEDIA_PLAYERS { + return Err(MediaSnapshotValidationError::TooManyPlayers); + } + + let mut handles = std::collections::HashSet::new(); + for player in &self.players { + if player.handle.is_empty() || !handles.insert(&player.handle) { + return Err(MediaSnapshotValidationError::InvalidPlayerHandle); + } + player.validate_strings()?; + } + + if self + .active_player_handle + .as_ref() + .is_some_and(|handle| !handles.contains(handle)) + { + return Err(MediaSnapshotValidationError::UnknownActivePlayer); + } + + Ok(()) + } +} + +impl MediaPlayer { + fn validate_strings(&self) -> Result<(), MediaSnapshotValidationError> { + let fields = [ + Some(self.identity.as_str()), + self.title.as_deref(), + self.artist.as_deref(), + self.album.as_deref(), + ]; + if fields + .into_iter() + .flatten() + .any(|field| field.len() > MAX_STRING_BYTES) + { + return Err(MediaSnapshotValidationError::StringTooLong); + } + Ok(()) + } +} + +/// Notifications urgency levels (`0` low, `1` normal, `2` critical). +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum NotificationUrgency { + Low, + Normal, + Critical, +} + +/// One observed notification. The handle is opaque and feed-issued; the raw +/// daemon replacement id never crosses Velora IPC. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct Notification { + /// Opaque, feed-issued identifier. Never a raw daemon id. + pub handle: String, + pub app_name: String, + pub summary: String, + pub body: String, + pub urgency: NotificationUrgency, + /// Unix timestamp in milliseconds when the notification was posted. + pub timestamp_unix_ms: u64, +} + +/// The bounded, memory-only notification feed Core serves to the frontend. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct NotificationFeed { + /// Monotonically increasing within one Core session. + pub sequence: u64, + pub notifications: Vec, +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum NotificationFeedValidationError { + #[error("notification feed contains more than {MAX_NOTIFICATIONS} notifications")] + TooManyNotifications, + #[error("notification feed contains an empty or duplicate handle")] + InvalidNotificationHandle, + #[error("notification string exceeds {MAX_STRING_BYTES} bytes")] + StringTooLong, +} + +impl NotificationFeed { + pub fn is_newer_than(&self, sequence: u64) -> bool { + self.sequence > sequence + } + + pub fn validate(&self) -> Result<(), NotificationFeedValidationError> { + if self.notifications.len() > MAX_NOTIFICATIONS { + return Err(NotificationFeedValidationError::TooManyNotifications); + } + + let mut handles = std::collections::HashSet::new(); + for notification in &self.notifications { + if notification.handle.is_empty() || !handles.insert(¬ification.handle) { + return Err(NotificationFeedValidationError::InvalidNotificationHandle); + } + notification.validate_strings()?; + } + + Ok(()) + } +} + +impl Notification { + fn validate_strings(&self) -> Result<(), NotificationFeedValidationError> { + let fields = [ + self.app_name.as_str(), + self.summary.as_str(), + self.body.as_str(), + ]; + if fields.iter().any(|field| field.len() > MAX_STRING_BYTES) { + return Err(NotificationFeedValidationError::StringTooLong); + } + Ok(()) + } +} + +/// The only control verbs Godot may send. Bus names, method names, and +/// arguments never cross Velora IPC; Core re-maps this allowlisted verb onto +/// the corresponding MPRIS method for the opaque player handle. +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum MediaControlVerb { + Play, + Pause, + PlayPause, + Stop, + Next, + Previous, +} + #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] pub struct Application { pub id: String, @@ -343,6 +557,21 @@ pub enum Request { protocol_version: u8, request_id: u64, }, + GetMediaSnapshot { + protocol_version: u8, + request_id: u64, + }, + GetNotifications { + protocol_version: u8, + request_id: u64, + }, + SendMediaControl { + protocol_version: u8, + request_id: u64, + /// A snapshot-issued opaque handle. Raw bus names are never accepted. + player_handle: String, + verb: MediaControlVerb, + }, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] @@ -433,6 +662,39 @@ pub enum Response { code: TelemetrySnapshotError, retryable: bool, }, + MediaSnapshot { + protocol_version: u8, + request_id: u64, + snapshot: MediaSnapshot, + }, + MediaSnapshotRejected { + protocol_version: u8, + request_id: u64, + code: MediaSnapshotError, + retryable: bool, + }, + Notifications { + protocol_version: u8, + request_id: u64, + feed: NotificationFeed, + }, + NotificationsRejected { + protocol_version: u8, + request_id: u64, + code: NotificationsError, + retryable: bool, + }, + MediaControlAccepted { + protocol_version: u8, + request_id: u64, + player_handle: String, + }, + MediaControlRejected { + protocol_version: u8, + request_id: u64, + player_handle: String, + code: MediaControlError, + }, } #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] @@ -471,6 +733,31 @@ pub enum WindowFocusError { FocusFailed, } +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum MediaSnapshotError { + MediaUnavailable, + SnapshotNotReady, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum MediaControlError { + MediaUnavailable, + UnknownPlayer, + StaleHandle, + ControlUnavailable, + ControlFailed, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum NotificationsError { + NotificationsUnavailable, + MonitorRestricted, + FeedNotReady, +} + impl Request { pub fn protocol_version(&self) -> u8 { match self { @@ -500,6 +787,15 @@ impl Request { } | Self::GetTelemetrySnapshot { protocol_version, .. + } + | Self::GetMediaSnapshot { + protocol_version, .. + } + | Self::GetNotifications { + protocol_version, .. + } + | Self::SendMediaControl { + protocol_version, .. } => *protocol_version, } } @@ -552,7 +848,7 @@ mod tests { .unwrap(); assert_eq!( value, - r#"{"type":"hello","protocol_version":4,"client_name":"velora-godot","client_version":"0.2.0"}"# + r#"{"type":"hello","protocol_version":5,"client_name":"velora-godot","client_version":"0.2.0"}"# ); } @@ -941,4 +1237,292 @@ mod tests { Err(TelemetryValidationError::InvalidSampleInterval) ); } + + fn test_media_player(handle: &str) -> MediaPlayer { + MediaPlayer { + handle: handle.to_owned(), + identity: "Spotify".to_owned(), + status: PlaybackStatus::Playing, + title: Some("Velora Theme".to_owned()), + artist: Some("Velora".to_owned()), + album: Some("Phase 5".to_owned()), + length_micros: Some(250_000_000), + position_micros: 12_500_000, + can_play: true, + can_pause: true, + can_go_next: true, + can_go_previous: true, + can_seek: true, + can_control: true, + } + } + + fn test_media_snapshot() -> MediaSnapshot { + MediaSnapshot { + sequence: 9, + players: vec![test_media_player("player:opaque-1")], + active_player_handle: Some("player:opaque-1".to_owned()), + } + } + + fn test_notification(handle: &str) -> Notification { + Notification { + handle: handle.to_owned(), + app_name: "Velora".to_owned(), + summary: "Build complete".to_owned(), + body: "The release gate passed.".to_owned(), + urgency: NotificationUrgency::Normal, + timestamp_unix_ms: 1_777_777_777_000, + } + } + + fn test_notification_feed() -> NotificationFeed { + NotificationFeed { + sequence: 5, + notifications: vec![test_notification("notification:opaque-1")], + } + } + + #[test] + fn round_trips_media_snapshot_request_response_and_rejection() { + let request = Request::GetMediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 61, + }; + let json = serde_json::to_string(&request).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), request); + assert_eq!(request.protocol_version(), PROTOCOL_VERSION); + + let response = Response::MediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 61, + snapshot: test_media_snapshot(), + }; + let json = serde_json::to_string(&response).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), response); + + let rejected = Response::MediaSnapshotRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 62, + code: MediaSnapshotError::MediaUnavailable, + retryable: false, + }; + let json = serde_json::to_string(&rejected).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), rejected); + } + + #[test] + fn round_trips_notifications_request_response_and_rejection() { + let request = Request::GetNotifications { + protocol_version: PROTOCOL_VERSION, + request_id: 63, + }; + let json = serde_json::to_string(&request).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), request); + assert_eq!(request.protocol_version(), PROTOCOL_VERSION); + + let response = Response::Notifications { + protocol_version: PROTOCOL_VERSION, + request_id: 63, + feed: test_notification_feed(), + }; + let json = serde_json::to_string(&response).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), response); + + for code in [ + NotificationsError::NotificationsUnavailable, + NotificationsError::MonitorRestricted, + NotificationsError::FeedNotReady, + ] { + let rejected = Response::NotificationsRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 64, + code, + retryable: true, + }; + let json = serde_json::to_string(&rejected).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), rejected); + } + } + + #[test] + fn round_trips_media_control_request_and_typed_outcomes() { + for verb in [ + MediaControlVerb::Play, + MediaControlVerb::Pause, + MediaControlVerb::PlayPause, + MediaControlVerb::Stop, + MediaControlVerb::Next, + MediaControlVerb::Previous, + ] { + let request = Request::SendMediaControl { + protocol_version: PROTOCOL_VERSION, + request_id: 71, + player_handle: "player:opaque-1".to_owned(), + verb, + }; + let json = serde_json::to_string(&request).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), request); + assert_eq!(request.protocol_version(), PROTOCOL_VERSION); + } + + let accepted = Response::MediaControlAccepted { + protocol_version: PROTOCOL_VERSION, + request_id: 71, + player_handle: "player:opaque-1".to_owned(), + }; + let json = serde_json::to_string(&accepted).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), accepted); + + for code in [ + MediaControlError::MediaUnavailable, + MediaControlError::UnknownPlayer, + MediaControlError::StaleHandle, + MediaControlError::ControlUnavailable, + MediaControlError::ControlFailed, + ] { + let rejected = Response::MediaControlRejected { + protocol_version: PROTOCOL_VERSION, + request_id: 72, + player_handle: "player:opaque-1".to_owned(), + code, + }; + let json = serde_json::to_string(&rejected).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), rejected); + } + } + + #[test] + fn media_snapshot_validation_detects_bounds_and_stale_sequences() { + let mut snapshot = test_media_snapshot(); + assert!(snapshot.validate().is_ok()); + assert!(snapshot.is_newer_than(8)); + assert!(!snapshot.is_newer_than(9)); + + snapshot.active_player_handle = Some("player:missing".to_owned()); + assert_eq!( + snapshot.validate(), + Err(MediaSnapshotValidationError::UnknownActivePlayer) + ); + snapshot.active_player_handle = Some("player:opaque-1".to_owned()); + + snapshot.players.push(test_media_player("player:opaque-1")); + assert_eq!( + snapshot.validate(), + Err(MediaSnapshotValidationError::InvalidPlayerHandle) + ); + snapshot.players.pop(); + + snapshot.players[0].handle.clear(); + assert_eq!( + snapshot.validate(), + Err(MediaSnapshotValidationError::InvalidPlayerHandle) + ); + snapshot.players[0].handle = "player:opaque-1".to_owned(); + + snapshot.players[0].title = Some("t".repeat(MAX_STRING_BYTES + 1)); + assert_eq!( + snapshot.validate(), + Err(MediaSnapshotValidationError::StringTooLong) + ); + } + + #[test] + fn media_snapshot_rejects_too_many_players() { + let mut snapshot = test_media_snapshot(); + snapshot.players = (0..=MAX_MEDIA_PLAYERS) + .map(|index| test_media_player(&format!("player:{index}"))) + .collect(); + assert_eq!( + snapshot.validate(), + Err(MediaSnapshotValidationError::TooManyPlayers) + ); + } + + #[test] + fn notification_feed_validation_detects_bounds_and_stale_sequences() { + let mut feed = test_notification_feed(); + assert!(feed.validate().is_ok()); + assert!(feed.is_newer_than(4)); + assert!(!feed.is_newer_than(5)); + + feed.notifications + .push(test_notification("notification:opaque-1")); + assert_eq!( + feed.validate(), + Err(NotificationFeedValidationError::InvalidNotificationHandle) + ); + feed.notifications.pop(); + + feed.notifications[0].handle.clear(); + assert_eq!( + feed.validate(), + Err(NotificationFeedValidationError::InvalidNotificationHandle) + ); + feed.notifications[0].handle = "notification:opaque-1".to_owned(); + + feed.notifications[0].body = "b".repeat(MAX_STRING_BYTES + 1); + assert_eq!( + feed.validate(), + Err(NotificationFeedValidationError::StringTooLong) + ); + } + + #[test] + fn notification_feed_rejects_too_many_entries() { + let mut feed = test_notification_feed(); + feed.notifications = (0..=MAX_NOTIFICATIONS) + .map(|index| test_notification(&format!("notification:{index}"))) + .collect(); + assert_eq!( + feed.validate(), + Err(NotificationFeedValidationError::TooManyNotifications) + ); + } + + #[test] + fn full_media_snapshot_stays_under_the_transport_limit() { + let mut snapshot = test_media_snapshot(); + snapshot.players = (0..MAX_MEDIA_PLAYERS) + .map(|index| { + let handle = format!("player:{index}"); + MediaPlayer { + handle, + identity: format!("Player {index}"), + status: PlaybackStatus::Paused, + title: Some(format!("Title {index}")), + artist: Some(format!("Artist {index}")), + album: Some(format!("Album {index}")), + length_micros: Some(u64::MAX), + position_micros: u64::MAX, + can_play: false, + can_pause: false, + can_go_next: false, + can_go_previous: false, + can_seek: false, + can_control: false, + } + }) + .collect(); + snapshot.active_player_handle = Some("player:0".to_owned()); + + assert!(snapshot.validate().is_ok()); + let response = Response::MediaSnapshot { + protocol_version: PROTOCOL_VERSION, + request_id: 81, + snapshot, + }; + let json = serde_json::to_string(&response).unwrap(); + assert!(json.len() <= MAX_MESSAGE_BYTES); + } + + #[test] + fn protocol_v5_bounds_are_aligned() { + assert_eq!(PROTOCOL_VERSION, 5); + assert_eq!(MAX_MEDIA_PLAYERS, 16); + assert_eq!(MAX_NOTIFICATIONS, 32); + assert_eq!(MAX_STRING_BYTES, 256); + assert_eq!(MAX_MEDIA_PAYLOAD_BYTES, 4 * 1024); + assert_eq!(MAX_NOTIFICATION_PAYLOAD_BYTES, 4 * 1024); + } } diff --git a/frontend/godot/scenes/main.tscn b/frontend/godot/scenes/main.tscn index f198726..dd4bc74 100644 --- a/frontend/godot/scenes/main.tscn +++ b/frontend/godot/scenes/main.tscn @@ -1,4 +1,4 @@ -[gd_scene load_steps=11 format=3] +[gd_scene load_steps=13 format=3] [ext_resource type="Script" path="res://scripts/main.gd" id="1_main"] [ext_resource type="Script" path="res://scripts/backend_client.gd" id="2_backend"] @@ -7,6 +7,8 @@ [ext_resource type="Script" path="res://scripts/player.gd" id="5_player"] [ext_resource type="Script" path="res://ui/hud.gd" id="6_hud"] [ext_resource type="Script" path="res://ui/workspace_map.gd" id="7_workspace_map"] +[ext_resource type="Script" path="res://ui/notification_feed.gd" id="8_notification_feed"] +[ext_resource type="Script" path="res://ui/media_console.gd" id="9_media_console"] [sub_resource type="RectangleShape2D" id="Shape_player"] size = Vector2(10, 8) @@ -282,3 +284,13 @@ text_overrun_behavior = 3 layer = 2 visible = false script = ExtResource("7_workspace_map") + +[node name="NotificationFeed" type="CanvasLayer" parent="."] +layer = 3 +visible = false +script = ExtResource("8_notification_feed") + +[node name="MediaConsole" type="CanvasLayer" parent="."] +layer = 4 +visible = false +script = ExtResource("9_media_console") diff --git a/frontend/godot/scripts/backend_client.gd b/frontend/godot/scripts/backend_client.gd index fe9952b..aca60ce 100644 --- a/frontend/godot/scripts/backend_client.gd +++ b/frontend/godot/scripts/backend_client.gd @@ -18,6 +18,12 @@ signal focus_accepted(window_handle: String) signal focus_rejected(window_handle: String, code: String, message: String, retryable: bool) signal telemetry_snapshot_changed(snapshot: Dictionary) signal telemetry_availability_changed(availability: String) +signal media_snapshot_changed(snapshot: Dictionary) +signal media_availability_changed(availability: String) +signal media_control_accepted(player_handle: String, verb: String) +signal media_control_rejected(player_handle: String, verb: String, code: String, message: String, retryable: bool) +signal notification_feed_changed(feed: Dictionary) +signal notifications_availability_changed(availability: String) enum ConnectionState { DISCONNECTED, @@ -28,7 +34,9 @@ enum ConnectionState { INCOMPATIBLE, } -const PROTOCOL_VERSION := 4 +# Phase 5 bumps the exact-match contract to v5 for the typed media and +# notification families. Core, the bridge, and this client move together. +const PROTOCOL_VERSION := 5 const CLIENT_NAME := "velora-godot" const CLIENT_VERSION := "0.2.0" const PING_INTERVAL_SECONDS := 5.0 @@ -41,6 +49,16 @@ const MAX_SESSION_WINDOWS := 1024 const SWITCH_TIMEOUT_SECONDS := 5.0 const FOCUS_TIMEOUT_SECONDS := 5.0 const TELEMETRY_POLL_SECONDS := 1.0 +const MAX_MEDIA_PLAYERS := 16 +const MAX_NOTIFICATIONS := 32 +const MAX_STRING_BYTES := 256 +const MEDIA_CONTROL_TIMEOUT_SECONDS := 5.0 +const PLAYBACK_STATUSES := ["playing", "paused", "stopped"] +const NOTIFICATION_URGENCIES := ["low", "normal", "critical"] +# The only control verbs this client may send. Core re-maps each verb onto the +# matching MPRIS method for the opaque player handle; bus names, method names, +# raw arguments, and shell commands never cross Velora IPC. +const MEDIA_CONTROL_VERBS := ["play", "pause", "play_pause", "stop", "next", "previous"] @export var auto_connect := true @@ -60,6 +78,13 @@ var session_snapshot: Dictionary = {} var session_availability := "unknown" var telemetry_snapshot: Dictionary = {} var telemetry_availability := "unknown" +# Last good media and notification state is intentionally kept across +# reconnects so the UI keeps showing stale-but-labelled data instead of going +# blank; monotonic sequence fencing drops anything older once Core answers. +var media_snapshot: Dictionary = {} +var media_availability := "unknown" +var notification_feed: Dictionary = {} +var notifications_availability := "unknown" var _bridge: Node var _socket_path := "" @@ -86,6 +111,12 @@ var _focus_handle := "" var _focus_elapsed := 0.0 var _telemetry_request_id := 0 var _telemetry_elapsed := 0.0 +var _media_request_id := 0 +var _notifications_request_id := 0 +var _media_control_request_id := 0 +var _media_control_handle := "" +var _media_control_verb := "" +var _media_control_elapsed := 0.0 func _ready() -> void: _bridge = bridge_override @@ -137,6 +168,8 @@ func disconnect_from_core() -> void: _pending_applications.clear() _application_request_id = 0 _session_request_id = 0 + _media_request_id = 0 + _notifications_request_id = 0 if _focus_request_id != 0: var pending_focus := _focus_handle _clear_focus_request() @@ -145,6 +178,7 @@ func disconnect_from_core() -> void: var pending_handle := _switch_handle _clear_switch_request() _emit_switch_rejection(pending_handle, "connection_lost", "CONNECTION LOST // RETRY", true) + _fail_pending_media_control("connection_lost") _fail_pending_launch("connection_lost", true) _set_state(ConnectionState.DISCONNECTED, "CORE // DISCONNECTED") @@ -203,6 +237,28 @@ func request_telemetry_snapshot() -> bool: "request_id": request_id, }) +func request_media_snapshot() -> bool: + if state != ConnectionState.READY or _media_request_id != 0: + return false + var request_id := _take_request_id() + _media_request_id = request_id + return _send_message({ + "type": "get_media_snapshot", + "protocol_version": PROTOCOL_VERSION, + "request_id": request_id, + }) + +func request_notifications() -> bool: + if state != ConnectionState.READY or _notifications_request_id != 0: + return false + var request_id := _take_request_id() + _notifications_request_id = request_id + return _send_message({ + "type": "get_notifications", + "protocol_version": PROTOCOL_VERSION, + "request_id": request_id, + }) + func _update_telemetry_poll(delta: float) -> void: _telemetry_elapsed += delta if _telemetry_elapsed >= TELEMETRY_POLL_SECONDS: @@ -266,6 +322,40 @@ func request_focus_window(window_handle: String) -> bool: return false return true +# Sends one of the six allowlisted control verbs for an opaque player handle +# issued by a media snapshot. Bus names, method names, raw arguments, and +# shell commands are not part of the request surface and are never forwarded. +func send_media_control(player_handle: String, verb: String) -> bool: + if state != ConnectionState.READY: + _reject_media_control(player_handle, verb, "core_offline") + return false + if player_handle.is_empty(): + _reject_media_control(player_handle, verb, "invalid_player_handle") + return false + if not MEDIA_CONTROL_VERBS.has(verb): + _reject_media_control(player_handle, verb, "invalid_verb") + return false + if _media_control_request_id != 0: + _reject_media_control(player_handle, verb, "media_busy") + return false + var request_id := _take_request_id() + _media_control_request_id = request_id + _media_control_handle = player_handle + _media_control_verb = verb + _media_control_elapsed = 0.0 + var sent := _send_message({ + "type": "send_media_control", + "protocol_version": PROTOCOL_VERSION, + "request_id": request_id, + "player_handle": player_handle, + "verb": verb, + }) + if not sent: + _clear_media_control_request() + _reject_media_control(player_handle, verb, "send_failed") + return false + return true + func launch_app(desktop_id: String) -> bool: last_requested_desktop_id = desktop_id if state != ConnectionState.READY: @@ -301,8 +391,11 @@ func _attempt_connect() -> void: _waiting_for_pong = false _application_request_id = 0 _session_request_id = 0 + _media_request_id = 0 + _notifications_request_id = 0 _clear_focus_request() _clear_switch_request() + _clear_media_control_request() _set_state(ConnectionState.CONNECTING, "CORE // CONNECTING") _bridge.connect_socket(_socket_path) @@ -321,6 +414,8 @@ func _on_socket_disconnected(_reason: String) -> void: _waiting_for_pong = false _application_request_id = 0 _session_request_id = 0 + _media_request_id = 0 + _notifications_request_id = 0 if _focus_request_id != 0: var pending_focus := _focus_handle _clear_focus_request() @@ -329,6 +424,7 @@ func _on_socket_disconnected(_reason: String) -> void: var pending_handle := _switch_handle _clear_switch_request() _emit_switch_rejection(pending_handle, "connection_lost", "CONNECTION LOST // RETRY", true) + _fail_pending_media_control("connection_lost") _fail_pending_launch("connection_lost", true) if state != ConnectionState.INCOMPATIBLE and state != ConnectionState.DISCONNECTED: _schedule_reconnect() @@ -359,6 +455,11 @@ func _on_line_received(payload: String) -> void: request_applications() request_hyprland_capabilities() request_telemetry_snapshot() + # One media/notification fetch per connection: refreshes + # stale-but-labelled state after a reconnect without ever + # becoming a polling loop. Later refreshes are scene-driven. + request_media_snapshot() + request_notifications() if session_snapshot.is_empty(): # Only the first fetch is client-driven; later refreshes are # Core's event-driven snapshots arriving unprompted or a @@ -382,6 +483,18 @@ func _on_line_received(payload: String) -> void: _on_telemetry_snapshot(message) "telemetry_snapshot_rejected": _on_telemetry_snapshot_rejected(message) + "media_snapshot": + _on_media_snapshot(message) + "media_snapshot_rejected": + _on_media_snapshot_rejected(message) + "notifications": + _on_notifications(message) + "notifications_rejected": + _on_notifications_rejected(message) + "media_control_accepted": + _on_media_control_accepted(message) + "media_control_rejected": + _on_media_control_rejected(message) "switch_accepted": var request_id := int(message.get("request_id", 0)) if request_id != _switch_request_id: @@ -469,6 +582,10 @@ func _update_launch_timeout(delta: float) -> void: var focused := _focus_handle _clear_focus_request() _emit_focus_rejection(focused, "focus_timeout", "FOCUS TIMED OUT // RETRY", true) + if _media_control_request_id != 0: + _media_control_elapsed += delta + if _media_control_elapsed >= MEDIA_CONTROL_TIMEOUT_SECONDS: + _fail_pending_media_control("media_control_timeout") func _clear_switch_request() -> void: _switch_request_id = 0 @@ -538,6 +655,85 @@ func _emit_switch_rejection( switch_rejected.emit(workspace_handle, code, message, retryable) _emit_ux_status("switch_failed", message, "failure", 3.0 if retryable else -1.0) +func _clear_media_control_request() -> void: + _media_control_request_id = 0 + _media_control_handle = "" + _media_control_verb = "" + _media_control_elapsed = 0.0 + +func _on_media_control_accepted(message: Dictionary) -> void: + var request_id := int(message.get("request_id", 0)) + if request_id != _media_control_request_id: + return + var handle := String(message.get("player_handle", "")) + if handle != _media_control_handle or handle.is_empty(): + _fail_pending_media_control("invalid_media_response") + return + var verb := _media_control_verb + _clear_media_control_request() + media_control_accepted.emit(handle, verb) + +func _on_media_control_rejected(message: Dictionary) -> void: + var request_id := int(message.get("request_id", 0)) + if request_id != _media_control_request_id: + connection_changed.emit("CORE // STALE MEDIA CONTROL REJECTION") + return + var handle := String(message.get("player_handle", "")) + if handle != _media_control_handle: + _fail_pending_media_control("invalid_media_response") + return + var code := String(message.get("code", "control_failed")) + var verb := _media_control_verb + _clear_media_control_request() + if code == "media_unavailable": + _set_media_availability("unavailable") + _reject_media_control(handle, verb, code) + +func _fail_pending_media_control(code: String) -> void: + if _media_control_request_id == 0: + return + var handle := _media_control_handle + var verb := _media_control_verb + _clear_media_control_request() + _reject_media_control(handle, verb, code) + +func _reject_media_control(player_handle: String, verb: String, code: String) -> void: + var details := _media_control_error_details(code) + media_control_rejected.emit(player_handle, verb, code, details["message"], details["retryable"]) + _emit_ux_status( + "media_control_failed", + details["message"], + "failure", + 3.0 if details["retryable"] else -1.0 + ) + +func _media_control_error_details(code: String) -> Dictionary: + match code: + "media_unavailable": + return {"message": "MEDIA PLAYBACK UNAVAILABLE", "retryable": false} + "unknown_player": + return {"message": "PLAYER NO LONGER EXISTS", "retryable": false} + "stale_handle": + return {"message": "PLAYER STALE // REFRESH LIST", "retryable": false} + "control_unavailable": + return {"message": "CONTROL NOT AVAILABLE", "retryable": false} + "core_offline": + return {"message": "MEDIA CONTROL OFFLINE", "retryable": true} + "connection_lost": + return {"message": "CONNECTION LOST // RETRY", "retryable": true} + "send_failed": + return {"message": "REQUEST FAILED // RETRY", "retryable": true} + "media_control_timeout": + return {"message": "CONTROL TIMED OUT // RETRY", "retryable": true} + "media_busy": + return {"message": "MEDIA CONTROL ALREADY IN PROGRESS", "retryable": true} + "invalid_player_handle", "invalid_verb": + return {"message": "INVALID MEDIA CONTROL", "retryable": false} + "invalid_media_response": + return {"message": "INVALID MEDIA RESPONSE", "retryable": true} + _: + return {"message": "MEDIA CONTROL FAILED // RETRY", "retryable": true} + func _schedule_reconnect() -> void: if state == ConnectionState.RECONNECTING: return @@ -692,6 +888,89 @@ func _set_telemetry_availability(availability: String) -> void: telemetry_availability = availability telemetry_availability_changed.emit(availability) +func _on_media_snapshot(message: Dictionary) -> void: + if state != ConnectionState.READY: + return + var request_id := int(message.get("request_id", 0)) + if request_id != 0: + if _media_request_id == 0 or request_id != _media_request_id: + connection_changed.emit("CORE // STALE MEDIA SNAPSHOT") + return + _media_request_id = 0 + var snapshot := _normalize_media_snapshot(message.get("snapshot", null)) + if snapshot.is_empty(): + _emit_ux_status("media_failed", "INVALID MEDIA DATA", "failure", 3.0) + return + var sequence := int(snapshot.get("sequence", 0)) + if sequence <= int(media_snapshot.get("sequence", 0)): + return + media_snapshot = snapshot + _set_media_availability("available") + media_snapshot_changed.emit(snapshot) + +func _on_media_snapshot_rejected(message: Dictionary) -> void: + # Rejections are strictly request-scoped, like telemetry: without a + # pending request with a matching ID the frame is fenced so a stale or + # unsolicited rejection can never mutate availability. + if int(message.get("request_id", 0)) != _media_request_id: + return + _media_request_id = 0 + match String(message.get("code", "")): + "media_unavailable": + _set_media_availability("unavailable") + "snapshot_not_ready": + _set_media_availability("waiting") + _: + pass + +func _on_notifications(message: Dictionary) -> void: + if state != ConnectionState.READY: + return + var request_id := int(message.get("request_id", 0)) + if request_id != 0: + if _notifications_request_id == 0 or request_id != _notifications_request_id: + connection_changed.emit("CORE // STALE NOTIFICATION FEED") + return + _notifications_request_id = 0 + var feed := _normalize_notification_feed(message.get("feed", null)) + if feed.is_empty(): + _emit_ux_status("notifications_failed", "INVALID NOTIFICATION DATA", "failure", 3.0) + return + var sequence := int(feed.get("sequence", 0)) + if sequence <= int(notification_feed.get("sequence", 0)): + return + notification_feed = feed + _set_notifications_availability("available") + notification_feed_changed.emit(feed) + +func _on_notifications_rejected(message: Dictionary) -> void: + # Strict request correlation, like telemetry: a stale or unsolicited + # rejection never mutates notifications availability. + if int(message.get("request_id", 0)) != _notifications_request_id: + return + _notifications_request_id = 0 + match String(message.get("code", "")): + "notifications_unavailable": + _set_notifications_availability("unavailable") + "monitor_restricted": + _set_notifications_availability("restricted") + "feed_not_ready": + _set_notifications_availability("waiting") + _: + pass + +func _set_media_availability(availability: String) -> void: + if media_availability == availability: + return + media_availability = availability + media_availability_changed.emit(availability) + +func _set_notifications_availability(availability: String) -> void: + if notifications_availability == availability: + return + notifications_availability = availability + notifications_availability_changed.emit(availability) + func _set_session_availability(availability: String) -> void: if availability == session_availability: return @@ -818,6 +1097,165 @@ func _normalize_window(value: Variant) -> Dictionary: "is_fullscreen": is_fullscreen_value, } +func _normalize_media_snapshot(value: Variant) -> Dictionary: + if not value is Dictionary: + return {} + var sequence_value = value.get("sequence", null) + if not sequence_value is float and not sequence_value is int: + return {} + if sequence_value < 0: + return {} + var raw_players = value.get("players", null) + if not raw_players is Array: + return {} + if raw_players.size() > MAX_MEDIA_PLAYERS: + return {} + + var players: Array[Dictionary] = [] + var player_handles := {} + for raw_player in raw_players: + var player := _normalize_media_player(raw_player) + if player.is_empty() or player_handles.has(player.get("handle")): + return {} + player_handles[player.get("handle")] = true + players.append(player) + + var active_handle := "" + var active_value = value.get("active_player_handle", null) + if active_value != null: + if not active_value is String or not player_handles.has(active_value): + return {} + active_handle = String(active_value) + + return { + "sequence": int(sequence_value), + "players": players, + "active_player_handle": active_handle, + } + +func _normalize_media_player(value: Variant) -> Dictionary: + if not value is Dictionary: + return {} + var handle_value = value.get("handle", null) + if not handle_value is String or String(handle_value).is_empty(): + return {} + var identity_value = value.get("identity", null) + if not identity_value is String: + return {} + var status := String(value.get("status", "")) + if not PLAYBACK_STATUSES.has(status): + return {} + var title_value = value.get("title", null) + var artist_value = value.get("artist", null) + var album_value = value.get("album", null) + for optional_string in [title_value, artist_value, album_value]: + if optional_string != null and not optional_string is String: + return {} + var length_value = value.get("length_micros", null) + if length_value != null and not length_value is float and not length_value is int: + return {} + if length_value != null and length_value < 0: + return {} + var position_value = value.get("position_micros", null) + if not position_value is float and not position_value is int: + return {} + if position_value < 0: + return {} + for capability in [ + "can_play", "can_pause", "can_go_next", "can_go_previous", "can_seek", "can_control" + ]: + if not value.get(capability, null) is bool: + return {} + if _string_exceeds_budget(identity_value, MAX_STRING_BYTES): + return {} + for bounded_string in [title_value, artist_value, album_value]: + if bounded_string != null and _string_exceeds_budget(bounded_string, MAX_STRING_BYTES): + return {} + # Optional metadata is flattened with sentinels: absent strings become "" + # and an unknown track length becomes -1, matching the session snapshot + # convention of never carrying null across the normalized boundary. + return { + "handle": String(handle_value), + "identity": String(identity_value), + "status": status, + "title": "" if title_value == null else String(title_value), + "artist": "" if artist_value == null else String(artist_value), + "album": "" if album_value == null else String(album_value), + "length_micros": -1 if length_value == null else int(length_value), + "position_micros": int(position_value), + "can_play": value.get("can_play"), + "can_pause": value.get("can_pause"), + "can_go_next": value.get("can_go_next"), + "can_go_previous": value.get("can_go_previous"), + "can_seek": value.get("can_seek"), + "can_control": value.get("can_control"), + } + +func _normalize_notification_feed(value: Variant) -> Dictionary: + if not value is Dictionary: + return {} + var sequence_value = value.get("sequence", null) + if not sequence_value is float and not sequence_value is int: + return {} + if sequence_value < 0: + return {} + var raw_notifications = value.get("notifications", null) + if not raw_notifications is Array: + return {} + if raw_notifications.size() > MAX_NOTIFICATIONS: + return {} + + var notifications: Array[Dictionary] = [] + var notification_handles := {} + for raw_notification in raw_notifications: + var notification := _normalize_notification(raw_notification) + if notification.is_empty() or notification_handles.has(notification.get("handle")): + return {} + notification_handles[notification.get("handle")] = true + notifications.append(notification) + + return { + "sequence": int(sequence_value), + "notifications": notifications, + } + +func _normalize_notification(value: Variant) -> Dictionary: + if not value is Dictionary: + return {} + var handle_value = value.get("handle", null) + if not handle_value is String or String(handle_value).is_empty(): + return {} + var app_name_value = value.get("app_name", null) + var summary_value = value.get("summary", null) + var body_value = value.get("body", null) + for required_string in [app_name_value, summary_value, body_value]: + if not required_string is String: + return {} + var urgency := String(value.get("urgency", "")) + if not NOTIFICATION_URGENCIES.has(urgency): + return {} + var timestamp_value = value.get("timestamp_unix_ms", null) + if not timestamp_value is float and not timestamp_value is int: + return {} + if timestamp_value < 0: + return {} + for bounded_string in [app_name_value, summary_value, body_value]: + if _string_exceeds_budget(bounded_string, MAX_STRING_BYTES): + return {} + return { + "handle": String(handle_value), + "app_name": String(app_name_value), + "summary": String(summary_value), + "body": String(body_value), + "urgency": urgency, + "timestamp_unix_ms": int(timestamp_value), + } + +func _string_exceeds_budget(value: String, budget: int) -> bool: + # The protocol bounds UTF-8 bytes, not code points, so measure bytes the + # same way Core does. + return value.to_utf8_buffer().size() > budget + func _on_launch_rejected(message: Dictionary) -> void: var request_id := int(message.get("request_id", 0)) if request_id != _launch_request_id: diff --git a/frontend/godot/scripts/main.gd b/frontend/godot/scripts/main.gd index 592b030..b93d033 100644 --- a/frontend/godot/scripts/main.gd +++ b/frontend/godot/scripts/main.gd @@ -6,9 +6,13 @@ const SessionBinding = preload("res://scripts/session_binding.gd") @onready var backend: Node = $BackendClient @onready var hud: CanvasLayer = $HUD @onready var workspace_map: CanvasLayer = $WorkspaceMap +@onready var notification_feed: CanvasLayer = $NotificationFeed +@onready var media_console: CanvasLayer = $MediaConsole var menu_open := false var map_open := false +var feed_open := false +var media_open := false var _stations: Array[Node] = [] func _ready() -> void: @@ -25,6 +29,21 @@ func _ready() -> void: backend.session_availability_changed.connect(_on_session_availability_changed) backend.telemetry_snapshot_changed.connect(hud.set_telemetry_snapshot) backend.telemetry_availability_changed.connect(hud.set_telemetry_availability) + backend.notification_feed_changed.connect(notification_feed.update_feed) + backend.notifications_availability_changed.connect(notification_feed.set_availability) + notification_feed.feed_closed.connect(_on_feed_closed) + notification_feed.set_availability(backend.notifications_availability) + if not backend.notification_feed.is_empty(): + notification_feed.update_feed(backend.notification_feed) + backend.media_snapshot_changed.connect(media_console.update_media) + backend.media_availability_changed.connect(media_console.set_availability) + backend.media_control_accepted.connect(media_console.apply_control_accepted) + backend.media_control_rejected.connect(media_console.apply_control_rejected) + media_console.control_requested.connect(backend.send_media_control) + media_console.console_closed.connect(_on_media_console_closed) + media_console.set_availability(backend.media_availability) + if not backend.media_snapshot.is_empty(): + media_console.update_media(backend.media_snapshot) workspace_map.map_closed.connect(_on_map_closed) workspace_map.switch_requested.connect(backend.request_switch_workspace) if backend.session_availability != "unknown": @@ -34,11 +53,19 @@ func _ready() -> void: hud.set_status("VELORA // POCKET TERMINAL") func _unhandled_input(event: InputEvent) -> void: - if menu_open or map_open or not event is InputEventKey: + if menu_open or map_open or feed_open or media_open or not event is InputEventKey: return - if event.pressed and not event.echo and event.keycode in [KEY_TAB, KEY_M]: + if not event.pressed or event.echo: + return + if event.keycode in [KEY_TAB, KEY_M]: get_viewport().set_input_as_handled() _toggle_workspace_map() + elif event.keycode == KEY_N: + get_viewport().set_input_as_handled() + _toggle_notification_feed() + elif event.keycode == KEY_P: + get_viewport().set_input_as_handled() + _toggle_media_console() func _toggle_workspace_map() -> void: map_open = true @@ -49,6 +76,30 @@ func _on_map_closed() -> void: map_open = false player.set_input_enabled(true) +func _toggle_notification_feed() -> void: + feed_open = true + player.set_input_enabled(false) + # Scene-driven refresh: the client fetches once per connection, so the + # panel asks for a fresh single-flight feed whenever it is inspected. + backend.request_notifications() + notification_feed.open() + +func _on_feed_closed() -> void: + feed_open = false + player.set_input_enabled(true) + +func _toggle_media_console() -> void: + media_open = true + player.set_input_enabled(false) + # Scene-driven refresh: the client fetches once per connection, so the + # console asks for a fresh single-flight snapshot whenever it is opened. + backend.request_media_snapshot() + media_console.open() + +func _on_media_console_closed() -> void: + media_open = false + player.set_input_enabled(true) + func _on_session_snapshot_changed(snapshot: Dictionary) -> void: workspace_map.update_session(snapshot) _refresh_station_running_states(snapshot) diff --git a/frontend/godot/tests/backend_client_validation.gd b/frontend/godot/tests/backend_client_validation.gd index 092da05..02c511a 100644 --- a/frontend/godot/tests/backend_client_validation.gd +++ b/frontend/godot/tests/backend_client_validation.gd @@ -52,6 +52,13 @@ func _message_at(bridge: FakeBridge, index: int) -> Dictionary: var value = JSON.parse_string(bridge.sent_lines[index]) return value if value is Dictionary else {} +func _last_request_of_type(bridge: FakeBridge, request_type: String) -> Dictionary: + for index in range(bridge.sent_lines.size() - 1, -1, -1): + var candidate := _message_at(bridge, index) + if candidate.get("type") == request_type: + return candidate + return {} + func _run() -> void: var bridge := FakeBridge.new() var backend := BackendClient.new() @@ -198,11 +205,10 @@ func _run() -> void: "server_name": "velora-core-test", "server_version": "0.2.0", })) - var capability_request := _message_at(bridge, bridge.sent_lines.size() - 2) - var snapshot_request := _message_at(bridge, bridge.sent_lines.size() - 1) + var capability_request := _last_request_of_type(bridge, "get_hyprland_capabilities") + var snapshot_request := _last_request_of_type(bridge, "get_workspace_snapshot") _check( - capability_request.get("type") == "get_hyprland_capabilities" - and snapshot_request.get("type") == "get_workspace_snapshot", + not capability_request.is_empty() and not snapshot_request.is_empty(), "P3.06 ready state requests Hyprland capabilities and a session snapshot" ) @@ -445,6 +451,568 @@ func _run() -> void: "P3.10 reconnect resets pending focus state for new requests" ) + # --- P5.02 typed media and notification protocol v5 --- + _check( + BackendClient.PROTOCOL_VERSION == 5, + "P5.02 client locks to the v5 exact-match protocol" + ) + var media_request := _last_request_of_type(bridge, "get_media_snapshot") + var notifications_request := _last_request_of_type(bridge, "get_notifications") + _check( + media_request.get("protocol_version") == 5 + and notifications_request.get("protocol_version") == 5, + "P5.02 welcome requests typed v5 media and notification snapshots" + ) + _check( + not backend.request_media_snapshot() and not backend.request_notifications(), + "P5.02 snapshot requests stay single-flight while a response is pending" + ) + + var media_availability_emissions := [0] + var last_media_availability := [""] + backend.media_availability_changed.connect(func(availability: String) -> void: + media_availability_emissions[0] += 1 + last_media_availability[0] = availability + ) + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": media_request.get("request_id"), + "code": "media_unavailable", + "retryable": false, + })) + _check( + backend.media_availability == "unavailable" and media_availability_emissions[0] == 1, + "P5.02 the typed media-unavailable path reports availability once" + ) + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 424242, + "code": "media_unavailable", + "retryable": false, + })) + _check( + media_availability_emissions[0] == 1, + "P5.02 repeated media unavailability stays silent without log spam" + ) + + _check(backend.request_media_snapshot(), "P5.02 media snapshots can be requested on demand") + var waiting_request := _message_at(bridge, bridge.sent_lines.size() - 1) + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 999999, + "code": "snapshot_not_ready", + "retryable": true, + })) + _check( + backend._media_request_id != 0 and backend.media_availability == "unavailable", + "P5.02 stale rejections are fenced while a correlated request is pending" + ) + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": waiting_request.get("request_id"), + "code": "snapshot_not_ready", + "retryable": true, + })) + _check( + backend.media_availability == "waiting" and media_availability_emissions[0] == 2, + "P5.02 snapshot-not-ready maps to a waiting availability" + ) + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 424243, + "code": "media_unavailable", + "retryable": false, + })) + _check( + backend.media_availability == "waiting" and media_availability_emissions[0] == 2, + "P5.02 uncorrelated media rejections never mutate availability" + ) + + _check(backend.request_media_snapshot(), "P5.02 media snapshot request can be re-issued") + var media_snapshot_request := _message_at(bridge, bridge.sent_lines.size() - 1) + var media_emissions := [0] + backend.media_snapshot_changed.connect(func(_snapshot: Dictionary) -> void: + media_emissions[0] += 1 + ) + var media_player := { + "handle": "player:opaque-1", + "identity": "Velora Test Player", + "status": "playing", + "title": "Velora Theme", + "artist": "Velora", + "album": null, + "length_micros": 250000000, + "position_micros": 12500000, + "can_play": true, + "can_pause": true, + "can_go_next": true, + "can_go_previous": false, + "can_seek": false, + "can_control": true, + } + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": media_snapshot_request.get("request_id"), + "snapshot": { + "sequence": 3, + "players": [media_player], + "active_player_handle": "player:opaque-1", + }, + })) + _check( + backend.media_snapshot.get("sequence") == 3 and media_emissions[0] == 1, + "P5.02 valid media snapshots are normalized, stored, and signalled" + ) + _check( + backend._media_request_id == 0, + "P5.02 fulfilled media requests clear their correlation ID" + ) + _check( + backend.media_availability == "available" and media_availability_emissions[0] == 3, + "P5.02 a served snapshot restores the typed media availability" + ) + _check( + String(backend.media_snapshot["players"][0].get("status")) == "playing" + and bool(backend.media_snapshot["players"][0].get("can_go_previous")) == false + and String(backend.media_snapshot["players"][0].get("album")) == "", + "P5.02 player records preserve status, flags, and absent metadata" + ) + + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 0, + "snapshot": { + "sequence": 3, + "players": [media_player], + "active_player_handle": "player:opaque-1", + }, + })) + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 0, + "snapshot": { + "sequence": 2, + "players": [], + "active_player_handle": null, + }, + })) + _check( + media_emissions[0] == 1 and int(backend.media_snapshot.get("sequence", 0)) == 3, + "P5.02 equal or older media sequences are ignored as fencing tokens" + ) + + var second_media_player = media_player.duplicate(true) + second_media_player["handle"] = "player:opaque-2" + second_media_player["identity"] = "Second Player" + second_media_player["status"] = "paused" + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 0, + "snapshot": { + "sequence": 4, + "players": [media_player, second_media_player], + "active_player_handle": "player:opaque-2", + }, + })) + _check( + media_emissions[0] == 2 + and backend.media_snapshot["players"].size() == 2 + and String(backend.media_snapshot.get("active_player_handle")) == "player:opaque-2", + "P5.02 newer unprompted media snapshots replace state without polling" + ) + + var media_player_missing_flag = media_player.duplicate(true) + media_player_missing_flag.erase("can_seek") + var too_many_players: Array = [] + for index in range(BackendClient.MAX_MEDIA_PLAYERS + 1): + var bounded_player = media_player.duplicate(true) + bounded_player["handle"] = "player:opaque-%d" % index + too_many_players.append(bounded_player) + var long_title_player = media_player.duplicate(true) + long_title_player["title"] = "t".repeat(BackendClient.MAX_STRING_BYTES + 1) + var malformed_media_snapshots := [ + {"sequence": 5, "players": [media_player], "active_player_handle": "player:missing"}, + {"sequence": 5, "players": [media_player, media_player], "active_player_handle": null}, + {"sequence": 5, "players": too_many_players, "active_player_handle": null}, + {"sequence": 5, "players": [media_player_missing_flag], "active_player_handle": null}, + {"sequence": 5, "players": [long_title_player], "active_player_handle": null}, + ] + for malformed_snapshot in malformed_media_snapshots: + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 0, + "snapshot": malformed_snapshot, + })) + _check( + last_ux_stage == "media_failed" and last_ux_message == "INVALID MEDIA DATA", + "P5.02 malformed media snapshots produce concise visible feedback" + ) + _check( + media_emissions[0] == 2 and int(backend.media_snapshot.get("sequence", 0)) == 4, + "P5.02 malformed media snapshots never replace last good state" + ) + + var notifications_availability_emissions := [0] + var last_notifications_availability := [""] + backend.notifications_availability_changed.connect(func(availability: String) -> void: + notifications_availability_emissions[0] += 1 + last_notifications_availability[0] = availability + ) + bridge.line_received.emit(JSON.stringify({ + "type": "notifications_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": notifications_request.get("request_id"), + "code": "notifications_unavailable", + "retryable": false, + })) + _check( + backend.notifications_availability == "unavailable" + and notifications_availability_emissions[0] == 1, + "P5.02 the typed notifications-unavailable path reports availability once" + ) + + _check(backend.request_notifications(), "P5.02 notification feed can be requested on demand") + var feed_request := _message_at(bridge, bridge.sent_lines.size() - 1) + bridge.line_received.emit(JSON.stringify({ + "type": "notifications_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": feed_request.get("request_id"), + "code": "monitor_restricted", + "retryable": true, + })) + _check( + backend.notifications_availability == "restricted" + and notifications_availability_emissions[0] == 2, + "P5.02 monitor-restricted notification paths surface a typed availability" + ) + + _check(backend.request_notifications(), "P5.02 notification feed can be requested again") + feed_request = _message_at(bridge, bridge.sent_lines.size() - 1) + var feed_emissions := [0] + backend.notification_feed_changed.connect(func(_feed: Dictionary) -> void: + feed_emissions[0] += 1 + ) + bridge.line_received.emit(JSON.stringify({ + "type": "notifications", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": feed_request.get("request_id"), + "feed": { + "sequence": 7, + "notifications": [ + { + "handle": "notification:opaque-1", + "app_name": "Velora", + "summary": "Build complete", + "body": "The release gate passed.", + "urgency": "normal", + "timestamp_unix_ms": 1777777777000, + }, + { + "handle": "notification:opaque-2", + "app_name": "Velora", + "summary": "Disk space low", + "body": "", + "urgency": "critical", + "timestamp_unix_ms": 1777777778000, + }, + ], + }, + })) + _check( + backend.notification_feed.get("sequence") == 7 and feed_emissions[0] == 1, + "P5.02 valid notification feeds are normalized, stored, and signalled" + ) + _check( + backend._notifications_request_id == 0 + and backend.notifications_availability == "available" + and notifications_availability_emissions[0] == 3, + "P5.02 a served feed clears its request and restores availability" + ) + bridge.line_received.emit(JSON.stringify({ + "type": "notifications_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 424243, + "code": "notifications_unavailable", + "retryable": false, + })) + _check( + backend.notifications_availability == "available" + and notifications_availability_emissions[0] == 3, + "P5.02 uncorrelated notification rejections never mutate availability" + ) + _check( + backend.notification_feed["notifications"].size() == 2 + and String(backend.notification_feed["notifications"][1].get("urgency")) == "critical", + "P5.02 notification records preserve urgency levels" + ) + + var duplicate_notification := { + "handle": "notification:opaque-1", + "app_name": "Velora", + "summary": "Duplicate", + "body": "", + "urgency": "low", + "timestamp_unix_ms": 1, + } + var bad_urgency_notification := { + "handle": "notification:opaque-3", + "app_name": "Velora", + "summary": "Bad urgency", + "body": "", + "urgency": "silent", + "timestamp_unix_ms": 1, + } + var too_many_notifications: Array = [] + for index in range(BackendClient.MAX_NOTIFICATIONS + 1): + too_many_notifications.append({ + "handle": "notification:opaque-%d" % (index + 10), + "app_name": "Velora", + "summary": "Flood", + "body": "", + "urgency": "low", + "timestamp_unix_ms": index, + }) + var long_summary_notification := { + "handle": "notification:opaque-long", + "app_name": "Velora", + "summary": "s".repeat(BackendClient.MAX_STRING_BYTES + 1), + "body": "", + "urgency": "low", + "timestamp_unix_ms": 1, + } + var malformed_feeds := [ + {"sequence": 8, "notifications": [bad_urgency_notification]}, + {"sequence": 8, "notifications": [duplicate_notification, duplicate_notification]}, + {"sequence": 8, "notifications": too_many_notifications}, + {"sequence": 8, "notifications": [long_summary_notification]}, + ] + for malformed_feed in malformed_feeds: + bridge.line_received.emit(JSON.stringify({ + "type": "notifications", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 0, + "feed": malformed_feed, + })) + bridge.line_received.emit(JSON.stringify({ + "type": "notifications", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 0, + "feed": {"sequence": 6, "notifications": []}, + })) + _check( + last_ux_stage == "notifications_failed" + and last_ux_message == "INVALID NOTIFICATION DATA", + "P5.02 malformed notification feeds produce concise visible feedback" + ) + _check( + feed_emissions[0] == 1 and int(backend.notification_feed.get("sequence", 0)) == 7, + "P5.02 malformed or stale feeds never replace last good state" + ) + + var media_control_accepts: Array = [] + var media_control_rejections: Array = [] + backend.media_control_accepted.connect(func(player_handle: String, verb: String) -> void: + media_control_accepts.append([player_handle, verb]) + ) + backend.media_control_rejected.connect( + func(player_handle: String, verb: String, code: String, _message: String, _retryable: bool) -> void: + media_control_rejections.append([player_handle, verb, code]) + ) + var sent_lines_before_control := bridge.sent_lines.size() + _check( + not backend.send_media_control("player:opaque-1", "open_uri"), + "P5.02 non-allowlisted verbs are rejected locally" + ) + _check( + not backend.send_media_control("", "play"), + "P5.02 empty player handles are rejected locally" + ) + _check( + bridge.sent_lines.size() == sent_lines_before_control + and media_control_rejections.size() == 2, + "P5.02 rejected verbs and handles never reach the wire" + ) + + _check( + backend.send_media_control("player:opaque-2", "play_pause"), + "P5.02 ready client accepts an allowlisted media control" + ) + var control_request := _message_at(bridge, bridge.sent_lines.size() - 1) + _check( + control_request.get("type") == "send_media_control" + and control_request.get("protocol_version") == 5 + and control_request.get("player_handle") == "player:opaque-2" + and control_request.get("verb") == "play_pause" + and control_request.keys().size() == 5, + "P5.02 control requests carry only the typed handle and verb boundary" + ) + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_accepted", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": 777777, + "player_handle": "player:opaque-2", + })) + _check( + backend._media_control_request_id != 0 and media_control_accepts.is_empty(), + "P5.02 uncorrelated control acceptance is fenced out" + ) + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_accepted", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": control_request.get("request_id"), + "player_handle": "player:opaque-2", + })) + _check( + media_control_accepts.size() == 1 + and media_control_accepts[0][0] == "player:opaque-2" + and media_control_accepts[0][1] == "play_pause" + and backend._media_control_request_id == 0, + "P5.02 correlated acceptance clears pending state and echoes the verb" + ) + + _check( + backend.send_media_control("player:opaque-1", "next"), + "P5.02 a second control can be requested" + ) + var stale_control := _message_at(bridge, bridge.sent_lines.size() - 1) + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": stale_control.get("request_id"), + "player_handle": "player:opaque-1", + "code": "stale_handle", + })) + _check( + media_control_rejections.size() == 3 + and media_control_rejections[2][2] == "stale_handle" + and last_ux_message == "PLAYER STALE // REFRESH LIST", + "P5.02 stale player handles fail with concise typed feedback" + ) + + _check( + backend.send_media_control("player:opaque-1", "play"), + "P5.02 a third control can be requested" + ) + backend._update_launch_timeout(BackendClient.MEDIA_CONTROL_TIMEOUT_SECONDS + 0.1) + _check( + backend._media_control_request_id == 0 + and media_control_rejections.size() == 4 + and media_control_rejections[3][2] == "media_control_timeout", + "P5.02 pending controls time out with retryable feedback" + ) + + _check( + backend.send_media_control("player:gone", "stop"), + "P5.02 control for an unknown player is sent" + ) + var unknown_control := _message_at(bridge, bridge.sent_lines.size() - 1) + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": unknown_control.get("request_id"), + "player_handle": "player:gone", + "code": "unknown_player", + })) + _check( + media_control_rejections.size() == 5 + and media_control_rejections[4][2] == "unknown_player" + and last_ux_message == "PLAYER NO LONGER EXISTS", + "P5.02 unknown players fail with typed non-retryable feedback" + ) + + _check( + backend.send_media_control("player:opaque-2", "pause"), + "P5.02 control can be re-issued" + ) + var unavailable_control := _message_at(bridge, bridge.sent_lines.size() - 1) + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": unavailable_control.get("request_id"), + "player_handle": "player:opaque-2", + "code": "control_unavailable", + })) + _check( + media_control_rejections.size() == 6 + and media_control_rejections[5][2] == "control_unavailable" + and backend.media_availability == "available", + "P5.02 control-unavailable is typed without flipping snapshot availability" + ) + + _check( + backend.send_media_control("player:opaque-2", "next"), + "P5.02 control while media is down can be requested" + ) + var media_down_control := _message_at(bridge, bridge.sent_lines.size() - 1) + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": media_down_control.get("request_id"), + "player_handle": "player:opaque-2", + "code": "media_unavailable", + })) + _check( + media_control_rejections.size() == 7 + and media_control_rejections[6][2] == "media_unavailable" + and backend.media_availability == "unavailable" + and media_availability_emissions[0] == 4, + "P5.02 a media-unavailable control failure updates the availability" + ) + + _check( + backend.send_media_control("player:opaque-2", "play"), + "P5.02 a pending control can be left open" + ) + bridge.socket_disconnected.emit("media test disconnect") + _check( + media_control_rejections.size() == 8 + and media_control_rejections[7][2] == "connection_lost", + "P5.02 disconnects fail pending controls as retryable connection loss" + ) + _check( + not backend.media_snapshot.is_empty() + and int(backend.media_snapshot.get("sequence", 0)) == 4 + and not backend.notification_feed.is_empty() + and int(backend.notification_feed.get("sequence", 0)) == 7, + "P5.02 reconnects preserve the last good media and notification state" + ) + + bridge.socket_connected.emit() + bridge.line_received.emit(JSON.stringify({ + "type": "welcome", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "server_name": "velora-core-test", + "server_version": "0.2.0", + })) + var refreshed_media_request := _last_request_of_type(bridge, "get_media_snapshot") + var refreshed_notifications_request := _last_request_of_type(bridge, "get_notifications") + _check( + int(refreshed_media_request.get("request_id", 0)) > int(media_request.get("request_id", 0)) + and int(refreshed_notifications_request.get("request_id", 0)) > int(notifications_request.get("request_id", 0)), + "P5.02 reconnect re-requests initial snapshots without adding polling" + ) + + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": 4, + "request_id": 0, + "snapshot": {"sequence": 99, "players": [], "active_player_handle": null}, + })) + _check( + backend.state == BackendClient.ConnectionState.INCOMPATIBLE, + "P5.02 the exact-match handshake rejects any non-v5 media frame" + ) + backend.queue_free() await process_frame if failures.is_empty(): diff --git a/frontend/godot/tests/media_client_validation.gd b/frontend/godot/tests/media_client_validation.gd new file mode 100644 index 0000000..fe6f46a --- /dev/null +++ b/frontend/godot/tests/media_client_validation.gd @@ -0,0 +1,515 @@ +extends SceneTree + +# P5.07 media client validation: the BackendClient media surface over a fake +# bridge, covering the typed v5 fetch, normalization with bounds and types, +# strict sequence fencing, last-good reconnect retention, de-duplicated +# availability transitions, and typed control results. Scene and console +# coverage lives in media_validation.gd; this file keeps no scene or UI +# dependencies. + +class FakeBridge: + extends Node + + signal socket_connected + signal socket_disconnected(reason: String) + signal line_received(payload: String) + signal transport_error(code: String, message: String) + + var sent_lines: Array[String] = [] + var connected_path := "" + var disconnected := false + + func default_socket_path() -> String: + return "/tmp/velora-fake.sock" + + func connect_socket(path: String) -> bool: + connected_path = path + return true + + func disconnect_socket() -> void: + disconnected = true + + func send_line(payload: String) -> bool: + sent_lines.append(payload) + return true + +var failures: Array[String] = [] +var last_ux_stage := "" +var last_ux_message := "" +var last_ux_tone := "" + +func _initialize() -> void: + call_deferred("_run") + +func _check(condition: bool, message: String) -> void: + if condition: + print("PASS: ", message) + else: + failures.append(message) + push_error("FAIL: " + message) + +func _on_ux_status(stage: String, message: String, tone: String, _seconds: float) -> void: + last_ux_stage = stage + last_ux_message = message + last_ux_tone = tone + +func _welcome() -> Dictionary: + return { + "type": "welcome", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "server_name": "velora-core-test", + "server_version": "0.2.0", + } + +func _player( + handle: String, + identity := "Velora Test Player", + status := "playing", + title := "Velora Theme", + artist := "Velora", + album: Variant = null, + length_micros: Variant = null, + position_micros := 12500000, + can_play := true, + can_pause := true, + can_go_next := true, + can_go_previous := true, + can_seek := false, + can_control := true +) -> Dictionary: + return { + "handle": handle, + "identity": identity, + "status": status, + "title": title, + "artist": artist, + "album": album, + "length_micros": length_micros, + "position_micros": position_micros, + "can_play": can_play, + "can_pause": can_pause, + "can_go_next": can_go_next, + "can_go_previous": can_go_previous, + "can_seek": can_seek, + "can_control": can_control, + } + +func _snapshot(sequence: int, players: Array, active: Variant = null) -> Dictionary: + return {"sequence": sequence, "players": players, "active_player_handle": active} + +func _emit_media(bridge: FakeBridge, request_id: Variant, snapshot: Variant) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "snapshot": snapshot, + })) + +func _emit_media_rejected( + bridge: FakeBridge, + request_id: Variant, + code: String, + retryable: bool +) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "code": code, + "retryable": retryable, + })) + +func _emit_control_accepted(bridge: FakeBridge, request_id: Variant, player_handle: String) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_accepted", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "player_handle": player_handle, + })) + +func _emit_control_rejected( + bridge: FakeBridge, + request_id: Variant, + player_handle: String, + code: String +) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "player_handle": player_handle, + "code": code, + })) + +func _message_at(bridge: FakeBridge, index: int) -> Dictionary: + if index < 0 or index >= bridge.sent_lines.size(): + return {} + var value = JSON.parse_string(bridge.sent_lines[index]) + return value if value is Dictionary else {} + +func _last_request_of_type(bridge: FakeBridge, request_type: String) -> Dictionary: + for index in range(bridge.sent_lines.size() - 1, -1, -1): + var candidate := _message_at(bridge, index) + if candidate.get("type") == request_type: + return candidate + return {} + +func _run() -> void: + await _run_client() + if failures.is_empty(): + print("P5.07 media client validation passed.") + quit(0) + else: + push_error("P5.07 media client validation failed: %s" % [failures]) + quit(1) + +func _run_client() -> void: + # --- typed client media surface over the fake bridge --- + var bridge := FakeBridge.new() + var backend := BackendClient.new() + backend.auto_connect = false + backend.bridge_override = bridge + backend.ux_status_changed.connect(_on_ux_status) + var snapshot_emissions := [0] + backend.media_snapshot_changed.connect(func(_snapshot: Dictionary) -> void: + snapshot_emissions[0] += 1 + ) + var availability_emissions := [0] + backend.media_availability_changed.connect(func(availability: String) -> void: + availability_emissions[0] += 1 + ) + var control_accepts: Array = [] + var control_rejections: Array = [] + backend.media_control_accepted.connect(func(player_handle: String, verb: String) -> void: + control_accepts.append([player_handle, verb]) + ) + backend.media_control_rejected.connect( + func(player_handle: String, verb: String, code: String, _message: String, _retryable: bool) -> void: + control_rejections.append([player_handle, verb, code]) + ) + root.add_child(backend) + await process_frame + + backend.connect_to_core() + bridge.socket_connected.emit() + bridge.line_received.emit(JSON.stringify(_welcome())) + var media_request := _last_request_of_type(bridge, "get_media_snapshot") + _check( + media_request.get("type") == "get_media_snapshot" + and media_request.get("protocol_version") == 5, + "P5.07 the client fetches the typed v5 media snapshot on connect" + ) + + # --- normalization: required fields stay typed, optional metadata flattens + var normalized_player := _player("player:opaque-1") + _emit_media(bridge, media_request.get("request_id"), _snapshot(7, [normalized_player], "player:opaque-1")) + var stored := backend.media_snapshot + _check( + backend._media_request_id == 0 + and snapshot_emissions[0] == 1 + and backend.media_availability == "available" + and availability_emissions[0] == 1, + "P5.07 a served snapshot normalizes, stores, and signals exactly once" + ) + _check( + int(stored.get("sequence", 0)) == 7 + and String(stored.get("active_player_handle", "")) == "player:opaque-1", + "P5.07 the snapshot carries its sequence and active player handle" + ) + var stored_player: Dictionary = stored.get("players", [])[0] + _check( + String(stored_player.get("handle", "")) == "player:opaque-1" + and String(stored_player.get("status", "")) == "playing" + and bool(stored_player.get("can_seek", true)) == false + and bool(stored_player.get("can_control", false)) == true, + "P5.07 required player fields keep their validated types and flags" + ) + _check( + String(stored_player.get("album", "unset")) == "" + and int(stored_player.get("length_micros", 0)) == -1 + and int(stored_player.get("position_micros", 0)) == 12500000, + "P5.07 absent metadata flattens to empty and -1 sentinels" + ) + + # --- bounds and types: malformed payloads never replace last-good state + var missing_flag := _player("player:opaque-3").duplicate(true) + missing_flag.erase("can_seek") + var missing_position := _player("player:opaque-11").duplicate(true) + missing_position.erase("position_micros") + var bad_identity := _player("player:opaque-7").duplicate(true) + bad_identity["identity"] = 5 + var bad_length := _player("player:opaque-12", "Bad Length") + bad_length["length_micros"] = "long" + var too_many_players: Array = [] + for index in range(BackendClient.MAX_MEDIA_PLAYERS + 1): + var bounded_player := _player("player:opaque-%d" % index) + too_many_players.append(bounded_player) + var malformed_snapshots := [ + _snapshot(8, [_player("player:opaque-2", "Bad Status", "buffering")], null), + _snapshot(8, [missing_flag], null), + _snapshot(8, [_player("player:opaque-4", "Long Title", "playing", "t".repeat(BackendClient.MAX_STRING_BYTES + 1))], null), + _snapshot(8, [_player("")], null), + _snapshot(8, [normalized_player, normalized_player], null), + _snapshot(8, too_many_players, null), + _snapshot(8, [_player("player:opaque-5")], "player:missing"), + _snapshot(8, [_player("player:opaque-13")], 5), + {"sequence": 8, "players": "not-an-array", "active_player_handle": null}, + {"sequence": "eight", "players": [normalized_player], "active_player_handle": null}, + _snapshot(-1, [normalized_player], null), + _snapshot(8, [_player("player:opaque-6", "Negative Position", "playing", "T", "A", null, null, -5)], null), + _snapshot(8, [_player("player:opaque-8", "Negative Length", "playing", "T", "A", null, -3)], null), + _snapshot(8, [bad_identity], null), + _snapshot(8, [bad_length], null), + _snapshot(8, [missing_position], null), + ] + for malformed_snapshot in malformed_snapshots: + _emit_media(bridge, 0, malformed_snapshot) + _emit_media(bridge, 0, "not-a-dictionary") + _check( + last_ux_stage == "media_failed" and last_ux_message == "INVALID MEDIA DATA", + "P5.07 malformed media snapshots produce concise visible feedback" + ) + _check( + snapshot_emissions[0] == 1 + and int(backend.media_snapshot.get("sequence", 0)) == 7 + and backend.media_availability == "available" + and availability_emissions[0] == 1, + "P5.07 out-of-bounds or mistyped payloads never replace last-good media state" + ) + + # --- strict sequence fencing: single-flight requests and stale frames + _check(backend.request_media_snapshot(), "P5.07 a fresh snapshot can be requested on demand") + var pending_request := _message_at(bridge, bridge.sent_lines.size() - 1) + _check( + not backend.request_media_snapshot(), + "P5.07 snapshot requests stay single-flight while one is pending" + ) + _emit_media(bridge, 888888, _snapshot(8, [_player("player:opaque-stale", "Stale Frame")], null)) + _check( + snapshot_emissions[0] == 1 + and int(backend.media_snapshot.get("sequence", 0)) == 7 + and backend._media_request_id != 0, + "P5.07 stale snapshot frames are fenced while a request is pending" + ) + _emit_media(bridge, 0, _snapshot(8, [], null)) + _check( + snapshot_emissions[0] == 2 + and int(backend.media_snapshot.get("sequence", 0)) == 8 + and backend._media_request_id != 0, + "P5.07 a live Core push is accepted without cancelling a pending request" + ) + _emit_media(bridge, pending_request.get("request_id"), _snapshot(8, [_player("player:opaque-equal", "Equal Seq")], null)) + _check( + snapshot_emissions[0] == 2 + and int(backend.media_snapshot.get("sequence", 0)) == 8 + and backend._media_request_id == 0, + "P5.07 an equal sequence clears the request without replacing state" + ) + _emit_media(bridge, 0, _snapshot(6, [], null)) + _check( + snapshot_emissions[0] == 2 + and int(backend.media_snapshot.get("sequence", 0)) == 8, + "P5.07 older sequences are fenced out without emissions" + ) + _emit_media(bridge, 0, _snapshot(8, [], null)) + _check( + snapshot_emissions[0] == 2 + and backend.media_snapshot.get("players", []).is_empty() + and String(backend.media_snapshot.get("active_player_handle", "")) == "", + "P5.07 an empty player list is a valid frame, not an error" + ) + _emit_media(bridge, 0, _snapshot(9, [ + normalized_player, + _player("player:opaque-2", "Second Player", "paused"), + ], "player:opaque-2")) + _check( + snapshot_emissions[0] == 3 + and backend.media_snapshot.get("players", []).size() == 2 + and String(backend.media_snapshot.get("active_player_handle", "")) == "player:opaque-2", + "P5.07 newer event-driven snapshots replace state without polling" + ) + + # --- availability transitions stay de-duplicated and request-scoped + _check(backend.request_media_snapshot(), "P5.07 snapshot requests can be re-issued") + var unavailable_request := _message_at(bridge, bridge.sent_lines.size() - 1) + _emit_media_rejected(bridge, 999999, "media_unavailable", false) + _check( + backend.media_availability == "available" and availability_emissions[0] == 1, + "P5.07 uncorrelated rejections never mutate availability" + ) + _emit_media_rejected(bridge, unavailable_request.get("request_id"), "media_unavailable", false) + _check( + backend.media_availability == "unavailable" and availability_emissions[0] == 2, + "P5.07 a correlated media-unavailable rejection flips availability once" + ) + _emit_media_rejected(bridge, unavailable_request.get("request_id"), "media_unavailable", false) + _check( + backend.media_availability == "unavailable" and availability_emissions[0] == 2, + "P5.07 repeated media unavailability stays silent without log spam" + ) + _check(backend.request_media_snapshot(), "P5.07 the snapshot can be requested while unavailable") + var waiting_request := _message_at(bridge, bridge.sent_lines.size() - 1) + _emit_media_rejected(bridge, waiting_request.get("request_id"), "snapshot_not_ready", true) + _check( + backend.media_availability == "waiting" and availability_emissions[0] == 3, + "P5.07 snapshot-not-ready maps to a typed waiting availability" + ) + _check( + snapshot_emissions[0] == 3 + and int(backend.media_snapshot.get("sequence", 0)) == 9, + "P5.07 transient rejections never discard last-good media state" + ) + _check(backend.request_media_snapshot(), "P5.07 the snapshot can be requested while waiting") + var restore_request := _message_at(bridge, bridge.sent_lines.size() - 1) + _emit_media(bridge, restore_request.get("request_id"), _snapshot(10, [ + normalized_player, + _player("player:opaque-2", "Second Player", "paused"), + ], "player:opaque-2")) + _check( + backend.media_availability == "available" + and availability_emissions[0] == 4 + and snapshot_emissions[0] == 4, + "P5.07 a served snapshot restores availability without extra emissions" + ) + + # --- reconnect retention and post-reconnect fencing + _check( + backend.send_media_control("player:opaque-2", "next"), + "P5.07 a control can be pending across a disconnect" + ) + bridge.socket_disconnected.emit("media retention test") + _check( + control_rejections.size() == 1 + and control_rejections[0][2] == "connection_lost", + "P5.07 a disconnect fails pending controls as connection loss" + ) + _check( + int(backend.media_snapshot.get("sequence", 0)) == 10 + and not backend.media_snapshot.is_empty(), + "P5.07 last-good media state survives the disconnect" + ) + bridge.socket_connected.emit() + bridge.line_received.emit(JSON.stringify(_welcome())) + var refreshed_request := _last_request_of_type(bridge, "get_media_snapshot") + _check( + int(refreshed_request.get("request_id", 0)) > int(restore_request.get("request_id", 0)), + "P5.07 reconnect re-requests the media snapshot without adding polling" + ) + _emit_media(bridge, refreshed_request.get("request_id"), _snapshot(9, [], null)) + _check( + snapshot_emissions[0] == 4 + and int(backend.media_snapshot.get("sequence", 0)) == 10, + "P5.07 an older post-reconnect frame cannot regress retained state" + ) + _emit_media(bridge, 0, _snapshot(11, [ + _player("player:opaque-9", "Fresh Player", "stopped"), + ], "player:opaque-9")) + _check( + snapshot_emissions[0] == 5 + and int(backend.media_snapshot.get("sequence", 0)) == 11, + "P5.07 a newer post-reconnect snapshot refreshes the retained state" + ) + + # --- control handling: only the typed handle and verb boundary + var sent_lines_before_control := bridge.sent_lines.size() + _check( + not backend.send_media_control("", "play"), + "P5.07 empty player handles are rejected locally" + ) + _check( + not backend.send_media_control("player:opaque-9", "SetPosition"), + "P5.07 raw MPRIS method names are rejected as verbs" + ) + _check( + not backend.send_media_control("player:opaque-9", "org.mpris.MediaPlayer2.Play"), + "P5.07 raw D-Bus names are rejected as verbs or handles" + ) + _check( + bridge.sent_lines.size() == sent_lines_before_control + and control_rejections.size() == 4, + "P5.07 locally rejected controls never reach the wire" + ) + _check( + backend.send_media_control("player:opaque-9", "play_pause"), + "P5.07 a ready client accepts an allowlisted control" + ) + var control_request := _message_at(bridge, bridge.sent_lines.size() - 1) + _check( + control_request.get("type") == "send_media_control" + and control_request.get("protocol_version") == 5 + and control_request.get("player_handle") == "player:opaque-9" + and control_request.get("verb") == "play_pause" + and control_request.keys().size() == 5, + "P5.07 control requests carry only the typed handle and verb boundary" + ) + _emit_control_accepted(bridge, 777777, "player:opaque-9") + _check( + backend._media_control_request_id != 0 and control_accepts.is_empty(), + "P5.07 uncorrelated control acceptance is fenced out" + ) + _check( + not backend.send_media_control("player:opaque-9", "stop"), + "P5.07 a second control is rejected while one is pending" + ) + _emit_control_accepted(bridge, control_request.get("request_id"), "player:opaque-9") + _check( + control_accepts.size() == 1 + and control_accepts[0][0] == "player:opaque-9" + and control_accepts[0][1] == "play_pause" + and backend._media_control_request_id == 0, + "P5.07 correlated acceptance clears pending state and echoes the verb" + ) + _check( + backend.send_media_control("player:opaque-9", "next"), + "P5.07 another control can be requested" + ) + var stale_control := _message_at(bridge, bridge.sent_lines.size() - 1) + _emit_control_rejected(bridge, stale_control.get("request_id"), "player:opaque-9", "stale_handle") + _check( + control_rejections.size() == 6 + and control_rejections[5][2] == "stale_handle" + and last_ux_message == "PLAYER STALE // REFRESH LIST", + "P5.07 stale player handles fail with concise typed feedback" + ) + _check( + backend.send_media_control("player:opaque-9", "play"), + "P5.07 a pending control can be left to time out" + ) + backend._update_launch_timeout(BackendClient.MEDIA_CONTROL_TIMEOUT_SECONDS + 0.1) + _check( + backend._media_control_request_id == 0 + and control_rejections.size() == 7 + and control_rejections[6][2] == "media_control_timeout", + "P5.07 pending controls time out with retryable typed feedback" + ) + + # --- typed control results drive availability transitions once + _check( + backend.send_media_control("player:opaque-9", "next"), + "P5.07 a control result can report media unavailability" + ) + var unavailable_control := _message_at(bridge, bridge.sent_lines.size() - 1) + _emit_control_rejected(bridge, unavailable_control.get("request_id"), "player:opaque-9", "media_unavailable") + _check( + control_rejections.size() == 8 + and control_rejections[7][2] == "media_unavailable" + and backend.media_availability == "unavailable" + and availability_emissions[0] == 5, + "P5.07 a media-unavailable control failure flips availability exactly once" + ) + _emit_control_rejected(bridge, unavailable_control.get("request_id"), "player:opaque-9", "media_unavailable") + _check( + control_rejections.size() == 8 + and backend.media_availability == "unavailable" + and availability_emissions[0] == 5, + "P5.07 repeated control-driven unavailability stays silent" + ) + _check( + last_ux_stage == "media_control_failed" + and last_ux_message == "MEDIA PLAYBACK UNAVAILABLE" + and last_ux_tone == "failure", + "P5.07 control unavailability surfaces concise typed feedback" + ) + + backend.queue_free() + await process_frame diff --git a/frontend/godot/tests/media_validation.gd b/frontend/godot/tests/media_validation.gd new file mode 100644 index 0000000..8b7f7c1 --- /dev/null +++ b/frontend/godot/tests/media_validation.gd @@ -0,0 +1,721 @@ +extends SceneTree + +# P5.08 media console scene and UI validation. Client-side BackendClient +# media coverage (normalization, bounds, fencing, retention, availability, +# and control results) lives in media_client_validation.gd; this file +# exercises the console and its main-scene wiring only, including the +# Core-aligned capability gates and keyboard reachability of all six +# allowlisted verbs. + +const MediaConsoleScript = preload("res://ui/media_console.gd") + +class FakeBridge: + extends Node + + signal socket_connected + signal socket_disconnected(reason: String) + signal line_received(payload: String) + signal transport_error(code: String, message: String) + + var sent_lines: Array[String] = [] + var connected_path := "" + var disconnected := false + + func default_socket_path() -> String: + return "/tmp/velora-fake.sock" + + func connect_socket(path: String) -> bool: + connected_path = path + return true + + func disconnect_socket() -> void: + disconnected = true + + func send_line(payload: String) -> bool: + sent_lines.append(payload) + return true + +var failures: Array[String] = [] + +func _initialize() -> void: + call_deferred("_run") + +func _check(condition: bool, message: String) -> void: + if condition: + print("PASS: ", message) + else: + failures.append(message) + push_error("FAIL: " + message) + +func _key_event(keycode: int) -> InputEventKey: + var event := InputEventKey.new() + event.keycode = keycode + event.pressed = true + return event + +func _welcome() -> Dictionary: + return { + "type": "welcome", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "server_name": "velora-core-test", + "server_version": "0.2.0", + } + +func _player( + handle: String, + identity := "Velora Test Player", + status := "playing", + title := "Velora Theme", + artist := "Velora", + album: Variant = null, + length_micros: Variant = null, + position_micros := 12500000, + can_play := true, + can_pause := true, + can_go_next := true, + can_go_previous := true, + can_seek := false, + can_control := true +) -> Dictionary: + return { + "handle": handle, + "identity": identity, + "status": status, + "title": title, + "artist": artist, + "album": album, + "length_micros": length_micros, + "position_micros": position_micros, + "can_play": can_play, + "can_pause": can_pause, + "can_go_next": can_go_next, + "can_go_previous": can_go_previous, + "can_seek": can_seek, + "can_control": can_control, + } + +func _snapshot(sequence: int, players: Array, active: Variant = null) -> Dictionary: + return {"sequence": sequence, "players": players, "active_player_handle": active} + +func _emit_media(bridge: FakeBridge, request_id: Variant, snapshot: Variant) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "snapshot": snapshot, + })) + +func _emit_media_rejected( + bridge: FakeBridge, + request_id: Variant, + code: String, + retryable: bool +) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_snapshot_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "code": code, + "retryable": retryable, + })) + +func _emit_control_accepted(bridge: FakeBridge, request_id: Variant, player_handle: String) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_accepted", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "player_handle": player_handle, + })) + +func _emit_control_rejected( + bridge: FakeBridge, + request_id: Variant, + player_handle: String, + code: String +) -> void: + bridge.line_received.emit(JSON.stringify({ + "type": "media_control_rejected", + "protocol_version": BackendClient.PROTOCOL_VERSION, + "request_id": request_id, + "player_handle": player_handle, + "code": code, + })) + +func _message_at(bridge: FakeBridge, index: int) -> Dictionary: + if index < 0 or index >= bridge.sent_lines.size(): + return {} + var value = JSON.parse_string(bridge.sent_lines[index]) + return value if value is Dictionary else {} + +func _last_request_of_type(bridge: FakeBridge, request_type: String) -> Dictionary: + for index in range(bridge.sent_lines.size() - 1, -1, -1): + var candidate := _message_at(bridge, index) + if candidate.get("type") == request_type: + return candidate + return {} + +func _run() -> void: + await _run_scene_wiring() + await _run_console() + if failures.is_empty(): + print("P5.08 media console validation passed.") + quit(0) + else: + push_error("P5.08 media console validation failed: %s" % [failures]) + quit(1) + +func _run_scene_wiring() -> void: + # --- main-scene wiring: typed client signals reach the console --- + var bridge := FakeBridge.new() + var main_scene := load("res://scenes/main.tscn") as PackedScene + var main: Node = main_scene.instantiate() + var scene_backend: BackendClient = main.get_node("BackendClient") + scene_backend.auto_connect = false + scene_backend.bridge_override = bridge + root.add_child(main) + await process_frame + var console: CanvasLayer = main.get_node("MediaConsole") + _check(not console.visible, "P5.08 the media console starts hidden in the scene") + + scene_backend.connect_to_core() + bridge.socket_connected.emit() + bridge.line_received.emit(JSON.stringify(_welcome())) + var scene_media_request := _last_request_of_type(bridge, "get_media_snapshot") + _emit_media(bridge, scene_media_request.get("request_id"), _snapshot(21, [ + _player("player:music-1", "Spotify", "playing", "Velora Theme", "Velora", "Night Album", 250000000), + _player("player:music-2", "Firefox", "paused", "Quiet Track", "", "", null, 5000000, true, true, false, false, false, true), + ], "player:music-1")) + _check( + console.players.size() == 2 and console.selected_index == 0, + "P5.08 typed client signals reach the scene console with the active player selected" + ) + _check( + console._title.text == "MEDIA // PLAYERS", + "P5.08 the scene console labels availability from typed client state" + ) + _check( + String(console._rows[0]["summary"].text) == ">+@ SPOTIFY", + "P5.08 the scene console renders status and active markers without color" + ) + + main._toggle_media_console() + _check( + main.media_open and console.visible and not main.player.input_enabled, + "P5.08 opening the console locks world input" + ) + var refresh_request := _last_request_of_type(bridge, "get_media_snapshot") + _check( + int(refresh_request.get("request_id", 0)) > int(scene_media_request.get("request_id", 0)), + "P5.08 opening the console triggers a scene-driven snapshot refresh" + ) + + console._unhandled_input(_key_event(KEY_SPACE)) + var control_message := _last_request_of_type(bridge, "send_media_control") + _check( + control_message.get("player_handle") == "player:music-1" + and control_message.get("verb") == "play_pause" + and control_message.keys().size() == 5, + "P5.08 console verb keypresses travel the typed request path" + ) + _emit_control_accepted(bridge, control_message.get("request_id"), "player:music-1") + _check( + String(console._feedback.text) == "PLAY/PAUSE OK", + "P5.08 correlated control acceptance surfaces in the console feedback line" + ) + + console._unhandled_input(_key_event(KEY_N)) + var next_message := _last_request_of_type(bridge, "send_media_control") + _emit_control_rejected(bridge, next_message.get("request_id"), "player:music-1", "stale_handle") + _check( + String(console._feedback.text) == "PLAYER STALE // REFRESH LIST", + "P5.08 typed control rejections surface in the console feedback line" + ) + + console._unhandled_input(_key_event(KEY_DOWN)) + var lines_before_gate := bridge.sent_lines.size() + console._unhandled_input(_key_event(KEY_N)) + _check( + bridge.sent_lines.size() == lines_before_gate + and String(console._feedback.text) == "CONTROL NOT AVAILABLE", + "P5.08 capability gates block unsupported verbs before the wire" + ) + + console._unhandled_input(_key_event(KEY_ESCAPE)) + _check( + not main.media_open and not console.visible and main.player.input_enabled, + "P5.08 closing the console restores world input" + ) + main._unhandled_input(_key_event(KEY_P)) + _check(main.media_open and console.visible, "P5.08 P toggles the console from the world view") + console._unhandled_input(_key_event(KEY_ESCAPE)) + main.queue_free() + await process_frame + +func _run_console() -> void: + # --- standalone console behaviours (offline, no core) --- + var user_files_before := DirAccess.get_files_at(OS.get_user_data_dir()) + var user_dirs_before := DirAccess.get_directories_at(OS.get_user_data_dir()) + + var console: CanvasLayer = CanvasLayer.new() + console.set_script(MediaConsoleScript) + root.add_child(console) + await process_frame + + # --- conservative start state + _check(not console.visible, "P5.08 the console starts hidden") + _check(console._title.text.contains("WAITING"), "P5.08 the console starts in a typed waiting state") + _check(console._counter.text == "0/0", "P5.08 the position counter starts at zero") + _check(console._feedback.text == "", "P5.08 the feedback line starts empty") + + # --- explicit availability states + console.set_availability("unavailable") + _check(console._title.text.contains("NO SERVICE"), "P5.08 a missing media service is labelled explicitly") + console.set_availability("available") + _check( + console._title.text.contains("PLAYERS") and not console._title.text.contains("NO SERVICE"), + "P5.08 an available media service is labelled explicitly" + ) + console.set_availability("unknown") + _check(console._title.text.contains("WAITING"), "P5.08 unknown availability falls back to waiting") + + # --- empty snapshots are explicit, never guessed + console.update_media(_snapshot(1, [], null)) + console.open() + _check( + String(console._rows[0]["summary"].text) == "NO PLAYERS", + "P5.08 an empty player list states it explicitly rather than guessing" + ) + _check( + console.selected_index == -1 and console.scroll_offset == 0, + "P5.08 an empty player list has no selection" + ) + console._unhandled_input(_key_event(KEY_SPACE)) + _check( + String(console._feedback.text) == "NO PLAYERS", + "P5.08 control keypresses with no players are labelled explicitly" + ) + console.close() + + # --- status and active markers never rely on color alone + var music_player := _player("player:music-1", "Spotify", "playing", "Velora Theme", "Velora", "Night Album", 250000000, 12500000) + var paused_player := _player("player:music-2", "Firefox", "paused", "Quiet Track", "", "", null, 5000000) + var stopped_player := _player("player:music-3", "Vlc", "stopped", "", "Someone", "", null, 0) + console.update_media(_snapshot(2, [music_player, paused_player, stopped_player], "player:music-1")) + console.open() + _check(console._counter.text == "1/3", "P5.08 the counter reports the selected position and total") + _check( + String(console._rows[0]["summary"].text) == ">+@ SPOTIFY", + "P5.08 a selected playing active player carries cursor, status, and active markers" + ) + _check( + String(console._rows[0]["detail"].text) == "PLAY // ACTIVE // Velora Theme // Velora // Night Album // 0:12 / 4:10", + "P5.08 the active player spells status, metadata, and position" + ) + _check( + String(console._rows[1]["summary"].text) == " = FIREFOX" + and String(console._rows[1]["detail"].text).begins_with("PAUSE // Quiet Track // 0:05 / --:--"), + "P5.08 paused players carry the equals marker and an unknown length sentinel" + ) + _check( + String(console._rows[2]["summary"].text) == " . VLC" + and String(console._rows[2]["detail"].text).begins_with("STOP // UNTITLED // Someone // 0:00 / --:--"), + "P5.08 stopped players carry the dot marker and spell UNTITLED" + ) + _check( + console._hint.text == "SPACE PLAY/PAUSE X STOP N NEXT B PREV P CLOSE", + "P5.08 the hint line lists exactly the capability-allowed verbs" + ) + + # --- keyboard-only selection and scrolling across more players + var scroll_players: Array = [] + var statuses := ["playing", "paused", "stopped"] + for index in range(6): + scroll_players.append(_player( + "player:scroll-%d" % index, + "Scroll %d" % index, + statuses[index % 3] + )) + console.update_media(_snapshot(3, scroll_players, null)) + console.open() + _check( + console.selected_index == 0 and console._counter.text == "1/6", + "P5.08 reopening resets selection to the first player" + ) + console._unhandled_input(_key_event(KEY_END)) + _check( + console.selected_index == 5 and console.scroll_offset == 3 and console._counter.text == "6/6", + "P5.08 End jumps to the last player and scrolls the window" + ) + _check( + String(console._rows[0]["summary"].text).begins_with(" + SCROLL 3") + and String(console._rows[2]["summary"].text).begins_with(">. SCROLL 5"), + "P5.08 the visible window follows the selection" + ) + console._unhandled_input(_key_event(KEY_DOWN)) + _check(console.selected_index == 0, "P5.08 selection wraps forward past the end") + console._unhandled_input(_key_event(KEY_UP)) + _check(console.selected_index == 5, "P5.08 selection wraps backward past the start") + console._unhandled_input(_key_event(KEY_HOME)) + _check( + console.selected_index == 0 and console.scroll_offset == 0, + "P5.08 Home jumps to the first player" + ) + console._unhandled_input(_key_event(KEY_PAGEDOWN)) + _check(console.selected_index == 3, "P5.08 Page Down scrolls a full window") + console._unhandled_input(_key_event(KEY_PAGEUP)) + _check(console.selected_index == 0, "P5.08 Page Up scrolls a full window back") + console._unhandled_input(_key_event(KEY_S)) + _check(console.selected_index == 1, "P5.08 W and S mirror the arrow keys") + + # --- verb keypresses emit only allowlisted verbs for opaque handles + console.update_media(_snapshot(4, [music_player], "player:music-1")) + console.open() + var emitted: Array = [] + console.control_requested.connect(func(player_handle: String, verb: String) -> void: + emitted.append([player_handle, verb]) + ) + # All six allowlisted verbs are keyboard reachable: the toggle keys + # resolve the combined verb for players advertising both capabilities, + # and the numpad play/pause glyphs carry the standalone verbs. + var verb_keys := { + KEY_SPACE: "play_pause", + KEY_E: "play_pause", + KEY_ENTER: "play_pause", + KEY_N: "next", + KEY_RIGHT: "next", + KEY_D: "next", + KEY_B: "previous", + KEY_LEFT: "previous", + KEY_A: "previous", + KEY_X: "stop", + KEY_KP_0: "play", + KEY_KP_2: "pause", + } + for verb_key in verb_keys: + console._unhandled_input(_key_event(verb_key)) + _check( + emitted.size() == verb_keys.size() + and String(emitted[0][0]) == "player:music-1", + "P5.08 each control key emits exactly one typed verb for the opaque handle" + ) + var emitted_verbs := {} + for pair in emitted: + emitted_verbs[pair[1]] = true + _check( + emitted_verbs.keys().size() == 6 + and emitted_verbs.has("play") + and emitted_verbs.has("pause") + and emitted_verbs.has("play_pause") + and emitted_verbs.has("stop") + and emitted_verbs.has("next") + and emitted_verbs.has("previous"), + "P5.08 every one of the six allowlisted verbs is keyboard reachable" + ) + + # --- capability gates fail closed before the wire + var locked_player := _player("player:locked-1", "Locked", "playing", "T", "A", null, null, 0, true, true, true, true, false, false) + console.update_media(_snapshot(5, [locked_player], "player:locked-1")) + var emitted_before_gate := emitted.size() + console._unhandled_input(_key_event(KEY_SPACE)) + console._unhandled_input(_key_event(KEY_N)) + console._unhandled_input(_key_event(KEY_X)) + _check( + emitted.size() == emitted_before_gate + and String(console._feedback.text) == "CONTROL NOT AVAILABLE" + and console._hint.text == "NO CONTROLS P CLOSE", + "P5.08 players without control capability fail closed with an explicit label" + ) + var no_next_player := _player("player:nonext-1", "No Next", "paused", "T", "A", null, null, 0, true, true, false) + console.update_media(_snapshot(6, [no_next_player], "player:nonext-1")) + console._unhandled_input(_key_event(KEY_N)) + _check( + emitted.size() == emitted_before_gate + and String(console._feedback.text) == "CONTROL NOT AVAILABLE", + "P5.08 unsupported next controls are gated before the wire" + ) + var listen_only := _player("player:listen-1", "Listen Only", "playing", "T", "A", null, null, 0, false, false, false, false) + console.update_media(_snapshot(7, [listen_only], "player:listen-1")) + console._unhandled_input(_key_event(KEY_SPACE)) + _check( + emitted.size() == emitted_before_gate, + "P5.08 players without play or pause capability gate the toggle verb" + ) + + # --- Core-aligned PlayPause gate: both capabilities are required + # media_store::verb_supported gates PlayPause on can_play AND can_pause, + # so the combined verb must never leave the console for a half-capable + # player; the toggle key degrades to the exact advertised verb instead. + var play_only := _player("player:playonly-1", "Play Only", "paused", "T", "A", null, null, 0, true, false, false, false) + console.update_media(_snapshot(14, [play_only], "player:playonly-1")) + console._unhandled_input(_key_event(KEY_SPACE)) + _check( + emitted.size() == emitted_before_gate + 1 + and String(emitted[emitted.size() - 1][1]) == "play", + "P5.08 a play-only player toggles with the standalone play verb" + ) + _check( + console._hint.text == "SPACE PLAY X STOP P CLOSE", + "P5.08 the hint names the exact verb the toggle key will fire" + ) + console._unhandled_input(_key_event(KEY_KP_0)) + console._unhandled_input(_key_event(KEY_KP_2)) + _check( + emitted.size() == emitted_before_gate + 2 + and String(emitted[emitted.size() - 1][0]) == "player:playonly-1" + and String(emitted[emitted.size() - 1][1]) == "play", + "P5.08 the standalone play key still fires for a play-only player" + ) + var pause_only := _player("player:pauseonly-1", "Pause Only", "playing", "T", "A", null, null, 0, false, true, false, false) + console.update_media(_snapshot(15, [pause_only], "player:pauseonly-1")) + console._unhandled_input(_key_event(KEY_SPACE)) + _check( + emitted.size() == emitted_before_gate + 3 + and String(emitted[emitted.size() - 1][1]) == "pause", + "P5.08 a pause-only player toggles with the standalone pause verb" + ) + _check( + console._hint.text == "SPACE PAUSE X STOP P CLOSE", + "P5.08 the pause-only hint names the pause verb" + ) + var half_toggle := _player("player:half-1", "Half", "playing", "T", "A", null, null, 0, true, false, false, false) + console.update_media(_snapshot(16, [half_toggle], "player:half-1")) + console._request_verb("play_pause") + _check( + emitted.size() == emitted_before_gate + 3 + and String(console._feedback.text) == "CONTROL NOT AVAILABLE", + "P5.08 the combined toggle verb requires both play and pause capability like Core" + ) + + # --- the toggle degrades conservatively as capabilities change + var degrading := _player("player:degrade-1", "Degrade", "playing", "T", "A", null, null, 0, true, true, false, false) + console.update_media(_snapshot(17, [degrading], "player:degrade-1")) + console._unhandled_input(_key_event(KEY_SPACE)) + degrading["can_pause"] = false + console.update_media(_snapshot(18, [degrading], "player:degrade-1")) + console._unhandled_input(_key_event(KEY_SPACE)) + _check( + emitted.size() == emitted_before_gate + 5 + and String(emitted[emitted.size() - 2][1]) == "play_pause" + and String(emitted[emitted.size() - 1][1]) == "play", + "P5.08 the toggle degrades from combined to standalone as capabilities drop" + ) + + # --- correlated control outcomes in the feedback line + console.update_media(_snapshot(8, [music_player], "player:music-1")) + console.open() + console.apply_control_accepted("player:music-1", "next") + _check( + console._feedback.text == "NEXT OK" + and console._feedback.get_theme_color("font_color") == MediaConsoleScript.TONE_COLORS["ready"], + "P5.08 accepted controls render a ready-tone outcome" + ) + console.apply_control_rejected("player:music-1", "next", "unknown_player", "PLAYER NO LONGER EXISTS", false) + _check( + console._feedback.text == "PLAYER NO LONGER EXISTS" + and console._feedback.get_theme_color("font_color") == MediaConsoleScript.TONE_COLORS["failure"], + "P5.08 non-retryable rejections render the typed failure tone" + ) + console.apply_control_rejected("player:music-1", "next", "connection_lost", "CONNECTION LOST // RETRY", true) + _check( + console._feedback.text == "CONNECTION LOST // RETRY" + and console._feedback.get_theme_color("font_color") == MediaConsoleScript.TONE_COLORS["waiting"], + "P5.08 retryable rejections render the typed waiting tone" + ) + console.close() + console.open() + _check( + console._feedback.text == "", + "P5.08 reopening resets the feedback line for a fresh inspection" + ) + + # --- selection follows player handles across updates + console.update_media(_snapshot(9, [music_player, paused_player, stopped_player], "player:music-1")) + console.open() + console._unhandled_input(_key_event(KEY_DOWN)) + _check(console.selected_index == 1, "P5.08 the second player can be selected") + console.update_media(_snapshot(10, [music_player, stopped_player, paused_player], "player:music-1")) + _check( + console.selected_index == 2 + and String(console.players[console.selected_index].get("handle", "")) == "player:music-2", + "P5.08 selection follows the player handle across snapshot reordering" + ) + console.update_media(_snapshot(11, [music_player, stopped_player], "player:music-1")) + _check( + console.selected_index == 0 + and console._counter.text == "1/2", + "P5.08 a vanished selection falls back to the active player" + ) + + # --- malformed console frames never replace last-good state + console.update_media({"sequence": 12, "players": "not-an-array"}) + _check( + console.players.size() == 2 + and String(console.players[0].get("handle", "")) == "player:music-1", + "P5.08 malformed console frames never replace last-good state" + ) + console.update_media(_snapshot(12, [ + {"handle": "", "identity": "X", "status": "playing"}, + stopped_player, + ], null)) + _check( + console.players.size() == 1 + and String(console.players[0].get("handle", "")) == "player:music-3", + "P5.08 entries without handles are dropped while valid frames replace state" + ) + console.update_media(_snapshot(12, [stopped_player, stopped_player], null)) + _check( + console.players.size() == 1, + "P5.08 duplicate player handles are dropped defensively" + ) + var oversized: Array = [] + for index in range(MediaConsoleScript.MAX_TRACKED_PLAYERS + 1): + oversized.append(_player("player:flood-%d" % index, "Flood %d" % index)) + console.update_media(_snapshot(13, oversized, null)) + _check( + console.players.size() == 1, + "P5.08 oversized player lists never replace last-good console state" + ) + + # --- stale-but-labelled availability keeps last-good players + console.set_availability("unavailable") + _check( + console._title.text.contains("NO SERVICE") and console.players.size() == 1, + "P5.08 unavailability labels stale players instead of clearing them" + ) + console.set_availability("available") + _check( + console._title.text.contains("PLAYERS") and console.players.size() == 1, + "P5.08 restored availability keeps the tracked players" + ) + + # --- rapid snapshot bursts never reflow the layout + console.update_media(_snapshot(20, [music_player, paused_player, stopped_player], "player:music-1")) + console.open() + await process_frame + var panel_rect: Rect2 = console._panel.get_rect() + var row_height: float = console._rows[0]["panel"].get_rect().size.y + _check( + panel_rect.position == Vector2(40, 24) + and panel_rect.end.x <= 320.0 + and panel_rect.end.y <= 180.0, + "P5.08 the fixed panel always fits the 320 x 180 canvas" + ) + for burst in range(60): + var flood: Array = [] + for index in range(burst % 18): + flood.append(_player( + "player:burst-%d-%d" % [burst, index], + "Burst %d %s" % [index, "x".repeat(index * 8)], + statuses[index % 3], + "Title %d %s" % [index, "y".repeat(index * 8)], + "Artist %d" % index + )) + console.update_media(_snapshot(100 + burst, flood, null)) + await process_frame + _check( + console._panel.get_rect() == panel_rect, + "P5.08 rapid snapshot bursts never reflow the panel geometry" + ) + _check( + console._rows_box.get_child_count() == MediaConsoleScript.MAX_VISIBLE_PLAYERS, + "P5.08 the row structure stays fixed under bursts" + ) + _check( + console._rows[0]["panel"].get_rect().size.y == row_height, + "P5.08 row heights stay fixed under bursts" + ) + + # --- maximum-length content is clipped, never overflowing + var max_identity := "s".repeat(256) + var max_title := "t".repeat(256) + console.update_media(_snapshot(200, [ + _player("player:long-1", max_identity, "playing", max_title, "Velora", "", null, 0), + ], "player:long-1")) + await process_frame + var long_row: Dictionary = console._rows[0] + _check( + bool(long_row["summary"].clip_text) and int(long_row["summary"].text_overrun_behavior) == 3, + "P5.08 long identities clip with word ellipsis" + ) + _check( + bool(long_row["detail"].clip_text) and int(long_row["detail"].text_overrun_behavior) == 3, + "P5.08 long titles clip with word ellipsis" + ) + _check( + long_row["panel"].get_rect().size.y == row_height + and console._panel.get_rect() == panel_rect, + "P5.08 maximum-length entries never change the panel geometry" + ) + + # --- reduced motion: every state change is instant, never animated + console.update_media(_snapshot(300, [music_player, paused_player], "player:music-1")) + console.open() + console._unhandled_input(_key_event(KEY_DOWN)) + _check( + console._rows[1]["style"].bg_color == MediaConsoleScript.ROW_BG_SELECTED, + "P5.08 selection applies in the same frame with no animated transition" + ) + console._unhandled_input(_key_event(KEY_UP)) + _check( + console._rows[0]["style"].bg_color == MediaConsoleScript.ROW_BG_SELECTED + and console._rows[1]["style"].bg_color == MediaConsoleScript.ROW_BG, + "P5.08 deselection is equally instant" + ) + + # --- closing + var close_count := [0] + console.console_closed.connect(func() -> void: + close_count[0] += 1 + ) + console._unhandled_input(_key_event(KEY_ESCAPE)) + _check( + not console.visible and close_count[0] == 1, + "P5.08 Escape closes the console" + ) + console.open() + console._unhandled_input(_key_event(KEY_P)) + _check( + not console.visible and close_count[0] == 2, + "P5.08 P closes the console" + ) + + # --- the console never persists, shells out, or logs + var console_source := FileAccess.get_file_as_string("res://ui/media_console.gd") + for banned in [ + "FileAccess", + "ConfigFile", + "ResourceSaver", + "user://", + "store_", + "save_", + "Tween", + "create_tween", + "AnimationPlayer", + "print(", + "hyprctl", + "OS." + "execute", + ]: + _check(not console_source.contains(banned), "P5.08 the console never uses %s" % banned) + var user_files_after := DirAccess.get_files_at(OS.get_user_data_dir()) + var user_dirs_after := DirAccess.get_directories_at(OS.get_user_data_dir()) + _check( + user_files_before == user_files_after and user_dirs_before == user_dirs_after, + "P5.08 a full console inspection cycle writes nothing to user data" + ) + + # --- nothing survives a restart + var restarted: CanvasLayer = CanvasLayer.new() + restarted.set_script(MediaConsoleScript) + root.add_child(restarted) + await process_frame + _check( + restarted.players.is_empty() + and restarted.selected_index == -1 + and restarted._title.text.contains("WAITING"), + "P5.08 a fresh console starts empty: nothing survives a restart" + ) + restarted.queue_free() + await process_frame + + console.queue_free() + await process_frame diff --git a/frontend/godot/tests/notification_validation.gd b/frontend/godot/tests/notification_validation.gd new file mode 100644 index 0000000..af22480 --- /dev/null +++ b/frontend/godot/tests/notification_validation.gd @@ -0,0 +1,417 @@ +extends SceneTree + +const NotificationFeedScript = preload("res://ui/notification_feed.gd") + +var failures: Array[String] = [] + +func _initialize() -> void: + call_deferred("_run") + +func _check(condition: bool, message: String) -> void: + if condition: + print("PASS: ", message) + else: + failures.append(message) + push_error("FAIL: " + message) + +func _entry( + handle: String, + summary: String, + body: String, + urgency: String, + timestamp: int, + app_name := "Velora" +) -> Dictionary: + return { + "handle": handle, + "app_name": app_name, + "summary": summary, + "body": body, + "urgency": urgency, + "timestamp_unix_ms": timestamp, + } + +func _feed(notifications: Array, sequence: int) -> Dictionary: + return {"sequence": sequence, "notifications": notifications} + +func _key_event(keycode: int) -> InputEventKey: + var event := InputEventKey.new() + event.keycode = keycode + event.pressed = true + return event + +func _run() -> void: + # --- main-scene wiring: typed client signals reach the panel --- + # The client stays offline so the wiring check is deterministic and + # never touches a live session bus or socket. + var main_scene := load("res://scenes/main.tscn") as PackedScene + var main: Node = main_scene.instantiate() + var scene_backend: BackendClient = main.get_node("BackendClient") + scene_backend.auto_connect = false + root.add_child(main) + await process_frame + var scene_feed: CanvasLayer = main.get_node("NotificationFeed") + scene_backend.notification_feed_changed.emit(_feed([ + _entry("notification:wired-1", "Wired summary", "Wired body", "critical", 500), + _entry("notification:wired-2", "Wired second", "", "low", 600), + ], 10)) + scene_backend.notifications_availability_changed.emit("available") + _check( + scene_feed.entries.size() == 2 and scene_feed._title.text.contains("FEED"), + "P5.10 main-scene wiring routes typed client signals into the panel" + ) + main._toggle_notification_feed() + _check( + main.feed_open and scene_feed.visible and not main.player.input_enabled, + "P5.10 opening the feed locks world input" + ) + scene_feed._unhandled_input(_key_event(KEY_ESCAPE)) + _check( + not main.feed_open and not scene_feed.visible and main.player.input_enabled, + "P5.10 closing the feed restores world input" + ) + main.queue_free() + await process_frame + + var user_files_before := DirAccess.get_files_at(OS.get_user_data_dir()) + var user_dirs_before := DirAccess.get_directories_at(OS.get_user_data_dir()) + + var panel: CanvasLayer = CanvasLayer.new() + panel.set_script(NotificationFeedScript) + root.add_child(panel) + await process_frame + + # --- conservative start state --- + _check(not panel.visible, "P5.10 the feed panel starts hidden") + _check(panel._title.text.contains("WAITING"), "P5.10 the feed panel starts in a typed waiting state") + _check(panel._counter.text == "0/0", "P5.10 the position counter starts at zero") + + # --- explicit availability states --- + panel.set_availability("unavailable") + _check(panel._title.text.contains("NO FEED"), "P5.10 a missing feed is labelled explicitly") + panel.set_availability("restricted") + _check(panel._title.text.contains("RESTRICTED"), "P5.10 a monitor-restricted feed is labelled explicitly") + panel.set_availability("available") + _check( + panel._title.text.contains("FEED") and not panel._title.text.contains("NO FEED"), + "P5.10 an available feed is labelled explicitly" + ) + panel.set_availability("unknown") + _check(panel._title.text.contains("WAITING"), "P5.10 unknown availability falls back to waiting") + + # --- empty feeds are explicit, never guessed --- + panel.update_feed(_feed([], 1)) + _check( + String(panel._rows[0]["summary"].text) == "NO NOTIFICATIONS", + "P5.10 an empty feed states it explicitly rather than guessing" + ) + _check( + panel.selected_index == -1 and panel.scroll_offset == 0, + "P5.10 an empty feed has no selection" + ) + + # --- entries are ordered newest first --- + panel.update_feed(_feed([ + _entry("notification:old", "Old summary", "Old body", "normal", 1000), + _entry("notification:urgent", "Disk space low", "Root partition 95% full", "critical", 3000, "Backup Tool"), + _entry("notification:quiet", "Quiet summary", "", "low", 2000), + ], 2)) + _check(panel.entries.size() == 3, "P5.10 feed entries are tracked") + _check( + String(panel.entries[0].get("handle")) == "notification:urgent" + and String(panel.entries[1].get("handle")) == "notification:quiet" + and String(panel.entries[2].get("handle")) == "notification:old", + "P5.10 entries render newest first" + ) + + # --- urgency cues that never rely on color alone --- + panel.open() + _check( + panel.visible and panel.selected_index == 0, + "P5.10 open() reveals the feed with the newest entry selected" + ) + _check( + String(panel._rows[0]["summary"].text).begins_with(">!! "), + "P5.10 critical entries carry a cursor plus double-bang marker" + ) + _check( + String(panel._rows[0]["detail"].text).begins_with("CRIT // BACKUP TOOL // Root partition 95% full"), + "P5.10 critical entries spell the urgency level and app name" + ) + panel._unhandled_input(_key_event(KEY_DOWN)) + panel._unhandled_input(_key_event(KEY_DOWN)) + _check( + String(panel._rows[0]["summary"].text).begins_with(" !! "), + "P5.10 unselected critical entries keep the marker column" + ) + _check( + String(panel._rows[1]["summary"].text).begins_with(" . "), + "P5.10 low entries carry the dot marker" + ) + _check( + String(panel._rows[1]["detail"].text).begins_with("LOW // VELORA"), + "P5.10 low entries spell the urgency level and omit empty bodies" + ) + _check( + String(panel._rows[2]["summary"].text).begins_with(">! "), + "P5.10 normal entries carry a single-bang marker under the cursor" + ) + _check( + String(panel._rows[2]["detail"].text).begins_with("NORM // VELORA // Old body"), + "P5.10 normal entries spell the urgency level" + ) + _check( + panel._counter.text == "3/3", + "P5.10 the counter reports the selected position and total" + ) + + # --- keyboard-only scrolling across a longer feed --- + var scroll_feed: Array = [] + for index in range(12): + scroll_feed.append(_entry( + "notification:scroll-%d" % index, + "Entry %d" % index, + "Body %d" % index, + "normal", + 2000 - index * 10 + )) + panel.update_feed(_feed(scroll_feed, 3)) + panel.open() + _check( + panel.selected_index == 0 and panel._counter.text == "1/12", + "P5.10 reopening resets to the newest entry" + ) + panel._unhandled_input(_key_event(KEY_DOWN)) + _check( + panel.selected_index == 1 and panel.scroll_offset == 0, + "P5.10 arrow keys scroll within the visible window" + ) + for _step in range(4): + panel._unhandled_input(_key_event(KEY_DOWN)) + _check( + panel.selected_index == 5 and panel.scroll_offset == 2, + "P5.10 the visible window follows the selection downward" + ) + _check( + String(panel._rows[0]["summary"].text).begins_with(" ! Entry 2"), + "P5.10 the top row shows the scrolled window start" + ) + _check( + String(panel._rows[3]["summary"].text).begins_with(">! Entry 5"), + "P5.10 the selected row shows the cursor" + ) + panel._unhandled_input(_key_event(KEY_UP)) + _check(panel.selected_index == 4, "P5.10 arrow keys scroll back up") + panel._unhandled_input(_key_event(KEY_END)) + _check( + panel.selected_index == 11 and panel.scroll_offset == 8, + "P5.10 End jumps to the oldest entry" + ) + panel._unhandled_input(_key_event(KEY_DOWN)) + _check(panel.selected_index == 0, "P5.10 scrolling wraps forward past the end") + panel._unhandled_input(_key_event(KEY_UP)) + _check(panel.selected_index == 11, "P5.10 scrolling wraps backward past the start") + panel._unhandled_input(_key_event(KEY_HOME)) + _check( + panel.selected_index == 0 and panel.scroll_offset == 0, + "P5.10 Home jumps to the newest entry" + ) + panel._unhandled_input(_key_event(KEY_PAGEDOWN)) + _check(panel.selected_index == 4, "P5.10 Page Down scrolls a full window") + panel._unhandled_input(_key_event(KEY_PAGEUP)) + _check(panel.selected_index == 0, "P5.10 Page Up scrolls a full window back") + panel._unhandled_input(_key_event(KEY_S)) + _check(panel.selected_index == 1, "P5.10 W and S mirror the arrow keys") + + # --- closing --- + var close_count := [0] + panel.feed_closed.connect(func() -> void: + close_count[0] += 1 + ) + panel._unhandled_input(_key_event(KEY_ESCAPE)) + _check( + not panel.visible and close_count[0] == 1, + "P5.10 Escape closes the feed" + ) + panel.open() + panel._unhandled_input(_key_event(KEY_N)) + _check( + not panel.visible and close_count[0] == 2, + "P5.10 N closes the feed" + ) + + # --- spam never reflows the layout --- + panel.update_feed(_feed(scroll_feed, 4)) + panel.open() + await process_frame + var panel_rect: Rect2 = panel._panel.get_rect() + var row_height: float = panel._rows[0]["panel"].get_rect().size.y + _check( + panel_rect.position == Vector2(40, 24) + and panel_rect.end.x <= 320.0 + and panel_rect.end.y <= 180.0, + "P5.10 the fixed panel always fits the 320 x 180 canvas" + ) + for burst in range(60): + var count := burst % 33 + var flood: Array = [] + for index in range(count): + flood.append(_entry( + "notification:flood-%d-%d" % [burst, index], + "Summary %d %s" % [index, "x".repeat(index * 8)], + "Body %d %s" % [index, "y".repeat(index * 8)], + ["low", "normal", "critical"][index % 3], + index * 10 + )) + panel.update_feed(_feed(flood, 100 + burst)) + await process_frame + _check( + panel._panel.get_rect() == panel_rect, + "P5.10 rapid feed bursts never reflow the panel geometry" + ) + _check( + panel._rows_box.get_child_count() == NotificationFeedScript.MAX_VISIBLE_ENTRIES, + "P5.10 the row structure stays fixed under spam" + ) + _check( + panel._rows[0]["panel"].get_rect().size.y == row_height, + "P5.10 row heights stay fixed under spam" + ) + + # --- maximum-length content is clipped, never overflowing --- + var max_summary := "s".repeat(256) + var max_body := "b".repeat(256) + panel.update_feed(_feed([ + _entry("notification:long", max_summary, max_body, "critical", 9000), + ], 200)) + await process_frame + var long_row: Dictionary = panel._rows[0] + _check( + bool(long_row["summary"].clip_text) and int(long_row["summary"].text_overrun_behavior) == 3, + "P5.10 long summaries clip with word ellipsis" + ) + _check( + bool(long_row["detail"].clip_text) and int(long_row["detail"].text_overrun_behavior) == 3, + "P5.10 long bodies clip with word ellipsis" + ) + _check( + long_row["panel"].get_rect().size.y == row_height, + "P5.10 maximum-length entries never grow a row" + ) + _check( + panel._panel.get_rect() == panel_rect, + "P5.10 maximum-length entries never change the panel geometry" + ) + var all_clipped := true + for row in panel._rows: + all_clipped = all_clipped and bool(row["summary"].clip_text) and bool(row["detail"].clip_text) + _check(all_clipped, "P5.10 every feed label clips by construction") + + # --- selection follows entries across updates --- + panel.update_feed(_feed([ + _entry("notification:older", "Older entry", "Older body", "normal", 100), + _entry("notification:newer", "Newer entry", "", "low", 200), + ], 300)) + panel.open() + panel._unhandled_input(_key_event(KEY_DOWN)) + _check(panel.selected_index == 1, "P5.10 the second newest entry can be selected") + panel.update_feed(_feed([ + _entry("notification:latest", "Latest entry", "", "critical", 300), + _entry("notification:newer", "Newer entry updated", "", "low", 201), + _entry("notification:older", "Older entry", "Older body", "normal", 100), + ], 301)) + _check( + panel.selected_index == 2 + and String(panel.entries[panel.selected_index].get("handle")) == "notification:older", + "P5.10 selection follows the entry handle across feed updates" + ) + panel.update_feed(_feed([ + _entry("notification:fresh", "Fresh entry", "", "normal", 400), + ], 302)) + _check( + panel.selected_index == 0 and panel._counter.text == "1/1", + "P5.10 a vanished selection clamps to a valid entry" + ) + + # --- stale-but-labelled and malformed feeds --- + panel.set_availability("restricted") + _check( + panel._title.text.contains("RESTRICTED") and panel.entries.size() == 1, + "P5.10 restricted monitoring keeps last-good entries labelled as stale" + ) + panel.update_feed({"sequence": 500, "notifications": "not-an-array"}) + _check(panel.entries.size() == 1, "P5.10 malformed feeds never replace last-good state") + panel.update_feed(_feed([ + {"handle": "", "app_name": "X", "summary": "Y", "body": "", "urgency": "low", "timestamp_unix_ms": 1}, + _entry("notification:valid", "Valid entry", "", "low", 900), + ], 501)) + _check( + panel.entries.size() == 1 and String(panel.entries[0].get("handle")) == "notification:valid", + "P5.10 entries without handles are dropped while valid frames replace state" + ) + panel.set_availability("unavailable") + _check( + panel._title.text.contains("NO FEED") and panel.entries.size() == 1, + "P5.10 unavailability labels stale entries instead of clearing them" + ) + + # --- reduced motion: every state change is instant, never animated --- + panel.set_availability("available") + panel.update_feed(_feed([ + _entry("notification:motion-a", "Motion A", "", "normal", 600), + _entry("notification:motion-b", "Motion B", "", "normal", 700), + ], 600)) + panel.open() + panel._unhandled_input(_key_event(KEY_DOWN)) + _check( + panel._rows[1]["style"].bg_color == NotificationFeedScript.ROW_BG_SELECTED, + "P5.10 selection applies in the same frame with no animated transition" + ) + panel._unhandled_input(_key_event(KEY_UP)) + _check( + panel._rows[0]["style"].bg_color == NotificationFeedScript.ROW_BG_SELECTED + and panel._rows[1]["style"].bg_color == NotificationFeedScript.ROW_BG, + "P5.10 deselection is equally instant" + ) + + # --- nothing persists across restarts --- + var panel_source := FileAccess.get_file_as_string("res://ui/notification_feed.gd") + for banned in [ + "FileAccess", + "ConfigFile", + "ResourceSaver", + "user://", + "store_", + "save_", + "Tween", + "create_tween", + "AnimationPlayer", + ]: + _check(not panel_source.contains(banned), "P5.10 the panel never uses %s" % banned) + var user_files_after := DirAccess.get_files_at(OS.get_user_data_dir()) + var user_dirs_after := DirAccess.get_directories_at(OS.get_user_data_dir()) + _check( + user_files_before == user_files_after and user_dirs_before == user_dirs_after, + "P5.10 a full inspection cycle writes nothing to user data" + ) + var restarted: CanvasLayer = CanvasLayer.new() + restarted.set_script(NotificationFeedScript) + root.add_child(restarted) + await process_frame + _check( + restarted.entries.is_empty() + and restarted.selected_index == -1 + and restarted._title.text.contains("WAITING"), + "P5.10 a fresh instance starts empty: nothing survives a restart" + ) + restarted.queue_free() + await process_frame + + panel.queue_free() + await process_frame + if failures.is_empty(): + print("P5.10 notification feed validation passed.") + quit(0) + else: + push_error("P5.10 notification feed validation failed: %s" % [failures]) + quit(1) diff --git a/frontend/godot/ui/media_console.gd b/frontend/godot/ui/media_console.gd new file mode 100644 index 0000000..4a297bb --- /dev/null +++ b/frontend/godot/ui/media_console.gd @@ -0,0 +1,568 @@ +extends CanvasLayer + +signal control_requested(player_handle: String, verb: String) +signal console_closed + +# P5.08 media console panel. +# +# Renders the BackendClient media snapshot in a fixed panel: keyboard-only +# player selection, color-independent status and active-player cues, and +# strict clipping so long identities and titles can never overflow the +# 320 x 180 canvas. Controls travel only as opaque snapshot-issued player +# handles plus the six allowlisted verbs; bus names, method names, raw +# arguments, and shell commands never appear on this side of the boundary. +# All state is memory-only and every state change is applied instantly with +# no animated transitions, so the panel writes nothing to disk and the +# reduced-motion guarantee holds by construction. + +const TONE_COLORS := { + "ready": Color("9af4e7"), + "waiting": Color("f5b943"), + "failure": Color("e05a67"), +} +const TEXT_COLOR := Color("dce4f0") +const DIM_COLOR := Color("586a80") +const ROW_BG := Color("0c1c33") +const ROW_BG_SELECTED := Color("16324f") +# Status never relies on color alone: every level renders a distinct marker +# glyph plus its spelled name, and color is only a secondary channel. An +# unrecognized status is labelled UNKNOWN instead of being guessed. +const STATUS_MARKERS := { + "playing": "+", + "paused": "=", + "stopped": ".", +} +const STATUS_LABELS := { + "playing": "PLAY", + "paused": "PAUSE", + "stopped": "STOP", +} +const STATUS_COLORS := { + "playing": Color("9af4e7"), + "paused": Color("f5b943"), + "stopped": Color("586a80"), +} +const VERB_LABELS := { + "play": "PLAY", + "pause": "PAUSE", + "play_pause": "PLAY/PAUSE", + "stop": "STOP", + "next": "NEXT", + "previous": "PREVIOUS", +} +# How many play/pause capabilities a player advertises. The single toggle key +# resolves to exactly one of the three play/pause verbs using this ratio, so +# the console never emits a verb the player cannot honour and Core will never +# have to reject. Core applies the identical table (media_store::verb_supported). +const TOGGLE_BOTH := 2 +const TOGGLE_PLAY_ONLY := 1 +const TOGGLE_PAUSE_ONLY := -1 +const TOGGLE_NONE := 0 +const MAX_VISIBLE_PLAYERS := 3 +# Mirrors the protocol player ceiling (BackendClient.MAX_MEDIA_PLAYERS) so a +# mis-wired source can never grow the tracked set beyond the v5 bound. +const MAX_TRACKED_PLAYERS := 16 + +var players: Array[Dictionary] = [] +var selected_index := -1 +var scroll_offset := 0 +var availability := "waiting" +var active_handle := "" + +var _panel: PanelContainer +var _title: Label +var _counter: Label +var _rows_box: VBoxContainer +var _feedback: Label +var _hint: Label +var _rows: Array[Dictionary] = [] + +func _ready() -> void: + visible = false + _build_ui() + +func _unhandled_input(event: InputEvent) -> void: + if not visible: + return + if event is InputEventKey and event.pressed and not event.echo: + match event.keycode: + KEY_ESCAPE, KEY_P: + get_viewport().set_input_as_handled() + close() + KEY_UP, KEY_W: + get_viewport().set_input_as_handled() + _move_selection(-1) + KEY_DOWN, KEY_S: + get_viewport().set_input_as_handled() + _move_selection(1) + KEY_PAGEUP: + get_viewport().set_input_as_handled() + _move_selection(-MAX_VISIBLE_PLAYERS) + KEY_PAGEDOWN: + get_viewport().set_input_as_handled() + _move_selection(MAX_VISIBLE_PLAYERS) + KEY_HOME: + get_viewport().set_input_as_handled() + _select_index(0) + KEY_END: + get_viewport().set_input_as_handled() + _select_index(players.size() - 1) + KEY_SPACE, KEY_E, KEY_ENTER, KEY_KP_ENTER: + get_viewport().set_input_as_handled() + _request_toggle() + KEY_N, KEY_RIGHT, KEY_D: + get_viewport().set_input_as_handled() + _request_verb("next") + KEY_B, KEY_LEFT, KEY_A: + get_viewport().set_input_as_handled() + _request_verb("previous") + KEY_X: + get_viewport().set_input_as_handled() + _request_verb("stop") + # All six allowlisted verbs are keyboard reachable. Standalone + # Play and Pause ride the numpad play/pause glyphs, which the + # world menu already uses for its numeric shortcuts, while + # the primary keys resolve the same verbs from capability. + KEY_KP_0: + get_viewport().set_input_as_handled() + _request_verb("play") + KEY_KP_2: + get_viewport().set_input_as_handled() + _request_verb("pause") + +func open() -> void: + visible = true + _set_feedback("", "ready") + _select_index(_default_selection()) + +func close() -> void: + visible = false + console_closed.emit() + +func toggle() -> void: + if visible: + close() + else: + open() + +func set_availability(next_availability: String) -> void: + availability = next_availability + _refresh_title() + +# Consumes a client-normalized media snapshot. Last-good players are kept +# across malformed frames and stale availability so the console keeps +# showing stale-but-labelled state instead of going blank; the client's +# sequence fencing guarantees this method only runs for newer frames. +func update_media(snapshot: Dictionary) -> void: + var raw_players = snapshot.get("players", null) + if not raw_players is Array: + return + if raw_players.size() > MAX_TRACKED_PLAYERS: + return + var selected_handle := _selected_handle() + players.clear() + var seen_handles := {} + for raw_player in raw_players: + if not raw_player is Dictionary: + continue + var handle := String(raw_player.get("handle", "")) + if handle.is_empty() or seen_handles.has(handle): + continue + seen_handles[handle] = true + players.append({ + "handle": handle, + "identity": _as_text(raw_player.get("identity", null), ""), + "status": _as_text(raw_player.get("status", null), ""), + "title": _as_text(raw_player.get("title", null), ""), + "artist": _as_text(raw_player.get("artist", null), ""), + "album": _as_text(raw_player.get("album", null), ""), + "length_micros": _as_micros(raw_player.get("length_micros", null), -1), + "position_micros": _as_micros(raw_player.get("position_micros", null), 0), + "can_play": bool(raw_player.get("can_play", false)), + "can_pause": bool(raw_player.get("can_pause", false)), + "can_go_next": bool(raw_player.get("can_go_next", false)), + "can_go_previous": bool(raw_player.get("can_go_previous", false)), + "can_seek": bool(raw_player.get("can_seek", false)), + "can_control": bool(raw_player.get("can_control", false)), + }) + active_handle = _as_text(snapshot.get("active_player_handle", null), "") + _preserve_selection(selected_handle) + +# Correlated control outcomes arrive through the client's typed signals. +func apply_control_accepted(_player_handle: String, verb: String) -> void: + _set_feedback("%s OK" % VERB_LABELS.get(verb, verb.to_upper()), "ready") + +func apply_control_rejected( + _player_handle: String, + _verb: String, + _code: String, + message: String, + retryable: bool +) -> void: + _set_feedback(message, "waiting" if retryable else "failure") + +func _default_selection() -> int: + if not active_handle.is_empty(): + for index in range(players.size()): + if String(players[index].get("handle", "")) == active_handle: + return index + return 0 if not players.is_empty() else -1 + +func _selected_handle() -> String: + if selected_index >= 0 and selected_index < players.size(): + return String(players[selected_index].get("handle", "")) + return "" + +func _selected_player() -> Dictionary: + if selected_index >= 0 and selected_index < players.size(): + return players[selected_index] + return {} + +func _preserve_selection(handle: String) -> void: + if not handle.is_empty(): + for index in range(players.size()): + if String(players[index].get("handle", "")) == handle: + _select_index(index) + return + _select_index(_default_selection()) + +func _move_selection(step: int) -> void: + if players.is_empty(): + return + if selected_index < 0: + _select_index(0) + return + var count := players.size() + var next_index := selected_index + step + while next_index < 0: + next_index += count + _select_index(next_index % count) + +func _select_index(index: int) -> void: + if players.is_empty(): + selected_index = -1 + scroll_offset = 0 + _refresh_rows() + return + selected_index = clampi(index, 0, players.size() - 1) + if selected_index < scroll_offset: + scroll_offset = selected_index + elif selected_index >= scroll_offset + MAX_VISIBLE_PLAYERS: + scroll_offset = selected_index - MAX_VISIBLE_PLAYERS + 1 + scroll_offset = clampi(scroll_offset, 0, maxi(0, players.size() - MAX_VISIBLE_PLAYERS)) + _refresh_rows() + +func _refresh_title() -> void: + match availability: + "available": + _title.text = "MEDIA // PLAYERS" + _title.add_theme_color_override("font_color", TONE_COLORS["ready"]) + "unavailable": + _title.text = "MEDIA // NO SERVICE" + _title.add_theme_color_override("font_color", TONE_COLORS["failure"]) + _: + _title.text = "MEDIA // WAITING" + _title.add_theme_color_override("font_color", TONE_COLORS["waiting"]) + +# Emits one allowlisted verb for the selected player's opaque handle. The +# verb is gated on the snapshot's capability flags so unsupported controls +# fail closed here instead of crossing IPC to be rejected by Core. +func _request_verb(verb: String) -> void: + if players.is_empty(): + _set_feedback("NO PLAYERS", "failure") + return + var player := _selected_player() + if player.is_empty(): + _set_feedback("NO PLAYERS", "failure") + return + if not _verb_allowed(player, verb): + _set_feedback("CONTROL NOT AVAILABLE", "failure") + return + _set_feedback("%s SENT" % VERB_LABELS.get(verb, verb.to_upper()), "waiting") + control_requested.emit(String(player.get("handle", "")), verb) + +# The toggle key resolves to the exact play/pause verb the player advertises +# rather than always forcing the combined verb, so every one of the six +# allowlisted verbs is keyboard reachable and no keypress ever emits a verb +# Core would reject. +func _request_toggle() -> void: + if players.is_empty(): + _set_feedback("NO PLAYERS", "failure") + return + var player := _selected_player() + if player.is_empty(): + _set_feedback("NO PLAYERS", "failure") + return + _request_verb(_toggle_verb(player)) + +func _toggle_verb(player: Dictionary) -> String: + match _toggle_ratio(player): + TOGGLE_BOTH: + return "play_pause" + TOGGLE_PLAY_ONLY: + return "play" + TOGGLE_PAUSE_ONLY: + return "pause" + return "" + +func _toggle_ratio(player: Dictionary) -> int: + var can_play := bool(player.get("can_play", false)) + var can_pause := bool(player.get("can_pause", false)) + if can_play and can_pause: + return TOGGLE_BOTH + if can_play: + return TOGGLE_PLAY_ONLY + if can_pause: + return TOGGLE_PAUSE_ONLY + return TOGGLE_NONE + +# Core re-maps each verb onto its MPRIS method, and media_store::verb_supported +# gates PlayPause on both can_play AND can_pause. This table mirrors Core +# exactly, so the console and the Core dispatcher can never disagree; a +# player that can only play is started with the standalone play verb instead +# of a combined toggle Core would reject. MPRIS has no CanStop flag, so Stop +# is gated by the master CanControl alone, again identically to Core. +func _verb_allowed(player: Dictionary, verb: String) -> bool: + if not VERB_LABELS.has(verb): + return false + if not bool(player.get("can_control", false)): + return false + match verb: + "play": + return bool(player.get("can_play", false)) + "pause": + return bool(player.get("can_pause", false)) + "play_pause": + return bool(player.get("can_play", false)) and bool(player.get("can_pause", false)) + "next": + return bool(player.get("can_go_next", false)) + "previous": + return bool(player.get("can_go_previous", false)) + "stop": + return true + return false + +func _set_feedback(message: String, tone: String) -> void: + _feedback.text = message + _feedback.add_theme_color_override("font_color", TONE_COLORS.get(tone, TONE_COLORS["ready"])) + +func _refresh_rows() -> void: + if players.is_empty(): + for row_index in range(_rows.size()): + _apply_row( + _rows[row_index], + "NO PLAYERS" if row_index == 0 else "", + "", + DIM_COLOR, + false + ) + _refresh_counter() + _refresh_hint() + return + for row_index in range(_rows.size()): + var row := _rows[row_index] + var player_index := scroll_offset + row_index + if player_index >= players.size(): + _apply_row(row, "", "", DIM_COLOR, false) + continue + var player := players[player_index] + _apply_row( + row, + _build_summary(player_index, player), + _build_detail(player), + _status_color(String(player.get("status", ""))), + player_index == selected_index + ) + _refresh_counter() + _refresh_hint() + +func _build_summary(player_index: int, player: Dictionary) -> String: + var status := String(player.get("status", "")) + var marker: String = STATUS_MARKERS.get(status, "?") + var is_selected := player_index == selected_index + var is_active := String(player.get("handle", "")) == active_handle + var identity := String(player.get("identity", "")).to_upper() + if identity.is_empty(): + identity = "UNKNOWN PLAYER" + return "%s%s%s %s" % [ + ">" if is_selected else " ", + marker, + "@" if is_active else " ", + identity, + ] + +func _build_detail(player: Dictionary) -> String: + var status := String(player.get("status", "")) + var parts: Array[String] = [String(STATUS_LABELS.get(status, "UNKNOWN"))] + if String(player.get("handle", "")) == active_handle: + parts.append("ACTIVE") + var title := String(player.get("title", "")) + parts.append("UNTITLED" if title.is_empty() else title) + for metadata in ["artist", "album"]: + var value := String(player.get(metadata, "")) + if not value.is_empty(): + parts.append(value) + var position_micros := int(player.get("position_micros", 0)) + var length_micros := int(player.get("length_micros", -1)) + var time_text := "%s / %s" % [ + _format_time(position_micros), + _format_time(length_micros) if length_micros >= 0 else "--:--", + ] + parts.append(time_text) + return " // ".join(parts) + +func _format_time(micros: int) -> String: + var total_seconds := micros / 1000000 + return "%d:%02d" % [total_seconds / 60, total_seconds % 60] + +func _status_color(status: String) -> Color: + return STATUS_COLORS.get(status, TEXT_COLOR) + +func _refresh_hint() -> void: + var parts: Array[String] = [] + if not players.is_empty(): + var player := _selected_player() + if not player.is_empty(): + # The toggle hint names the exact verb the key will fire for this + # player, so the label and the wire request can never disagree. + var toggle_verb := _toggle_verb(player) + if not toggle_verb.is_empty() and _verb_allowed(player, toggle_verb): + parts.append("SPACE %s" % VERB_LABELS[toggle_verb]) + if _verb_allowed(player, "stop"): + parts.append("X STOP") + if _verb_allowed(player, "next"): + parts.append("N NEXT") + if _verb_allowed(player, "previous"): + parts.append("B PREV") + if parts.is_empty(): + parts.append("NO CONTROLS") + parts.append("P CLOSE") + _hint.text = " ".join(parts) + +func _apply_row( + row: Dictionary, + summary_text: String, + detail_text: String, + summary_color: Color, + is_selected: bool +) -> void: + row["style"].bg_color = ROW_BG_SELECTED if is_selected else ROW_BG + row["summary"].text = summary_text + row["summary"].add_theme_color_override("font_color", summary_color) + row["detail"].text = detail_text + +func _refresh_counter() -> void: + if selected_index < 0 or players.is_empty(): + _counter.text = "0/0" + else: + _counter.text = "%d/%d" % [selected_index + 1, players.size()] + +func _as_micros(value: Variant, fallback: int) -> int: + if value is float or value is int: + return int(value) + return fallback + +# Strings are coerced defensively: the client normalizes snapshots before they +# reach the console, but a non-string field degrades to its default instead +# of crashing or guessing. +func _as_text(value: Variant, fallback: String) -> String: + if value is String: + return value + return fallback + +func _build_ui() -> void: + var shade := ColorRect.new() + shade.name = "Shade" + shade.color = Color(0.027451, 0.039216, 0.07451, 0.901961) + shade.set_anchors_preset(Control.PRESET_FULL_RECT) + add_child(shade) + + _panel = PanelContainer.new() + _panel.position = Vector2(40, 24) + _panel.custom_minimum_size = Vector2(240, 0) + add_child(_panel) + + var margin := MarginContainer.new() + margin.add_theme_constant_override("margin_left", 8) + margin.add_theme_constant_override("margin_top", 5) + margin.add_theme_constant_override("margin_right", 8) + margin.add_theme_constant_override("margin_bottom", 5) + _panel.add_child(margin) + + var box := VBoxContainer.new() + box.add_theme_constant_override("separation", 4) + margin.add_child(box) + + var header := HBoxContainer.new() + box.add_child(header) + + _title = Label.new() + _title.text = "MEDIA // WAITING" + _title.add_theme_font_size_override("font_size", 8) + _title.add_theme_color_override("font_color", TONE_COLORS["waiting"]) + _title.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _title.clip_text = true + _title.text_overrun_behavior = 3 + header.add_child(_title) + + _counter = Label.new() + _counter.text = "0/0" + _counter.add_theme_font_size_override("font_size", 8) + _counter.add_theme_color_override("font_color", DIM_COLOR) + header.add_child(_counter) + + _rows_box = VBoxContainer.new() + _rows_box.add_theme_constant_override("separation", 2) + box.add_child(_rows_box) + + # The row structure is fixed and every row keeps the same two clipped + # lines regardless of content, so snapshot bursts can never reflow the + # panel. + for _row_index in range(MAX_VISIBLE_PLAYERS): + _rows.append(_build_row()) + + _feedback = Label.new() + _feedback.text = "" + _feedback.add_theme_font_size_override("font_size", 7) + _feedback.add_theme_color_override("font_color", DIM_COLOR) + _feedback.clip_text = true + _feedback.text_overrun_behavior = 3 + box.add_child(_feedback) + + _hint = Label.new() + _hint.text = "P CLOSE" + _hint.add_theme_font_size_override("font_size", 7) + _hint.add_theme_color_override("font_color", DIM_COLOR) + _hint.clip_text = true + _hint.text_overrun_behavior = 3 + box.add_child(_hint) + +func _build_row() -> Dictionary: + var row := PanelContainer.new() + var style := StyleBoxFlat.new() + style.bg_color = ROW_BG + style.content_margin_left = 4 + style.content_margin_right = 4 + style.content_margin_top = 2 + style.content_margin_bottom = 2 + row.add_theme_stylebox_override("panel", style) + _rows_box.add_child(row) + + var lines := VBoxContainer.new() + lines.add_theme_constant_override("separation", 0) + row.add_child(lines) + + var summary := Label.new() + summary.add_theme_font_size_override("font_size", 7) + summary.clip_text = true + summary.text_overrun_behavior = 3 + lines.add_child(summary) + + var detail := Label.new() + detail.add_theme_font_size_override("font_size", 7) + detail.add_theme_color_override("font_color", DIM_COLOR) + detail.clip_text = true + detail.text_overrun_behavior = 3 + lines.add_child(detail) + + return {"panel": row, "style": style, "summary": summary, "detail": detail} diff --git a/frontend/godot/ui/notification_feed.gd b/frontend/godot/ui/notification_feed.gd new file mode 100644 index 0000000..0448aa1 --- /dev/null +++ b/frontend/godot/ui/notification_feed.gd @@ -0,0 +1,341 @@ +extends CanvasLayer + +signal feed_closed + +# P5.10 notification feed panel. +# +# Renders the most recent BackendClient notification feed entries in a +# fixed panel: keyboard-only scrolling, color-independent urgency cues, and +# strict clipping so long summaries and bodies can never overflow the +# 320 x 180 canvas. All state is memory-only and every state change is +# applied instantly with no animated transitions, so the panel writes +# nothing to disk and the reduced-motion guarantee holds by construction. + +const TONE_COLORS := { + "ready": Color("9af4e7"), + "waiting": Color("f5b943"), + "failure": Color("e05a67"), +} +const DIM_COLOR := Color("586a80") +const ROW_BG := Color("0c1c33") +const ROW_BG_SELECTED := Color("16324f") +# Urgency never relies on color alone: every level renders a distinct marker +# glyph plus its spelled name, and color is only a secondary channel. +const URGENCY_MARKERS := { + "critical": "!!", + "normal": "!", + "low": ".", +} +const URGENCY_LABELS := { + "critical": "CRIT", + "normal": "NORM", + "low": "LOW", +} +const URGENCY_COLORS := { + "critical": Color("e05a67"), + "normal": Color("dce4f0"), + "low": Color("586a80"), +} +const FALLBACK_URGENCY := "normal" +const MAX_VISIBLE_ENTRIES := 4 +# Mirrors the protocol feed ceiling (BackendClient.MAX_NOTIFICATIONS) so a +# mis-wired source can never grow the tracked set beyond the v5 bound. +const MAX_TRACKED_ENTRIES := 32 + +var entries: Array[Dictionary] = [] +var selected_index := -1 +var scroll_offset := 0 +var availability := "waiting" + +var _panel: PanelContainer +var _title: Label +var _counter: Label +var _rows_box: VBoxContainer +var _hint: Label +var _rows: Array[Dictionary] = [] + +func _ready() -> void: + visible = false + _build_ui() + +func _unhandled_input(event: InputEvent) -> void: + if not visible: + return + if event is InputEventKey and event.pressed and not event.echo: + match event.keycode: + KEY_ESCAPE, KEY_N: + get_viewport().set_input_as_handled() + close() + KEY_UP, KEY_W: + get_viewport().set_input_as_handled() + _move_selection(-1) + KEY_DOWN, KEY_S: + get_viewport().set_input_as_handled() + _move_selection(1) + KEY_LEFT, KEY_A, KEY_PAGEUP: + get_viewport().set_input_as_handled() + _move_selection(-MAX_VISIBLE_ENTRIES) + KEY_RIGHT, KEY_D, KEY_PAGEDOWN: + get_viewport().set_input_as_handled() + _move_selection(MAX_VISIBLE_ENTRIES) + KEY_HOME: + get_viewport().set_input_as_handled() + _select_index(0) + KEY_END: + get_viewport().set_input_as_handled() + _select_index(entries.size() - 1) + +func open() -> void: + visible = true + _select_index(_default_selection()) + +func close() -> void: + visible = false + feed_closed.emit() + +func toggle() -> void: + if visible: + close() + else: + open() + +func set_availability(next_availability: String) -> void: + availability = next_availability + _refresh_title() + +func update_feed(feed: Dictionary) -> void: + var raw_entries = feed.get("notifications", null) + if not raw_entries is Array: + return + var selected_handle := _selected_handle() + entries.clear() + # Keep only the newest slice when a source exceeds the feed ceiling. + var start_index := maxi(0, raw_entries.size() - MAX_TRACKED_ENTRIES) + for raw_index in range(start_index, raw_entries.size()): + var raw_entry = raw_entries[raw_index] + if not raw_entry is Dictionary: + continue + var handle := String(raw_entry.get("handle", "")) + if handle.is_empty(): + continue + entries.append({ + "handle": handle, + "app_name": String(raw_entry.get("app_name", "")), + "summary": String(raw_entry.get("summary", "")), + "body": String(raw_entry.get("body", "")), + "urgency": String(raw_entry.get("urgency", "")), + "timestamp_unix_ms": int(raw_entry.get("timestamp_unix_ms", 0)), + }) + entries.sort_custom(_newest_first) + _preserve_selection(selected_handle) + +func _default_selection() -> int: + return 0 if not entries.is_empty() else -1 + +func _selected_handle() -> String: + if selected_index >= 0 and selected_index < entries.size(): + return String(entries[selected_index].get("handle", "")) + return "" + +func _preserve_selection(handle: String) -> void: + if not handle.is_empty(): + for index in range(entries.size()): + if String(entries[index].get("handle", "")) == handle: + _select_index(index) + return + _select_index(selected_index) + +func _newest_first(a: Dictionary, b: Dictionary) -> bool: + var a_time := int(a.get("timestamp_unix_ms", 0)) + var b_time := int(b.get("timestamp_unix_ms", 0)) + if a_time != b_time: + return a_time > b_time + # Deterministic order for equal timestamps: sort by the opaque handle. + return String(a.get("handle", "")) < String(b.get("handle", "")) + +func _move_selection(step: int) -> void: + if entries.is_empty(): + return + if selected_index < 0: + _select_index(0) + return + var count := entries.size() + var next_index := selected_index + step + while next_index < 0: + next_index += count + _select_index(next_index % count) + +func _select_index(index: int) -> void: + if entries.is_empty(): + selected_index = -1 + scroll_offset = 0 + _refresh_rows() + return + selected_index = clampi(index, 0, entries.size() - 1) + if selected_index < scroll_offset: + scroll_offset = selected_index + elif selected_index >= scroll_offset + MAX_VISIBLE_ENTRIES: + scroll_offset = selected_index - MAX_VISIBLE_ENTRIES + 1 + scroll_offset = clampi(scroll_offset, 0, maxi(0, entries.size() - MAX_VISIBLE_ENTRIES)) + _refresh_rows() + +func _refresh_title() -> void: + match availability: + "available": + _title.text = "NOTIFICATIONS // FEED" + _title.add_theme_color_override("font_color", TONE_COLORS["ready"]) + "unavailable": + _title.text = "NOTIFICATIONS // NO FEED" + _title.add_theme_color_override("font_color", TONE_COLORS["failure"]) + "restricted": + _title.text = "NOTIFICATIONS // MONITOR RESTRICTED" + _title.add_theme_color_override("font_color", TONE_COLORS["failure"]) + _: + _title.text = "NOTIFICATIONS // WAITING" + _title.add_theme_color_override("font_color", TONE_COLORS["waiting"]) + +func _refresh_rows() -> void: + if entries.is_empty(): + for row_index in range(_rows.size()): + _apply_row( + _rows[row_index], + "NO NOTIFICATIONS" if row_index == 0 else "", + "", + DIM_COLOR, + false + ) + _refresh_counter() + return + for row_index in range(_rows.size()): + var row := _rows[row_index] + var entry_index := scroll_offset + row_index + if entry_index >= entries.size(): + _apply_row(row, "", "", DIM_COLOR, false) + continue + var entry := entries[entry_index] + var urgency := String(entry.get("urgency", "")) + if not URGENCY_MARKERS.has(urgency): + urgency = FALLBACK_URGENCY + var summary := String(entry.get("summary", "")) + if summary.is_empty(): + summary = "UNTITLED" + var app_name := String(entry.get("app_name", "")).to_upper() + if app_name.is_empty(): + app_name = "UNKNOWN APP" + var detail := "%s // %s" % [URGENCY_LABELS[urgency], app_name] + var body := String(entry.get("body", "")) + if not body.is_empty(): + detail += " // " + body + var is_selected := entry_index == selected_index + _apply_row( + row, + "%s%s %s" % [">" if is_selected else " ", URGENCY_MARKERS[urgency], summary], + detail, + URGENCY_COLORS[urgency], + is_selected + ) + _refresh_counter() + +func _apply_row( + row: Dictionary, + summary_text: String, + detail_text: String, + summary_color: Color, + is_selected: bool +) -> void: + row["style"].bg_color = ROW_BG_SELECTED if is_selected else ROW_BG + row["summary"].text = summary_text + row["summary"].add_theme_color_override("font_color", summary_color) + row["detail"].text = detail_text + +func _refresh_counter() -> void: + if selected_index < 0 or entries.is_empty(): + _counter.text = "0/0" + else: + _counter.text = "%d/%d" % [selected_index + 1, entries.size()] + +func _build_ui() -> void: + var shade := ColorRect.new() + shade.name = "Shade" + shade.color = Color(0.027451, 0.039216, 0.07451, 0.901961) + shade.set_anchors_preset(Control.PRESET_FULL_RECT) + add_child(shade) + + _panel = PanelContainer.new() + _panel.position = Vector2(40, 24) + _panel.custom_minimum_size = Vector2(240, 0) + add_child(_panel) + + var margin := MarginContainer.new() + margin.add_theme_constant_override("margin_left", 8) + margin.add_theme_constant_override("margin_top", 5) + margin.add_theme_constant_override("margin_right", 8) + margin.add_theme_constant_override("margin_bottom", 5) + _panel.add_child(margin) + + var box := VBoxContainer.new() + box.add_theme_constant_override("separation", 4) + margin.add_child(box) + + var header := HBoxContainer.new() + box.add_child(header) + + _title = Label.new() + _title.text = "NOTIFICATIONS // WAITING" + _title.add_theme_font_size_override("font_size", 8) + _title.add_theme_color_override("font_color", TONE_COLORS["waiting"]) + _title.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _title.clip_text = true + _title.text_overrun_behavior = 3 + header.add_child(_title) + + _counter = Label.new() + _counter.text = "0/0" + _counter.add_theme_font_size_override("font_size", 8) + _counter.add_theme_color_override("font_color", DIM_COLOR) + header.add_child(_counter) + + _rows_box = VBoxContainer.new() + _rows_box.add_theme_constant_override("separation", 2) + box.add_child(_rows_box) + + # The row structure is fixed and every row keeps the same two clipped + # lines regardless of content, so feed bursts can never reflow the panel. + for _row_index in range(MAX_VISIBLE_ENTRIES): + _rows.append(_build_row()) + + _hint = Label.new() + _hint.text = "ARROWS SCROLL N CLOSE" + _hint.add_theme_font_size_override("font_size", 7) + _hint.add_theme_color_override("font_color", DIM_COLOR) + box.add_child(_hint) + +func _build_row() -> Dictionary: + var row := PanelContainer.new() + var style := StyleBoxFlat.new() + style.bg_color = ROW_BG + style.content_margin_left = 4 + style.content_margin_right = 4 + style.content_margin_top = 2 + style.content_margin_bottom = 2 + row.add_theme_stylebox_override("panel", style) + _rows_box.add_child(row) + + var lines := VBoxContainer.new() + lines.add_theme_constant_override("separation", 0) + row.add_child(lines) + + var summary := Label.new() + summary.add_theme_font_size_override("font_size", 7) + summary.clip_text = true + summary.text_overrun_behavior = 3 + lines.add_child(summary) + + var detail := Label.new() + detail.add_theme_font_size_override("font_size", 7) + detail.add_theme_color_override("font_color", DIM_COLOR) + detail.clip_text = true + detail.text_overrun_behavior = 3 + lines.add_child(detail) + + return {"panel": row, "style": style, "summary": summary, "detail": detail} diff --git a/native/velora-bridge/src/lib.rs b/native/velora-bridge/src/lib.rs index 874c185..fc38e56 100644 --- a/native/velora-bridge/src/lib.rs +++ b/native/velora-bridge/src/lib.rs @@ -355,6 +355,15 @@ impl LineAccumulator { #[cfg(test)] mod tests { use super::*; + use velora_protocol::PROTOCOL_VERSION; + + #[test] + fn bridge_locks_to_the_exact_match_protocol_version() { + // The bridge is transport glue with no business logic, but it must be + // compiled against the same exact-match contract as Core and Godot. + // v5 bumps the media/notification contract; any version drift fails here. + assert_eq!(PROTOCOL_VERSION, 5); + } #[test] fn assembles_partial_and_multiple_lines() { diff --git a/scripts/check-core-resources.sh b/scripts/check-core-resources.sh index 42a79f4..3038fd4 100755 --- a/scripts/check-core-resources.sh +++ b/scripts/check-core-resources.sh @@ -32,6 +32,8 @@ echo "Building Core (release profile for representative idle cost)..." XDG_RUNTIME_DIR="$runtime_dir" \ HYPRLAND_INSTANCE_SIGNATURE= \ VELORA_SOCKET="$socket_path" \ +VELORA_MEDIA_ENABLED=false \ +VELORA_NOTIFICATIONS_ENABLED=false \ "$repo_dir/target/release/velora-core" & core_pid=$! diff --git a/scripts/check-dbus-resources.sh b/scripts/check-dbus-resources.sh new file mode 100755 index 0000000..0f23199 --- /dev/null +++ b/scripts/check-dbus-resources.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# P5.12 resource gate: compare Core with D-Bus integrations disabled and +# enabled on a private session bus. The test never contacts the live bus. +set -euo pipefail + +script_dir="$(cd "$(dirname "$0")" && pwd)" +repo_dir="$(cd "$script_dir/.." && pwd)" +test_dir="$(mktemp -d /tmp/velora-dbus-resources.XXXXXX)" +bus_pid="" +core_pid="" + +cleanup() { + if [[ -n "$core_pid" ]] && kill -0 "$core_pid" 2>/dev/null; then + kill -INT "$core_pid" 2>/dev/null || true + wait "$core_pid" 2>/dev/null || true + fi + if [[ -n "$bus_pid" ]] && kill -0 "$bus_pid" 2>/dev/null; then + kill "$bus_pid" 2>/dev/null || true + wait "$bus_pid" 2>/dev/null || true + fi + rm -rf "$test_dir" +} +trap cleanup EXIT + +command -v dbus-daemon >/dev/null 2>&1 || { + echo "missing dependency: dbus-daemon" >&2 + exit 1 +} + +mkdir -p "$test_dir/runtime" "$test_dir/data/applications" "$test_dir/system-data/applications" +chmod 700 "$test_dir/runtime" + +dbus-daemon --session --nofork --print-address=1 >"$test_dir/bus-address" 2>"$test_dir/bus.log" & +bus_pid=$! +for _attempt in {1..100}; do + [[ -s "$test_dir/bus-address" ]] && break + kill -0 "$bus_pid" 2>/dev/null || { cat "$test_dir/bus.log" >&2; exit 1; } + sleep 0.02 +done +[[ -s "$test_dir/bus-address" ]] || { echo "private D-Bus did not publish an address" >&2; exit 1; } +bus_address="$(head -n 1 "$test_dir/bus-address")" + +(cd "$repo_dir" && cargo build --release -p velora-core --quiet) + +start_core() { + local mode="$1" + local media_enabled="$2" + local notifications_enabled="$3" + local socket_path="$test_dir/runtime/velora-$mode.sock" + + XDG_RUNTIME_DIR="$test_dir/runtime" \ + XDG_DATA_HOME="$test_dir/data" \ + XDG_DATA_DIRS="$test_dir/system-data" \ + HYPRLAND_INSTANCE_SIGNATURE= \ + VELORA_SOCKET="$socket_path" \ + VELORA_SESSION_BUS_ADDRESS="$bus_address" \ + VELORA_TELEMETRY_ENABLED=false \ + VELORA_MEDIA_ENABLED="$media_enabled" \ + VELORA_NOTIFICATIONS_ENABLED="$notifications_enabled" \ + "$repo_dir/target/release/velora-core" >"$test_dir/core-$mode.log" 2>&1 & + core_pid=$! + + for _attempt in {1..100}; do + [[ -S "$socket_path" ]] && return 0 + kill -0 "$core_pid" 2>/dev/null || { cat "$test_dir/core-$mode.log" >&2; return 1; } + sleep 0.05 + done + cat "$test_dir/core-$mode.log" >&2 + return 1 +} + +rss_kib() { + awk '/VmRSS/ {print $2}' "/proc/$core_pid/status" +} + +stop_core() { + kill -INT "$core_pid" + wait "$core_pid" + core_pid="" +} + +start_core baseline false false +sleep 1 +baseline_rss="$(rss_kib)" +stop_core + +start_core active true true +sleep 1 +active_rss_early="$(rss_kib)" +read -r active_utime_early active_stime_early < <(awk '{print $14, $15}' "/proc/$core_pid/stat") +sleep 5 +active_rss_late="$(rss_kib)" +read -r active_utime_late active_stime_late < <(awk '{print $14, $15}' "/proc/$core_pid/stat") +stop_core + +clock_ticks="$(getconf CLK_TCK)" +cpu_ticks=$(( (active_utime_late - active_utime_early) + (active_stime_late - active_stime_early) )) +cpu_basis_points=$(( 10000 * cpu_ticks / (clock_ticks * 5) )) +dbus_overhead_kib=$(( active_rss_late - baseline_rss )) +active_growth_kib=$(( active_rss_late - active_rss_early )) + +echo "Private-bus idle CPU: $((cpu_basis_points / 100)).$((cpu_basis_points % 100))% of one core" +echo "Core RSS: baseline=${baseline_rss} KiB active=${active_rss_late} KiB overhead=${dbus_overhead_kib} KiB" +echo "Active D-Bus RSS growth: ${active_growth_kib} KiB" + +if (( cpu_basis_points > 50 )); then + echo "P5.12 gate failed: idle D-Bus CPU exceeds 0.50%" >&2 + exit 1 +fi +if (( dbus_overhead_kib > 3072 )); then + echo "P5.12 gate failed: fixed D-Bus RSS overhead exceeds the measured 3 MiB ceiling" >&2 + exit 1 +fi +if (( active_growth_kib > 1024 )); then + echo "P5.12 gate failed: active D-Bus RSS grew by more than 1 MiB" >&2 + exit 1 +fi + +echo "PASS: P5.12 media/notification resource budgets hold on a private bus" diff --git a/scripts/check-dev.sh b/scripts/check-dev.sh index 60ffa9c..b3132d6 100755 --- a/scripts/check-dev.sh +++ b/scripts/check-dev.sh @@ -20,6 +20,8 @@ export XDG_DATA_DIRS="$test_dir/system-data" export XDG_CONFIG_HOME="$test_dir/config" export XDG_CACHE_HOME="$test_dir/cache" export VELORA_SOCKET="$XDG_RUNTIME_DIR/velora.sock" +export VELORA_MEDIA_ENABLED=false +export VELORA_NOTIFICATIONS_ENABLED=false mkdir -p "$XDG_RUNTIME_DIR" "$XDG_DATA_HOME" "$XDG_DATA_DIRS" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" chmod 700 "$XDG_RUNTIME_DIR" diff --git a/scripts/check-godot.sh b/scripts/check-godot.sh index 6caf7c4..4cb92c9 100755 --- a/scripts/check-godot.sh +++ b/scripts/check-godot.sh @@ -44,3 +44,6 @@ run_godot launch-ux --script res://tests/launch_ux_validation.gd run_godot backend-client --script res://tests/backend_client_validation.gd run_godot workspace-map --script res://tests/workspace_map_validation.gd run_godot session-binding --script res://tests/session_binding_validation.gd +run_godot notification-feed --script res://tests/notification_validation.gd +run_godot media-client --script res://tests/media_client_validation.gd +run_godot media-console --script res://tests/media_validation.gd diff --git a/scripts/check-ipc.sh b/scripts/check-ipc.sh index 9d78782..c4ad08f 100755 --- a/scripts/check-ipc.sh +++ b/scripts/check-ipc.sh @@ -27,6 +27,8 @@ export XDG_DATA_DIRS="$test_dir/system-data" export XDG_CONFIG_HOME="$test_dir/config" export XDG_CACHE_HOME="$test_dir/cache" export VELORA_IPC_TEST_DIR="$test_dir" +export VELORA_MEDIA_ENABLED=false +export VELORA_NOTIFICATIONS_ENABLED=false mkdir -p \ "$XDG_RUNTIME_DIR" \ "$XDG_DATA_HOME/applications" \ diff --git a/scripts/check-phase-five.sh b/scripts/check-phase-five.sh new file mode 100755 index 0000000..db2128e --- /dev/null +++ b/scripts/check-phase-five.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# P5.12 cumulative release gate: retain every Phase 4 check, then enforce the +# private-bus resource budget introduced by Phase 5. +set -euo pipefail + +script_dir="$(cd "$(dirname "$0")" && pwd)" + +"$script_dir/check-phase-four.sh" +"$script_dir/check-dbus-resources.sh" + +echo "PASS: P5.12 Phase 5 release gate" diff --git a/scripts/check-security.sh b/scripts/check-security.sh index 8c770e1..e113548 100755 --- a/scripts/check-security.sh +++ b/scripts/check-security.sh @@ -20,4 +20,20 @@ reject_pattern "Rust must not spawn a shell" 'Command::new\([^)]*("|r#")?(sh|bas reject_pattern "Rust must not pass shell -c arguments" '\.arg\("-(c|lc)"\)' core/src native reject_pattern "Velora must not edit Hyprland or Omarchy configuration" '(hyprctl[[:space:]]+keyword|\.config/(hypr|omarchy))' core native frontend scripts --glob '!check-security.sh' -echo "PASS: P2.12 static security boundary checks" +# Every untyped zbus Proxy call in production must use one of the audited +# read methods or the fixed six-verb MPRIS mapper. Typed DBusProxy and +# MonitoringProxy calls remain constrained by their generated interfaces. +if rg -nUP '\.call(?:<[^>]+>)?\(\s*(?!player_method\(verb\)|"(?:GetServerInformation|GetNameOwner|GetAll)")' \ + core/src/dbus.rs core/src/mpris.rs; then + echo "P5.12 security gate failed: D-Bus method is outside the audited allowlist" >&2 + exit 1 +fi + +for method in Play Pause PlayPause Stop Next Previous; do + if ! rg -q "MediaControlVerb::${method} => \"${method}\"" core/src/mpris.rs; then + echo "P5.12 security gate failed: MPRIS allowlist mapping is incomplete for $method" >&2 + exit 1 + fi +done + +echo "PASS: P5.12 cumulative static security boundary checks" diff --git a/scripts/run-velora.sh b/scripts/run-velora.sh index 0db9dd6..974bed7 100755 --- a/scripts/run-velora.sh +++ b/scripts/run-velora.sh @@ -1,8 +1,5 @@ #!/usr/bin/env bash set -euo pipefail -if ! command -v godot >/dev/null 2>&1; then - echo "Godot 4 is required. Install it with: omarchy pkg add godot" >&2 - exit 1 -fi -cd "$(dirname "$0")/../frontend/godot" -exec godot --editor project.godot + +script_dir="$(cd "$(dirname "$0")" && pwd)" +exec "$script_dir/velora.sh" run diff --git a/scripts/velora.sh b/scripts/velora.sh index 3ee2425..787b3b4 100755 --- a/scripts/velora.sh +++ b/scripts/velora.sh @@ -19,7 +19,7 @@ Commands: build-bridge Build the native Unix-socket GDExtension ipc-check Run the live core ↔ Godot handshake test check Run Godot acceptance tests and Rust checks - gate Run the deterministic Phase 4 release gate + gate Run the cumulative deterministic Phase 5 release gate perf Run the rendered integrated-graphics benchmark all Run acceptance, Rust, IPC, and performance checks help Show this help @@ -64,7 +64,7 @@ case "$command_name" in "$script_dir/check-dev.sh" ;; gate) - exec "$script_dir/check-phase-four.sh" + exec "$script_dir/check-phase-five.sh" ;; perf|performance) "$script_dir/build-bridge.sh"