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