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