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