subspace_shell/
search_runtime.rs1use 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
14pub 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
50fn 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 default_order: usize::MAX,
139 artwork: subspace_dashboard::BoardArtwork::default(),
140 connection: Default::default(),
141 contracts: Default::default(),
142 }
143 }
144
145 #[test]
146 fn headless_search_uses_the_product_allowlist_without_enabling_data_collection() {
147 let root = tempfile::tempdir().unwrap();
148 let context = context(root.path());
149 let files = ProductFiles::for_context(&context);
150 let mut environment = test_support::environment(Config::default());
151 initialize(&mut environment, &context, &[board()], &files, None).unwrap();
152 let service = environment.search.unwrap();
153 assert_eq!(service.app_id(), context.product.binary_name.as_str());
154 assert!(!service.policy("irc").unwrap().enabled);
155 assert!(service.policy("github").is_err());
156 assert_eq!(service.sources().unwrap()[0].records, 0);
157 assert!(
158 service
159 .reranker_status()
160 .is_none_or(|status| !status.installed)
161 );
162 assert_eq!(FIRST_SWEEP_DELAY.as_secs(), 600);
163 }
164
165 #[test]
166 fn a_board_stored_by_default_starts_on_until_the_person_chooses() {
167 let root = tempfile::tempdir().unwrap();
168 let context = context(root.path());
169 let files = ProductFiles::for_context(&context);
170 let mut stored = board();
171 stored.settings.store_by_default = true;
172 let mut environment = test_support::environment(Config::default());
173 initialize(&mut environment, &context, &[stored.clone()], &files, None).unwrap();
174 let service = environment.search.unwrap();
175 assert!(service.policy("irc").unwrap().enabled);
176 service
177 .set_policy("irc", subspace_search::Policy::default())
178 .unwrap();
179 drop(service);
180 let mut environment = test_support::environment(Config::default());
181 initialize(&mut environment, &context, &[stored], &files, None).unwrap();
182 assert!(!environment.search.unwrap().policy("irc").unwrap().enabled);
183 }
184
185 #[test]
186 fn nonparticipating_products_do_not_create_search_storage() {
187 let root = tempfile::tempdir().unwrap();
188 let context = context(root.path());
189 let files = ProductFiles::for_context(&context);
190 let mut environment = test_support::environment(Config::default());
191 initialize(
192 &mut environment,
193 &context,
194 &[],
195 &files,
196 Some(|_| panic!("A nonparticipating product must not construct a model")),
197 )
198 .unwrap();
199 assert!(environment.search.is_none());
200 assert!(!root.path().join("Library").exists());
201 }
202}