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        product_tool_environment(&context, &files, &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/// As [`tool_environment`], for the running product in either start-up mode,
190/// and the first load of its config and state files. First it installs the
191/// product's former Space ids, so this and every later config, Settings or
192/// state read maps them (see [`subspace_core::former_ids`]).
193pub(crate) fn product_tool_environment(
194    context: &ProductContext,
195    files: &product::ProductFiles,
196    boards: &[BoardRegistration],
197    host: ToolHost,
198    sign_in: bool,
199) -> (ToolEnvironment, Vec<String>) {
200    subspace_core::former_ids::install(subspace_core::former_ids::declared(&context.product));
201    tool_environment(&files.config, boards, host, sign_in)
202}
203
204/// The product's configuration, with the own settings files of `boards`, and
205/// credentials, as every board and agent tool in `host` receives them, with
206/// the configuration notices as text. `sign_in` is whether the app offers
207/// Sign in with GitHub.
208pub(crate) fn tool_environment(
209    config_file: &std::path::Path,
210    boards: &[BoardRegistration],
211    host: ToolHost,
212    sign_in: bool,
213) -> (ToolEnvironment, Vec<String>) {
214    let (config, notices) =
215        config::load_with_boards(config_file, boards.iter().map(|board| board.id));
216    let credentials = Arc::new(Credentials::from_system(&config).with_sign_in_offered(sign_in));
217    let environment = ToolEnvironment {
218        config: Arc::new(config),
219        credentials,
220        search: None,
221        config_file: Some(config_file.to_owned()),
222        host,
223    };
224    (
225        environment,
226        notices.iter().map(ToString::to_string).collect(),
227    )
228}
229
230fn open_product_window(notices: Vec<String>, name: &str, cx: &mut App) {
231    let options = WindowOptions {
232        window_bounds: Some(app::window_bounds(cx)),
233        titlebar: Some(app::titlebar::options(name.to_owned())),
234        app_owns_titlebar_drag: app::titlebar::INTEGRATED,
235        ..Default::default()
236    };
237    let opened = gpui_kit::open_window(options, cx, |window, cx| {
238        cx.new(|cx| app::SubspaceApp::new(notices, window, cx))
239    });
240    if let Err(error) = opened {
241        let message = format!("{name} could not open its window: {error}");
242        subspace_core::log::Logger::new("app").record(
243            subspace_core::log::Level::Error,
244            &message,
245            &[],
246        );
247        eprintln!("{message}");
248        cx.quit();
249    }
250    #[cfg(all(debug_assertions, feature = "capture"))]
251    capture::start(cx);
252}
253
254/// Only explicit activation (Dock or notification click) creates a replacement window.
255fn ensure_product_window(cx: &mut App) {
256    let Some(runtime) = cx.try_global::<notifications::Runtime>() else {
257        return;
258    };
259    if let Some((window, app)) = runtime.window.clone()
260        && let Some(app) = app.upgrade()
261        && window
262            .update(cx, |_, window, cx| {
263                let pending = cx.global_mut::<notifications::Runtime>().pending.take();
264                if let Some(route) = pending {
265                    app.update(cx, |app, cx| app.open_notification(route, window, cx));
266                }
267                window.activate_window();
268            })
269            .is_ok()
270    {
271        return;
272    }
273    let name = product::desktop_name(cx).to_owned();
274    open_product_window(Vec::new(), &name, cx);
275}