1use std::fmt::Write as _;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use sapphire_backend::protocol as proto;
8use sapphire_bridge_api::{
9 DevicePrioritySetParams, DeviceRetireParams, InviteParams, JoinParams, WorkgroupCreateParams,
10};
11use sapphire_bridge_client::BridgeClient;
12use sapphire_framework_service::{Environment, ServiceCommand, SystemManager};
13use sapphire_ipc::{ClientInfo, Endpoint};
14
15use crate::AppServer;
16use crate::error::{Error, Result};
17use crate::settings::{AppSettings, Settings};
18use sapphire_workspace::AppContext;
19
20mod config;
21
22pub use config::{AppConfigCommand, AppScopeFlags};
23
24pub use sapphire_backend::protocol::{StatusReport, StatusRow};
25
26#[derive(Debug, clap::Subcommand)]
32pub enum FrameworkCommand {
33 Serve,
35 Status,
37 #[command(subcommand)]
39 Service(ServiceCommand),
40 Update(AppUpdateArgs),
44 #[command(subcommand)]
47 Workspace(WorkspaceCommand),
48 #[command(subcommand)]
50 Workgroup(WorkgroupCommand),
51 #[command(subcommand)]
53 Device(DeviceCommand),
54 #[command(subcommand)]
57 Embedding(sapphire_bridge_api::EmbeddingCommand),
58 #[command(subcommand)]
62 ExternalDevice(sapphire_bridge_api::ExternalDeviceCommand),
63 #[command(subcommand)]
66 Config(AppConfigCommand),
67 #[cfg(feature = "mcp")]
70 Mcp,
71}
72
73impl FrameworkCommand {
74 pub async fn dispatch<A, F>(
90 self,
91 ctx: &'static AppContext,
92 owner: A,
93 build: F,
94 version: &'static str,
95 ) -> Result<i32>
96 where
97 A: AppSettings + Clone,
98 F: Fn(&Settings) -> AppServer,
99 {
100 let app = ctx.app_name;
101 let server = |owner: A| -> Result<AppServer> {
105 Ok(build(&settings_or_defaults(ctx, Arc::new(owner))?))
106 };
107 match self {
108 FrameworkCommand::Serve => {
109 crate::serve_restarting(ctx, owner, build).await?;
110 Ok(0)
111 }
112 FrameworkCommand::Status => {
113 let endpoint = Endpoint::for_app(app)?;
114 run_status(&endpoint, app, version).await
115 }
116 FrameworkCommand::Service(command) => {
117 let spec = server(owner)?.service_spec();
118 command
119 .run(&spec, &Environment::detect(), &SystemManager)
120 .map_err(Error::from)
121 }
122 FrameworkCommand::Update(args) => {
123 let server = server(owner)?;
124 let own = match server.release_source() {
125 Some(source) => {
126 sapphire_framework_update::run(&args.update, source, app, version)
127 .await
128 .map_err(Error::from)
129 }
130 None => {
131 println!("{app} does not say where its releases are");
132 Ok(1)
133 }
134 };
135 let bridge = if args.no_bridge {
138 0
139 } else {
140 update_bridge(&args.update).await?
141 };
142 Ok(own?.max(bridge))
143 }
144 FrameworkCommand::Config(command) => config::config(ctx, owner, command, version).await,
145 FrameworkCommand::Workspace(command) => command.dispatch(app, version).await,
146 FrameworkCommand::Workgroup(command) => command.dispatch(app, version).await,
147 FrameworkCommand::Device(command) => command.dispatch(app, version).await,
148 FrameworkCommand::Embedding(command) => embedding(command, app, version).await,
149 FrameworkCommand::ExternalDevice(command) => {
150 external_device(command, app, version).await
151 }
152 #[cfg(feature = "mcp")]
153 FrameworkCommand::Mcp => {
154 server(owner)?.serve_mcp_stdio(version).await?;
155 Ok(0)
156 }
157 }
158 }
159}
160
161fn settings_or_defaults(ctx: &AppContext, owner: Arc<dyn AppSettings>) -> Result<Settings> {
167 match Settings::load(ctx, Arc::clone(&owner)) {
168 Ok(settings) => Ok(settings),
169 Err(err) => {
170 let file = Settings::device_file(ctx)
171 .map_or_else(|| "the settings".to_owned(), |f| f.display().to_string());
172 eprintln!("warning: could not read {file} ({err}); going on with the default settings");
173 Settings::defaults(ctx, owner)
174 }
175 }
176}
177
178#[derive(Clone, Debug, Default, clap::Args)]
180pub struct AppUpdateArgs {
181 #[command(flatten)]
183 pub update: sapphire_framework_update::UpdateArgs,
184 #[arg(long)]
186 pub no_bridge: bool,
187}
188
189const BRIDGE_BINARY: &str = "sapphire-bridge";
191
192const BRIDGE_RELEASES: &str = "https://github.com/sapphire-turtle/sapphire-framework/releases";
194
195fn find_on_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
197 let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
198 std::env::split_paths(path?)
199 .map(|dir| dir.join(&file))
200 .find(|candidate| candidate.is_file())
201}
202
203async fn update_bridge(args: &sapphire_framework_update::UpdateArgs) -> Result<i32> {
206 match find_on_path(BRIDGE_BINARY, std::env::var_os("PATH").as_deref()) {
207 Some(exe) => run_bridge_update(&exe, args).await,
208 None => {
209 println!("{BRIDGE_BINARY} is not on PATH; not updating it");
210 Ok(0)
211 }
212 }
213}
214
215async fn run_bridge_update(
221 exe: &std::path::Path,
222 args: &sapphire_framework_update::UpdateArgs,
223) -> Result<i32> {
224 let knows_update = tokio::process::Command::new(exe)
226 .args(["update", "--help"])
227 .stdout(std::process::Stdio::null())
228 .stderr(std::process::Stdio::null())
229 .status()
230 .await?
231 .success();
232 if !knows_update {
233 println!(
234 "{} cannot update itself; install the newest from {BRIDGE_RELEASES}",
235 exe.display()
236 );
237 return Ok(1);
238 }
239 let mut command = tokio::process::Command::new(exe);
240 command.arg("update");
241 if args.check {
242 command.arg("--check");
243 }
244 if args.yes {
245 command.arg("--yes");
246 }
247 let status = command.status().await?;
249 Ok(status.code().unwrap_or(1))
250}
251
252#[derive(Debug, clap::Subcommand)]
259pub enum WorkspaceCommand {
260 Init {
262 dir: Option<PathBuf>,
264 #[arg(long)]
266 sync: bool,
267 #[arg(long, value_name = "NAME|ID", requires = "sync")]
270 remote_workspace: Option<String>,
271 },
272 Select {
274 dir: Option<PathBuf>,
276 #[arg(long)]
279 sync: bool,
280 },
281 #[command(subcommand)]
283 Sync(WorkspaceSyncCommand),
284 Show,
286 Move {
288 dir: PathBuf,
290 },
291 Remove {
293 #[arg(long)]
295 delete: bool,
296 },
297}
298
299impl WorkspaceCommand {
300 pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
305 match self {
306 WorkspaceCommand::Init {
307 dir,
308 sync,
309 remote_workspace,
310 } => workspace_init(app, version, dir, sync, remote_workspace).await,
311 WorkspaceCommand::Select { dir, sync } => {
312 workspace_select(app, version, dir, sync).await
313 }
314 WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
315 WorkspaceCommand::Show => workspace_show(app, version).await,
316 WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
317 WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
318 }
319 }
320}
321
322#[derive(Debug, clap::Subcommand)]
324pub enum WorkspaceSyncCommand {
325 Enable,
327 Disable,
330 Status,
332}
333
334#[derive(Debug, clap::Subcommand)]
339pub enum WorkgroupCommand {
340 Create {
342 name: String,
344 #[arg(long)]
346 device_name: String,
347 },
348 List,
350 Join {
352 ticket: String,
354 #[arg(long)]
356 device_name: Option<String>,
357 },
358}
359
360impl WorkgroupCommand {
361 pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
363 match self {
364 WorkgroupCommand::Create { name, device_name } => {
365 let Some(client) = relayed_bridge(app, version).await? else {
366 return Ok(1);
367 };
368 let created = client
369 .workgroup_create(WorkgroupCreateParams { name, device_name })
370 .await?;
371 println!(
372 "created workgroup {} ({}); this device is {}",
373 created.name, created.workgroup_id, created.device_id
374 );
375 Ok(0)
376 }
377 WorkgroupCommand::List => {
378 let Some(client) = relayed_bridge(app, version).await? else {
379 return Ok(1);
380 };
381 match client.status().await?.workgroup {
382 Some(workgroup) => {
383 println!("{} ({})", workgroup.name, workgroup.workgroup_id);
384 Ok(0)
385 }
386 None => {
387 println!("this host has not joined a workgroup");
388 Ok(1)
389 }
390 }
391 }
392 WorkgroupCommand::Join {
393 ticket,
394 device_name,
395 } => {
396 let Some(client) = relayed_bridge(app, version).await? else {
397 return Ok(1);
398 };
399 let joined = client
400 .join(JoinParams {
401 ticket,
402 device_name,
403 })
404 .await?;
405 println!(
406 "joined workgroup {} ({}); this device is {}",
407 joined.workgroup_name, joined.workgroup_id, joined.device_id
408 );
409 Ok(0)
410 }
411 }
412 }
413}
414
415#[derive(Debug, clap::Subcommand)]
421pub enum DeviceCommand {
422 List,
424 Invite {
426 #[arg(long)]
428 name: String,
429 #[arg(long)]
431 ttl: Option<u64>,
432 #[arg(long)]
434 workgroup: Option<String>,
435 },
436 Retire {
438 selector: String,
440 },
441 Priority {
444 selector: String,
446 priority: Option<u8>,
448 },
449}
450
451impl DeviceCommand {
452 pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
454 match self {
455 DeviceCommand::List => {
456 let Some(client) = relayed_bridge(app, version).await? else {
457 return Ok(1);
458 };
459 let peers = client.peers().await?;
460 if peers.peers.is_empty() {
461 println!("no devices");
462 return Ok(0);
463 }
464 for peer in peers.peers {
465 println!(
466 "{} {} p{}{}{}",
467 peer.name,
468 peer.device_id,
469 peer.priority,
470 peer.availability
471 .map(|a| format!(" a{a}"))
472 .unwrap_or_default(),
473 if peer.connected { " (online)" } else { "" }
474 );
475 }
476 Ok(0)
477 }
478 DeviceCommand::Invite {
479 name,
480 ttl,
481 workgroup,
482 } => {
483 let Some(client) = relayed_bridge(app, version).await? else {
484 return Ok(1);
485 };
486 let invite = client
487 .invite(InviteParams {
488 name,
489 ttl,
490 workgroup,
491 })
492 .await?;
493 println!("{}", invite.ticket);
496 Ok(0)
497 }
498 DeviceCommand::Retire { selector } => {
499 let Some(client) = relayed_bridge(app, version).await? else {
500 return Ok(1);
501 };
502 let retired = client
503 .device_retire(DeviceRetireParams { selector })
504 .await?;
505 println!("retired device {} ({})", retired.name, retired.device_id);
506 Ok(0)
507 }
508 DeviceCommand::Priority { selector, priority } => {
509 let Some(client) = relayed_bridge(app, version).await? else {
510 return Ok(1);
511 };
512 match priority {
513 Some(priority) => {
514 let set = client
515 .device_priority_set(DevicePrioritySetParams { selector, priority })
516 .await?;
517 println!("{} ({}) priority {}", set.name, set.device_id, set.priority);
518 }
519 None => {
520 let peers = client.peers().await?;
521 match peers
522 .peers
523 .iter()
524 .find(|p| p.name == selector || p.device_id.to_string() == selector)
525 {
526 Some(p) => {
527 println!("{} ({}) priority {}", p.name, p.device_id, p.priority)
528 }
529 None => {
530 println!("no device {selector:?}");
531 return Ok(1);
532 }
533 }
534 }
535 }
536 Ok(0)
537 }
538 }
539 }
540}
541
542async fn relayed_bridge(app: &str, version: &str) -> Result<Option<BridgeClient>> {
549 let Some(client) = connect_app(app, version).await? else {
550 return Ok(None);
551 };
552 Ok(Some(BridgeClient::relayed(
553 Arc::new(client),
554 sapphire_ipc::runtime_dir()?,
555 )))
556}
557
558async fn embedding(
560 command: sapphire_bridge_api::EmbeddingCommand,
561 app: &str,
562 version: &str,
563) -> Result<i32> {
564 let Some(client) = relayed_bridge(app, version).await? else {
566 return Ok(1);
567 };
568 let request = command.request()?;
569 let report = client.embed_request(request).await?;
570 for line in sapphire_bridge_api::describe(&report) {
571 println!("{line}");
572 }
573 Ok(0)
574}
575
576async fn external_device(
578 command: sapphire_bridge_api::ExternalDeviceCommand,
579 app: &str,
580 version: &str,
581) -> Result<i32> {
582 let Some(client) = relayed_bridge(app, version).await? else {
583 return Ok(1);
584 };
585 let outcome = client
586 .external_device_request(command.request(Some(app)))
587 .await?;
588 for line in sapphire_bridge_api::describe_external_outcome(&outcome) {
589 println!("{line}");
590 }
591 Ok(0)
592}
593
594async fn workspace_init(
607 app: &'static str,
608 version: &'static str,
609 dir: Option<PathBuf>,
610 sync: bool,
611 remote_workspace: Option<String>,
612) -> Result<i32> {
613 let endpoint = Endpoint::for_app(app)?;
614 let client_info = ClientInfo {
615 kind: "cli".to_owned(),
616 version: version.to_owned(),
617 api: proto::API_VERSION,
618 app_api: None,
619 pid: std::process::id(),
620 };
621 let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
622 else {
623 println!("no {app} server is running");
624 return Ok(1);
625 };
626
627 let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
629 if let Some(selector) = remote_workspace {
630 let mapped: proto::SyncEnableResult = client
631 .call(
632 proto::SYNC_MAP,
633 proto::SyncMapParams {
634 workspace: selector.clone(),
635 dir: dir.clone(),
636 },
637 )
638 .await?;
639 println!(
640 "initialized {app} workspace in {} from {selector}",
641 dir.display()
642 );
643 println!(
644 "the {app} server now serves it, syncing as {}",
645 mapped.workspace_id
646 );
647 return Ok(0);
648 }
649 let result: proto::WorkspaceInitResult = client
650 .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
651 .await?;
652 if result.created {
653 println!("initialized {app} workspace in {}", result.root.display());
654 } else {
655 println!(
656 "{} already exists (workspace {})",
657 result.root.display(),
658 result.workspace_id
659 );
660 }
661 println!("the {app} server now serves {}", result.root.display());
662
663 if sync {
664 enable_sync(&client).await?;
665 }
666 Ok(0)
667}
668
669async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
675 let enabled: proto::SyncEnableResult = client
676 .call(proto::SYNC_ENABLE, serde_json::json!({}))
677 .await?;
678 let status: proto::SyncStatusResult = client
681 .call(proto::SYNC_STATUS, serde_json::json!({}))
682 .await
683 .unwrap_or(proto::SyncStatusResult {
684 enabled: true,
685 workspace_id: Some(enabled.workspace_id),
686 ..proto::SyncStatusResult::not_synced()
687 });
688 println!(
689 "syncing as {} ({} peer{})",
690 enabled.workspace_id,
691 status.peers,
692 if status.peers == 1 { "" } else { "s" }
693 );
694 Ok(())
695}
696
697async fn workspace_sync(
699 app: &'static str,
700 version: &'static str,
701 command: WorkspaceSyncCommand,
702) -> Result<i32> {
703 let Some(client) = connect_app(app, version).await? else {
704 return Ok(1);
705 };
706 match command {
707 WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
708 WorkspaceSyncCommand::Disable => {
709 let _: proto::Ack = client
710 .call(proto::SYNC_DISABLE, serde_json::json!({}))
711 .await?;
712 println!("sync is off for the {app} workspace on this host; it keeps its sync id");
713 }
714 WorkspaceSyncCommand::Status => {
715 let status: proto::SyncStatusResult = client
716 .call(proto::SYNC_STATUS, serde_json::json!({}))
717 .await?;
718 for line in describe_sync(&status) {
719 println!("{line}");
720 }
721 }
722 }
723 Ok(0)
724}
725
726fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
728 let mut lines = vec![format!(
729 "sync: {}",
730 if status.enabled { "on" } else { "off" }
731 )];
732 if let Some(id) = status.workspace_id {
733 lines.push(format!("workspace id: {id}"));
734 }
735 if status.enabled {
736 lines.push(format!(
737 "peers: {}{}",
738 status.peers,
739 if matches!(status.topology, proto::Topology::Star { .. }) {
740 " (star)"
741 } else {
742 ""
743 }
744 ));
745 lines.push(format!(
746 "bridge: {}",
747 if status.bridge_available {
748 "reachable"
749 } else {
750 "not reachable"
751 }
752 ));
753 }
754 if let Some(paused) = &status.paused {
755 lines.push(format!("paused: {paused}"));
756 }
757 if let Some(error) = &status.last_error {
758 lines.push(format!("last error: {error}"));
759 }
760 lines
761}
762
763pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
768 let current: proto::WorkspaceCurrentResult = client
769 .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
770 .await?;
771 let Some(ws) = current.workspace else {
772 writeln!(
773 out,
774 "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
775 )
776 .expect("writing to a String cannot fail");
777 return Ok(1);
778 };
779 writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
780 .expect("writing to a String cannot fail");
781 Ok(0)
782}
783
784fn describe_state(ws: &proto::CurrentWorkspace) -> String {
786 let state = if !ws.reachable {
787 "unreachable"
788 } else if ws.sync.enabled {
789 "synced"
790 } else {
791 "not synced"
792 };
793 let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
794 " (star)"
795 } else {
796 ""
797 };
798 let pending = match &ws.sync.embedding {
799 Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
800 _ => String::new(),
801 };
802 format!("{state}{star}{pending}")
803}
804
805async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
807 let client = try_connect_app(app, version).await?;
808 if client.is_none() {
809 println!("no {app} server is running");
810 }
811 Ok(client)
812}
813
814async fn try_connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
816 let endpoint = Endpoint::for_app(app)?;
817 let client_info = ClientInfo {
818 kind: "cli".to_owned(),
819 version: version.to_owned(),
820 api: proto::API_VERSION,
821 app_api: None,
822 pid: std::process::id(),
823 };
824 let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
825 Ok(client.map(|(c, _)| c))
826}
827
828async fn workspace_select(
830 app: &'static str,
831 version: &'static str,
832 dir: Option<PathBuf>,
833 sync: bool,
834) -> Result<i32> {
835 let Some(client) = connect_app(app, version).await? else {
836 return Ok(1);
837 };
838 let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
840 let ws: proto::CurrentWorkspace = client
841 .call(
842 proto::WORKSPACE_SELECT,
843 proto::WorkspaceSelectParams { dir },
844 )
845 .await?;
846 println!("{} {}", ws.root.display(), describe_state(&ws));
847 if sync && !ws.sync.enabled {
849 enable_sync(&client).await?;
850 }
851 Ok(0)
852}
853
854async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
856 let Some(client) = connect_app(app, version).await? else {
857 return Ok(1);
858 };
859 let dir = std::env::current_dir()?.join(dir);
861 let ws: proto::CurrentWorkspace = client
862 .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
863 .await?;
864 println!("{} {}", ws.root.display(), describe_state(&ws));
865 Ok(0)
866}
867
868async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
870 let Some(client) = connect_app(app, version).await? else {
871 return Ok(1);
872 };
873 let _: proto::Ack = client
874 .call(
875 proto::WORKSPACE_REMOVE,
876 proto::WorkspaceRemoveParams { delete },
877 )
878 .await?;
879 println!(
880 "{}",
881 if delete {
882 "removed and deleted"
883 } else {
884 "removed; the files stay"
885 }
886 );
887 Ok(0)
888}
889
890async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
896 let Some(client) = connect_app(app, version).await? else {
897 return Ok(1);
898 };
899 let mut out = String::new();
900 let code = render_workspace_show(Arc::new(client), app, &mut out).await?;
901 for line in out.lines() {
902 println!("{line}");
903 }
904 Ok(code)
905}
906
907#[doc(hidden)]
912pub async fn render_workspace_show(
913 client: Arc<sapphire_ipc::Client>,
914 app: &str,
915 out: &mut String,
916) -> Result<i32> {
917 let code = render_workspace(&client, out).await?;
918 let bridge = BridgeClient::relayed(client, sapphire_ipc::runtime_dir()?);
919 let workspaces = match bridge.workspaces().await {
920 Ok(workspaces) => workspaces,
921 Err(sapphire_ipc::Error::NotRunning(_)) => {
922 writeln!(out, "no sapphire-bridge is running")
923 .expect("writing to a String cannot fail");
924 return Ok(code);
925 }
926 Err(error) => return Err(error.into()),
927 };
928 let mine: Vec<_> = workspaces
929 .workspaces
930 .into_iter()
931 .filter(|w| w.app_name == app)
932 .collect();
933 if !mine.is_empty() {
934 writeln!(out).expect("writing to a String cannot fail");
935 writeln!(out, "in the workgroup:").expect("writing to a String cannot fail");
936 for workspace in mine {
937 writeln!(out, "{} {}", workspace.name, workspace.workspace_id)
938 .expect("writing to a String cannot fail");
939 }
940 }
941 Ok(code)
942}
943
944async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
953 let mut out = String::new();
954 let code = run_status_into(endpoint, app, version, &mut out).await?;
955 for line in out.lines() {
956 println!("{line}");
957 }
958 Ok(code)
959}
960
961async fn run_status_into(
964 endpoint: &Endpoint,
965 app: &str,
966 version: &str,
967 out: &mut String,
968) -> Result<i32> {
969 let client_info = ClientInfo {
970 kind: "cli".to_owned(),
971 version: version.to_owned(),
972 api: proto::API_VERSION,
973 app_api: None,
974 pid: std::process::id(),
975 };
976 let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
977 else {
978 writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
981 return Ok(1);
982 };
983 let report: StatusReport = client
984 .call(
985 sapphire_backend::protocol::SERVER_INFO,
986 serde_json::json!({}),
987 )
988 .await?;
989 writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
990 if let Some(version) = &report.version {
991 writeln!(out, "version: {version}").expect("writing to a String cannot fail");
992 }
993 if let Some(pid) = report.pid {
994 writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
995 }
996 if let Some(managed_by) = &report.managed_by {
997 writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
998 }
999 for row in &report.app {
1000 writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
1001 }
1002 let update: Option<proto::UpdateStatus> = client
1005 .call(proto::SERVER_UPDATE, serde_json::json!({}))
1006 .await
1007 .ok();
1008 for line in describe_update(app, version, report.version.as_deref(), update.as_ref()) {
1009 writeln!(out, "{line}").expect("writing to a String cannot fail");
1010 }
1011 Ok(0)
1012}
1013
1014fn describe_update(
1021 app: &str,
1022 installed: &str,
1023 running: Option<&str>,
1024 update: Option<&proto::UpdateStatus>,
1025) -> Vec<String> {
1026 let parse = |v: &str| semver::Version::parse(v).ok();
1027 let installed_v = parse(installed);
1028 let mut lines = Vec::new();
1029 if let Some(update) = update.filter(|u| u.enabled) {
1030 match (&update.latest, &update.last_error) {
1031 (Some(latest), _) => {
1032 let newer = match (parse(&latest.version), &installed_v) {
1033 (Some(latest), Some(installed)) => latest > *installed,
1034 _ => update.update_available,
1035 };
1036 if newer {
1037 lines.push(format!(
1038 "update: {} is available ({})",
1039 latest.version, latest.url
1040 ));
1041 } else {
1042 lines.push(format!(
1043 "update: up to date (latest release {})",
1044 latest.version
1045 ));
1046 }
1047 }
1048 (None, Some(error)) => lines.push(format!("update: could not check: {error}")),
1049 (None, None) => lines.push("update: not checked yet".to_owned()),
1050 }
1051 }
1052 if let (Some(running), Some(installed)) = (running.and_then(parse), installed_v)
1053 && installed > running
1054 {
1055 lines.push(format!(
1056 "restart: needed: {installed} is installed but {running} is running; restart the {app} service"
1057 ));
1058 }
1059 lines
1060}
1061#[cfg(test)]
1062mod tests {
1063 use super::*;
1064 use clap::Parser;
1065
1066 #[derive(Parser)]
1075 struct Probe {
1076 #[command(subcommand)]
1077 command: Command,
1078 }
1079
1080 #[derive(Debug, clap::Subcommand)]
1081 enum Command {
1082 Greet,
1084 #[command(flatten)]
1085 Framework(FrameworkCommand),
1086 }
1087
1088 #[test]
1089 fn app_and_framework_commands_parse_side_by_side() {
1090 let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
1091 assert!(matches!(probe.command, Command::Greet));
1092 let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
1093 assert!(matches!(
1094 probe.command,
1095 Command::Framework(FrameworkCommand::Serve)
1096 ));
1097 let probe = Probe::try_parse_from(["app", "status"]).unwrap();
1098 assert!(matches!(
1099 probe.command,
1100 Command::Framework(FrameworkCommand::Status)
1101 ));
1102 }
1103
1104 #[cfg(feature = "mcp")]
1105 #[test]
1106 fn the_mcp_command_parses_beside_the_apps() {
1107 let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
1108 assert!(matches!(
1109 probe.command,
1110 Command::Framework(FrameworkCommand::Mcp)
1111 ));
1112 }
1113
1114 #[test]
1115 fn the_update_command_parses_with_and_without_the_bridge() {
1116 let probe = Probe::try_parse_from(["app", "update", "--check", "-y"]).unwrap();
1117 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
1118 panic!("not update");
1119 };
1120 assert!(args.update.check && args.update.yes && !args.no_bridge);
1121 let probe = Probe::try_parse_from(["app", "update", "--no-bridge"]).unwrap();
1122 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
1123 panic!("not update");
1124 };
1125 assert!(args.no_bridge);
1126 }
1127
1128 #[test]
1129 fn the_bridge_is_found_in_the_first_directory_of_path_that_has_it() {
1130 let tmp = tempfile::tempdir().unwrap();
1131 let (empty, first, second) = (
1132 tmp.path().join("empty"),
1133 tmp.path().join("first"),
1134 tmp.path().join("second"),
1135 );
1136 let file = format!("sapphire-bridge{}", std::env::consts::EXE_SUFFIX);
1137 for dir in [&empty, &first, &second] {
1138 std::fs::create_dir(dir).unwrap();
1139 }
1140 std::fs::write(first.join(&file), b"").unwrap();
1141 std::fs::write(second.join(&file), b"").unwrap();
1142 let path = std::env::join_paths([&empty, &first, &second]).unwrap();
1143 assert_eq!(
1144 find_on_path("sapphire-bridge", Some(&path)),
1145 Some(first.join(&file))
1146 );
1147 let path = std::env::join_paths([&empty]).unwrap();
1148 assert_eq!(find_on_path("sapphire-bridge", Some(&path)), None);
1149 assert_eq!(find_on_path("sapphire-bridge", None), None);
1150 }
1151
1152 #[cfg(unix)]
1154 fn script(dir: &std::path::Path, name: &str, body: &str) -> PathBuf {
1155 use std::os::unix::fs::PermissionsExt;
1156 let path = dir.join(name);
1157 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
1158 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1159 path
1160 }
1161
1162 #[cfg(unix)]
1163 #[tokio::test]
1164 async fn the_bridge_runs_its_own_update_with_the_apps_flags() {
1165 let tmp = tempfile::tempdir().unwrap();
1166 let log = tmp.path().join("args");
1167 let exe = script(
1170 tmp.path(),
1171 "bridge",
1172 &format!(
1173 r#"case "$*" in *--help*) exit 0;; esac; echo "$@" > {}; exit 1"#,
1174 log.display()
1175 ),
1176 );
1177 let args = sapphire_framework_update::UpdateArgs {
1178 check: true,
1179 yes: true,
1180 };
1181 assert_eq!(run_bridge_update(&exe, &args).await.unwrap(), 1);
1182 assert_eq!(
1183 std::fs::read_to_string(&log).unwrap().trim(),
1184 "update --check --yes"
1185 );
1186 }
1187
1188 #[cfg(unix)]
1189 #[tokio::test]
1190 async fn a_bridge_without_update_is_not_run() {
1191 let tmp = tempfile::tempdir().unwrap();
1192 let runs = tmp.path().join("runs");
1193 let exe = script(
1195 tmp.path(),
1196 "bridge",
1197 &format!(r#"echo "$*" >> {}; exit 2"#, runs.display()),
1198 );
1199 let code = run_bridge_update(&exe, &Default::default()).await.unwrap();
1200 assert_eq!(code, 1);
1201 assert_eq!(
1202 std::fs::read_to_string(&runs).unwrap(),
1203 "update --help\n",
1204 "only the probe ran"
1205 );
1206 }
1207
1208 #[test]
1209 fn the_service_subcommands_parse() {
1210 for args in [
1211 vec!["app", "service", "install"],
1212 vec!["app", "service", "uninstall"],
1213 vec!["app", "service", "status"],
1214 ] {
1215 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1216 }
1217 }
1218
1219 #[test]
1220 fn the_workspace_and_bridge_commands_parse() {
1221 for args in [
1222 vec!["app", "workspace", "init"],
1223 vec!["app", "workspace", "init", "papers"],
1224 vec!["app", "workspace", "init", "--sync"],
1225 vec!["app", "workspace", "show"],
1226 vec!["app", "workspace", "select", "papers"],
1227 vec!["app", "workspace", "select", "--sync"],
1228 vec!["app", "workspace", "select", "papers", "--sync"],
1229 vec!["app", "workspace", "sync", "enable"],
1230 vec!["app", "workspace", "sync", "disable"],
1231 vec!["app", "workspace", "sync", "status"],
1232 vec![
1233 "app",
1234 "workspace",
1235 "init",
1236 "--sync",
1237 "--remote-workspace=Ledger",
1238 ],
1239 vec![
1240 "app",
1241 "workspace",
1242 "init",
1243 "papers",
1244 "--sync",
1245 "--remote-workspace",
1246 "Ledger",
1247 ],
1248 vec!["app", "workspace", "move", "../papers"],
1249 vec!["app", "workspace", "remove"],
1250 vec!["app", "workspace", "remove", "--delete"],
1251 vec![
1252 "app",
1253 "workgroup",
1254 "create",
1255 "--device-name",
1256 "laptop",
1257 "home",
1258 ],
1259 vec!["app", "workgroup", "list"],
1260 vec![
1261 "app",
1262 "workgroup",
1263 "join",
1264 "--device-name",
1265 "laptop",
1266 "TICKET",
1267 ],
1268 vec!["app", "device", "list"],
1269 vec!["app", "device", "invite", "--name", "phone"],
1270 vec!["app", "device", "retire", "phone"],
1271 ] {
1272 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1273 }
1274 }
1275
1276 #[test]
1277 fn a_remote_workspace_needs_sync() {
1278 let args = ["app", "workspace", "init", "--remote-workspace=Ledger"];
1279 assert!(Probe::try_parse_from(args).is_err());
1280 }
1281
1282 #[test]
1283 fn bare_invocation_prints_the_help() {
1284 #[derive(Parser)]
1288 #[command(arg_required_else_help = true)]
1289 struct Bare {
1290 #[command(subcommand)]
1291 command: Command,
1292 }
1293 let err = Bare::try_parse_from(["app"]).err().unwrap();
1294 assert_eq!(
1295 err.kind(),
1296 clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
1297 );
1298 }
1299}
1300
1301#[cfg(test)]
1302mod status_tests {
1303 use super::*;
1304 use sapphire_workspace::AppContext;
1305
1306 static CTX: AppContext = AppContext::new("sapphire-statustest");
1307
1308 async fn wait_until_listening(endpoint: &Endpoint) {
1314 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
1315 while !sapphire_ipc::probe(endpoint).await.unwrap() {
1316 assert!(
1317 tokio::time::Instant::now() < deadline,
1318 "the server never started listening"
1319 );
1320 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1321 }
1322 }
1323
1324 #[tokio::test]
1325 async fn status_reports_no_server_when_none_is_running() {
1326 let tmp = tempfile::tempdir().unwrap();
1327 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1328 let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
1329 assert_eq!(code, 1, "no server is a non-zero exit");
1330 }
1331
1332 fn update(latest: Option<&str>, error: Option<&str>) -> proto::UpdateStatus {
1333 proto::UpdateStatus {
1334 enabled: true,
1335 latest: latest.map(|version| proto::ReleaseInfo {
1336 version: version.to_owned(),
1337 url: format!("https://example.invalid/v{version}"),
1338 }),
1339 update_available: false,
1340 last_error: error.map(str::to_owned),
1341 }
1342 }
1343
1344 #[test]
1345 fn status_names_a_newer_release_and_nothing_when_up_to_date() {
1346 let lines = describe_update(
1347 "app",
1348 "0.19.0",
1349 Some("0.19.0"),
1350 Some(&update(Some("0.20.0"), None)),
1351 );
1352 assert_eq!(
1353 lines,
1354 vec!["update: 0.20.0 is available (https://example.invalid/v0.20.0)"]
1355 );
1356 let lines = describe_update(
1357 "app",
1358 "0.19.0",
1359 Some("0.19.0"),
1360 Some(&update(Some("0.19.0"), None)),
1361 );
1362 assert_eq!(lines, vec!["update: up to date (latest release 0.19.0)"]);
1363 }
1364
1365 #[test]
1366 fn status_asks_for_a_restart_when_the_installed_server_is_newer_than_the_running_one() {
1367 let lines = describe_update(
1370 "app",
1371 "0.20.0",
1372 Some("0.19.0"),
1373 Some(&update(Some("0.20.0"), None)),
1374 );
1375 assert_eq!(
1376 lines,
1377 vec![
1378 "update: up to date (latest release 0.20.0)",
1379 "restart: needed: 0.20.0 is installed but 0.19.0 is running; restart the app service",
1380 ]
1381 );
1382 let lines = describe_update("app", "0.20.0", Some("0.19.0"), None);
1384 assert_eq!(lines.len(), 1);
1385 assert!(lines[0].starts_with("restart: needed"));
1386 }
1387
1388 #[test]
1389 fn status_says_why_a_check_failed_and_nothing_when_checks_are_off() {
1390 let lines = describe_update(
1391 "app",
1392 "0.19.0",
1393 Some("0.19.0"),
1394 Some(&update(None, Some("offline"))),
1395 );
1396 assert_eq!(lines, vec!["update: could not check: offline"]);
1397 let off = proto::UpdateStatus::default();
1398 assert!(describe_update("app", "0.19.0", Some("0.19.0"), Some(&off)).is_empty());
1399 }
1400
1401 #[tokio::test(flavor = "multi_thread")]
1402 async fn status_shows_a_newer_release_the_server_found() {
1403 let tmp = tempfile::tempdir().unwrap();
1404 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1405 let api = crate::update::stub::one_response(
1406 "200 OK",
1407 r#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid/v0.20.0"}]"#,
1408 )
1409 .await;
1410 let server = AppServer::new(&CTX, "0.19.0")
1411 .endpoint(endpoint.clone())
1412 .selection_file(tmp.path().join("workspace.toml"))
1413 .releases(crate::ReleaseSource::github("o", "r").api_base(api));
1414 let handle = tokio::spawn(async move { server.run().await });
1415 wait_until_listening(&endpoint).await;
1416
1417 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
1419 let out = loop {
1420 let mut out = String::new();
1421 run_status_into(&endpoint, CTX.app_name, "0.19.0", &mut out)
1422 .await
1423 .unwrap();
1424 if !out.contains("not checked yet") {
1425 break out;
1426 }
1427 assert!(
1428 tokio::time::Instant::now() < deadline,
1429 "never checked: {out}"
1430 );
1431 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1432 };
1433 assert!(
1434 out.contains("update: 0.20.0 is available (https://example.invalid/v0.20.0)"),
1435 "output was: {out}"
1436 );
1437 assert!(!out.contains("restart:"), "output was: {out}");
1438
1439 let (client, _) = sapphire_ipc::connect_or_absent(
1440 &endpoint,
1441 CTX.app_name,
1442 sapphire_ipc::ClientInfo {
1443 kind: "test".into(),
1444 version: "0.19.0".into(),
1445 api: sapphire_backend::protocol::API_VERSION,
1446 app_api: None,
1447 pid: std::process::id(),
1448 },
1449 )
1450 .await
1451 .unwrap()
1452 .expect("the server is listening");
1453 let _: serde_json::Value = client
1454 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1455 .await
1456 .unwrap();
1457 handle.await.unwrap().unwrap();
1458 }
1459
1460 #[tokio::test(flavor = "multi_thread")]
1461 async fn status_shows_the_extension_rows_of_a_running_server() {
1462 let tmp = tempfile::tempdir().unwrap();
1463 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1464 let server = AppServer::new(&CTX, "0.0.0")
1465 .endpoint(endpoint.clone())
1466 .selection_file(tmp.path().join("workspace.toml"))
1468 .status_rows(std::sync::Arc::new(|| {
1469 vec![StatusRow {
1470 name: "sync".into(),
1471 value: "on".into(),
1472 }]
1473 }));
1474 let handle = tokio::spawn(async move { server.run().await });
1475 wait_until_listening(&endpoint).await;
1476
1477 let mut out = String::new();
1480 let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
1481 .await
1482 .unwrap();
1483 assert_eq!(code, 0);
1484 assert!(out.contains("running: true"), "output was: {out}");
1485 assert!(out.contains("sync: on"), "output was: {out}");
1486
1487 let (client, _) = sapphire_ipc::connect_or_absent(
1488 &endpoint,
1489 CTX.app_name,
1490 sapphire_ipc::ClientInfo {
1491 kind: "test".into(),
1492 version: "0.0.0".into(),
1493 api: sapphire_backend::protocol::API_VERSION,
1494 app_api: None,
1495 pid: std::process::id(),
1496 },
1497 )
1498 .await
1499 .unwrap()
1500 .expect("the server is listening");
1501 let _: serde_json::Value = client
1502 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1503 .await
1504 .unwrap();
1505 handle.await.unwrap().unwrap();
1506 }
1507}
1508
1509#[cfg(test)]
1510mod service_spec_tests {
1511 use super::*;
1512 use sapphire_workspace::AppContext;
1513
1514 static CTX: AppContext = AppContext::new("sapphire-servicetest");
1515
1516 #[test]
1517 fn the_generated_spec_runs_the_server_not_the_cli() {
1518 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1522 assert_eq!(spec.args, vec!["serve".to_owned()]);
1523 }
1524
1525 #[test]
1526 fn the_generated_spec_names_this_application() {
1527 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1528 assert_eq!(spec.app_name, CTX.app_name);
1529 }
1530
1531 #[test]
1532 fn the_generated_spec_describes_the_server() {
1533 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1534 assert!(
1535 spec.description.contains(CTX.app_name),
1536 "the unit's description should name the application: {:?}",
1537 spec.description
1538 );
1539 assert!(spec.description.contains("0.0.0"));
1540 }
1541}