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) default_order: usize,
59    pub(crate) artwork: subspace_dashboard::BoardArtwork,
60    pub(crate) connection: subspace_dashboard::settings::ConnectionSettings,
61    /// The board's contract declarations, read without creating the board.
62    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    /// The position used when no personal Space order has been saved.
97    // qual:api - Products rank their built-in Spaces, including configured ones.
98    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
128/// Every board included by the product, even when config disables it.
129pub(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
138/// The product's boards that the config file leaves active, in switcher
139/// order. A board the config disables is left out everywhere; a board the
140/// product does not list cannot be added by the config file.
141pub(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
157/// As [`registration_sets`], with the app's configured boards after its
158/// own. A configured board is enabled unless the config file turns it off.
159pub(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
231/// The agent tools of `boards`, in their order, with the board help tool.
232pub(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
241/// The boards as the MCP server sees them.
242pub(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            // MCP's static catalog label cannot borrow an editable title.
248            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
263/// Included board metadata. The fallback supports focused tests that install
264/// the older globals only; production always installs `IncludedBoards`.
265pub(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                default_enabled: *default_enabled,
558            })
559            .collect();
560        validate_product(&descriptor).unwrap()
561    }
562
563    fn future_product() -> subspace_product::ValidatedProduct {
564        product(&[("future-board", true)])
565    }
566
567    #[test]
568    fn factories_follow_selection_order_and_reject_missing_providers() {
569        let available = [board("github"), board("irc")];
570        let selected = selected_registrations(
571            &product(&[("irc", true), ("github", true)]),
572            &available,
573            &Config::default(),
574        )
575        .unwrap();
576        assert_eq!(ids(&selected), ["irc", "github"]);
577        let known = subspace_product::fixture::products().unwrap();
578        let missing = selected_registrations(&known[0], &available, &Config::default());
579        assert!(matches!(missing, Err(error) if error.contains("github-copilot-agents")));
580    }
581
582    #[test]
583    fn saved_order_is_normalized_before_enablement_filtering() {
584        let product = product(&[("irc", true), ("github", true)]);
585        let available = [board("irc"), board("github")];
586        let config = Config {
587            board_order: vec!["github".into(), "github".into(), "unknown".into()],
588            ..Default::default()
589        };
590        let sets = registration_sets(&product, &available, &config).unwrap();
591        assert_eq!(ids(&sets.included), ["github", "irc"]);
592        assert_eq!(ids(&sets.active), ["github", "irc"]);
593    }
594
595    #[test]
596    fn the_config_file_leaves_out_disabled_boards_and_cannot_add_others() {
597        let product = product(&[("irc", true)]);
598        let available = [board("github"), board("irc")];
599        let off = config(&[("irc", false), ("github", true), ("unknown", true)]);
600        let selected = selected_registrations(&product, &available, &off).unwrap();
601        assert!(selected.is_empty(), "{:?}", ids(&selected));
602        let on = config(&[("irc", true)]);
603        assert_eq!(
604            ids(&selected_registrations(&product, &available, &on).unwrap()),
605            ["irc"]
606        );
607    }
608
609    #[test]
610    fn a_disabled_board_still_needs_settings_metadata() {
611        let off = config(&[("irc", false)]);
612        let result = selected_registrations(&product(&[("irc", true)]), &[board("github")], &off);
613        assert!(matches!(result, Err(error) if error.contains("irc")));
614    }
615
616    #[test]
617    fn future_board_registration_keeps_disabled_metadata_and_nested_sections() {
618        let registration = BoardRegistration::new::<FutureBoard>();
619        let sets = registration_sets(
620            &future_product(),
621            &[registration, board("excluded")],
622            &config(&[("future-board", false)]),
623        )
624        .unwrap();
625        assert!(sets.active.is_empty());
626        assert_eq!(ids(&sets.included), ["future-board"]);
627        let settings = sets.included[0].settings;
628        assert_eq!(sets.included[0].icon, Some("future.svg"));
629        assert_eq!(settings.features, &[GRADUATED, REMOVED]);
630        assert_eq!(settings.sections[0].children[0].features, &[EXPERIMENT]);
631    }
632
633    #[test]
634    fn board_defaults_allow_missing_and_explicit_config_choices() {
635        let product = product(&[("irc", false)]);
636        let available = [board("irc")];
637
638        assert!(
639            registration_sets(&product, &available, &Config::default())
640                .unwrap()
641                .active
642                .is_empty()
643        );
644        assert_eq!(
645            ids(
646                &registration_sets(&product, &available, &config(&[("irc", true)]))
647                    .unwrap()
648                    .active
649            ),
650            ["irc"]
651        );
652        assert!(
653            registration_sets(&product, &available, &config(&[("irc", false)]))
654                .unwrap()
655                .active
656                .is_empty()
657        );
658    }
659
660    #[test]
661    fn invalid_owner_duplicate_keys_and_duplicate_registrations_are_rejected() {
662        let product = future_product();
663        let mut wrong_owner = BoardRegistration::new::<FutureBoard>();
664        wrong_owner.settings.features = &[FeatureSpec {
665            id: "board.other.preview",
666            ..EXPERIMENT
667        }];
668        assert!(registration_sets(&product, &[wrong_owner], &Config::default()).is_err());
669
670        let mut duplicate = BoardRegistration::new::<FutureBoard>();
671        duplicate.settings.features = &[EXPERIMENT];
672        assert!(registration_sets(&product, &[duplicate], &Config::default()).is_err());
673
674        let registration = BoardRegistration::new::<FutureBoard>();
675        assert!(
676            registration_sets(
677                &product,
678                &[registration.clone(), registration],
679                &Config::default()
680            )
681            .is_err()
682        );
683    }
684
685    fn configured(id: &str) -> BoardRegistration {
686        BoardRegistration::configured::<FutureBoard>(id, "Configured", "A page", unused_factory)
687    }
688
689    #[test]
690    fn configured_boards_follow_saved_order_and_are_enabled_by_default() {
691        let product = future_product();
692        let available = [BoardRegistration::new::<FutureBoard>()];
693        let config = Config {
694            board_order: vec!["wiki".into(), "future-board".into()],
695            boards: BTreeMap::from([("app".to_owned(), false)]),
696            ..Default::default()
697        };
698        let sets = super::registration_sets_with(
699            &product,
700            &available,
701            vec![configured("app"), configured("wiki")],
702            &config,
703        )
704        .unwrap();
705        assert_eq!(ids(&sets.included), ["wiki", "future-board", "app"]);
706        assert_eq!(ids(&sets.active), ["wiki", "future-board"]);
707        let wiki = &sets.included[0];
708        assert_eq!(
709            (wiki.title.as_ref(), wiki.description.as_ref()),
710            ("Configured", "A page")
711        );
712        assert_eq!(wiki.icon, Some("future.svg"));
713        assert!(!wiki.searchable);
714    }
715
716    #[test]
717    fn defaults_order_native_and_configured_boards_together() {
718        let product = product(&[("irc", true), ("github", true)]);
719        let available = [
720            board("irc").with_default_order(0),
721            board("github").with_default_order(2),
722        ];
723        let configured = vec![configured("console").with_default_order(1)];
724        let sets =
725            super::registration_sets_with(&product, &available, configured, &Config::default())
726                .unwrap();
727        assert_eq!(ids(&sets.active), ["irc", "console", "github"]);
728    }
729
730    #[test]
731    fn a_configured_board_cannot_take_a_built_in_id() {
732        let (accepted, notices) = super::configured::accept_configured(
733            &future_product(),
734            vec![configured("future-board"), configured("wiki")],
735        );
736        assert_eq!(ids(&accepted), ["wiki"]);
737        assert_eq!(notices.len(), 1);
738        assert!(notices[0].contains("future-board"));
739    }
740
741    #[test]
742    fn configured_boards_add_no_tools_of_their_own() {
743        let environment = subspace_agent_tools::test_support::environment(Default::default());
744        let catalog = tool_catalog(&[configured("a"), configured("b")], &environment).unwrap();
745        assert!(catalog.is_empty());
746    }
747
748    #[test]
749    fn boards_without_tools_or_help_give_an_empty_catalog() {
750        let environment = subspace_agent_tools::test_support::environment(Default::default());
751        let catalog = tool_catalog(&[board("github"), board("irc")], &environment).unwrap();
752        assert!(catalog.is_empty());
753        assert!(tool_catalog(&[], &environment).unwrap().is_empty());
754    }
755
756    #[test]
757    fn a_documented_board_adds_the_shared_help_tool() {
758        let environment = subspace_agent_tools::test_support::environment(Default::default());
759        let catalog = tool_catalog(&[board("github"), documented("irc")], &environment).unwrap();
760        assert!(catalog.get(HELP_TOOL).is_some());
761        assert_eq!(catalog.tools().len(), 1);
762    }
763
764    #[gpui_kit::test]
765    fn background_follows_the_active_set_and_headless_catalog_never_starts_it(
766        cx: &mut gpui_kit::TestAppContext,
767    ) {
768        /// Starts and stops, as counts.
769        struct Calls(usize, usize);
770        impl gpui_kit::Global for Calls {}
771        let mut registration = board("fixture");
772        registration.start_background = |cx| cx.global_mut::<Calls>().0 += 1;
773        registration.stop_background = |cx| cx.global_mut::<Calls>().1 += 1;
774        let environment = subspace_agent_tools::test_support::environment(Default::default());
775        assert!(
776            tool_catalog(&[registration.clone()], &environment)
777                .unwrap()
778                .is_empty()
779        );
780        cx.update(|cx| {
781            cx.set_global(Calls(0, 0));
782            cx.set_global(super::BoardFactories(vec![registration.clone()]));
783            super::sync_backgrounds(cx);
784            super::sync_backgrounds(cx);
785            assert_eq!((cx.global::<Calls>().0, cx.global::<Calls>().1), (1, 0));
786            cx.set_global(super::BoardFactories(vec![board("other")]));
787            super::sync_backgrounds(cx);
788            assert_eq!((cx.global::<Calls>().0, cx.global::<Calls>().1), (1, 1));
789            cx.set_global(super::BoardFactories(vec![registration]));
790            super::sync_backgrounds(cx);
791            assert_eq!((cx.global::<Calls>().0, cx.global::<Calls>().1), (2, 1));
792        });
793    }
794
795    #[test]
796    fn background_change_starts_new_boards_and_stops_removed_ones() {
797        fn stopped(_: &mut App) {}
798        let running = [("kept", stopped as fn(&mut App)), ("removed", stopped)];
799        let change = super::background::change(&running, &[board("kept"), board("added")]);
800        assert_eq!(change.start.len(), 1);
801        assert_eq!(change.stop.len(), 1);
802        let ids: Vec<_> = change.running.iter().map(|(id, _)| *id).collect();
803        assert_eq!(ids, ["kept", "added"]);
804    }
805}