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    /// The GitHub repository (`owner/name`) Report issue files into. `None`
67    /// or blank hides Report issue; a malformed one hides it with a notice.
68    #[cfg(feature = "report-issue")]
69    pub report_issue_repository: Option<&'static str>,
70}
71
72/// Whether `args` start a route that reads the app's configuration. The
73/// product metadata, About, `--version` and `upgrade` read none, so an app
74/// that checks its own settings before [`launch`] skips those checks for
75/// them, and a broken setting never blocks an upgrade.
76// qual:api - a product calls it before its own start-up checks.
77pub fn reads_configuration(descriptor: &ProductDescriptor, args: &[String]) -> bool {
78    reads_configuration_for(args, descriptor.update.is_some())
79}
80
81fn reads_configuration_for(args: &[String], updates: bool) -> bool {
82    !matches!(
83        route(args, updates),
84        StartupRoute::Metadata
85            | StartupRoute::About
86            | StartupRoute::Version
87            | StartupRoute::Upgrade
88    )
89}
90
91impl ProductBuild {
92    /// Build a product with no optional host integrations or startup hook.
93    pub fn new(descriptor: ProductDescriptor, version: &'static str, build: BuildInfo) -> Self {
94        Self {
95            descriptor,
96            version,
97            build,
98            pre_startup: None,
99            account: None,
100            display_name_prefix: None,
101            search_reranker: None,
102            default_theme_override: None,
103            configured_boards: None,
104            settings_extensions: &[],
105            dock_panel: None,
106            github_oauth: None,
107            fonts: &[],
108            product_themes: &[],
109            #[cfg(feature = "report-issue")]
110            report_issue_repository: None,
111        }
112    }
113}
114
115type CommandRunner = fn(
116    &ProductContext,
117    &[subspace_mcp::Board],
118    &subspace_agent_tools::ToolEnvironment,
119    &[String],
120) -> ExitCode;
121
122/// `updates` is whether this app has an update source. Without one,
123/// `upgrade` is not a Framework command and falls through to the normal
124/// command path, which reports it as unknown.
125fn route(args: &[String], updates: bool) -> StartupRoute {
126    startup_route(args.is_empty(), host_command(args, updates))
127}
128
129fn startup_route(empty: bool, host: Option<HostCommand>) -> StartupRoute {
130    match (empty, host) {
131        (true, _) => StartupRoute::Desktop,
132        (_, Some(HostCommand::Metadata)) => StartupRoute::Metadata,
133        (_, Some(HostCommand::About)) => StartupRoute::About,
134        (_, Some(HostCommand::Version)) => StartupRoute::Version,
135        (_, Some(HostCommand::Mcp)) => StartupRoute::Mcp,
136        (_, Some(HostCommand::Upgrade)) => StartupRoute::Upgrade,
137        (false, None) => StartupRoute::Command,
138    }
139}
140
141/// Called by thin binaries with only their selected board providers. Every
142/// mode first names the data directory after the binary, unless the app
143/// called [`subspace_product::configure_data_name`] first, then gets the
144/// user's `PATH`; nothing before that starts a thread. It fails when
145/// something read a data path under another name before it.
146pub fn launch(
147    build: ProductBuild,
148    boards: Vec<BoardRegistration>,
149    artwork: &'static [(&'static str, &'static [u8])],
150    command: CommandRunner,
151) -> ExitCode {
152    if let Err(error) = name_data_directory(build.descriptor.binary_name.as_str()) {
153        return finish(Err(error));
154    }
155    crate::startup_path::apply();
156    let args = std::env::args().skip(1).collect::<Vec<_>>();
157    launch_after_path(build, boards, artwork, command, &args)
158}
159
160fn launch_after_path(
161    build: ProductBuild,
162    boards: Vec<BoardRegistration>,
163    artwork: &'static [(&'static str, &'static [u8])],
164    command: CommandRunner,
165    args: &[String],
166) -> ExitCode {
167    if let Some(code) = build.pre_startup.and_then(|hook| hook(args)) {
168        return code;
169    }
170    prepare_startup(build, (boards, artwork), command, args)
171}
172
173fn prepare_startup(
174    build: ProductBuild,
175    (boards, artwork): (
176        Vec<BoardRegistration>,
177        &'static [(&'static str, &'static [u8])],
178    ),
179    command: CommandRunner,
180    args: &[String],
181) -> ExitCode {
182    let mut build = build;
183    let descriptor = &mut build.descriptor;
184    let version = build.version;
185    if let Err(error) = descriptor.apply_default_theme_override(build.default_theme_override) {
186        return finish(Err(error.to_string()));
187    }
188    subspace_update::cleanup_previous(&descriptor.binary_name);
189    let updates = descriptor.update.is_some();
190    warn_prerelease(descriptor, version, args, &route(args, updates));
191    if route(args, updates) == StartupRoute::Metadata {
192        return finish(print_metadata(descriptor, version));
193    }
194    if let Some(text) = build_text(&route(args, updates), descriptor, version, &build.build) {
195        println!("{text}");
196        return ExitCode::SUCCESS;
197    }
198    if route(args, updates) == StartupRoute::Upgrade {
199        return upgrade(descriptor, version, args);
200    }
201    let context = match prepare_context(build.descriptor.clone(), version) {
202        Ok(context) => ProductContext {
203            build: build.build,
204            ..context
205        },
206        Err(error) => return finish(Err(error)),
207    };
208    start_mode(build, context, (boards, artwork), args, command)
209}
210
211fn start_mode(
212    build: ProductBuild,
213    context: ProductContext,
214    (boards, artwork): (
215        Vec<BoardRegistration>,
216        &'static [(&'static str, &'static [u8])],
217    ),
218    args: &[String],
219    command: CommandRunner,
220) -> ExitCode {
221    match route(args, context.product.update.is_some()) {
222        StartupRoute::Desktop => finish(run_desktop(
223            context,
224            boards,
225            build.configured_boards,
226            artwork,
227            DesktopOptions {
228                account: build.account,
229                display_name_prefix: build.display_name_prefix,
230                reranker: build.search_reranker,
231                extensions: build.settings_extensions,
232                dock_panel: build.dock_panel,
233                github_oauth: build.github_oauth,
234                fonts: build.fonts,
235                product_themes: build.product_themes,
236                #[cfg(feature = "report-issue")]
237                report_issue_repository: build.report_issue_repository,
238            },
239        )),
240        _ => {
241            let sign_in = (boards.as_slice(), build.github_oauth.is_some());
242            headless(&context, sign_in, args, build.search_reranker, command)
243        }
244    }
245}
246
247/// Names the data directory after the binary, unless the app named it
248/// first; `launch`, `prepare_context` and `record_new_install_theme` call
249/// it. Fails while a read has implicitly fixed another name, so the
250/// process never uses two data directories.
251pub(crate) fn name_data_directory(binary_name: &str) -> Result<(), String> {
252    data_name_outcome(subspace_product::configure_data_name(binary_name))
253}
254
255fn data_name_outcome(result: Result<(), DataNameError>) -> Result<(), String> {
256    match result {
257        Ok(()) | Err(DataNameError::Configured(_)) => Ok(()),
258        Err(error) => Err(error.to_string()),
259    }
260}
261
262/// What `about` and `--version` print; other routes print nothing here.
263fn build_text(
264    route: &StartupRoute,
265    descriptor: &ProductDescriptor,
266    version: &str,
267    build: &BuildInfo,
268) -> Option<String> {
269    match route {
270        StartupRoute::About => Some(crate::build_metadata::about_text(
271            descriptor, version, build,
272        )),
273        StartupRoute::Version => Some(crate::build_metadata::version_text(
274            descriptor, version, build,
275        )),
276        _ => None,
277    }
278}
279
280/// Environment variable that hides the pre-release warning when set to `1`.
281const NO_PRERELEASE_WARNING: &str = "SUBSPACE_NO_PRERELEASE_WARNING";
282
283/// Writes the one-line pre-release warning to stderr before a CLI command.
284fn warn_prerelease(
285    descriptor: &ProductDescriptor,
286    version: &str,
287    args: &[String],
288    route: &StartupRoute,
289) {
290    let suppressed = std::env::var(NO_PRERELEASE_WARNING).is_ok_and(|value| value == "1");
291    if warns(Channel::current(), route, args, suppressed) {
292        eprintln!("{}", warning_line(&descriptor.display_name, version));
293    }
294}
295
296/// True for a pre-release build running a CLI command whose output is not
297/// machine-read: never for the desktop app, `--version`,
298/// `__product_metadata` or a `--json` command.
299fn warns(channel: Channel, route: &StartupRoute, args: &[String], suppressed: bool) -> bool {
300    let machine_output = args
301        .iter()
302        .any(|arg| arg == "--json" || arg.starts_with("--json="));
303    let cli = !matches!(
304        route,
305        StartupRoute::Desktop | StartupRoute::Metadata | StartupRoute::Version
306    );
307    channel.is_prerelease() && cli && !machine_output && !suppressed
308}
309
310fn warning_line(display_name: &str, version: &str) -> String {
311    format!("warning: {display_name} {version} is a pre-release build")
312}
313
314/// `upgrade`: the app's own release check and install, before any
315/// configuration is read, so a broken configuration cannot block an update.
316fn upgrade(descriptor: &ProductDescriptor, version: &str, args: &[String]) -> ExitCode {
317    match validate_product(descriptor) {
318        Ok(product) => subspace_update::run_cli(&product, version, args),
319        Err(error) => finish(Err(error.to_string())),
320    }
321}
322
323fn print_metadata(descriptor: &ProductDescriptor, version: &str) -> Result<(), String> {
324    let metadata = product_metadata(descriptor, version).map_err(|error| error.to_string())?;
325    println!("{metadata}");
326    Ok(())
327}
328
329fn finish(result: Result<(), String>) -> ExitCode {
330    match result {
331        Ok(()) => ExitCode::SUCCESS,
332        Err(error) => {
333            eprintln!("{error}");
334            ExitCode::FAILURE
335        }
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use subspace_product::{Channel, DataNameError, ProductError};
342
343    use super::{StartupRoute, data_name_outcome, route, warning_line, warns};
344
345    #[cfg(unix)]
346    mod former_ids;
347
348    #[test]
349    fn launch_keeps_an_app_s_own_data_name_and_refuses_a_second_one() {
350        assert_eq!(data_name_outcome(Ok(())), Ok(()));
351        assert_eq!(
352            data_name_outcome(Err(DataNameError::Configured("example-app".into()))),
353            Ok(())
354        );
355        let read_first = data_name_outcome(Err(DataNameError::Resolved("subspace".into())));
356        assert!(
357            read_first.as_ref().is_err_and(
358                |error| error.contains("'subspace'") && error.contains("configure_data_name")
359            ),
360            "{read_first:?}"
361        );
362        let invalid = DataNameError::Invalid(ProductError::UnsafeIdentity { name: "..".into() });
363        assert!(data_name_outcome(Err(invalid)).is_err());
364    }
365
366    mod pre_startup;
367
368    fn words(values: &[&str]) -> Vec<String> {
369        values.iter().map(|value| (*value).to_owned()).collect()
370    }
371
372    fn nightly_warns(args: &[&str], suppressed: bool) -> bool {
373        let args = words(args);
374        warns(Channel::Nightly, &route(&args, true), &args, suppressed)
375    }
376
377    #[test]
378    fn a_pre_release_cli_command_warns_once_with_its_name_and_version() {
379        assert_eq!(
380            warning_line("Subspace (Nightly)", "1.10.2-nightly.202611010200.ga43a333"),
381            "warning: Subspace (Nightly) 1.10.2-nightly.202611010200.ga43a333 is a pre-release build"
382        );
383        for args in [
384            &["about"][..],
385            &["upgrade", "--check"],
386            &["mcp"],
387            &["github", "read"],
388        ] {
389            assert!(nightly_warns(args, false), "{args:?}");
390        }
391    }
392
393    #[test]
394    fn machine_output_the_desktop_suppression_and_stable_never_warn() {
395        for args in [
396            &[][..],
397            &["--version"],
398            &["__product_metadata"],
399            &["github", "read", "--json"],
400            &["github", "read", "--json=true"],
401        ] {
402            assert!(!nightly_warns(args, false), "{args:?}");
403        }
404        assert!(!nightly_warns(&["about"], true));
405        let about = words(&["about"]);
406        assert!(!warns(Channel::Stable, &route(&about, true), &about, false));
407    }
408
409    #[test]
410    fn only_no_arguments_choose_desktop_initialization() {
411        assert_eq!(route(&[], true), StartupRoute::Desktop);
412        for args in [["--help"], ["--version"], ["tui"], ["unknown"]] {
413            let expected = if args == ["--version"] {
414                StartupRoute::Version
415            } else {
416                StartupRoute::Command
417            };
418            assert_eq!(route(&args.map(str::to_owned), true), expected);
419        }
420        assert_eq!(
421            route(&["__product_metadata".into()], true),
422            StartupRoute::Metadata
423        );
424        assert_eq!(route(&["about".into()], true), StartupRoute::About);
425        assert_eq!(route(&["--about".into()], true), StartupRoute::About);
426    }
427
428    #[test]
429    fn a_lone_about_is_start_ups_but_a_space_named_about_keeps_its_commands() {
430        assert_eq!(route(&words(&["about"]), true), StartupRoute::About);
431        assert_eq!(
432            route(&words(&["about", "read"]), true),
433            StartupRoute::Command
434        );
435    }
436
437    #[test]
438    fn mcp_is_routed_before_the_board_commands() {
439        assert_eq!(route(&["mcp".into()], true), StartupRoute::Mcp);
440        assert_eq!(
441            route(&["mcp".into(), "--http".into()], true),
442            StartupRoute::Mcp
443        );
444        assert_eq!(
445            route(&["github".into(), "mcp".into()], true),
446            StartupRoute::Command
447        );
448    }
449
450    #[test]
451    fn upgrade_is_routed_before_any_configuration_when_the_app_has_updates() {
452        for args in [
453            vec!["upgrade".to_owned()],
454            vec!["upgrade".to_owned(), "--check".to_owned()],
455            vec!["upgrade".to_owned(), "--version".to_owned(), "1.2.0".into()],
456        ] {
457            assert_eq!(route(&args, true), StartupRoute::Upgrade);
458        }
459        assert_eq!(
460            route(&["github".into(), "upgrade".into()], true),
461            StartupRoute::Command
462        );
463    }
464
465    #[test]
466    fn only_desktop_mcp_and_commands_read_the_configuration() {
467        let updating = |args: &[&str]| super::reads_configuration_for(&words(args), true);
468        for args in [
469            &["upgrade"][..],
470            &["--version"],
471            &["about"],
472            &["__product_metadata"],
473        ] {
474            assert!(!updating(args), "{args:?}");
475        }
476        for args in [&[][..], &["mcp"], &["issues", "list"]] {
477            assert!(updating(args), "{args:?}");
478        }
479        assert!(super::reads_configuration_for(&words(&["upgrade"]), false));
480    }
481
482    #[test]
483    fn upgrade_falls_through_without_an_update_source() {
484        assert_eq!(route(&["upgrade".into()], false), StartupRoute::Command);
485        assert_eq!(
486            route(&["upgrade".into(), "--check".into()], false),
487            StartupRoute::Command
488        );
489        assert_eq!(route(&["mcp".into()], false), StartupRoute::Mcp);
490    }
491}