1use std::process::ExitCode;
4
5use subspace_product::{
6 BuildInfo, Channel, MCP_COMMAND, ProductContext, ProductDescriptor, UPGRADE_COMMAND,
7 product_metadata, validate_product,
8};
9
10use crate::{BoardRegistration, DesktopOptions, prepare_context, run_desktop};
11
12#[derive(Debug, PartialEq, Eq)]
13enum StartupRoute {
14 Desktop,
15 Metadata,
16 About,
17 Version,
18 Mcp,
19 Upgrade,
20 Command,
21}
22
23pub struct ProductBuild {
25 pub account: Option<crate::AccountRegistration>,
29 pub descriptor: ProductDescriptor,
30 pub display_name_prefix: Option<&'static str>,
32 pub version: &'static str,
33 pub build: BuildInfo,
35 pub search_reranker: Option<crate::RerankerFactory>,
36 pub default_theme_override: Option<&'static str>,
37 pub configured_boards: Option<crate::ConfiguredBoards>,
40 pub settings_extensions: &'static [crate::SettingsExtension],
41 pub dock_panel: Option<subspace_dashboard::dock_panel::DockPanelRegistration>,
44 pub github_oauth: Option<subspace_github_auth::OAuthClient>,
48 pub fonts: &'static [crate::BundledFont],
53 #[cfg(feature = "report-issue")]
56 pub report_issue_repository: Option<&'static str>,
57}
58
59pub fn reads_configuration(descriptor: &ProductDescriptor, args: &[String]) -> bool {
65 reads_configuration_for(args, descriptor.update.is_some())
66}
67
68fn reads_configuration_for(args: &[String], updates: bool) -> bool {
69 !matches!(
70 route(args, updates),
71 StartupRoute::Metadata
72 | StartupRoute::About
73 | StartupRoute::Version
74 | StartupRoute::Upgrade
75 )
76}
77
78fn route(args: &[String], updates: bool) -> StartupRoute {
82 match args {
83 [] => StartupRoute::Desktop,
84 [arg] if arg == "__product_metadata" => StartupRoute::Metadata,
85 [arg] if arg == "about" || arg == "--about" => StartupRoute::About,
86 [arg] if arg == "--version" => StartupRoute::Version,
87 [first, ..] if first == MCP_COMMAND => StartupRoute::Mcp,
88 [first, ..] if updates && first == UPGRADE_COMMAND => StartupRoute::Upgrade,
89 _ => StartupRoute::Command,
90 }
91}
92
93pub fn launch(
96 build: ProductBuild,
97 boards: Vec<BoardRegistration>,
98 artwork: &'static [(&'static str, &'static [u8])],
99 command: fn(
100 &ProductContext,
101 &[subspace_mcp::Board],
102 &subspace_agent_tools::ToolEnvironment,
103 &[String],
104 ) -> ExitCode,
105) -> ExitCode {
106 crate::startup_path::apply(&build.descriptor);
107 let mut descriptor = build.descriptor;
108 let version = build.version;
109 let args = std::env::args().skip(1).collect::<Vec<_>>();
110 if let Err(error) = descriptor.apply_default_theme_override(build.default_theme_override) {
111 return finish(Err(error.to_string()));
112 }
113 subspace_update::cleanup_previous(&descriptor.binary_name);
114 let updates = descriptor.update.is_some();
115 warn_prerelease(&descriptor, version, &args, &route(&args, updates));
116 if route(&args, updates) == StartupRoute::Metadata {
117 return finish(print_metadata(&descriptor, version));
118 }
119 if let Some(text) = build_text(&route(&args, updates), &descriptor, version, &build.build) {
120 println!("{text}");
121 return ExitCode::SUCCESS;
122 }
123 if route(&args, updates) == StartupRoute::Upgrade {
124 return upgrade(&descriptor, version, &args);
125 }
126 let context = match prepare_context(descriptor, version) {
127 Ok(context) => ProductContext {
128 build: build.build,
129 ..context
130 },
131 Err(error) => return finish(Err(error)),
132 };
133 match route(&args, updates) {
134 StartupRoute::Desktop => finish(run_desktop(
135 context,
136 boards,
137 build.configured_boards,
138 artwork,
139 DesktopOptions {
140 account: build.account,
141 display_name_prefix: build.display_name_prefix,
142 reranker: build.search_reranker,
143 extensions: build.settings_extensions,
144 dock_panel: build.dock_panel,
145 github_oauth: build.github_oauth,
146 fonts: build.fonts,
147 #[cfg(feature = "report-issue")]
148 report_issue_repository: build.report_issue_repository,
149 },
150 )),
151 _ => {
152 let sign_in = (boards.as_slice(), build.github_oauth.is_some());
153 headless(&context, sign_in, &args, build.search_reranker, command)
154 }
155 }
156}
157
158fn build_text(
160 route: &StartupRoute,
161 descriptor: &ProductDescriptor,
162 version: &str,
163 build: &BuildInfo,
164) -> Option<String> {
165 match route {
166 StartupRoute::About => Some(crate::build_metadata::about_text(
167 descriptor, version, build,
168 )),
169 StartupRoute::Version => Some(crate::build_metadata::version_text(
170 descriptor, version, build,
171 )),
172 _ => None,
173 }
174}
175
176const NO_PRERELEASE_WARNING: &str = "SUBSPACE_NO_PRERELEASE_WARNING";
178
179fn warn_prerelease(
181 descriptor: &ProductDescriptor,
182 version: &str,
183 args: &[String],
184 route: &StartupRoute,
185) {
186 let suppressed = std::env::var(NO_PRERELEASE_WARNING).is_ok_and(|value| value == "1");
187 if warns(Channel::current(), route, args, suppressed) {
188 eprintln!("{}", warning_line(&descriptor.display_name, version));
189 }
190}
191
192fn warns(channel: Channel, route: &StartupRoute, args: &[String], suppressed: bool) -> bool {
196 let machine_output = args
197 .iter()
198 .any(|arg| arg == "--json" || arg.starts_with("--json="));
199 let cli = !matches!(
200 route,
201 StartupRoute::Desktop | StartupRoute::Metadata | StartupRoute::Version
202 );
203 channel.is_prerelease() && cli && !machine_output && !suppressed
204}
205
206fn warning_line(display_name: &str, version: &str) -> String {
207 format!("warning: {display_name} {version} is a pre-release build")
208}
209
210fn upgrade(descriptor: &ProductDescriptor, version: &str, args: &[String]) -> ExitCode {
213 match validate_product(descriptor) {
214 Ok(product) => subspace_update::run_cli(&product, version, args),
215 Err(error) => finish(Err(error.to_string())),
216 }
217}
218
219fn headless(
224 context: &ProductContext,
225 (boards, sign_in): (&[BoardRegistration], bool),
226 args: &[String],
227 reranker: Option<crate::RerankerFactory>,
228 command: fn(
229 &ProductContext,
230 &[subspace_mcp::Board],
231 &subspace_agent_tools::ToolEnvironment,
232 &[String],
233 ) -> ExitCode,
234) -> ExitCode {
235 let files = crate::product::ProductFiles::for_context(context);
236 let (mut environment, notices) = crate::tool_environment(
237 &files.config,
238 boards,
239 subspace_agent_tools::ToolHost::Headless,
240 sign_in,
241 );
242 let log_notice = crate::logging::start(&files, context);
243 for notice in notices.into_iter().chain(log_notice) {
244 eprintln!("{notice}");
245 }
246 let selected = match crate::registry::selected_registrations(
247 &context.product,
248 boards,
249 &environment.config,
250 ) {
251 Ok(selected) => selected,
252 Err(error) => return finish(Err(error)),
253 };
254 if let Err(error) =
255 crate::search_runtime::initialize(&mut environment, context, &selected, &files, reranker)
256 {
257 eprintln!("Full-text search unavailable: {error}");
258 }
259 let boards = crate::registry::mcp_boards(&selected);
260 if args.first().is_some_and(|arg| arg == "mcp") {
261 subspace_mcp::run(
262 context,
263 &boards,
264 &environment,
265 &args[1..],
266 &environment.config.mcp,
267 )
268 } else {
269 command(context, &boards, &environment, args)
270 }
271}
272
273fn print_metadata(descriptor: &ProductDescriptor, version: &str) -> Result<(), String> {
274 let metadata = product_metadata(descriptor, version).map_err(|error| error.to_string())?;
275 println!("{metadata}");
276 Ok(())
277}
278
279fn finish(result: Result<(), String>) -> ExitCode {
280 match result {
281 Ok(()) => ExitCode::SUCCESS,
282 Err(error) => {
283 eprintln!("{error}");
284 ExitCode::FAILURE
285 }
286 }
287}
288
289#[cfg(test)]
290mod tests {
291 use subspace_product::Channel;
292
293 use super::{StartupRoute, route, warning_line, warns};
294
295 fn words(values: &[&str]) -> Vec<String> {
296 values.iter().map(|value| (*value).to_owned()).collect()
297 }
298
299 fn nightly_warns(args: &[&str], suppressed: bool) -> bool {
300 let args = words(args);
301 warns(Channel::Nightly, &route(&args, true), &args, suppressed)
302 }
303
304 #[test]
305 fn a_pre_release_cli_command_warns_once_with_its_name_and_version() {
306 assert_eq!(
307 warning_line("Subspace (Nightly)", "1.10.2-nightly.202611010200.ga43a333"),
308 "warning: Subspace (Nightly) 1.10.2-nightly.202611010200.ga43a333 is a pre-release build"
309 );
310 for args in [
311 &["about"][..],
312 &["upgrade", "--check"],
313 &["mcp"],
314 &["github", "read"],
315 ] {
316 assert!(nightly_warns(args, false), "{args:?}");
317 }
318 }
319
320 #[test]
321 fn machine_output_the_desktop_suppression_and_stable_never_warn() {
322 for args in [
323 &[][..],
324 &["--version"],
325 &["__product_metadata"],
326 &["github", "read", "--json"],
327 &["github", "read", "--json=true"],
328 ] {
329 assert!(!nightly_warns(args, false), "{args:?}");
330 }
331 assert!(!nightly_warns(&["about"], true));
332 let about = words(&["about"]);
333 assert!(!warns(Channel::Stable, &route(&about, true), &about, false));
334 }
335
336 #[test]
337 fn only_no_arguments_choose_desktop_initialization() {
338 assert_eq!(route(&[], true), StartupRoute::Desktop);
339 for args in [["--help"], ["--version"], ["tui"], ["unknown"]] {
340 let expected = if args == ["--version"] {
341 StartupRoute::Version
342 } else {
343 StartupRoute::Command
344 };
345 assert_eq!(route(&args.map(str::to_owned), true), expected);
346 }
347 assert_eq!(
348 route(&["__product_metadata".into()], true),
349 StartupRoute::Metadata
350 );
351 assert_eq!(route(&["about".into()], true), StartupRoute::About);
352 assert_eq!(route(&["--about".into()], true), StartupRoute::About);
353 }
354
355 #[test]
356 fn mcp_is_routed_before_the_board_commands() {
357 assert_eq!(route(&["mcp".into()], true), StartupRoute::Mcp);
358 assert_eq!(
359 route(&["mcp".into(), "--http".into()], true),
360 StartupRoute::Mcp
361 );
362 assert_eq!(
363 route(&["github".into(), "mcp".into()], true),
364 StartupRoute::Command
365 );
366 }
367
368 #[test]
369 fn upgrade_is_routed_before_any_configuration_when_the_app_has_updates() {
370 for args in [
371 vec!["upgrade".to_owned()],
372 vec!["upgrade".to_owned(), "--check".to_owned()],
373 vec!["upgrade".to_owned(), "--version".to_owned(), "1.2.0".into()],
374 ] {
375 assert_eq!(route(&args, true), StartupRoute::Upgrade);
376 }
377 assert_eq!(
378 route(&["github".into(), "upgrade".into()], true),
379 StartupRoute::Command
380 );
381 }
382
383 #[test]
384 fn only_desktop_mcp_and_commands_read_the_configuration() {
385 let updating = |args: &[&str]| super::reads_configuration_for(&words(args), true);
386 for args in [
387 &["upgrade"][..],
388 &["--version"],
389 &["about"],
390 &["__product_metadata"],
391 ] {
392 assert!(!updating(args), "{args:?}");
393 }
394 for args in [&[][..], &["mcp"], &["issues", "list"]] {
395 assert!(updating(args), "{args:?}");
396 }
397 assert!(super::reads_configuration_for(&words(&["upgrade"]), false));
398 }
399
400 #[test]
401 fn upgrade_falls_through_without_an_update_source() {
402 assert_eq!(route(&["upgrade".into()], false), StartupRoute::Command);
403 assert_eq!(
404 route(&["upgrade".into(), "--check".into()], false),
405 StartupRoute::Command
406 );
407 assert_eq!(route(&["mcp".into()], false), StartupRoute::Mcp);
408 }
409}