Skip to main content

sapphire_framework_server/
command.rs

1//! The framework-provided half of an application's CLI.
2
3use std::fmt::Write as _;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use corundum_framework_service::{Environment, ServiceCommand, SystemManager};
8use sapphire_backend::protocol as proto;
9use sapphire_bridge_client::BridgeClient;
10use sapphire_ipc::{ClientInfo, Endpoint};
11
12use crate::AppServer;
13use crate::error::{Error, Result};
14use crate::selection::SelectionFile;
15use crate::settings::{AppSettings, Settings};
16use sapphire_workspace::AppContext;
17
18mod config;
19
20pub use config::{AppConfigCommand, AppScopeFlags};
21
22pub use sapphire_backend::protocol::{StatusReport, StatusRow};
23
24/// The framework's commands, flattened into an application's CLI (spec decision 2).
25///
26/// An application composes these beside its own verbs by giving its subcommand enum a
27/// `#[command(flatten)] Framework(FrameworkCommand)` variant, so every verb — the app's and
28/// the framework's — sits at the same top level. The parse tests below pin that shape.
29///
30/// A desktop app's binary carries the same enum (#366): it is the CLI as well, so the CLI
31/// version is a subset of it. Its subcommand is optional, and with none it opens the
32/// window; the CLI version's is required, so a bare invocation prints the help. The verbs
33/// are one definition either way:
34///
35/// ```rust,ignore
36/// #[derive(clap::Parser)]
37/// struct Desktop {
38///     #[command(subcommand)]
39///     command: Option<Command>, // `Command` for the CLI version
40/// }
41///
42/// match Desktop::parse().command {
43///     None => open_the_window(),
44///     Some(command) => runtime.block_on(run(command)),
45/// }
46/// ```
47#[derive(Debug, clap::Subcommand)]
48pub enum FrameworkCommand {
49    /// Run the server in this process until SIGTERM or SIGINT.
50    Serve,
51    /// Report whether a server is running, and which version.
52    Status,
53    /// Install, remove or report this application's operating-system service.
54    #[command(subcommand)]
55    Service(ServiceCommand),
56    /// Replace this executable with the newest release, then do the same for
57    /// `sapphire-bridge` (unless `--no-bridge`). Restart the services afterwards to run
58    /// them.
59    Update(AppUpdateArgs),
60    /// Create, select, show and map this application's workspace. The server serves one
61    /// at a time.
62    #[command(subcommand)]
63    Workspace(WorkspaceCommand),
64    /// Add, list, retire, restore and rotate the API keys of the workspace this application
65    /// serves — for clients that reach it over HTTP. Works on the workspace's files, with or
66    /// without a running server; the keys sync with the workspace.
67    #[command(subcommand)]
68    ApiKey(corundum_framework_keys::KeyCommand),
69    /// Renamed to `api-key` (#364).
70    #[command(hide = true)]
71    ExternalDevice(LegacyExternalDevice),
72    /// List, show, set and unset this application's settings and the bridge's, by key.
73    /// Without a running server, this application's own, on its files.
74    #[command(subcommand)]
75    Config(AppConfigCommand),
76    /// Serve this application's tools to an AI agent over MCP on stdin/stdout. Talks to the
77    /// running server, which it does not start; register this command with the agent.
78    #[cfg(feature = "mcp")]
79    Mcp,
80}
81
82impl FrameworkCommand {
83    /// Carry out the command, returning the process exit code.
84    ///
85    /// The application matches its own variants first, then hands the framework's here,
86    /// with what [`serve_restarting`](crate::serve_restarting) takes: its context, its own
87    /// settings (`()` for none) and the function that builds its server from the settings.
88    /// `serve` runs [`serve_restarting`](crate::serve_restarting); the commands that need an
89    /// [`AppServer`] — `service`, `update` and `mcp` — read the settings and call `build`
90    /// once; `config` reads and writes the settings through the running server, or the
91    /// files themselves when none runs.
92    ///
93    /// ```rust,ignore
94    /// command
95    ///     .dispatch(&CTX, MyOwner, |settings: &Settings| AppServer::new(&CTX, VERSION), VERSION)
96    ///     .await
97    /// ```
98    pub async fn dispatch<A, F>(
99        self,
100        ctx: &'static AppContext,
101        owner: A,
102        build: F,
103        version: &'static str,
104    ) -> Result<i32>
105    where
106        A: AppSettings + Clone,
107        F: Fn(&Settings) -> AppServer,
108    {
109        let app = ctx.app_name;
110        // Built only by the commands that need a server, and then once. These are the way
111        // out of a bad release or a broken install, so settings that cannot be read are
112        // warned about and replaced by the defaults rather than stopping them.
113        let server = |owner: A| -> Result<AppServer> {
114            Ok(build(&settings_or_defaults(ctx, Arc::new(owner))?))
115        };
116        match self {
117            FrameworkCommand::Serve => {
118                crate::serve_restarting(ctx, owner, build).await?;
119                Ok(0)
120            }
121            FrameworkCommand::Status => {
122                let endpoint = Endpoint::for_app(app)?;
123                run_status(&endpoint, app, version).await
124            }
125            FrameworkCommand::Service(command) => {
126                let spec = server(owner)?.service_spec();
127                command
128                    .run(&spec, &Environment::detect(), &SystemManager)
129                    .map_err(Error::from)
130            }
131            FrameworkCommand::Update(args) => {
132                let server = server(owner)?;
133                let own = match server.release_source() {
134                    Some(source) => {
135                        sapphire_framework_update::run(&args.update, source, app, version)
136                            .await
137                            .map_err(Error::from)
138                    }
139                    None => {
140                        println!("{app} does not say where its releases are");
141                        Ok(1)
142                    }
143                };
144                // The bridge is updated whatever became of the app: one is independent of
145                // the other, and an app installed with cargo still has a released bridge.
146                let bridge = if args.no_bridge {
147                    0
148                } else {
149                    update_bridge(&args.update).await?
150                };
151                Ok(own?.max(bridge))
152            }
153            FrameworkCommand::Config(command) => config::config(ctx, owner, command, version).await,
154            FrameworkCommand::Workspace(command) => command.dispatch(app, version).await,
155            FrameworkCommand::ApiKey(command) => {
156                api_key(ctx, &server(owner)?.profiles().list(), command)
157            }
158            FrameworkCommand::ExternalDevice(legacy) => {
159                eprintln!("warning: `external-device` is renamed to `api-key`");
160                if !legacy.app.is_empty() {
161                    eprintln!(
162                        "API keys are per workspace now, not per application: `--app` is not taken"
163                    );
164                    return Ok(2);
165                }
166                api_key(ctx, &server(owner)?.profiles().list(), legacy.command)
167            }
168            #[cfg(feature = "mcp")]
169            FrameworkCommand::Mcp => {
170                server(owner)?.serve_mcp_stdio(version).await?;
171                Ok(0)
172            }
173        }
174    }
175}
176
177/// `ctx`'s application's settings, or — when they cannot be read — every key at its
178/// default, after one warning on stderr naming the device file and the error.
179///
180/// For `update`, `service` and `mcp`, which must work whatever the files hold: `update` is
181/// the way out of a bad release, and `service uninstall` must always be possible.
182fn settings_or_defaults(ctx: &AppContext, owner: Arc<dyn AppSettings>) -> Result<Settings> {
183    match Settings::load(ctx, Arc::clone(&owner)) {
184        Ok(settings) => Ok(settings),
185        Err(err) => {
186            let file = Settings::device_file(ctx)
187                .map_or_else(|| "the settings".to_owned(), |f| f.display().to_string());
188            eprintln!("warning: could not read {file} ({err}); going on with the default settings");
189            Settings::defaults(ctx, owner)
190        }
191    }
192}
193
194/// `update`'s arguments in an application: its own, and whether the bridge follows.
195#[derive(Clone, Debug, Default, clap::Args)]
196pub struct AppUpdateArgs {
197    /// `--check` and `--yes`, for the application and the bridge alike.
198    #[command(flatten)]
199    pub update: sapphire_framework_update::UpdateArgs,
200    /// Update this application alone, leaving `sapphire-bridge` as it is.
201    #[arg(long)]
202    pub no_bridge: bool,
203}
204
205/// The bridge's executable, as it is installed beside the apps.
206const BRIDGE_BINARY: &str = "sapphire-bridge";
207
208/// Where the bridge's releases are, for a bridge too old to update itself.
209const BRIDGE_RELEASES: &str = "https://github.com/sapphire-turtle/sapphire-framework/releases";
210
211/// The first `name` (with the platform's executable suffix) in the directories of `path`.
212fn find_on_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
213    let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
214    std::env::split_paths(path?)
215        .map(|dir| dir.join(&file))
216        .find(|candidate| candidate.is_file())
217}
218
219/// Run the bridge on `PATH`'s own `update` with `args`; returns its exit code. No bridge on
220/// `PATH` is nothing to update.
221async fn update_bridge(args: &sapphire_framework_update::UpdateArgs) -> Result<i32> {
222    match find_on_path(BRIDGE_BINARY, std::env::var_os("PATH").as_deref()) {
223        Some(exe) => run_bridge_update(&exe, args).await,
224        None => {
225            println!("{BRIDGE_BINARY} is not on PATH; not updating it");
226            Ok(0)
227        }
228    }
229}
230
231/// Run the bridge at `exe`'s own `update` with `args`; returns its exit code.
232///
233/// The bridge updates itself rather than being replaced from here: it knows its own
234/// version and where it was installed from, and replacing a running executable is its own
235/// business on every platform.
236async fn run_bridge_update(
237    exe: &std::path::Path,
238    args: &sapphire_framework_update::UpdateArgs,
239) -> Result<i32> {
240    // A bridge from before `update` rejects the subcommand.
241    let knows_update = tokio::process::Command::new(exe)
242        .args(["update", "--help"])
243        .stdout(std::process::Stdio::null())
244        .stderr(std::process::Stdio::null())
245        .status()
246        .await?
247        .success();
248    if !knows_update {
249        println!(
250            "{} cannot update itself; install the newest from {BRIDGE_RELEASES}",
251            exe.display()
252        );
253        return Ok(1);
254    }
255    let mut command = tokio::process::Command::new(exe);
256    command.arg("update");
257    if args.check {
258        command.arg("--check");
259    }
260    if args.yes {
261        command.arg("--yes");
262    }
263    // Inherited stdio: the bridge asks its own question and says what it did.
264    let status = command.status().await?;
265    Ok(status.code().unwrap_or(1))
266}
267
268/// The `workspace` subcommands (#215: one workspace per server).
269///
270/// `init`, `select`, `sync`, `move` and `remove` go to the app's server over IPC,
271/// because the server owns the marker directories, the sync ids and which workspace it
272/// serves; `show` asks the server for its workspace and then the bridge for the workgroup's
273/// ledger. `init --remote-workspace` has the server resolve the name through the bridge.
274#[derive(Debug, clap::Subcommand)]
275pub enum WorkspaceCommand {
276    /// Create this app's workspace home in the given directory, and switch the server to it.
277    Init {
278        /// Where the workspace root goes. Defaults to the current directory.
279        dir: Option<PathBuf>,
280        /// Also start syncing it, which publishes it into the workgroup ledger.
281        #[arg(long)]
282        sync: bool,
283        /// Sync it as this workspace of the workgroup, by name or id, instead of as a new
284        /// one: its files and settings arrive from the other devices.
285        #[arg(long, value_name = "NAME|ID", requires = "sync")]
286        remote_workspace: Option<String>,
287    },
288    /// Switch the server to an existing workspace of this app.
289    Select {
290        /// The workspace's root. Defaults to the current directory.
291        dir: Option<PathBuf>,
292        /// Also start syncing it, which publishes it into the workgroup ledger. A
293        /// workspace that has synced before turns sync back on by itself.
294        #[arg(long)]
295        sync: bool,
296    },
297    /// Turn sync on or off for the server's workspace, or show its sync state.
298    #[command(subcommand)]
299    Sync(WorkspaceSyncCommand),
300    /// Show the server's workspace, then the workgroup's workspaces of this app.
301    Show,
302    /// Move the server's workspace folder to a new path on this host, keeping its sync.
303    Move {
304        /// The new root. It must not exist yet; its parent must.
305        dir: PathBuf,
306    },
307    /// Stop serving the server's workspace on this host. Other devices keep their copies.
308    Remove {
309        /// Also delete the workspace's folder and every file in it.
310        #[arg(long)]
311        delete: bool,
312    },
313}
314
315impl WorkspaceCommand {
316    /// Carry out the command, returning the process exit code.
317    ///
318    /// `app` names the endpoint to open (`Endpoint::for_app`); `version` is this
319    /// process's own, for the handshake.
320    pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
321        match self {
322            WorkspaceCommand::Init {
323                dir,
324                sync,
325                remote_workspace,
326            } => workspace_init(app, version, dir, sync, remote_workspace).await,
327            WorkspaceCommand::Select { dir, sync } => {
328                workspace_select(app, version, dir, sync).await
329            }
330            WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
331            WorkspaceCommand::Show => workspace_show(app, version).await,
332            WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
333            WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
334        }
335    }
336}
337
338/// The `workspace sync` subcommands: the server's workspace's sync, switched after the fact.
339#[derive(Debug, clap::Subcommand)]
340pub enum WorkspaceSyncCommand {
341    /// Start syncing the server's workspace, which publishes it into the workgroup ledger.
342    Enable,
343    /// Stop syncing the server's workspace on this host. It keeps its sync id, so enabling
344    /// it again picks up where it left off; other devices keep their copies.
345    Disable,
346    /// Show the server's workspace's sync state.
347    Status,
348}
349
350/// `external-device …`, kept one release as a hidden alias of `api-key`.
351#[derive(Debug, clap::Args)]
352pub struct LegacyExternalDevice {
353    /// What `external-device add --app` took; refused, as keys are per workspace now.
354    #[arg(long = "app", global = true, hide = true)]
355    app: Vec<String>,
356    #[command(subcommand)]
357    command: corundum_framework_keys::KeyCommand,
358}
359
360/// `api-key …`: on the files of the workspace this application serves, as its selection
361/// file records it. No workspace selected → a line naming `workspace select`, exit 1.
362/// `add --profile` takes one of `profiles`.
363fn api_key(
364    ctx: &AppContext,
365    profiles: &[sapphire_framework_keys::Profile],
366    command: corundum_framework_keys::KeyCommand,
367) -> Result<i32> {
368    let Some(selection) = SelectionFile::for_app(ctx).load(ctx.app_name)? else {
369        eprintln!(
370            "{} serves no workspace yet: choose one with `{} workspace select <dir>`",
371            ctx.app_name, ctx.app_name
372        );
373        return Ok(1);
374    };
375    // Opening the store creates its directory: never recreate a workspace that moved away.
376    if !selection.root.join(format!(".{}", ctx.app_name)).is_dir() {
377        eprintln!(
378            "the workspace at {} is not reachable: bring it back, or choose another with `{} workspace select <dir>`",
379            selection.root.display(),
380            ctx.app_name
381        );
382        return Ok(1);
383    }
384    let run = sapphire_framework_keys::open_store(ctx.app_name, &selection.root)
385        .and_then(|mut store| command.run(&mut store, profiles));
386    match run {
387        Ok(code) => Ok(code),
388        Err(err) => {
389            eprintln!("{err}");
390            Ok(1)
391        }
392    }
393}
394
395/// `workspace init`: the server does the creating, over IPC.
396///
397/// The server owns the marker, the registry and the sync ids, so a workspace created
398/// here is one the server already knows and a GUI sharing the registry sees. Nothing is
399/// listening → the one line and exit 1; nothing is ever started (Global Constraints).
400/// `--sync` rides the server's existing `sync.enable` path on the same connection, and
401/// its state is printed after, so an unjoined host's "no workgroup knows it yet" is
402/// plain.
403///
404/// `--remote-workspace` goes to `sync.map` instead, which makes the marker and takes the
405/// workgroup's identity in one step: the workspace's `config.toml` is the one that
406/// arrives, not one written here first (#253).
407async fn workspace_init(
408    app: &'static str,
409    version: &'static str,
410    dir: Option<PathBuf>,
411    sync: bool,
412    remote_workspace: Option<String>,
413) -> Result<i32> {
414    let endpoint = Endpoint::for_app(app)?;
415    let client_info = ClientInfo {
416        kind: "cli".to_owned(),
417        version: version.to_owned(),
418        api: proto::API_VERSION,
419        app_api: None,
420        pid: std::process::id(),
421    };
422    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
423    else {
424        println!("no {app} server is running");
425        return Ok(1);
426    };
427
428    // Resolved here: the server's cwd is not the user's.
429    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
430    if let Some(selector) = remote_workspace {
431        let mapped: proto::SyncEnableResult = client
432            .call(
433                proto::SYNC_MAP,
434                proto::SyncMapParams {
435                    workspace: selector.clone(),
436                    dir: dir.clone(),
437                },
438            )
439            .await?;
440        println!(
441            "initialized {app} workspace in {} from {selector}",
442            dir.display()
443        );
444        println!(
445            "the {app} server now serves it, syncing as {}",
446            mapped.workspace_id
447        );
448        return Ok(0);
449    }
450    let result: proto::WorkspaceInitResult = client
451        .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
452        .await?;
453    if result.created {
454        println!("initialized {app} workspace in {}", result.root.display());
455    } else {
456        println!(
457            "{} already exists (workspace {})",
458            result.root.display(),
459            result.workspace_id
460        );
461    }
462    println!("the {app} server now serves {}", result.root.display());
463
464    if sync {
465        enable_sync(&client).await?;
466    }
467    Ok(0)
468}
469
470/// Turn sync on for the server's workspace over `client`, and print what it syncs as.
471///
472/// The one path behind `init --sync`, `select --sync` and `sync enable`: the server's
473/// `sync.enable`, then its status, printed after, so an unjoined host's "no workgroup knows
474/// it yet" is plain.
475async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
476    let enabled: proto::SyncEnableResult = client
477        .call(proto::SYNC_ENABLE, serde_json::json!({}))
478        .await?;
479    // Never fails on account of the bridge: the workspace is synced either way, and the
480    // status is the user's word for what the workgroup does not know yet.
481    let status: proto::SyncStatusResult = client
482        .call(proto::SYNC_STATUS, serde_json::json!({}))
483        .await
484        .unwrap_or(proto::SyncStatusResult {
485            enabled: true,
486            workspace_id: Some(enabled.workspace_id),
487            ..proto::SyncStatusResult::not_synced()
488        });
489    println!(
490        "syncing as {} ({} peer{})",
491        enabled.workspace_id,
492        status.peers,
493        if status.peers == 1 { "" } else { "s" }
494    );
495    Ok(())
496}
497
498/// `workspace sync …`: the server's workspace's sync, switched after the fact.
499async fn workspace_sync(
500    app: &'static str,
501    version: &'static str,
502    command: WorkspaceSyncCommand,
503) -> Result<i32> {
504    let Some(client) = connect_app(app, version).await? else {
505        return Ok(1);
506    };
507    match command {
508        WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
509        WorkspaceSyncCommand::Disable => {
510            let _: proto::Ack = client
511                .call(proto::SYNC_DISABLE, serde_json::json!({}))
512                .await?;
513            println!("sync is off for the {app} workspace on this host; it keeps its sync id");
514        }
515        WorkspaceSyncCommand::Status => {
516            let status: proto::SyncStatusResult = client
517                .call(proto::SYNC_STATUS, serde_json::json!({}))
518                .await?;
519            for line in describe_sync(&status) {
520                println!("{line}");
521            }
522        }
523    }
524    Ok(0)
525}
526
527/// `workspace sync status`, line by line.
528fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
529    let mut lines = vec![format!(
530        "sync: {}",
531        if status.enabled { "on" } else { "off" }
532    )];
533    if let Some(id) = status.workspace_id {
534        lines.push(format!("workspace id: {id}"));
535    }
536    if status.enabled {
537        lines.push(format!(
538            "peers: {}{}",
539            status.peers,
540            if matches!(status.topology, proto::Topology::Star { .. }) {
541                " (star)"
542            } else {
543                ""
544            }
545        ));
546        lines.push(format!(
547            "bridge: {}",
548            if status.bridge_available {
549                "reachable"
550            } else {
551                "not reachable"
552            }
553        ));
554    }
555    if let Some(paused) = &status.paused {
556        lines.push(format!("paused: {paused}"));
557    }
558    if let Some(error) = &status.last_error {
559        lines.push(format!("last error: {error}"));
560    }
561    lines
562}
563
564/// Render the server's workspace as the CLI prints it: `root state`.
565///
566/// Public so the integration tests can capture it; `workspace show` writes it to standard
567/// output.
568pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
569    let current: proto::WorkspaceCurrentResult = client
570        .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
571        .await?;
572    let Some(ws) = current.workspace else {
573        writeln!(
574            out,
575            "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
576        )
577        .expect("writing to a String cannot fail");
578        return Ok(1);
579    };
580    writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
581        .expect("writing to a String cannot fail");
582    Ok(0)
583}
584
585/// `synced (star), embedding 3 pending` and the like.
586fn describe_state(ws: &proto::CurrentWorkspace) -> String {
587    let state = if !ws.reachable {
588        "unreachable"
589    } else if ws.sync.enabled {
590        "synced"
591    } else {
592        "not synced"
593    };
594    let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
595        " (star)"
596    } else {
597        ""
598    };
599    let pending = match &ws.sync.embedding {
600        Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
601        _ => String::new(),
602    };
603    format!("{state}{star}{pending}")
604}
605
606/// Connect to `app`'s server, or say none is running.
607async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
608    let client = try_connect_app(app, version).await?;
609    if client.is_none() {
610        println!("no {app} server is running");
611    }
612    Ok(client)
613}
614
615/// Connect to `app`'s server; `None`, silently, when none is running.
616async fn try_connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
617    let endpoint = Endpoint::for_app(app)?;
618    let client_info = ClientInfo {
619        kind: "cli".to_owned(),
620        version: version.to_owned(),
621        api: proto::API_VERSION,
622        app_api: None,
623        pid: std::process::id(),
624    };
625    let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
626    Ok(client.map(|(c, _)| c))
627}
628
629/// `workspace select`: switch the server to an existing workspace, syncing it with `--sync`.
630async fn workspace_select(
631    app: &'static str,
632    version: &'static str,
633    dir: Option<PathBuf>,
634    sync: bool,
635) -> Result<i32> {
636    let Some(client) = connect_app(app, version).await? else {
637        return Ok(1);
638    };
639    // Resolved here: the server's cwd is not the user's.
640    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
641    let ws: proto::CurrentWorkspace = client
642        .call(
643            proto::WORKSPACE_SELECT,
644            proto::WorkspaceSelectParams { dir },
645        )
646        .await?;
647    println!("{} {}", ws.root.display(), describe_state(&ws));
648    // A workspace that has synced before is synced again by the select itself.
649    if sync && !ws.sync.enabled {
650        enable_sync(&client).await?;
651    }
652    Ok(0)
653}
654
655/// `workspace move`: move the server's workspace folder.
656async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
657    let Some(client) = connect_app(app, version).await? else {
658        return Ok(1);
659    };
660    // Resolved here: the server's cwd is not the user's.
661    let dir = std::env::current_dir()?.join(dir);
662    let ws: proto::CurrentWorkspace = client
663        .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
664        .await?;
665    println!("{} {}", ws.root.display(), describe_state(&ws));
666    Ok(0)
667}
668
669/// `workspace remove`: let go of the server's workspace, deleting it with `--delete`.
670async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
671    let Some(client) = connect_app(app, version).await? else {
672        return Ok(1);
673    };
674    let _: proto::Ack = client
675        .call(
676            proto::WORKSPACE_REMOVE,
677            proto::WorkspaceRemoveParams { delete },
678        )
679        .await?;
680    println!(
681        "{}",
682        if delete {
683            "removed and deleted"
684        } else {
685            "removed; the files stay"
686        }
687    );
688    Ok(0)
689}
690
691/// `workspace show`: the server's workspace, then the workgroup's workspaces of this app.
692///
693/// The workgroup's ledger is the bridge's to answer, and the bridge being down is not the
694/// server half's failure: the ledger's absence is one line, and the exit is the server
695/// half's.
696async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
697    let Some(client) = connect_app(app, version).await? else {
698        return Ok(1);
699    };
700    let mut out = String::new();
701    let code = render_workspace_show(Arc::new(client), app, &mut out).await?;
702    for line in out.lines() {
703        println!("{line}");
704    }
705    Ok(code)
706}
707
708/// [`workspace_show`]'s text, over one connection to the app's server.
709///
710/// The workgroup half goes through the same connection, relayed to the bridge. Public so
711/// the integration tests can capture it.
712#[doc(hidden)]
713pub async fn render_workspace_show(
714    client: Arc<sapphire_ipc::Client>,
715    app: &str,
716    out: &mut String,
717) -> Result<i32> {
718    let code = render_workspace(&client, out).await?;
719    let bridge = BridgeClient::relayed(client, sapphire_ipc::runtime_dir()?);
720    let workspaces = match bridge.workspaces().await {
721        Ok(workspaces) => workspaces,
722        Err(sapphire_ipc::Error::NotRunning(_)) => {
723            writeln!(out, "no sapphire-bridge is running")
724                .expect("writing to a String cannot fail");
725            return Ok(code);
726        }
727        Err(error) => return Err(error.into()),
728    };
729    let mine: Vec<_> = workspaces
730        .workspaces
731        .into_iter()
732        .filter(|w| w.app_name == app)
733        .collect();
734    if !mine.is_empty() {
735        writeln!(out).expect("writing to a String cannot fail");
736        writeln!(out, "in the workgroup:").expect("writing to a String cannot fail");
737        for workspace in mine {
738            writeln!(out, "{} {}", workspace.name, workspace.workspace_id)
739                .expect("writing to a String cannot fail");
740        }
741    }
742    Ok(code)
743}
744
745/// Probe, handshake and call `SERVER_INFO` in one go, or report absence.
746///
747/// Every step the CLI needs — liveness and the API gate — is inside
748/// [`connect_or_absent`], so the command is that call plus one `SERVER_INFO` round trip.
749/// The API gate doubles as the liveness check here: a live server of another API version
750/// is `ApiVersionMismatch`, which names both API versions and advises upgrading and
751/// restarting the service. The report goes through [`run_status_into`] so tests can
752/// capture it.
753async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
754    let mut out = String::new();
755    let code = run_status_into(endpoint, app, version, &mut out).await?;
756    for line in out.lines() {
757        println!("{line}");
758    }
759    Ok(code)
760}
761
762/// [`run_status`], writing the rendered lines into `out` instead of the process's
763/// standard output.
764async fn run_status_into(
765    endpoint: &Endpoint,
766    app: &str,
767    version: &str,
768    out: &mut String,
769) -> Result<i32> {
770    let client_info = ClientInfo {
771        kind: "cli".to_owned(),
772        version: version.to_owned(),
773        api: proto::API_VERSION,
774        app_api: None,
775        pid: std::process::id(),
776    };
777    let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
778    else {
779        // Nothing is listening: the framework's half is only the one line, and the
780        // application's rows are skipped (there is no server to have configured them).
781        writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
782        return Ok(1);
783    };
784    let report: StatusReport = client
785        .call(
786            sapphire_backend::protocol::SERVER_INFO,
787            serde_json::json!({}),
788        )
789        .await?;
790    writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
791    if let Some(version) = &report.version {
792        writeln!(out, "version: {version}").expect("writing to a String cannot fail");
793    }
794    if let Some(pid) = report.pid {
795        writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
796    }
797    if let Some(managed_by) = &report.managed_by {
798        writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
799    }
800    for row in &report.app {
801        writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
802    }
803    // A server older than `server.update` answers method-not-found: there is nothing to
804    // say about releases then, and the restart line still stands.
805    let update: Option<proto::UpdateStatus> = client
806        .call(proto::SERVER_UPDATE, serde_json::json!({}))
807        .await
808        .ok();
809    for line in describe_update(app, version, report.version.as_deref(), update.as_ref()) {
810        writeln!(out, "{line}").expect("writing to a String cannot fail");
811    }
812    Ok(0)
813}
814
815/// The `update` and `restart` lines of `status`.
816///
817/// `installed` is this CLI's version — the executable on disk — and `running` the
818/// server's. A server older than what is installed was upgraded under it and needs a
819/// restart; a release newer than what is installed is an update to install. A release
820/// that is newer than the server but already installed is only the restart.
821fn describe_update(
822    app: &str,
823    installed: &str,
824    running: Option<&str>,
825    update: Option<&proto::UpdateStatus>,
826) -> Vec<String> {
827    let parse = |v: &str| semver::Version::parse(v).ok();
828    let installed_v = parse(installed);
829    let mut lines = Vec::new();
830    if let Some(update) = update.filter(|u| u.enabled) {
831        match (&update.latest, &update.last_error) {
832            (Some(latest), _) => {
833                let newer = match (parse(&latest.version), &installed_v) {
834                    (Some(latest), Some(installed)) => latest > *installed,
835                    _ => update.update_available,
836                };
837                if newer {
838                    lines.push(format!(
839                        "update: {} is available ({})",
840                        latest.version, latest.url
841                    ));
842                } else {
843                    lines.push(format!(
844                        "update: up to date (latest release {})",
845                        latest.version
846                    ));
847                }
848            }
849            (None, Some(error)) => lines.push(format!("update: could not check: {error}")),
850            (None, None) => lines.push("update: not checked yet".to_owned()),
851        }
852    }
853    if let (Some(running), Some(installed)) = (running.and_then(parse), installed_v)
854        && installed > running
855    {
856        lines.push(format!(
857            "restart: needed: {installed} is installed but {running} is running; restart the {app} service"
858        ));
859    }
860    lines
861}
862#[cfg(test)]
863mod tests {
864    use super::*;
865    use clap::Parser;
866
867    /// The composition every app binary uses: an app-owned subcommand enum whose framework
868    /// verbs ride in on a flattened variant (spec decision 2).
869    ///
870    /// clap 4 rejects `#[command(flatten)]` on a struct field beside a
871    /// `#[command(subcommand)]` field — two subcommand enums cannot share one level, and a
872    /// flattened field must implement `clap::Args`, which the `Subcommand` derive does not
873    /// provide. The plan's Risks section names this probe as the decision, and the flat
874    /// fallback is what it decided: one subcommand enum, every verb at the top level.
875    #[derive(Parser)]
876    struct Probe {
877        #[command(subcommand)]
878        command: Command,
879    }
880
881    #[derive(Debug, clap::Subcommand)]
882    enum Command {
883        /// An app-specific verb that must parse beside the framework's.
884        Greet,
885        #[command(flatten)]
886        Framework(FrameworkCommand),
887    }
888
889    /// A desktop binary: the same verbs, and none at all to open the window.
890    #[derive(Parser)]
891    struct DesktopProbe {
892        #[command(subcommand)]
893        command: Option<Command>,
894    }
895
896    #[test]
897    fn a_desktop_binary_takes_the_same_verbs_or_none() {
898        let probe = DesktopProbe::try_parse_from(["app"]).unwrap();
899        assert!(probe.command.is_none());
900        let probe = DesktopProbe::try_parse_from(["app", "serve"]).unwrap();
901        assert!(matches!(
902            probe.command,
903            Some(Command::Framework(FrameworkCommand::Serve))
904        ));
905        let probe = DesktopProbe::try_parse_from(["app", "greet"]).unwrap();
906        assert!(matches!(probe.command, Some(Command::Greet)));
907        // The CLI version's bare invocation is an error, which clap answers with the help.
908        assert!(Probe::try_parse_from(["app"]).is_err());
909    }
910
911    #[test]
912    fn app_and_framework_commands_parse_side_by_side() {
913        let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
914        assert!(matches!(probe.command, Command::Greet));
915        let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
916        assert!(matches!(
917            probe.command,
918            Command::Framework(FrameworkCommand::Serve)
919        ));
920        let probe = Probe::try_parse_from(["app", "status"]).unwrap();
921        assert!(matches!(
922            probe.command,
923            Command::Framework(FrameworkCommand::Status)
924        ));
925    }
926
927    #[cfg(feature = "mcp")]
928    #[test]
929    fn the_mcp_command_parses_beside_the_apps() {
930        let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
931        assert!(matches!(
932            probe.command,
933            Command::Framework(FrameworkCommand::Mcp)
934        ));
935    }
936
937    #[test]
938    fn the_update_command_parses_with_and_without_the_bridge() {
939        let probe = Probe::try_parse_from(["app", "update", "--check", "-y"]).unwrap();
940        let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
941            panic!("not update");
942        };
943        assert!(args.update.check && args.update.yes && !args.no_bridge);
944        let probe = Probe::try_parse_from(["app", "update", "--no-bridge"]).unwrap();
945        let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
946            panic!("not update");
947        };
948        assert!(args.no_bridge);
949    }
950
951    #[test]
952    fn the_bridge_is_found_in_the_first_directory_of_path_that_has_it() {
953        let tmp = tempfile::tempdir().unwrap();
954        let (empty, first, second) = (
955            tmp.path().join("empty"),
956            tmp.path().join("first"),
957            tmp.path().join("second"),
958        );
959        let file = format!("sapphire-bridge{}", std::env::consts::EXE_SUFFIX);
960        for dir in [&empty, &first, &second] {
961            std::fs::create_dir(dir).unwrap();
962        }
963        std::fs::write(first.join(&file), b"").unwrap();
964        std::fs::write(second.join(&file), b"").unwrap();
965        let path = std::env::join_paths([&empty, &first, &second]).unwrap();
966        assert_eq!(
967            find_on_path("sapphire-bridge", Some(&path)),
968            Some(first.join(&file))
969        );
970        let path = std::env::join_paths([&empty]).unwrap();
971        assert_eq!(find_on_path("sapphire-bridge", Some(&path)), None);
972        assert_eq!(find_on_path("sapphire-bridge", None), None);
973    }
974
975    /// An executable shell script at `dir/name` that runs `body`.
976    #[cfg(unix)]
977    fn script(dir: &std::path::Path, name: &str, body: &str) -> PathBuf {
978        use std::os::unix::fs::PermissionsExt;
979        let path = dir.join(name);
980        std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
981        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
982        path
983    }
984
985    #[cfg(unix)]
986    #[tokio::test]
987    async fn the_bridge_runs_its_own_update_with_the_apps_flags() {
988        let tmp = tempfile::tempdir().unwrap();
989        let log = tmp.path().join("args");
990        // Records the real run (not the `--help` probe) and exits as an update that
991        // declined would.
992        let exe = script(
993            tmp.path(),
994            "bridge",
995            &format!(
996                r#"case "$*" in *--help*) exit 0;; esac; echo "$@" > {}; exit 1"#,
997                log.display()
998            ),
999        );
1000        let args = sapphire_framework_update::UpdateArgs {
1001            check: true,
1002            yes: true,
1003        };
1004        assert_eq!(run_bridge_update(&exe, &args).await.unwrap(), 1);
1005        assert_eq!(
1006            std::fs::read_to_string(&log).unwrap().trim(),
1007            "update --check --yes"
1008        );
1009    }
1010
1011    #[cfg(unix)]
1012    #[tokio::test]
1013    async fn a_bridge_without_update_is_not_run() {
1014        let tmp = tempfile::tempdir().unwrap();
1015        let runs = tmp.path().join("runs");
1016        // What clap does with an unknown subcommand: exit 2, whatever the arguments.
1017        let exe = script(
1018            tmp.path(),
1019            "bridge",
1020            &format!(r#"echo "$*" >> {}; exit 2"#, runs.display()),
1021        );
1022        let code = run_bridge_update(&exe, &Default::default()).await.unwrap();
1023        assert_eq!(code, 1);
1024        assert_eq!(
1025            std::fs::read_to_string(&runs).unwrap(),
1026            "update --help\n",
1027            "only the probe ran"
1028        );
1029    }
1030
1031    #[test]
1032    fn the_service_subcommands_parse() {
1033        for args in [
1034            vec!["app", "service", "install"],
1035            vec!["app", "service", "uninstall"],
1036            vec!["app", "service", "status"],
1037        ] {
1038            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1039        }
1040    }
1041
1042    #[test]
1043    fn the_workspace_commands_parse() {
1044        for args in [
1045            vec!["app", "workspace", "init"],
1046            vec!["app", "workspace", "init", "papers"],
1047            vec!["app", "workspace", "init", "--sync"],
1048            vec!["app", "workspace", "show"],
1049            vec!["app", "workspace", "select", "papers"],
1050            vec!["app", "workspace", "select", "--sync"],
1051            vec!["app", "workspace", "select", "papers", "--sync"],
1052            vec!["app", "workspace", "sync", "enable"],
1053            vec!["app", "workspace", "sync", "disable"],
1054            vec!["app", "workspace", "sync", "status"],
1055            vec![
1056                "app",
1057                "workspace",
1058                "init",
1059                "--sync",
1060                "--remote-workspace=Ledger",
1061            ],
1062            vec![
1063                "app",
1064                "workspace",
1065                "init",
1066                "papers",
1067                "--sync",
1068                "--remote-workspace",
1069                "Ledger",
1070            ],
1071            vec!["app", "workspace", "move", "../papers"],
1072            vec!["app", "workspace", "remove"],
1073            vec!["app", "workspace", "remove", "--delete"],
1074        ] {
1075            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1076        }
1077    }
1078
1079    #[test]
1080    fn a_remote_workspace_needs_sync() {
1081        let args = ["app", "workspace", "init", "--remote-workspace=Ledger"];
1082        assert!(Probe::try_parse_from(args).is_err());
1083    }
1084
1085    #[test]
1086    fn bare_invocation_prints_the_help() {
1087        // <app> with no subcommand prints the help; the server starts only on an explicit
1088        // `serve`. An app CLI gets that by a required subcommand and
1089        // `arg_required_else_help`, as this probe does.
1090        #[derive(Parser)]
1091        #[command(arg_required_else_help = true)]
1092        struct Bare {
1093            #[command(subcommand)]
1094            command: Command,
1095        }
1096        let err = Bare::try_parse_from(["app"]).err().unwrap();
1097        assert_eq!(
1098            err.kind(),
1099            clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
1100        );
1101    }
1102}
1103
1104#[cfg(test)]
1105mod status_tests {
1106    use super::*;
1107    use sapphire_workspace::AppContext;
1108
1109    static CTX: AppContext = AppContext::new("sapphire-statustest");
1110
1111    /// Wait until something is listening on `endpoint`.
1112    ///
1113    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
1114    /// `run_status` probe can run before `run` has bound the socket, and with nothing
1115    /// listening that single unlucky probe is the whole test failing.
1116    async fn wait_until_listening(endpoint: &Endpoint) {
1117        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
1118        while !sapphire_ipc::probe(endpoint).await.unwrap() {
1119            assert!(
1120                tokio::time::Instant::now() < deadline,
1121                "the server never started listening"
1122            );
1123            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1124        }
1125    }
1126
1127    #[tokio::test]
1128    async fn status_reports_no_server_when_none_is_running() {
1129        let tmp = tempfile::tempdir().unwrap();
1130        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1131        let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
1132        assert_eq!(code, 1, "no server is a non-zero exit");
1133    }
1134
1135    fn update(latest: Option<&str>, error: Option<&str>) -> proto::UpdateStatus {
1136        proto::UpdateStatus {
1137            enabled: true,
1138            latest: latest.map(|version| proto::ReleaseInfo {
1139                version: version.to_owned(),
1140                url: format!("https://example.invalid/v{version}"),
1141            }),
1142            update_available: false,
1143            last_error: error.map(str::to_owned),
1144        }
1145    }
1146
1147    #[test]
1148    fn status_names_a_newer_release_and_nothing_when_up_to_date() {
1149        let lines = describe_update(
1150            "app",
1151            "0.19.0",
1152            Some("0.19.0"),
1153            Some(&update(Some("0.20.0"), None)),
1154        );
1155        assert_eq!(
1156            lines,
1157            vec!["update: 0.20.0 is available (https://example.invalid/v0.20.0)"]
1158        );
1159        let lines = describe_update(
1160            "app",
1161            "0.19.0",
1162            Some("0.19.0"),
1163            Some(&update(Some("0.19.0"), None)),
1164        );
1165        assert_eq!(lines, vec!["update: up to date (latest release 0.19.0)"]);
1166    }
1167
1168    #[test]
1169    fn status_asks_for_a_restart_when_the_installed_server_is_newer_than_the_running_one() {
1170        // Installed 0.20.0 under a running 0.19.0: the release is no longer news, the
1171        // restart is.
1172        let lines = describe_update(
1173            "app",
1174            "0.20.0",
1175            Some("0.19.0"),
1176            Some(&update(Some("0.20.0"), None)),
1177        );
1178        assert_eq!(
1179            lines,
1180            vec![
1181                "update: up to date (latest release 0.20.0)",
1182                "restart: needed: 0.20.0 is installed but 0.19.0 is running; restart the app service",
1183            ]
1184        );
1185        // An older server without `server.update` still gets the restart line.
1186        let lines = describe_update("app", "0.20.0", Some("0.19.0"), None);
1187        assert_eq!(lines.len(), 1);
1188        assert!(lines[0].starts_with("restart: needed"));
1189    }
1190
1191    #[test]
1192    fn status_says_why_a_check_failed_and_nothing_when_checks_are_off() {
1193        let lines = describe_update(
1194            "app",
1195            "0.19.0",
1196            Some("0.19.0"),
1197            Some(&update(None, Some("offline"))),
1198        );
1199        assert_eq!(lines, vec!["update: could not check: offline"]);
1200        let off = proto::UpdateStatus::default();
1201        assert!(describe_update("app", "0.19.0", Some("0.19.0"), Some(&off)).is_empty());
1202    }
1203
1204    #[tokio::test(flavor = "multi_thread")]
1205    async fn status_shows_a_newer_release_the_server_found() {
1206        let tmp = tempfile::tempdir().unwrap();
1207        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1208        let api = crate::update::stub::one_response(
1209            "200 OK",
1210            r#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid/v0.20.0"}]"#,
1211        )
1212        .await;
1213        let server = AppServer::new(&CTX, "0.19.0")
1214            .endpoint(endpoint.clone())
1215            .selection_file(tmp.path().join("workspace.toml"))
1216            .releases(crate::ReleaseSource::github("o", "r").api_base(api));
1217        let handle = tokio::spawn(async move { server.run().await });
1218        wait_until_listening(&endpoint).await;
1219
1220        // The first look runs as the server starts; wait for its answer to land.
1221        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
1222        let out = loop {
1223            let mut out = String::new();
1224            run_status_into(&endpoint, CTX.app_name, "0.19.0", &mut out)
1225                .await
1226                .unwrap();
1227            if !out.contains("not checked yet") {
1228                break out;
1229            }
1230            assert!(
1231                tokio::time::Instant::now() < deadline,
1232                "never checked: {out}"
1233            );
1234            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1235        };
1236        assert!(
1237            out.contains("update: 0.20.0 is available (https://example.invalid/v0.20.0)"),
1238            "output was: {out}"
1239        );
1240        assert!(!out.contains("restart:"), "output was: {out}");
1241
1242        let (client, _) = sapphire_ipc::connect_or_absent(
1243            &endpoint,
1244            CTX.app_name,
1245            sapphire_ipc::ClientInfo {
1246                kind: "test".into(),
1247                version: "0.19.0".into(),
1248                api: sapphire_backend::protocol::API_VERSION,
1249                app_api: None,
1250                pid: std::process::id(),
1251            },
1252        )
1253        .await
1254        .unwrap()
1255        .expect("the server is listening");
1256        let _: serde_json::Value = client
1257            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1258            .await
1259            .unwrap();
1260        handle.await.unwrap().unwrap();
1261    }
1262
1263    #[tokio::test(flavor = "multi_thread")]
1264    async fn status_shows_the_extension_rows_of_a_running_server() {
1265        let tmp = tempfile::tempdir().unwrap();
1266        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1267        let server = AppServer::new(&CTX, "0.0.0")
1268            .endpoint(endpoint.clone())
1269            // This context's directories are never initialised here.
1270            .selection_file(tmp.path().join("workspace.toml"))
1271            .status_rows(std::sync::Arc::new(|| {
1272                vec![StatusRow {
1273                    name: "sync".into(),
1274                    value: "on".into(),
1275                }]
1276            }));
1277        let handle = tokio::spawn(async move { server.run().await });
1278        wait_until_listening(&endpoint).await;
1279
1280        // The report goes through the sink face so the rendering is asserted, not just
1281        // the exit code.
1282        let mut out = String::new();
1283        let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
1284            .await
1285            .unwrap();
1286        assert_eq!(code, 0);
1287        assert!(out.contains("running: true"), "output was: {out}");
1288        assert!(out.contains("sync: on"), "output was: {out}");
1289
1290        let (client, _) = sapphire_ipc::connect_or_absent(
1291            &endpoint,
1292            CTX.app_name,
1293            sapphire_ipc::ClientInfo {
1294                kind: "test".into(),
1295                version: "0.0.0".into(),
1296                api: sapphire_backend::protocol::API_VERSION,
1297                app_api: None,
1298                pid: std::process::id(),
1299            },
1300        )
1301        .await
1302        .unwrap()
1303        .expect("the server is listening");
1304        let _: serde_json::Value = client
1305            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1306            .await
1307            .unwrap();
1308        handle.await.unwrap().unwrap();
1309    }
1310}
1311
1312#[cfg(test)]
1313mod service_spec_tests {
1314    use super::*;
1315    use sapphire_workspace::AppContext;
1316
1317    static CTX: AppContext = AppContext::new("sapphire-servicetest");
1318
1319    #[test]
1320    fn the_generated_spec_runs_the_server_not_the_cli() {
1321        // A service manager starts the executable directly, and the executable's bare
1322        // invocation is `serve`: the unit's argv must be exactly that, so the server that
1323        // starts has no CLI verbs on its command line to misparse.
1324        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1325        assert_eq!(spec.args, vec!["serve".to_owned()]);
1326    }
1327
1328    #[test]
1329    fn the_generated_spec_retires_the_first_label() {
1330        // The first label sapphire registered on macOS; corundum retires its own earlier
1331        // one (net.sapphire-turtle.<app>) by itself.
1332        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1333        assert_eq!(
1334            spec.legacy_labels,
1335            [format!("net.fireturtle.sapphire.{}", CTX.app_name)]
1336        );
1337    }
1338
1339    #[test]
1340    fn the_generated_spec_names_this_application() {
1341        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1342        assert_eq!(spec.app_name, CTX.app_name);
1343    }
1344
1345    #[test]
1346    fn the_generated_spec_describes_the_server() {
1347        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1348        assert!(
1349            spec.description.contains(CTX.app_name),
1350            "the unit's description should name the application: {:?}",
1351            spec.description
1352        );
1353        assert!(spec.description.contains("0.0.0"));
1354    }
1355}