super-voice-daemon/src/daemon/model_management/instantiate.rs
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-3.0-only |
2 | | use crate::backend_headers::push_context; |
3 | | use crate::backend_headers::{self, Feature}; |
4 | | use crate::daemon::types::{LoadTurn, SuperSTTDaemon}; |
5 | | use crate::stt_models::ModelDefinition; |
6 | | use crate::stt_models::backends::{self, DiscoveredBackend}; |
7 | | use crate::stt_models::transcribe::Transcribe; |
8 | | use anyhow::{Result, anyhow, bail}; |
9 | | use super_voice_shared::models::contexts::DictationContext; |
10 | | |
11 | | impl SuperSTTDaemon { |
12 | | /// Build a running backend instance for `(name, source)` plus its |
13 | | /// resolved definition. Central routing point for all model loading — |
14 | | /// startup, a model switch, a device switch, and a config reload all |
15 | | /// funnel through here, so `chosen` (the model's own framework, if it has |
16 | | /// one) is resolved into the framework it loads on right here rather than |
17 | | /// by each caller: the same answer `GET …/device` gives, so a load never |
18 | | /// lands somewhere the card did not say. |
19 | | /// |
20 | | /// It takes the load's `turn` at the stage's slot |
21 | | /// ([`ModelSlot::begin_load`] or |
22 | | /// [`ModelSlot::begin_load_if_empty`]), so no load runs outside one: a |
23 | | /// load takes minutes, and two at once put two models on one GPU. The |
24 | | /// turn holds the slot until the caller installs what this returns with |
25 | | /// it. |
26 | | /// |
27 | | /// [`ModelSlot::begin_load`]: super_engine_daemon::model_slot::ModelSlot::begin_load |
28 | | /// [`ModelSlot::begin_load_if_empty`]: super_engine_daemon::model_slot::ModelSlot::begin_load_if_empty |
29 | | /// |
30 | | /// # Errors |
31 | | /// Returns an error if no installed backend serves the model, the backend |
32 | | /// declares an unknown kind, or instantiation fails. |
33 | 31 | pub async fn instantiate_backend( |
34 | 31 | &self, |
35 | 31 | _turn: &LoadTurn<'_>, |
36 | 31 | name: &str, |
37 | 31 | source: &str, |
38 | 31 | chosen: Option<&str>, |
39 | 31 | stage: crate::daemon::device_management::PipelineStage, |
40 | 31 | ) -> Result<(Box<dyn Transcribe>, ModelDefinition)> { |
41 | | let (backend, def) = { |
42 | 31 | let backends = self.backends.read().await; |
43 | 31 | let (b, d) = backends::find_model(&backends, name, source) |
44 | 0 | .ok_or_else(|| anyhow!("no installed backend serves {name}"))?; |
45 | 31 | (b.clone(), d.clone()) |
46 | | }; |
47 | | // A model of the other stage would be driven over a route its backend |
48 | | // does not serve, failing on every transcript: refused here, once, |
49 | | // whatever the load. |
50 | 31 | if def.product.role.is_post_processor() != stage.is_post_processor() { |
51 | 1 | let (is, isnt) = if stage.is_post_processor() { |
52 | 0 | ("a transcription model", "a post-processing model") |
53 | | } else { |
54 | 1 | ("a post-processing model", "a transcription model") |
55 | | }; |
56 | 1 | bail!("model {name} is {is}, not {isnt}"); |
57 | 30 | } |
58 | | |
59 | 30 | let instance: Box<dyn Transcribe> = match backend.kind.as_str() { |
60 | 30 | "wasm" => self.instantiate_wasm(&backend, &def).await?20 , |
61 | | "subprocess" => { |
62 | | // Empty when no framework is offered here: the load then |
63 | | // names none and the backend runs on what it has. |
64 | 0 | let resolved = self |
65 | 0 | .install_context(&backend.dir) |
66 | 0 | .await |
67 | 0 | .effective(&def, chosen) |
68 | | .unwrap_or_default(); |
69 | 0 | self.instantiate_subprocess(&backend, &def, &resolved, stage) |
70 | 0 | .await? |
71 | | } |
72 | 0 | other => bail!("backend {} declares unknown kind '{other}'", backend.source), |
73 | | }; |
74 | 10 | Ok((instance, def)) |
75 | 31 | } |
76 | | |
77 | 30 | async fn instantiate_wasm( |
78 | 30 | &self, |
79 | 30 | backend: &DiscoveredBackend, |
80 | 30 | def: &ModelDefinition, |
81 | 30 | ) -> Result<Box<dyn Transcribe>> { |
82 | | use crate::stt_models::transcribe::ModelInfoData; |
83 | 30 | let context = self.backend_context(backend, def).await?4 ; |
84 | 26 | let component = backend.dir.join(&backend.entrypoint); |
85 | 26 | let info = ModelInfoData::new( |
86 | 26 | def.name.clone(), |
87 | 26 | def.source.clone(), |
88 | 26 | def.is_multilingual, |
89 | 26 | def.is_online(), |
90 | 26 | def.processing_interval, |
91 | 26 | ); |
92 | | // Websocket capability is a per-backend flag (every model the backend |
93 | | // serves shares it), carried through discovery so a ws-capable |
94 | | // component is linked against the realtime world. It used to be read |
95 | | // back off `backend.toml` here; discovery already parsed the manifest, |
96 | | // and the header path below asks the same object a question on every |
97 | | // settings write, where a disk read would not be affordable. |
98 | 26 | let websocket_capability = backend.capabilities.websocket; |
99 | | // Egress = the manifest-pinned `allowed_hosts` (fully SSRF-guarded) plus |
100 | | // what the user authorized via the `base_url` option, whose `host:port` |
101 | | // may be local or private. |
102 | 26 | let inst = crate::stt_models::wasm::WasmBackend::with_info( |
103 | 26 | &component, |
104 | 26 | backend.allowed_hosts.clone(), |
105 | 26 | context.user_allowed_hosts, |
106 | 26 | info, |
107 | 26 | context.headers, |
108 | 26 | websocket_capability, |
109 | 26 | def.realtime, |
110 | 26 | )?16 |
111 | 10 | .with_user_context(context.context); |
112 | 10 | Ok(Box::new(inst)) |
113 | 30 | } |
114 | | |
115 | 0 | async fn instantiate_subprocess( |
116 | 0 | &self, |
117 | 0 | backend: &DiscoveredBackend, |
118 | 0 | def: &ModelDefinition, |
119 | 0 | device_pref: &str, |
120 | 0 | stage: crate::daemon::device_management::PipelineStage, |
121 | 0 | ) -> Result<Box<dyn Transcribe>> { |
122 | 0 | let name = def.name.as_str(); |
123 | | // The same secret/option headers the WASM transport is handed: a |
124 | | // subprocess backend reads its `[[options]]` off the request too. |
125 | | // Resolved before the download tracker exists, so a missing required |
126 | | // secret fails the load without leaving a progress card behind. |
127 | 0 | let context = self.backend_context(backend, def).await?; |
128 | | |
129 | | // Count the files we'll provision so the tracker's denominator is |
130 | | // accurate from the first broadcast. Each `[[models.files]]` entry is |
131 | | // one file. Empty-files models (cloud-only) skip the tracker entirely — |
132 | | // there is nothing to download. |
133 | 0 | let manifest = crate::stt_models::backends::manifest::Manifest::load(&backend.dir)?; |
134 | 0 | let total_files = manifest |
135 | 0 | .models |
136 | 0 | .iter() |
137 | 0 | .find(|m| m.name == name) |
138 | 0 | .map_or(0, |m| m.files.len()); |
139 | | |
140 | 0 | let tracker = if total_files == 0 { |
141 | 0 | None |
142 | | } else { |
143 | 0 | let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); |
144 | 0 | let t = std::sync::Arc::new( |
145 | 0 | crate::download_progress::DownloadProgressTracker::new( |
146 | 0 | name.to_string(), |
147 | 0 | crate::download_progress::StageSlot { |
148 | 0 | source: backend.source.clone(), |
149 | 0 | stage: stage.position(), |
150 | 0 | }, |
151 | 0 | total_files, |
152 | 0 | cancelled, |
153 | 0 | ) |
154 | 0 | .with_event_bus(std::sync::Arc::clone(&self.events)), |
155 | 0 | ); |
156 | | // Register so `GET /download_status` returns this tracker and the |
157 | | // app's progress card lights up. A previous tracker (from |
158 | | // a failed load) is cleared first — the manager rejects parallel |
159 | | // downloads, but a leftover entry would block this one. |
160 | 0 | self.download_manager.clear_download(stage.position()); |
161 | 0 | if let Err(e) = self |
162 | 0 | .download_manager |
163 | 0 | .start_download(std::sync::Arc::clone(&t)) |
164 | | { |
165 | 0 | log::warn!("could not register download tracker: {e}"); |
166 | 0 | } |
167 | | // Emit the initial state immediately so the UI has something to |
168 | | // show while the first file is checked. The tracker opens in its |
169 | | // `verifying` phase, so a load whose files are all present reports |
170 | | // exactly that and never claims a download. |
171 | 0 | t.broadcast_progress(); |
172 | 0 | Some(t) |
173 | | }; |
174 | | |
175 | 0 | let result = crate::stt_models::subprocess::SubprocessBackend::spawn( |
176 | 0 | &backend.dir, |
177 | 0 | name, |
178 | 0 | device_pref, |
179 | 0 | tracker.as_ref(), |
180 | 0 | context.headers, |
181 | 0 | ) |
182 | 0 | .await |
183 | 0 | .map(|backend| backend.with_user_context(context.context)); |
184 | | |
185 | | // Whatever happened (success, error, cancel), the tracker has done |
186 | | // its job — mark the terminal status and clear the manager so the |
187 | | // UI's progress card collapses and the next load can register. |
188 | 0 | if let Some(t) = &tracker { |
189 | 0 | match &result { |
190 | 0 | Ok(_) => t.mark_completed(), |
191 | 0 | Err(e) => t.mark_error(&format!("{e:#}")), |
192 | | } |
193 | 0 | t.broadcast_progress(); |
194 | 0 | self.download_manager.clear_download(stage.position()); |
195 | 0 | } |
196 | | |
197 | 0 | Ok(Box::new(result?)) |
198 | 0 | } |
199 | | |
200 | | /// Everything the daemon resolves from the user's settings for one model |
201 | | /// of a backend, as the one bundle both a load and a settings write hand |
202 | | /// over. The backend's secrets and options, and the dictation context when |
203 | | /// the model takes one. |
204 | | /// |
205 | | /// The single entry point matters more than the saving: the headers and the |
206 | | /// egress list must come from one snapshot of the options (see |
207 | | /// [`BackendContext`](crate::stt_models::transcribe::BackendContext)), and |
208 | | /// having two callers assemble that pair for themselves is how they would |
209 | | /// come to disagree. A load builds an instance around it; a settings write |
210 | | /// hands the running instance a new one. |
211 | | /// |
212 | | /// # Errors |
213 | | /// Returns an error if a required secret is unset or a declared `base_url` |
214 | | /// names no host. |
215 | 61 | pub(crate) async fn backend_context( |
216 | 61 | &self, |
217 | 61 | backend: &DiscoveredBackend, |
218 | 61 | model: &ModelDefinition, |
219 | 61 | ) -> Result<crate::stt_models::transcribe::BackendContext> { |
220 | 61 | let overrides = self.backend_option_overrides(backend).await?0 ; |
221 | 61 | let headers = self.backend_headers(backend, model, &overrides).await?4 ; |
222 | | // Only the WASM transport can dial anything; a subprocess backend runs |
223 | | // under `PrivateNetwork=yes`, so there is no egress for a `base_url` to |
224 | | // authorize and nothing to derive. |
225 | 57 | let user_allowed_hosts = Self::base_url_egress_hosts(backend, &overrides); |
226 | | Ok(crate::stt_models::transcribe::BackendContext { |
227 | 57 | headers, |
228 | 57 | user_allowed_hosts, |
229 | 57 | context: self.user_context(backend, model).await, |
230 | | }) |
231 | 61 | } |
232 | | |
233 | | /// The user's dictation context for `model` of `backend`, when the model |
234 | | /// takes one: the context in force for the backend, or an empty one when |
235 | | /// none is. `None` when the model takes no context, so that nothing a |
236 | | /// request adds reaches it either. |
237 | | /// |
238 | | /// Gated on the model's declaration rather than sent to everyone, |
239 | | /// because a model that does not read the context headers has no way to |
240 | | /// say so and would silently ignore a vocabulary the user watched |
241 | | /// themselves type. With the declaration, a settings UI can tell them |
242 | | /// which models will actually hear it. |
243 | 126 | async fn user_context( |
244 | 126 | &self, |
245 | 126 | backend: &DiscoveredBackend, |
246 | 126 | model: &ModelDefinition, |
247 | 126 | ) -> Option<DictationContext> { |
248 | 126 | if !model.product.takes_context(&backend.capabilities.product) { |
249 | 70 | return None; |
250 | 56 | } |
251 | | Some( |
252 | 56 | self.config |
253 | 56 | .read() |
254 | 56 | .await |
255 | 56 | .resolve_context(&backend.source) |
256 | | .cloned() |
257 | | .unwrap_or_default(), |
258 | | ) |
259 | 126 | } |
260 | | |
261 | | /// Form the `x-voice-secret-*` / `x-voice-option-*` headers a backend is |
262 | | /// handed on every `/v1` request for `model`, whichever transport carries |
263 | | /// it, and the context headers when `model` takes a context. |
264 | | /// |
265 | | /// Secrets come solely from the daemon's secrets file, by backend source |
266 | | /// and secret name, as the app wrote them — there is no |
267 | | /// legacy `<provider>-api-key` fallback, so the key must be set for this |
268 | | /// specific backend. Options use the config override if set, else the |
269 | | /// manifest default. A required secret that resolves to nothing is an error. |
270 | 73 | async fn backend_headers( |
271 | 73 | &self, |
272 | 73 | backend: &DiscoveredBackend, |
273 | 73 | model: &ModelDefinition, |
274 | 73 | overrides: &std::collections::HashMap<String, String>, |
275 | 73 | ) -> Result<Vec<(String, String)>> { |
276 | 73 | let mut headers = Vec::new(); |
277 | 73 | for secret in &backend.secrets { |
278 | 4 | let value = self |
279 | 4 | .secrets |
280 | 4 | .get_backend_secret(&backend.source, &secret.name) |
281 | 0 | .filter(|v| !v.is_empty()); |
282 | 4 | match value { |
283 | 0 | Some(v) => backend_headers::push( |
284 | 0 | &mut headers, |
285 | 0 | Feature::SpeechToText, |
286 | 0 | &format!("secret-{}", secret.name), |
287 | 0 | v, |
288 | 0 | ), |
289 | | // Safety-net error: the settings UI is expected to surface this |
290 | | // requirement *before* the user can request a model load. If |
291 | | // that pre-flight is bypassed (a UI bug, or a non-UI client), |
292 | | // the daemon is the final guard — keep the message short and |
293 | | // user-facing rather than naming internals (`secret name`, |
294 | | // `backend source`), since the caller already chose this |
295 | | // backend. |
296 | 4 | None if secret.required => bail!( |
297 | | "{} must be set.", |
298 | 4 | secret.label.as_deref().unwrap_or(&secret.name) |
299 | | ), |
300 | 0 | None => {} |
301 | | } |
302 | | } |
303 | 69 | for opt in &backend.options { |
304 | 8 | if let Some(v) = resolved_backend_option(overrides, opt) { |
305 | 7 | backend_headers::push( |
306 | 7 | &mut headers, |
307 | 7 | Feature::SpeechToText, |
308 | 7 | &format!("option-{}", opt.name), |
309 | 7 | v, |
310 | 7 | ); |
311 | 1 | } |
312 | | } |
313 | | // The user's dictation context, for a model that said it can use one. |
314 | | // Read last and in a scope of its own: no await may happen under the |
315 | | // config guard, and everything above this works from the secrets in |
316 | | // memory or the `overrides` snapshot it was handed. |
317 | 69 | if let Some(context) = self.user_context(backend, model).await { |
318 | 31 | push_context(&mut headers, &context); |
319 | 38 | } |
320 | 69 | Ok(headers) |
321 | 73 | } |
322 | | |
323 | | /// Snapshot of the user's option overrides for one backend. |
324 | | /// |
325 | | /// Taken once per load and shared by header injection and egress |
326 | | /// derivation. Resolving them separately let a config write land in |
327 | | /// between, so the component could be handed one gateway while a different |
328 | | /// one was authorized, and every request would then be refused until the |
329 | | /// model was reloaded. Cloned rather than held as a guard: the header path |
330 | | /// awaits, and a read guard spanning that would block config writers for |
331 | | /// its duration. |
332 | | /// |
333 | | /// `base_url` is canonicalized on the way out (see |
334 | | /// [`normalize`](backends::base_url::normalize)). It is the one value the |
335 | | /// two paths must read *identically* — one dials it, the other authorizes |
336 | | /// what it names — and the component is handed it verbatim, so the rewrite |
337 | | /// that keeps the pair consistent is also what spares every backend its own |
338 | | /// URL parser. Every other option is passed through exactly as the user set |
339 | | /// it: whitespace may carry meaning in a value the daemon does not |
340 | | /// interpret. |
341 | | /// |
342 | | /// The two ways a value can fail are not the same failure. One that is only |
343 | | /// whitespace is no value at all: it is dropped, so it neither reaches the |
344 | | /// component nor authorizes anything, and the backend falls back to its |
345 | | /// built-in endpoint exactly as if nothing were set. One the daemon cannot |
346 | | /// read as a URL is a setting the user meant, so it fails the load instead — |
347 | | /// dropping it would fall back to that same built-in endpoint and send the |
348 | | /// user's audio and credentials to the vendor they had configured their way |
349 | | /// out of. |
350 | | /// |
351 | | /// A value stored for an option this backend does not declare is inert — |
352 | | /// nothing injects or authorizes it — so it is left alone rather than |
353 | | /// validated. |
354 | | /// |
355 | | /// # Errors |
356 | | /// Returns an error when a declared, non-empty `base_url` yields no host. |
357 | 70 | async fn backend_option_overrides( |
358 | 70 | &self, |
359 | 70 | backend: &DiscoveredBackend, |
360 | 70 | ) -> Result<std::collections::HashMap<String, String>> { |
361 | | #[allow(unused_mut)] // mutated only by the canonicalization below |
362 | 70 | let mut overrides: std::collections::HashMap<String, String> = self |
363 | 70 | .config |
364 | 70 | .read() |
365 | 70 | .await |
366 | | .backends |
367 | | .options |
368 | 70 | .get(&backend.source) |
369 | | .cloned() |
370 | | .unwrap_or_default(); |
371 | | // `base_url` is an endpoint to dial, and only the WASM transport can |
372 | | // dial anything — a subprocess backend has no network. Reading it |
373 | | // shares the WASM host's URL code. |
374 | 70 | super_engine_daemon::wasm::base_url::canonicalize_override(backend, &mut overrides)?1 ; |
375 | 69 | Ok(overrides) |
376 | 70 | } |
377 | | |
378 | | /// What the *user* authorized via a `base_url` option. See |
379 | | /// `super_engine_daemon::wasm::base_url::egress_hosts`. |
380 | 65 | fn base_url_egress_hosts( |
381 | 65 | backend: &DiscoveredBackend, |
382 | 65 | overrides: &std::collections::HashMap<String, String>, |
383 | 65 | ) -> Vec<String> { |
384 | 65 | super_engine_daemon::wasm::base_url::egress_hosts(backend, overrides) |
385 | 65 | } |
386 | | } |
387 | | |
388 | | /// The effective value of a backend option — the user's override if set, else |
389 | | /// the manifest default — as injected into the backend's headers by |
390 | | /// [`SuperSTTDaemon::backend_headers`]. |
391 | | /// |
392 | | /// Not what authorizes egress: `base_url_egress_hosts` deliberately reads the |
393 | | /// override alone, because a manifest default is the backend author's value and |
394 | | /// must not widen the sandbox. The settings-facing read path |
395 | | /// (`http/v1/backends/options.rs::effective`) resolves the same two sources |
396 | | /// separately, for display. |
397 | 8 | fn resolved_backend_option( |
398 | 8 | overrides: &std::collections::HashMap<String, String>, |
399 | 8 | opt: &backends::manifest::Opt, |
400 | 8 | ) -> Option<String> { |
401 | 8 | overrides |
402 | 8 | .get(&opt.name) |
403 | 8 | .cloned() |
404 | 1 | .or_else(|| opt.default.as_ref().map(ToString::to_string)) |
405 | 8 | } |
406 | | |
407 | | #[cfg(test)] |
408 | | mod tests { |
409 | | use super::SuperSTTDaemon; |
410 | | |
411 | | /// Only a user-set `base_url` feeds the egress allowlist, as the endpoint it |
412 | | /// names followed by its bare host. A backend declaring no such option, and |
413 | | /// one the user has not configured, both contribute nothing — a manifest |
414 | | /// value must never widen the sandbox. |
415 | | #[tokio::test] |
416 | 1 | async fn base_url_egress_hosts_resolves_override_or_default() { |
417 | | use crate::daemon::test_fixtures::openai_backend; |
418 | | use crate::daemon::types::test_daemon; |
419 | | use crate::stt_models::backends::DiscoveredBackend; |
420 | | |
421 | 1 | let daemon = test_daemon().await; |
422 | 1 | let source = "github.com/super-stt/openai"; |
423 | | // The manifest default is one `Manifest::parse` would reject; it is here |
424 | | // to prove this read does not depend on that rejection. |
425 | 1 | let backend = openai_backend(source, Vec::new(), Some("https://api.openai.com")); |
426 | | |
427 | | // No override → nothing, even though the option carries a default: a |
428 | | // value the backend author wrote must not authorize egress. |
429 | 1 | let overrides = daemon |
430 | 1 | .backend_option_overrides(&backend) |
431 | 1 | .await |
432 | 1 | .expect("a valid base_url"); |
433 | 1 | assert!(SuperSTTDaemon::base_url_egress_hosts(&backend, &overrides).is_empty()); |
434 | | |
435 | | // Config override pointing at a local gateway → that endpoint, port kept. |
436 | | // Only the `host:port` entry carries the relaxation, so the bare host |
437 | | // opens no other local port. |
438 | 1 | daemon |
439 | 1 | .config |
440 | 1 | .write() |
441 | 1 | .await |
442 | | .backends |
443 | | .options |
444 | 1 | .entry(source.to_string()) |
445 | | .or_default() |
446 | 1 | .insert("base_url".to_string(), "http://localhost:8080".to_string()); |
447 | 1 | let overrides = daemon |
448 | 1 | .backend_option_overrides(&backend) |
449 | 1 | .await |
450 | 1 | .expect("a valid base_url"); |
451 | 1 | assert_eq!( |
452 | 1 | SuperSTTDaemon::base_url_egress_hosts(&backend, &overrides), |
453 | 1 | vec!["localhost:8080", "localhost"] |
454 | | ); |
455 | | |
456 | | // A backend declaring no `base_url` option contributes nothing, even |
457 | | // with the override still in config. |
458 | 1 | let no_base = DiscoveredBackend { |
459 | 1 | description: String::new(), |
460 | 1 | options: vec![], |
461 | 1 | ..backend |
462 | 1 | }; |
463 | 1 | assert!(SuperSTTDaemon::base_url_egress_hosts(&no_base, &overrides).is_empty()); |
464 | 1 | } |
465 | | |
466 | | /// A `base_url` pasted with surrounding whitespace must reach both paths as |
467 | | /// the same string: the component dials the header it is given, and the |
468 | | /// daemon authorizes what the value names. A value that is only whitespace |
469 | | /// is no value — it must not be injected or authorize anything. |
470 | | #[tokio::test] |
471 | 1 | async fn whitespace_in_base_url_cannot_split_the_two_paths() { |
472 | | use crate::daemon::test_fixtures::openai_backend; |
473 | | use crate::daemon::types::test_daemon; |
474 | | use crate::stt_models::backends::DiscoveredBackend; |
475 | | |
476 | 1 | let daemon = test_daemon().await; |
477 | 1 | let source = "github.com/super-stt/openai"; |
478 | | // No secrets: the assertions run through the real header path, which |
479 | | // would otherwise refuse the fixture's required key, unset here. |
480 | 1 | let backend = DiscoveredBackend { |
481 | 1 | description: String::new(), |
482 | 1 | secrets: Vec::new(), |
483 | 1 | ..openai_backend(source, Vec::new(), None) |
484 | 1 | }; |
485 | | |
486 | 1 | for (stored, expected_header) in [ |
487 | 1 | (" http://10.0.0.5:8080 ", Some("http://10.0.0.5:8080")), |
488 | 1 | ("\thttp://10.0.0.5:8080\n", Some("http://10.0.0.5:8080")), |
489 | 1 | (" ", None), |
490 | 1 | ] { |
491 | 3 | daemon |
492 | 3 | .config |
493 | 3 | .write() |
494 | 3 | .await |
495 | 1 | .backends |
496 | 1 | .options |
497 | 3 | .entry(source.to_string()) |
498 | 1 | .or_default() |
499 | 3 | .insert("base_url".to_string(), stored.to_string()); |
500 | 1 | |
501 | 3 | let overrides = daemon |
502 | 3 | .backend_option_overrides(&backend) |
503 | 3 | .await |
504 | 3 | .expect("a valid base_url"); |
505 | 3 | let headers = daemon |
506 | 3 | .backend_headers( |
507 | 3 | &backend, |
508 | 3 | &crate::daemon::test_fixtures::transcription_model(source), |
509 | 3 | &overrides, |
510 | 3 | ) |
511 | 3 | .await |
512 | 3 | .expect("headers for a secret-free backend"); |
513 | 3 | let injected = headers |
514 | 3 | .iter() |
515 | 2 | .find(|(k, _)| k == "x-voice-option-base_url") |
516 | 2 | .map(|(_, v)| v.as_str()); |
517 | 3 | let egress = SuperSTTDaemon::base_url_egress_hosts(&backend, &overrides); |
518 | 3 | assert_eq!(injected, expected_header, "header for {stored:?}"); |
519 | 3 | match expected_header { |
520 | 2 | Some(_) => assert_eq!(egress, vec!["10.0.0.5:8080", "10.0.0.5"]), |
521 | 1 | None => assert!(egress.is_empty(), "egress for {stored:?}"), |
522 | 1 | } |
523 | 1 | } |
524 | 1 | } |
525 | | |
526 | | /// The component is handed the canonical form, not the string the user |
527 | | /// typed. A backend dials this value directly, so the rewrite and the |
528 | | /// authorization have to describe one endpoint — and a backend reading it |
529 | | /// can split at the first `/` rather than carry a URL parser of its own. |
530 | | #[tokio::test] |
531 | 1 | async fn the_injected_base_url_is_canonical() { |
532 | | use crate::daemon::test_fixtures::openai_backend; |
533 | | use crate::daemon::types::test_daemon; |
534 | | use crate::stt_models::backends::DiscoveredBackend; |
535 | | |
536 | 1 | let daemon = test_daemon().await; |
537 | 1 | let source = "github.com/super-stt/openai"; |
538 | | // No secrets: this drives the real header path, which would otherwise |
539 | | // refuse the fixture's required key, unset here. |
540 | 1 | let backend = DiscoveredBackend { |
541 | 1 | description: String::new(), |
542 | 1 | secrets: Vec::new(), |
543 | 1 | ..openai_backend(source, Vec::new(), None) |
544 | 1 | }; |
545 | 1 | daemon |
546 | 1 | .config |
547 | 1 | .write() |
548 | 1 | .await |
549 | | .backends |
550 | | .options |
551 | 1 | .entry(source.to_string()) |
552 | | .or_default() |
553 | | .insert( |
554 | 1 | "base_url".to_string(), |
555 | 1 | " HTTPS://user:pass@gw.example.com:8443/v1/?k=v ".to_string(), |
556 | | ); |
557 | | |
558 | 1 | let overrides = daemon |
559 | 1 | .backend_option_overrides(&backend) |
560 | 1 | .await |
561 | 1 | .expect("a valid base_url"); |
562 | 1 | let headers = daemon |
563 | 1 | .backend_headers( |
564 | 1 | &backend, |
565 | 1 | &crate::daemon::test_fixtures::transcription_model(source), |
566 | 1 | &overrides, |
567 | 1 | ) |
568 | 1 | .await |
569 | 1 | .expect("headers for a secret-free backend"); |
570 | 1 | let injected = headers |
571 | 1 | .iter() |
572 | 1 | .find(|(k, _)| k == "x-voice-option-base_url") |
573 | 1 | .map(|(_, v)| v.as_str()); |
574 | 1 | assert_eq!(injected, Some("https://gw.example.com:8443/v1")); |
575 | 1 | assert_eq!( |
576 | 1 | SuperSTTDaemon::base_url_egress_hosts(&backend, &overrides), |
577 | 1 | vec!["gw.example.com:8443", "gw.example.com"] |
578 | 1 | ); |
579 | 1 | } |
580 | | |
581 | | /// A value the daemon cannot read fails the load rather than being dropped: |
582 | | /// dropping it would fall back to the backend's built-in endpoint and send |
583 | | /// the user's audio and credentials to the vendor they had configured their |
584 | | /// way out of. The error names the setting, not the internals. |
585 | | /// |
586 | | /// The same stored value is inert for a backend declaring no such option — |
587 | | /// nothing injects or authorizes it — so it must not block that load. |
588 | | #[tokio::test] |
589 | 1 | async fn an_unreadable_base_url_fails_the_load() { |
590 | | use crate::daemon::test_fixtures::openai_backend; |
591 | | use crate::daemon::types::test_daemon; |
592 | | use crate::stt_models::backends::DiscoveredBackend; |
593 | | |
594 | 1 | let daemon = test_daemon().await; |
595 | 1 | let source = "github.com/super-stt/openai"; |
596 | 1 | let backend = openai_backend(source, Vec::new(), None); |
597 | 1 | daemon |
598 | 1 | .config |
599 | 1 | .write() |
600 | 1 | .await |
601 | | .backends |
602 | | .options |
603 | 1 | .entry(source.to_string()) |
604 | | .or_default() |
605 | 1 | .insert("base_url".to_string(), "http://".to_string()); |
606 | | |
607 | 1 | let err = daemon |
608 | 1 | .backend_option_overrides(&backend) |
609 | 1 | .await |
610 | 1 | .expect_err("an unreadable base_url fails the load"); |
611 | 1 | assert!(err.to_string().contains("API base URL"), "{err}"); |
612 | | |
613 | 1 | let undeclared = DiscoveredBackend { |
614 | 1 | description: String::new(), |
615 | 1 | options: Vec::new(), |
616 | 1 | ..backend |
617 | 1 | }; |
618 | 1 | assert!( |
619 | 1 | daemon.backend_option_overrides(&undeclared).await.is_ok(), |
620 | 1 | "a value for an undeclared option must not block a load" |
621 | 1 | ); |
622 | 1 | } |
623 | | |
624 | | /// Headers and egress must describe one config state. Resolving them |
625 | | /// separately let a write land in between, handing the component one |
626 | | /// endpoint while a different one was authorized; both now read the same |
627 | | /// snapshot, so the pair either sees the write or does not. |
628 | | #[tokio::test] |
629 | 1 | async fn headers_and_egress_read_the_same_snapshot() { |
630 | | use crate::daemon::test_fixtures::openai_backend; |
631 | | use crate::daemon::types::test_daemon; |
632 | | use crate::stt_models::backends::DiscoveredBackend; |
633 | | |
634 | 1 | let daemon = test_daemon().await; |
635 | 1 | let source = "github.com/super-stt/openai"; |
636 | | // No secrets: this drives the real `backend_headers`, which would |
637 | | // otherwise refuse the fixture's required key, unset here. |
638 | 1 | let backend = DiscoveredBackend { |
639 | 1 | description: String::new(), |
640 | 1 | secrets: Vec::new(), |
641 | 1 | ..openai_backend(source, Vec::new(), None) |
642 | 1 | }; |
643 | 1 | daemon |
644 | 1 | .config |
645 | 1 | .write() |
646 | 1 | .await |
647 | | .backends |
648 | | .options |
649 | 1 | .entry(source.to_string()) |
650 | | .or_default() |
651 | 1 | .insert("base_url".to_string(), "http://10.0.0.5:8080".to_string()); |
652 | | |
653 | 1 | let overrides = daemon |
654 | 1 | .backend_option_overrides(&backend) |
655 | 1 | .await |
656 | 1 | .expect("a valid base_url"); |
657 | | // A write landing here reaches neither side, which is the point. |
658 | 1 | daemon |
659 | 1 | .config |
660 | 1 | .write() |
661 | 1 | .await |
662 | | .backends |
663 | | .options |
664 | 1 | .entry(source.to_string()) |
665 | | .or_default() |
666 | 1 | .insert("base_url".to_string(), "http://10.0.0.9:8080".to_string()); |
667 | | |
668 | | // Drive the real header path, not the resolver it happens to call: the |
669 | | // regression this pins is `backend_headers` reading config for itself. |
670 | 1 | let headers = daemon |
671 | 1 | .backend_headers( |
672 | 1 | &backend, |
673 | 1 | &crate::daemon::test_fixtures::transcription_model(source), |
674 | 1 | &overrides, |
675 | 1 | ) |
676 | 1 | .await |
677 | 1 | .expect("headers for a secret-free backend"); |
678 | 1 | let injected = headers |
679 | 1 | .iter() |
680 | 1 | .find(|(k, _)| k == "x-voice-option-base_url") |
681 | 1 | .map(|(_, v)| v.as_str()) |
682 | 1 | .expect("base_url is injected from the snapshot"); |
683 | 1 | let egress = SuperSTTDaemon::base_url_egress_hosts(&backend, &overrides); |
684 | 1 | assert_eq!(injected, "http://10.0.0.5:8080"); |
685 | 1 | assert_eq!(egress, vec!["10.0.0.5:8080", "10.0.0.5"]); |
686 | 1 | } |
687 | | |
688 | | /// A model that did not ask for a context is not handed one, and one that |
689 | | /// did is, under both header names. |
690 | | /// |
691 | | /// The gate is not tidiness: a model that ignores these headers has no way |
692 | | /// to say so, and the user would watch themselves type a vocabulary that |
693 | | /// reached nothing. The declaration is what lets a settings UI tell them |
694 | | /// which models will actually hear it. |
695 | | #[tokio::test] |
696 | 1 | async fn a_context_reaches_only_a_model_that_declared_it() { |
697 | | use crate::daemon::test_fixtures::{openai_backend, transcription_model}; |
698 | | use crate::daemon::types::test_daemon; |
699 | | use crate::stt_models::backends::DiscoveredBackend; |
700 | | use super_voice_shared::models::contexts::DictationContext; |
701 | | |
702 | 1 | let daemon = test_daemon().await; |
703 | 1 | let source = "github.com/super-stt/openai"; |
704 | 1 | let backend = DiscoveredBackend { |
705 | 1 | secrets: Vec::new(), |
706 | 1 | options: Vec::new(), |
707 | 1 | ..openai_backend(source, Vec::new(), None) |
708 | 1 | }; |
709 | 1 | daemon |
710 | 1 | .handle_set_context(DictationContext { |
711 | 1 | id: "coding".to_string(), |
712 | 1 | name: "Coding".to_string(), |
713 | 1 | prompt: "I dictate code.".to_string(), |
714 | 1 | vocabulary: vec!["kubectl".to_string()], |
715 | 1 | }) |
716 | 1 | .await; |
717 | 1 | daemon |
718 | 1 | .handle_set_active_context(Some("coding".to_string())) |
719 | 1 | .await; |
720 | 1 | let none = std::collections::HashMap::new(); |
721 | | |
722 | 1 | let without = daemon |
723 | 1 | .backend_headers(&backend, &transcription_model(source), &none) |
724 | 1 | .await |
725 | 1 | .expect("headers"); |
726 | 1 | assert!( |
727 | 1 | !without |
728 | 1 | .iter() |
729 | 0 | .any(|(k, _)| k.ends_with("-prompt") || k.ends_with("-vocabulary")), |
730 | | "not declared, no context headers: {without:?}" |
731 | | ); |
732 | | |
733 | 1 | let mut declared = transcription_model(source); |
734 | 1 | declared.product.accepts_context = true; |
735 | 1 | let with = daemon |
736 | 1 | .backend_headers(&backend, &declared, &none) |
737 | 1 | .await |
738 | 1 | .expect("headers"); |
739 | 4 | let value = |name: &str| { |
740 | 4 | with.iter() |
741 | 10 | .find(|(k, _)| k == name) |
742 | 4 | .map(|(_, v)| v.as_str()) |
743 | 4 | }; |
744 | | // Under its name, and under the name a backend built before it reads. |
745 | 1 | for name in ["x-voice-prompt", "x-stt-prompt"] { |
746 | 2 | assert_eq!(value(name), Some(r#""I dictate code.""#), "{name}"); |
747 | | } |
748 | 1 | for name in ["x-voice-vocabulary", "x-stt-vocabulary"] { |
749 | 2 | assert_eq!(value(name), Some(r#"["kubectl"]"#), "{name}"); |
750 | | } |
751 | | |
752 | | // The bundle a load hands the backend keeps the user's context whole, |
753 | | // for a dictation's own to be added to, under the same rule. |
754 | 2 | let context = |model| { |
755 | 2 | let daemon = &daemon; |
756 | 2 | let backend = &backend; |
757 | 2 | async move { |
758 | 2 | daemon |
759 | 2 | .backend_context(backend, &model) |
760 | 2 | .await |
761 | 2 | .expect("a context") |
762 | | .context |
763 | 2 | } |
764 | 2 | }; |
765 | 1 | assert_eq!(context(transcription_model(source)).await, None); |
766 | 1 | let kept = context(declared).await.expect("the user's context"); |
767 | 1 | assert_eq!(kept.vocabulary, ["kubectl"]); |
768 | 1 | } |
769 | | |
770 | | /// A backend still declaring the deprecated `[capabilities] context` hands |
771 | | /// the context to each of its speech-to-text models, as it did before the |
772 | | /// models could say it themselves: the backends published with it keep |
773 | | /// their context until they move. |
774 | | #[tokio::test] |
775 | 1 | async fn the_deprecated_backend_flag_still_hands_every_model_the_context() { |
776 | | use crate::daemon::test_fixtures::{openai_backend, transcription_model}; |
777 | | use crate::daemon::types::test_daemon; |
778 | | use crate::stt_models::backends::DiscoveredBackend; |
779 | | use super_voice_shared::models::contexts::DictationContext; |
780 | | |
781 | 1 | let daemon = test_daemon().await; |
782 | 1 | let source = "github.com/super-stt/openai"; |
783 | 1 | let backend = DiscoveredBackend { |
784 | 1 | secrets: Vec::new(), |
785 | 1 | options: Vec::new(), |
786 | 1 | capabilities: super_voice_registry_types::manifest::Capabilities { |
787 | 1 | websocket: false, |
788 | 1 | product: super_voice_registry_types::manifest::VoiceCapabilities { |
789 | 1 | context: true, |
790 | 1 | ..Default::default() |
791 | 1 | }, |
792 | 1 | }, |
793 | 1 | ..openai_backend(source, Vec::new(), None) |
794 | 1 | }; |
795 | 1 | daemon |
796 | 1 | .handle_set_context(DictationContext { |
797 | 1 | id: "coding".to_string(), |
798 | 1 | name: "Coding".to_string(), |
799 | 1 | prompt: "I dictate code.".to_string(), |
800 | 1 | vocabulary: Vec::new(), |
801 | 1 | }) |
802 | 1 | .await; |
803 | 1 | daemon |
804 | 1 | .handle_set_active_context(Some("coding".to_string())) |
805 | 1 | .await; |
806 | | |
807 | 1 | let headers = daemon |
808 | 1 | .backend_headers( |
809 | 1 | &backend, |
810 | 1 | &transcription_model(source), |
811 | 1 | &std::collections::HashMap::new(), |
812 | 1 | ) |
813 | 1 | .await |
814 | 1 | .expect("headers"); |
815 | 1 | assert!( |
816 | 1 | headers.iter().any(|(k, _)| k == "x-voice-prompt"), |
817 | 1 | "{headers:?}" |
818 | 1 | ); |
819 | 1 | } |
820 | | |
821 | | /// Both headers must survive the round trip a backend actually makes: |
822 | | /// built into a `HeaderValue`, read back out with `to_str`, and decoded. |
823 | | /// |
824 | | /// This is the test that catches the naive encoder. `HeaderValue` is |
825 | | /// asymmetric — it accepts any byte from `0x80` up at construction and then |
826 | | /// refuses those same bytes in `to_str` — so `serde_json::to_string`, which |
827 | | /// emits non-ASCII as itself, produces a header the daemon considers valid |
828 | | /// and the backend cannot read. The symptom is a context that silently goes |
829 | | /// missing for the users whose words have accents in them. |
830 | | #[tokio::test] |
831 | 1 | async fn a_context_survives_the_header_round_trip_in_any_language() { |
832 | | use crate::daemon::test_fixtures::openai_backend; |
833 | | use crate::daemon::types::test_daemon; |
834 | | use crate::stt_models::backends::DiscoveredBackend; |
835 | | use axum::http::HeaderValue; |
836 | | use super_voice_shared::models::contexts::DictationContext; |
837 | | |
838 | 1 | let daemon = test_daemon().await; |
839 | 1 | let source = "github.com/super-stt/openai"; |
840 | 1 | let backend = DiscoveredBackend { |
841 | 1 | secrets: Vec::new(), |
842 | 1 | options: Vec::new(), |
843 | 1 | ..openai_backend(source, Vec::new(), None) |
844 | 1 | }; |
845 | | |
846 | 1 | let prompt = "Dicto código.\nPrefiere términos de programación — \"main branch\"."; |
847 | 1 | let vocabulary = vec![ |
848 | 1 | "Menjivar, Jorge".to_string(), |
849 | 1 | "café".to_string(), |
850 | 1 | "\u{1f680} deploy".to_string(), |
851 | 1 | "back\\slash".to_string(), |
852 | | ]; |
853 | 1 | daemon |
854 | 1 | .handle_set_context(DictationContext { |
855 | 1 | id: "coding".to_string(), |
856 | 1 | name: "Coding".to_string(), |
857 | 1 | prompt: prompt.to_string(), |
858 | 1 | vocabulary: vocabulary.clone(), |
859 | 1 | }) |
860 | 1 | .await; |
861 | 1 | daemon |
862 | 1 | .handle_set_active_context(Some("coding".to_string())) |
863 | 1 | .await; |
864 | | |
865 | 1 | let headers = daemon |
866 | 1 | .backend_headers( |
867 | 1 | &backend, |
868 | 1 | &crate::daemon::test_fixtures::context_model(source), |
869 | 1 | &std::collections::HashMap::new(), |
870 | 1 | ) |
871 | 1 | .await |
872 | 1 | .expect("headers"); |
873 | | |
874 | 1 | for (name, raw) in &headers { |
875 | 4 | assert!( |
876 | 4 | raw.is_ascii(), |
877 | | "{name} is not pure ASCII, so `to_str` will refuse it: {raw}" |
878 | | ); |
879 | 4 | let value = HeaderValue::from_str(raw) |
880 | 0 | .unwrap_or_else(|e| panic!("{name} is not a valid header value: {e}")); |
881 | 4 | value |
882 | 4 | .to_str() |
883 | 0 | .unwrap_or_else(|e| panic!("{name} built but cannot be read back: {e}")); |
884 | | } |
885 | | |
886 | 2 | let read_back = |name: &str| -> String { |
887 | 2 | let raw = headers |
888 | 2 | .iter() |
889 | 4 | .find(|(k, _)| k == name) |
890 | 2 | .map(|(_, v)| v.clone()) |
891 | 0 | .unwrap_or_else(|| panic!("{name} is missing")); |
892 | 2 | HeaderValue::from_str(&raw) |
893 | 2 | .expect("valid header") |
894 | 2 | .to_str() |
895 | 2 | .expect("readable header") |
896 | 2 | .to_string() |
897 | 2 | }; |
898 | | |
899 | 1 | assert_eq!( |
900 | 1 | serde_json::from_str::<String>(&read_back("x-voice-prompt")).expect("decodes"), |
901 | 1 | prompt, |
902 | | "the prompt comes back exactly as the user typed it, newline and all" |
903 | | ); |
904 | 1 | assert_eq!( |
905 | 1 | serde_json::from_str::<Vec<String>>(&read_back("x-voice-vocabulary")).expect("decodes"), |
906 | 1 | vocabulary, |
907 | 1 | "a term holding a comma stays one term — that is why this is an array" |
908 | 1 | ); |
909 | 1 | } |
910 | | |
911 | | /// Half a context is a context. A backend reading one field and not the |
912 | | /// other should never have to tell "absent" from "empty". |
913 | | #[tokio::test] |
914 | 1 | async fn each_half_of_a_context_is_sent_only_when_it_has_something_in_it() { |
915 | | use crate::daemon::test_fixtures::openai_backend; |
916 | | use crate::daemon::types::test_daemon; |
917 | | use crate::stt_models::backends::DiscoveredBackend; |
918 | | use super_voice_shared::models::contexts::DictationContext; |
919 | | |
920 | 1 | let daemon = test_daemon().await; |
921 | 1 | let source = "github.com/super-stt/openai"; |
922 | 1 | let backend = DiscoveredBackend { |
923 | 1 | secrets: Vec::new(), |
924 | 1 | options: Vec::new(), |
925 | 1 | ..openai_backend(source, Vec::new(), None) |
926 | 1 | }; |
927 | | |
928 | 1 | let cases = [ |
929 | 1 | ( |
930 | 1 | "terms-only", |
931 | 1 | String::new(), |
932 | 1 | vec!["kubectl".to_string()], |
933 | 1 | false, |
934 | 1 | true, |
935 | 1 | ), |
936 | 1 | ( |
937 | 1 | "prompt-only", |
938 | 1 | "Be terse.".to_string(), |
939 | 1 | Vec::new(), |
940 | 1 | true, |
941 | 1 | false, |
942 | 1 | ), |
943 | 1 | // Stored, but with nothing in either half: no headers at all. |
944 | 1 | ("empty", " ".to_string(), Vec::new(), false, false), |
945 | 1 | ]; |
946 | 1 | for (id, prompt, vocabulary, wants_prompt, wants_terms) in cases { |
947 | 3 | daemon |
948 | 3 | .handle_set_context(DictationContext { |
949 | 3 | id: id.to_string(), |
950 | 3 | name: id.to_string(), |
951 | 3 | prompt, |
952 | 3 | vocabulary, |
953 | 3 | }) |
954 | 3 | .await; |
955 | 3 | daemon.handle_set_active_context(Some(id.to_string())).await; |
956 | 1 | |
957 | 3 | let headers = daemon |
958 | 3 | .backend_headers( |
959 | 3 | &backend, |
960 | 3 | &crate::daemon::test_fixtures::context_model(source), |
961 | 3 | &std::collections::HashMap::new(), |
962 | 3 | ) |
963 | 3 | .await |
964 | 3 | .expect("headers"); |
965 | 3 | assert_eq!( |
966 | 3 | headers.iter().any(|(k, _)| k == "x-voice-prompt"), |
967 | 3 | wants_prompt, |
968 | 1 | "x-voice-prompt for {id}: {headers:?}" |
969 | 1 | ); |
970 | 3 | assert_eq!( |
971 | 3 | headers.iter().any(|(k, _)| k == "x-voice-vocabulary"), |
972 | 3 | wants_terms, |
973 | 1 | "x-voice-vocabulary for {id}: {headers:?}" |
974 | 1 | ); |
975 | 1 | } |
976 | 1 | } |
977 | | } |