1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use crate::protocol::{ClientMessage, DaemonMessage, SearchResultWire};
use fount_core::{IndexCatalog, SearchResult};
use std::thread;
use thiserror::Error;
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, error, info, warn};
/// Errors returned when communicating with the background search engine actor.
#[derive(Debug, Error)]
pub enum EngineError {
#[error("Search engine actor channel closed")]
ActorStopped,
#[error("Failed to launch entry: {0}")]
LaunchFailed(String),
}
/// Commands sent from async Tokio tasks across the thread boundary to the synchronous actor thread.
pub enum EngineCommand {
/// Update query, tick Nucleo matcher, and return up to `limit` ranked results.
Search {
query: String,
limit: usize,
reply: oneshot::Sender<Vec<SearchResult>>,
},
/// Record frecency usage for `id` and optionally spawn its underlying action.
Exec {
id: String,
execute_process: bool,
reply: oneshot::Sender<Result<(), String>>,
},
/// Rescan desktop directories and reload entries.
Reload { reply: oneshot::Sender<usize> },
/// Persist frecency state and terminate the actor loop cleanly.
Shutdown { reply: oneshot::Sender<()> },
}
/// Cloneable async handle used by Tokio IPC servers (Unix socket, D-Bus) to query the actor thread.
#[derive(Clone, Debug)]
pub struct EngineHandle {
tx: mpsc::Sender<EngineCommand>,
}
impl EngineHandle {
/// Spawns the dedicated OS actor thread initialized from `$XDG_CONFIG_HOME/fount/config.json`
/// (or `~/.config/fount/config.json`, falling back to defaults if not present).
pub fn spawn() -> Self {
let catalog = IndexCatalog::from_default_config();
Self::spawn_with_catalog(catalog)
}
/// Spawns the dedicated OS actor thread taking ownership of the provided `IndexCatalog`.
///
/// `Nucleo` runs its own internal Rayon thread pool; keeping `IndexCatalog` and `nucleo.tick()`
/// isolated on this dedicated OS thread guarantees Tokio worker threads are never blocked.
pub fn spawn_with_catalog(mut catalog: IndexCatalog) -> Self {
let (tx, mut rx) = mpsc::channel::<EngineCommand>(256);
// Prime initial snapshot
catalog.tick(10);
thread::Builder::new()
.name("fount-engine-actor".into())
.spawn(move || {
info!(
entries = catalog.len(),
"Search engine actor started on dedicated OS thread"
);
while let Some(cmd) = rx.blocking_recv() {
match cmd {
EngineCommand::Search {
query,
limit,
reply,
} => {
catalog.search(&query);
catalog.tick(10);
let results = catalog.results(limit);
let _ = reply.send(results);
}
EngineCommand::Exec {
id,
execute_process,
reply,
} => {
let outcome = match catalog.get_by_id(&id).cloned() {
Some(entry) => {
let exec_res = if execute_process {
entry
.action
.execute()
.map(|_| ())
.map_err(|e| e.to_string())
} else {
Ok(())
};
if exec_res.is_ok() {
let new_score = catalog.record_launch(&id);
debug!(id = %id, new_score, "Recorded launch in frecency store");
if let Err(e) = catalog.save_frecency() {
warn!(error = %e, "Failed to save frecency store to disk");
}
}
exec_res
}
None => Err(format!("Entry not found: '{id}'")),
};
let _ = reply.send(outcome);
}
EngineCommand::Reload { reply } => {
let count = catalog.reload();
catalog.tick(10);
info!(entries = count, "Reloaded search catalog");
let _ = reply.send(count);
}
EngineCommand::Shutdown { reply } => {
info!("Shutting down search engine actor");
if let Err(e) = catalog.save_frecency() {
error!(error = %e, "Failed to save frecency state during shutdown");
}
let _ = reply.send(());
break;
}
}
}
})
.expect("Failed to spawn fount-engine-actor thread");
Self { tx }
}
/// Submits a fuzzy search query to the engine actor and awaits the ranked results.
pub async fn search(
&self,
query: impl Into<String>,
limit: usize,
) -> Result<Vec<SearchResult>, EngineError> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(EngineCommand::Search {
query: query.into(),
limit,
reply: reply_tx,
})
.await
.map_err(|_| EngineError::ActorStopped)?;
reply_rx.await.map_err(|_| EngineError::ActorStopped)
}
/// Records a launch for `id` (updating frecency) and optionally spawns the process.
pub async fn launch(
&self,
id: impl Into<String>,
execute_process: bool,
) -> Result<(), EngineError> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(EngineCommand::Exec {
id: id.into(),
execute_process,
reply: reply_tx,
})
.await
.map_err(|_| EngineError::ActorStopped)?;
match reply_rx.await {
Ok(Ok(())) => Ok(()),
Ok(Err(msg)) => Err(EngineError::LaunchFailed(msg)),
Err(_) => Err(EngineError::ActorStopped),
}
}
/// Triggers an index reload and returns the updated entry count.
pub async fn reload(&self) -> Result<usize, EngineError> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(EngineCommand::Reload { reply: reply_tx })
.await
.map_err(|_| EngineError::ActorStopped)?;
reply_rx.await.map_err(|_| EngineError::ActorStopped)
}
/// Flushes state to disk and stops the actor thread cleanly.
pub async fn shutdown(&self) -> Result<(), EngineError> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(EngineCommand::Shutdown { reply: reply_tx })
.await
.map_err(|_| EngineError::ActorStopped)?;
reply_rx.await.map_err(|_| EngineError::ActorStopped)
}
/// Stateless dispatcher for wire protocol messages received from the IPC server.
pub async fn dispatch(&self, msg: ClientMessage) -> DaemonMessage {
match msg {
ClientMessage::Search { query, limit } => {
match self.search(query.clone(), limit as usize).await {
Ok(results) => DaemonMessage::Results {
query,
items: results.into_iter().map(SearchResultWire::from).collect(),
},
Err(e) => DaemonMessage::Error {
message: e.to_string(),
},
}
}
ClientMessage::Exec { id, execute } => match self.launch(id.clone(), execute).await {
Ok(()) => DaemonMessage::Launched {
id,
success: true,
error: None,
},
Err(e) => DaemonMessage::Launched {
id,
success: false,
error: Some(e.to_string()),
},
},
ClientMessage::Reload => match self.reload().await {
Ok(count) => DaemonMessage::Reloaded {
count: count as u32,
},
Err(e) => DaemonMessage::Error {
message: e.to_string(),
},
},
ClientMessage::Ping => DaemonMessage::Pong,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use fount_core::FrecencyStore;
use std::fs;
use tempfile::tempdir;
#[tokio::test]
async fn test_actor_search_launch_and_frecency() {
let temp = tempdir().unwrap();
let apps_dir = temp.path().join("applications");
let frecency_path = temp.path().join("frecency.bin");
fs::create_dir_all(&apps_dir).unwrap();
fs::write(
apps_dir.join("code.desktop"),
r#"
[Desktop Entry]
Type=Application
Name=Code Editor
Exec=code
"#,
)
.unwrap();
fs::write(
apps_dir.join("console.desktop"),
r#"
[Desktop Entry]
Type=Application
Name=Console Terminal
Exec=kgx
"#,
)
.unwrap();
let mut catalog = IndexCatalog::with_dirs(vec![apps_dir.clone()]);
catalog.set_frecency_store(FrecencyStore::open_or_create(frecency_path.clone()));
catalog.set_include_system_actions(true);
let handle = EngineHandle::spawn_with_catalog(catalog);
// 1. Search for "code"
let results = handle.search("code", 5).await.unwrap();
assert!(!results.is_empty());
assert_eq!(results[0].entry.id, "code.desktop");
// 2. Search for system action by alias "shutdown"
let sys_results = handle.search("shutdown", 5).await.unwrap();
assert!(!sys_results.is_empty());
assert_eq!(sys_results[0].entry.id, "action:poweroff");
// 3. Record multiple launches for "console.desktop" without spawning external binary
for _ in 0..5 {
handle.launch("console.desktop", false).await.unwrap();
}
assert!(frecency_path.is_file());
// 4. Empty query should rank "console.desktop" #1 due to frecency
let recent = handle.search("", 5).await.unwrap();
assert_eq!(recent[0].entry.id, "console.desktop");
// 5. Test wire protocol dispatch
let resp = handle
.dispatch(ClientMessage::Search {
query: "co".into(),
limit: 5,
})
.await;
match resp {
DaemonMessage::Results { items, .. } => {
assert!(!items.is_empty());
assert_eq!(items[0].id, "console.desktop");
}
other => panic!("Unexpected daemon response: {other:?}"),
}
// 6. Test reload and clean shutdown
let count = handle.reload().await.unwrap();
assert_eq!(count, 7); // 2 desktop apps + 5 system actions
handle.shutdown().await.unwrap();
}
}