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