Skip to main content

paper/daemon/
mod.rs

1//! Daemon core: IPC server, scheduler, watcher, resource guard, and auto-discovery.
2
3pub mod auto_discover;
4pub mod ipc;
5pub mod resource_guard;
6pub mod scheduler;
7pub mod watcher;
8
9pub use ipc::DaemonHandler;
10
11use crate::cli::Workspace;
12use crate::core::index::{init_db, Connection, Indexer};
13use crate::core::search::SharedEmbedder;
14use crate::daemon::auto_discover::discover_default_roots;
15use crate::daemon::ipc::{run_ipc_server, DaemonRequest, DaemonResponse};
16use crate::daemon::resource_guard::{PauseReason, ResourceGuard, ResourceGuardConfig};
17use crate::daemon::scheduler::RootAwareScheduler;
18use crate::daemon::watcher::Watcher;
19use anyhow::Result;
20use clap::Args;
21use std::path::PathBuf;
22use std::sync::Arc;
23use tokio::signal;
24use tokio::sync::{mpsc, Notify, RwLock};
25
26/// Arguments for the daemon subcommand.
27#[derive(Args, Debug, Clone)]
28pub struct DaemonArgs {
29    /// Run in foreground (don't daemonize)
30    #[arg(long)]
31    pub foreground: bool,
32
33    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock)
34    #[arg(long)]
35    pub socket: Option<PathBuf>,
36
37    /// Roots to index (default: auto-discover Documents, Downloads, Desktop)
38    #[arg(long, short)]
39    pub root: Vec<PathBuf>,
40
41    /// Disable file system watcher
42    #[arg(long)]
43    pub no_watch: bool,
44
45    /// Disable scheduler
46    #[arg(long)]
47    pub no_schedule: bool,
48
49    /// Disable resource guard (battery/CPU monitoring)
50    #[arg(long)]
51    pub no_resource_guard: bool,
52
53    /// Full reindex cron expression (default: "0 0 3 * * *" = daily 3 AM)
54    #[arg(long)]
55    pub full_cron: Option<String>,
56
57    /// Incremental index interval in seconds (default: 300 = 5 min)
58    #[arg(long)]
59    pub incremental_interval: Option<u64>,
60
61    /// Debounce time for file watcher in milliseconds (default: 250)
62    #[arg(long)]
63    pub debounce_ms: Option<u64>,
64
65    /// Battery threshold percentage (default: 20)
66    #[arg(long)]
67    pub battery_threshold: Option<u8>,
68
69    /// CPU threshold percentage (default: 80)
70    #[arg(long)]
71    pub cpu_threshold: Option<u8>,
72}
73
74/// Shared daemon state.
75///
76/// Deliberately does NOT hold an `Indexer` or `Connection`: rusqlite
77/// connections are not `Sync`, so each indexing request opens a fresh
78/// connection inside `spawn_blocking` (the same pattern the CLI uses).
79struct DaemonState {
80    roots: RwLock<Vec<PathBuf>>,
81    paused: RwLock<bool>,
82    shutdown: RwLock<bool>,
83    shutdown_notify: Arc<Notify>,
84    db_path: PathBuf,
85    embedder: Option<SharedEmbedder>,
86}
87
88/// Daemon request handler.
89struct DaemonHandlerImpl {
90    state: Arc<DaemonState>,
91    scheduler: Arc<RootAwareScheduler>,
92    watcher: Arc<RwLock<Option<Watcher>>>,
93}
94
95#[async_trait::async_trait]
96impl DaemonHandler for DaemonHandlerImpl {
97    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
98        match request {
99            DaemonRequest::IndexRoots { roots } => {
100                let roots_to_index = if roots.is_empty() {
101                    self.state.roots.read().await.clone()
102                } else {
103                    roots
104                };
105
106                if roots_to_index.is_empty() {
107                    return DaemonResponse::Error {
108                        msg: "No roots configured for indexing".to_string(),
109                    };
110                }
111
112                if *self.state.paused.read().await {
113                    return DaemonResponse::Error {
114                        msg: "Indexing paused by resource guard".to_string(),
115                    };
116                }
117
118                let db_path = self.state.db_path.clone();
119                let embedder = self.state.embedder.clone();
120
121                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
122                // create it inside the blocking task and run it there.
123                match tokio::task::spawn_blocking(
124                    move || -> Result<crate::core::index::IndexStats> {
125                        let conn = Connection::open(&db_path)?;
126                        init_db(&conn)?;
127                        let indexer = Indexer::new(conn, embedder)?;
128                        indexer.index_roots(&roots_to_index)
129                    },
130                )
131                .await
132                {
133                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
134                    Ok(Err(e)) => DaemonResponse::Error {
135                        msg: format!("Indexing failed: {e}"),
136                    },
137                    Err(e) => DaemonResponse::Error {
138                        msg: format!("Indexing task failed: {e}"),
139                    },
140                }
141            }
142            DaemonRequest::AddRoot { path } => {
143                if !path.exists() {
144                    return DaemonResponse::Error {
145                        msg: format!("Path does not exist: {}", path.display()),
146                    };
147                }
148
149                let mut roots = self.state.roots.write().await;
150                if !roots.contains(&path) {
151                    roots.push(path.clone());
152                    drop(roots);
153
154                    if let Some(watcher) = self.watcher.write().await.as_mut() {
155                        let _ = watcher.add_root(path.clone()).await;
156                    }
157                    self.scheduler.add_root(path).await;
158                }
159                DaemonResponse::Ok
160            }
161            DaemonRequest::RemoveRoot { path } => {
162                self.state.roots.write().await.retain(|r| r != &path);
163
164                if let Some(watcher) = self.watcher.write().await.as_mut() {
165                    let _ = watcher.remove_root(&path).await;
166                }
167                self.scheduler.remove_root(&path).await;
168                DaemonResponse::Ok
169            }
170            DaemonRequest::GetStatus => {
171                let paused = *self.state.paused.read().await;
172                // Open one connection and reuse it for both status queries
173                // instead of opening two separate connections (M15).
174                let (indexed_files, model) = match Connection::open(&self.state.db_path) {
175                    Ok(conn) => (
176                        Self::count_indexed_files(&conn),
177                        Self::stored_embedding_model(&conn),
178                    ),
179                    Err(_) => (0, None),
180                };
181
182                DaemonResponse::Status {
183                    indexed_files,
184                    queued: 0,
185                    paused,
186                    model,
187                }
188            }
189            DaemonRequest::Pause => {
190                *self.state.paused.write().await = true;
191                DaemonResponse::Ok
192            }
193            DaemonRequest::Resume => {
194                *self.state.paused.write().await = false;
195                DaemonResponse::Ok
196            }
197            DaemonRequest::Shutdown => {
198                // Signal shutdown via a flag and wake the dispatch loop; do not
199                // re-enqueue Shutdown on the same channel (IK).
200                *self.state.shutdown.write().await = true;
201                self.state.shutdown_notify.notify_waiters();
202                DaemonResponse::Ok
203            }
204        }
205    }
206}
207
208impl DaemonHandlerImpl {
209    fn count_indexed_files(conn: &Connection) -> usize {
210        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
211            .unwrap_or(0) as usize
212    }
213
214    fn stored_embedding_model(conn: &Connection) -> Option<String> {
215        conn.stored_embedding_model().ok().flatten()
216    }
217}
218
219/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
220pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
221    let workspace = Workspace::new();
222
223    // Determine socket path
224    let socket_path = args
225        .socket
226        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
227
228    // Ensure parent directory exists
229    if let Some(parent) = socket_path.parent() {
230        tokio::fs::create_dir_all(parent).await?;
231    }
232
233    // Determine roots to index. Explicit `--root` wins; otherwise the
234    // auto-discovered user directories are combined with any roots persisted in
235    // the config (by `daemon-control add-root` or the MCP add_index_root tool),
236    // so a root added once survives a reboot.
237    let roots = if args.root.is_empty() {
238        let mut roots = discover_default_roots();
239        for root in &workspace.config.roots {
240            if !roots.contains(root) {
241                roots.push(root.clone());
242            }
243        }
244        roots
245    } else {
246        args.root.clone()
247    };
248
249    if roots.is_empty() {
250        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
251    } else {
252        tracing::info!("Daemon will index: {:?}", roots);
253    }
254
255    // Download the default embedding model if this is a fresh install. Doing it
256    // here (rather than in the installer) covers every install channel, and
257    // doing it before the embedder is loaded means the first index pass already
258    // gets vectors instead of needing a reindex later.
259    #[cfg(feature = "daemon")]
260    crate::bootstrap::ensure_models(&workspace).await;
261
262    // Load the embedder once, after the download step above.
263    let embedder = workspace.embedder();
264    let db_path = workspace.paths.db_path();
265
266    // Create channels
267    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
268
269    // Create shared state
270    let state = Arc::new(DaemonState {
271        roots: RwLock::new(roots.clone()),
272        paused: RwLock::new(false),
273        shutdown: RwLock::new(false),
274        shutdown_notify: Arc::new(Notify::new()),
275        db_path,
276        embedder,
277    });
278
279    // Create scheduler
280    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
281    let incremental_interval = args
282        .incremental_interval
283        .map(std::time::Duration::from_secs)
284        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
285    let scheduler = Arc::new(RootAwareScheduler::new(
286        &full_cron,
287        incremental_interval,
288        request_tx.clone(),
289    )?);
290    scheduler.set_roots(roots.clone()).await;
291
292    // Create watcher
293    let debounce_ms = args.debounce_ms.unwrap_or(250);
294    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
295    for root in &roots {
296        watcher.add_root(root.clone()).await?;
297    }
298    let watcher = Arc::new(RwLock::new(Some(watcher)));
299
300    // Create resource guard
301    let mut resource_config = ResourceGuardConfig::default();
302    if let Some(b) = args.battery_threshold {
303        resource_config.battery_threshold = b;
304    }
305    if let Some(c) = args.cpu_threshold {
306        resource_config.cpu_threshold = c;
307    }
308    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));
309
310    // Create handler
311    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
312        state: state.clone(),
313        scheduler: scheduler.clone(),
314        watcher: watcher.clone(),
315    });
316
317    // Start components
318    if !args.no_schedule {
319        scheduler.start().await;
320
321        // First install: index now rather than waiting for the first
322        // incremental tick (the scheduler skips its immediate tick on start).
323        #[cfg(feature = "daemon")]
324        if crate::bootstrap::index_is_empty(&workspace.paths) {
325            tracing::info!("empty index — starting the first indexing pass");
326            scheduler.trigger_incremental().await;
327        }
328    }
329
330    if !args.no_watch {
331        if let Some(w) = watcher.write().await.as_mut() {
332            w.start().await?;
333        }
334    }
335
336    if !args.no_resource_guard {
337        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
338        resource_guard.start_monitoring(pause_tx);
339        let state = state.clone();
340        tokio::spawn(async move {
341            while let Some(reason) = pause_rx.recv().await {
342                match reason {
343                    PauseReason::Resumed => {
344                        *state.paused.write().await = false;
345                        tracing::info!("Resource guard: resuming indexing");
346                    }
347                    other => {
348                        *state.paused.write().await = true;
349                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
350                    }
351                }
352            }
353        });
354    }
355
356    // Start IPC server task
357    let socket_path_clone = socket_path.clone();
358    let handler_clone = handler.clone();
359    let ipc_handle = tokio::spawn(async move {
360        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
361            tracing::error!("IPC server error: {e}");
362        }
363    });
364
365    // Handle shutdown signals
366    let shutdown = async {
367        #[cfg(unix)]
368        {
369            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
370            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
371            tokio::select! {
372                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
373                _ = sigint.recv() => tracing::info!("Received SIGINT"),
374            }
375        }
376        #[cfg(windows)]
377        {
378            signal::ctrl_c().await?;
379            tracing::info!("Received Ctrl+C");
380        }
381        Ok::<(), anyhow::Error>(())
382    };
383
384    // Dispatch loop: requests from the scheduler and watcher are handled here;
385    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
386    let dispatch = async {
387        let state = state.clone();
388        loop {
389            tokio::select! {
390                // A request from the scheduler, watcher, or a directly-enqueued
391                // Shutdown.
392                request = request_rx.recv() => {
393                    match request {
394                        Some(request) => {
395                            if *state.shutdown.read().await || matches!(request, DaemonRequest::Shutdown) {
396                                break;
397                            }
398                            let handler = handler.clone();
399                            tokio::spawn(async move {
400                                let _ = handler.handle(request).await;
401                            });
402                        }
403                        None => break, // channel closed
404                    }
405                }
406                // Woken by the Shutdown handler (IK) so we can check the flag.
407                _ = state.shutdown_notify.notified() => {
408                    if *state.shutdown.read().await {
409                        break;
410                    }
411                }
412            }
413        }
414    };
415
416    // Run until shutdown signal or shutdown request
417    tokio::select! {
418        _ = shutdown => {
419            tracing::info!("Shutting down daemon...");
420        }
421        _ = dispatch => {
422            tracing::info!("Shutdown requested via IPC...");
423        }
424    }
425
426    // Graceful shutdown
427    scheduler.stop().await;
428
429    if let Some(w) = watcher.write().await.as_mut() {
430        w.stop().await;
431    }
432
433    ipc_handle.abort();
434    let _ = ipc_handle.await;
435
436    // Clean up socket file
437    let _ = tokio::fs::remove_file(&socket_path).await;
438
439    tracing::info!("Daemon stopped");
440    Ok(0)
441}