super-voice-daemon/src/output/typer.rs
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-3.0-only |
2 | | |
3 | | //! The preview typer state machine: the running transcript of the current |
4 | | //! recording plus the keyboard-driving update logic. The pure text algorithms |
5 | | //! it builds on — normalization, the screen diff, window stitching — live in |
6 | | //! [`crate::output::preview`]. |
7 | | |
8 | | use crate::output::keyboard::Simulator; |
9 | | use crate::output::preview::{ |
10 | | capitalize_first, find_common_prefix, merge_window_preview, normalize_text, preprocess_text, |
11 | | sanitize_for_typing, |
12 | | }; |
13 | | use log::{debug, info, warn}; |
14 | | use super_voice_shared::models::protocol::PreviewSource; |
15 | | |
16 | | /// The running transcript of the current recording. |
17 | | #[derive(Default)] |
18 | | pub struct State { |
19 | | /// The last normalized preview, so a repeat is not retyped. |
20 | | pub prev_text: String, |
21 | | /// Everything recognized so far this recording: a stream's own running |
22 | | /// transcript, or the daemon's sliding windows stitched together. |
23 | | pub full_session_text: String, |
24 | | } |
25 | | |
26 | | impl State { |
27 | | /// Fold one preview into the running transcript. |
28 | | /// |
29 | | /// A stream frame is the transcript so far and simply replaces it. A window |
30 | | /// frame is the last few seconds only, so it is stitched onto the |
31 | | /// transcript by the audio the two windows share. |
32 | | /// |
33 | | /// The old two-phase scheme — lock a "stabilized" prefix from consecutive |
34 | | /// previews, then graft each preview onto it by its last three characters — |
35 | | /// was built for previews that all start at the same audio. Sliding windows |
36 | | /// do not, so the prefix froze after the first seconds, and the three-char |
37 | | /// graft found the *rightmost* recurrence of the prefix's tail and dropped |
38 | | /// whatever lay between ("the cat sat on the mat and the dog" became |
39 | | /// "the cat sat on the dog"). |
40 | 25 | fn absorb(&mut self, preview: &str, source: PreviewSource) { |
41 | 25 | self.full_session_text = match source { |
42 | 4 | PreviewSource::Stream => preview.to_string(), |
43 | 21 | PreviewSource::Window => merge_window_preview(&self.full_session_text, preview), |
44 | | }; |
45 | 25 | } |
46 | | } |
47 | | |
48 | | /// How long [`Typer::type_notice`] waits before typing, so the user's shortcut |
49 | | /// keys can be fully released first. |
50 | | /// |
51 | | /// A failure notice can be emitted within milliseconds of a keypress, at which |
52 | | /// point the shortcut's modifier keys (Ctrl/Alt/Super/Shift) are usually still |
53 | | /// physically held down. Simulated keystrokes sent during that window arrive |
54 | | /// *modified*, so the focused application interprets the notice as shortcuts |
55 | | /// rather than text. |
56 | | /// |
57 | | /// Two distinct cases hit this window, which is why the wait applies to every |
58 | | /// notice rather than just the first: |
59 | | /// |
60 | | /// - The no-model preflight rejects the request before capture even starts, so |
61 | | /// the notice follows the *start* keypress almost immediately. |
62 | | /// - In manual stop mode the user presses the hotkey to end the recording, and |
63 | | /// a failure that surfaces quickly after that — a model unloaded mid-cycle, |
64 | | /// say — puts the notice right behind the *stop* keypress. |
65 | | /// |
66 | | /// This does not apply to transcription output: that is typed after speech has |
67 | | /// been captured and transcribed, long past any plausible key-release window. |
68 | | const NOTICE_KEY_RELEASE_DELAY: std::time::Duration = std::time::Duration::from_secs(1); |
69 | | |
70 | | /// Why a take's final transcript was not typed. Its words go to the |
71 | | /// clipboard instead. |
72 | | #[derive(Debug, Clone, PartialEq, Eq)] |
73 | | pub enum Untyped { |
74 | | /// No keyboard could be built for the take: why. On macOS this is almost |
75 | | /// always Device Control (Accessibility) switched off. |
76 | | NoKeyboard(String), |
77 | | /// Another app holds secure keyboard entry, so every key would be |
78 | | /// dropped without an error (macOS). |
79 | | SecureInput, |
80 | | /// The keyboard refused the text: why. |
81 | | Failed(String), |
82 | | } |
83 | | |
84 | | impl std::fmt::Display for Untyped { |
85 | 0 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
86 | 0 | match self { |
87 | 0 | Self::NoKeyboard(why) => write!(f, "no keyboard: {why}"), |
88 | 0 | Self::SecureInput => f.write_str("another app holds secure keyboard entry"), |
89 | 0 | Self::Failed(why) => write!(f, "typing failed: {why}"), |
90 | | } |
91 | 0 | } |
92 | | } |
93 | | |
94 | | /// A final transcript that was not typed: why, and the words as they would |
95 | | /// have been typed. |
96 | | #[derive(Debug, Clone, PartialEq, Eq)] |
97 | | pub struct NotTyped { |
98 | | pub why: Untyped, |
99 | | pub text: String, |
100 | | } |
101 | | |
102 | | /// Types previews and the final transcript into the focused window. |
103 | | pub struct Typer { |
104 | | // `None` for a recording that types nothing. Every keystroke path is gated |
105 | | // on write mode, so such a recording never reaches for the keyboard. |
106 | | keyboard_simulator: Option<Simulator>, |
107 | | /// Why a write-mode take has no keyboard: it could not be built. The |
108 | | /// take records anyway, and its words go to the clipboard. |
109 | | unable: Option<String>, |
110 | | state: State, |
111 | | } |
112 | | |
113 | | impl Typer { |
114 | | #[must_use] |
115 | 34 | pub fn new(keyboard_simulator: Simulator) -> Self { |
116 | 34 | Self { |
117 | 34 | keyboard_simulator: Some(keyboard_simulator), |
118 | 34 | unable: None, |
119 | 34 | state: State::default(), |
120 | 34 | } |
121 | 34 | } |
122 | | |
123 | | /// A typer for a write-mode take whose keyboard could not be built, |
124 | | /// `why`. Nothing is typed; the final transcript comes back from |
125 | | /// [`Self::process_final_text`] as [`Untyped::NoKeyboard`]. |
126 | | #[must_use] |
127 | 2 | pub fn unable(why: String) -> Self { |
128 | 2 | Self { |
129 | 2 | keyboard_simulator: None, |
130 | 2 | unable: Some(why), |
131 | 2 | state: State::default(), |
132 | 2 | } |
133 | 2 | } |
134 | | |
135 | | /// A typer for a recording that types nothing. Building a keyboard is not |
136 | | /// free: the portal backend asks the user for permission and waits for the |
137 | | /// answer. |
138 | | #[must_use] |
139 | 8 | pub fn without_keyboard() -> Self { |
140 | 8 | Self { |
141 | 8 | keyboard_simulator: None, |
142 | 8 | unable: None, |
143 | 8 | state: State::default(), |
144 | 8 | } |
145 | 8 | } |
146 | | |
147 | | #[must_use] |
148 | 0 | pub fn write_method_name(&self) -> &'static str { |
149 | 0 | self.keyboard_simulator |
150 | 0 | .as_ref() |
151 | 0 | .map_or("none", Simulator::name) |
152 | 0 | } |
153 | | |
154 | | /// Extract the simulator so it can be cached for reuse. |
155 | | #[must_use] |
156 | 5 | pub fn take_simulator(self) -> Option<Simulator> { |
157 | 5 | self.keyboard_simulator |
158 | 5 | } |
159 | | |
160 | 35 | async fn type_text(&mut self, text: &str) -> anyhow::Result<()> { |
161 | 35 | match self.keyboard_simulator.as_mut() { |
162 | 35 | Some(keyboard) => keyboard.type_text(text).await, |
163 | 0 | None => Err(anyhow::anyhow!("this recording has no keyboard")), |
164 | | } |
165 | 35 | } |
166 | | |
167 | 7 | async fn backspace_n(&mut self, n: usize) -> anyhow::Result<()> { |
168 | 7 | match self.keyboard_simulator.as_mut() { |
169 | 7 | Some(keyboard) => keyboard.backspace_n(n).await, |
170 | 0 | None => Err(anyhow::anyhow!("this recording has no keyboard")), |
171 | | } |
172 | 7 | } |
173 | | |
174 | | /// Drive the screen from `old_text` to `new_text`: backspace to the first |
175 | | /// differing character and type the rest. |
176 | | /// |
177 | | /// The one path every preview update takes. An empty screen (common prefix |
178 | | /// 0, nothing to delete) and a pure extension (the prefix is all of |
179 | | /// `old_text`, nothing to delete) are just what the diff computes, not |
180 | | /// separate branches that can disagree about what they typed. |
181 | 25 | async fn retype_from_first_difference(&mut self, old_text: &str, new_text: &str) { |
182 | 25 | if old_text == new_text { |
183 | 0 | return; |
184 | 25 | } |
185 | | |
186 | 25 | let common_prefix = find_common_prefix(old_text, new_text); |
187 | 25 | let chars_to_delete = old_text.chars().count() - common_prefix; |
188 | 25 | let text_to_type: String = new_text.chars().skip(common_prefix).collect(); |
189 | | |
190 | 25 | debug!( |
191 | 0 | "Retype: prefix={common_prefix}, delete={chars_to_delete}, type='{}'", |
192 | 0 | text_to_type.chars().take(20).collect::<String>() |
193 | | ); |
194 | | |
195 | | // A refused keystroke is the only sign that the screen and the mirror |
196 | | // may now disagree; it has to be visible in the log. |
197 | 25 | if chars_to_delete > 0 |
198 | 4 | && let Err(e) = self.backspace_n(chars_to_delete).await |
199 | | { |
200 | 0 | warn!("Failed to backspace preview text: {e}"); |
201 | 25 | } |
202 | 25 | if !text_to_type.is_empty() |
203 | 25 | && let Err(e) = self.type_text(&text_to_type).await |
204 | | { |
205 | 0 | warn!("Failed to type preview text: {e}"); |
206 | 25 | } |
207 | 25 | } |
208 | | |
209 | | /// Type one preview: fold it into the running transcript and put the |
210 | | /// result on screen. The screen shows the transcript so far, never the |
211 | | /// preview itself — a window is only a few seconds of it. |
212 | 26 | pub async fn update_preview( |
213 | 26 | &mut self, |
214 | 26 | new_text: &str, |
215 | 26 | source: PreviewSource, |
216 | 26 | actually_typed: &mut String, |
217 | 26 | ) { |
218 | 26 | let normalized = normalize_text(new_text); |
219 | 26 | debug!( |
220 | 0 | "Preview update ({source}): new='{normalized}', prev='{}', typed='{actually_typed}'", |
221 | 0 | self.state.prev_text |
222 | | ); |
223 | | |
224 | 26 | if normalized == self.state.prev_text { |
225 | 1 | debug!("Preview unchanged; nothing to type"0 ); |
226 | 1 | return; |
227 | 25 | } |
228 | 25 | if normalized.is_empty() { |
229 | 0 | debug!("Preview is empty; nothing to type"); |
230 | 0 | return; |
231 | 25 | } |
232 | | |
233 | 25 | self.state.absorb(&normalized, source); |
234 | 25 | let display_text = capitalize_first(&self.state.full_session_text); |
235 | | // The head of a running transcript stops changing after the first |
236 | | // seconds; its tail is where each window lands. |
237 | 25 | info!("Transcript so far ends '{}'", tail_of0 (&display_text, 40)); |
238 | | |
239 | 25 | self.apply_text_update(&display_text, actually_typed).await; |
240 | 25 | self.state.prev_text = normalized; |
241 | 26 | } |
242 | | |
243 | | /// Type the final transcript, then reset for the next recording. |
244 | | /// |
245 | | /// # Errors |
246 | | /// When the words could not be typed, and why, with the words as they |
247 | | /// would have been typed: the caller puts them on the clipboard. |
248 | 7 | pub async fn process_final_text(&mut self, transcription_result: &str) -> Result<(), NotTyped> { |
249 | | // No preview typing, type directly |
250 | 7 | let processed_text = preprocess_text(transcription_result, false); |
251 | | |
252 | | // An empty transcript has nothing to type. Without this guard the |
253 | | // `format!("{processed_text} ")` below deposits a bare space into the |
254 | | // user's focused window every time a recording produces no text. |
255 | 7 | if processed_text.trim().is_empty() { |
256 | 4 | info!("Final transcription is empty; typing nothing"0 ); |
257 | 4 | self.reset_after_recording(); |
258 | 4 | return Ok(()); |
259 | 3 | } |
260 | | |
261 | 3 | let outcome = self.type_final(&processed_text).await; |
262 | 3 | self.reset_after_recording(); |
263 | 3 | outcome.map_err(|why| {1 |
264 | 1 | warn!("Final transcription not typed: {why0 }"); |
265 | 1 | NotTyped { |
266 | 1 | why, |
267 | 1 | text: processed_text, |
268 | 1 | } |
269 | 1 | }) |
270 | 7 | } |
271 | | |
272 | | /// Type `text` and the space after it, or say why not. |
273 | 3 | async fn type_final(&mut self, text: &str) -> Result<(), Untyped> { |
274 | 3 | let Some(simulator) = self.keyboard_simulator.as_ref() else { |
275 | | return Err(Untyped::NoKeyboard( |
276 | 1 | self.unable |
277 | 1 | .clone() |
278 | 0 | .unwrap_or_else(|| "this recording has no keyboard".to_string()), |
279 | | )); |
280 | | }; |
281 | | // Checked before the first key: with it on, macOS drops every |
282 | | // synthetic key and says nothing. |
283 | 2 | if simulator.secure_input_on() { |
284 | 0 | return Err(Untyped::SecureInput); |
285 | 2 | } |
286 | 2 | let final_text = format!("{text} "); |
287 | 2 | self.type_text(&final_text) |
288 | 2 | .await |
289 | 0 | .map_err(|e| Untyped::Failed(format!("{e:#}")))?; |
290 | 2 | info!("Final transcript typed"0 ); |
291 | 2 | Ok(()) |
292 | 3 | } |
293 | | |
294 | | /// Clear the per-recording transcript state so the next recording starts |
295 | | /// clean. Window stitching reads `full_session_text` and the repeat check |
296 | | /// reads `prev_text`, so anything left here would be extended. |
297 | | /// |
298 | | /// Split out of [`Self::process_final_text`] because the no-speech path |
299 | | /// finishes a recording without typing anything and still has to reset. |
300 | 8 | pub fn reset_after_recording(&mut self) { |
301 | 8 | self.state.prev_text.clear(); |
302 | 8 | self.state.full_session_text.clear(); |
303 | 8 | } |
304 | | |
305 | | /// Type a fixed daemon-authored notice into the focused window. |
306 | | /// |
307 | | /// Deliberately **not** `process_final_text`. That method mutates |
308 | | /// transcript state (`prev_text`, `full_session_text`), which the next |
309 | | /// recording's window stitching would extend, and applies transcript |
310 | | /// semantics — capitalization, a trailing period, a trailing space — that |
311 | | /// a fixed marker must not inherit. A notice is typed verbatim and leaves |
312 | | /// session state alone. |
313 | | /// |
314 | | /// Routed through the same [`sanitize_for_typing`] choke point as every |
315 | | /// other write path (audit 2 Tier 3 #8). The callers pass constants, so |
316 | | /// this is a no-op today; it is here so the property holds by |
317 | | /// construction. |
318 | | /// |
319 | | /// Waits [`NOTICE_KEY_RELEASE_DELAY`] before typing — see that constant for |
320 | | /// why. |
321 | 8 | pub async fn type_notice(&mut self, notice: &str) { |
322 | | // Let the user's hotkey come back up first. The no-model preflight |
323 | | // rejects before capture starts, so this can run within milliseconds of |
324 | | // the press, while the shortcut's modifiers are still physically held. |
325 | | // Typing then delivers *modified* keystrokes to the focused window — |
326 | | // the notice would fire shortcuts in the user's application instead of |
327 | | // inserting text. |
328 | 8 | tokio::time::sleep(NOTICE_KEY_RELEASE_DELAY).await; |
329 | | |
330 | 8 | let sanitized = sanitize_for_typing(notice); |
331 | 8 | if let Err(e) = self.type_text(&sanitized).await { |
332 | 0 | warn!("Failed to type notice: {e}"); |
333 | | } else { |
334 | 8 | info!("Typed failure notice: {sanitized0 }"); |
335 | | } |
336 | 8 | } |
337 | | |
338 | | /// Put `new_text` on screen in place of what `actually_typed` says is |
339 | | /// there, then record `new_text` as what is there now. |
340 | | /// |
341 | | /// The mirror has to be exactly the screen: `clear_preview` backspaces its |
342 | | /// length and the next update diffs against it. It used to drift by one |
343 | | /// space per update — the first text and every extension were typed with a |
344 | | /// trailing space the mirror never held — so extensions doubled spaces, |
345 | | /// replacements backspaced too few characters and left fragments of the |
346 | | /// old text behind, and the clear at the end of a recording left the first |
347 | | /// characters of the preview in front of the final transcript. |
348 | 25 | async fn apply_text_update(&mut self, new_text: &str, actually_typed: &mut String) { |
349 | 25 | self.retype_from_first_difference(actually_typed, new_text) |
350 | 25 | .await; |
351 | | |
352 | 25 | actually_typed.clear(); |
353 | 25 | actually_typed.push_str(new_text); |
354 | 25 | } |
355 | | |
356 | | /// Erase the typed preview from the screen and reset the transcript state. |
357 | 3 | pub async fn clear_preview(&mut self, actually_typed: &mut String) { |
358 | 3 | let chars_to_delete = actually_typed.chars().count(); |
359 | 3 | if chars_to_delete == 0 { |
360 | 0 | debug!("No preview on screen to clear"); |
361 | | } else { |
362 | 3 | info!("Clearing the {chars_to_delete0 }-character preview"); |
363 | 3 | if let Err(e) = self.backspace_n(chars_to_delete).await { |
364 | 0 | warn!("Failed to backspace preview text: {e}"); |
365 | 3 | } |
366 | | } |
367 | | |
368 | 3 | actually_typed.clear(); |
369 | 3 | self.state.prev_text.clear(); |
370 | 3 | self.state.full_session_text.clear(); |
371 | 3 | } |
372 | | } |
373 | | |
374 | | /// The last `n` chars of `text`, marked when that is not all of it. |
375 | 0 | fn tail_of(text: &str, n: usize) -> String { |
376 | 0 | let total = text.chars().count(); |
377 | 0 | if total <= n { |
378 | 0 | return text.to_string(); |
379 | 0 | } |
380 | 0 | format!("…{}", text.chars().skip(total - n).collect::<String>()) |
381 | 0 | } |
382 | | |
383 | | #[cfg(test)] |
384 | | #[path = "typer_tests.rs"] |
385 | | mod tests; |