Skip to main content

paper/cli/
daemon.rs

1//! CLI control and OS service integration for the Paper daemon.
2
3use crate::core::paths::Paths;
4#[cfg(unix)]
5use crate::daemon::ipc::IpcClient;
6use crate::daemon::ipc::{DaemonRequest, DaemonResponse};
7#[cfg(unix)]
8use anyhow::Context;
9use anyhow::{bail, Result};
10use clap::{Args, Subcommand};
11#[cfg(any(target_os = "linux", target_os = "macos"))]
12use std::fs;
13#[cfg(any(target_os = "linux", target_os = "macos"))]
14use std::io::Write;
15use std::path::{Path, PathBuf};
16#[cfg(any(target_os = "linux", target_os = "macos"))]
17use std::process::Command;
18#[cfg(unix)]
19use std::time::Duration;
20
21#[cfg(unix)]
22const IPC_TIMEOUT: Duration = Duration::from_secs(5);
23const LAUNCHD_LABEL: &str = "tools.kintsugi.paper";
24#[cfg(target_os = "linux")]
25const SYSTEMD_SERVICE_NAME: &str = "paper.service";
26
27/// Control a running daemon or manage its OS service.
28#[derive(Args, Debug)]
29pub struct DaemonControlArgs {
30    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock).
31    #[arg(long, global = true)]
32    pub socket: Option<PathBuf>,
33
34    #[command(subcommand)]
35    pub command: DaemonControlCommand,
36}
37
38#[derive(Subcommand, Debug)]
39pub enum DaemonControlCommand {
40    /// Show daemon status.
41    Status {
42        /// Emit the status response as JSON.
43        #[arg(long)]
44        json: bool,
45    },
46    /// Pause indexing.
47    Pause,
48    /// Resume indexing.
49    Resume,
50    /// Index roots now (no roots = the daemon's configured roots).
51    Index {
52        #[arg(long)]
53        root: Vec<PathBuf>,
54    },
55    /// Add a root to watch and index.
56    AddRoot { path: PathBuf },
57    /// Remove a root from watching and indexing.
58    RemoveRoot { path: PathBuf },
59    /// Ask the daemon to shut down gracefully.
60    Stop,
61    /// Install and start Paper as a user service.
62    Install {
63        /// Overwrite an existing, different service definition.
64        #[arg(long)]
65        force: bool,
66    },
67    /// Stop and remove the Paper user service.
68    Uninstall,
69    /// Start the installed Paper user service.
70    Start,
71    /// Restart the installed Paper user service.
72    Restart,
73}
74
75pub async fn run(args: DaemonControlArgs) -> Result<i32> {
76    let DaemonControlArgs { socket, command } = args;
77    let socket_path = socket.unwrap_or_else(|| Paths::new().base_dir().join("daemon.sock"));
78
79    match command {
80        DaemonControlCommand::Status { json } => {
81            let response = send_request(&socket_path, DaemonRequest::GetStatus).await?;
82            print_status(&response, json)?;
83        }
84        DaemonControlCommand::Pause => {
85            expect_ok(send_request(&socket_path, DaemonRequest::Pause).await?)?;
86            println!("Daemon indexing paused.");
87        }
88        DaemonControlCommand::Resume => {
89            expect_ok(send_request(&socket_path, DaemonRequest::Resume).await?)?;
90            println!("Daemon indexing resumed.");
91        }
92        DaemonControlCommand::Index { root } => {
93            let response =
94                send_request(&socket_path, DaemonRequest::IndexRoots { roots: root }).await?;
95            match response {
96                DaemonResponse::IndexRoots { stats } => {
97                    println!(
98                        "Indexed {} file(s) ({} chunks); {} scanned, {} unchanged, {} skipped, {} warning(s).",
99                        stats.indexed,
100                        stats.chunks,
101                        stats.scanned,
102                        stats.unchanged,
103                        stats.skipped,
104                        stats.warnings
105                    );
106                }
107                DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
108                other => bail!("unexpected daemon response to index request: {other:?}"),
109            }
110        }
111        DaemonControlCommand::AddRoot { path } => {
112            let path = canonical_or_original(&path);
113            persist_root(Some(&path), None)?;
114            expect_ok(
115                send_request(&socket_path, DaemonRequest::AddRoot { path: path.clone() }).await?,
116            )?;
117            println!("Added indexing root: {}", path.display());
118        }
119        DaemonControlCommand::RemoveRoot { path } => {
120            let path = canonical_or_original(&path);
121            persist_root(None, Some(&path))?;
122            expect_ok(
123                send_request(
124                    &socket_path,
125                    DaemonRequest::RemoveRoot { path: path.clone() },
126                )
127                .await?,
128            )?;
129            println!("Removed indexing root: {}", path.display());
130        }
131        DaemonControlCommand::Stop => {
132            expect_ok(send_request(&socket_path, DaemonRequest::Shutdown).await?)?;
133            println!("Daemon shutdown requested.");
134        }
135        DaemonControlCommand::Install { force } => {
136            let path = install_service(force)?;
137            println!("Installed and started Paper service: {}", path.display());
138        }
139        DaemonControlCommand::Uninstall => {
140            let path = uninstall_service()?;
141            println!("Uninstalled Paper service: {}", path.display());
142        }
143        DaemonControlCommand::Start => {
144            start_service()?;
145            println!("Started Paper service.");
146        }
147        DaemonControlCommand::Restart => {
148            restart_service()?;
149            println!("Restarted Paper service.");
150        }
151    }
152
153    Ok(super::EXIT_FOUND)
154}
155
156fn print_status(response: &DaemonResponse, json: bool) -> Result<()> {
157    match response {
158        DaemonResponse::Status {
159            indexed_files,
160            queued,
161            paused,
162            model,
163        } => {
164            if json {
165                println!("{}", serde_json::to_string(response)?);
166            } else {
167                println!("Indexed files: {indexed_files}");
168                println!("Queued: {queued}");
169                println!("Paused: {paused}");
170                println!("Model: {}", model.as_deref().unwrap_or("none"));
171            }
172            Ok(())
173        }
174        DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
175        other => bail!("unexpected daemon response to status request: {other:?}"),
176    }
177}
178
179fn expect_ok(response: DaemonResponse) -> Result<()> {
180    match response {
181        DaemonResponse::Ok => Ok(()),
182        DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
183        other => bail!("unexpected daemon response: {other:?}"),
184    }
185}
186
187#[cfg(unix)]
188async fn send_request(socket_path: &Path, request: DaemonRequest) -> Result<DaemonResponse> {
189    let operation = async {
190        let mut client = IpcClient::connect(socket_path).await.with_context(|| {
191            format!(
192                "could not connect to paper daemon at {}; start it with `paper daemon --foreground` or run `paper daemon-control install`",
193                socket_path.display()
194            )
195        })?;
196        client.send(request).await.with_context(|| {
197            format!(
198                "communicating with paper daemon at {}",
199                socket_path.display()
200            )
201        })
202    };
203
204    tokio::time::timeout(IPC_TIMEOUT, operation)
205        .await
206        .map_err(|_| {
207            anyhow::anyhow!(
208                "paper daemon at {} did not respond within {} seconds",
209                socket_path.display(),
210                IPC_TIMEOUT.as_secs()
211            )
212        })?
213}
214
215#[cfg(not(unix))]
216async fn send_request(_socket_path: &Path, _request: DaemonRequest) -> Result<DaemonResponse> {
217    bail!("daemon IPC is not yet supported on Windows")
218}
219
220/// Render a systemd user unit without touching the host service manager.
221pub fn render_systemd_unit(exe_path: &Path) -> String {
222    let exe = systemd_argument(&exe_path.to_string_lossy());
223    format!(
224        "# Managed by `paper daemon-control`.\n\
225         [Unit]\n\
226         Description=Paper local document index daemon\n\n\
227         [Service]\n\
228         Type=simple\n\
229         ExecStart={exe} daemon --foreground\n\
230         Restart=on-failure\n\n\
231         [Install]\n\
232         WantedBy=default.target\n"
233    )
234}
235
236fn systemd_argument(value: &str) -> String {
237    let escaped = value
238        .replace('\\', "\\\\")
239        .replace('"', "\\\"")
240        .replace('%', "%%");
241    format!("\"{escaped}\"")
242}
243
244/// Render a launchd user agent without touching the host service manager.
245pub fn render_launchd_plist(exe_path: &Path, cache_dir: &Path) -> String {
246    let exe = xml_escape(&exe_path.to_string_lossy());
247    let stdout = xml_escape(&format!(
248        "{}/daemon.stdout.log",
249        cache_dir.to_string_lossy().replace('\\', "/")
250    ));
251    let stderr = xml_escape(&format!(
252        "{}/daemon.stderr.log",
253        cache_dir.to_string_lossy().replace('\\', "/")
254    ));
255    format!(
256        r#"<?xml version="1.0" encoding="UTF-8"?>
257<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
258<!-- Managed by `paper daemon-control`. -->
259<plist version="1.0">
260  <dict>
261    <key>Label</key>
262    <string>{LAUNCHD_LABEL}</string>
263    <key>ProgramArguments</key>
264    <array>
265      <string>{exe}</string>
266      <string>daemon</string>
267      <string>--foreground</string>
268    </array>
269    <key>RunAtLoad</key>
270    <true/>
271    <key>KeepAlive</key>
272    <false/>
273    <key>StandardOutPath</key>
274    <string>{stdout}</string>
275    <key>StandardErrorPath</key>
276    <string>{stderr}</string>
277  </dict>
278</plist>
279"#
280    )
281}
282
283fn xml_escape(value: &str) -> String {
284    value
285        .replace('&', "&amp;")
286        .replace('<', "&lt;")
287        .replace('>', "&gt;")
288        .replace('"', "&quot;")
289        .replace('\'', "&apos;")
290}
291
292#[cfg(any(target_os = "linux", target_os = "macos"))]
293fn install_service_file(path: &Path, contents: &str, force: bool) -> Result<()> {
294    if !force && path.exists() {
295        let existing = fs::read_to_string(path)
296            .with_context(|| format!("reading existing service file {}", path.display()))?;
297        if existing != contents {
298            bail!(
299                "service file {} already exists with different contents; use `paper daemon-control install --force` to replace it",
300                path.display()
301            );
302        }
303    }
304    atomic_write(path, contents)
305}
306
307#[cfg(any(target_os = "linux", target_os = "macos"))]
308fn atomic_write(path: &Path, contents: &str) -> Result<()> {
309    let parent = path
310        .parent()
311        .with_context(|| format!("service path has no parent: {}", path.display()))?;
312    fs::create_dir_all(parent)
313        .with_context(|| format!("creating service directory {}", parent.display()))?;
314    let file_name = path
315        .file_name()
316        .with_context(|| format!("service path has no file name: {}", path.display()))?;
317    let temp_path = parent.join(format!(
318        ".{}.{}.tmp",
319        file_name.to_string_lossy(),
320        std::process::id()
321    ));
322
323    let result = (|| -> Result<()> {
324        let mut file = fs::OpenOptions::new()
325            .write(true)
326            .create_new(true)
327            .open(&temp_path)
328            .with_context(|| format!("creating temporary service file {}", temp_path.display()))?;
329        file.write_all(contents.as_bytes())
330            .with_context(|| format!("writing temporary service file {}", temp_path.display()))?;
331        file.sync_all()
332            .with_context(|| format!("syncing temporary service file {}", temp_path.display()))?;
333        fs::rename(&temp_path, path).with_context(|| {
334            format!(
335                "renaming temporary service file {} to {}",
336                temp_path.display(),
337                path.display()
338            )
339        })?;
340        Ok(())
341    })();
342
343    if result.is_err() {
344        let _ = fs::remove_file(&temp_path);
345    }
346    result
347}
348
349#[cfg(any(target_os = "linux", target_os = "macos"))]
350fn remove_service_file(path: &Path) -> Result<()> {
351    match fs::remove_file(path) {
352        Ok(()) => Ok(()),
353        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
354        Err(error) => {
355            Err(error).with_context(|| format!("removing service file {}", path.display()))
356        }
357    }
358}
359
360#[cfg(any(target_os = "linux", target_os = "macos"))]
361fn require_service_installed(path: &Path) -> Result<()> {
362    if !path.is_file() {
363        bail!("Paper service is not installed; run `paper daemon-control install` first");
364    }
365    Ok(())
366}
367
368#[cfg(any(target_os = "linux", target_os = "macos"))]
369fn run_checked(command: &mut Command) -> Result<()> {
370    let display = format!("{command:?}");
371    let output = command
372        .output()
373        .with_context(|| format!("running {display}"))?;
374    if output.status.success() {
375        return Ok(());
376    }
377
378    let stderr = String::from_utf8_lossy(&output.stderr);
379    let stdout = String::from_utf8_lossy(&output.stdout);
380    let details = if stderr.trim().is_empty() {
381        stdout.trim()
382    } else {
383        stderr.trim()
384    };
385    bail!("{display} failed with {}: {details}", output.status)
386}
387
388#[cfg(target_os = "linux")]
389fn systemd_unit_path() -> Result<PathBuf> {
390    let config = dirs::config_dir().context("could not determine the user config directory")?;
391    Ok(config.join("systemd/user").join(SYSTEMD_SERVICE_NAME))
392}
393
394#[cfg(target_os = "linux")]
395fn install_service(force: bool) -> Result<PathBuf> {
396    let path = systemd_unit_path()?;
397    let exe = std::env::current_exe().context("locating the current paper executable")?;
398    let unit = render_systemd_unit(&exe);
399    install_service_file(&path, &unit, force)?;
400
401    run_checked(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
402    run_checked(Command::new("systemctl").args([
403        "--user",
404        "enable",
405        "--now",
406        SYSTEMD_SERVICE_NAME,
407    ]))?;
408    Ok(path)
409}
410
411#[cfg(target_os = "linux")]
412fn uninstall_service() -> Result<PathBuf> {
413    let path = systemd_unit_path()?;
414    if let Err(error) = run_checked(Command::new("systemctl").args([
415        "--user",
416        "disable",
417        "--now",
418        SYSTEMD_SERVICE_NAME,
419    ])) {
420        tracing::warn!("Could not disable the Paper service cleanly: {error:#}");
421    }
422    remove_service_file(&path)?;
423    run_checked(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
424    Ok(path)
425}
426
427#[cfg(target_os = "linux")]
428fn start_service() -> Result<()> {
429    require_service_installed(&systemd_unit_path()?)?;
430    run_checked(Command::new("systemctl").args(["--user", "start", SYSTEMD_SERVICE_NAME]))
431}
432
433#[cfg(target_os = "linux")]
434fn restart_service() -> Result<()> {
435    require_service_installed(&systemd_unit_path()?)?;
436    run_checked(Command::new("systemctl").args(["--user", "restart", SYSTEMD_SERVICE_NAME]))
437}
438
439#[cfg(target_os = "macos")]
440fn launchd_plist_path() -> Result<PathBuf> {
441    let home = dirs::home_dir().context("could not determine the user home directory")?;
442    Ok(home
443        .join("Library/LaunchAgents")
444        .join(format!("{LAUNCHD_LABEL}.plist")))
445}
446
447#[cfg(target_os = "macos")]
448fn current_uid() -> Result<String> {
449    let output = Command::new("id")
450        .arg("-u")
451        .output()
452        .context("running `id -u` for launchd")?;
453    if !output.status.success() {
454        bail!("`id -u` failed with {}", output.status);
455    }
456    let uid = String::from_utf8(output.stdout).context("decoding `id -u` output")?;
457    let uid = uid.trim();
458    if uid.is_empty() {
459        bail!("`id -u` returned an empty user ID");
460    }
461    Ok(uid.to_string())
462}
463
464#[cfg(target_os = "macos")]
465fn load_launchd_service(domain: &str, path: &Path) -> Result<()> {
466    // Boot out any already-loaded copy first. `bootstrap` refuses to replace an
467    // existing job, so without this a reinstall that changes the binary path
468    // leaves launchd running the old, possibly deleted, executable forever
469    // (spawning it fails and the job exits 78, EX_CONFIG).
470    let service = format!("{domain}/{LAUNCHD_LABEL}");
471    let _ = run_checked(Command::new("launchctl").args(["bootout", &service]));
472
473    let bootstrap = run_checked(
474        Command::new("launchctl")
475            .args(["bootstrap", domain])
476            .arg(path),
477    );
478    if let Err(bootstrap_error) = bootstrap {
479        run_checked(Command::new("launchctl").arg("load").arg(path)).with_context(|| {
480            format!("launchctl bootstrap failed ({bootstrap_error:#}); `launchctl load` fallback also failed")
481        })?;
482    }
483    Ok(())
484}
485
486#[cfg(target_os = "macos")]
487fn install_service(force: bool) -> Result<PathBuf> {
488    let path = launchd_plist_path()?;
489    let exe = std::env::current_exe().context("locating the current paper executable")?;
490    let cache_dir = Paths::new().base_dir();
491    fs::create_dir_all(&cache_dir)
492        .with_context(|| format!("creating Paper cache directory {}", cache_dir.display()))?;
493    let plist = render_launchd_plist(&exe, &cache_dir);
494    install_service_file(&path, &plist, force)?;
495
496    let domain = format!("gui/{}", current_uid()?);
497    load_launchd_service(&domain, &path)?;
498    Ok(path)
499}
500
501#[cfg(target_os = "macos")]
502fn uninstall_service() -> Result<PathBuf> {
503    let path = launchd_plist_path()?;
504    let domain = format!("gui/{}", current_uid()?);
505    let bootout = run_checked(
506        Command::new("launchctl")
507            .args(["bootout", &domain])
508            .arg(&path),
509    );
510    if let Err(bootout_error) = bootout {
511        if let Err(unload_error) = run_checked(Command::new("launchctl").arg("unload").arg(&path)) {
512            tracing::warn!(
513                "Could not unload the Paper launchd agent cleanly (bootout: {bootout_error:#}; unload: {unload_error:#})"
514            );
515        }
516    }
517    remove_service_file(&path)?;
518    Ok(path)
519}
520
521#[cfg(target_os = "macos")]
522fn start_service() -> Result<()> {
523    let path = launchd_plist_path()?;
524    require_service_installed(&path)?;
525    let domain = format!("gui/{}", current_uid()?);
526    let service = format!("{domain}/{LAUNCHD_LABEL}");
527    if run_checked(Command::new("launchctl").args(["kickstart", &service])).is_err() {
528        load_launchd_service(&domain, &path)?;
529    }
530    Ok(())
531}
532
533#[cfg(target_os = "macos")]
534fn restart_service() -> Result<()> {
535    let path = launchd_plist_path()?;
536    require_service_installed(&path)?;
537    let domain = format!("gui/{}", current_uid()?);
538    let service = format!("{domain}/{LAUNCHD_LABEL}");
539    if run_checked(Command::new("launchctl").args(["kickstart", "-k", &service])).is_err() {
540        load_launchd_service(&domain, &path)?;
541    }
542    Ok(())
543}
544
545#[cfg(not(any(target_os = "linux", target_os = "macos")))]
546fn install_service(_force: bool) -> Result<PathBuf> {
547    bail!("OS service installation is not yet supported on Windows; use Linux or macOS")
548}
549
550#[cfg(not(any(target_os = "linux", target_os = "macos")))]
551fn uninstall_service() -> Result<PathBuf> {
552    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
553}
554
555#[cfg(not(any(target_os = "linux", target_os = "macos")))]
556fn start_service() -> Result<()> {
557    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
558}
559
560#[cfg(not(any(target_os = "linux", target_os = "macos")))]
561fn restart_service() -> Result<()> {
562    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
563}
564
565/// Install the background service, or start it when its file already exists
566/// (for example after a binary upgrade). Used by first-run automation, so it
567/// must be idempotent and must not fail because the service was already
568/// registered.
569pub(crate) fn ensure_service() -> Result<()> {
570    match install_service(false) {
571        Ok(_) => Ok(()),
572        Err(install_error) => start_service().map_err(|start_error| {
573            anyhow::anyhow!("install failed ({install_error:#}); start failed ({start_error:#})")
574        }),
575    }
576}
577
578fn canonical_or_original(path: &Path) -> PathBuf {
579    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
580}
581
582/// Persist a root change in the config so it survives daemon restarts and
583/// reboots. Without this, `add-root` only lived until the daemon exited.
584fn persist_root(add: Option<&Path>, remove: Option<&Path>) -> Result<()> {
585    let mut config = crate::core::config::Config::load().unwrap_or_default();
586    if let Some(add) = add {
587        if !add.exists() {
588            bail!("{} does not exist", add.display());
589        }
590        if !config.roots.iter().any(|root| root == add) {
591            config.roots.push(add.to_path_buf());
592        }
593    }
594    if let Some(remove) = remove {
595        config.roots.retain(|root| root != remove);
596    }
597    config.save()
598}