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 = BridgeService::start(bridge_config, bridge_token_file, bridge_token_path)?;
136        registry.register(Arc::new(bridge));
137    }
138    if services.includes(DaemonServiceKind::Snowflake) {
139        let snowflake = SnowflakeService::new(SnowflakeEngineConfig::from_env_and_settings()?);
140        registry.register(Arc::new(snowflake));
141    }
142    if services.includes(DaemonServiceKind::Worktrees) {
143        // Start the off-thread menu-refresh loop so the tray serves a cached menu
144        // instead of running git enrichment on the macOS GUI thread (#1186 fix).
145        let worktrees = WorktreesService::new();
146        // Seed the per-repo PR-poll enable set from its persisted `0600` file so the
147        // user's choices survive a restart; the poller reads it below (#1376). A path
148        // that cannot be resolved (no data dir) just disables persistence.
149        match crate::daemon::paths::worktrees_polling_path() {
150            Ok(path) => worktrees.load_polling_prefs(path),
151            Err(err) => tracing::warn!("worktrees polling prefs disabled: {err:#}"),
152        }
153        // Seed the resolved PR-badge cache from its persisted `0600` file so a restart
154        // serves badges instantly and the poller can skip its immediate re-poll when
155        // they are still fresh (#1389, fix 4). Before `start_pr_poller` so the warm
156        // start is in place when the loop spawns; a path that cannot be resolved just
157        // disables persistence.
158        match crate::daemon::paths::worktrees_pr_cache_path() {
159            Ok(path) => worktrees.load_pr_cache(path),
160            Err(err) => tracing::warn!("worktrees PR cache disabled: {err:#}"),
161        }
162        worktrees.start_menu_refresh();
163        // Keep PR check badges fresh for every open window from one `gh` call, rather
164        // than each window resolving its own and none of them ever re-asking (#1337).
165        worktrees.start_pr_poller();
166        // Watch the GitHub API budget the PR poller (and every other `gh` on the box)
167        // spends, so `daemon status` / the tray surface an approaching exhaustion before
168        // it rate-limits everything — polling `/rate_limit` is exempt, so this is free
169        // (#1375). Share the cache with the registry for the built-in `status` op.
170        worktrees.start_rate_limit_poller();
171        let rate_limit_cache = worktrees.rate_limit_cache();
172        registry.register(Arc::new(worktrees));
173        registry.set_github_rate_limit(rate_limit_cache);
174    }
175    if services.includes(DaemonServiceKind::Sessions) {
176        // The cross-window Claude Code sessions tracker; start its transcript watcher
177        // (Feed 2) so sessions predating the daemon — and the hook-silent thinking
178        // window — are still tracked (#1210).
179        let sessions = SessionsService::new();
180        sessions.start_watcher();
181        registry.register(Arc::new(sessions));
182    }
183    // Periodically log a summary of the GitHub API-call counters (#1387): once
184    // ~5s after boot, every 10 minutes, and once on shutdown. Best-effort and
185    // bounded (a small local log read, no network); never blocks shutdown. Not one
186    // of the selectable services (#1318) — a daemon-wide observability concern that
187    // stays on for any subset.
188    let github_counters = GithubCountersService::new();
189    github_counters.start_counter_logger();
190    registry.register(Arc::new(github_counters));
191    Ok(registry)
192}
193
194/// Runs the daemon headlessly (no tray).
195///
196/// Builds the registry and serves until a signal or `daemon stop`. The default
197/// `daemon run` path on every platform, and the only path when the `menu-bar`
198/// feature is off.
199#[cfg(unix)]
200pub async fn run_headless(cfg: DaemonRunConfig) -> Result<()> {
201    let registry = build_default_registry(
202        cfg.bridge_config,
203        cfg.bridge_token_file.as_deref(),
204        cfg.bridge_token_path,
205        &cfg.services,
206    )
207    .await?;
208    server::run(
209        registry,
210        DaemonOptions {
211            socket_path: cfg.socket_path,
212        },
213    )
214    .await
215}
216
217#[cfg(all(unix, test))]
218#[allow(clippy::unwrap_used, clippy::expect_used)]
219mod tests {
220    use super::*;
221
222    /// A subset selection registers only the chosen services and, crucially,
223    /// never constructs the others — so their startup work does not run. Snowflake
224    /// is the cheap probe here: its `new()` does no eager auth or I/O, and gating
225    /// out the bridge means the test binds no TCP planes. See #1318.
226    #[tokio::test]
227    async fn build_default_registry_honours_a_subset() {
228        let selection = ServiceSelection::Only(vec![DaemonServiceKind::Snowflake]);
229        let registry = build_default_registry(
230            BridgeConfig::default(),
231            None,
232            PathBuf::from("/nonexistent/bridge.token"),
233            &selection,
234        )
235        .await
236        .expect("a snowflake-only registry builds without touching the bridge");
237
238        // Only the selected service is constructed, plus the always-on GitHub
239        // API-call counter logger (#1387) — daemon-wide observability that is not
240        // one of the four selectable kinds, so it rides along in any subset.
241        let names: Vec<_> = registry.services().iter().map(|s| s.name()).collect();
242        assert_eq!(names, vec![services::snowflake::SERVICE_NAME, "github"]);
243    }
244}