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, Default, clap::Subcommand)]
25pub enum FrameworkCommand {
26    /// Run the server in this process until SIGTERM or SIGINT (the bare invocation).
27    #[default]
28    Serve,
29    /// Report whether a server is running, and which version.
30    Status,
31    /// Install, remove or report this application's operating-system service.
32    #[command(subcommand)]
33    Service(ServiceCommand),
34    /// Create, select, show and map this application's workspace. The server serves one
35    /// at a time.
36    #[command(subcommand)]
37    Workspace(WorkspaceCommand),
38    /// Found, show or join the workgroup this device belongs to.
39    #[command(subcommand)]
40    Workgroup(WorkgroupCommand),
41    /// List the workgroup's devices, invite one or retire one.
42    #[command(subcommand)]
43    Device(DeviceCommand),
44    /// Show or change the embedding models (the workgroup's local and remote one), this
45    /// device's switches, and its API key. Needs the running bridge.
46    #[command(subcommand)]
47    Embedding(sapphire_bridge_api::EmbeddingCommand),
48    /// Add, list, retire, restore and rotate the workgroup's external devices — clients
49    /// that reach this application with a key. `add` allows this application unless told
50    /// otherwise. Needs the running bridge.
51    #[command(subcommand)]
52    ExternalDevice(sapphire_bridge_api::ExternalDeviceCommand),
53}
54
55impl FrameworkCommand {
56    /// Carry out the command, returning the process exit code.
57    ///
58    /// The application matches its own variants first, then hands the framework's here;
59    /// the app name and the service spec come from `server` itself.
60    pub async fn dispatch(self, server: AppServer, version: &'static str) -> Result<i32> {
61        match self {
62            FrameworkCommand::Serve => {
63                server.run().await?;
64                Ok(0)
65            }
66            FrameworkCommand::Status => crate::command::status(&server, version).await,
67            FrameworkCommand::Service(command) => {
68                let spec = server.service_spec();
69                command
70                    .run(&spec, &Environment::detect(), &SystemManager)
71                    .map_err(Error::from)
72            }
73            FrameworkCommand::Workspace(command) => {
74                command.dispatch(server.app_name(), version).await
75            }
76            FrameworkCommand::Workgroup(command) => command.dispatch(version).await,
77            FrameworkCommand::Device(command) => command.dispatch(version).await,
78            FrameworkCommand::Embedding(command) => embedding(command, version).await,
79            FrameworkCommand::ExternalDevice(command) => {
80                external_device(command, server.app_name(), version).await
81            }
82        }
83    }
84}
85
86/// The `workspace` subcommands (#215: one workspace per server).
87///
88/// `init`, `select`, `move`, `remove` and `map`'s write go to the app's server over IPC,
89/// because the server owns the marker directories, the sync ids and which workspace it
90/// serves; `show` asks the server for its workspace and then the bridge for the workgroup's
91/// ledger; `map`'s selector resolution is the workgroup's word, so it goes to the bridge
92/// first. These are the only verbs that take a path: everything else acts on the server's
93/// workspace.
94#[derive(Debug, clap::Subcommand)]
95pub enum WorkspaceCommand {
96    /// Create this app's workspace home in the given directory, and switch the server to it.
97    Init {
98        /// Where the workspace root goes. Defaults to the current directory.
99        dir: Option<PathBuf>,
100        /// Also start syncing it, which publishes it into the workgroup ledger.
101        #[arg(long)]
102        sync: bool,
103    },
104    /// Switch the server to an existing workspace of this app.
105    Select {
106        /// The workspace's root. Defaults to the current directory.
107        dir: Option<PathBuf>,
108    },
109    /// Show the server's workspace, then the workgroup's workspaces of this app.
110    Show,
111    /// Move the server's workspace folder to a new path on this host, keeping its sync.
112    Move {
113        /// The new root. It must not exist yet; its parent must.
114        dir: PathBuf,
115    },
116    /// Stop serving the server's workspace on this host. Other devices keep their copies.
117    Remove {
118        /// Also delete the workspace's folder and every file in it.
119        #[arg(long)]
120        delete: bool,
121    },
122    /// Bring a workspace the workgroup knows to a local directory, and switch to it.
123    Map {
124        /// The workspace, by name or id, as the workgroup lists it.
125        selector: String,
126        /// The local directory to map it to. Defaults to the current one.
127        dir: Option<PathBuf>,
128    },
129}
130
131impl WorkspaceCommand {
132    /// Carry out the command, returning the process exit code.
133    ///
134    /// `app` names the endpoint to open (`Endpoint::for_app`); `version` is this
135    /// process's own, for the handshake.
136    pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
137        match self {
138            WorkspaceCommand::Init { dir, sync } => workspace_init(app, version, dir, sync).await,
139            WorkspaceCommand::Select { dir } => workspace_select(app, version, dir).await,
140            WorkspaceCommand::Show => workspace_show(app, version).await,
141            WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
142            WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
143            WorkspaceCommand::Map { selector, dir } => {
144                workspace_map(app, version, &selector, dir).await
145            }
146        }
147    }
148}
149
150/// The `workgroup` subcommands.
151///
152/// The workgroup's ledger is the bridge's business end to end, so these go to the bridge's
153/// endpoint directly, including `create`, which goes through the running bridge.
154#[derive(Debug, clap::Subcommand)]
155pub enum WorkgroupCommand {
156    /// Found a workgroup on this host.
157    Create {
158        /// The workgroup's name.
159        name: String,
160        /// This host's device name inside it.
161        #[arg(long)]
162        device_name: String,
163    },
164    /// Show the workgroup this host belongs to.
165    List,
166    /// Join the workgroup a ticket names.
167    Join {
168        /// The ticket the inviting device printed.
169        ticket: String,
170        /// The name this device will carry. Defaults to this host's name.
171        #[arg(long)]
172        device_name: Option<String>,
173    },
174}
175
176impl WorkgroupCommand {
177    /// Carry out the command, returning the process exit code.
178    pub async fn dispatch(self, version: &'static str) -> Result<i32> {
179        match self {
180            WorkgroupCommand::Create { name, device_name } => {
181                let client = connect_running(version).await?;
182                let created = client
183                    .workgroup_create(WorkgroupCreateParams { name, device_name })
184                    .await?;
185                println!(
186                    "created workgroup {} ({}); this device is {}",
187                    created.name, created.workgroup_id, created.device_id
188                );
189                Ok(0)
190            }
191            WorkgroupCommand::List => {
192                let client = connect_running(version).await?;
193                match client.status().await?.workgroup {
194                    Some(workgroup) => {
195                        println!("{} ({})", workgroup.name, workgroup.workgroup_id);
196                        Ok(0)
197                    }
198                    None => {
199                        println!("this host has not joined a workgroup");
200                        Ok(1)
201                    }
202                }
203            }
204            WorkgroupCommand::Join {
205                ticket,
206                device_name,
207            } => {
208                let client = connect_running(version).await?;
209                let joined = client
210                    .join(JoinParams {
211                        ticket,
212                        device_name,
213                    })
214                    .await?;
215                println!(
216                    "joined workgroup {} ({}); this device is {}",
217                    joined.workgroup_name, joined.workgroup_id, joined.device_id
218                );
219                Ok(0)
220            }
221        }
222    }
223}
224
225/// The `device` subcommands.
226///
227/// The ledger's word for taking a device out is `retire` — a device id is written into
228/// synced content and must keep resolving, so its record stays as a tombstone — and this
229/// command goes through the running bridge to retire a device.
230#[derive(Debug, clap::Subcommand)]
231pub enum DeviceCommand {
232    /// List the workgroup's devices, and which are reachable.
233    List,
234    /// Create an invite ticket for a device that is about to join.
235    Invite {
236        /// What the joining device will be called.
237        #[arg(long)]
238        name: String,
239        /// How long the invite stays good, in seconds.
240        #[arg(long)]
241        ttl: Option<u64>,
242        /// The workgroup to invite into, by name or id.
243        #[arg(long)]
244        workgroup: Option<String>,
245    },
246    /// Retire a device, so it may no longer connect.
247    Retire {
248        /// The device's name or id.
249        selector: String,
250    },
251    /// Show or set a device's election priority (0-255; 0 = never primary or secondary).
252    /// The election is non-preemptive: raising a priority does not move a role already held.
253    Priority {
254        /// The device's name or id.
255        selector: String,
256        /// The new priority. Omit to show the current one.
257        priority: Option<u8>,
258    },
259}
260
261impl DeviceCommand {
262    /// Carry out the command, returning the process exit code.
263    pub async fn dispatch(self, version: &'static str) -> Result<i32> {
264        match self {
265            DeviceCommand::List => {
266                let client = connect_running(version).await?;
267                let peers = client.peers().await?;
268                if peers.peers.is_empty() {
269                    println!("no devices");
270                    return Ok(0);
271                }
272                for peer in peers.peers {
273                    println!(
274                        "{} {} p{}{}{}",
275                        peer.name,
276                        peer.device_id,
277                        peer.priority,
278                        peer.availability
279                            .map(|a| format!(" a{a}"))
280                            .unwrap_or_default(),
281                        if peer.connected { " (online)" } else { "" }
282                    );
283                }
284                Ok(0)
285            }
286            DeviceCommand::Invite {
287                name,
288                ttl,
289                workgroup,
290            } => {
291                let client = connect_running(version).await?;
292                let invite = client
293                    .invite(InviteParams {
294                        name,
295                        ttl,
296                        workgroup,
297                    })
298                    .await?;
299                // The ticket on its own line, and nothing else on it: this is the one
300                // output a user pipes to the joining device.
301                println!("{}", invite.ticket);
302                Ok(0)
303            }
304            DeviceCommand::Retire { selector } => {
305                let client = connect_running(version).await?;
306                let retired = client
307                    .device_retire(DeviceRetireParams { selector })
308                    .await?;
309                println!("retired device {} ({})", retired.name, retired.device_id);
310                Ok(0)
311            }
312            DeviceCommand::Priority { selector, priority } => {
313                let client = connect_running(version).await?;
314                match priority {
315                    Some(priority) => {
316                        let set = client
317                            .device_priority_set(DevicePrioritySetParams { selector, priority })
318                            .await?;
319                        println!("{} ({}) priority {}", set.name, set.device_id, set.priority);
320                    }
321                    None => {
322                        let peers = client.peers().await?;
323                        match peers
324                            .peers
325                            .iter()
326                            .find(|p| p.name == selector || p.device_id.to_string() == selector)
327                        {
328                            Some(p) => {
329                                println!("{} ({}) priority {}", p.name, p.device_id, p.priority)
330                            }
331                            None => {
332                                println!("no device {selector:?}");
333                                return Ok(1);
334                            }
335                        }
336                    }
337                }
338                Ok(0)
339            }
340        }
341    }
342}
343
344/// Connect to the running bridge, or fail with the message the command layer prints.
345///
346/// One wrapper for every arm that talks to the bridge: the error's text is what the
347/// `main` prints, so the absence case reads "no sapphire-bridge is running" without each
348/// arm repeating it.
349async fn connect_running(version: &str) -> Result<BridgeClient> {
350    BridgeClient::connect_running("cli", version)
351        .await
352        .map_err(Error::from)
353}
354
355/// `embedding …`: always through the running bridge, whose files these are.
356async fn embedding(command: sapphire_bridge_api::EmbeddingCommand, version: &str) -> Result<i32> {
357    // Connect first: `key set` asks for the key, which is pointless with no bridge to take it.
358    let client = connect_running(version).await?;
359    let request = command.request()?;
360    let report = client.embed_request(request).await?;
361    for line in sapphire_bridge_api::describe(&report) {
362        println!("{line}");
363    }
364    Ok(0)
365}
366
367/// `external-device …`: always through the running bridge, which owns the ledger.
368async fn external_device(
369    command: sapphire_bridge_api::ExternalDeviceCommand,
370    app: &str,
371    version: &str,
372) -> Result<i32> {
373    let client = connect_running(version).await?;
374    let outcome = client
375        .external_device_request(command.request(Some(app)))
376        .await?;
377    for line in sapphire_bridge_api::describe_external_outcome(&outcome) {
378        println!("{line}");
379    }
380    Ok(0)
381}
382
383/// `workspace init`: the server does the creating, over IPC.
384///
385/// The server owns the marker, the registry and the sync ids, so a workspace created
386/// here is one the server already knows and a GUI sharing the registry sees. Nothing is
387/// listening → the one line and exit 1; nothing is ever started (Global Constraints).
388/// `--sync` rides the server's existing `sync.enable` path on the same connection, and
389/// its state is printed after, so an unjoined host's "no workgroup knows it yet" is
390/// plain.
391async fn workspace_init(
392    app: &'static str,
393    version: &'static str,
394    dir: Option<PathBuf>,
395    sync: bool,
396) -> Result<i32> {
397    let endpoint = Endpoint::for_app(app)?;
398    let client_info = ClientInfo {
399        kind: "cli".to_owned(),
400        version: version.to_owned(),
401        api: proto::API_VERSION,
402        app_api: None,
403        pid: std::process::id(),
404    };
405    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
406    else {
407        println!("no {app} server is running");
408        return Ok(1);
409    };
410
411    // Resolved here: the server's cwd is not the user's.
412    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
413    let result: proto::WorkspaceInitResult = client
414        .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
415        .await?;
416    if result.created {
417        println!("initialized {app} workspace in {}", result.root.display());
418    } else {
419        println!(
420            "{} already exists (workspace {})",
421            result.root.display(),
422            result.workspace_id
423        );
424    }
425    println!("the {app} server now serves {}", result.root.display());
426
427    if sync {
428        let enabled: proto::SyncEnableResult = client
429            .call(proto::SYNC_ENABLE, serde_json::json!({}))
430            .await?;
431        // Never fails on account of the bridge: the workspace is synced either way, and
432        // the status is the user's word for what the workgroup does not know yet.
433        let status: proto::SyncStatusResult = client
434            .call(proto::SYNC_STATUS, serde_json::json!({}))
435            .await
436            .unwrap_or(proto::SyncStatusResult {
437                enabled: true,
438                workspace_id: Some(enabled.workspace_id),
439                ..proto::SyncStatusResult::not_synced()
440            });
441        println!(
442            "syncing as {} ({} peer{})",
443            enabled.workspace_id,
444            status.peers,
445            if status.peers == 1 { "" } else { "s" }
446        );
447    }
448    Ok(0)
449}
450
451/// Render the server's workspace as the CLI prints it: `root state`.
452///
453/// Public so the integration tests can capture it; `workspace show` writes it to standard
454/// output.
455pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
456    let current: proto::WorkspaceCurrentResult = client
457        .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
458        .await?;
459    let Some(ws) = current.workspace else {
460        writeln!(
461            out,
462            "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
463        )
464        .expect("writing to a String cannot fail");
465        return Ok(1);
466    };
467    writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
468        .expect("writing to a String cannot fail");
469    Ok(0)
470}
471
472/// `synced (star), embedding 3 pending` and the like.
473fn describe_state(ws: &proto::CurrentWorkspace) -> String {
474    let state = if !ws.reachable {
475        "unreachable"
476    } else if ws.sync.enabled {
477        "synced"
478    } else {
479        "not synced"
480    };
481    let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
482        " (star)"
483    } else {
484        ""
485    };
486    let pending = match &ws.sync.embedding {
487        Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
488        _ => String::new(),
489    };
490    format!("{state}{star}{pending}")
491}
492
493/// Connect to `app`'s server, or say none is running.
494async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
495    let endpoint = Endpoint::for_app(app)?;
496    let client_info = ClientInfo {
497        kind: "cli".to_owned(),
498        version: version.to_owned(),
499        api: proto::API_VERSION,
500        app_api: None,
501        pid: std::process::id(),
502    };
503    let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
504    if client.is_none() {
505        println!("no {app} server is running");
506    }
507    Ok(client.map(|(c, _)| c))
508}
509
510/// `workspace select`: switch the server to an existing workspace.
511async fn workspace_select(
512    app: &'static str,
513    version: &'static str,
514    dir: Option<PathBuf>,
515) -> Result<i32> {
516    let Some(client) = connect_app(app, version).await? else {
517        return Ok(1);
518    };
519    // Resolved here: the server's cwd is not the user's.
520    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
521    let ws: proto::CurrentWorkspace = client
522        .call(
523            proto::WORKSPACE_SELECT,
524            proto::WorkspaceSelectParams { dir },
525        )
526        .await?;
527    println!("{} {}", ws.root.display(), describe_state(&ws));
528    Ok(0)
529}
530
531/// `workspace move`: move the server's workspace folder.
532async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
533    let Some(client) = connect_app(app, version).await? else {
534        return Ok(1);
535    };
536    // Resolved here: the server's cwd is not the user's.
537    let dir = std::env::current_dir()?.join(dir);
538    let ws: proto::CurrentWorkspace = client
539        .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
540        .await?;
541    println!("{} {}", ws.root.display(), describe_state(&ws));
542    Ok(0)
543}
544
545/// `workspace remove`: let go of the server's workspace, deleting it with `--delete`.
546async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
547    let Some(client) = connect_app(app, version).await? else {
548        return Ok(1);
549    };
550    let _: proto::Ack = client
551        .call(
552            proto::WORKSPACE_REMOVE,
553            proto::WorkspaceRemoveParams { delete },
554        )
555        .await?;
556    println!(
557        "{}",
558        if delete {
559            "removed and deleted"
560        } else {
561            "removed; the files stay"
562        }
563    );
564    Ok(0)
565}
566
567/// `workspace show`: the server's workspace, then the workgroup's workspaces of this app.
568///
569/// The workgroup's ledger is the bridge's to answer, and the bridge being down is not the
570/// server half's failure: the ledger's absence is one line, and the exit is the server
571/// half's.
572async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
573    let Some(client) = connect_app(app, version).await? else {
574        return Ok(1);
575    };
576    let mut out = String::new();
577    let code = render_workspace(&client, &mut out).await?;
578    for line in out.lines() {
579        println!("{line}");
580    }
581
582    let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
583        println!("no sapphire-bridge is running");
584        return Ok(code);
585    };
586    let workspaces = client.workspaces().await.map_err(Error::from)?;
587    let mine: Vec<_> = workspaces
588        .workspaces
589        .into_iter()
590        .filter(|w| w.app_name == app)
591        .collect();
592    if !mine.is_empty() {
593        println!();
594        println!("in the workgroup:");
595        for workspace in mine {
596            println!("{} {}", workspace.name, workspace.workspace_id);
597        }
598    }
599    Ok(code)
600}
601
602/// `workspace map`: the bridge resolves the selector, the server takes the write.
603///
604/// The resolution is the workgroup's word (which workspace, by what id), the write is the
605/// server's (`sync.map` places the id and starts the replica). The bridge is required —
606/// without it there is nothing to resolve against, so exit 1 — and so is the server,
607/// because the write and the replica are its.
608async fn workspace_map(
609    app: &'static str,
610    version: &'static str,
611    selector: &str,
612    dir: Option<PathBuf>,
613) -> Result<i32> {
614    let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
615        println!("no sapphire-bridge is running");
616        return Ok(1);
617    };
618    let workspaces = client.workspaces().await.map_err(Error::from)?;
619    let wanted = workspaces
620        .workspaces
621        .iter()
622        // A name is the user-facing handle; the id is the exact one.
623        .find(|w| w.name == selector || w.workspace_id.to_string() == selector)
624        .ok_or_else(|| Error::UnknownWorkspaceName(selector.to_owned()))?;
625
626    let endpoint = Endpoint::for_app(app)?;
627    let client_info = ClientInfo {
628        kind: "cli".to_owned(),
629        version: version.to_owned(),
630        api: proto::API_VERSION,
631        app_api: None,
632        pid: std::process::id(),
633    };
634    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
635    else {
636        println!("no {app} server is running");
637        return Ok(1);
638    };
639
640    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
641    let mapped: proto::SyncEnableResult = client
642        .call(
643            proto::SYNC_MAP,
644            proto::SyncMapParams {
645                workspace: wanted.workspace_id.to_string(),
646                dir,
647            },
648        )
649        .await?;
650    println!(
651        "mapped {} as {}; the {app} server now serves it",
652        wanted.name, mapped.workspace_id
653    );
654    Ok(0)
655}
656
657/// The status command's face: render and return the exit code, going to the process's
658/// standard output.
659async fn status(server: &AppServer, version: &str) -> Result<i32> {
660    let endpoint = Endpoint::for_app(server.app_name())?;
661    run_status(&endpoint, server.app_name(), version).await
662}
663
664/// Probe, handshake and call `SERVER_INFO` in one go, or report absence.
665///
666/// Every step the CLI needs — liveness and the API gate — is inside
667/// [`connect_or_absent`], so the command is that call plus one `SERVER_INFO` round trip.
668/// The API gate doubles as the liveness check here: a live server of another API version
669/// is `ApiVersionMismatch`, which names both API versions and advises upgrading and
670/// restarting the service. The report goes through [`run_status_into`] so tests can
671/// capture it.
672async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
673    let mut out = String::new();
674    let code = run_status_into(endpoint, app, version, &mut out).await?;
675    for line in out.lines() {
676        println!("{line}");
677    }
678    Ok(code)
679}
680
681/// [`run_status`], writing the rendered lines into `out` instead of the process's
682/// standard output.
683async fn run_status_into(
684    endpoint: &Endpoint,
685    app: &str,
686    version: &str,
687    out: &mut String,
688) -> Result<i32> {
689    let client_info = ClientInfo {
690        kind: "cli".to_owned(),
691        version: version.to_owned(),
692        api: proto::API_VERSION,
693        app_api: None,
694        pid: std::process::id(),
695    };
696    let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
697    else {
698        // Nothing is listening: the framework's half is only the one line, and the
699        // application's rows are skipped (there is no server to have configured them).
700        writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
701        return Ok(1);
702    };
703    let report: StatusReport = client
704        .call(
705            sapphire_backend::protocol::SERVER_INFO,
706            serde_json::json!({}),
707        )
708        .await?;
709    writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
710    if let Some(version) = &report.version {
711        writeln!(out, "version: {version}").expect("writing to a String cannot fail");
712    }
713    if let Some(pid) = report.pid {
714        writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
715    }
716    if let Some(managed_by) = &report.managed_by {
717        writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
718    }
719    for row in &report.app {
720        writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
721    }
722    Ok(0)
723}
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use clap::Parser;
728
729    /// The composition every app binary uses: an app-owned subcommand enum whose framework
730    /// verbs ride in on a flattened variant (spec decision 2).
731    ///
732    /// clap 4 rejects `#[command(flatten)]` on a struct field beside a
733    /// `#[command(subcommand)]` field — two subcommand enums cannot share one level, and a
734    /// flattened field must implement `clap::Args`, which the `Subcommand` derive does not
735    /// provide. The plan's Risks section names this probe as the decision, and the flat
736    /// fallback is what it decided: one subcommand enum, every verb at the top level.
737    #[derive(Parser)]
738    struct Probe {
739        #[command(subcommand)]
740        command: Command,
741    }
742
743    #[derive(Debug, clap::Subcommand)]
744    enum Command {
745        /// An app-specific verb that must parse beside the framework's.
746        Greet,
747        #[command(flatten)]
748        Framework(FrameworkCommand),
749    }
750
751    #[test]
752    fn app_and_framework_commands_parse_side_by_side() {
753        let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
754        assert!(matches!(probe.command, Command::Greet));
755        let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
756        assert!(matches!(
757            probe.command,
758            Command::Framework(FrameworkCommand::Serve)
759        ));
760        let probe = Probe::try_parse_from(["app", "status"]).unwrap();
761        assert!(matches!(
762            probe.command,
763            Command::Framework(FrameworkCommand::Status)
764        ));
765    }
766
767    #[test]
768    fn the_service_subcommands_parse() {
769        for args in [
770            vec!["app", "service", "install"],
771            vec!["app", "service", "uninstall"],
772            vec!["app", "service", "status"],
773        ] {
774            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
775        }
776    }
777
778    #[test]
779    fn the_workspace_and_bridge_commands_parse() {
780        for args in [
781            vec!["app", "workspace", "init"],
782            vec!["app", "workspace", "init", "papers"],
783            vec!["app", "workspace", "init", "--sync"],
784            vec!["app", "workspace", "show"],
785            vec!["app", "workspace", "select", "papers"],
786            vec!["app", "workspace", "map", "papers", "papers-remote"],
787            vec!["app", "workspace", "move", "../papers"],
788            vec!["app", "workspace", "remove"],
789            vec!["app", "workspace", "remove", "--delete"],
790            vec![
791                "app",
792                "workgroup",
793                "create",
794                "--device-name",
795                "laptop",
796                "home",
797            ],
798            vec!["app", "workgroup", "list"],
799            vec![
800                "app",
801                "workgroup",
802                "join",
803                "--device-name",
804                "laptop",
805                "TICKET",
806            ],
807            vec!["app", "device", "list"],
808            vec!["app", "device", "invite", "--name", "phone"],
809            vec!["app", "device", "retire", "phone"],
810        ] {
811            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
812        }
813    }
814
815    #[test]
816    fn bare_invocation_defaults_to_serve() {
817        // <app> with no subcommand at all means serve (spec decision 1). An app CLI
818        // achieves it by `Option<Command>` and handing the framework's default here; this
819        // probe pins the framework half.
820        #[derive(Parser)]
821        struct Bare {
822            #[command(subcommand)]
823            command: Option<Command>,
824        }
825        let bare = Bare::try_parse_from(["app"]).unwrap();
826        assert!(bare.command.is_none());
827        assert!(matches!(
828            FrameworkCommand::default(),
829            FrameworkCommand::Serve
830        ));
831    }
832}
833
834#[cfg(test)]
835mod status_tests {
836    use super::*;
837    use sapphire_workspace::AppContext;
838
839    static CTX: AppContext = AppContext::new("sapphire-statustest");
840
841    /// Wait until something is listening on `endpoint`.
842    ///
843    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
844    /// `run_status` probe can run before `run` has bound the socket, and with nothing
845    /// listening that single unlucky probe is the whole test failing.
846    async fn wait_until_listening(endpoint: &Endpoint) {
847        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
848        while !sapphire_ipc::probe(endpoint).await.unwrap() {
849            assert!(
850                tokio::time::Instant::now() < deadline,
851                "the server never started listening"
852            );
853            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
854        }
855    }
856
857    #[tokio::test]
858    async fn status_reports_no_server_when_none_is_running() {
859        let tmp = tempfile::tempdir().unwrap();
860        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
861        let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
862        assert_eq!(code, 1, "no server is a non-zero exit");
863    }
864
865    #[tokio::test(flavor = "multi_thread")]
866    async fn status_shows_the_extension_rows_of_a_running_server() {
867        let tmp = tempfile::tempdir().unwrap();
868        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
869        let server = AppServer::new(&CTX, "0.0.0")
870            .endpoint(endpoint.clone())
871            // This context's directories are never initialised here.
872            .selection_file(tmp.path().join("workspace.toml"))
873            .status_rows(std::sync::Arc::new(|| {
874                vec![StatusRow {
875                    name: "sync".into(),
876                    value: "on".into(),
877                }]
878            }));
879        let handle = tokio::spawn(async move { server.run().await });
880        wait_until_listening(&endpoint).await;
881
882        // The report goes through the sink face so the rendering is asserted, not just
883        // the exit code.
884        let mut out = String::new();
885        let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
886            .await
887            .unwrap();
888        assert_eq!(code, 0);
889        assert!(out.contains("running: true"), "output was: {out}");
890        assert!(out.contains("sync: on"), "output was: {out}");
891
892        let (client, _) = sapphire_ipc::connect_or_absent(
893            &endpoint,
894            CTX.app_name,
895            sapphire_ipc::ClientInfo {
896                kind: "test".into(),
897                version: "0.0.0".into(),
898                api: sapphire_backend::protocol::API_VERSION,
899                app_api: None,
900                pid: std::process::id(),
901            },
902        )
903        .await
904        .unwrap()
905        .expect("the server is listening");
906        let _: serde_json::Value = client
907            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
908            .await
909            .unwrap();
910        handle.await.unwrap().unwrap();
911    }
912}
913
914#[cfg(test)]
915mod service_spec_tests {
916    use super::*;
917    use sapphire_workspace::AppContext;
918
919    static CTX: AppContext = AppContext::new("sapphire-servicetest");
920
921    #[test]
922    fn the_generated_spec_runs_the_server_not_the_cli() {
923        // A service manager starts the executable directly, and the executable's bare
924        // invocation is `serve`: the unit's argv must be exactly that, so the server that
925        // starts has no CLI verbs on its command line to misparse.
926        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
927        assert_eq!(spec.args, vec!["serve".to_owned()]);
928    }
929
930    #[test]
931    fn the_generated_spec_names_this_application() {
932        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
933        assert_eq!(spec.app_name, CTX.app_name);
934    }
935
936    #[test]
937    fn the_generated_spec_describes_the_server() {
938        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
939        assert!(
940            spec.description.contains(CTX.app_name),
941            "the unit's description should name the application: {:?}",
942            spec.description
943        );
944        assert!(spec.description.contains("0.0.0"));
945    }
946}