From 4386003e30b8f0c6a35c467ce73dbda25b573acd Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 14:17:51 -0700 Subject: [PATCH] feat(kwin): survive KWin restarting KWin can go away under a running daemon while the session bus stays: it crashed, or kwin_wayland --replace took its place. Its windows go with it, and so does the bridge, which would have reported them closing; in the spikes the old windows vanished without a single removed event. What the daemon does see is the bus, so the thread that serves the connection watches NameOwnerChanged for org.kde.KWin. When the name loses its owner, Table::compositor_lost marks every window closed and returns a Destroy for each, so the window manager takes them out of its layout, and their ids are not given out again. When the name has an owner again, the daemon loads the bridge into the new KWin, trying for up to 15 seconds while KWin is not ready for it, and the bridge reports the new desktop in a snapshot. zbus does not end a held call when its caller leaves the bus, so the Poll of the old bridge is still waiting when the new bridge calls, and it was woken first: it took the commands for the new KWin and answered them to nobody. vm-kwin-restart lost the tile of a window opened in the third KWin that way in one run of three, and a recording of the bus showed the batch going to the old bridge. A Poll held since before KWin last left the bus is answered with nothing and passes its wake-up on to the next call, which a unit test holds. The VM suite vm-kwin-restart (from the spike's spike7-resync) restarts the headless KWin twice under a running daemon, through Kde.restart_kwin in the VM library, and checks that the daemon sees KWin go, takes the old windows out of its layout, loads the bridge into the new KWin, and tiles the windows that open there. --- Cargo.lock | 13 ++ README.md | 2 +- docs/dev/ARCHITECTURE.md | 15 +++ docs/dev/DESIGN.md | 12 ++ docs/dev/PLATFORM.md | 17 ++- docs/dev/vm-tests.md | 2 + komorebi/Cargo.toml | 1 + komorebi/src/kwin/mod.rs | 114 ++++++++++++++-- komorebi/src/kwin/state.rs | 47 ++++++- nix/tests/vm/lib/komorebi_vm/kde.py | 11 ++ nix/tests/vm/lib/tests/test_kde.py | 22 ++++ nix/tests/vm/suites/kwin-restart/default.nix | 5 + nix/tests/vm/suites/kwin-restart/test.py | 131 +++++++++++++++++++ 13 files changed, 380 insertions(+), 12 deletions(-) create mode 100644 nix/tests/vm/suites/kwin-restart/default.nix create mode 100644 nix/tests/vm/suites/kwin-restart/test.py diff --git a/Cargo.lock b/Cargo.lock index 8f57b407..1474f253 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -601,6 +601,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "futures-task" version = "0.3.34" @@ -614,6 +625,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -949,6 +961,7 @@ dependencies = [ "crossbeam-channel", "ctrlc", "dirs", + "futures-util", "komorebi-layouts", "lazy_static", "nanoid", diff --git a/README.md b/README.md index b4cc9fe0..ae7bceef 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ KWin, the bridge, reports what KWin sees over the session bus, and carries out the commands it is given as the answer to a call it holds open. The daemon keeps a table of the windows and monitors from those reports, answers the window manager's questions from it, and turns each report into an event for the window -manager. +manager. If KWin restarts, the daemon loads the bridge into the new one. The window manager models the desktop as monitors, each with a ring of workspaces, each with a ring of containers, each with a ring of windows. A diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d82a0aac..1583aeb4 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -139,6 +139,16 @@ script: when it follows the focus, the backend invokes KWin's "Move Mouse to Foc which centers it on the window KWin has focused. When komorebi stops, the backend asks KWin to unload the bridge. +KWin can restart under a running daemon, on the same session bus. The thread that serves +the connection watches the owner of `org.kde.KWin` on the bus. When KWin leaves it, the +bridge has gone with it and its windows too, and nothing will report them closing: +[`Table::compositor_lost`] marks every window closed and returns a `Destroy` for each, so the +window manager takes them out of its layout. When KWin is back, the daemon loads the bridge +into it again, the bridge sends a snapshot of the new KWin's desktop, and its events are +handled as before. The `Poll` call the old bridge held is still open in the daemon, since +zbus does not end a call when its caller leaves the bus: it is answered with nothing as soon +as it wakes, and the commands go to the new bridge's call. + [`connect`] makes the backend: it connects to the session bus, loads the bridge into KWin, and returns once the snapshot has arrived, so that the window manager reads a full table when it starts. [PLATFORM.md](PLATFORM.md) has the D-Bus names, the files and the environment @@ -219,6 +229,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Every window is where komorebi asked for it, within the size its client keeps to | VM test | `vm-core-e2e`, `vm-client-geometry` | a client may refuse a size: the frame is what `window_rect` says | | A retile reaches KWin as one batch | framework path: the answer to `Poll` waits a millisecond after the first command for the others | `vm-latency` | none | | The window manager sees a frame it asked for at once | framework path: the KWin backend's `set_rect` records it in the table before KWin answers | `a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one` | none | +| A KWin that restarts gets the bridge again, and the windows of the old one leave the layout | framework path: the connection's thread watches `NameOwnerChanged` for `org.kde.KWin`, and the table destroys every window when the name is lost | `when_kwin_goes_away_every_window_it_had_is_destroyed`, `vm-kwin-restart` | none | +| After KWin restarts, the commands go to the new bridge | framework path: a `Poll` held since before KWin last left the bus is answered with nothing, and passes on the wake-up it got | `a_poll_held_by_the_bridge_of_a_kwin_that_has_gone_gets_no_commands`, `vm-kwin-restart` ("a window opened in the third KWin is tiled") | none | | The bridge holds no window manager logic | convention, with every decision about an event in the table, which the `kwin::state` unit tests pin | the unit tests in `komorebi/src/kwin/state.rs` | none | | What the bridge sends is what the table reads | type checker: the JSDoc types of the messages in [`bridge.js`]; tests: the events of [`fixtures`] are what the bridge's tests check it sends and what the table's tests feed it | `what the bridge sends for a session is what the daemon's tests read`, `the_bridges_events_for_a_session_are_the_window_events_komorebi_expects` | none | | What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | @@ -289,6 +301,8 @@ A window is shown, and ends up on a tile: events of a real KWin, through the daemon. - [`nix/tests/vm/suites/core-e2e`](../../nix/tests/vm/suites/core-e2e/test.py): the daemon tiling a real KWin, checked against what KWin has. +- [`nix/tests/vm/suites/kwin-restart`](../../nix/tests/vm/suites/kwin-restart/test.py): KWin + restarting under the daemon. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. @@ -320,6 +334,7 @@ A window is shown, and ends up on a tile: [`kwin::state`]: ../../komorebi/src/kwin/state.rs [`Table`]: ../../komorebi/src/kwin/state.rs [`Table::handle`]: ../../komorebi/src/kwin/state.rs +[`Table::compositor_lost`]: ../../komorebi/src/kwin/state.rs [`bridge.js`]: ../../komorebi/src/kwin/bridge.js [`kwin-api.d.ts`]: ../../komorebi/src/kwin/kwin-api.d.ts [`bridge.test.js`]: ../../komorebi/src/kwin/bridge.test.js diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index eb01257c..cf1a65cb 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -143,3 +143,15 @@ to the middle of the focused window, for two different windows. The backend asks KWin reports the window it focused as active, so the action finds the right one. The cost is that the pointer can go to the middle of the focused window and nowhere else, which is what komorebi asks for. + +## Why does komorebi take every window out of its layout when KWin leaves the session bus? + +Because nothing else will say that they have gone. When KWin goes away under a running +session (it crashed, or another KWin replaced it), its clients lose their connection and +their windows go with it, and so does the bridge, which would have reported them closing. In +the spikes KWin was killed and started again under a running daemon on the same bus, twice: +the old windows vanished without a single `removed` event. What the daemon does see is the +bus itself: `NameOwnerChanged` says that `org.kde.KWin` has lost its owner, and later that it +has a new one. So losing the name counts as every window closing, and getting it back as the +moment to load the bridge into the new KWin, which then reports its desktop as it does at +start. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 12fbcb6c..9d2a41ce 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -74,6 +74,18 @@ and carries the commands out in KWin, in order. The script API cannot move the p when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut, which puts the pointer in the middle of the window KWin has focused. +#### When KWin restarts + +KWin can go away while the session goes on: it crashed, or `kwin_wayland --replace` took its +place. The session bus stays, and the windows go with the old KWin. komorebi keeps running. It +watches who owns `org.kde.KWin` on the session bus, and when nobody does it takes every window +of the old KWin out of its layout, as if each had been closed: the bridge went with KWin, so +nothing reports them closing. When the name has an owner again, komorebi loads the bridge into +the new KWin, trying again for up to 15 seconds while KWin is not ready for it, and the bridge +reports the new KWin's windows and outputs as it does at start. A window that opens in the new +KWin is tiled. In the spikes the bridge was loaded again 1.0 to 1.1 seconds after the name had +an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a running daemon. + #### What komorebi leaves behind When it is stopped with `SIGINT` or `SIGTERM` it asks KWin to unload the script. The file @@ -120,8 +132,9 @@ What komorebi calls: | Name | Object | Interface | Member | When | |---|---|---|---|---| -| `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `unloadScript(s)`, `loadScript(ss) -> i` | at start; `unloadScript` again at exit | -| `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | at start | +| `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `unloadScript(s)`, `loadScript(ss) -> i` | at start, and when KWin is back after a restart; `unloadScript` again at exit | +| `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | after `loadScript` | +| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back | | `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | ## Files and directories diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index cce66e77..dd68907c 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -103,6 +103,8 @@ the run. - `start_komorebi(*args)` starts the daemon in the session, `stop_komorebi()` stops it with `SIGTERM`, `komorebi_log()` returns its log since it was last started, and `script_loaded()` asks KWin whether it runs the bridge. + `restart_kwin()` stops the session's KWin and starts a new one on the same + bus, as when the compositor of a running session crashes, and waits for it. - `daemon` reads the daemon's view of the desktop from that log, started with `--log-level debug`: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index f2ebecb6..d419f055 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -26,6 +26,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] } tracing = { workspace = true } tracing-subscriber = { workspace = true } zbus = { version = "5", default-features = false, features = ["tokio"] } +futures-util = "0.3" [features] default = ["schemars"] diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 24125ff7..f8e04377 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -27,6 +27,13 @@ //! window events of [`crate::window_manager_event`], and queues every command of [`Backend`] for //! the script, which carries it out in KWin. //! +//! KWin can go away under a running daemon (it crashed, or `kwin_wayland --replace` took its +//! place) while the session bus stays. The daemon watches who owns `org.kde.KWin` on the bus: +//! when nobody does, every window of the old KWin is gone, and nothing will report it closing, so +//! the table reports each as destroyed ([`state::Table::compositor_lost`]); when the name has an +//! owner again, the daemon loads the script into the new KWin, which reports its desktop as it +//! does at start. +//! //! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved, //! and `docs/dev/DESIGN.md` the reasons for this design. @@ -42,6 +49,7 @@ use crate::core::Rect; use crate::window_manager_event_listener; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use futures_util::StreamExt; use parking_lot::Condvar; use parking_lot::Mutex; use serde_json::Value; @@ -84,20 +92,23 @@ struct Shared { queue: Mutex>, wake: Notify, batch: AtomicU64, + /// how many times KWin has left the session bus. A `Poll` held since before then was made by a + /// script that went with its KWin, and is answered with nothing rather than with the commands + kwin_lost: AtomicU64, /// set once the script has reported its first snapshot ready: (Mutex, Condvar), cursor_waiters: Mutex>>, next_token: AtomicU64, handle: Handle, - /// false once the thread that runs the runtime has ended: the runtime is then being shut down, - /// and blocking on it panics + /// false once the thread that runs the runtime has ended, which is when KWin is gone: the + /// runtime is then being shut down, and blocking on it panics alive: AtomicBool, connection: Mutex>, } impl Shared { - /// Run something on the runtime and wait for it, unless the runtime is gone: once its thread - /// has ended, tokio panics rather than run it + /// Run something on the runtime and wait for it, unless the runtime is gone: when KWin has gone + /// (the session is being torn down), its thread has ended and tokio panics rather than run it fn block_on(&self, future: F) -> eyre::Result { if !self.alive.load(Ordering::SeqCst) { eyre::bail!("KWin is gone"); @@ -173,7 +184,8 @@ struct Poll { #[interface(name = "org.komorebi.Bridge.Poll")] impl Poll { /// `args` is JSON `{"hold_ms": n}`. Returns a JSON array of command batches: as soon as there - /// are commands, or empty once `hold_ms` has passed. + /// are commands, or empty once `hold_ms` has passed, or empty as soon as KWin has left the bus + /// since the call was made. async fn poll(&self, args: String) -> String { let hold_ms = serde_json::from_str::(&args) .ok() @@ -181,8 +193,16 @@ impl Poll { .unwrap_or(HOLD_MS); let deadline = tokio::time::Instant::now() + Duration::from_millis(hold_ms); + let kwin = self.shared.kwin_lost.load(Ordering::SeqCst); loop { + if self.shared.kwin_lost.load(Ordering::SeqCst) != kwin { + // the script that made this call went with its KWin: the commands, and the wake-up + // that came for them, are for the script of the KWin that took its place + self.shared.wake.notify_one(); + return "[]".to_string(); + } + if !self.shared.queue.lock().is_empty() { // let a burst finish arriving, so that a retile is one batch and not twenty tokio::time::sleep(COALESCE).await; @@ -229,7 +249,8 @@ pub struct KWinBackend { /// the desktop straight away. /// /// The connection is served by a thread of its own (`kwin-bridge-main`), which runs until the -/// daemon exits. +/// daemon exits or the session bus goes away. The same thread watches KWin on the bus, and loads +/// the script again into a KWin that has restarted. /// /// # Errors /// @@ -267,6 +288,7 @@ pub fn connect() -> eyre::Result> { queue: Mutex::new(VecDeque::new()), wake: Notify::new(), batch: AtomicU64::new(0), + kwin_lost: AtomicU64::new(0), ready: (Mutex::new(false), Condvar::new()), cursor_waiters: Mutex::new(HashMap::new()), next_token: AtomicU64::new(1), @@ -286,8 +308,7 @@ pub fn connect() -> eyre::Result> { match start(thread_shared.clone()).await { Ok(()) => { let _ = started_tx.send(Ok(())); - // the connection is served by this runtime for as long as the daemon runs - std::future::pending::<()>().await; + supervise(thread_shared).await; } Err(error) => { let _ = started_tx.send(Err(error)); @@ -393,6 +414,52 @@ async fn load_script(connection: &Connection) -> eyre::Result<()> { Ok(()) } +/// Watch KWin itself. If it goes away (a crash, `kwin_wayland --replace`) its windows go with it; +/// when it is back the script has to be loaded again. +async fn supervise(shared: Arc) { + let Ok(connection) = shared.connection().await else { + return; + }; + + let Ok(dbus) = zbus::fdo::DBusProxy::new(&connection).await else { + return; + }; + let Ok(mut owner_changes) = dbus.receive_name_owner_changed().await else { + return; + }; + + while let Some(signal) = owner_changes.next().await { + let Ok(args) = signal.args() else { continue }; + if args.name().as_str() != "org.kde.KWin" { + continue; + } + + if args.new_owner().is_none() { + tracing::warn!("KWin went away; its windows are gone"); + shared.kwin_lost.fetch_add(1, Ordering::SeqCst); + let outputs = shared.table.lock().compositor_lost(Instant::now()); + shared.dispatch(outputs); + continue; + } + + tracing::info!("KWin is back; loading the bridge script again"); + let started = Instant::now(); + loop { + match load_script(&connection).await { + Ok(()) => break, + Err(error) if started.elapsed() < Duration::from_secs(15) => { + tracing::debug!("KWin is not ready for the script yet: {error}"); + tokio::time::sleep(Duration::from_millis(250)).await; + } + Err(error) => { + tracing::error!("could not load the bridge script into the new KWin: {error}"); + break; + } + } + } + } +} + /// KWin's own "Move Mouse to Focus" action: the scripting API cannot move the pointer async fn move_mouse_to_focus(shared: &Shared) -> eyre::Result<()> { let connection = shared.connection().await?; @@ -556,6 +623,7 @@ mod tests { queue: Mutex::new(VecDeque::new()), wake: Notify::new(), batch: AtomicU64::new(0), + kwin_lost: AtomicU64::new(0), ready: (Mutex::new(false), Condvar::new()), cursor_waiters: Mutex::new(HashMap::new()), next_token: AtomicU64::new(1), @@ -634,6 +702,36 @@ mod tests { assert_eq!(next_poll(&runtime, &backend), json!([])); } + /// zbus does not end a held call when its caller leaves the bus, so the `Poll` of the bridge of + /// a KWin that has gone is still waiting when the next bridge calls. Were it given the + /// commands, they would be answered to nobody and lost. + #[test] + fn a_poll_held_by_the_bridge_of_a_kwin_that_has_gone_gets_no_commands() { + let (runtime, backend) = offline(); + let poll = || { + let poll = Poll { + shared: backend.shared.clone(), + }; + async move { poll.poll(json!({ "hold_ms": 10_000 }).to_string()).await } + }; + + runtime.block_on(async { + let old = tokio::spawn(poll()); + tokio::time::sleep(Duration::from_millis(10)).await; + + // KWin leaves the bus, and the bridge of the KWin that takes its place calls + backend.shared.kwin_lost.fetch_add(1, Ordering::SeqCst); + let new = tokio::spawn(poll()); + tokio::time::sleep(Duration::from_millis(10)).await; + + backend.shared.push(json!({ "op": "cursor", "token": 1 })); + + assert_eq!(old.await.unwrap(), "[]"); + let reply: Value = serde_json::from_str(&new.await.unwrap()).unwrap(); + assert_eq!(reply[0]["cmds"], json!([{ "op": "cursor", "token": 1 }])); + }); + } + #[test] fn a_poll_with_nothing_to_send_is_answered_with_nothing_once_its_hold_is_over() { let (runtime, backend) = offline(); diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 97c13b34..2bd92a99 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -59,6 +59,7 @@ use crate::window_manager_event::KWinNotification; use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use serde_json::Value; +use serde_json::json; use std::collections::HashMap; use std::time::Duration; use std::time::Instant; @@ -213,6 +214,30 @@ impl Table { entry.kwin_normal } + /// KWin went away. Its windows go with it, and nothing will report them closing. + /// + /// Returns a [`WindowManagerEvent::Destroy`] for every window the window manager may manage, + /// as if each had been closed, and forgets which window has the focus. The windows stay in + /// the table as closed ones, so their ids are not given out again. A KWin that comes back + /// reports its desktop in a new snapshot. + pub fn compositor_lost(&mut self, now: Instant) -> Vec { + let ids: Vec = self + .windows + .iter() + .filter(|(_, e)| e.info.alive) + .map(|(id, _)| *id) + .collect(); + + let mut out = vec![]; + for id in ids { + let uuid = self.windows[&id].uuid.clone(); + out.extend(self.on_removed(&json!({ "id": uuid }), now)); + } + + self.foreground = None; + out + } + /// Records the frame komorebi has just asked KWin to give a window, so that the window manager /// sees it at once. The `geometry` event that says what the client did replaces it. pub fn note_requested_rect(&mut self, id: u32, rect: Rect) { @@ -516,7 +541,6 @@ fn process(pid: i32, class: &str) -> (String, String) { #[cfg(test)] mod tests { use super::*; - use serde_json::json; fn win(id: &str, desktops: &[&str]) -> Value { json!({ @@ -877,4 +901,25 @@ mod tests { "the client rounded it to its cell grid" ); } + + #[test] + fn when_kwin_goes_away_every_window_it_had_is_destroyed() { + let mut t = table(vec![win("a", &["d1"]), win("b", &["d1"])]); + t.handle(&json!({ "type": "activated", "id": "a" }), Instant::now()); + + let mut destroyed = events(&t.compositor_lost(Instant::now())); + destroyed.sort(); + assert_eq!(destroyed, vec!["Destroy 1", "Destroy 2"]); + assert_eq!(t.foreground(), None); + assert!(t.windows().is_empty()); + assert!( + t.compositor_lost(Instant::now()).is_empty(), + "a window is destroyed once" + ); + + // the windows of the KWin that comes back are new ones, with ids of their own + t.handle(&snapshot(vec![win("c", &["d1"])]), Instant::now()); + let ids: Vec = t.windows().iter().map(|w| w.id).collect(); + assert_eq!(ids, vec![3]); + } } diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index db583dbe..86bf3d22 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -202,6 +202,17 @@ class Kde: "stop", f"kwin-virtual@{self.name}.service", f"session-bus@{self.name}.service" ) + def restart_kwin(self) -> None: + """Stops the session's KWin and starts a new one, on the same bus, and waits for it. + + The bus outlives KWin, as it does when the compositor of a running session crashes or is + replaced. The clients of the old KWin go with it. + """ + self.systemctl("restart", f"kwin-virtual@{self.name}.service") + if not self.wait_for(lambda: self.has_name("org.kde.KWin"), timeout=60): + log = self.machine.execute(f"journalctl _UID={self.uid} --no-pager -n 40")[1] + raise AssertionError(f"KWin did not come back:\n{log}") + def start_komorebi(self, *args: str) -> None: """Starts the daemon in this session, with `args`, as the user unit `komorebi@NAME`. diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 5fb407d0..2675538a 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -243,3 +243,25 @@ def test_a_session_has_the_users_data_and_config_directories_not_roots( "XDG_DATA_DIRS=/etc/profiles/per-user/komorebi/share:/run/current-system/sw/share" in words ) assert not any("/root" in word for word in words) + + +def test_restart_kwin_restarts_its_unit_alone_and_waits_for_the_new_one( + machine: FakeMachine, +) -> None: + machine.reply("busctl", status=0) + + Kde(machine, "main").restart_kwin() + + scripts = [inner(command) for command in machine.commands if " sh -c " in command] + assert scripts[0] == "systemctl --user restart kwin-virtual@main.service" + assert "busctl --user --no-pager list | grep -q '^org.kde.KWin '" in scripts[1:] + + +def test_restart_kwin_reports_the_journal_when_kwin_does_not_come_back( + machine: FakeMachine, +) -> None: + machine.reply("busctl", status=1) + machine.reply("journalctl", output="kwin: the socket is taken") + + with pytest.raises(AssertionError, match="the socket is taken"): + Kde(machine, "main", scale=0.01).restart_kwin() diff --git a/nix/tests/vm/suites/kwin-restart/default.nix b/nix/tests/vm/suites/kwin-restart/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/kwin-restart/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/kwin-restart/test.py b/nix/tests/vm/suites/kwin-restart/test.py new file mode 100644 index 00000000..eaac35a7 --- /dev/null +++ b/nix/tests/vm/suites/kwin-restart/test.py @@ -0,0 +1,131 @@ +# KWin restarts under a running daemon, as when the compositor of a session crashes or is replaced: +# the session bus stays, KWin leaves it and comes back, and the clients of the old KWin go with it. +# What only a real KWin can tell: that the daemon sees KWin go and come back on the bus, that it +# takes every window of the old KWin out of its layout, that it loads its script into the new +# KWin, and that it tiles what opens there, right away. Twice, as the spike did. +from komorebi_vm import Checks, Kde, daemon + +W, H = 1920, 1080 +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + +def daemon_log() -> str: + return kde.komorebi_log() + + +def loads() -> int: + """How many times the daemon has loaded its script into a KWin.""" + return daemon_log().count("loaded the KWin bridge script") + + +def where_asked(title: str) -> bool: + """KWin has the window where the daemon asked: the same place, and the size up to a cell.""" + want, wid = daemon.asked(daemon_log(), title), kde.wid(title) + if want is None or wid == "": + return False + have = kde.rect(wid) + return ( + (have.x, have.y) == (want.x, want.y) + and 0 <= want.w - have.w < CELL + and 0 <= want.h - have.h < CELL + ) + + +def open_window(title: str) -> None: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + kde.wait_for(lambda: title in daemon.window_ids(daemon_log()), timeout=10) + + +def destroyed(titles: list[str]) -> bool: + """The daemon took every one of these windows out of its layout.""" + log = daemon_log() + ids = daemon.window_ids(log) + gone = {e.window for e in daemon.events(log) if e.kind == "Destroy"} + return all(ids.get(title) in gone for title in titles) + + +def alone(title: str) -> bool: + """The window is where the daemon asked, and the only one: it has the whole width.""" + return where_asked(title) and kde.rect(kde.wid(title)).w > W - 100 + + +def side_by_side(a: str, b: str) -> bool: + if not (where_asked(a) and where_asked(b)): + return False + ra, rb = kde.rect(kde.wid(a)), kde.rect(kde.wid(b)) + return not ra.overlaps(rb) and ra.w < W - 20 and rb.w < W - 20 + + +def restart(old: list[str], loaded: int) -> None: + kde.restart_kwin() + checks.check( + "the daemon saw KWin go", + kde.wait_for(lambda: "KWin went away" in daemon_log(), timeout=10), + ) + checks.check( + "every window of the old KWin left the layout", kde.wait_for(lambda: destroyed(old)) + ) + checks.check( + "the daemon loaded its script into the new KWin", + kde.wait_for(lambda: loads() == loaded, timeout=30), + ) + checks.check("the new KWin runs the script", kde.wait_for(kde.script_loaded)) + checks.check("the daemon is still running", kde.komorebi_running()) + + +print("== 1. three windows are tiled") +kde.start_komorebi("--log-level", "debug") +checks.check( + "the daemon loaded its script into KWin", kde.wait_for(lambda: loads() == 1, timeout=30) +) +before = ["pre1", "pre2", "pre3"] +for title in before: + open_window(title) +checks.check( + "every window is where the daemon asked for it", + kde.wait_for(lambda: all(where_asked(t) for t in before), timeout=20), +) + +print("== 2. KWin restarts") +restart(before, loaded=2) +checks.check("the windows of the old KWin are gone", all(kde.wid(t) == "" for t in before)) + +print("== 3. windows open in the new KWin") +open_window("post1") +checks.check("the first is tiled on its own", kde.wait_for(lambda: alone("post1"), timeout=20)) +open_window("post2") +checks.check( + "the second is tiled next to it", + kde.wait_for(lambda: side_by_side("post1", "post2"), timeout=20), +) +for title in ["post1", "post2"]: + asked = daemon.asked(daemon_log(), title) + print(f" {title}: asked {asked}, has {kde.rect(kde.wid(title))}") + +print("== 4. KWin restarts again, with one window open") +kde.close(kde.wid("post2")) +checks.check( + "the window that is left has the screen", kde.wait_for(lambda: alone("post1"), timeout=20) +) +restart(["post1"], loaded=3) +open_window("again") +checks.check( + "a window opened in the third KWin is tiled", kde.wait_for(lambda: alone("again"), timeout=20) +) + +print("== 5. stop") +kde.stop_komorebi() +checks.check("the daemon exited", not kde.komorebi_running()) +checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded())) + +kde.stop() +checks.finish()