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, 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
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    /// Optional prefix for desktop window titles, menus and About.
31    pub display_name_prefix: Option<&'static str>,
32    pub version: &'static str,
33    /// How this binary was built, stamped by the product's build script.
34    pub build: BuildInfo,
35    pub search_reranker: Option<crate::RerankerFactory>,
36    pub default_theme_override: Option<&'static str>,
37    /// Boards the desktop app adds from its config file. Headless commands
38    /// do not use them.
39    pub configured_boards: Option<crate::ConfiguredBoards>,
40    pub settings_extensions: &'static [crate::SettingsExtension],
41    /// The panel the shell docks beside every Space, such as the terminal.
42    /// `None` shows no terminal button, action, menu item or command.
43    pub dock_panel: Option<subspace_dashboard::dock_panel::DockPanelRegistration>,
44    /// The app's GitHub OAuth App, for Sign in with GitHub. The Framework has
45    /// none: `None` offers no Sign in with GitHub anywhere, and tokens come
46    /// from the environment, the config file and the `gh` CLI as before.
47    pub github_oauth: Option<subspace_github_auth::OAuthClient>,
48    /// Font files the app embeds, registered with the text system before the
49    /// theme is applied. A theme or Settings that names one of their families
50    /// gets it on every platform; automatic choices still use the platform's
51    /// fonts. `&[]` embeds none.
52    pub fonts: &'static [crate::BundledFont],
53    /// Theme documents the product embeds beside the Framework's catalogue,
54    /// as `(id, json)`. List an id in the descriptor's `themes`, and name one
55    /// of its variants as `default_theme`, to use it. An id must not repeat a
56    /// Framework theme id. `&[]` adds none.
57    pub product_themes: crate::ProductThemes,
58    /// The GitHub repository (`owner/name`) Report issue files into. `None`
59    /// or blank hides Report issue; a malformed one hides it with a notice.
60    #[cfg(feature = "report-issue")]
61    pub report_issue_repository: Option<&'static str>,
62}
63
64/// Whether `args` start a route that reads the app's configuration. The
65/// product metadata, About, `--version` and `upgrade` read none, so an app
66/// that checks its own settings before [`launch`] skips those checks for
67/// them, and a broken setting never blocks an upgrade.
68// qual:api - a product calls it before its own start-up checks.
69pub fn reads_configuration(descriptor: &ProductDescriptor, args: &[String]) -> bool {
70    reads_configuration_for(args, descriptor.update.is_some())
71}
72
73fn reads_configuration_for(args: &[String], updates: bool) -> bool {
74    !matches!(
75        route(args, updates),
76        StartupRoute::Metadata
77            | StartupRoute::About
78            | StartupRoute::Version
79            | StartupRoute::Upgrade
80    )
81}
82
83/// `updates` is whether this app has an update source. Without one,
84/// `upgrade` is not a Framework command and falls through to the normal
85/// command path, which reports it as unknown.
86fn route(args: &[String], updates: bool) -> StartupRoute {
87    match args {
88        [] => StartupRoute::Desktop,
89        [arg] if arg == "__product_metadata" => StartupRoute::Metadata,
90        [arg] if arg == "about" || arg == "--about" => StartupRoute::About,
91        [arg] if arg == "--version" => StartupRoute::Version,
92        [first, ..] if first == MCP_COMMAND => StartupRoute::Mcp,
93        [first, ..] if updates && first == UPGRADE_COMMAND => StartupRoute::Upgrade,
94        _ => StartupRoute::Command,
95    }
96}
97
98/// Called by thin binaries with only their selected board providers. Every
99/// mode first gets the user's `PATH`; nothing before that starts a thread.
100pub fn launch(
101    build: ProductBuild,
102    boards: Vec<BoardRegistration>,
103    artwork: &'static [(&'static str, &'static [u8])],
104    command: fn(
105        &ProductContext,
106        &[subspace_mcp::Board],
107        &subspace_agent_tools::ToolEnvironment,
108        &[String],
109    ) -> ExitCode,
110) -> ExitCode {
111    crate::startup_path::apply(&build.descriptor);
112    let mut descriptor = build.descriptor;
113    let version = build.version;
114    let args = std::env::args().skip(1).collect::<Vec<_>>();
115    if let Err(error) = descriptor.apply_default_theme_override(build.default_theme_override) {
116        return finish(Err(error.to_string()));
117    }
118    subspace_update::cleanup_previous(&descriptor.binary_name);
119    let updates = descriptor.update.is_some();
120    warn_prerelease(&descriptor, version, &args, &route(&args, updates));
121    if route(&args, updates) == StartupRoute::Metadata {
122        return finish(print_metadata(&descriptor, version));
123    }
124    if let Some(text) = build_text(&route(&args, updates), &descriptor, version, &build.build) {
125        println!("{text}");
126        return ExitCode::SUCCESS;
127    }
128    if route(&args, updates) == StartupRoute::Upgrade {
129        return upgrade(&descriptor, version, &args);
130    }
131    let context = match prepare_context(descriptor, version) {
132        Ok(context) => ProductContext {
133            build: build.build,
134            ..context
135        },
136        Err(error) => return finish(Err(error)),
137    };
138    match route(&args, updates) {
139        StartupRoute::Desktop => finish(run_desktop(
140            context,
141            boards,
142            build.configured_boards,
143            artwork,
144            DesktopOptions {
145                account: build.account,
146                display_name_prefix: build.display_name_prefix,
147                reranker: build.search_reranker,
148                extensions: build.settings_extensions,
149                dock_panel: build.dock_panel,
150                github_oauth: build.github_oauth,
151                fonts: build.fonts,
152                product_themes: build.product_themes,
153                #[cfg(feature = "report-issue")]
154                report_issue_repository: build.report_issue_repository,
155            },
156        )),
157        _ => {
158            let sign_in = (boards.as_slice(), build.github_oauth.is_some());
159            headless(&context, sign_in, &args, build.search_reranker, command)
160        }
161    }
162}
163
164/// What `about` and `--version` print; other routes print nothing here.
165fn build_text(
166    route: &StartupRoute,
167    descriptor: &ProductDescriptor,
168    version: &str,
169    build: &BuildInfo,
170) -> Option<String> {
171    match route {
172        StartupRoute::About => Some(crate::build_metadata::about_text(
173            descriptor, version, build,
174        )),
175        StartupRoute::Version => Some(crate::build_metadata::version_text(
176            descriptor, version, build,
177        )),
178        _ => None,
179    }
180}
181
182/// Environment variable that hides the pre-release warning when set to `1`.
183const NO_PRERELEASE_WARNING: &str = "SUBSPACE_NO_PRERELEASE_WARNING";
184
185/// Writes the one-line pre-release warning to stderr before a CLI command.
186fn warn_prerelease(
187    descriptor: &ProductDescriptor,
188    version: &str,
189    args: &[String],
190    route: &StartupRoute,
191) {
192    let suppressed = std::env::var(NO_PRERELEASE_WARNING).is_ok_and(|value| value == "1");
193    if warns(Channel::current(), route, args, suppressed) {
194        eprintln!("{}", warning_line(&descriptor.display_name, version));
195    }
196}
197
198/// True for a pre-release build running a CLI command whose output is not
199/// machine-read: never for the desktop app, `--version`,
200/// `__product_metadata` or a `--json` command.
201fn warns(channel: Channel, route: &StartupRoute, args: &[String], suppressed: bool) -> bool {
202    let machine_output = args
203        .iter()
204        .any(|arg| arg == "--json" || arg.starts_with("--json="));
205    let cli = !matches!(
206        route,
207        StartupRoute::Desktop | StartupRoute::Metadata | StartupRoute::Version
208    );
209    channel.is_prerelease() && cli && !machine_output && !suppressed
210}
211
212fn warning_line(display_name: &str, version: &str) -> String {
213    format!("warning: {display_name} {version} is a pre-release build")
214}
215
216/// `upgrade`: the app's own release check and install, before any
217/// configuration is read, so a broken configuration cannot block an update.
218fn upgrade(descriptor: &ProductDescriptor, version: &str, args: &[String]) -> ExitCode {
219    match validate_product(descriptor) {
220        Ok(product) => subspace_update::run_cli(&product, version, args),
221        Err(error) => finish(Err(error.to_string())),
222    }
223}
224
225/// `mcp`: the selected boards' agent tools for other harnesses, without GPUI
226/// or a Copilot login.
227/// `sign_in` is whether the app offers Sign in with GitHub, which guidance
228/// may then name.
229fn headless(
230    context: &ProductContext,
231    (boards, sign_in): (&[BoardRegistration], bool),
232    args: &[String],
233    reranker: Option<crate::RerankerFactory>,
234    command: fn(
235        &ProductContext,
236        &[subspace_mcp::Board],
237        &subspace_agent_tools::ToolEnvironment,
238        &[String],
239    ) -> ExitCode,
240) -> ExitCode {
241    let files = crate::product::ProductFiles::for_context(context);
242    let (mut environment, notices) = crate::tool_environment(
243        &files.config,
244        boards,
245        subspace_agent_tools::ToolHost::Headless,
246        sign_in,
247    );
248    let log_notice = crate::logging::start(&files, context);
249    for notice in notices.into_iter().chain(log_notice) {
250        eprintln!("{notice}");
251    }
252    let selected = match crate::registry::selected_registrations(
253        &context.product,
254        boards,
255        &environment.config,
256    ) {
257        Ok(selected) => selected,
258        Err(error) => return finish(Err(error)),
259    };
260    if let Err(error) =
261        crate::search_runtime::initialize(&mut environment, context, &selected, &files, reranker)
262    {
263        eprintln!("Full-text search unavailable: {error}");
264    }
265    let boards = crate::registry::mcp_boards(&selected);
266    if args.first().is_some_and(|arg| arg == "mcp") {
267        subspace_mcp::run(
268            context,
269            &boards,
270            &environment,
271            &args[1..],
272            &environment.config.mcp,
273        )
274    } else {
275        command(context, &boards, &environment, args)
276    }
277}
278
279fn print_metadata(descriptor: &ProductDescriptor, version: &str) -> Result<(), String> {
280    let metadata = product_metadata(descriptor, version).map_err(|error| error.to_string())?;
281    println!("{metadata}");
282    Ok(())
283}
284
285fn finish(result: Result<(), String>) -> ExitCode {
286    match result {
287        Ok(()) => ExitCode::SUCCESS,
288        Err(error) => {
289            eprintln!("{error}");
290            ExitCode::FAILURE
291        }
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use subspace_product::Channel;
298
299    use super::{StartupRoute, route, warning_line, warns};
300
301    fn words(values: &[&str]) -> Vec<String> {
302        values.iter().map(|value| (*value).to_owned()).collect()
303    }
304
305    fn nightly_warns(args: &[&str], suppressed: bool) -> bool {
306        let args = words(args);
307        warns(Channel::Nightly, &route(&args, true), &args, suppressed)
308    }
309
310    #[test]
311    fn a_pre_release_cli_command_warns_once_with_its_name_and_version() {
312        assert_eq!(
313            warning_line("Subspace (Nightly)", "1.10.2-nightly.202611010200.ga43a333"),
314            "warning: Subspace (Nightly) 1.10.2-nightly.202611010200.ga43a333 is a pre-release build"
315        );
316        for args in [
317            &["about"][..],
318            &["upgrade", "--check"],
319            &["mcp"],
320            &["github", "read"],
321        ] {
322            assert!(nightly_warns(args, false), "{args:?}");
323        }
324    }
325
326    #[test]
327    fn machine_output_the_desktop_suppression_and_stable_never_warn() {
328        for args in [
329            &[][..],
330            &["--version"],
331            &["__product_metadata"],
332            &["github", "read", "--json"],
333            &["github", "read", "--json=true"],
334        ] {
335            assert!(!nightly_warns(args, false), "{args:?}");
336        }
337        assert!(!nightly_warns(&["about"], true));
338        let about = words(&["about"]);
339        assert!(!warns(Channel::Stable, &route(&about, true), &about, false));
340    }
341
342    #[test]
343    fn only_no_arguments_choose_desktop_initialization() {
344        assert_eq!(route(&[], true), StartupRoute::Desktop);
345        for args in [["--help"], ["--version"], ["tui"], ["unknown"]] {
346            let expected = if args == ["--version"] {
347                StartupRoute::Version
348            } else {
349                StartupRoute::Command
350            };
351            assert_eq!(route(&args.map(str::to_owned), true), expected);
352        }
353        assert_eq!(
354            route(&["__product_metadata".into()], true),
355            StartupRoute::Metadata
356        );
357        assert_eq!(route(&["about".into()], true), StartupRoute::About);
358        assert_eq!(route(&["--about".into()], true), StartupRoute::About);
359    }
360
361    #[test]
362    fn mcp_is_routed_before_the_board_commands() {
363        assert_eq!(route(&["mcp".into()], true), StartupRoute::Mcp);
364        assert_eq!(
365            route(&["mcp".into(), "--http".into()], true),
366            StartupRoute::Mcp
367        );
368        assert_eq!(
369            route(&["github".into(), "mcp".into()], true),
370            StartupRoute::Command
371        );
372    }
373
374    #[test]
375    fn upgrade_is_routed_before_any_configuration_when_the_app_has_updates() {
376        for args in [
377            vec!["upgrade".to_owned()],
378            vec!["upgrade".to_owned(), "--check".to_owned()],
379            vec!["upgrade".to_owned(), "--version".to_owned(), "1.2.0".into()],
380        ] {
381            assert_eq!(route(&args, true), StartupRoute::Upgrade);
382        }
383        assert_eq!(
384            route(&["github".into(), "upgrade".into()], true),
385            StartupRoute::Command
386        );
387    }
388
389    #[test]
390    fn only_desktop_mcp_and_commands_read_the_configuration() {
391        let updating = |args: &[&str]| super::reads_configuration_for(&words(args), true);
392        for args in [
393            &["upgrade"][..],
394            &["--version"],
395            &["about"],
396            &["__product_metadata"],
397        ] {
398            assert!(!updating(args), "{args:?}");
399        }
400        for args in [&[][..], &["mcp"], &["issues", "list"]] {
401            assert!(updating(args), "{args:?}");
402        }
403        assert!(super::reads_configuration_for(&words(&["upgrade"]), false));
404    }
405
406    #[test]
407    fn upgrade_falls_through_without_an_update_source() {
408        assert_eq!(route(&["upgrade".into()], false), StartupRoute::Command);
409        assert_eq!(
410            route(&["upgrade".into(), "--check".into()], false),
411            StartupRoute::Command
412        );
413        assert_eq!(route(&["mcp".into()], false), StartupRoute::Mcp);
414    }
415}