Skip to main content

subspace_shell/
registry.rs

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