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