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