Skip to main content

subspace_shell/
search_runtime.rs

1//! Product-scoped search initialization for GUI and headless tool consumers.
2use std::time::Duration;
3
4use gpui_kit::{App, AppContext as _, Global, Task};
5use subspace_agent_tools::ToolEnvironment;
6use subspace_product::ProductContext;
7use subspace_search::{Policy, Service};
8
9use crate::product::ProductFiles;
10use crate::registry::BoardRegistration;
11
12const FIRST_SWEEP_DELAY: Duration = Duration::from_secs(600);
13
14/// A product supplies its optional model implementation without coupling other products to it.
15pub type RerankerFactory = fn(std::path::PathBuf) -> std::sync::Arc<dyn subspace_search::Reranker>;
16
17pub(crate) fn initialize(
18    environment: &mut ToolEnvironment,
19    context: &ProductContext,
20    boards: &[BoardRegistration],
21    files: &ProductFiles,
22    reranker: Option<RerankerFactory>,
23) -> Result<(), String> {
24    let allowed: Vec<String> = boards
25        .iter()
26        .filter(|board| board.searchable)
27        .map(|board| board.id.to_owned())
28        .collect();
29    if allowed.is_empty() {
30        return Ok(());
31    }
32    let root = files
33        .state
34        .parent()
35        .ok_or("Cannot locate private search storage.")?
36        .join("search");
37    let service = Service::open(
38        root.clone(),
39        context.product.binary_name.as_str().to_owned(),
40        allowed,
41    )?;
42    offer_defaults(&service, boards);
43    if let Some(create) = reranker {
44        service.set_reranker(create(root.join("models")));
45    }
46    environment.search = Some(service);
47    Ok(())
48}
49
50/// Turns on the store of each board that declares it on by default, until
51/// the person chooses in the Search view.
52fn offer_defaults(service: &Service, boards: &[BoardRegistration]) {
53    let stored = Policy {
54        enabled: true,
55        ..Policy::default()
56    };
57    for board in boards
58        .iter()
59        .filter(|board| board.searchable && board.settings.store_by_default)
60    {
61        let _ = service.offer_default(board.id, stored.clone());
62    }
63}
64
65struct Maintenance {
66    _task: Task<()>,
67}
68impl Global for Maintenance {}
69
70pub(crate) fn start(cx: &mut App) {
71    let Some(service) = subspace_dashboard::full_text_service(cx) else {
72        return;
73    };
74    let task = cx.spawn(async move |cx| {
75        loop {
76            cx.background_executor().timer(FIRST_SWEEP_DELAY).await;
77            let service = service.clone();
78            let _ = cx.background_spawn(async move { service.sweep() }).await;
79        }
80    });
81    cx.set_global(Maintenance { _task: task });
82}
83
84#[cfg(test)]
85mod tests {
86    use std::path::Path;
87
88    use gpui_kit::{App, Window};
89    use subspace_agent_tools::{AgentTool, ToolEnvironment, test_support};
90    use subspace_core::config::Config;
91    use subspace_dashboard::DashboardHandle;
92    use subspace_dashboard::settings::BoardSettings;
93    use subspace_product::{OsKind, PlatformEnv, ProductContext, fixture};
94
95    use super::{FIRST_SWEEP_DELAY, initialize};
96    use crate::product::ProductFiles;
97    use crate::registry::BoardRegistration;
98
99    fn context(root: &Path) -> ProductContext {
100        let known = fixture::products().unwrap();
101        let env = PlatformEnv {
102            os: OsKind::Macos,
103            home: root.to_owned(),
104            xdg_config_home: None,
105            xdg_state_home: None,
106            app_data: None,
107            local_app_data: None,
108        };
109        ProductContext::new(known[0].clone(), env)
110    }
111
112    fn no_gui(_: &mut Window, _: &mut App) -> DashboardHandle {
113        panic!("Search initialization must not construct a board")
114    }
115
116    fn no_tools(_: &ToolEnvironment) -> Vec<std::sync::Arc<dyn AgentTool>> {
117        panic!("Search initialization must not fetch board tools")
118    }
119
120    fn board() -> BoardRegistration {
121        BoardRegistration {
122            id: "irc",
123            title: "Channels".into(),
124            description: "IRC networks, channels and private messages".into(),
125            icon: None,
126            help: "",
127            help_images: &[],
128            searchable: true,
129            create: std::sync::Arc::new(no_gui),
130            tools: no_tools,
131            settings: BoardSettings::default(),
132            settings_editor: None,
133            fields: None,
134            start_background: |_| panic!("Headless initialization must not start monitoring"),
135            stop_background: |_| panic!("Headless initialization must not stop monitoring"),
136            retain_when_disabled: false,
137            configuration: None,
138            artwork: subspace_dashboard::BoardArtwork::default(),
139            connection: Default::default(),
140            contracts: Default::default(),
141        }
142    }
143
144    #[test]
145    fn headless_search_uses_the_product_allowlist_without_enabling_data_collection() {
146        let root = tempfile::tempdir().unwrap();
147        let context = context(root.path());
148        let files = ProductFiles::for_context(&context);
149        let mut environment = test_support::environment(Config::default());
150        initialize(&mut environment, &context, &[board()], &files, None).unwrap();
151        let service = environment.search.unwrap();
152        assert_eq!(service.app_id(), context.product.binary_name.as_str());
153        assert!(!service.policy("irc").unwrap().enabled);
154        assert!(service.policy("github").is_err());
155        assert_eq!(service.sources().unwrap()[0].records, 0);
156        assert!(
157            service
158                .reranker_status()
159                .is_none_or(|status| !status.installed)
160        );
161        assert_eq!(FIRST_SWEEP_DELAY.as_secs(), 600);
162    }
163
164    #[test]
165    fn a_board_stored_by_default_starts_on_until_the_person_chooses() {
166        let root = tempfile::tempdir().unwrap();
167        let context = context(root.path());
168        let files = ProductFiles::for_context(&context);
169        let mut stored = board();
170        stored.settings.store_by_default = true;
171        let mut environment = test_support::environment(Config::default());
172        initialize(&mut environment, &context, &[stored.clone()], &files, None).unwrap();
173        let service = environment.search.unwrap();
174        assert!(service.policy("irc").unwrap().enabled);
175        service
176            .set_policy("irc", subspace_search::Policy::default())
177            .unwrap();
178        drop(service);
179        let mut environment = test_support::environment(Config::default());
180        initialize(&mut environment, &context, &[stored], &files, None).unwrap();
181        assert!(!environment.search.unwrap().policy("irc").unwrap().enabled);
182    }
183
184    #[test]
185    fn nonparticipating_products_do_not_create_search_storage() {
186        let root = tempfile::tempdir().unwrap();
187        let context = context(root.path());
188        let files = ProductFiles::for_context(&context);
189        let mut environment = test_support::environment(Config::default());
190        initialize(
191            &mut environment,
192            &context,
193            &[],
194            &files,
195            Some(|_| panic!("A nonparticipating product must not construct a model")),
196        )
197        .unwrap();
198        assert!(environment.search.is_none());
199        assert!(!root.path().join("Library").exists());
200    }
201}