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