1mod background;
4mod configuration;
5mod configured;
6mod settings;
7mod validation;
8
9use gpui_kit::{App, Global, Window};
10use std::borrow::Cow;
11use std::sync::Arc;
12use subspace_agent_tools::{BoardDoc, Catalog, ToolEnvironment, ToolProvider};
13use subspace_core::config::Config;
14use subspace_dashboard::settings::{BoardFields, BoardSettings};
15use subspace_dashboard::{Dashboard, DashboardHandle};
16use subspace_product::ValidatedProduct;
17
18pub(crate) use background::sync_backgrounds;
19pub use configuration::BoardConfiguration;
20pub use configured::ConfiguredBoards;
21pub use configured::reload_configured_boards;
22pub(crate) use configured::retain_provider;
23pub(crate) use configured::{apply_board_selection, apply_running_config, desktop_sets};
24
25pub type BoardFactory = Arc<dyn Fn(&mut Window, &mut App) -> DashboardHandle + Send + Sync>;
28pub type BoardFieldSource = Arc<dyn Fn() -> Option<BoardFields> + Send + Sync>;
29
30#[derive(Clone)]
31#[non_exhaustive]
32pub struct BoardRegistration {
33 pub id: &'static str,
34 pub title: Cow<'static, str>,
35 pub description: Cow<'static, str>,
36 pub icon: Option<&'static str>,
38 pub help: &'static str,
40 pub help_images: &'static [subspace_dashboard::HelpImage],
41 pub searchable: bool,
42 pub create: BoardFactory,
43 pub tools: ToolProvider,
45 pub settings: BoardSettings,
47 pub fields: Option<BoardFieldSource>,
49 pub settings_editor: Option<subspace_dashboard::settings::SettingsEditorFactory>,
50 pub start_background: fn(&mut App),
51 pub stop_background: fn(&mut App),
52 pub retain_when_disabled: bool,
55 pub configuration: Option<BoardConfiguration>,
56 pub(crate) artwork: subspace_dashboard::BoardArtwork,
57 pub(crate) connection: subspace_dashboard::settings::ConnectionSettings,
58 pub contracts: subspace_dashboard::contracts::BoardContracts,
60}
61
62impl BoardRegistration {
63 pub fn new<D: Dashboard>() -> Self {
64 Self {
65 id: D::ID,
66 title: D::TITLE.into(),
67 description: D::DESCRIPTION.into(),
68 icon: D::ICON,
69 help: D::HELP_MARKDOWN,
70 help_images: D::HELP_IMAGES,
71 searchable: D::SEARCHABLE,
72 create: Arc::new(DashboardHandle::new::<D>),
73 tools: D::agent_tools,
74 settings: D::settings(),
75 fields: None,
76 settings_editor: D::settings_editor(),
77 start_background: D::start_background,
78 stop_background: D::stop_background,
79 retain_when_disabled: D::RETAIN_WHEN_DISABLED,
80 configuration: None,
81 artwork: D::ARTWORK,
82 connection: D::connection_settings(),
83 contracts: D::contracts(),
84 }
85 }
86
87 pub fn description(mut self, description: &'static str) -> Self {
88 self.description = description.into();
89 self
90 }
91
92 pub fn artwork(&self) -> subspace_dashboard::BoardArtwork {
93 self.artwork
94 }
95
96 pub fn connection_settings(&self) -> subspace_dashboard::settings::ConnectionSettings {
97 self.connection
98 }
99
100 pub fn doc(&self) -> Option<BoardDoc> {
101 let Cow::Borrowed(title) = &self.title else {
102 return None;
103 };
104 Some(BoardDoc {
105 id: self.id,
106 title,
107 markdown: self.help,
108 images: self.help_images,
109 })
110 }
111}
112
113pub(crate) struct BoardFactories(pub Vec<BoardRegistration>);
114
115impl Global for BoardFactories {}
116
117pub(crate) struct IncludedBoards(pub Vec<BoardRegistration>);
119
120impl Global for IncludedBoards {}
121
122pub(crate) struct RegistrationSets {
123 pub included: Vec<BoardRegistration>,
124 pub active: Vec<BoardRegistration>,
125}
126
127pub(crate) fn selected_registrations(
131 product: &ValidatedProduct,
132 available: &[BoardRegistration],
133 config: &Config,
134) -> Result<Vec<BoardRegistration>, String> {
135 Ok(registration_sets(product, available, config)?.active)
136}
137
138pub(crate) fn registration_sets(
139 product: &ValidatedProduct,
140 available: &[BoardRegistration],
141 config: &Config,
142) -> Result<RegistrationSets, String> {
143 registration_sets_with(product, available, Vec::new(), config)
144}
145
146pub(crate) fn registration_sets_with(
149 product: &ValidatedProduct,
150 available: &[BoardRegistration],
151 configured: Vec<BoardRegistration>,
152 config: &Config,
153) -> Result<RegistrationSets, String> {
154 reject_duplicate_registrations(available)?;
155 let mut included = product
156 .boards
157 .iter()
158 .map(|board| {
159 available
160 .iter()
161 .find(|registration| registration.id == board.id.as_str())
162 .cloned()
163 .ok_or_else(|| format!("no GUI provider for board {}", board.id.as_str()))
164 })
165 .collect::<Result<Vec<_>, _>>()?;
166 included.extend(configured);
167 let order = normalize_order(&included, &config.board_order);
168 included.sort_by_key(|board| {
169 order
170 .iter()
171 .position(|id| id == board.id)
172 .unwrap_or(usize::MAX)
173 });
174 validation::validate(&included)?;
175 let active = included
176 .iter()
177 .filter(|board| {
178 let default_enabled = product
179 .boards
180 .iter()
181 .find(|descriptor| descriptor.id.as_str() == board.id)
182 .is_none_or(|descriptor| descriptor.default_enabled);
183 config.board_enabled_or(board.id, default_enabled)
184 })
185 .cloned()
186 .collect();
187 Ok(RegistrationSets { included, active })
188}
189
190pub(crate) fn normalize_order(boards: &[BoardRegistration], saved: &[String]) -> Vec<String> {
191 let available: Vec<_> = boards.iter().map(|board| board.id).collect();
192 let saved: Vec<_> = saved.iter().map(String::as_str).collect();
193 let mut result = Vec::with_capacity(available.len());
194 for id in saved {
195 if let Some(found) = available.iter().find(|candidate| **candidate == id)
196 && !result.iter().any(|saved| saved == found)
197 {
198 result.push((*found).to_owned());
199 }
200 }
201 for id in available {
202 if !result.iter().any(|saved| saved == id) {
203 result.push(id.to_owned());
204 }
205 }
206 result
207}
208
209fn reject_duplicate_registrations(available: &[BoardRegistration]) -> Result<(), String> {
210 let mut ids = std::collections::HashSet::new();
211 for board in available {
212 if !ids.insert(board.id) {
213 return Err(format!("duplicate GUI provider for board {}", board.id));
214 }
215 }
216 Ok(())
217}
218
219pub(crate) fn tool_catalog(
221 boards: &[BoardRegistration],
222 environment: &ToolEnvironment,
223) -> Result<Catalog, String> {
224 let providers: Vec<ToolProvider> = boards.iter().map(|board| board.tools).collect();
225 let docs: Vec<BoardDoc> = boards.iter().filter_map(BoardRegistration::doc).collect();
226 subspace_agent_tools::catalog_with_help(&providers, docs, environment)
227}
228
229pub(crate) fn mcp_boards(boards: &[BoardRegistration]) -> Vec<subspace_mcp::Board> {
231 boards
232 .iter()
233 .map(|board| subspace_mcp::Board {
234 id: board.id,
235 title: match &board.title {
237 Cow::Borrowed(title) => title,
238 Cow::Owned(_) => board.id,
239 },
240 description: match &board.description {
241 Cow::Borrowed(description) => description,
242 Cow::Owned(_) => "",
243 },
244 help: board.help,
245 help_images: board.help_images,
246 tools: board.tools,
247 })
248 .collect()
249}
250
251pub(crate) fn included_registrations(cx: &App) -> Vec<BoardRegistration> {
254 cx.try_global::<IncludedBoards>()
255 .map(|boards| boards.0.clone())
256 .or_else(|| {
257 cx.try_global::<BoardFactories>()
258 .map(|boards| boards.0.clone())
259 })
260 .unwrap_or_default()
261}
262
263pub fn dashboards(window: &mut Window, cx: &mut App) -> Vec<DashboardHandle> {
264 let factories = cx.global::<BoardFactories>().0.clone();
265 factories
266 .iter()
267 .map(|registration| {
268 let mut dashboard = (registration.create)(window, cx);
269 dashboard.id = registration.id;
270 dashboard.title = registration.title.to_string().into();
271 dashboard.description = registration.description.to_string().into();
272 dashboard
273 })
274 .collect()
275}
276
277#[cfg(test)]
278mod tests {
279 use super::{
280 BoardRegistration, mcp_boards, registration_sets, selected_registrations, tool_catalog,
281 };
282 use gpui_kit::{
283 App, Context, EventEmitter, FocusHandle, Focusable, IntoElement, Render, Window, div,
284 };
285 use std::collections::BTreeMap;
286 use std::sync::Arc;
287 use subspace_agent_tools::{AgentTool, HELP_TOOL, ToolEnvironment};
288 use subspace_core::config::Config;
289 use subspace_core::features::{FeatureSpec, FeatureStage};
290 use subspace_dashboard::settings::{BoardSettings, SettingsSection};
291 use subspace_dashboard::{Dashboard, DashboardEvent, DashboardHandle};
292 use subspace_lucide::IconName;
293 use subspace_product::{BoardDescriptor, validate_product};
294
295 const GRADUATED: FeatureSpec = FeatureSpec {
296 id: "board.future-board.regular",
297 title: "Regular feature",
298 description: "A graduated fixture feature.",
299 stage: FeatureStage::Stable,
300 default_enabled: true,
301 toggleable: true,
302 };
303 const REMOVED: FeatureSpec = FeatureSpec {
304 id: "board.future-board.removed",
305 title: "Removed feature",
306 description: "A removed fixture feature.",
307 stage: FeatureStage::Removed,
308 default_enabled: false,
309 toggleable: false,
310 };
311 const EXPERIMENT: FeatureSpec = FeatureSpec {
312 id: "board.future-board.preview",
313 title: "Preview",
314 description: "A nested fixture experiment.",
315 stage: FeatureStage::Experimental,
316 default_enabled: false,
317 toggleable: true,
318 };
319 const NESTED: &[SettingsSection] = &[SettingsSection {
320 id: "nested",
321 title: "Nested",
322 icon: IconName::Settings,
323 children: &[],
324 features: &[EXPERIMENT],
325 }];
326 const SECTIONS: &[SettingsSection] = &[SettingsSection {
327 id: "advanced",
328 title: "Advanced",
329 icon: IconName::Settings,
330 children: NESTED,
331 features: &[],
332 }];
333
334 struct FutureBoard {
335 focus: FocusHandle,
336 }
337
338 impl EventEmitter<DashboardEvent> for FutureBoard {}
339
340 impl Focusable for FutureBoard {
341 fn focus_handle(&self, _: &App) -> FocusHandle {
342 self.focus.clone()
343 }
344 }
345
346 impl Render for FutureBoard {
347 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
348 div()
349 }
350 }
351
352 impl Dashboard for FutureBoard {
353 const ID: &'static str = "future-board";
354 const ARTWORK: subspace_dashboard::BoardArtwork =
355 subspace_dashboard::BoardArtwork::new(&[("fixture/board.svg", b"board artwork")]);
356 const TITLE: &'static str = "Future Board";
357 const ICON: Option<&'static str> = Some("future.svg");
358
359 fn settings() -> BoardSettings {
360 BoardSettings {
361 icon: Some(IconName::Settings),
362 description: "",
363 sections: SECTIONS,
364 features: &[GRADUATED, REMOVED],
365 notifications: false,
366 notification_defaults: Default::default(),
367 background_updates: false,
368 store_by_default: false,
369 live_features: &[],
370 }
371 }
372
373 fn connection_settings() -> subspace_dashboard::settings::ConnectionSettings {
374 subspace_dashboard::settings::ConnectionSettings::new(&[
375 subspace_dashboard::settings::ConnectionField::GitHubCredentials,
376 ])
377 }
378
379 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
380 panic!(
381 "registration must not construct FutureBoard: {:?}",
382 cx.entity_id()
383 )
384 }
385
386 fn reload(&mut self, _: &mut Window, _: &mut Context<Self>) {}
387 }
388
389 fn unused_factory(_: &mut Window, _: &mut App) -> DashboardHandle {
390 panic!("selection tests must not initialize a dashboard")
391 }
392
393 fn no_tools(_: &ToolEnvironment) -> Vec<Arc<dyn AgentTool>> {
394 Vec::new()
395 }
396
397 #[test]
398 fn mcp_catalog_keeps_static_titles_and_uses_stable_ids_for_editable_titles() {
399 const IMAGES: &[subspace_dashboard::HelpImage] = &[subspace_dashboard::HelpImage::new(
400 "guide",
401 "Guide",
402 "image/png",
403 b"test image",
404 )];
405 let mut native = BoardRegistration::new::<FutureBoard>();
406 native.help_images = IMAGES;
407 let mut configured = board("configured-fixture");
408 configured.title = String::from("Editable title").into();
409 configured.description = String::from("Editable description").into();
410 assert_eq!(native.doc().unwrap().images, IMAGES);
411 assert!(configured.doc().is_none());
412 let catalog = mcp_boards(&[native.description("Future work"), configured]);
413 assert_eq!(catalog.len(), 2);
414 assert_eq!(catalog[0].title, "Future Board");
415 assert_eq!(catalog[0].description, "Future work");
416 assert_eq!(catalog[1].description, "");
417 assert_eq!(catalog[0].help_images, IMAGES);
418 assert_eq!(catalog[1].id, "configured-fixture");
419 assert_eq!(catalog[1].title, "configured-fixture");
420 }
421
422 #[test]
423 fn native_and_configured_registrations_capture_the_boards_artwork() {
424 let native = BoardRegistration::new::<FutureBoard>();
425 let configured = BoardRegistration::configured::<FutureBoard>(
426 "configured-art",
427 "Artwork",
428 "Fixture",
429 unused_factory,
430 );
431 assert_eq!(native.artwork().entries(), FutureBoard::ARTWORK.entries());
432 assert_eq!(configured.artwork().entries(), native.artwork().entries());
433 assert_eq!(
434 native.connection_settings(),
435 FutureBoard::connection_settings()
436 );
437 assert_eq!(
438 configured.connection_settings(),
439 native.connection_settings()
440 );
441 }
442
443 #[test]
444 fn artwork_collisions_keep_product_first_then_declaration_and_registration_order() {
445 use gpui_kit::AssetSource as _;
446 use subspace_dashboard::BoardArtwork;
447 const FIRST: &[(&str, &[u8])] = &[("fixture/collision", b"first")];
448 const SECOND: &[(&str, &[u8])] = &[("fixture/collision", b"second")];
449 let mut late = board("late");
450 late.artwork = BoardArtwork::new(SECOND).with_order(2);
451 let mut early = board("early");
452 early.artwork = BoardArtwork::new(FIRST).with_order(1);
453 let source = crate::assets::Assets::new(&[], &[late.clone(), early.clone()]);
454 assert_eq!(
455 source.load("fixture/collision").unwrap().unwrap().as_ref(),
456 b"first"
457 );
458 assert_eq!(source.list("fixture/").unwrap().len(), 2);
459 let mut tied = late;
460 tied.artwork = BoardArtwork::new(SECOND).with_order(1);
461 let source = crate::assets::Assets::new(&[], &[tied.clone(), early.clone()]);
462 assert_eq!(
463 source.load("fixture/collision").unwrap().unwrap().as_ref(),
464 b"second"
465 );
466 let source = crate::assets::Assets::new(FIRST, &[tied, early]);
467 assert_eq!(
468 source.load("fixture/collision").unwrap().unwrap().as_ref(),
469 b"first"
470 );
471 }
472
473 fn board(id: &'static str) -> BoardRegistration {
474 BoardRegistration {
475 id,
476 title: id.into(),
477 description: id.into(),
478 icon: None,
479 help: "",
480 help_images: &[],
481 searchable: false,
482 create: Arc::new(unused_factory),
483 tools: no_tools,
484 settings: BoardSettings::default(),
485 settings_editor: None,
486 fields: None,
487 start_background: |_| {},
488 stop_background: |_| {},
489 retain_when_disabled: false,
490 configuration: None,
491 artwork: subspace_dashboard::BoardArtwork::default(),
492 connection: Default::default(),
493 contracts: Default::default(),
494 }
495 }
496
497 fn documented(id: &'static str) -> BoardRegistration {
498 BoardRegistration {
499 help: "# Help",
500 ..board(id)
501 }
502 }
503
504 fn config(boards: &[(&str, bool)]) -> Config {
505 Config {
506 boards: boards
507 .iter()
508 .map(|(id, enabled)| ((*id).to_owned(), *enabled))
509 .collect::<BTreeMap<String, bool>>(),
510 ..Default::default()
511 }
512 }
513
514 #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
515 #[test]
516 fn board_lab_defaults_off_in_release_builds_and_keeps_a_saved_choice() {
517 let mut descriptor = subspace_product::fixture::descriptor();
518 descriptor.boards.retain(|board| board.id == "board-lab");
519 assert_eq!(descriptor.boards.len(), 1);
520 let product = validate_product(&descriptor).unwrap();
521 let available = [board("board-lab")];
522 let initial = registration_sets(&product, &available, &Config::default()).unwrap();
523 assert_eq!(ids(&initial.included), ["board-lab"]);
524 assert_eq!(initial.active.is_empty(), !cfg!(debug_assertions));
525 let enabled =
526 selected_registrations(&product, &available, &config(&[("board-lab", true)])).unwrap();
527 assert_eq!(ids(&enabled), ["board-lab"]);
528 let disabled =
529 selected_registrations(&product, &available, &config(&[("board-lab", false)])).unwrap();
530 assert!(disabled.is_empty());
531 }
532
533 fn ids(boards: &[BoardRegistration]) -> Vec<&'static str> {
534 boards.iter().map(|board| board.id).collect()
535 }
536
537 fn product(boards: &[(&str, bool)]) -> subspace_product::ValidatedProduct {
538 let mut descriptor = subspace_product::fixture::descriptor();
539 descriptor.boards = boards
540 .iter()
541 .map(|(id, default_enabled)| BoardDescriptor {
542 id: (*id).into(),
543 aliases: Vec::new(),
544 default_enabled: *default_enabled,
545 })
546 .collect();
547 validate_product(&descriptor).unwrap()
548 }
549
550 fn future_product() -> subspace_product::ValidatedProduct {
551 product(&[("future-board", true)])
552 }
553
554 #[test]
555 fn factories_follow_selection_order_and_reject_missing_providers() {
556 let available = [board("github"), board("irc")];
557 let selected = selected_registrations(
558 &product(&[("irc", true), ("github", true)]),
559 &available,
560 &Config::default(),
561 )
562 .unwrap();
563 assert_eq!(ids(&selected), ["irc", "github"]);
564 let known = subspace_product::fixture::products().unwrap();
565 let missing = selected_registrations(&known[0], &available, &Config::default());
566 assert!(matches!(missing, Err(error) if error.contains("github-copilot-agents")));
567 }
568
569 #[test]
570 fn saved_order_is_normalized_before_enablement_filtering() {
571 let product = product(&[("irc", true), ("github", true)]);
572 let available = [board("irc"), board("github")];
573 let config = Config {
574 board_order: vec!["github".into(), "github".into(), "unknown".into()],
575 ..Default::default()
576 };
577 let sets = registration_sets(&product, &available, &config).unwrap();
578 assert_eq!(ids(&sets.included), ["github", "irc"]);
579 assert_eq!(ids(&sets.active), ["github", "irc"]);
580 }
581
582 #[test]
583 fn the_config_file_leaves_out_disabled_boards_and_cannot_add_others() {
584 let product = product(&[("irc", true)]);
585 let available = [board("github"), board("irc")];
586 let off = config(&[("irc", false), ("github", true), ("unknown", true)]);
587 let selected = selected_registrations(&product, &available, &off).unwrap();
588 assert!(selected.is_empty(), "{:?}", ids(&selected));
589 let on = config(&[("irc", true)]);
590 assert_eq!(
591 ids(&selected_registrations(&product, &available, &on).unwrap()),
592 ["irc"]
593 );
594 }
595
596 #[test]
597 fn a_disabled_board_still_needs_settings_metadata() {
598 let off = config(&[("irc", false)]);
599 let result = selected_registrations(&product(&[("irc", true)]), &[board("github")], &off);
600 assert!(matches!(result, Err(error) if error.contains("irc")));
601 }
602
603 #[test]
604 fn future_board_registration_keeps_disabled_metadata_and_nested_sections() {
605 let registration = BoardRegistration::new::<FutureBoard>();
606 let sets = registration_sets(
607 &future_product(),
608 &[registration, board("excluded")],
609 &config(&[("future-board", false)]),
610 )
611 .unwrap();
612 assert!(sets.active.is_empty());
613 assert_eq!(ids(&sets.included), ["future-board"]);
614 let settings = sets.included[0].settings;
615 assert_eq!(sets.included[0].icon, Some("future.svg"));
616 assert_eq!(settings.features, &[GRADUATED, REMOVED]);
617 assert_eq!(settings.sections[0].children[0].features, &[EXPERIMENT]);
618 }
619
620 #[test]
621 fn board_defaults_allow_missing_and_explicit_config_choices() {
622 let product = product(&[("irc", false)]);
623 let available = [board("irc")];
624
625 assert!(
626 registration_sets(&product, &available, &Config::default())
627 .unwrap()
628 .active
629 .is_empty()
630 );
631 assert_eq!(
632 ids(
633 ®istration_sets(&product, &available, &config(&[("irc", true)]))
634 .unwrap()
635 .active
636 ),
637 ["irc"]
638 );
639 assert!(
640 registration_sets(&product, &available, &config(&[("irc", false)]))
641 .unwrap()
642 .active
643 .is_empty()
644 );
645 }
646
647 #[test]
648 fn invalid_owner_duplicate_keys_and_duplicate_registrations_are_rejected() {
649 let product = future_product();
650 let mut wrong_owner = BoardRegistration::new::<FutureBoard>();
651 wrong_owner.settings.features = &[FeatureSpec {
652 id: "board.other.preview",
653 ..EXPERIMENT
654 }];
655 assert!(registration_sets(&product, &[wrong_owner], &Config::default()).is_err());
656
657 let mut duplicate = BoardRegistration::new::<FutureBoard>();
658 duplicate.settings.features = &[EXPERIMENT];
659 assert!(registration_sets(&product, &[duplicate], &Config::default()).is_err());
660
661 let registration = BoardRegistration::new::<FutureBoard>();
662 assert!(
663 registration_sets(
664 &product,
665 &[registration.clone(), registration],
666 &Config::default()
667 )
668 .is_err()
669 );
670 }
671
672 fn configured(id: &str) -> BoardRegistration {
673 BoardRegistration::configured::<FutureBoard>(id, "Configured", "A page", unused_factory)
674 }
675
676 #[test]
677 fn configured_boards_follow_saved_order_and_are_enabled_by_default() {
678 let product = future_product();
679 let available = [BoardRegistration::new::<FutureBoard>()];
680 let config = Config {
681 board_order: vec!["wiki".into(), "future-board".into()],
682 boards: BTreeMap::from([("app".to_owned(), false)]),
683 ..Default::default()
684 };
685 let sets = super::registration_sets_with(
686 &product,
687 &available,
688 vec![configured("app"), configured("wiki")],
689 &config,
690 )
691 .unwrap();
692 assert_eq!(ids(&sets.included), ["wiki", "future-board", "app"]);
693 assert_eq!(ids(&sets.active), ["wiki", "future-board"]);
694 let wiki = &sets.included[0];
695 assert_eq!(
696 (wiki.title.as_ref(), wiki.description.as_ref()),
697 ("Configured", "A page")
698 );
699 assert_eq!(wiki.icon, Some("future.svg"));
700 assert!(!wiki.searchable);
701 }
702
703 #[test]
704 fn a_configured_board_cannot_take_a_built_in_id() {
705 let (accepted, notices) = super::configured::accept_configured(
706 &future_product(),
707 vec![configured("future-board"), configured("wiki")],
708 );
709 assert_eq!(ids(&accepted), ["wiki"]);
710 assert_eq!(notices.len(), 1);
711 assert!(notices[0].contains("future-board"));
712 }
713
714 #[test]
715 fn configured_boards_add_no_tools_of_their_own() {
716 let environment = subspace_agent_tools::test_support::environment(Default::default());
717 let catalog = tool_catalog(&[configured("a"), configured("b")], &environment).unwrap();
718 assert!(catalog.is_empty());
719 }
720
721 #[test]
722 fn boards_without_tools_or_help_give_an_empty_catalog() {
723 let environment = subspace_agent_tools::test_support::environment(Default::default());
724 let catalog = tool_catalog(&[board("github"), board("irc")], &environment).unwrap();
725 assert!(catalog.is_empty());
726 assert!(tool_catalog(&[], &environment).unwrap().is_empty());
727 }
728
729 #[test]
730 fn a_documented_board_adds_the_shared_help_tool() {
731 let environment = subspace_agent_tools::test_support::environment(Default::default());
732 let catalog = tool_catalog(&[board("github"), documented("irc")], &environment).unwrap();
733 assert!(catalog.get(HELP_TOOL).is_some());
734 assert_eq!(catalog.tools().len(), 1);
735 }
736
737 #[gpui_kit::test]
738 fn background_follows_the_active_set_and_headless_catalog_never_starts_it(
739 cx: &mut gpui_kit::TestAppContext,
740 ) {
741 struct Calls(usize, usize);
743 impl gpui_kit::Global for Calls {}
744 let mut registration = board("fixture");
745 registration.start_background = |cx| cx.global_mut::<Calls>().0 += 1;
746 registration.stop_background = |cx| cx.global_mut::<Calls>().1 += 1;
747 let environment = subspace_agent_tools::test_support::environment(Default::default());
748 assert!(
749 tool_catalog(&[registration.clone()], &environment)
750 .unwrap()
751 .is_empty()
752 );
753 cx.update(|cx| {
754 cx.set_global(Calls(0, 0));
755 cx.set_global(super::BoardFactories(vec![registration.clone()]));
756 super::sync_backgrounds(cx);
757 super::sync_backgrounds(cx);
758 assert_eq!((cx.global::<Calls>().0, cx.global::<Calls>().1), (1, 0));
759 cx.set_global(super::BoardFactories(vec![board("other")]));
760 super::sync_backgrounds(cx);
761 assert_eq!((cx.global::<Calls>().0, cx.global::<Calls>().1), (1, 1));
762 cx.set_global(super::BoardFactories(vec![registration]));
763 super::sync_backgrounds(cx);
764 assert_eq!((cx.global::<Calls>().0, cx.global::<Calls>().1), (2, 1));
765 });
766 }
767
768 #[test]
769 fn background_change_starts_new_boards_and_stops_removed_ones() {
770 fn stopped(_: &mut App) {}
771 let running = [("kept", stopped as fn(&mut App)), ("removed", stopped)];
772 let change = super::background::change(&running, &[board("kept"), board("added")]);
773 assert_eq!(change.start.len(), 1);
774 assert_eq!(change.stop.len(), 1);
775 let ids: Vec<_> = change.running.iter().map(|(id, _)| *id).collect();
776 assert_eq!(ids, ["kept", "added"]);
777 }
778}