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