Skip to main content

subspace_shell/
lib.rs

1//! Shared desktop shell. Product entrypoints route headless commands before
2//! calling [`run`], then supply the selected dashboard factories and artwork.
3
4use std::sync::Arc;
5
6use gpui_kit::{App, AppContext as _, WindowOptions};
7use subspace_agent_tools::{ToolEnvironment, ToolHost};
8use subspace_core::config;
9use subspace_core::credentials::Credentials;
10use subspace_dashboard::dock_panel::DockPanelRegistration;
11use subspace_dashboard::{Services, prefs};
12use subspace_github_auth::OAuthClient;
13use subspace_product::ProductContext;
14
15mod account;
16pub(crate) mod app;
17mod assets;
18mod build_metadata;
19mod bundled_fonts;
20#[cfg(any(test, all(debug_assertions, feature = "capture")))]
21mod capture;
22#[cfg(windows)]
23mod console;
24mod diagnostics;
25#[cfg(debug_assertions)]
26mod inspector;
27mod jig;
28mod logging;
29mod mcp;
30mod notifications;
31mod palette;
32mod product;
33mod registry;
34mod search_runtime;
35mod settings;
36mod startup;
37mod startup_path;
38mod status_bar;
39mod terminal;
40mod theme;
41pub(crate) mod toolbar_labels;
42
43pub use account::{AccountRegistration, AccountSession, AccountTokenSource, account_session};
44pub use bundled_fonts::BundledFont;
45pub use product::{config_file, prepare_context};
46pub use registry::reload_configured_boards;
47pub use registry::{BoardRegistration, ConfiguredBoards};
48pub use search_runtime::RerankerFactory;
49pub use settings::extensions::SettingsExtension;
50pub use startup::{ProductBuild, launch};
51pub use theme::record_new_install_theme;
52
53#[cfg(any(test, feature = "test-support"))]
54pub mod test_support;
55
56/// What the desktop app adds to the shell, from [`ProductBuild`].
57pub(crate) struct DesktopOptions {
58    pub account: Option<AccountRegistration>,
59    pub display_name_prefix: Option<&'static str>,
60    pub reranker: Option<RerankerFactory>,
61    pub extensions: &'static [SettingsExtension],
62    pub dock_panel: Option<DockPanelRegistration>,
63    pub github_oauth: Option<OAuthClient>,
64    pub fonts: &'static [BundledFont],
65    #[cfg(feature = "report-issue")]
66    pub report_issue_repository: Option<&'static str>,
67}
68
69/// Opens one product window. [`launch`] is the only caller.
70fn run_desktop(
71    context: ProductContext,
72    boards: Vec<BoardRegistration>,
73    configured: Option<ConfiguredBoards>,
74    artwork: &'static [(&'static str, &'static [u8])],
75    options: DesktopOptions,
76) -> Result<(), String> {
77    theme::validate_product_themes(&context.product)?;
78    let files = product::ProductFiles::for_context(&context);
79    let sign_in = options.github_oauth.is_some();
80    let (mut environment, mut notices) =
81        tool_environment(&files.config, &boards, ToolHost::App, sign_in);
82    #[cfg(feature = "report-issue")]
83    notices.extend(app::report_issue::target(options.report_issue_repository).err());
84    notices.extend(logging::start(&files, &context));
85    let (registrations, board_notices) =
86        registry::desktop_sets(&context.product, &boards, configured, &environment.config)?;
87    notices.extend(board_notices);
88    if let Err(error) = search_runtime::initialize(
89        &mut environment,
90        &context,
91        &registrations.active,
92        &files,
93        options.reranker,
94    ) {
95        notices.push(format!("Full-text search unavailable: {error}"));
96    }
97    let tools = registry::tool_catalog(&registrations.active, &environment)?;
98    let mcp = mcp::McpService::new(&registrations.active, environment.clone());
99    let context = Arc::new(context);
100    #[cfg(windows)]
101    console::detach()?;
102    let application =
103        gpui_kit::application().with_assets(assets::Assets::new(artwork, &registrations.included));
104    application.on_reopen(ensure_product_window);
105    application.run(move |cx| {
106        gpui_kit::init(cx);
107        product::install_context(context.clone(), options.display_name_prefix, cx);
108        install_registrations(
109            boards.clone(),
110            configured,
111            registrations,
112            options.extensions,
113            cx,
114        );
115        terminal::install(options.dock_panel, cx);
116        prefs::init_file(Some(files.state.clone()), cx);
117        let config_file = files.config.clone();
118        cx.set_global(files);
119        let notices = start_theme(notices, options.fonts, cx);
120        install_services(environment, tools, config_file, options.github_oauth, cx);
121        account::init(options.account, cx);
122        #[cfg(feature = "report-issue")]
123        app::report_issue::install(options.report_issue_repository, cx);
124        bind_keys(cx);
125        app::install_menus(cx);
126        notifications::init(cx);
127        search_runtime::start(cx);
128        registry::sync_backgrounds(cx);
129        mcp::init(mcp, cx);
130        let name = product::desktop_name(cx).to_owned();
131        open_product_window(notices, &name, cx);
132    });
133    Ok(())
134}
135
136/// Registers the app's fonts, then starts the theme, so the theme resolves
137/// the families they add. The theme's notices follow `notices`.
138fn start_theme(notices: Vec<String>, fonts: &'static [BundledFont], cx: &mut App) -> Vec<String> {
139    notices.into_iter().chain(theme::start(fonts, cx)).collect()
140}
141
142/// The services every board and agent tool reads, and the one Sign in with
143/// GitHub that uses their credentials, when the app has an OAuth App.
144fn install_services(
145    environment: ToolEnvironment,
146    tools: subspace_dashboard::Catalog,
147    config_file: std::path::PathBuf,
148    github_oauth: Option<OAuthClient>,
149    cx: &mut App,
150) {
151    cx.set_global(Services {
152        config: environment.config,
153        credentials: environment.credentials,
154        tools,
155        search: environment.search,
156        config_file,
157    });
158    subspace_dashboard::github_sign_in::init(github_oauth, cx);
159}
160
161fn install_registrations(
162    boards: Vec<BoardRegistration>,
163    configured: Option<ConfiguredBoards>,
164    registrations: registry::RegistrationSets,
165    extensions: &'static [SettingsExtension],
166    cx: &mut App,
167) {
168    registry::retain_provider(boards, configured, cx);
169    notifications::install_defaults(&registrations.included, cx);
170    cx.set_global(settings::extensions::SettingsExtensions(extensions));
171    cx.set_global(registry::IncludedBoards(registrations.included));
172    cx.set_global(registry::BoardFactories(registrations.active));
173}
174
175fn bind_keys(cx: &mut App) {
176    app::bind_keys(cx);
177    terminal::bind_keys(cx);
178    subspace_dashboard::bind_keys(cx);
179    #[cfg(debug_assertions)]
180    inspector::init(cx);
181}
182
183/// The product's configuration, with the own settings files of `boards`, and
184/// credentials, as every board and agent tool in `host` receives them, with
185/// the configuration notices as text. `sign_in` is whether the app offers
186/// Sign in with GitHub.
187pub(crate) fn tool_environment(
188    config_file: &std::path::Path,
189    boards: &[BoardRegistration],
190    host: ToolHost,
191    sign_in: bool,
192) -> (ToolEnvironment, Vec<String>) {
193    let (config, notices) =
194        config::load_with_boards(config_file, boards.iter().map(|board| board.id));
195    let credentials = Arc::new(Credentials::from_system(&config).with_sign_in_offered(sign_in));
196    let environment = ToolEnvironment {
197        config: Arc::new(config),
198        credentials,
199        search: None,
200        config_file: Some(config_file.to_owned()),
201        host,
202    };
203    (
204        environment,
205        notices.iter().map(ToString::to_string).collect(),
206    )
207}
208
209fn open_product_window(notices: Vec<String>, name: &str, cx: &mut App) {
210    let options = WindowOptions {
211        window_bounds: Some(app::window_bounds(cx)),
212        titlebar: Some(app::titlebar::options(name.to_owned())),
213        app_owns_titlebar_drag: app::titlebar::INTEGRATED,
214        ..Default::default()
215    };
216    let opened = gpui_kit::open_window(options, cx, |window, cx| {
217        cx.new(|cx| app::SubspaceApp::new(notices, window, cx))
218    });
219    if let Err(error) = opened {
220        let message = format!("{name} could not open its window: {error}");
221        subspace_core::log::Logger::new("app").record(
222            subspace_core::log::Level::Error,
223            &message,
224            &[],
225        );
226        eprintln!("{message}");
227        cx.quit();
228    }
229    #[cfg(all(debug_assertions, feature = "capture"))]
230    capture::start(cx);
231}
232
233/// Only explicit activation (Dock or notification click) creates a replacement window.
234fn ensure_product_window(cx: &mut App) {
235    let Some(runtime) = cx.try_global::<notifications::Runtime>() else {
236        return;
237    };
238    if let Some((window, app)) = runtime.window.clone()
239        && let Some(app) = app.upgrade()
240        && window
241            .update(cx, |_, window, cx| {
242                let pending = cx.global_mut::<notifications::Runtime>().pending.take();
243                if let Some(route) = pending {
244                    app.update(cx, |app, cx| app.open_notification(route, window, cx));
245                }
246                window.activate_window();
247            })
248            .is_ok()
249    {
250        return;
251    }
252    let name = product::desktop_name(cx).to_owned();
253    open_product_window(Vec::new(), &name, cx);
254}