From 661e04796f64681c65212104279a1c288d2080d9 Mon Sep 17 00:00:00 2001 From: Quinn Groves Date: Wed, 18 Nov 2026 14:03:11 -0500 Subject: [PATCH] Start the launcher on demand, without a service Bluefin's packaging PR asked whether Compass can work with no compass.service running. The systemd unit is only one of several start paths, but with no service and no login-start entry the first hotkey press used to fail: toggle was a pure IPC client and nothing was listening. The summoning commands now start what they need and let it outlive them: - toggle/show spawn a detached, visible 'compass start' when no engine answers, then wait for the engine's own DescribeWindow to report the window shown. - query starts a hidden session with a display, or a headless 'serve' without one, and waits for readiness before querying. - hide and ping keep their honest no-engine refusal, and an engine that is already up keeps the ordinary IPC path. This adds no IPC, protocol bump, D-Bus activation or unsafe code; the UI lease makes concurrent cold starts safe. The systemd unit stays as an optional packager fallback. ADR-0023 records the decision. --- crates/compass/src/activation.rs | 234 ++++++++++++++++++ crates/compass/src/cli.rs | 10 +- crates/compass/src/lib.rs | 24 +- crates/compass/tests/activation_cli.rs | 132 ++++++++++ crates/compass/tests/cli.rs | 33 ++- docs/crates.md | 2 +- docs/getting-started.md | 23 +- .../0015-the-launcher-window-is-resident.md | 3 +- .../adr/0023-the-launcher-starts-on-demand.md | 86 +++++++ docs/rust-engine/adr/README.md | 1 + packaging/README.md | 6 +- 11 files changed, 531 insertions(+), 23 deletions(-) create mode 100644 crates/compass/src/activation.rs create mode 100644 crates/compass/tests/activation_cli.rs create mode 100644 docs/rust-engine/adr/0023-the-launcher-starts-on-demand.md diff --git a/crates/compass/src/activation.rs b/crates/compass/src/activation.rs new file mode 100644 index 0000000000..41a5f17f5c --- /dev/null +++ b/crates/compass/src/activation.rs @@ -0,0 +1,234 @@ +//! Cold-starting Compass from a command that was bound to a key. +//! +//! [ADR-0015](../../docs/rust-engine/adr/0015-the-launcher-window-is-resident.md) +//! makes the window a resident client of the engine, so both have to be running +//! before `compass toggle` can do anything. On a machine with no service and no +//! login autostart, the first press of the hotkey is the first thing that asks +//! for either. The commands that summon the launcher therefore start what they +//! need and let it outlive them: a short-lived CLI process spawns a detached +//! `compass start`, which owns the engine and the window through the ordinary +//! [`crate::session`] and [`crate::supervise`] paths. No service manager, no D-Bus +//! activation and no enabled login switch are involved. +//! +//! A client that already has what it needs is left alone. The single UI lease +//! makes two simultaneous cold starts safe: one wins the lease, and the other +//! shows the window it just started instead of opening a second one. + +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use compass_ipc::{Request, Response, SocketPath}; + +use crate::ipc; +use crate::session; + +/// How long a cold command waits for what it started to become usable. +const READY_TIMEOUT: Duration = Duration::from_secs(15); +/// How long a poll of the window's own state is allowed to take. +const DESCRIBE_TIMEOUT: Duration = Duration::from_secs(5); +/// The poll interval while waiting for the engine or the window. +const POLL: Duration = Duration::from_millis(50); + +/// What a cold command spawns. Kept separate from the decision so the exact +/// command line can be tested without starting a process. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Spawn { + /// Engine plus a hidden resident window: enough to answer a headless + /// command, and ready for the next summon without another cold start. + SessionHidden, + /// Engine plus a visible resident window: what `toggle` and `show` want. + SessionVisible, + /// The engine alone, for a machine with no graphical session. + Headless, +} + +impl Spawn { + fn subcommand(self) -> &'static [&'static str] { + match self { + Self::SessionHidden => &["start", "--hidden"], + Self::SessionVisible => &["start"], + Self::Headless => &["serve", "--no-hotkey"], + } + } +} + +/// Whether this process has a graphical session to open a window on. +#[must_use] +pub fn has_display() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var_os("WAYLAND_SOCKET").is_some() + || std::env::var_os("DISPLAY").is_some() +} + +/// Builds the detached process a cold command starts. +/// +/// A new process group means a terminal hangup or Ctrl-C aimed at the invoking +/// command does not take the session with it. Null stdio means a daemon that +/// outlives its invoking terminal owns no pipe back to it; the engine's log is +/// its own file, as it is for every other start path. +fn command(exe: &Path, socket: &SocketPath, spawn: Spawn, verbose: u8) -> Command { + let mut command = Command::new(exe); + command + .arg("--engine=rust") + .arg("--socket") + .arg(socket.as_path()) + .args(std::iter::repeat_n("-v", usize::from(verbose))) + .args(spawn.subcommand()) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } + command +} + +/// Starts `spawn` and waits until its engine answers a ping. +/// +/// Returning the child lets a caller keep watching the process it started, and +/// checking it in the loop reports an engine that exits during startup instead +/// of waiting the full timeout for one that is never coming. +async fn start(socket: &SocketPath, spawn: Spawn, verbose: u8) -> Result { + let exe = std::env::current_exe().context("finding the compass executable")?; + let mut child = command(&exe, socket, spawn, verbose) + .spawn() + .context("starting Compass on demand")?; + let deadline = tokio::time::Instant::now() + READY_TIMEOUT; + loop { + if let Some(status) = child.try_wait().context("checking the Compass process")? { + if session::listening(socket).await? { + // A second cold starter lost the race and exited cleanly; the + // engine the other one started is the one we care about. + return Ok(child); + } + if !status.success() { + bail!("Compass exited before its engine was ready: {status}"); + } + // A duplicate `start` exits cleanly after handing the job to the + // process holding the UI lease. Keep waiting for that engine. + } + if session::listening(socket).await? { + return Ok(child); + } + if tokio::time::Instant::now() >= deadline { + bail!( + "the Compass engine did not become ready within {} seconds", + READY_TIMEOUT.as_secs() + ); + } + tokio::time::sleep(POLL).await; + } +} + +/// Whether a window is attached to the engine and currently shown. +/// +/// A poll, not a query for a person: a window that is starting, hidden, gone or +/// wedged is uniformly "not usable yet", and the caller either waits or starts +/// one. `DescribeWindow` is the engine's own state, so this adds no IPC. +async fn window_open(socket: &SocketPath) -> bool { + tokio::time::timeout(DESCRIBE_TIMEOUT, ipc::send(socket, Request::DescribeWindow)) + .await + .ok() + .and_then(|answer| answer.ok()) + .is_some_and(|answer| matches!(answer, Response::WindowState { open: true })) +} + +/// Ensures a window is attached and shown, starting a session if needed. +/// +/// Returns whether this call had to start one. When it did, the window is +/// already visible, so a `toggle` or `show` that called this has nothing left +/// to send. An engine with a hidden window gets the same treatment as a cold +/// start: `start` either claims the free lease or asks the existing resident +/// window to show itself. +pub async fn ensure_window(socket: &SocketPath, verbose: u8) -> Result { + if session::listening(socket).await? && window_open(socket).await { + return Ok(false); + } + if !has_display() { + bail!( + "no Compass engine is listening on {socket}, and there is no graphical session to \ + start a launcher on. Run `compass start --hidden` from your desktop session, or see \ + `compass doctor` for the full picture" + ); + } + let _child = start(socket, Spawn::SessionVisible, verbose).await?; + let deadline = tokio::time::Instant::now() + READY_TIMEOUT; + while !window_open(socket).await { + if tokio::time::Instant::now() >= deadline { + bail!( + "the Compass launcher window did not open within {} seconds", + READY_TIMEOUT.as_secs() + ); + } + tokio::time::sleep(POLL).await; + } + Ok(true) +} + +/// Ensures an engine answers on `socket`, starting one if needed. +/// +/// With a display this starts the full hidden session, which leaves the +/// launcher ready for the next hotkey press. Headless it starts only `serve`: +/// opening a window there would fail, and asking for a hotkey would prompt for +/// a consent nobody can give. +pub async fn ensure_engine(socket: &SocketPath, verbose: u8) -> Result { + if session::listening(socket).await? { + return Ok(false); + } + let spawn = if has_display() { + Spawn::SessionHidden + } else { + Spawn::Headless + }; + let _child = start(socket, spawn, verbose).await?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser as _; + + use crate::Cli; + + #[test] + fn every_spawn_keeps_the_global_flags_and_socket_in_front() { + let socket = SocketPath::exact(Path::new("/run/user/1000/compass/ipc.sock")); + for (spawn, tail) in [ + (Spawn::SessionHidden, vec!["start", "--hidden"]), + (Spawn::SessionVisible, vec!["start"]), + (Spawn::Headless, vec!["serve", "--no-hotkey"]), + ] { + let command = command(Path::new("/usr/bin/compass"), &socket, spawn, 2); + let args: Vec<_> = command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + args, + vec![ + "--engine=rust", + "--socket", + "/run/user/1000/compass/ipc.sock", + "-v", + "-v" + ] + .into_iter() + .chain(tail) + .map(str::to_owned) + .collect::>() + ); + assert!( + Cli::try_parse_from( + std::iter::once("compass".to_owned()).chain(args.iter().cloned()) + ) + .is_ok(), + "the spawned argv must parse: {args:?}" + ); + } + } +} diff --git a/crates/compass/src/cli.rs b/crates/compass/src/cli.rs index 45d51fd51b..46064f8051 100644 --- a/crates/compass/src/cli.rs +++ b/crates/compass/src/cli.rs @@ -161,9 +161,14 @@ pub enum Command { }, /// Toggle the launcher window between shown and hidden. + /// + /// Starts the launcher if it is not running, so this works as the first + /// command after login without a service or a login-start entry. Toggle, /// Show the launcher window. + /// + /// Starts the launcher if it is not running. #[command(alias = "open")] Show, @@ -193,7 +198,10 @@ pub enum Command { /// Ask a running engine to shut down. Shutdown, - /// Search the running engine's index and print the ranked hits. + /// Search the engine's index and print the ranked hits. + /// + /// Starts the engine if it is not running. With a graphical session it + /// also brings up a hidden launcher, ready for the next hotkey press. Query { /// Search text. Joined with spaces if given as several words, so /// `compass query text editor` and `compass query "text editor"` agree. diff --git a/crates/compass/src/lib.rs b/crates/compass/src/lib.rs index 9d13bd66db..0478473479 100644 --- a/crates/compass/src/lib.rs +++ b/crates/compass/src/lib.rs @@ -11,6 +11,7 @@ #![warn(missing_docs)] #![warn(missing_debug_implementations)] +pub mod activation; pub mod appearance; pub mod catalog_watch; pub mod cli; @@ -171,10 +172,7 @@ pub fn run(cli: Cli) -> Result { // a backtrace naming winit's source file for the entirely ordinary // situation of running the launcher from a TTY or over ssh. `doctor` // already diagnoses this properly, so point at it. - if std::env::var_os("WAYLAND_DISPLAY").is_none() - && std::env::var_os("WAYLAND_SOCKET").is_none() - && std::env::var_os("DISPLAY").is_none() - { + if !activation::has_display() { bail!( "no graphical session: neither WAYLAND_DISPLAY nor DISPLAY is set, so there is \ nothing to open a window on. Run `compass doctor` for the full picture" @@ -569,6 +567,7 @@ fn launcher_surface() -> compass_wayland::SurfaceKind { async fn dispatch(cli: Cli) -> Result { let socket = cli.socket_path(); + let verbose = cli.verbose; match cli.command { Command::Doctor { check_only, json } => { @@ -612,6 +611,7 @@ async fn dispatch(cli: Cli) -> Result { provider, } => { require_servable_engine(cli.engine)?; + activation::ensure_engine(&socket, verbose).await?; let mut hits = ipc::query(&socket, &text.join(" ")).await?; if let Some(provider) = provider { let prefix = format!("{provider}:"); @@ -821,9 +821,9 @@ async fn dispatch(cli: Cli) -> Result { other => bail!("unexpected answer from the engine: {other:?}"), } } - Command::Toggle => window_command(&socket, cli.engine, Request::Toggle).await, - Command::Show => window_command(&socket, cli.engine, Request::Show).await, - Command::Hide => window_command(&socket, cli.engine, Request::Hide).await, + Command::Toggle => window_command(&socket, cli.engine, verbose, Request::Toggle).await, + Command::Show => window_command(&socket, cli.engine, verbose, Request::Show).await, + Command::Hide => window_command(&socket, cli.engine, verbose, Request::Hide).await, } } @@ -961,9 +961,19 @@ async fn handle_theme(cmd: crate::cli::ThemeCommand) -> Result { async fn window_command( socket: &compass_ipc::SocketPath, engine: Engine, + verbose: u8, request: Request, ) -> Result { require_servable_engine(engine)?; + // A cold `toggle`/`show` is often the first thing asked of a machine after + // login. With no engine there is no window and no hotkey either, so bring + // up the whole session; the window `start` opens is already visible, so + // there is nothing left to send. An engine that answers keeps the ordinary + // request path, including its honest "no window connected" refusal. + if matches!(request, Request::Toggle | Request::Show) && !session::listening(socket).await? { + activation::ensure_window(socket, verbose).await?; + return Ok(ExitCode::from(EXIT_OK)); + } send_window_command(socket, request, WINDOW_COMMAND_TIMEOUT).await?; Ok(ExitCode::from(EXIT_OK)) } diff --git a/crates/compass/tests/activation_cli.rs b/crates/compass/tests/activation_cli.rs new file mode 100644 index 0000000000..7df2ad9774 --- /dev/null +++ b/crates/compass/tests/activation_cli.rs @@ -0,0 +1,132 @@ +//! A command that needs the engine brings it up itself, with no service, no +//! login-start entry and no window, on a machine with no graphical session. +//! +//! The spawned engine is detached from this test: it is stopped with +//! `compass shutdown` at the end, and every path lives under a temporary +//! directory with a cleared environment. + +#![cfg(unix)] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; + +use tempfile::TempDir; + +struct Session { + dir: TempDir, + socket: PathBuf, +} + +impl Session { + fn new() -> Self { + let dir = tempfile::tempdir().expect("tempdir"); + std::fs::create_dir_all(dir.path().join("run")).expect("mkdir"); + let socket = dir.path().join("run/compass.sock"); + Self { dir, socket } + } + + fn command(&self) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_compass")); + command + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", self.dir.path()) + .env("XDG_CONFIG_HOME", self.dir.path().join(".config")) + .env("XDG_DATA_HOME", self.dir.path().join(".local/share")) + .env("XDG_CACHE_HOME", self.dir.path().join(".cache")) + .env("XDG_STATE_HOME", self.dir.path().join(".local/state")) + .env("XDG_RUNTIME_DIR", self.dir.path().join("run")) + .env("XDG_DATA_DIRS", self.dir.path().join("empty")) + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/nonexistent/compass-test-no-session-bus", + ) + .env("COMPASS_DISABLE_AUTO_RATE_REFRESH", "1") + .env( + "COMPASS_UPDATE_FEED_URL", + "http://127.0.0.1:9/releases/latest", + ) + .arg("--socket") + .arg(&self.socket); + command + } + + fn cli(&self, args: &[&str]) -> Output { + self.command() + .args(args) + .stdin(Stdio::null()) + .output() + .expect("the CLI binary should run") + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.cli(&["shutdown"]); + } +} + +#[test] +fn query_cold_starts_a_headless_engine_and_it_stays_up_after_the_command_exits() { + let session = Session::new(); + + let output = session.cli(&["query", "--json", "firefox"]); + assert!( + output.status.success(), + "query should start the engine it needs: {}", + String::from_utf8_lossy(&output.stderr) + ); + let hits: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("query --json printed JSON"); + assert!(hits.is_array(), "query printed {hits}"); + + // The engine outlived the short-lived query that started it. + let ping = session.cli(&["ping"]); + assert!( + ping.status.success(), + "the engine should still be answering: {}", + String::from_utf8_lossy(&ping.stderr) + ); + assert!(String::from_utf8_lossy(&ping.stdout).contains("engine alive")); +} + +#[test] +fn a_later_client_reuses_the_engine_a_cold_command_started() { + let session = Session::new(); + assert!( + session + .cli(&["query", "--json", "firefox"]) + .status + .success() + ); + + // A second query must not start another engine on the same socket. If it + // tried to, bind() would fail and this command would report the error. + let again = session.cli(&["query", "--json", "firefox"]); + assert!( + again.status.success(), + "the second query should reuse the engine: {}", + String::from_utf8_lossy(&again.stderr) + ); +} + +#[test] +fn the_cold_engine_is_owned_by_no_client_and_stops_on_shutdown() { + let session = Session::new(); + assert!( + session + .cli(&["query", "--json", "firefox"]) + .status + .success() + ); + + let shutdown = session.cli(&["shutdown"]); + assert!( + shutdown.status.success(), + "shutdown should reach the cold engine: {}", + String::from_utf8_lossy(&shutdown.stderr) + ); + let ping = session.cli(&["ping"]); + assert!(!ping.status.success(), "the engine should have stopped"); + assert!(!Path::new(&session.socket).exists()); +} diff --git a/crates/compass/tests/cli.rs b/crates/compass/tests/cli.rs index 6da792e64f..e648f2a55c 100644 --- a/crates/compass/tests/cli.rs +++ b/crates/compass/tests/cli.rs @@ -109,6 +109,12 @@ async fn window_commands_send_the_matching_request() { stderr(&output) ); + // A summon first asks whether an engine is listening; that readiness + // probe is a Ping, and only `toggle`/`show` make it (`hide` never + // cold-starts). The request under test comes after it. + if matches!(expected, Request::Toggle | Request::Show) { + assert_eq!(requests.recv().await, Some(Request::Ping)); + } let received = requests.recv().await.expect("a request should arrive"); assert_eq!(received, expected, "for `compass {argument}`"); } @@ -143,6 +149,7 @@ async fn only_the_requested_command_is_sent() { let output = run_cli(dir.path(), &socket, &["toggle"]).await; assert!(output.status.success(), "{}", stderr(&output)); + assert_eq!(requests.recv().await, Some(Request::Ping)); assert_eq!(requests.recv().await, Some(Request::Toggle)); // The client closed its connection; nothing further was sent. @@ -201,7 +208,7 @@ async fn vici_develops_links_go_to_the_engine_and_a_malformed_one_says_why() { #[tokio::test] async fn commands_without_a_daemon_explain_themselves() { - for argument in ["toggle", "show", "hide", "ping"] { + for argument in ["hide", "ping"] { let dir = tempfile::tempdir().expect("tempdir"); let socket = dir.path().join("absent.sock"); @@ -236,11 +243,33 @@ async fn a_stale_socket_file_is_still_reported_as_no_daemon() { // the message must still be the actionable one. std::fs::write(&socket, b"not a socket").expect("write"); - let output = run_cli(dir.path(), &socket, &["toggle"]).await; + let output = run_cli(dir.path(), &socket, &["ping"]).await; assert_eq!(output.status.code(), Some(1)); assert!(stderr(&output).contains("no Compass engine is listening")); } +#[tokio::test] +async fn a_cold_window_command_without_a_display_says_why_it_cannot_start() { + for argument in ["toggle", "show"] { + let dir = tempfile::tempdir().expect("tempdir"); + let socket = dir.path().join("absent.sock"); + + // `run_cli` clears the environment, so there is no WAYLAND_DISPLAY or + // DISPLAY for a self-started launcher to open a window on. The summon + // must say so rather than reporting a connection refused. + let output = run_cli(dir.path(), &socket, &[argument]).await; + assert_eq!( + output.status.code(), + Some(1), + "`{argument}` should fail without a display" + ); + let text = stderr(&output); + assert!(text.contains("no Compass engine is listening"), "{text}"); + assert!(text.contains("no graphical session"), "{text}"); + assert!(text.contains("compass doctor"), "{text}"); + } +} + // -------------------------------------------------------------------------- // The engine switch // -------------------------------------------------------------------------- diff --git a/docs/crates.md b/docs/crates.md index 52fd383674..f1c057e4c8 100644 --- a/docs/crates.md +++ b/docs/crates.md @@ -18,7 +18,7 @@ has the full rules. | Crate | What it is | |---|---| -| `compass` | The `compass` command: the CLI, the engine (`compass serve`, the IPC server and the services it runs), and the wiring of every other crate. Linux-bound. | +| `compass` | The `compass` command: the CLI, the engine (`compass serve`, the IPC server and the services it runs), on-demand startup from `toggle`/`show`/`query`, and the wiring of every other crate. Linux-bound. | | `compass-ui` | The Iced launcher window: every view, the settings, the onboarding flow. | ## Application logic diff --git a/docs/getting-started.md b/docs/getting-started.md index f48b794cb3..1dd41a8a5a 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -30,18 +30,22 @@ The examples on this page use the `compass` command. From the Flatpak, run it as ## Start Compass when you log in -Opening Compass from the application grid starts it for the rest of the session. To start it at -every login, turn on **Start at login**, in the first-run setup's "Make it your own" step or in -Settings, General. It is off until you turn it on. Compass asks your desktop's Background portal, -which shows you what it allows, to run `compass start --hidden` when you log in. Where there is no +You do not need a service or a login-start entry to use Compass. Pressing the launcher shortcut +starts the engine and window on demand, and they keep running for the rest of the session. + +Opening Compass from the application grid also starts it for the rest of the session. To have it +waiting from the moment you log in, turn on **Start at login**, in the first-run setup's "Make it +your own" step or in Settings, General. It is off until you turn it on. Compass asks your desktop's +Background portal, which shows you what it allows, to run `compass start --hidden` when you log in. Where there is no Background portal (some wlroots sessions) and Compass is not in the Flatpak, it writes `~/.config/autostart/compass.desktop` itself, and turning the switch off removes only that file. If your desktop declines, the switch stays off and says so. From a terminal, `compass login-start status` shows the same state, and `compass login-start enable` and `compass login-start disable` change it as the switch does. -Packages also install a systemd user unit, which Compass never turns on or off. Settings says when -it is installed and whether it is enabled. To use the unit instead of the switch: +Packages may also install a systemd user unit as an optional fallback. Compass never turns it on +or off, and nothing needs it for the launcher to work; Settings only reports when it is installed +and whether it is enabled. To use the unit as well: ```sh systemctl --user enable --now compass @@ -74,9 +78,10 @@ compositor's autostart instead, for example `exec compass start --hidden` in Swa ## Set a keyboard shortcut -The launcher opens with `compass toggle`, which shows it or hides it. Compass has to be running -for this to work: open it once from the application grid, or run `compass start --hidden` when you -log in. +The launcher opens with `compass toggle`, which shows it or hides it. If Compass is not running, +this command starts it for you, so the shortcut works from the first press without a service or a +login-start entry. `compass query` likewise starts the engine it needs; headless, it starts only +the engine and no window. Compass asks for Super+Space by default. To change it, run **Open Settings** and set **Launcher hotkey** under General, or set `launcher.hotkey` in the configuration file. diff --git a/docs/rust-engine/adr/0015-the-launcher-window-is-resident.md b/docs/rust-engine/adr/0015-the-launcher-window-is-resident.md index 4139aa3a3e..c3ff5819bf 100644 --- a/docs/rust-engine/adr/0015-the-launcher-window-is-resident.md +++ b/docs/rust-engine/adr/0015-the-launcher-window-is-resident.md @@ -79,4 +79,5 @@ not do that: it is PLAN.md §8's to revise once there is something to measure. **What this does not settle.** Whether the resident window is started by autostart, by `serve` spawning it when a display exists, or by the user, is deliberately open. The protocol above works for all three, and picking one before the shortcut path works would be guessing at a problem that -is not yet in front of us. +is not yet in front of us. [ADR-0023](./0023-the-launcher-starts-on-demand.md) later settled it: +the summoning commands start the session on demand, which needs neither a service nor autostart. diff --git a/docs/rust-engine/adr/0023-the-launcher-starts-on-demand.md b/docs/rust-engine/adr/0023-the-launcher-starts-on-demand.md new file mode 100644 index 0000000000..fbeff97177 --- /dev/null +++ b/docs/rust-engine/adr/0023-the-launcher-starts-on-demand.md @@ -0,0 +1,86 @@ +# ADR-0023: The launcher starts on demand, not from a service + +**Status:** Accepted · **Date:** 2026-11-18 · Amends: ADR-0015, ADR-0022 · Decides: the Bluefin PR's question — can Compass work with no service running? + +## Context + +Bluefin's packaging PR included a `compass.service` user unit, and its maintainer asked whether the +launcher could work without a service on the machine. Two ways already existed: + +- `compass start` starts its own engine on demand (`session::ensure`) and runs a resident window + under a supervisor, so the app-grid entry and a bare `compass` need no service. +- Login start asks the Background portal to run `compass start --hidden`, with an XDG autostart + entry as the fallback (ADR-0022 §2). The systemd unit is a packager option, never enabled by + the app. + +What was missing was the cold path. Every other command is a pure IPC client, and with no engine +listening `compass toggle` — the command Bluefin binds to Super+Space — fails with "no Compass +engine is listening". Without either the service or an enabled login-start switch, the first press +of the hotkey on a fresh machine does nothing useful. ADR-0015 deliberately left open *what starts +the resident window*: autostart, the daemon, or the user. This is the decision it left open. + +## Decision + +The commands a person binds to a key start what they need, and let it outlive the short-lived CLI +process that asked for it: + +1. **`toggle` and `show`** check whether an engine answers a ping. If none does, they spawn a + detached `compass start` — engine plus a *visible* resident window — in a new process group + with null stdio, and wait until the engine's own `DescribeWindow` reports the window shown. + The window is already up, so these commands return without sending a second request. +2. **`query`** does the same check. With a graphical session it spawns `compass start --hidden` + (engine plus a hidden window, ready for the next summon); with none it spawns + `compass serve --no-hotkey` (engine only, so a diagnostic command never triggers a hotkey + consent prompt). It waits for the engine to answer before querying. +3. **`hide` and `ping`** keep the honest refusal: there is nothing to hide or ping when cold. +4. An engine that *is* listening keeps the ordinary path, including ADR-0015's typed + "no launcher window is connected" refusal. The on-demand path does not paper over a broken + window; it only covers the case where nothing was started. +5. **`packaging/systemd/compass.service` stays**, as an optional fallback for packagers who + prefer it (ADR-0022 §2). Nothing enables it, and nothing requires it. Login start stays off + by default; on-demand start makes it an optimisation rather than a prerequisite. + +The implementation is one module, `crate::activation`. There is no new IPC request, no protocol +bump, no D-Bus well-known name and no socket activation. The existing UI lease +(`.ui.lock`) makes two simultaneous cold starts safe: one wins the lease and the other +shows the window that the first started. `process_group(0)` is a safe API, so the workspace's +`unsafe_code = "forbid"` stands. + +## Consequences + +- A fresh install works from the first key press: no service, no login-start switch and no + first-run consent to *start* the launcher. The global shortcut itself still needs its portal + grant, or Bluefin's GNOME-level custom shortcut calling `compass toggle`. +- The cold start's latency is paid once, on the first summon. Subsequent shows keep the resident + window's latency; ADR-0015's 120 ms figure was never a cold-start figure and remains one. +- `DescribeWindow` cannot tell "attached but hidden" from "not attached". Spawning a *visible* + `start` and waiting for `open: true` sidesteps the ambiguity without a new protocol field; a + hidden window from login start is shown by the same `start` through the UI lease. +- A detached engine started for a headless `query` has no supervising process. It lives until + `compass shutdown` or logout, which is the ordinary lifetime of a `serve` engine; a later + `start` reuses it rather than owning it. +- Tests changed accordingly: window-summon commands now send a `Ping` readiness probe first, + the no-daemon test covers `hide` and `ping`, and new integration tests prove a cold `query` + starts an engine that survives the query, is reused by the next client and stops on shutdown. + +## Alternatives considered + +- **Require the systemd service.** Rejected: it is what Bluefin asked to avoid, it needs a + `graphical-session.target` with a Wayland environment, and it is not present on every target. +- **Turn login autostart on by default.** Rejected: ADR-0022 chose default off, the portal asks + the user's permission, and neither helps before the first login after installation. +- **D-Bus activation of an `org.tunaos.compass` name.** Rejected: it needs an activation file, + a well-known name and a way to hand the graphical session environment to the activated + process. The Flatpak's `--own-name=org.tunaos.compass.*` grant is not backed by a name owner, + and the Background portal explicitly sets `set_dbus_activatable(false)`. +- **A new `WindowPresence`/wait-for-attach request.** Rejected: a protocol version bump and a new + long-poll in the engine for a question `DescribeWindow` already answers well enough once the + session we start is visible. +- **Socket activation.** Rejected for the same environment problem as D-Bus activation: a socket + activated by a manager has no `WAYLAND_DISPLAY` to open a launcher on. + +## Reopen when + +A maintained activation mechanism supplies the graphical session environment reliably on every +target, or the first summon has to meet the 120 ms SLA — then a resident-at-login model is needed +and this on-demand path should become the fallback instead of the primary route. diff --git a/docs/rust-engine/adr/README.md b/docs/rust-engine/adr/README.md index a35b55fb65..c6a1158128 100644 --- a/docs/rust-engine/adr/README.md +++ b/docs/rust-engine/adr/README.md @@ -30,3 +30,4 @@ drifting away from a recorded decision is not. | [0020](./0020-phase-7-rebrand.md) | The Phase 7 rebrand: `org.tunaos.compass`, the `compass` command and `~/.config/compass`, with a one-time move of the `vicinae` directories; `@vicinae/api`, `vicinae://`, the Vicinae Store and `VICINAE_*` fallbacks stay | Accepted | | [0021](./0021-remove-the-cpp-engine.md) | The C++ engine leaves the repository; upstream Vicinae releases are the benchmark and differential reference | Accepted | | [0022](./0022-the-november-calls-decided.md) | The accessibility tree is AccessKit's Unix adapter over our own model; login start is the Background portal; browser control uses a launcher-shipped native messaging host; zbus 5 advisories stay ignored until the pins move; baselines on hosted runners | Accepted | +| [0023](./0023-the-launcher-starts-on-demand.md) | The launcher starts on demand from `toggle`, `show` and `query`; no service or login-start entry is required; the systemd unit stays an optional fallback | Accepted; amends 0015, 0022 | diff --git a/packaging/README.md b/packaging/README.md index d2db313811..79f1e31acb 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -180,8 +180,10 @@ the system file, so a later change to the system file still reaches existing use and skipped. Compass reads it at start, so a change takes effect when the engine restarts. Bluefin binds Super+Space with a GNOME custom keyboard shortcut that runs `compass toggle`, -because the GlobalShortcuts portal asks the user to approve a binding the first time. The image -then turns off the engine's own request with: +because the GlobalShortcuts portal asks the user to approve a binding the first time. That command +starts Compass on demand when nothing is running (ADR-0023), so the image does not need to enable +`compass.service` or a login-start entry for the shortcut to work. The image then turns off the +engine's own request with: ```json {"launcher": {"hotkey": ""}}