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