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::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
36pub fn reload_configured_boards(window: &mut Window, cx: &mut App) -> Result<(), String> {
41 let services = cx.global::<Services>();
42 let path = services.config_file.clone();
43 let board_settings = services.config.board_settings.clone();
44 subspace_core::settings::SettingsFile::open(&path).map_err(|error| error.to_string())?;
45 let (mut config, _) = subspace_core::config::load(&path);
46 config.board_settings = board_settings;
47 apply_board_selection(config, window, cx)
48}
49
50pub(crate) fn apply_running_config(window: &mut Window, cx: &mut App) -> Result<(), String> {
54 let config = (*cx.global::<Services>().config).clone();
55 apply_board_selection(config, window, cx)
56}
57
58pub(crate) fn apply_board_selection(
62 config: Config,
63 window: &mut Window,
64 cx: &mut App,
65) -> Result<(), String> {
66 let mut sets = selected_sets(&config, cx)?;
67 let previous = super::included_registrations(cx);
68 reuse_registrations(&mut sets.included, &previous);
69 reuse_registrations(&mut sets.active, &previous);
70 install_sets(config, sets, cx)?;
71 window.refresh();
72 Ok(())
73}
74
75fn selected_sets(config: &Config, cx: &App) -> Result<RegistrationSets, String> {
76 let provider = cx
77 .try_global::<Provider>()
78 .ok_or("No configured board provider is retained.")?;
79 let product = &cx.global::<subspace_dashboard::CurrentProduct>().0.product;
80 let (sets, notices) = desktop_sets(product, &provider.available, provider.configured, config)?;
81 if notices.is_empty() {
82 Ok(sets)
83 } else {
84 Err(notices.join("\n"))
85 }
86}
87
88fn install_sets(config: Config, sets: RegistrationSets, cx: &mut App) -> Result<(), String> {
89 let config = Arc::new(config);
90 let environment = tool_environment(config.clone(), cx.global::<Services>());
91 let tools = super::tool_catalog(&sets.active, &environment)?;
92 let services = cx.global_mut::<Services>();
93 services.config = config.clone();
94 services.tools = tools;
95 crate::mcp::set_boards(&sets.active, &config, cx);
96 crate::notifications::install_defaults(&sets.included, cx);
97 cx.set_global(super::IncludedBoards(sets.included));
98 cx.set_global(super::BoardFactories(sets.active));
99 super::sync_backgrounds(cx);
100 Ok(())
101}
102
103fn tool_environment(config: Arc<Config>, services: &Services) -> ToolEnvironment {
105 ToolEnvironment {
106 config,
107 credentials: Arc::clone(&services.credentials),
108 search: services.search.clone(),
109 config_file: Some(services.config_file.clone()),
110 host: ToolHost::App,
111 }
112}
113
114fn reuse_registrations(next: &mut [BoardRegistration], previous: &[BoardRegistration]) {
115 for board in next {
116 if let Some(old) = previous.iter().find(|old| old.id == board.id)
117 && configuration_matches(old, board)
118 && old.title == board.title
119 && old.description == board.description
120 && old.settings == board.settings
121 && old.icon == board.icon
122 {
123 *board = old.clone();
124 }
125 }
126}
127
128fn configuration_matches(old: &BoardRegistration, next: &BoardRegistration) -> bool {
129 match (&old.configuration, &next.configuration) {
130 (Some(old), Some(next)) => old == next,
131 (None, None) => Arc::ptr_eq(&old.create, &next.create),
132 _ => false,
133 }
134}
135
136impl BoardRegistration {
137 pub fn configured<D: Dashboard>(
141 id: &str,
142 title: &str,
143 description: &str,
144 create: impl Fn(&mut Window, &mut App) -> DashboardHandle + Send + Sync + 'static,
145 ) -> Self {
146 Self {
147 id: intern_id(id),
148 title: title.to_owned().into(),
149 description: description.to_owned().into(),
150 icon: D::ICON,
151 help: D::HELP_MARKDOWN,
152 help_images: D::HELP_IMAGES,
153 searchable: false,
154 create: Arc::new(create),
155 tools: |_| Vec::new(),
156 settings: BoardSettings {
157 sections: &[],
158 features: &[],
159 ..D::settings()
160 },
161 start_background: |_| {},
162 stop_background: |_| {},
163 retain_when_disabled: D::RETAIN_WHEN_DISABLED,
164 fields: None,
165 settings_editor: D::settings_editor(),
166 configuration: None,
167 artwork: D::ARTWORK,
168 connection: D::connection_settings(),
169 contracts: Default::default(),
170 }
171 }
172}
173
174pub(crate) fn desktop_sets(
177 product: &ValidatedProduct,
178 available: &[BoardRegistration],
179 configured: Option<ConfiguredBoards>,
180 config: &Config,
181) -> Result<(RegistrationSets, Vec<String>), String> {
182 let configured = configured.map(|build| build(config)).unwrap_or_default();
183 let (configured, notices) = accept_configured(product, configured);
184 let sets = registration_sets_with(product, available, configured, config)?;
185 Ok((sets, notices))
186}
187
188pub(super) fn accept_configured(
191 product: &ValidatedProduct,
192 configured: Vec<BoardRegistration>,
193) -> (Vec<BoardRegistration>, Vec<String>) {
194 let (rejected, accepted): (Vec<_>, Vec<_>) = configured.into_iter().partition(|board| {
195 product
196 .boards
197 .iter()
198 .any(|built_in| built_in.id.as_str() == board.id)
199 });
200 let notices = rejected
201 .iter()
202 .map(|board| {
203 format!(
204 "Configured board {} ignored: a built-in board already uses this id",
205 board.id
206 )
207 })
208 .collect();
209 (accepted, notices)
210}
211
212fn intern_id(value: &str) -> &'static str {
215 static IDS: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
216 let mut ids = IDS
217 .get_or_init(Mutex::default)
218 .lock()
219 .unwrap_or_else(|poisoned| poisoned.into_inner());
220 if let Some(id) = ids.get(value) {
221 return id;
222 }
223 let id = Box::leak(value.to_owned().into_boxed_str());
224 ids.insert(id);
225 id
226}