1use 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#[derive(Debug, clap::Subcommand)]
25pub enum FrameworkCommand {
26 Serve,
28 Status,
30 #[command(subcommand)]
32 Service(ServiceCommand),
33 Update(AppUpdateArgs),
37 #[command(subcommand)]
40 Workspace(WorkspaceCommand),
41 #[command(subcommand)]
43 Workgroup(WorkgroupCommand),
44 #[command(subcommand)]
46 Device(DeviceCommand),
47 #[command(subcommand)]
50 Embedding(sapphire_bridge_api::EmbeddingCommand),
51 #[command(subcommand)]
55 ExternalDevice(sapphire_bridge_api::ExternalDeviceCommand),
56 #[cfg(feature = "mcp")]
59 Mcp,
60}
61
62impl FrameworkCommand {
63 pub async fn dispatch(self, server: AppServer, version: &'static str) -> Result<i32> {
68 match self {
69 FrameworkCommand::Serve => {
70 server.run().await?;
71 Ok(0)
72 }
73 FrameworkCommand::Status => crate::command::status(&server, version).await,
74 FrameworkCommand::Service(command) => {
75 let spec = server.service_spec();
76 command
77 .run(&spec, &Environment::detect(), &SystemManager)
78 .map_err(Error::from)
79 }
80 FrameworkCommand::Update(args) => {
81 let own = match server.release_source() {
82 Some(source) => sapphire_framework_update::run(
83 &args.update,
84 source,
85 server.app_name(),
86 version,
87 )
88 .await
89 .map_err(Error::from),
90 None => {
91 println!("{} does not say where its releases are", server.app_name());
92 Ok(1)
93 }
94 };
95 let bridge = if args.no_bridge {
98 0
99 } else {
100 update_bridge(&args.update).await?
101 };
102 Ok(own?.max(bridge))
103 }
104 FrameworkCommand::Workspace(command) => {
105 command.dispatch(server.app_name(), version).await
106 }
107 FrameworkCommand::Workgroup(command) => command.dispatch(version).await,
108 FrameworkCommand::Device(command) => command.dispatch(version).await,
109 FrameworkCommand::Embedding(command) => embedding(command, version).await,
110 FrameworkCommand::ExternalDevice(command) => {
111 external_device(command, server.app_name(), version).await
112 }
113 #[cfg(feature = "mcp")]
114 FrameworkCommand::Mcp => {
115 server.serve_mcp_stdio(version).await?;
116 Ok(0)
117 }
118 }
119 }
120}
121
122#[derive(Clone, Debug, Default, clap::Args)]
124pub struct AppUpdateArgs {
125 #[command(flatten)]
127 pub update: sapphire_framework_update::UpdateArgs,
128 #[arg(long)]
130 pub no_bridge: bool,
131}
132
133const BRIDGE_BINARY: &str = "sapphire-bridge";
135
136const BRIDGE_RELEASES: &str = "https://github.com/sapphire-turtle/sapphire-framework/releases";
138
139fn find_on_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
141 let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
142 std::env::split_paths(path?)
143 .map(|dir| dir.join(&file))
144 .find(|candidate| candidate.is_file())
145}
146
147async fn update_bridge(args: &sapphire_framework_update::UpdateArgs) -> Result<i32> {
150 match find_on_path(BRIDGE_BINARY, std::env::var_os("PATH").as_deref()) {
151 Some(exe) => run_bridge_update(&exe, args).await,
152 None => {
153 println!("{BRIDGE_BINARY} is not on PATH; not updating it");
154 Ok(0)
155 }
156 }
157}
158
159async fn run_bridge_update(
165 exe: &std::path::Path,
166 args: &sapphire_framework_update::UpdateArgs,
167) -> Result<i32> {
168 let knows_update = tokio::process::Command::new(exe)
170 .args(["update", "--help"])
171 .stdout(std::process::Stdio::null())
172 .stderr(std::process::Stdio::null())
173 .status()
174 .await?
175 .success();
176 if !knows_update {
177 println!(
178 "{} cannot update itself; install the newest from {BRIDGE_RELEASES}",
179 exe.display()
180 );
181 return Ok(1);
182 }
183 let mut command = tokio::process::Command::new(exe);
184 command.arg("update");
185 if args.check {
186 command.arg("--check");
187 }
188 if args.yes {
189 command.arg("--yes");
190 }
191 let status = command.status().await?;
193 Ok(status.code().unwrap_or(1))
194}
195
196#[derive(Debug, clap::Subcommand)]
203pub enum WorkspaceCommand {
204 Init {
206 dir: Option<PathBuf>,
208 #[arg(long)]
210 sync: bool,
211 #[arg(long, value_name = "NAME|ID", requires = "sync")]
214 remote_workspace: Option<String>,
215 },
216 Select {
218 dir: Option<PathBuf>,
220 #[arg(long)]
223 sync: bool,
224 },
225 #[command(subcommand)]
227 Sync(WorkspaceSyncCommand),
228 Show,
230 Move {
232 dir: PathBuf,
234 },
235 Remove {
237 #[arg(long)]
239 delete: bool,
240 },
241}
242
243impl WorkspaceCommand {
244 pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
249 match self {
250 WorkspaceCommand::Init {
251 dir,
252 sync,
253 remote_workspace,
254 } => workspace_init(app, version, dir, sync, remote_workspace).await,
255 WorkspaceCommand::Select { dir, sync } => {
256 workspace_select(app, version, dir, sync).await
257 }
258 WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
259 WorkspaceCommand::Show => workspace_show(app, version).await,
260 WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
261 WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
262 }
263 }
264}
265
266#[derive(Debug, clap::Subcommand)]
268pub enum WorkspaceSyncCommand {
269 Enable,
271 Disable,
274 Status,
276}
277
278#[derive(Debug, clap::Subcommand)]
283pub enum WorkgroupCommand {
284 Create {
286 name: String,
288 #[arg(long)]
290 device_name: String,
291 },
292 List,
294 Join {
296 ticket: String,
298 #[arg(long)]
300 device_name: Option<String>,
301 },
302}
303
304impl WorkgroupCommand {
305 pub async fn dispatch(self, version: &'static str) -> Result<i32> {
307 match self {
308 WorkgroupCommand::Create { name, device_name } => {
309 let client = connect_running(version).await?;
310 let created = client
311 .workgroup_create(WorkgroupCreateParams { name, device_name })
312 .await?;
313 println!(
314 "created workgroup {} ({}); this device is {}",
315 created.name, created.workgroup_id, created.device_id
316 );
317 Ok(0)
318 }
319 WorkgroupCommand::List => {
320 let client = connect_running(version).await?;
321 match client.status().await?.workgroup {
322 Some(workgroup) => {
323 println!("{} ({})", workgroup.name, workgroup.workgroup_id);
324 Ok(0)
325 }
326 None => {
327 println!("this host has not joined a workgroup");
328 Ok(1)
329 }
330 }
331 }
332 WorkgroupCommand::Join {
333 ticket,
334 device_name,
335 } => {
336 let client = connect_running(version).await?;
337 let joined = client
338 .join(JoinParams {
339 ticket,
340 device_name,
341 })
342 .await?;
343 println!(
344 "joined workgroup {} ({}); this device is {}",
345 joined.workgroup_name, joined.workgroup_id, joined.device_id
346 );
347 Ok(0)
348 }
349 }
350 }
351}
352
353#[derive(Debug, clap::Subcommand)]
359pub enum DeviceCommand {
360 List,
362 Invite {
364 #[arg(long)]
366 name: String,
367 #[arg(long)]
369 ttl: Option<u64>,
370 #[arg(long)]
372 workgroup: Option<String>,
373 },
374 Retire {
376 selector: String,
378 },
379 Priority {
382 selector: String,
384 priority: Option<u8>,
386 },
387}
388
389impl DeviceCommand {
390 pub async fn dispatch(self, version: &'static str) -> Result<i32> {
392 match self {
393 DeviceCommand::List => {
394 let client = connect_running(version).await?;
395 let peers = client.peers().await?;
396 if peers.peers.is_empty() {
397 println!("no devices");
398 return Ok(0);
399 }
400 for peer in peers.peers {
401 println!(
402 "{} {} p{}{}{}",
403 peer.name,
404 peer.device_id,
405 peer.priority,
406 peer.availability
407 .map(|a| format!(" a{a}"))
408 .unwrap_or_default(),
409 if peer.connected { " (online)" } else { "" }
410 );
411 }
412 Ok(0)
413 }
414 DeviceCommand::Invite {
415 name,
416 ttl,
417 workgroup,
418 } => {
419 let client = connect_running(version).await?;
420 let invite = client
421 .invite(InviteParams {
422 name,
423 ttl,
424 workgroup,
425 })
426 .await?;
427 println!("{}", invite.ticket);
430 Ok(0)
431 }
432 DeviceCommand::Retire { selector } => {
433 let client = connect_running(version).await?;
434 let retired = client
435 .device_retire(DeviceRetireParams { selector })
436 .await?;
437 println!("retired device {} ({})", retired.name, retired.device_id);
438 Ok(0)
439 }
440 DeviceCommand::Priority { selector, priority } => {
441 let client = connect_running(version).await?;
442 match priority {
443 Some(priority) => {
444 let set = client
445 .device_priority_set(DevicePrioritySetParams { selector, priority })
446 .await?;
447 println!("{} ({}) priority {}", set.name, set.device_id, set.priority);
448 }
449 None => {
450 let peers = client.peers().await?;
451 match peers
452 .peers
453 .iter()
454 .find(|p| p.name == selector || p.device_id.to_string() == selector)
455 {
456 Some(p) => {
457 println!("{} ({}) priority {}", p.name, p.device_id, p.priority)
458 }
459 None => {
460 println!("no device {selector:?}");
461 return Ok(1);
462 }
463 }
464 }
465 }
466 Ok(0)
467 }
468 }
469 }
470}
471
472async fn connect_running(version: &str) -> Result<BridgeClient> {
478 BridgeClient::connect_running("cli", version)
479 .await
480 .map_err(Error::from)
481}
482
483async fn embedding(command: sapphire_bridge_api::EmbeddingCommand, version: &str) -> Result<i32> {
485 let client = connect_running(version).await?;
487 let request = command.request()?;
488 let report = client.embed_request(request).await?;
489 for line in sapphire_bridge_api::describe(&report) {
490 println!("{line}");
491 }
492 Ok(0)
493}
494
495async fn external_device(
497 command: sapphire_bridge_api::ExternalDeviceCommand,
498 app: &str,
499 version: &str,
500) -> Result<i32> {
501 let client = connect_running(version).await?;
502 let outcome = client
503 .external_device_request(command.request(Some(app)))
504 .await?;
505 for line in sapphire_bridge_api::describe_external_outcome(&outcome) {
506 println!("{line}");
507 }
508 Ok(0)
509}
510
511async fn workspace_init(
524 app: &'static str,
525 version: &'static str,
526 dir: Option<PathBuf>,
527 sync: bool,
528 remote_workspace: Option<String>,
529) -> Result<i32> {
530 let endpoint = Endpoint::for_app(app)?;
531 let client_info = ClientInfo {
532 kind: "cli".to_owned(),
533 version: version.to_owned(),
534 api: proto::API_VERSION,
535 app_api: None,
536 pid: std::process::id(),
537 };
538 let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
539 else {
540 println!("no {app} server is running");
541 return Ok(1);
542 };
543
544 let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
546 if let Some(selector) = remote_workspace {
547 let mapped: proto::SyncEnableResult = client
548 .call(
549 proto::SYNC_MAP,
550 proto::SyncMapParams {
551 workspace: selector.clone(),
552 dir: dir.clone(),
553 },
554 )
555 .await?;
556 println!(
557 "initialized {app} workspace in {} from {selector}",
558 dir.display()
559 );
560 println!(
561 "the {app} server now serves it, syncing as {}",
562 mapped.workspace_id
563 );
564 return Ok(0);
565 }
566 let result: proto::WorkspaceInitResult = client
567 .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
568 .await?;
569 if result.created {
570 println!("initialized {app} workspace in {}", result.root.display());
571 } else {
572 println!(
573 "{} already exists (workspace {})",
574 result.root.display(),
575 result.workspace_id
576 );
577 }
578 println!("the {app} server now serves {}", result.root.display());
579
580 if sync {
581 enable_sync(&client).await?;
582 }
583 Ok(0)
584}
585
586async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
592 let enabled: proto::SyncEnableResult = client
593 .call(proto::SYNC_ENABLE, serde_json::json!({}))
594 .await?;
595 let status: proto::SyncStatusResult = client
598 .call(proto::SYNC_STATUS, serde_json::json!({}))
599 .await
600 .unwrap_or(proto::SyncStatusResult {
601 enabled: true,
602 workspace_id: Some(enabled.workspace_id),
603 ..proto::SyncStatusResult::not_synced()
604 });
605 println!(
606 "syncing as {} ({} peer{})",
607 enabled.workspace_id,
608 status.peers,
609 if status.peers == 1 { "" } else { "s" }
610 );
611 Ok(())
612}
613
614async fn workspace_sync(
616 app: &'static str,
617 version: &'static str,
618 command: WorkspaceSyncCommand,
619) -> Result<i32> {
620 let Some(client) = connect_app(app, version).await? else {
621 return Ok(1);
622 };
623 match command {
624 WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
625 WorkspaceSyncCommand::Disable => {
626 let _: proto::Ack = client
627 .call(proto::SYNC_DISABLE, serde_json::json!({}))
628 .await?;
629 println!("sync is off for the {app} workspace on this host; it keeps its sync id");
630 }
631 WorkspaceSyncCommand::Status => {
632 let status: proto::SyncStatusResult = client
633 .call(proto::SYNC_STATUS, serde_json::json!({}))
634 .await?;
635 for line in describe_sync(&status) {
636 println!("{line}");
637 }
638 }
639 }
640 Ok(0)
641}
642
643fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
645 let mut lines = vec![format!(
646 "sync: {}",
647 if status.enabled { "on" } else { "off" }
648 )];
649 if let Some(id) = status.workspace_id {
650 lines.push(format!("workspace id: {id}"));
651 }
652 if status.enabled {
653 lines.push(format!(
654 "peers: {}{}",
655 status.peers,
656 if matches!(status.topology, proto::Topology::Star { .. }) {
657 " (star)"
658 } else {
659 ""
660 }
661 ));
662 lines.push(format!(
663 "bridge: {}",
664 if status.bridge_available {
665 "reachable"
666 } else {
667 "not reachable"
668 }
669 ));
670 }
671 if let Some(paused) = &status.paused {
672 lines.push(format!("paused: {paused}"));
673 }
674 if let Some(error) = &status.last_error {
675 lines.push(format!("last error: {error}"));
676 }
677 lines
678}
679
680pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
685 let current: proto::WorkspaceCurrentResult = client
686 .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
687 .await?;
688 let Some(ws) = current.workspace else {
689 writeln!(
690 out,
691 "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
692 )
693 .expect("writing to a String cannot fail");
694 return Ok(1);
695 };
696 writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
697 .expect("writing to a String cannot fail");
698 Ok(0)
699}
700
701fn describe_state(ws: &proto::CurrentWorkspace) -> String {
703 let state = if !ws.reachable {
704 "unreachable"
705 } else if ws.sync.enabled {
706 "synced"
707 } else {
708 "not synced"
709 };
710 let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
711 " (star)"
712 } else {
713 ""
714 };
715 let pending = match &ws.sync.embedding {
716 Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
717 _ => String::new(),
718 };
719 format!("{state}{star}{pending}")
720}
721
722async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
724 let endpoint = Endpoint::for_app(app)?;
725 let client_info = ClientInfo {
726 kind: "cli".to_owned(),
727 version: version.to_owned(),
728 api: proto::API_VERSION,
729 app_api: None,
730 pid: std::process::id(),
731 };
732 let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
733 if client.is_none() {
734 println!("no {app} server is running");
735 }
736 Ok(client.map(|(c, _)| c))
737}
738
739async fn workspace_select(
741 app: &'static str,
742 version: &'static str,
743 dir: Option<PathBuf>,
744 sync: bool,
745) -> Result<i32> {
746 let Some(client) = connect_app(app, version).await? else {
747 return Ok(1);
748 };
749 let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
751 let ws: proto::CurrentWorkspace = client
752 .call(
753 proto::WORKSPACE_SELECT,
754 proto::WorkspaceSelectParams { dir },
755 )
756 .await?;
757 println!("{} {}", ws.root.display(), describe_state(&ws));
758 if sync && !ws.sync.enabled {
760 enable_sync(&client).await?;
761 }
762 Ok(0)
763}
764
765async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
767 let Some(client) = connect_app(app, version).await? else {
768 return Ok(1);
769 };
770 let dir = std::env::current_dir()?.join(dir);
772 let ws: proto::CurrentWorkspace = client
773 .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
774 .await?;
775 println!("{} {}", ws.root.display(), describe_state(&ws));
776 Ok(0)
777}
778
779async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
781 let Some(client) = connect_app(app, version).await? else {
782 return Ok(1);
783 };
784 let _: proto::Ack = client
785 .call(
786 proto::WORKSPACE_REMOVE,
787 proto::WorkspaceRemoveParams { delete },
788 )
789 .await?;
790 println!(
791 "{}",
792 if delete {
793 "removed and deleted"
794 } else {
795 "removed; the files stay"
796 }
797 );
798 Ok(0)
799}
800
801async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
807 let Some(client) = connect_app(app, version).await? else {
808 return Ok(1);
809 };
810 let mut out = String::new();
811 let code = render_workspace(&client, &mut out).await?;
812 for line in out.lines() {
813 println!("{line}");
814 }
815
816 let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
817 println!("no sapphire-bridge is running");
818 return Ok(code);
819 };
820 let workspaces = client.workspaces().await.map_err(Error::from)?;
821 let mine: Vec<_> = workspaces
822 .workspaces
823 .into_iter()
824 .filter(|w| w.app_name == app)
825 .collect();
826 if !mine.is_empty() {
827 println!();
828 println!("in the workgroup:");
829 for workspace in mine {
830 println!("{} {}", workspace.name, workspace.workspace_id);
831 }
832 }
833 Ok(code)
834}
835
836async fn status(server: &AppServer, version: &str) -> Result<i32> {
839 let endpoint = Endpoint::for_app(server.app_name())?;
840 run_status(&endpoint, server.app_name(), version).await
841}
842
843async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
852 let mut out = String::new();
853 let code = run_status_into(endpoint, app, version, &mut out).await?;
854 for line in out.lines() {
855 println!("{line}");
856 }
857 Ok(code)
858}
859
860async fn run_status_into(
863 endpoint: &Endpoint,
864 app: &str,
865 version: &str,
866 out: &mut String,
867) -> Result<i32> {
868 let client_info = ClientInfo {
869 kind: "cli".to_owned(),
870 version: version.to_owned(),
871 api: proto::API_VERSION,
872 app_api: None,
873 pid: std::process::id(),
874 };
875 let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
876 else {
877 writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
880 return Ok(1);
881 };
882 let report: StatusReport = client
883 .call(
884 sapphire_backend::protocol::SERVER_INFO,
885 serde_json::json!({}),
886 )
887 .await?;
888 writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
889 if let Some(version) = &report.version {
890 writeln!(out, "version: {version}").expect("writing to a String cannot fail");
891 }
892 if let Some(pid) = report.pid {
893 writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
894 }
895 if let Some(managed_by) = &report.managed_by {
896 writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
897 }
898 for row in &report.app {
899 writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
900 }
901 let update: Option<proto::UpdateStatus> = client
904 .call(proto::SERVER_UPDATE, serde_json::json!({}))
905 .await
906 .ok();
907 for line in describe_update(app, version, report.version.as_deref(), update.as_ref()) {
908 writeln!(out, "{line}").expect("writing to a String cannot fail");
909 }
910 Ok(0)
911}
912
913fn describe_update(
920 app: &str,
921 installed: &str,
922 running: Option<&str>,
923 update: Option<&proto::UpdateStatus>,
924) -> Vec<String> {
925 let parse = |v: &str| semver::Version::parse(v).ok();
926 let installed_v = parse(installed);
927 let mut lines = Vec::new();
928 if let Some(update) = update.filter(|u| u.enabled) {
929 match (&update.latest, &update.last_error) {
930 (Some(latest), _) => {
931 let newer = match (parse(&latest.version), &installed_v) {
932 (Some(latest), Some(installed)) => latest > *installed,
933 _ => update.update_available,
934 };
935 if newer {
936 lines.push(format!(
937 "update: {} is available ({})",
938 latest.version, latest.url
939 ));
940 } else {
941 lines.push(format!(
942 "update: up to date (latest release {})",
943 latest.version
944 ));
945 }
946 }
947 (None, Some(error)) => lines.push(format!("update: could not check: {error}")),
948 (None, None) => lines.push("update: not checked yet".to_owned()),
949 }
950 }
951 if let (Some(running), Some(installed)) = (running.and_then(parse), installed_v)
952 && installed > running
953 {
954 lines.push(format!(
955 "restart: needed: {installed} is installed but {running} is running; restart the {app} service"
956 ));
957 }
958 lines
959}
960#[cfg(test)]
961mod tests {
962 use super::*;
963 use clap::Parser;
964
965 #[derive(Parser)]
974 struct Probe {
975 #[command(subcommand)]
976 command: Command,
977 }
978
979 #[derive(Debug, clap::Subcommand)]
980 enum Command {
981 Greet,
983 #[command(flatten)]
984 Framework(FrameworkCommand),
985 }
986
987 #[test]
988 fn app_and_framework_commands_parse_side_by_side() {
989 let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
990 assert!(matches!(probe.command, Command::Greet));
991 let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
992 assert!(matches!(
993 probe.command,
994 Command::Framework(FrameworkCommand::Serve)
995 ));
996 let probe = Probe::try_parse_from(["app", "status"]).unwrap();
997 assert!(matches!(
998 probe.command,
999 Command::Framework(FrameworkCommand::Status)
1000 ));
1001 }
1002
1003 #[cfg(feature = "mcp")]
1004 #[test]
1005 fn the_mcp_command_parses_beside_the_apps() {
1006 let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
1007 assert!(matches!(
1008 probe.command,
1009 Command::Framework(FrameworkCommand::Mcp)
1010 ));
1011 }
1012
1013 #[test]
1014 fn the_update_command_parses_with_and_without_the_bridge() {
1015 let probe = Probe::try_parse_from(["app", "update", "--check", "-y"]).unwrap();
1016 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
1017 panic!("not update");
1018 };
1019 assert!(args.update.check && args.update.yes && !args.no_bridge);
1020 let probe = Probe::try_parse_from(["app", "update", "--no-bridge"]).unwrap();
1021 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
1022 panic!("not update");
1023 };
1024 assert!(args.no_bridge);
1025 }
1026
1027 #[test]
1028 fn the_bridge_is_found_in_the_first_directory_of_path_that_has_it() {
1029 let tmp = tempfile::tempdir().unwrap();
1030 let (empty, first, second) = (
1031 tmp.path().join("empty"),
1032 tmp.path().join("first"),
1033 tmp.path().join("second"),
1034 );
1035 let file = format!("sapphire-bridge{}", std::env::consts::EXE_SUFFIX);
1036 for dir in [&empty, &first, &second] {
1037 std::fs::create_dir(dir).unwrap();
1038 }
1039 std::fs::write(first.join(&file), b"").unwrap();
1040 std::fs::write(second.join(&file), b"").unwrap();
1041 let path = std::env::join_paths([&empty, &first, &second]).unwrap();
1042 assert_eq!(
1043 find_on_path("sapphire-bridge", Some(&path)),
1044 Some(first.join(&file))
1045 );
1046 let path = std::env::join_paths([&empty]).unwrap();
1047 assert_eq!(find_on_path("sapphire-bridge", Some(&path)), None);
1048 assert_eq!(find_on_path("sapphire-bridge", None), None);
1049 }
1050
1051 #[cfg(unix)]
1053 fn script(dir: &std::path::Path, name: &str, body: &str) -> PathBuf {
1054 use std::os::unix::fs::PermissionsExt;
1055 let path = dir.join(name);
1056 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
1057 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1058 path
1059 }
1060
1061 #[cfg(unix)]
1062 #[tokio::test]
1063 async fn the_bridge_runs_its_own_update_with_the_apps_flags() {
1064 let tmp = tempfile::tempdir().unwrap();
1065 let log = tmp.path().join("args");
1066 let exe = script(
1069 tmp.path(),
1070 "bridge",
1071 &format!(
1072 r#"case "$*" in *--help*) exit 0;; esac; echo "$@" > {}; exit 1"#,
1073 log.display()
1074 ),
1075 );
1076 let args = sapphire_framework_update::UpdateArgs {
1077 check: true,
1078 yes: true,
1079 };
1080 assert_eq!(run_bridge_update(&exe, &args).await.unwrap(), 1);
1081 assert_eq!(
1082 std::fs::read_to_string(&log).unwrap().trim(),
1083 "update --check --yes"
1084 );
1085 }
1086
1087 #[cfg(unix)]
1088 #[tokio::test]
1089 async fn a_bridge_without_update_is_not_run() {
1090 let tmp = tempfile::tempdir().unwrap();
1091 let runs = tmp.path().join("runs");
1092 let exe = script(
1094 tmp.path(),
1095 "bridge",
1096 &format!(r#"echo "$*" >> {}; exit 2"#, runs.display()),
1097 );
1098 let code = run_bridge_update(&exe, &Default::default()).await.unwrap();
1099 assert_eq!(code, 1);
1100 assert_eq!(
1101 std::fs::read_to_string(&runs).unwrap(),
1102 "update --help\n",
1103 "only the probe ran"
1104 );
1105 }
1106
1107 #[test]
1108 fn the_service_subcommands_parse() {
1109 for args in [
1110 vec!["app", "service", "install"],
1111 vec!["app", "service", "uninstall"],
1112 vec!["app", "service", "status"],
1113 ] {
1114 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1115 }
1116 }
1117
1118 #[test]
1119 fn the_workspace_and_bridge_commands_parse() {
1120 for args in [
1121 vec!["app", "workspace", "init"],
1122 vec!["app", "workspace", "init", "papers"],
1123 vec!["app", "workspace", "init", "--sync"],
1124 vec!["app", "workspace", "show"],
1125 vec!["app", "workspace", "select", "papers"],
1126 vec!["app", "workspace", "select", "--sync"],
1127 vec!["app", "workspace", "select", "papers", "--sync"],
1128 vec!["app", "workspace", "sync", "enable"],
1129 vec!["app", "workspace", "sync", "disable"],
1130 vec!["app", "workspace", "sync", "status"],
1131 vec![
1132 "app",
1133 "workspace",
1134 "init",
1135 "--sync",
1136 "--remote-workspace=Ledger",
1137 ],
1138 vec![
1139 "app",
1140 "workspace",
1141 "init",
1142 "papers",
1143 "--sync",
1144 "--remote-workspace",
1145 "Ledger",
1146 ],
1147 vec!["app", "workspace", "move", "../papers"],
1148 vec!["app", "workspace", "remove"],
1149 vec!["app", "workspace", "remove", "--delete"],
1150 vec![
1151 "app",
1152 "workgroup",
1153 "create",
1154 "--device-name",
1155 "laptop",
1156 "home",
1157 ],
1158 vec!["app", "workgroup", "list"],
1159 vec![
1160 "app",
1161 "workgroup",
1162 "join",
1163 "--device-name",
1164 "laptop",
1165 "TICKET",
1166 ],
1167 vec!["app", "device", "list"],
1168 vec!["app", "device", "invite", "--name", "phone"],
1169 vec!["app", "device", "retire", "phone"],
1170 ] {
1171 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1172 }
1173 }
1174
1175 #[test]
1176 fn a_remote_workspace_needs_sync() {
1177 let args = ["app", "workspace", "init", "--remote-workspace=Ledger"];
1178 assert!(Probe::try_parse_from(args).is_err());
1179 }
1180
1181 #[test]
1182 fn bare_invocation_prints_the_help() {
1183 #[derive(Parser)]
1187 #[command(arg_required_else_help = true)]
1188 struct Bare {
1189 #[command(subcommand)]
1190 command: Command,
1191 }
1192 let err = Bare::try_parse_from(["app"]).err().unwrap();
1193 assert_eq!(
1194 err.kind(),
1195 clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
1196 );
1197 }
1198}
1199
1200#[cfg(test)]
1201mod status_tests {
1202 use super::*;
1203 use sapphire_workspace::AppContext;
1204
1205 static CTX: AppContext = AppContext::new("sapphire-statustest");
1206
1207 async fn wait_until_listening(endpoint: &Endpoint) {
1213 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
1214 while !sapphire_ipc::probe(endpoint).await.unwrap() {
1215 assert!(
1216 tokio::time::Instant::now() < deadline,
1217 "the server never started listening"
1218 );
1219 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1220 }
1221 }
1222
1223 #[tokio::test]
1224 async fn status_reports_no_server_when_none_is_running() {
1225 let tmp = tempfile::tempdir().unwrap();
1226 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1227 let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
1228 assert_eq!(code, 1, "no server is a non-zero exit");
1229 }
1230
1231 fn update(latest: Option<&str>, error: Option<&str>) -> proto::UpdateStatus {
1232 proto::UpdateStatus {
1233 enabled: true,
1234 latest: latest.map(|version| proto::ReleaseInfo {
1235 version: version.to_owned(),
1236 url: format!("https://example.invalid/v{version}"),
1237 }),
1238 update_available: false,
1239 last_error: error.map(str::to_owned),
1240 }
1241 }
1242
1243 #[test]
1244 fn status_names_a_newer_release_and_nothing_when_up_to_date() {
1245 let lines = describe_update(
1246 "app",
1247 "0.19.0",
1248 Some("0.19.0"),
1249 Some(&update(Some("0.20.0"), None)),
1250 );
1251 assert_eq!(
1252 lines,
1253 vec!["update: 0.20.0 is available (https://example.invalid/v0.20.0)"]
1254 );
1255 let lines = describe_update(
1256 "app",
1257 "0.19.0",
1258 Some("0.19.0"),
1259 Some(&update(Some("0.19.0"), None)),
1260 );
1261 assert_eq!(lines, vec!["update: up to date (latest release 0.19.0)"]);
1262 }
1263
1264 #[test]
1265 fn status_asks_for_a_restart_when_the_installed_server_is_newer_than_the_running_one() {
1266 let lines = describe_update(
1269 "app",
1270 "0.20.0",
1271 Some("0.19.0"),
1272 Some(&update(Some("0.20.0"), None)),
1273 );
1274 assert_eq!(
1275 lines,
1276 vec![
1277 "update: up to date (latest release 0.20.0)",
1278 "restart: needed: 0.20.0 is installed but 0.19.0 is running; restart the app service",
1279 ]
1280 );
1281 let lines = describe_update("app", "0.20.0", Some("0.19.0"), None);
1283 assert_eq!(lines.len(), 1);
1284 assert!(lines[0].starts_with("restart: needed"));
1285 }
1286
1287 #[test]
1288 fn status_says_why_a_check_failed_and_nothing_when_checks_are_off() {
1289 let lines = describe_update(
1290 "app",
1291 "0.19.0",
1292 Some("0.19.0"),
1293 Some(&update(None, Some("offline"))),
1294 );
1295 assert_eq!(lines, vec!["update: could not check: offline"]);
1296 let off = proto::UpdateStatus::default();
1297 assert!(describe_update("app", "0.19.0", Some("0.19.0"), Some(&off)).is_empty());
1298 }
1299
1300 #[tokio::test(flavor = "multi_thread")]
1301 async fn status_shows_a_newer_release_the_server_found() {
1302 let tmp = tempfile::tempdir().unwrap();
1303 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1304 let api = crate::update::stub::one_response(
1305 "200 OK",
1306 r#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid/v0.20.0"}]"#,
1307 )
1308 .await;
1309 let server = AppServer::new(&CTX, "0.19.0")
1310 .endpoint(endpoint.clone())
1311 .selection_file(tmp.path().join("workspace.toml"))
1312 .releases(crate::ReleaseSource::github("o", "r").api_base(api));
1313 let handle = tokio::spawn(async move { server.run().await });
1314 wait_until_listening(&endpoint).await;
1315
1316 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
1318 let out = loop {
1319 let mut out = String::new();
1320 run_status_into(&endpoint, CTX.app_name, "0.19.0", &mut out)
1321 .await
1322 .unwrap();
1323 if !out.contains("not checked yet") {
1324 break out;
1325 }
1326 assert!(
1327 tokio::time::Instant::now() < deadline,
1328 "never checked: {out}"
1329 );
1330 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1331 };
1332 assert!(
1333 out.contains("update: 0.20.0 is available (https://example.invalid/v0.20.0)"),
1334 "output was: {out}"
1335 );
1336 assert!(!out.contains("restart:"), "output was: {out}");
1337
1338 let (client, _) = sapphire_ipc::connect_or_absent(
1339 &endpoint,
1340 CTX.app_name,
1341 sapphire_ipc::ClientInfo {
1342 kind: "test".into(),
1343 version: "0.19.0".into(),
1344 api: sapphire_backend::protocol::API_VERSION,
1345 app_api: None,
1346 pid: std::process::id(),
1347 },
1348 )
1349 .await
1350 .unwrap()
1351 .expect("the server is listening");
1352 let _: serde_json::Value = client
1353 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1354 .await
1355 .unwrap();
1356 handle.await.unwrap().unwrap();
1357 }
1358
1359 #[tokio::test(flavor = "multi_thread")]
1360 async fn status_shows_the_extension_rows_of_a_running_server() {
1361 let tmp = tempfile::tempdir().unwrap();
1362 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1363 let server = AppServer::new(&CTX, "0.0.0")
1364 .endpoint(endpoint.clone())
1365 .selection_file(tmp.path().join("workspace.toml"))
1367 .status_rows(std::sync::Arc::new(|| {
1368 vec![StatusRow {
1369 name: "sync".into(),
1370 value: "on".into(),
1371 }]
1372 }));
1373 let handle = tokio::spawn(async move { server.run().await });
1374 wait_until_listening(&endpoint).await;
1375
1376 let mut out = String::new();
1379 let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
1380 .await
1381 .unwrap();
1382 assert_eq!(code, 0);
1383 assert!(out.contains("running: true"), "output was: {out}");
1384 assert!(out.contains("sync: on"), "output was: {out}");
1385
1386 let (client, _) = sapphire_ipc::connect_or_absent(
1387 &endpoint,
1388 CTX.app_name,
1389 sapphire_ipc::ClientInfo {
1390 kind: "test".into(),
1391 version: "0.0.0".into(),
1392 api: sapphire_backend::protocol::API_VERSION,
1393 app_api: None,
1394 pid: std::process::id(),
1395 },
1396 )
1397 .await
1398 .unwrap()
1399 .expect("the server is listening");
1400 let _: serde_json::Value = client
1401 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1402 .await
1403 .unwrap();
1404 handle.await.unwrap().unwrap();
1405 }
1406}
1407
1408#[cfg(test)]
1409mod service_spec_tests {
1410 use super::*;
1411 use sapphire_workspace::AppContext;
1412
1413 static CTX: AppContext = AppContext::new("sapphire-servicetest");
1414
1415 #[test]
1416 fn the_generated_spec_runs_the_server_not_the_cli() {
1417 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1421 assert_eq!(spec.args, vec!["serve".to_owned()]);
1422 }
1423
1424 #[test]
1425 fn the_generated_spec_names_this_application() {
1426 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1427 assert_eq!(spec.app_name, CTX.app_name);
1428 }
1429
1430 #[test]
1431 fn the_generated_spec_describes_the_server() {
1432 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1433 assert!(
1434 spec.description.contains(CTX.app_name),
1435 "the unit's description should name the application: {:?}",
1436 spec.description
1437 );
1438 assert!(spec.description.contains("0.0.0"));
1439 }
1440}