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 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
122fn 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 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 default_order: usize::MAX,
187 artwork: D::ARTWORK,
188 connection: D::connection_settings(),
189 contracts: D::contracts(),
193 }
194 }
195}
196
197pub(crate) fn desktop_sets(
200 product: &ValidatedProduct,
201 available: &[BoardRegistration],
202 configured: Option<ConfiguredBoards>,
203 config: &Config,
204) -> Result<(RegistrationSets, Vec<String>), String> {
205 let configured = configured.map(|build| build(config)).unwrap_or_default();
206 let (configured, notices) = accept_configured(product, configured);
207 let sets = registration_sets_with(product, available, configured, config)?;
208 Ok((sets, notices))
209}
210
211pub(super) fn accept_configured(
214 product: &ValidatedProduct,
215 configured: Vec<BoardRegistration>,
216) -> (Vec<BoardRegistration>, Vec<String>) {
217 let mut notices = Vec::new();
218 let accepted = configured
219 .into_iter()
220 .filter(|board| match built_in_use(product, board.id) {
221 Some(reason) => {
222 notices.push(format!("Configured board {} ignored: {reason}", board.id));
223 false
224 }
225 None => true,
226 })
227 .collect();
228 (accepted, notices)
229}
230
231fn built_in_use(product: &ValidatedProduct, id: &str) -> Option<&'static str> {
233 product.board_id_use(id).map(|used| match used {
234 BoardIdUse::Id => "a built-in board already uses this id",
235 BoardIdUse::FormerId => {
236 "a built-in board used this id before and its saved settings are read as that board's"
237 }
238 })
239}
240
241fn intern_id(value: &str) -> &'static str {
244 static IDS: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
245 let mut ids = IDS
246 .get_or_init(Mutex::default)
247 .lock()
248 .unwrap_or_else(|poisoned| poisoned.into_inner());
249 if let Some(id) = ids.get(value) {
250 return id;
251 }
252 let id = Box::leak(value.to_owned().into_boxed_str());
253 ids.insert(id);
254 id
255}