super-voice-app-core/src/events.rs
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-3.0-only |
2 | | //! What the daemon tells an app as it happens: its `/events` stream, read into |
3 | | //! [`Event`]s. |
4 | | //! |
5 | | //! The stream heals itself: a dropped connection, an idle one, or a revoked |
6 | | //! token is reconnected with backoff. An app hears that the stream dropped |
7 | | //! ([`Event::Disconnected`]: the daemon may be gone), that it is live again |
8 | | //! ([`Event::Connected`]), or that the user refused it for good |
9 | | //! ([`Event::Blocked`]). |
10 | | |
11 | | use futures_util::{Stream, StreamExt}; |
12 | | use log::warn; |
13 | | use serde_json::Value; |
14 | | use super_voice_shared::daemon::http_client::WidgetEvent; |
15 | | use super_voice_shared::daemon::widget_subscription::{ |
16 | | WidgetSubscriptionConfig, WidgetSubscriptionUpdate, run_widget_subscription, |
17 | | }; |
18 | | use super_voice_shared::models::protocol::NotificationEvent; |
19 | | use super_voice_shared::registry::events::RegistryEvent; |
20 | | use super_voice_shared::validation::get_http_socket_path; |
21 | | |
22 | | use crate::daemon::client::SETTINGS_SCOPES; |
23 | | |
24 | | /// The topics an app subscribes to. |
25 | | /// |
26 | | /// `recording_state` drives the recording badge (`recording_events`), |
27 | | /// `frequency_bands` the microphone meter (`audio_visualization`), |
28 | | /// `speaking_state` the speaking badge (`playback_events`), |
29 | | /// `playback_frequency_bands` the playback meter (`audio_visualization`), and |
30 | | /// `daemon_status_changed` / `download_progress` / `registry_install` the |
31 | | /// model-switch progress and the Library's install cards (`daemon_status`), |
32 | | /// and `typing_failed` the toast for a dictation that went to the clipboard |
33 | | /// (`global_transcriptions`, since it carries the words). |
34 | | /// `transcribing_started` / `transcribing_stopped` say the daemon is turning |
35 | | /// a take into words (`recording_events`), and `speech_progress` how much of |
36 | | /// an utterance has been spoken (`playback_events`). |
37 | | /// |
38 | | /// Oldest first: a new topic goes at the end. A daemon older than the app |
39 | | /// refuses a topic it doesn't know (`400 invalid_topic`), and [`subscribe`] |
40 | | /// then asks again without the newest ones. |
41 | | pub const TOPICS: &[&str] = &[ |
42 | | "recording_state", |
43 | | "frequency_bands", |
44 | | "speaking_state", |
45 | | "playback_frequency_bands", |
46 | | "daemon_status_changed", |
47 | | "download_progress", |
48 | | "registry_install", |
49 | | "typing_failed", |
50 | | "transcribing_started", |
51 | | "transcribing_stopped", |
52 | | "speech_progress", |
53 | | ]; |
54 | | |
55 | | /// Something the daemon said, or the stream itself. |
56 | | #[derive(Debug, Clone)] |
57 | | pub enum Event { |
58 | | /// The stream is live, first or again. What happened while it was down |
59 | | /// was missed, so anything shown from it is read again. |
60 | | Connected, |
61 | | /// The stream dropped, and is being reconnected. The daemon may have |
62 | | /// stopped: an app asks it at once rather than at its next keep-alive. |
63 | | Disconnected, |
64 | | /// The user refused this app; the stream has ended. |
65 | | Blocked(String), |
66 | | /// The microphone opened or closed. |
67 | | Recording(bool), |
68 | | /// How loud the microphone is, 0 to 1, whether that sounds like speech, |
69 | | /// the energy in each frequency band (empty when the daemon sent none), |
70 | | /// and the raw energy the level is read from. |
71 | | MicrophoneLevel { |
72 | | level: f32, |
73 | | is_speech: bool, |
74 | | bands: Vec<f32>, |
75 | | total_energy: f32, |
76 | | }, |
77 | | /// The daemon started or finished turning a take into words. |
78 | | Transcribing(bool), |
79 | | /// How much of the utterance being spoken has played, in milliseconds. |
80 | | SpeechProgress { spoken_ms: u64 }, |
81 | | /// The daemon started or stopped speaking, and the utterance, when it |
82 | | /// names one. It speaks for whoever asked, not only this app. |
83 | | Speaking { |
84 | | is_speaking: bool, |
85 | | utterance_id: Option<String>, |
86 | | }, |
87 | | /// How loud what the daemon says is, 0 to 1, whether sound is reaching |
88 | | /// the speaker, the energy in each frequency band (empty when the daemon |
89 | | /// sent none), and the raw energy the level is read from. |
90 | | PlaybackLevel { |
91 | | level: f32, |
92 | | is_speech: bool, |
93 | | bands: Vec<f32>, |
94 | | total_energy: f32, |
95 | | }, |
96 | | /// A feature's model, or a download, moved on; or the daemon's own news, |
97 | | /// such as a shared setting changed. In the shape the daemon's older |
98 | | /// event list had. |
99 | | Status(NotificationEvent), |
100 | | /// A backend install moved on, finished or failed. |
101 | | Install(RegistryEvent), |
102 | | /// A dictation was transcribed and could not be typed. |
103 | | TypingFailed(TypingFailed), |
104 | | } |
105 | | |
106 | | /// A dictation the daemon could not type: why, whether its words are on the |
107 | | /// clipboard, and the words. |
108 | | #[derive(Debug, Clone, PartialEq, Eq)] |
109 | | pub struct TypingFailed { |
110 | | pub reason: TypingFailure, |
111 | | pub copied: bool, |
112 | | pub text: String, |
113 | | } |
114 | | |
115 | | /// Why a dictation was not typed. |
116 | | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
117 | | pub enum TypingFailure { |
118 | | /// The daemon may not type: Device Control (Accessibility) is off. |
119 | | NotAllowed, |
120 | | /// Another app held secure keyboard entry. |
121 | | SecureInput, |
122 | | /// Anything else. |
123 | | Failed, |
124 | | } |
125 | | |
126 | | impl TypingFailure { |
127 | | /// The reason the daemon names; one this app doesn't know is |
128 | | /// [`Self::Failed`]. |
129 | | #[must_use] |
130 | 3 | pub fn from_wire(reason: &str) -> Self { |
131 | 3 | match reason { |
132 | 1 | "not_allowed" => Self::NotAllowed, |
133 | 1 | "secure_input" => Self::SecureInput, |
134 | 1 | _ => Self::Failed, |
135 | | } |
136 | 3 | } |
137 | | } |
138 | | |
139 | | /// The daemon's `/events` stream, as [`Event`]s, until the user refuses this |
140 | | /// app. |
141 | | /// |
142 | | /// A daemon older than the app refuses the whole stream for a topic it |
143 | | /// doesn't know, so the stream is asked for again without the newest topic, |
144 | | /// one at a time, until the daemon takes it. When that stream drops later |
145 | | /// (the daemon may have been updated), every topic is asked for again. |
146 | 0 | pub fn subscribe() -> impl Stream<Item = Event> + Send + 'static { |
147 | 0 | subscribe_with(|topics| { |
148 | 0 | let config = WidgetSubscriptionConfig::new( |
149 | 0 | crate::daemon::client::app_id(), |
150 | 0 | crate::daemon::client::app_name(), |
151 | 0 | SETTINGS_SCOPES, |
152 | 0 | topics, |
153 | 0 | ); |
154 | 0 | run_widget_subscription(get_http_socket_path(), config) |
155 | 0 | }) |
156 | 0 | } |
157 | | |
158 | | /// A subscription's updates, boxed so a new one can take its place. |
159 | | type Updates = std::pin::Pin<Box<dyn Stream<Item = WidgetSubscriptionUpdate> + Send>>; |
160 | | |
161 | | /// [`subscribe`], with `open` starting the subscription to the topics given. |
162 | 2 | fn subscribe_with<S>( |
163 | 2 | open: impl Fn(&'static [&'static str]) -> S + Send + 'static, |
164 | 2 | ) -> impl Stream<Item = Event> + Send + 'static |
165 | 2 | where |
166 | 2 | S: Stream<Item = WidgetSubscriptionUpdate> + Send + 'static, |
167 | | { |
168 | 2 | let first: Updates = Box::pin(open(TOPICS)); |
169 | 2 | futures_util::stream::unfold( |
170 | 2 | (first, TOPICS.len(), open, Said::default()), |
171 | 7 | |(mut updates, mut kept, open, mut said)| async move { |
172 | | loop { |
173 | 10 | let update = updates.next().await?0 ; |
174 | 10 | match &update { |
175 | 3 | WidgetSubscriptionUpdate::Connected if kept < TOPICS.len() => log::info!( |
176 | | "/events connected, without the {} topics the daemon doesn't know", |
177 | 0 | TOPICS.len() - kept |
178 | | ), |
179 | 0 | WidgetSubscriptionUpdate::Connected => log::info!("/events connected"), |
180 | 3 | WidgetSubscriptionUpdate::Event(event) => said.say(event), |
181 | 4 | _ => {} |
182 | | } |
183 | 10 | if let WidgetSubscriptionUpdate::Disconnected { reason } = &update { |
184 | 4 | if let Some(fewer) = fewer_topics(reason, kept) { |
185 | 3 | warn!( |
186 | | "The daemon is older than the app: it doesn't know the event topic `{}`; \ |
187 | | subscribing without it", |
188 | 0 | TOPICS[fewer] |
189 | | ); |
190 | 3 | kept = fewer; |
191 | 3 | updates = Box::pin(open(&TOPICS[..kept])); |
192 | 3 | continue; |
193 | 1 | } |
194 | 1 | if kept < TOPICS.len() { |
195 | 1 | kept = TOPICS.len(); |
196 | 1 | updates = Box::pin(open(TOPICS)); |
197 | 0 | } |
198 | 6 | } |
199 | 7 | if let Some(event) = from_update(update) { |
200 | 7 | return Some((event, (updates, kept, open, said))); |
201 | 0 | } |
202 | | } |
203 | 14 | }, |
204 | | ) |
205 | 2 | } |
206 | | |
207 | | /// How many of [`TOPICS`] to ask for next, when the stream asking for the |
208 | | /// first `kept` dropped for `reason`: one fewer when the daemon refused a |
209 | | /// topic it doesn't know, or `None` to ask for the same again. Never none: |
210 | | /// the daemon refuses an empty list too. |
211 | 9 | fn fewer_topics(reason: &str, kept: usize) -> Option<usize> { |
212 | 9 | (reason.starts_with("invalid_topic") && kept > 16 ).then(|| kept5 - 15 ) |
213 | 9 | } |
214 | | |
215 | | /// What the stream's `update` tells an app, or `None` for one it needn't hear. |
216 | 10 | fn from_update(update: WidgetSubscriptionUpdate) -> Option<Event> { |
217 | 10 | match update { |
218 | 4 | WidgetSubscriptionUpdate::Connected => Some(Event::Connected), |
219 | 3 | WidgetSubscriptionUpdate::Event(event) => parse(&event), |
220 | | WidgetSubscriptionUpdate::Disconnected { reason } => { |
221 | 2 | log::info!("/events disconnected ({reason0 }); reconnecting"); |
222 | 2 | Some(Event::Disconnected) |
223 | | } |
224 | | WidgetSubscriptionUpdate::NeedsReauth { reason } => { |
225 | 1 | warn!("/events needs a new token ({reason0 }); asking again on the next attempt"); |
226 | 1 | None |
227 | | } |
228 | | WidgetSubscriptionUpdate::Blocked { reason } => { |
229 | 0 | warn!("/events refused by the user ({reason}); the stream has ended"); |
230 | 0 | Some(Event::Blocked(reason)) |
231 | | } |
232 | | } |
233 | 10 | } |
234 | | |
235 | | /// What the events say in the log: each one's topic and a few of its fields, |
236 | | /// at debug. The meters, and a download's or an install's ticks within one |
237 | | /// phase, come many times a second, and are said at trace. |
238 | | #[derive(Default)] |
239 | | struct Said { |
240 | | /// Each download's or install's last phase, by what it is for. |
241 | | phases: std::collections::HashMap<String, String>, |
242 | | } |
243 | | |
244 | | /// The fields an event is said with. Never `text`, the dictated words: only |
245 | | /// their length. |
246 | | const SAID_FIELDS: &[&str] = &[ |
247 | | "type", |
248 | | "feature", |
249 | | "stage", |
250 | | "status", |
251 | | "setting", |
252 | | "model", |
253 | | "model_name", |
254 | | "source", |
255 | | "phase", |
256 | | "version", |
257 | | "error", |
258 | | "reason", |
259 | | "is_recording", |
260 | | "is_speaking", |
261 | | "utterance_id", |
262 | | "copied", |
263 | | "percentage", |
264 | | ]; |
265 | | |
266 | | impl Said { |
267 | 3 | fn say(&mut self, event: &WidgetEvent) { |
268 | 3 | let level = self.level(event); |
269 | 3 | if log::log_enabled!(level) { |
270 | 0 | log::log!(level, "event {}: {}", event.name, summary(&event.payload)); |
271 | 3 | } |
272 | 3 | } |
273 | | |
274 | 8 | fn level(&mut self, event: &WidgetEvent) -> log::Level { |
275 | 8 | let p = &event.payload; |
276 | 9 | let text = |key: &str| p.get(key).map_or_default(ToString::to_string); |
277 | 8 | let phase = match event.name.as_str() { |
278 | 1 | "frequency_bands" | "playback_frequency_bands" => return log::Level::Trace, |
279 | 3 | "download_progress" => Some(( |
280 | 3 | format!("{}/{}", text("feature"), text("stage")), |
281 | 3 | text("status"), |
282 | 3 | )), |
283 | 0 | "registry_install" => Some((text("install_id"), text("phase"))), |
284 | 4 | _ => None, |
285 | | }; |
286 | 7 | match phase { |
287 | 3 | Some((what, phase)) if self.phases.get(&what) == Some(&phase) => log::Level::Trace1 , |
288 | | Some((what, phase)) => { |
289 | 2 | self.phases.insert(what, phase); |
290 | 2 | log::Level::Debug |
291 | | } |
292 | 4 | None => log::Level::Debug, |
293 | | } |
294 | 8 | } |
295 | | } |
296 | | |
297 | | /// An event's payload in a few words: its [`SAID_FIELDS`], and the length of |
298 | | /// its words, if it carries any. |
299 | 3 | fn summary(payload: &Value) -> String { |
300 | 3 | let mut parts: Vec<String> = SAID_FIELDS |
301 | 3 | .iter() |
302 | 51 | .filter_map(|&key| { |
303 | 51 | let value = payload.get(key)?47 ; |
304 | 4 | let value = match value { |
305 | 2 | Value::String(s) => s.clone(), |
306 | 1 | Value::Number(n) if n.is_f64() => format!("{:.1}", n.as_f64().unwrap_or_default()), |
307 | 0 | Value::Null | Value::Array(_) | Value::Object(_) => return None, |
308 | 1 | other => other.to_string(), |
309 | | }; |
310 | 4 | Some(format!("{key}={value}")) |
311 | 51 | }) |
312 | | .collect(); |
313 | 3 | if let Some(text) = payload.get("text").and_then(Value::as_str) { |
314 | 1 | parts.push(format!("text={} chars", text.chars().count())); |
315 | 2 | } |
316 | 3 | if parts.is_empty() { |
317 | 1 | "no details".to_string() |
318 | | } else { |
319 | 2 | parts.join(", ") |
320 | | } |
321 | 3 | } |
322 | | |
323 | | /// The event `event` is, or `None` for one an app doesn't show. |
324 | | #[must_use] |
325 | 22 | pub fn parse(event: &WidgetEvent) -> Option<Event> { |
326 | 22 | let p = &event.payload; |
327 | 22 | match event.name.as_str() { |
328 | 3 | "recording_state" => Some(Event::Recording(flag(p, "is_recording"))), |
329 | | "frequency_bands" => { |
330 | 4 | let (level, is_speech, total_energy) = level(p); |
331 | 4 | Some(Event::MicrophoneLevel { |
332 | 4 | level, |
333 | 4 | is_speech, |
334 | 4 | bands: bands(p), |
335 | 4 | total_energy, |
336 | 4 | }) |
337 | | } |
338 | 1 | "speaking_state" => Some(Event::Speaking { |
339 | 1 | is_speaking: flag(p, "is_speaking"), |
340 | 1 | utterance_id: p |
341 | 1 | .get("utterance_id") |
342 | 1 | .and_then(Value::as_str) |
343 | 1 | .map(str::to_owned), |
344 | 1 | }), |
345 | | "playback_frequency_bands" => { |
346 | 2 | let (level, is_speech, total_energy) = level(p); |
347 | 2 | Some(Event::PlaybackLevel { |
348 | 2 | level, |
349 | 2 | is_speech, |
350 | 2 | bands: bands(p), |
351 | 2 | total_energy, |
352 | 2 | }) |
353 | | } |
354 | 1 | "transcribing_started" => Some(Event::Transcribing(true)), |
355 | 1 | "transcribing_stopped" => Some(Event::Transcribing(false)), |
356 | 2 | "speech_progress" => Some(Event::SpeechProgress { |
357 | 2 | spoken_ms: p.get("spoken_ms").and_then(Value::as_u64).unwrap_or(0), |
358 | 2 | }), |
359 | | // Both features publish these, each naming itself in `feature`, and |
360 | | // the daemon's own news names none. The apps show both features, so |
361 | | // they take all three; a feature they don't know isn't theirs. |
362 | | "daemon_status_changed" | "download_progress" |
363 | 3 | if p.get("feature") |
364 | 3 | .and_then(Value::as_str) |
365 | 6 | .is_none_or(|feature| matches!(feature, "stt" | "tts")) => |
366 | | { |
367 | 5 | notification(event).map(Event::Status) |
368 | | } |
369 | 1 | "typing_failed" => Some(Event::TypingFailed(TypingFailed { |
370 | 1 | reason: TypingFailure::from_wire(p.get("reason").and_then(Value::as_str).unwrap_or("")), |
371 | 1 | copied: flag(p, "copied"), |
372 | 1 | text: p |
373 | 1 | .get("text") |
374 | 1 | .and_then(Value::as_str) |
375 | 1 | .unwrap_or_default() |
376 | 1 | .to_owned(), |
377 | 1 | })), |
378 | 0 | "registry_install" => match serde_json::from_value::<RegistryEvent>(p.clone()) { |
379 | | Ok(RegistryEvent::RefreshCompleted { .. } | RegistryEvent::RefreshFailed { .. }) => { |
380 | 0 | None |
381 | | } |
382 | 0 | Ok(install) => Some(Event::Install(install)), |
383 | | Err(_) => { |
384 | 0 | warn!("registry_install event isn't a RegistryEvent; dropped (payload: {p})"); |
385 | 0 | None |
386 | | } |
387 | | }, |
388 | 2 | _ => None, |
389 | | } |
390 | 22 | } |
391 | | |
392 | 5 | fn flag(payload: &Value, key: &str) -> bool { |
393 | 5 | payload.get(key).and_then(Value::as_bool).unwrap_or(false) |
394 | 5 | } |
395 | | |
396 | | /// A meter's level from the energy an event carries, whether that much is |
397 | | /// speech, and the energy itself. |
398 | 6 | fn level(payload: &Value) -> (f32, bool, f32) { |
399 | | // reason: audio energy is a small positive float, well within f32; a |
400 | | // meter loses nothing to the cast. |
401 | | #[allow(clippy::cast_possible_truncation)] |
402 | 6 | let energy = payload |
403 | 6 | .get("total_energy") |
404 | 6 | .and_then(Value::as_f64) |
405 | 6 | .unwrap_or(0.0) as f32; |
406 | 6 | (level_percent(energy), energy > 0.0001, energy) |
407 | 6 | } |
408 | | |
409 | | /// The bands an event carries: little-endian f32s in `bands_b64`. Empty when |
410 | | /// the field is missing, isn't base64, or isn't a whole number of f32s, so a |
411 | | /// broken payload draws nothing rather than something made up. |
412 | 6 | fn bands(payload: &Value) -> Vec<f32> { |
413 | | use base64::Engine as _; |
414 | 6 | let Some(encoded) = payload.get("bands_b64").and_then(Value::as_str) else { |
415 | 2 | return Vec::new(); |
416 | | }; |
417 | 4 | let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(encoded) else { |
418 | 1 | return Vec::new(); |
419 | | }; |
420 | 3 | let (samples, trailing) = bytes.as_chunks::<4>(); |
421 | 3 | if !trailing.is_empty() { |
422 | 1 | return Vec::new(); |
423 | 2 | } |
424 | 2 | samples.iter().copied().map(f32::from_le_bytes).collect() |
425 | 6 | } |
426 | | |
427 | | /// An event in the shape of the daemon's older event list, which the apps' |
428 | | /// status handling reads. |
429 | | /// |
430 | | /// `None` when the event has no string `timestamp`: every |
431 | | /// `daemon_status_changed` and `download_progress` the daemon publishes has |
432 | | /// one, so one without it is broken and dropped, rather than given a clock |
433 | | /// value made up here. |
434 | | #[must_use] |
435 | 11 | pub fn notification(event: &WidgetEvent) -> Option<NotificationEvent> { |
436 | 11 | let Some(timestamp) = event.payload.get("timestamp").and_then(Value::as_str) else { |
437 | 2 | warn!( |
438 | | "event '{}' has no string `timestamp`; dropped (payload: {})", |
439 | 0 | event.name, event.payload |
440 | | ); |
441 | 2 | return None; |
442 | | }; |
443 | 9 | Some(NotificationEvent { |
444 | 9 | event_type_field: event.name.clone(), |
445 | 9 | event_type: event.name.clone(), |
446 | 9 | client_id: "daemon".to_string(), |
447 | 9 | timestamp: timestamp.to_owned(), |
448 | 9 | data: event.payload.clone(), |
449 | 9 | }) |
450 | 11 | } |
451 | | |
452 | | /// The setting a status event says changed, from either feature: another |
453 | | /// client changed it, or this one did, and a page that shows it reads it |
454 | | /// again. |
455 | | #[must_use] |
456 | 14 | pub fn setting_changed(event: &Event) -> Option<&str> { |
457 | 14 | let Event::Status(status) = event else { |
458 | 1 | return None; |
459 | | }; |
460 | 13 | if status.data.get("status").and_then(Value::as_str) != Some("settings_changed") { |
461 | 3 | return None; |
462 | 10 | } |
463 | 10 | status.data.get("setting").and_then(Value::as_str) |
464 | 14 | } |
465 | | |
466 | | /// The stage a `download_progress` event is about, and the report: a download |
467 | | /// tick, a load step, or the end of either. The daemon says which stage it is |
468 | | /// provisioning for, so the report lands on that stage's card. |
469 | | #[must_use] |
470 | 0 | pub fn download_progress( |
471 | 0 | event: &Event, |
472 | 0 | ) -> Option<( |
473 | 0 | crate::state::Stage, |
474 | 0 | super_voice_shared::models::protocol::DownloadProgress, |
475 | 0 | )> { |
476 | 0 | let Event::Status(status) = event else { |
477 | 0 | return None; |
478 | | }; |
479 | 0 | if status.event_type != "download_progress" { |
480 | 0 | return None; |
481 | 0 | } |
482 | | let progress = |
483 | 0 | serde_json::from_value::<super_voice_shared::models::protocol::DownloadProgress>( |
484 | 0 | status.data.clone(), |
485 | 0 | ) |
486 | 0 | .ok()?; |
487 | 0 | let feature = status.data.get("feature").and_then(Value::as_str); |
488 | 0 | let stage = crate::state::Stage::from_wire(feature, progress.stage)?; |
489 | 0 | Some((stage, progress)) |
490 | 0 | } |
491 | | |
492 | | /// Raw frequency-band energy (typically 0.00001 to 0.1) as a meter's 0 to 1, |
493 | | /// on a -60 dB to 0 dB scale, where 0.1 is full. Quiet, normal and loud speech |
494 | | /// (0.003, 0.005, 0.008) come to about 49, 57 and 63%. |
495 | | #[must_use] |
496 | 16 | pub fn level_percent(energy: f32) -> f32 { |
497 | 16 | let db = if energy <= 0.0 { |
498 | 4 | -60.0 |
499 | | } else { |
500 | 12 | (20.0 * (energy * 10.0).log10()).clamp(-60.0, 0.0) |
501 | | }; |
502 | 16 | ((db + 60.0) / 60.0).clamp(0.0, 1.0) |
503 | 16 | } |
504 | | |
505 | | #[cfg(test)] |
506 | | mod tests; |