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;
4#[cfg(feature = "daemon")]
5pub mod auto_update;
6pub mod ipc;
7#[cfg(feature = "daemon")]
8pub mod remote;
9pub mod resource_guard;
10pub mod scheduler;
11pub mod watcher;
12
13pub use ipc::DaemonHandler;
14
15use crate::cli::Workspace;
16use crate::core::index::{init_db, Connection, Indexer};
17use crate::core::search::SharedEmbedder;
18use crate::daemon::auto_discover::discover_default_roots;
19use crate::daemon::ipc::{run_ipc_server, DaemonRequest, DaemonResponse};
20use crate::daemon::resource_guard::{PauseReason, ResourceGuard, ResourceGuardConfig};
21use crate::daemon::scheduler::RootAwareScheduler;
22use crate::daemon::watcher::Watcher;
23use anyhow::Result;
24use clap::Args;
25use std::path::PathBuf;
26use std::sync::Arc;
27use tokio::signal;
28use tokio::sync::{mpsc, Mutex, Notify, RwLock};
29
30/// Arguments for the daemon subcommand.
31#[derive(Args, Debug, Clone)]
32pub struct DaemonArgs {
33    /// Run in foreground (don't daemonize)
34    #[arg(long)]
35    pub foreground: bool,
36
37    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock)
38    #[arg(long)]
39    pub socket: Option<PathBuf>,
40
41    /// Roots to index (default: auto-discover Documents, Downloads, Desktop)
42    #[arg(long, short)]
43    pub root: Vec<PathBuf>,
44
45    /// Disable file system watcher
46    #[arg(long)]
47    pub no_watch: bool,
48
49    /// Disable scheduler
50    #[arg(long)]
51    pub no_schedule: bool,
52
53    /// Disable resource guard (battery/CPU monitoring)
54    #[arg(long)]
55    pub no_resource_guard: bool,
56
57    /// Full reindex cron expression (default: "0 0 3 * * *" = daily 3 AM)
58    #[arg(long)]
59    pub full_cron: Option<String>,
60
61    /// Incremental index interval in seconds (default: 300 = 5 min)
62    #[arg(long)]
63    pub incremental_interval: Option<u64>,
64
65    /// Debounce time for file watcher in milliseconds (default: 250)
66    #[arg(long)]
67    pub debounce_ms: Option<u64>,
68
69    /// Battery threshold percentage (default: 20)
70    #[arg(long)]
71    pub battery_threshold: Option<u8>,
72
73    /// CPU threshold percentage (default: 80)
74    #[arg(long)]
75    pub cpu_threshold: Option<u8>,
76}
77
78/// Shared daemon state.
79///
80/// Deliberately does NOT hold an `Indexer` or `Connection`: rusqlite
81/// connections are not `Sync`, so each indexing request opens a fresh
82/// connection inside `spawn_blocking` (the same pattern the CLI uses).
83struct DaemonState {
84    roots: RwLock<Vec<PathBuf>>,
85    paused: RwLock<bool>,
86    shutdown: RwLock<bool>,
87    shutdown_notify: Arc<Notify>,
88    db_path: PathBuf,
89    /// Swapped when a remote default moves the embedder.
90    embedder: RwLock<Option<SharedEmbedder>>,
91    /// Held for a whole `IndexRoots` job so scheduler, watcher and IPC runs
92    /// queue instead of overlapping and hitting SQLITE_BUSY.
93    index_lock: Mutex<()>,
94    /// Where the setup-status line lives; cleared when an index pass ends.
95    #[cfg(feature = "daemon")]
96    paths: crate::core::paths::Paths,
97}
98
99/// Clears the setup-status line on every exit path of an index request.
100#[cfg(feature = "daemon")]
101struct ClearSetupStatus<'a>(&'a crate::core::paths::Paths);
102
103#[cfg(feature = "daemon")]
104impl Drop for ClearSetupStatus<'_> {
105    fn drop(&mut self) {
106        crate::bootstrap::clear_setup_status(self.0);
107    }
108}
109
110/// One indexing pass. When it covers exactly the configured roots (the
111/// scheduled passes) it also prunes files deleted since the last pass.
112fn run_index_job(
113    db_path: &std::path::Path,
114    embedder: Option<SharedEmbedder>,
115    roots: &[PathBuf],
116    configured: &[PathBuf],
117) -> Result<crate::core::index::IndexStats> {
118    let conn = Connection::open(db_path)?;
119    init_db(&conn)?;
120    let indexer = Indexer::new(conn, embedder)?;
121    let stats = indexer.index_roots_within(roots, configured)?;
122    let sorted = |v: &[PathBuf]| {
123        let mut v = v.to_vec();
124        v.sort();
125        v
126    };
127    if sorted(roots) == sorted(configured) {
128        indexer.prune_missing()?;
129    }
130    Ok(stats)
131}
132
133/// Daemon request handler.
134struct DaemonHandlerImpl {
135    state: Arc<DaemonState>,
136    scheduler: Arc<RootAwareScheduler>,
137    watcher: Arc<RwLock<Option<Watcher>>>,
138}
139
140#[async_trait::async_trait]
141impl DaemonHandler for DaemonHandlerImpl {
142    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
143        match request {
144            DaemonRequest::IndexRoots { roots } => {
145                #[cfg(feature = "daemon")]
146                let _clear_status = ClearSetupStatus(&self.state.paths);
147                let roots_to_index = if roots.is_empty() {
148                    self.state.roots.read().await.clone()
149                } else {
150                    roots
151                };
152
153                if roots_to_index.is_empty() {
154                    return DaemonResponse::Error {
155                        msg: "No roots configured for indexing".to_string(),
156                    };
157                }
158
159                if *self.state.paused.read().await {
160                    return DaemonResponse::Error {
161                        msg: "Indexing paused by resource guard".to_string(),
162                    };
163                }
164
165                let db_path = self.state.db_path.clone();
166                let embedder = self.state.embedder.read().await.clone();
167                // A file named directly (the watcher sends changed files) is
168                // checked against the configured root it lives under.
169                let configured = self.state.roots.read().await.clone();
170
171                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
172                // create it inside the blocking task and run it there.
173                let _running = self.state.index_lock.lock().await;
174                match tokio::task::spawn_blocking(move || {
175                    run_index_job(&db_path, embedder, &roots_to_index, &configured)
176                })
177                .await
178                {
179                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
180                    Ok(Err(e)) => DaemonResponse::Error {
181                        msg: format!("Indexing failed: {e:#}"),
182                    },
183                    Err(e) => DaemonResponse::Error {
184                        msg: format!("Indexing task failed: {e:#}"),
185                    },
186                }
187            }
188            DaemonRequest::AddRoot { path } => {
189                if !path.exists() {
190                    return DaemonResponse::Error {
191                        msg: format!("Path does not exist: {}", path.display()),
192                    };
193                }
194
195                let mut roots = self.state.roots.write().await;
196                if !roots.contains(&path) {
197                    roots.push(path.clone());
198                    drop(roots);
199
200                    if let Some(watcher) = self.watcher.write().await.as_mut() {
201                        let _ = watcher.add_root(path.clone()).await;
202                    }
203                    self.scheduler.add_root(path).await;
204                }
205                DaemonResponse::Ok
206            }
207            DaemonRequest::RemoveRoot { path } => {
208                self.state.roots.write().await.retain(|r| r != &path);
209
210                if let Some(watcher) = self.watcher.write().await.as_mut() {
211                    let _ = watcher.remove_root(&path).await;
212                }
213                self.scheduler.remove_root(&path).await;
214                DaemonResponse::Ok
215            }
216            DaemonRequest::GetStatus => {
217                let paused = *self.state.paused.read().await;
218                // Open one connection and reuse it for both status queries
219                // instead of opening two separate connections (M15).
220                let (indexed_files, model) = match Connection::open(&self.state.db_path) {
221                    Ok(conn) => (
222                        Self::count_indexed_files(&conn),
223                        Self::stored_embedding_model(&conn),
224                    ),
225                    Err(_) => (0, None),
226                };
227
228                DaemonResponse::Status {
229                    indexed_files,
230                    queued: 0,
231                    paused,
232                    model,
233                }
234            }
235            DaemonRequest::Pause => {
236                *self.state.paused.write().await = true;
237                DaemonResponse::Ok
238            }
239            DaemonRequest::Resume => {
240                *self.state.paused.write().await = false;
241                DaemonResponse::Ok
242            }
243            DaemonRequest::Shutdown => {
244                // Signal shutdown via a flag and wake the dispatch loop; do not
245                // re-enqueue Shutdown on the same channel (IK).
246                *self.state.shutdown.write().await = true;
247                self.state.shutdown_notify.notify_waiters();
248                DaemonResponse::Ok
249            }
250        }
251    }
252}
253
254impl DaemonHandlerImpl {
255    fn count_indexed_files(conn: &Connection) -> usize {
256        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
257            .unwrap_or(0) as usize
258    }
259
260    fn stored_embedding_model(conn: &Connection) -> Option<String> {
261        conn.stored_embedding_model().ok().flatten()
262    }
263}
264
265/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
266pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
267    let workspace = Arc::new(Workspace::new());
268
269    // Determine socket path
270    let socket_path = args
271        .socket
272        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
273
274    // Ensure parent directory exists
275    if let Some(parent) = socket_path.parent() {
276        crate::core::paths::create_private_dir(parent)?;
277    }
278
279    // Determine roots to index. Explicit `--root` wins; otherwise the
280    // auto-discovered user directories are combined with any roots persisted in
281    // the config (by `daemon-control add-root` or the MCP add_index_root tool),
282    // so a root added once survives a reboot.
283    let roots = if args.root.is_empty() {
284        let mut roots = discover_default_roots();
285        for root in &workspace.config.roots {
286            if !roots.contains(root) {
287                roots.push(root.clone());
288            }
289        }
290        roots
291    } else {
292        args.root.clone()
293    };
294
295    if roots.is_empty() {
296        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
297    } else {
298        tracing::info!("Daemon will index: {:?}", roots);
299    }
300
301    // Download the default embedding model if this is a fresh install. Doing it
302    // here (rather than in the installer) covers every install channel, and
303    // doing it before the embedder is loaded means the first index pass already
304    // gets vectors instead of needing a reindex later.
305    #[cfg(feature = "daemon")]
306    crate::bootstrap::ensure_models(&workspace).await;
307
308    // The first pass (queued below) clears this line when it ends; with no
309    // first pass to wait for, the download step was the last background work.
310    #[cfg(feature = "daemon")]
311    let first_pass = !args.no_schedule && crate::bootstrap::index_is_empty(&workspace.paths);
312    #[cfg(feature = "daemon")]
313    if first_pass {
314        crate::bootstrap::set_setup_status(
315            &workspace.paths,
316            "indexing your documents for the first time",
317        );
318    } else {
319        crate::bootstrap::clear_setup_status(&workspace.paths);
320    }
321
322    // Load the embedder once, after the download step above.
323    let embedder = workspace.embedder();
324    let db_path = workspace.paths.db_path();
325
326    // Create channels
327    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
328
329    // Create shared state
330    let state = Arc::new(DaemonState {
331        roots: RwLock::new(roots.clone()),
332        paused: RwLock::new(false),
333        shutdown: RwLock::new(false),
334        shutdown_notify: Arc::new(Notify::new()),
335        db_path,
336        embedder: RwLock::new(embedder),
337        index_lock: Mutex::new(()),
338        #[cfg(feature = "daemon")]
339        paths: crate::core::paths::Paths::new(),
340    });
341
342    // Fetch the remote config now and daily, follow its defaults, and finish
343    // any interrupted re-embed (the re-embed holds `index_lock`). This also
344    // downloads the effective reranker without delaying the first index pass.
345    #[cfg(feature = "daemon")]
346    auto_update::check_after_restart();
347    #[cfg(feature = "daemon")]
348    tokio::spawn(remote::run_loop(workspace.clone(), state.clone()));
349
350    // Create scheduler
351    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
352    let incremental_interval = args
353        .incremental_interval
354        .map(std::time::Duration::from_secs)
355        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
356    let scheduler = Arc::new(RootAwareScheduler::new(
357        &full_cron,
358        incremental_interval,
359        request_tx.clone(),
360    )?);
361    scheduler.set_roots(roots.clone()).await;
362
363    // Create watcher
364    let debounce_ms = args.debounce_ms.unwrap_or(250);
365    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
366    for root in &roots {
367        watcher.add_root(root.clone()).await?;
368    }
369    let watcher = Arc::new(RwLock::new(Some(watcher)));
370
371    // Create resource guard
372    let mut resource_config = ResourceGuardConfig::default();
373    if let Some(b) = args.battery_threshold {
374        resource_config.battery_threshold = b;
375    }
376    if let Some(c) = args.cpu_threshold {
377        resource_config.cpu_threshold = c;
378    }
379    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));
380
381    // Create handler
382    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
383        state: state.clone(),
384        scheduler: scheduler.clone(),
385        watcher: watcher.clone(),
386    });
387
388    // Start components
389    if !args.no_schedule {
390        scheduler.start().await;
391
392        // First install: index now rather than waiting for the first
393        // incremental tick (the scheduler skips its immediate tick on start).
394        #[cfg(feature = "daemon")]
395        if first_pass {
396            tracing::info!("empty index — starting the first indexing pass");
397            scheduler.trigger_incremental().await;
398        }
399    }
400
401    if !args.no_watch {
402        if let Some(w) = watcher.write().await.as_mut() {
403            w.start().await?;
404        }
405    }
406
407    if !args.no_resource_guard {
408        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
409        resource_guard.start_monitoring(pause_tx);
410        let state = state.clone();
411        tokio::spawn(async move {
412            while let Some(reason) = pause_rx.recv().await {
413                match reason {
414                    PauseReason::Resumed => {
415                        *state.paused.write().await = false;
416                        tracing::info!("Resource guard: resuming indexing");
417                    }
418                    other => {
419                        *state.paused.write().await = true;
420                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
421                    }
422                }
423            }
424        });
425    }
426
427    // Start IPC server task
428    let socket_path_clone = socket_path.clone();
429    let handler_clone = handler.clone();
430    let ipc_handle = tokio::spawn(async move {
431        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
432            tracing::error!("IPC server error: {e:#}");
433        }
434    });
435
436    // Handle shutdown signals
437    let shutdown = async {
438        #[cfg(unix)]
439        {
440            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
441            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
442            tokio::select! {
443                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
444                _ = sigint.recv() => tracing::info!("Received SIGINT"),
445            }
446        }
447        #[cfg(windows)]
448        {
449            signal::ctrl_c().await?;
450            tracing::info!("Received Ctrl+C");
451        }
452        Ok::<(), anyhow::Error>(())
453    };
454
455    // Dispatch loop: requests from the scheduler and watcher are handled here;
456    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
457    let dispatch = async {
458        let state = state.clone();
459        loop {
460            tokio::select! {
461                // A request from the scheduler, watcher, or a directly-enqueued
462                // Shutdown.
463                request = request_rx.recv() => {
464                    match request {
465                        Some(request) => {
466                            if *state.shutdown.read().await || matches!(request, DaemonRequest::Shutdown) {
467                                break;
468                            }
469                            let handler = handler.clone();
470                            tokio::spawn(async move {
471                                let _ = handler.handle(request).await;
472                            });
473                        }
474                        None => break, // channel closed
475                    }
476                }
477                // Woken by the Shutdown handler (IK) so we can check the flag.
478                _ = state.shutdown_notify.notified() => {
479                    if *state.shutdown.read().await {
480                        break;
481                    }
482                }
483            }
484        }
485    };
486
487    // Run until shutdown signal or shutdown request
488    tokio::select! {
489        _ = shutdown => {
490            tracing::info!("Shutting down daemon...");
491        }
492        _ = dispatch => {
493            tracing::info!("Shutdown requested via IPC...");
494        }
495    }
496
497    // Graceful shutdown
498    scheduler.stop().await;
499
500    if let Some(w) = watcher.write().await.as_mut() {
501        w.stop().await;
502    }
503
504    ipc_handle.abort();
505    let _ = ipc_handle.await;
506
507    // Clean up socket file
508    let _ = tokio::fs::remove_file(&socket_path).await;
509
510    tracing::info!("Daemon stopped");
511    Ok(0)
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    #[test]
519    fn the_configured_pass_prunes_deleted_files_but_a_partial_one_does_not() {
520        let dir = tempfile::tempdir().unwrap();
521        let root = dir.path().join("docs");
522        std::fs::create_dir(&root).unwrap();
523        let (a, b) = (root.join("a.txt"), root.join("b.txt"));
524        std::fs::write(&a, "alpha zebra").unwrap();
525        std::fs::write(&b, "beta giraffe").unwrap();
526        let db = dir.path().join("chunks.db");
527        let configured = vec![root.clone()];
528        run_index_job(&db, None, &configured, &configured).unwrap();
529        std::fs::remove_file(&a).unwrap();
530        // A watcher-style pass over one other path must not prune.
531        run_index_job(&db, None, std::slice::from_ref(&b), &configured).unwrap();
532        let count = |p: &str| -> i64 {
533            Connection::open(&db)
534                .unwrap()
535                .inner()
536                .query_row(
537                    "SELECT COUNT(*) FROM chunks WHERE source_path = ?",
538                    [p],
539                    |r| r.get(0),
540                )
541                .unwrap()
542        };
543        let a = a.to_string_lossy().to_string();
544        assert_eq!(count(&a), 1);
545        run_index_job(&db, None, &configured, &configured).unwrap();
546        assert_eq!(count(&a), 0);
547    }
548}