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, RegistrationSets};
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
50pub(crate) fn initialize_desktop(
51    environment: &mut ToolEnvironment,
52    context: &ProductContext,
53    boards: &RegistrationSets,
54    files: &ProductFiles,
55    reranker: Option<RerankerFactory>,
56) -> Result<(), String> {
57    initialize(environment, context, &boards.included, files, reranker)?;
58    set_active(environment.search.as_ref(), &boards.active)
59}
60
61pub(crate) fn set_active(
62    service: Option<&Service>,
63    boards: &[BoardRegistration],
64) -> Result<(), String> {
65    if let Some(service) = service {
66        service.set_active_boards(
67            boards
68                .iter()
69                .filter(|board| board.searchable)
70                .map(|board| board.id.to_owned())
71                .collect(),
72        )?;
73    }
74    Ok(())
75}
76
77/// Turns on the store of each board that declares it on by default, until
78/// the person chooses in the Search view.
79fn offer_defaults(service: &Service, boards: &[BoardRegistration]) {
80    let stored = Policy {
81        enabled: true,
82        ..Policy::default()
83    };
84    for board in boards
85        .iter()
86        .filter(|board| board.searchable && board.settings.store_by_default)
87    {
88        let _ = service.offer_default(board.id, stored.clone());
89    }
90}
91
92struct Maintenance {
93    _task: Task<()>,
94    _provisioning: Task<()>,
95}
96impl Global for Maintenance {}
97
98pub(crate) fn start(cx: &mut App) {
99    let Some(service) = subspace_dashboard::full_text_service(cx) else {
100        return;
101    };
102    let model_service = service.clone();
103    let provisioning = cx.background_executor().spawn(async move {
104        provision_missing_model(&model_service);
105    });
106    let task = cx.spawn(async move |cx| {
107        loop {
108            cx.background_executor().timer(FIRST_SWEEP_DELAY).await;
109            let service = service.clone();
110            let _ = cx.background_spawn(async move { service.sweep() }).await;
111        }
112    });
113    cx.set_global(Maintenance {
114        _task: task,
115        _provisioning: provisioning,
116    });
117}
118
119fn provision_missing_model(service: &Service) {
120    if service
121        .reranker_status()
122        .is_some_and(|status| !status.installed)
123        && let Err(error) = service.install_reranker()
124    {
125        subspace_core::log::Logger::new("search").record(
126            subspace_core::log::Level::Warn,
127            error,
128            &[],
129        );
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use std::path::Path;
136
137    use gpui_kit::{App, Window};
138    use subspace_agent_tools::{AgentTool, ToolEnvironment, test_support};
139    use subspace_core::config::Config;
140    use subspace_dashboard::DashboardHandle;
141    use subspace_dashboard::settings::BoardSettings;
142    use subspace_product::{OsKind, PlatformEnv, ProductContext, fixture};
143
144    use super::{FIRST_SWEEP_DELAY, initialize, provision_missing_model};
145    use crate::product::ProductFiles;
146    use crate::registry::BoardRegistration;
147
148    fn context(root: &Path) -> ProductContext {
149        let known = fixture::products().unwrap();
150        let env = PlatformEnv {
151            os: OsKind::Macos,
152            home: root.to_owned(),
153            xdg_config_home: None,
154            xdg_state_home: None,
155            app_data: None,
156            local_app_data: None,
157        };
158        ProductContext::new(known[0].clone(), env)
159    }
160
161    fn no_gui(_: &mut Window, _: &mut App) -> DashboardHandle {
162        panic!("Search initialization must not construct a board")
163    }
164
165    fn no_tools(_: &ToolEnvironment) -> Vec<std::sync::Arc<dyn AgentTool>> {
166        panic!("Search initialization must not fetch board tools")
167    }
168
169    fn board() -> BoardRegistration {
170        BoardRegistration {
171            id: "irc",
172            title: "Channels".into(),
173            description: "IRC networks, channels and private messages".into(),
174            icon: None,
175            help: "",
176            help_images: &[],
177            searchable: true,
178            create: std::sync::Arc::new(no_gui),
179            tools: no_tools,
180            settings: BoardSettings::default(),
181            settings_editor: None,
182            fields: None,
183            start_background: |_| panic!("Headless initialization must not start monitoring"),
184            stop_background: |_| panic!("Headless initialization must not stop monitoring"),
185            retain_when_disabled: false,
186            configuration: None,
187            default_order: usize::MAX,
188            artwork: subspace_dashboard::BoardArtwork::default(),
189            connection: Default::default(),
190            contracts: Default::default(),
191        }
192    }
193
194    #[test]
195    fn headless_search_uses_the_product_allowlist_without_enabling_data_collection() {
196        let root = tempfile::tempdir().unwrap();
197        let context = context(root.path());
198        let files = ProductFiles::for_context(&context);
199        let mut environment = test_support::environment(Config::default());
200        initialize(&mut environment, &context, &[board()], &files, None).unwrap();
201        let service = environment.search.unwrap();
202        assert_eq!(service.app_id(), context.product.binary_name.as_str());
203        assert!(!service.policy("irc").unwrap().enabled);
204        assert!(service.policy("github").is_err());
205        assert_eq!(service.sources().unwrap()[0].records, 0);
206        assert!(
207            service
208                .reranker_status()
209                .is_none_or(|status| !status.installed)
210        );
211        assert_eq!(FIRST_SWEEP_DELAY.as_secs(), 600);
212    }
213
214    #[test]
215    fn a_board_stored_by_default_starts_on_until_the_person_chooses() {
216        let root = tempfile::tempdir().unwrap();
217        let context = context(root.path());
218        let files = ProductFiles::for_context(&context);
219        let mut stored = board();
220        stored.settings.store_by_default = true;
221        let mut environment = test_support::environment(Config::default());
222        initialize(&mut environment, &context, &[stored.clone()], &files, None).unwrap();
223        let service = environment.search.unwrap();
224        assert!(service.policy("irc").unwrap().enabled);
225        service
226            .set_policy("irc", subspace_search::Policy::default())
227            .unwrap();
228        drop(service);
229        let mut environment = test_support::environment(Config::default());
230        initialize(&mut environment, &context, &[stored], &files, None).unwrap();
231        assert!(!environment.search.unwrap().policy("irc").unwrap().enabled);
232    }
233
234    #[test]
235    fn desktop_setup_installs_the_model_once_when_it_is_missing() {
236        use std::sync::{
237            Arc,
238            atomic::{AtomicUsize, Ordering},
239        };
240        use subspace_search::{Hit, Reranker, RerankerStatus, Service};
241
242        #[derive(Default)]
243        struct Model(AtomicUsize);
244        impl Reranker for Model {
245            fn rerank(&self, _: &str, _: &[Hit]) -> Result<Vec<Hit>, String> {
246                panic!("Setup must not perform inference")
247            }
248
249            fn status(&self) -> RerankerStatus {
250                RerankerStatus {
251                    installed: self.0.load(Ordering::SeqCst) != 0,
252                    name: "Fixture model".into(),
253                    download_bytes: 10,
254                    message: String::new(),
255                }
256            }
257
258            fn install(&self) -> Result<(), String> {
259                self.0.fetch_add(1, Ordering::SeqCst);
260                Ok(())
261            }
262        }
263
264        let root = tempfile::tempdir().unwrap();
265        let service = Service::open(root.path().into(), "test-app".into(), vec![]).unwrap();
266        let model = Arc::new(Model::default());
267        service.set_reranker(model.clone());
268        assert_eq!(model.0.load(Ordering::SeqCst), 0);
269        provision_missing_model(&service);
270        provision_missing_model(&service);
271        assert_eq!(model.0.load(Ordering::SeqCst), 1);
272    }
273
274    #[test]
275    fn nonparticipating_products_do_not_create_search_storage() {
276        let root = tempfile::tempdir().unwrap();
277        let context = context(root.path());
278        let files = ProductFiles::for_context(&context);
279        let mut environment = test_support::environment(Config::default());
280        initialize(
281            &mut environment,
282            &context,
283            &[],
284            &files,
285            Some(|_| panic!("A nonparticipating product must not construct a model")),
286        )
287        .unwrap();
288        assert!(environment.search.is_none());
289        assert!(!root.path().join("Library").exists());
290    }
291}