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