victauri_core/registry.rs
1//! Thread-safe command registry with substring search and
2//! natural-language-to-command resolution.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::{Arc, RwLock};
7
8use serde::{Deserialize, Serialize};
9
10/// Metadata for a registered Tauri command, including intent and schema information.
11#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
12pub struct CommandInfo {
13 /// Fully qualified command name (e.g. "`get_settings`").
14 pub name: String,
15 /// Plugin namespace, if the command belongs to a Tauri plugin.
16 pub plugin: Option<String>,
17 /// Human-readable description of what the command does.
18 pub description: Option<String>,
19 /// Ordered list of arguments the command accepts.
20 pub args: Vec<CommandArg>,
21 /// Rust return type as a string (e.g. "Result<Settings, Error>").
22 pub return_type: Option<String>,
23 /// Whether the command handler is async.
24 pub is_async: bool,
25 /// Natural-language intent phrase for NL-to-command resolution.
26 pub intent: Option<String>,
27 /// Grouping category (e.g. "settings", "counter").
28 pub category: Option<String>,
29 /// Example natural-language queries that should resolve to this command.
30 pub examples: Vec<String>,
31}
32
33/// Schema for a single argument of a registered command.
34#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
35pub struct CommandArg {
36 /// Argument name as declared in the Rust function signature.
37 pub name: String,
38 /// Rust type name (e.g. "String", "`Option<u32>`").
39 pub type_name: String,
40 /// Whether the argument must be provided (not `Option`).
41 pub required: bool,
42 /// Optional JSON Schema for the argument's expected shape.
43 pub schema: Option<serde_json::Value>,
44}
45
46/// Factory function submitted by `#[inspectable]` for auto-discovery.
47///
48/// Wraps a `fn() -> CommandInfo` so it can be registered via `inventory`
49/// (function pointers are const-constructible, unlike `CommandInfo` with its `String` fields).
50#[doc(hidden)]
51pub struct CommandInfoFactory(pub fn() -> CommandInfo);
52
53inventory::collect!(CommandInfoFactory);
54
55impl CommandInfo {
56 /// Creates a new command with the given name and all optional fields set to `None`/empty.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// use victauri_core::CommandInfo;
62 ///
63 /// let cmd = CommandInfo::new("greet");
64 /// assert_eq!(cmd.name, "greet");
65 /// assert!(cmd.description.is_none());
66 /// ```
67 #[must_use]
68 pub fn new(name: impl Into<String>) -> Self {
69 Self {
70 name: name.into(),
71 plugin: None,
72 description: None,
73 args: Vec::new(),
74 return_type: None,
75 is_async: false,
76 intent: None,
77 category: None,
78 examples: Vec::new(),
79 }
80 }
81
82 /// Sets the description.
83 #[must_use]
84 pub fn with_description(mut self, description: impl Into<String>) -> Self {
85 self.description = Some(description.into());
86 self
87 }
88
89 /// Sets the intent phrase for natural-language resolution.
90 #[must_use]
91 pub fn with_intent(mut self, intent: impl Into<String>) -> Self {
92 self.intent = Some(intent.into());
93 self
94 }
95
96 /// Sets the category.
97 #[must_use]
98 pub fn with_category(mut self, category: impl Into<String>) -> Self {
99 self.category = Some(category.into());
100 self
101 }
102}
103
104/// Thread-safe registry of known Tauri commands, indexed by name.
105#[derive(Debug, Clone)]
106pub struct CommandRegistry {
107 commands: Arc<RwLock<BTreeMap<String, CommandInfo>>>,
108}
109
110impl CommandRegistry {
111 /// Creates an empty command registry.
112 ///
113 /// ```
114 /// use victauri_core::CommandRegistry;
115 ///
116 /// let registry = CommandRegistry::new();
117 /// assert_eq!(registry.count(), 0);
118 /// assert!(registry.list().is_empty());
119 /// ```
120 #[must_use]
121 pub fn new() -> Self {
122 Self {
123 commands: Arc::new(RwLock::new(BTreeMap::new())),
124 }
125 }
126
127 /// Registers a command, replacing any existing entry with the same name.
128 ///
129 /// ```
130 /// use victauri_core::{CommandRegistry, CommandInfo};
131 ///
132 /// let registry = CommandRegistry::new();
133 /// registry.register(CommandInfo::new("greet").with_description("Say hello"));
134 /// assert_eq!(registry.count(), 1);
135 /// assert!(registry.get("greet").is_some());
136 /// ```
137 pub fn register(&self, info: CommandInfo) {
138 self.commands
139 .write()
140 .unwrap_or_else(std::sync::PoisonError::into_inner)
141 .insert(info.name.clone(), info);
142 }
143
144 /// Looks up a command by exact name.
145 #[must_use]
146 pub fn get(&self, name: &str) -> Option<CommandInfo> {
147 self.commands
148 .read()
149 .unwrap_or_else(std::sync::PoisonError::into_inner)
150 .get(name)
151 .cloned()
152 }
153
154 /// Returns all registered commands in alphabetical order.
155 #[must_use]
156 pub fn list(&self) -> Vec<CommandInfo> {
157 self.commands
158 .read()
159 .unwrap_or_else(std::sync::PoisonError::into_inner)
160 .values()
161 .cloned()
162 .collect()
163 }
164
165 /// Returns the number of registered commands.
166 #[must_use]
167 pub fn count(&self) -> usize {
168 self.commands
169 .read()
170 .unwrap_or_else(std::sync::PoisonError::into_inner)
171 .len()
172 }
173
174 /// Searches commands by substring match on name or description (case-insensitive).
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// use victauri_core::{CommandRegistry, CommandInfo};
180 ///
181 /// let registry = CommandRegistry::new();
182 /// registry.register(
183 /// CommandInfo::new("get_settings").with_description("Retrieve app settings"),
184 /// );
185 /// let results = registry.search("settings");
186 /// assert_eq!(results.len(), 1);
187 /// assert_eq!(results[0].name, "get_settings");
188 /// ```
189 #[must_use]
190 pub fn search(&self, query: &str) -> Vec<CommandInfo> {
191 let query_lower = query.to_lowercase();
192 self.commands
193 .read()
194 .unwrap_or_else(std::sync::PoisonError::into_inner)
195 .values()
196 .filter(|cmd| {
197 cmd.name.to_lowercase().contains(&query_lower)
198 || cmd
199 .description
200 .as_ref()
201 .is_some_and(|d| d.to_lowercase().contains(&query_lower))
202 })
203 .cloned()
204 .collect()
205 }
206
207 /// Resolves a natural-language query to commands ranked by relevance score.
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// use victauri_core::{CommandRegistry, CommandInfo};
213 ///
214 /// let registry = CommandRegistry::new();
215 /// registry.register(
216 /// CommandInfo::new("get_settings")
217 /// .with_description("Retrieve app settings")
218 /// .with_intent("fetch configuration")
219 /// .with_category("settings"),
220 /// );
221 /// let results = registry.resolve("get settings");
222 /// assert!(!results.is_empty());
223 /// assert!(results[0].score > 0.0);
224 /// ```
225 #[must_use]
226 pub fn resolve(&self, query: &str) -> Vec<ScoredCommand> {
227 let query_lower = query.to_lowercase();
228 let query_words: Vec<&str> = query_lower.split_whitespace().collect();
229 if query_words.is_empty() {
230 return Vec::new();
231 }
232
233 let mut scored: Vec<ScoredCommand> = self
234 .commands
235 .read()
236 .unwrap_or_else(std::sync::PoisonError::into_inner)
237 .values()
238 .filter_map(|cmd| {
239 let score = score_command(cmd, &query_lower, &query_words);
240 if score > 0.0 {
241 Some(ScoredCommand {
242 command: cmd.clone(),
243 score,
244 })
245 } else {
246 None
247 }
248 })
249 .collect();
250
251 scored.sort_by(|a, b| b.score.total_cmp(&a.score));
252 scored
253 }
254}
255
256/// Returns all commands registered via `#[inspectable]` auto-discovery.
257///
258/// Collects every `CommandInfoFactory` submitted by the `#[inspectable]` macro
259/// and calls each factory to produce `CommandInfo` values.
260#[must_use]
261pub fn auto_discovered_commands() -> Vec<CommandInfo> {
262 inventory::iter::<CommandInfoFactory>
263 .into_iter()
264 .map(|factory| (factory.0)())
265 .collect()
266}
267
268impl CommandRegistry {
269 /// Creates a registry pre-populated with all `#[inspectable]` commands.
270 ///
271 /// Uses `inventory` to collect every `CommandInfo` that was submitted at
272 /// link time by the `#[inspectable]` macro. This replaces manual
273 /// `register_commands!` or `.commands(&[...])` calls.
274 ///
275 /// ```
276 /// use victauri_core::CommandRegistry;
277 ///
278 /// let registry = CommandRegistry::from_auto_discovery();
279 /// // Contains all #[inspectable] commands from the binary
280 /// ```
281 #[must_use]
282 pub fn from_auto_discovery() -> Self {
283 let registry = Self::new();
284 for info in auto_discovered_commands() {
285 registry.register(info);
286 }
287 registry
288 }
289}
290
291impl Default for CommandRegistry {
292 fn default() -> Self {
293 Self::new()
294 }
295}
296
297/// A command paired with its relevance score from natural-language resolution.
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct ScoredCommand {
300 /// The matched command metadata.
301 pub command: CommandInfo,
302 /// Relevance score (higher is better); 0 means no match.
303 pub score: f64,
304}
305
306impl fmt::Display for ScoredCommand {
307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308 write!(f, "{} (score: {:.2})", self.command.name, self.score)
309 }
310}
311
312const SCORE_EXACT_NAME: f64 = 10.0;
313const SCORE_NAME_SUBSTRING: f64 = 3.0;
314const SCORE_NAME_WORD: f64 = 2.0;
315const SCORE_DESCRIPTION: f64 = 1.5;
316const SCORE_INTENT: f64 = 2.5;
317const SCORE_CATEGORY: f64 = 1.0;
318const SCORE_EXAMPLE_FULL: f64 = 4.0;
319const SCORE_EXAMPLE_WORD: f64 = 0.5;
320
321/// Scores a command against a query. Per-word contributions (substring, word,
322/// description, intent, category, example-word matches) are normalized by query
323/// length so scores remain comparable across queries of different word counts.
324/// Whole-query bonuses (exact name match, full example match) are not normalized.
325fn score_command(cmd: &CommandInfo, query_lower: &str, query_words: &[&str]) -> f64 {
326 let mut score = 0.0;
327 let mut exact_bonus = 0.0;
328 let name_lower = cmd.name.to_lowercase();
329 let name_words: Vec<&str> = name_lower.split('_').collect();
330
331 if name_lower == query_lower.replace(' ', "_") {
332 exact_bonus += SCORE_EXACT_NAME;
333 }
334
335 for word in query_words {
336 if name_lower.contains(word) {
337 score += SCORE_NAME_SUBSTRING;
338 }
339 if name_words.contains(word) {
340 score += SCORE_NAME_WORD;
341 }
342 }
343
344 if let Some(desc) = &cmd.description {
345 let desc_lower = desc.to_lowercase();
346 for word in query_words {
347 if desc_lower.contains(word) {
348 score += SCORE_DESCRIPTION;
349 }
350 }
351 }
352
353 if let Some(intent) = &cmd.intent {
354 let intent_lower = intent.to_lowercase();
355 for word in query_words {
356 if intent_lower.contains(word) {
357 score += SCORE_INTENT;
358 }
359 }
360 }
361
362 if let Some(category) = &cmd.category {
363 let cat_lower = category.to_lowercase();
364 for word in query_words {
365 if cat_lower.contains(word) {
366 score += SCORE_CATEGORY;
367 }
368 }
369 }
370
371 for example in &cmd.examples {
372 let ex_lower = example.to_lowercase();
373 if ex_lower.contains(query_lower) {
374 exact_bonus += SCORE_EXAMPLE_FULL;
375 break;
376 }
377 for word in query_words {
378 if ex_lower.contains(word) {
379 score += SCORE_EXAMPLE_WORD;
380 }
381 }
382 }
383
384 // Normalize per-word contributions so scores are comparable across queries of different lengths.
385 let word_count = query_words.len() as f64;
386 let per_word_score = score / word_count;
387 exact_bonus + per_word_score
388}