Skip to main content

subspace_shell/registry/
configured.rs

1//! Boards an app builds from its config file, after the boards its
2//! descriptor lists.
3
4use std::sync::{Arc, Mutex, OnceLock};
5
6use gpui_kit::{App, Global, Window};
7use subspace_agent_tools::{ToolEnvironment, ToolHost};
8use subspace_core::config::Config;
9use subspace_dashboard::settings::BoardSettings;
10use subspace_dashboard::{Dashboard, DashboardHandle, Services};
11use subspace_product::ValidatedProduct;
12
13use super::{BoardRegistration, RegistrationSets, registration_sets_with};
14
15/// The boards an app builds from its config file, such as `webBoards`.
16/// Apps without one show only the boards their descriptor lists.
17pub type ConfiguredBoards = fn(&Config) -> Vec<BoardRegistration>;
18
19pub(crate) struct Provider {
20    available: Vec<BoardRegistration>,
21    configured: Option<ConfiguredBoards>,
22}
23impl Global for Provider {}
24
25pub(crate) fn retain_provider(
26    available: Vec<BoardRegistration>,
27    configured: Option<ConfiguredBoards>,
28    cx: &mut App,
29) {
30    cx.set_global(Provider {
31        available,
32        configured,
33    });
34}
35
36/// Drops the retained provider, so the board set cannot be rebuilt and a
37/// board choice applies only after a restart.
38#[cfg(test)]
39pub(crate) fn forget_provider(cx: &mut App) {
40    cx.remove_global::<Provider>();
41}
42
43/// Reloads the configured provider after a checked, confirmed config write.
44/// Shells observe the factory set and reconcile their retained views and editors.
45/// Native boards' own files are not part of that write, so their settings stay.
46// qual:api
47pub fn reload_configured_boards(window: &mut Window, cx: &mut App) -> Result<(), String> {
48    let services = cx.global::<Services>();
49    let path = services.config_file.clone();
50    let board_settings = services.config.board_settings.clone();
51    subspace_core::settings::SettingsFile::open(&path).map_err(|error| error.to_string())?;
52    let (mut config, _) = subspace_core::config::load(&path);
53    config.board_settings = board_settings;
54    apply_board_selection(config, window, cx)
55}
56
57/// Rebuilds the agent tools and the MCP catalog from the config the app runs
58/// with now, after a board changed it (`DashboardEvent::ConfigChanged`), such
59/// as the favourite repositories.
60pub(crate) fn apply_running_config(window: &mut Window, cx: &mut App) -> Result<(), String> {
61    let config = (*cx.global::<Services>().config).clone();
62    apply_board_selection(config, window, cx)
63}
64
65/// Applies the boards `config` enables without a restart: shells add and
66/// remove tabs, background work starts and stops, and chat and MCP serve
67/// the tools of the active boards. Unchanged registrations keep their views.
68pub(crate) fn apply_board_selection(
69    config: Config,
70    window: &mut Window,
71    cx: &mut App,
72) -> Result<(), String> {
73    let mut sets = selected_sets(&config, cx)?;
74    let previous = super::included_registrations(cx);
75    reuse_registrations(&mut sets.included, &previous);
76    reuse_registrations(&mut sets.active, &previous);
77    install_sets(config, sets, cx)?;
78    window.refresh();
79    Ok(())
80}
81
82/// Whether applying `config` would leave at least one board active, as
83/// [`apply_board_selection`] or the next start builds the set. Boards the
84/// config file defines but cannot be shown do not count.
85pub(crate) fn enables_a_board(config: &Config, cx: &App) -> Result<bool, String> {
86    let provider = cx
87        .try_global::<Provider>()
88        .ok_or("No configured board provider is retained.")?;
89    let product = &cx.global::<subspace_dashboard::CurrentProduct>().0.product;
90    let (sets, _) = desktop_sets(product, &provider.available, provider.configured, config)?;
91    Ok(!sets.active.is_empty())
92}
93
94fn selected_sets(config: &Config, cx: &App) -> Result<RegistrationSets, String> {
95    let provider = cx
96        .try_global::<Provider>()
97        .ok_or("No configured board provider is retained.")?;
98    let product = &cx.global::<subspace_dashboard::CurrentProduct>().0.product;
99    let (sets, notices) = desktop_sets(product, &provider.available, provider.configured, config)?;
100    if notices.is_empty() {
101        Ok(sets)
102    } else {
103        Err(notices.join("\n"))
104    }
105}
106
107fn install_sets(config: Config, sets: RegistrationSets, cx: &mut App) -> Result<(), String> {
108    let config = Arc::new(config);
109    let environment = tool_environment(config.clone(), cx.global::<Services>());
110    let tools = super::tool_catalog(&sets.active, &environment)?;
111    let services = cx.global_mut::<Services>();
112    services.config = config.clone();
113    services.tools = tools;
114    crate::mcp::set_boards(&sets.active, &config, cx);
115    crate::notifications::install_defaults(&sets.included, cx);
116    cx.set_global(super::IncludedBoards(sets.included));
117    cx.set_global(super::BoardFactories(sets.active));
118    super::sync_backgrounds(cx);
119    Ok(())
120}
121
122/// The environment chat tools receive, with `config` as the app now runs it.
123fn tool_environment(config: Arc<Config>, services: &Services) -> ToolEnvironment {
124    ToolEnvironment {
125        config,
126        credentials: Arc::clone(&services.credentials),
127        search: services.search.clone(),
128        config_file: Some(services.config_file.clone()),
129        host: ToolHost::App,
130    }
131}
132
133fn reuse_registrations(next: &mut [BoardRegistration], previous: &[BoardRegistration]) {
134    for board in next {
135        if let Some(old) = previous.iter().find(|old| old.id == board.id)
136            && configuration_matches(old, board)
137            && old.title == board.title
138            && old.description == board.description
139            && old.settings == board.settings
140            && old.icon == board.icon
141        {
142            *board = old.clone();
143        }
144    }
145}
146
147fn configuration_matches(old: &BoardRegistration, next: &BoardRegistration) -> bool {
148    match (&old.configuration, &next.configuration) {
149        (Some(old), Some(next)) => old == next,
150        (None, None) => Arc::ptr_eq(&old.create, &next.create),
151        _ => false,
152    }
153}
154
155impl BoardRegistration {
156    /// One instance of board type `D` that the config file defines, such as
157    /// a web board. Instances have no agent tools, search, features or
158    /// background work of their own, so several can share one type.
159    pub fn configured<D: Dashboard>(
160        id: &str,
161        title: &str,
162        description: &str,
163        create: impl Fn(&mut Window, &mut App) -> DashboardHandle + Send + Sync + 'static,
164    ) -> Self {
165        Self {
166            id: intern_id(id),
167            title: title.to_owned().into(),
168            description: description.to_owned().into(),
169            icon: D::ICON,
170            help: D::HELP_MARKDOWN,
171            help_images: D::HELP_IMAGES,
172            searchable: false,
173            create: Arc::new(create),
174            tools: |_| Vec::new(),
175            settings: BoardSettings {
176                sections: &[],
177                features: &[],
178                ..D::settings()
179            },
180            start_background: |_| {},
181            stop_background: |_| {},
182            retain_when_disabled: D::RETAIN_WHEN_DISABLED,
183            fields: None,
184            settings_editor: D::settings_editor(),
185            configuration: None,
186            artwork: D::ARTWORK,
187            connection: D::connection_settings(),
188            // Every instance declares its type's roles under its own ID. A
189            // configured type must not respond: two instances would be two
190            // responders, which registration rejects.
191            contracts: D::contracts(),
192        }
193    }
194}
195
196/// The desktop's boards: the product's own and the app's configured boards,
197/// with a notice for each configured board left out.
198pub(crate) fn desktop_sets(
199    product: &ValidatedProduct,
200    available: &[BoardRegistration],
201    configured: Option<ConfiguredBoards>,
202    config: &Config,
203) -> Result<(RegistrationSets, Vec<String>), String> {
204    let configured = configured.map(|build| build(config)).unwrap_or_default();
205    let (configured, notices) = accept_configured(product, configured);
206    let sets = registration_sets_with(product, available, configured, config)?;
207    Ok((sets, notices))
208}
209
210/// The configured boards whose ids the product does not already use, with
211/// a notice for each one left out.
212pub(super) fn accept_configured(
213    product: &ValidatedProduct,
214    configured: Vec<BoardRegistration>,
215) -> (Vec<BoardRegistration>, Vec<String>) {
216    let (rejected, accepted): (Vec<_>, Vec<_>) = configured.into_iter().partition(|board| {
217        product
218            .boards
219            .iter()
220            .any(|built_in| built_in.id.as_str() == board.id)
221    });
222    let notices = rejected
223        .iter()
224        .map(|board| {
225            format!(
226                "Configured board {} ignored: a built-in board already uses this id",
227                board.id
228            )
229        })
230        .collect();
231    (accepted, notices)
232}
233
234/// Agent/MCP routing uses static IDs. Retain each ID once per process, never
235/// titles, descriptions or a fresh identity allocation on each reload.
236fn intern_id(value: &str) -> &'static str {
237    static IDS: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
238    let mut ids = IDS
239        .get_or_init(Mutex::default)
240        .lock()
241        .unwrap_or_else(|poisoned| poisoned.into_inner());
242    if let Some(id) = ids.get(value) {
243        return id;
244    }
245    let id = Box::leak(value.to_owned().into_boxed_str());
246    ids.insert(id);
247    id
248}