1use 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::{BoardIdUse, ValidatedProduct};
12
13use super::{BoardRegistration, RegistrationSets, registration_sets_with};
14
15pub 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#[cfg(test)]
39pub(crate) fn forget_provider(cx: &mut App) {
40 cx.remove_global::<Provider>();
41}
42
43pub 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
57pub(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
65pub(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
82pub(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 crate::search_runtime::set_active(environment.search.as_ref(), &sets.active)?;
112 let services = cx.global_mut::<Services>();
113 services.config = config.clone();
114 services.tools = tools;
115 crate::mcp::set_boards(&sets.active, &config, cx);
116 crate::notifications::install_defaults(&sets.included, cx);
117 cx.set_global(super::IncludedBoards(sets.included));
118 cx.set_global(super::BoardFactories(sets.active));
119 super::sync_backgrounds(cx);
120 Ok(())
121}
122
123fn tool_environment(config: Arc<Config>, services: &Services) -> ToolEnvironment {
125 ToolEnvironment {
126 config,
127 credentials: Arc::clone(&services.credentials),
128 search: services.search.clone(),
129 config_file: Some(services.config_file.clone()),
130 host: ToolHost::App,
131 }
132}
133
134fn reuse_registrations(next: &mut [BoardRegistration], previous: &[BoardRegistration]) {
135 for board in next {
136 if let Some(old) = previous.iter().find(|old| old.id == board.id)
137 && configuration_matches(old, board)
138 && old.title == board.title
139 && old.description == board.description
140 && old.settings == board.settings
141 && old.icon == board.icon
142 {
143 *board = old.clone();
144 }
145 }
146}
147
148fn configuration_matches(old: &BoardRegistration, next: &BoardRegistration) -> bool {
149 match (&old.configuration, &next.configuration) {
150 (Some(old), Some(next)) => old == next,
151 (None, None) => Arc::ptr_eq(&old.create, &next.create),
152 _ => false,
153 }
154}
155
156impl BoardRegistration {
157 pub fn configured<D: Dashboard>(
161 id: &str,
162 title: &str,
163 description: &str,
164 create: impl Fn(&mut Window, &mut App) -> DashboardHandle + Send + Sync + 'static,
165 ) -> Self {
166 Self {
167 id: intern_id(id),
168 title: title.to_owned().into(),
169 description: description.to_owned().into(),
170 icon: D::ICON,
171 help: D::HELP_MARKDOWN,
172 help_images: D::HELP_IMAGES,
173 searchable: false,
174 create: Arc::new(create),
175 tools: |_| Vec::new(),
176 settings: BoardSettings {
177 sections: &[],
178 features: &[],
179 ..D::settings()
180 },
181 start_background: |_| {},
182 stop_background: |_| {},
183 retain_when_disabled: D::RETAIN_WHEN_DISABLED,
184 fields: None,
185 settings_editor: D::settings_editor(),
186 configuration: None,
187 default_order: usize::MAX,
188 artwork: D::ARTWORK,
189 connection: D::connection_settings(),
190 contracts: D::contracts(),
194 }
195 }
196}
197
198pub(crate) fn desktop_sets(
201 product: &ValidatedProduct,
202 available: &[BoardRegistration],
203 configured: Option<ConfiguredBoards>,
204 config: &Config,
205) -> Result<(RegistrationSets, Vec<String>), String> {
206 let configured = configured.map(|build| build(config)).unwrap_or_default();
207 let (configured, notices) = accept_configured(product, configured);
208 let sets = registration_sets_with(product, available, configured, config)?;
209 Ok((sets, notices))
210}
211
212pub(super) fn accept_configured(
215 product: &ValidatedProduct,
216 configured: Vec<BoardRegistration>,
217) -> (Vec<BoardRegistration>, Vec<String>) {
218 let mut notices = Vec::new();
219 let accepted = configured
220 .into_iter()
221 .filter(|board| match built_in_use(product, board.id) {
222 Some(reason) => {
223 notices.push(format!("Configured board {} ignored: {reason}", board.id));
224 false
225 }
226 None => true,
227 })
228 .collect();
229 (accepted, notices)
230}
231
232fn built_in_use(product: &ValidatedProduct, id: &str) -> Option<&'static str> {
234 product.board_id_use(id).map(|used| match used {
235 BoardIdUse::Id => "a built-in board already uses this id",
236 BoardIdUse::FormerId => {
237 "a built-in board used this id before and its saved settings are read as that board's"
238 }
239 })
240}
241
242fn intern_id(value: &str) -> &'static str {
245 static IDS: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
246 let mut ids = IDS
247 .get_or_init(Mutex::default)
248 .lock()
249 .unwrap_or_else(|poisoned| poisoned.into_inner());
250 if let Some(id) = ids.get(value) {
251 return id;
252 }
253 let id = Box::leak(value.to_owned().into_boxed_str());
254 ids.insert(id);
255 id
256}