Skip to main content

omni_dev/
daemon.rs

1//! The extensible omni-dev daemon: a long-lived supervisor that hosts pluggable
2//! [`DaemonService`](service::DaemonService)s over a local Unix-domain control
3//! socket.
4//!
5//! The daemon owns **lifecycle, single-instance supervision, status
6//! aggregation, and (on macOS) the menu-bar shell**. Each service wraps its own
7//! work and exposes status/control; the browser bridge is the first such
8//! service (#987). The control socket is a private operator/tray channel — it
9//! does **not** carry any service's own data plane (e.g. the bridge keeps its
10//! loopback-TCP planes per ADR-0036). See ADR-0039.
11//!
12//! Process model:
13//! - `daemon run` *becomes* the daemon ([`server::run`]), blocking until a
14//!   signal or a built-in `shutdown` op.
15//! - `daemon start` launches it in the background (a launchd LaunchAgent on
16//!   macOS, a systemd user unit on Linux); `stop` / `restart` / `status` are thin
17//!   [`client::DaemonClient`]s.
18
19// The control plane is a Unix-domain socket (`UnixListener`/`UnixStream`), so the
20// daemon runtime is Unix-only and gated `#[cfg(unix)]`; on Windows it runs only
21// under WSL2 (a real Linux kernel), and a native (non-WSL) Windows port is future
22// work (#1363). `paths` stays cross-platform because the request log and the
23// browser thin-client token discovery depend on it.
24pub mod paths;
25
26#[cfg(unix)]
27pub mod client;
28#[cfg(unix)]
29pub mod lifecycle;
30#[cfg(unix)]
31pub mod protocol;
32#[cfg(unix)]
33pub mod registry;
34#[cfg(unix)]
35pub mod selection;
36#[cfg(unix)]
37pub mod server;
38#[cfg(unix)]
39pub mod service;
40#[cfg(unix)]
41pub mod services;
42#[cfg(unix)]
43pub mod single_instance;
44
45#[cfg(all(unix, test))]
46pub(crate) mod testutil;
47
48#[cfg(target_os = "macos")]
49pub mod launchd;
50
51#[cfg(target_os = "linux")]
52pub mod systemd;
53
54#[cfg(all(target_os = "macos", feature = "menu-bar"))]
55pub mod tray;
56
57#[cfg(unix)]
58use std::path::Path;
59#[cfg(unix)]
60use std::path::PathBuf;
61#[cfg(unix)]
62use std::sync::Arc;
63
64#[cfg(unix)]
65use anyhow::Result;
66
67#[cfg(unix)]
68use crate::browser::BridgeConfig;
69#[cfg(unix)]
70use crate::snowflake::SnowflakeEngineConfig;
71#[cfg(unix)]
72use registry::ServiceRegistry;
73#[cfg(unix)]
74pub use selection::{DaemonServiceKind, ServiceSelection};
75#[cfg(unix)]
76use server::DaemonOptions;
77#[cfg(unix)]
78use services::bridge::BridgeService;
79#[cfg(unix)]
80use services::github_counters::GithubCountersService;
81#[cfg(unix)]
82use services::sessions::SessionsService;
83#[cfg(unix)]
84use services::snowflake::SnowflakeService;
85#[cfg(unix)]
86use services::worktrees::WorktreesService;
87
88/// Everything `daemon run` needs to start the daemon, resolved from the CLI.
89///
90/// Shared by the headless path ([`run_headless`]) and the macOS menu-bar path
91/// (`tray::run`) so both start an identical daemon. The latter is a plain code
92/// span, not an intra-doc link, because the `tray` module is feature- and
93/// target-gated and absent from the docs build.
94#[cfg(unix)]
95#[derive(Debug, Clone)]
96pub struct DaemonRunConfig {
97    /// Control-socket path (also the single-instance lock).
98    pub socket_path: PathBuf,
99    /// Browser-bridge configuration (ports, allow-origin, limits).
100    pub bridge_config: BridgeConfig,
101    /// Optional file the bridge session token is read from instead of generated.
102    pub bridge_token_file: Option<PathBuf>,
103    /// Where the resolved bridge token is persisted (`0600`) for thin clients.
104    pub bridge_token_path: PathBuf,
105    /// Which default-registry services to host (all, or an explicit subset).
106    pub services: ServiceSelection,
107}
108
109/// Builds the daemon's default service registry.
110///
111/// Starts the browser bridge on its loopback-TCP planes and registers it
112/// alongside the Snowflake query service, the cross-window worktrees registry,
113/// and the Claude Code sessions tracker.
114///
115/// `bridge_token_file` overrides token generation; `bridge_token_path` is where
116/// the resolved token is persisted (`0600`) for thin-client discovery. The
117/// Snowflake service is registered cheaply (no eager auth or I/O); its sessions
118/// are authenticated lazily on first query. The worktrees and sessions services
119/// are likewise cheap (in-memory only); they fill as VS Code windows register and
120/// as Claude Code hooks/transcripts report.
121///
122/// `services` selects which of the four to host. A service outside the selection
123/// is never constructed, so its startup work is skipped entirely — no bridge TCP
124/// planes, no worktrees pollers, no sessions watcher (#1318). The default
125/// ([`ServiceSelection::All`]) hosts everything.
126#[cfg(unix)]
127pub async fn build_default_registry(
128    bridge_config: BridgeConfig,
129    bridge_token_file: Option<&Path>,
130    bridge_token_path: PathBuf,
131    services: &ServiceSelection,
132) -> Result<ServiceRegistry> {
133    let mut registry = ServiceRegistry::new();
134    if services.includes(DaemonServiceKind::Bridge) {
135        let bridge =
136            BridgeService::start(bridge_config, bridge_token_file, bridge_token_path).await?;
137        registry.register(Arc::new(bridge));
138    }
139    if services.includes(DaemonServiceKind::Snowflake) {
140        let snowflake = SnowflakeService::new(SnowflakeEngineConfig::from_env_and_settings()?);
141        registry.register(Arc::new(snowflake));
142    }
143    if services.includes(DaemonServiceKind::Worktrees) {
144        // Start the off-thread menu-refresh loop so the tray serves a cached menu
145        // instead of running git enrichment on the macOS GUI thread (#1186 fix).
146        let worktrees = WorktreesService::new();
147        // Seed the per-repo PR-poll enable set from its persisted `0600` file so the
148        // user's choices survive a restart; the poller reads it below (#1376). A path
149        // that cannot be resolved (no data dir) just disables persistence.
150        match crate::daemon::paths::worktrees_polling_path() {
151            Ok(path) => worktrees.load_polling_prefs(path),
152            Err(err) => tracing::warn!("worktrees polling prefs disabled: {err:#}"),
153        }
154        // Seed the resolved PR-badge cache from its persisted `0600` file so a restart
155        // serves badges instantly and the poller can skip its immediate re-poll when
156        // they are still fresh (#1389, fix 4). Before `start_pr_poller` so the warm
157        // start is in place when the loop spawns; a path that cannot be resolved just
158        // disables persistence.
159        match crate::daemon::paths::worktrees_pr_cache_path() {
160            Ok(path) => worktrees.load_pr_cache(path),
161            Err(err) => tracing::warn!("worktrees PR cache disabled: {err:#}"),
162        }
163        worktrees.start_menu_refresh();
164        // Keep PR check badges fresh for every open window from one `gh` call, rather
165        // than each window resolving its own and none of them ever re-asking (#1337).
166        worktrees.start_pr_poller();
167        // Watch the GitHub API budget the PR poller (and every other `gh` on the box)
168        // spends, so `daemon status` / the tray surface an approaching exhaustion before
169        // it rate-limits everything — polling `/rate_limit` is exempt, so this is free
170        // (#1375). Share the cache with the registry for the built-in `status` op.
171        worktrees.start_rate_limit_poller();
172        let rate_limit_cache = worktrees.rate_limit_cache();
173        registry.register(Arc::new(worktrees));
174        registry.set_github_rate_limit(rate_limit_cache);
175    }
176    if services.includes(DaemonServiceKind::Sessions) {
177        // The cross-window Claude Code sessions tracker; start its transcript watcher
178        // (Feed 2) so sessions predating the daemon — and the hook-silent thinking
179        // window — are still tracked (#1210).
180        let sessions = SessionsService::new();
181        sessions.start_watcher();
182        registry.register(Arc::new(sessions));
183    }
184    // Periodically log a summary of the GitHub API-call counters (#1387): once
185    // ~5s after boot, every 10 minutes, and once on shutdown. Best-effort and
186    // bounded (a small local log read, no network); never blocks shutdown. Not one
187    // of the selectable services (#1318) — a daemon-wide observability concern that
188    // stays on for any subset.
189    let github_counters = GithubCountersService::new();
190    github_counters.start_counter_logger();
191    registry.register(Arc::new(github_counters));
192    Ok(registry)
193}
194
195/// Runs the daemon headlessly (no tray).
196///
197/// Builds the registry and serves until a signal or `daemon stop`. The default
198/// `daemon run` path on every platform, and the only path when the `menu-bar`
199/// feature is off.
200#[cfg(unix)]
201pub async fn run_headless(cfg: DaemonRunConfig) -> Result<()> {
202    let registry = build_default_registry(
203        cfg.bridge_config,
204        cfg.bridge_token_file.as_deref(),
205        cfg.bridge_token_path,
206        &cfg.services,
207    )
208    .await?;
209    server::run(
210        registry,
211        DaemonOptions {
212            socket_path: cfg.socket_path,
213        },
214    )
215    .await
216}
217
218#[cfg(all(unix, test))]
219#[allow(clippy::unwrap_used, clippy::expect_used)]
220mod tests {
221    use super::*;
222
223    /// A subset selection registers only the chosen services and, crucially,
224    /// never constructs the others — so their startup work does not run. Snowflake
225    /// is the cheap probe here: its `new()` does no eager auth or I/O, and gating
226    /// out the bridge means the test binds no TCP planes. See #1318.
227    #[tokio::test]
228    async fn build_default_registry_honours_a_subset() {
229        let selection = ServiceSelection::Only(vec![DaemonServiceKind::Snowflake]);
230        let registry = build_default_registry(
231            BridgeConfig::default(),
232            None,
233            PathBuf::from("/nonexistent/bridge.token"),
234            &selection,
235        )
236        .await
237        .expect("a snowflake-only registry builds without touching the bridge");
238
239        // Only the selected service is constructed, plus the always-on GitHub
240        // API-call counter logger (#1387) — daemon-wide observability that is not
241        // one of the four selectable kinds, so it rides along in any subset.
242        let names: Vec<_> = registry.services().iter().map(|s| s.name()).collect();
243        assert_eq!(names, vec![services::snowflake::SERVICE_NAME, "github"]);
244    }
245}