Skip to main content

subspace_shell/
startup.rs

1//! One product entrypoint. Headless routes run before desktop initialization.
2
3use std::process::ExitCode;
4
5use subspace_product::{
6    BuildInfo, Channel, DataNameError, HostCommand, ProductContext, ProductDescriptor,
7    host_command, product_metadata, validate_product,
8};
9
10use crate::{BoardRegistration, DesktopOptions, prepare_context, run_desktop};
11
12mod headless;
13
14use headless::headless;
15
16#[derive(Debug, PartialEq, Eq)]
17enum StartupRoute {
18    Desktop,
19    Metadata,
20    About,
21    Version,
22    Mcp,
23    Upgrade,
24    Command,
25}
26
27/// Compile-time identity supplied by a thin product binary.
28pub struct ProductBuild {
29    /// The app's native account: its identity provider (Entra, WorkOS or
30    /// its own) and the trusted token consumer it installs before Spaces
31    /// start. `None` shows no Account settings page.
32    pub account: Option<crate::AccountRegistration>,
33    pub descriptor: ProductDescriptor,
34    /// Runs after startup `PATH` setup, before configuration, theme validation
35    /// or GPUI. Arguments exclude the binary name. `Some(code)` exits;
36    /// `None` continues normal startup. No capability gate applies.
37    pub pre_startup: Option<fn(&[String]) -> Option<ExitCode>>,
38    /// Optional prefix for desktop window titles, menus and About.
39    pub display_name_prefix: Option<&'static str>,
40    pub version: &'static str,
41    /// How this binary was built, stamped by the product's build script.
42    pub build: BuildInfo,
43    pub search_reranker: Option<crate::RerankerFactory>,
44    pub default_theme_override: Option<&'static str>,
45    /// Boards the desktop app adds from its config file. Headless commands
46    /// do not use them.
47    pub configured_boards: Option<crate::ConfiguredBoards>,
48    pub settings_extensions: &'static [crate::SettingsExtension],
49    /// The panel the shell docks beside every Space, such as the terminal.
50    /// `None` shows no terminal button, action, menu item or command.
51    pub dock_panel: Option<subspace_dashboard::dock_panel::DockPanelRegistration>,
52    /// The app's GitHub OAuth App, for Sign in with GitHub. The Framework has
53    /// none: `None` offers no Sign in with GitHub anywhere, and tokens come
54    /// from the environment, the config file and the `gh` CLI as before.
55    pub github_oauth: Option<subspace_github_auth::OAuthClient>,
56    /// Font files the app embeds, registered with the text system before the
57    /// theme is applied. A theme or Settings that names one of their families
58    /// gets it on every platform; automatic choices still use the platform's
59    /// fonts. `&[]` embeds none.
60    pub fonts: &'static [crate::BundledFont],
61    /// Theme documents the product embeds beside the Framework's catalogue,
62    /// as `(id, json)`. List an id in the descriptor's `themes`, and name one
63    /// of its variants as `default_theme`, to use it. An id must not repeat a
64    /// Framework theme id. `&[]` adds none.
65    pub product_themes: crate::ProductThemes,
66    /// Whether a navigator starts with the Space's title in the accent
67    /// colour, for people who have not chosen in Settings › Layout. A saved
68    /// choice always wins. [`ProductBuild::new`] sets `true`.
69    pub navigator_title: bool,
70    /// The GitHub repository (`owner/name`) Report issue files into. `None`
71    /// or blank hides Report issue; a malformed one hides it with a notice.
72    #[cfg(feature = "report-issue")]
73    pub report_issue_repository: Option<&'static str>,
74}
75
76/// Whether `args` start a route that reads the app's configuration. The
77/// product metadata, About, `--version` and `upgrade` read none, so an app
78/// that checks its own settings before [`launch`] skips those checks for
79/// them, and a broken setting never blocks an upgrade.
80// qual:api - a product calls it before its own start-up checks.
81pub fn reads_configuration(descriptor: &ProductDescriptor, args: &[String]) -> bool {
82    reads_configuration_for(args, descriptor.update.is_some())
83}
84
85fn reads_configuration_for(args: &[String], updates: bool) -> bool {
86    !matches!(
87        route(args, updates),
88        StartupRoute::Metadata
89            | StartupRoute::About
90            | StartupRoute::Version
91            | StartupRoute::Upgrade
92    )
93}
94
95impl ProductBuild {
96    /// Build a product with no optional host integrations or startup hook.
97    pub fn new(descriptor: ProductDescriptor, version: &'static str, build: BuildInfo) -> Self {
98        Self {
99            descriptor,
100            version,
101            build,
102            pre_startup: None,
103            account: None,
104            display_name_prefix: None,
105            search_reranker: None,
106            default_theme_override: None,
107            configured_boards: None,
108            settings_extensions: &[],
109            dock_panel: None,
110            github_oauth: None,
111            fonts: &[],
112            product_themes: &[],
113            navigator_title: true,
114            #[cfg(feature = "report-issue")]
115            report_issue_repository: None,
116        }
117    }
118}
119
120type CommandRunner = fn(
121    &ProductContext,
122    &[subspace_mcp::Board],
123    &subspace_agent_tools::ToolEnvironment,
124    &[String],
125) -> ExitCode;
126
127/// `updates` is whether this app has an update source. Without one,
128/// `upgrade` is not a Framework command and falls through to the normal
129/// command path, which reports it as unknown.
130fn route(args: &[String], updates: bool) -> StartupRoute {
131    startup_route(args.is_empty(), host_command(args, updates))
132}
133
134fn startup_route(empty: bool, host: Option<HostCommand>) -> StartupRoute {
135    match (empty, host) {
136        (true, _) => StartupRoute::Desktop,
137        (_, Some(HostCommand::Metadata)) => StartupRoute::Metadata,
138        (_, Some(HostCommand::About)) => StartupRoute::About,
139        (_, Some(HostCommand::Version)) => StartupRoute::Version,
140        (_, Some(HostCommand::Mcp)) => StartupRoute::Mcp,
141        (_, Some(HostCommand::Upgrade)) => StartupRoute::Upgrade,
142        (false, None) => StartupRoute::Command,
143    }
144}
145
146/// Called by thin binaries with only their selected board providers. Every
147/// mode first names the data directory after the binary, unless the app
148/// called [`subspace_product::configure_data_name`] first, then gets the
149/// user's `PATH`; nothing before that starts a thread. It fails when
150/// something read a data path under another name before it.
151pub fn launch(
152    build: ProductBuild,
153    boards: Vec<BoardRegistration>,
154    artwork: &'static [(&'static str, &'static [u8])],
155    command: CommandRunner,
156) -> ExitCode {
157    if let Err(error) = name_data_directory(build.descriptor.binary_name.as_str()) {
158        return finish(Err(error));
159    }
160    crate::startup_path::apply();
161    let args = std::env::args().skip(1).collect::<Vec<_>>();
162    launch_after_path(build, boards, artwork, command, &args)
163}
164
165fn launch_after_path(
166    build: ProductBuild,
167    boards: Vec<BoardRegistration>,
168    artwork: &'static [(&'static str, &'static [u8])],
169    command: CommandRunner,
170    args: &[String],
171) -> ExitCode {
172    if let Some(code) = build.pre_startup.and_then(|hook| hook(args)) {
173        return code;
174    }
175    prepare_startup(build, (boards, artwork), command, args)
176}
177
178fn prepare_startup(
179    build: ProductBuild,
180    (boards, artwork): (
181        Vec<BoardRegistration>,
182        &'static [(&'static str, &'static [u8])],
183    ),
184    command: CommandRunner,
185    args: &[String],
186) -> ExitCode {
187    let mut build = build;
188    let descriptor = &mut build.descriptor;
189    let version = build.version;
190    if let Err(error) = descriptor.apply_default_theme_override(build.default_theme_override) {
191        return finish(Err(error.to_string()));
192    }
193    subspace_update::cleanup_previous(&descriptor.binary_name);
194    let updates = descriptor.update.is_some();
195    warn_prerelease(descriptor, version, args, &route(args, updates));
196    if route(args, updates) == StartupRoute::Metadata {
197        return finish(print_metadata(descriptor, version));
198    }
199    if let Some(text) = build_text(&route(args, updates), descriptor, version, &build.build) {
200        println!("{text}");
201        return ExitCode::SUCCESS;
202    }
203    if route(args, updates) == StartupRoute::Upgrade {
204        return upgrade(descriptor, version, args);
205    }
206    let context = match prepare_context(build.descriptor.clone(), version) {
207        Ok(context) => ProductContext {
208            build: build.build,
209            ..context
210        },
211        Err(error) => return finish(Err(error)),
212    };
213    start_mode(build, context, (boards, artwork), args, command)
214}
215
216fn start_mode(
217    build: ProductBuild,
218    context: ProductContext,
219    (boards, artwork): (
220        Vec<BoardRegistration>,
221        &'static [(&'static str, &'static [u8])],
222    ),
223    args: &[String],
224    command: CommandRunner,
225) -> ExitCode {
226    match route(args, context.product.update.is_some()) {
227        StartupRoute::Desktop => finish(run_desktop(
228            context,
229            boards,
230            build.configured_boards,
231            artwork,
232            DesktopOptions {
233                account: build.account,
234                display_name_prefix: build.display_name_prefix,
235                reranker: build.search_reranker,
236                extensions: build.settings_extensions,
237                dock_panel: build.dock_panel,
238                github_oauth: build.github_oauth,
239                fonts: build.fonts,
240                product_themes: build.product_themes,
241                navigator_title: build.navigator_title,
242                #[cfg(feature = "report-issue")]
243                report_issue_repository: build.report_issue_repository,
244            },
245        )),
246        _ => {
247            let sign_in = (boards.as_slice(), build.github_oauth.is_some());
248            headless(&context, sign_in, args, build.search_reranker, command)
249        }
250    }
251}
252
253/// Names the data directory after the binary, unless the app named it
254/// first; `launch`, `prepare_context` and `record_new_install_theme` call
255/// it. Fails while a read has implicitly fixed another name, so the
256/// process never uses two data directories.
257pub(crate) fn name_data_directory(binary_name: &str) -> Result<(), String> {
258    data_name_outcome(subspace_product::configure_data_name(binary_name))
259}
260
261fn data_name_outcome(result: Result<(), DataNameError>) -> Result<(), String> {
262    match result {
263        Ok(()) | Err(DataNameError::Configured(_)) => Ok(()),
264        Err(error) => Err(error.to_string()),
265    }
266}
267
268/// What `about` and `--version` print; other routes print nothing here.
269fn build_text(
270    route: &StartupRoute,
271    descriptor: &ProductDescriptor,
272    version: &str,
273    build: &BuildInfo,
274) -> Option<String> {
275    match route {
276        StartupRoute::About => Some(crate::build_metadata::about_text(
277            descriptor, version, build,
278        )),
279        StartupRoute::Version => Some(crate::build_metadata::version_text(
280            descriptor, version, build,
281        )),
282        _ => None,
283    }
284}
285
286/// Environment variable that hides the pre-release warning when set to `1`.
287const NO_PRERELEASE_WARNING: &str = "SUBSPACE_NO_PRERELEASE_WARNING";
288
289/// Writes the one-line pre-release warning to stderr before a CLI command.
290fn warn_prerelease(
291    descriptor: &ProductDescriptor,
292    version: &str,
293    args: &[String],
294    route: &StartupRoute,
295) {
296    let suppressed = std::env::var(NO_PRERELEASE_WARNING).is_ok_and(|value| value == "1");
297    if warns(Channel::current(), route, args, suppressed) {
298        eprintln!("{}", warning_line(&descriptor.display_name, version));
299    }
300}
301
302/// True for a pre-release build running a CLI command whose output is not
303/// machine-read: never for the desktop app, `--version`,
304/// `__product_metadata` or a `--json` command.
305fn warns(channel: Channel, route: &StartupRoute, args: &[String], suppressed: bool) -> bool {
306    let machine_output = args
307        .iter()
308        .any(|arg| arg == "--json" || arg.starts_with("--json="));
309    let cli = !matches!(
310        route,
311        StartupRoute::Desktop | StartupRoute::Metadata | StartupRoute::Version
312    );
313    channel.is_prerelease() && cli && !machine_output && !suppressed
314}
315
316fn warning_line(display_name: &str, version: &str) -> String {
317    format!("warning: {display_name} {version} is a pre-release build")
318}
319
320/// `upgrade`: the app's own release check and install, before any
321/// configuration is read, so a broken configuration cannot block an update.
322fn upgrade(descriptor: &ProductDescriptor, version: &str, args: &[String]) -> ExitCode {
323    match validate_product(descriptor) {
324        Ok(product) => subspace_update::run_cli(&product, version, args),
325        Err(error) => finish(Err(error.to_string())),
326    }
327}
328
329fn print_metadata(descriptor: &ProductDescriptor, version: &str) -> Result<(), String> {
330    let metadata = product_metadata(descriptor, version).map_err(|error| error.to_string())?;
331    println!("{metadata}");
332    Ok(())
333}
334
335fn finish(result: Result<(), String>) -> ExitCode {
336    match result {
337        Ok(()) => ExitCode::SUCCESS,
338        Err(error) => {
339            eprintln!("{error}");
340            ExitCode::FAILURE
341        }
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use subspace_product::{Channel, DataNameError, ProductError};
348
349    use super::{StartupRoute, data_name_outcome, route, warning_line, warns};
350
351    #[cfg(unix)]
352    mod former_ids;
353
354    #[test]
355    fn launch_keeps_an_app_s_own_data_name_and_refuses_a_second_one() {
356        assert_eq!(data_name_outcome(Ok(())), Ok(()));
357        assert_eq!(
358            data_name_outcome(Err(DataNameError::Configured("example-app".into()))),
359            Ok(())
360        );
361        let read_first = data_name_outcome(Err(DataNameError::Resolved("subspace".into())));
362        assert!(
363            read_first.as_ref().is_err_and(
364                |error| error.contains("'subspace'") && error.contains("configure_data_name")
365            ),
366            "{read_first:?}"
367        );
368        let invalid = DataNameError::Invalid(ProductError::UnsafeIdentity { name: "..".into() });
369        assert!(data_name_outcome(Err(invalid)).is_err());
370    }
371
372    mod pre_startup;
373
374    fn words(values: &[&str]) -> Vec<String> {
375        values.iter().map(|value| (*value).to_owned()).collect()
376    }
377
378    fn nightly_warns(args: &[&str], suppressed: bool) -> bool {
379        let args = words(args);
380        warns(Channel::Nightly, &route(&args, true), &args, suppressed)
381    }
382
383    #[test]
384    fn a_pre_release_cli_command_warns_once_with_its_name_and_version() {
385        assert_eq!(
386            warning_line("Subspace (Nightly)", "1.10.2-nightly.202611010200.ga43a333"),
387            "warning: Subspace (Nightly) 1.10.2-nightly.202611010200.ga43a333 is a pre-release build"
388        );
389        for args in [
390            &["about"][..],
391            &["upgrade", "--check"],
392            &["mcp"],
393            &["github", "read"],
394        ] {
395            assert!(nightly_warns(args, false), "{args:?}");
396        }
397    }
398
399    #[test]
400    fn machine_output_the_desktop_suppression_and_stable_never_warn() {
401        for args in [
402            &[][..],
403            &["--version"],
404            &["__product_metadata"],
405            &["github", "read", "--json"],
406            &["github", "read", "--json=true"],
407        ] {
408            assert!(!nightly_warns(args, false), "{args:?}");
409        }
410        assert!(!nightly_warns(&["about"], true));
411        let about = words(&["about"]);
412        assert!(!warns(Channel::Stable, &route(&about, true), &about, false));
413    }
414
415    #[test]
416    fn only_no_arguments_choose_desktop_initialization() {
417        assert_eq!(route(&[], true), StartupRoute::Desktop);
418        for args in [["--help"], ["--version"], ["tui"], ["unknown"]] {
419            let expected = if args == ["--version"] {
420                StartupRoute::Version
421            } else {
422                StartupRoute::Command
423            };
424            assert_eq!(route(&args.map(str::to_owned), true), expected);
425        }
426        assert_eq!(
427            route(&["__product_metadata".into()], true),
428            StartupRoute::Metadata
429        );
430        assert_eq!(route(&["about".into()], true), StartupRoute::About);
431        assert_eq!(route(&["--about".into()], true), StartupRoute::About);
432    }
433
434    #[test]
435    fn a_lone_about_is_start_ups_but_a_space_named_about_keeps_its_commands() {
436        assert_eq!(route(&words(&["about"]), true), StartupRoute::About);
437        assert_eq!(
438            route(&words(&["about", "read"]), true),
439            StartupRoute::Command
440        );
441    }
442
443    #[test]
444    fn mcp_is_routed_before_the_board_commands() {
445        assert_eq!(route(&["mcp".into()], true), StartupRoute::Mcp);
446        assert_eq!(
447            route(&["mcp".into(), "--http".into()], true),
448            StartupRoute::Mcp
449        );
450        assert_eq!(
451            route(&["github".into(), "mcp".into()], true),
452            StartupRoute::Command
453        );
454    }
455
456    #[test]
457    fn upgrade_is_routed_before_any_configuration_when_the_app_has_updates() {
458        for args in [
459            vec!["upgrade".to_owned()],
460            vec!["upgrade".to_owned(), "--check".to_owned()],
461            vec!["upgrade".to_owned(), "--version".to_owned(), "1.2.0".into()],
462        ] {
463            assert_eq!(route(&args, true), StartupRoute::Upgrade);
464        }
465        assert_eq!(
466            route(&["github".into(), "upgrade".into()], true),
467            StartupRoute::Command
468        );
469    }
470
471    #[test]
472    fn only_desktop_mcp_and_commands_read_the_configuration() {
473        let updating = |args: &[&str]| super::reads_configuration_for(&words(args), true);
474        for args in [
475            &["upgrade"][..],
476            &["--version"],
477            &["about"],
478            &["__product_metadata"],
479        ] {
480            assert!(!updating(args), "{args:?}");
481        }
482        for args in [&[][..], &["mcp"], &["issues", "list"]] {
483            assert!(updating(args), "{args:?}");
484        }
485        assert!(super::reads_configuration_for(&words(&["upgrade"]), false));
486    }
487
488    #[test]
489    fn upgrade_falls_through_without_an_update_source() {
490        assert_eq!(route(&["upgrade".into()], false), StartupRoute::Command);
491        assert_eq!(
492            route(&["upgrade".into(), "--check".into()], false),
493            StartupRoute::Command
494        );
495        assert_eq!(route(&["mcp".into()], false), StartupRoute::Mcp);
496    }
497}