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