super-voice-cli/src/main.rs
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-3.0-only |
2 | | //! `voice`: Super Voice's command-line client. Talks to the daemon over the |
3 | | //! HTTP protocol on its Unix socket. |
4 | | //! |
5 | | //! Each feature's commands are under its own subcommand — `voice record` for |
6 | | //! speech to text, `voice speak` for text to speech — and what the daemon has |
7 | | //! once is at the top: `ping`, `status`, `updates`, `logout`. |
8 | | //! `assistant-hook` is for an AI assistant's hooks that can only run a |
9 | | //! command. |
10 | | //! |
11 | | //! Auth flow is delegated to `super_voice_shared::daemon::session`, the |
12 | | //! shared client-side session helper. Each client (CLI, app, |
13 | | //! applet) keeps its token in a file of its own, named by its `AppId`; the |
14 | | //! CLI's is `$XDG_STATE_HOME/super-voice/clients/super-voice-cli.json`. One |
15 | | //! token serves both features. |
16 | | //! |
17 | | //! `session::with_token` handles cache-hit, consent-popup-on-miss, and |
18 | | //! `invalid_session` retry transparently — handlers below just write |
19 | | //! the network call and propagate the daemon's error string. |
20 | | //! |
21 | | //! For tests / CI: set `SUPER_VOICE_AUTO_APPROVE=1` in the daemon's |
22 | | //! environment so the consent popup is bypassed and `/auth/request` |
23 | | //! auto-approves. |
24 | | |
25 | | use anyhow::{Context, Result, anyhow}; |
26 | | use clap::{Arg, ArgAction, ArgMatches, Command, value_parser}; |
27 | | use std::io::Read; |
28 | | use std::path::PathBuf; |
29 | | use super_voice_shared::daemon::http_client::{self, TranscribeOptions}; |
30 | | use super_voice_shared::daemon::session::{self, AppId}; |
31 | | use super_voice_shared::models::assistants::AssistantId; |
32 | | use super_voice_shared::models::contexts::ExtraContext; |
33 | | use super_voice_shared::validation::get_http_socket_path; |
34 | | |
35 | | mod assistant_hook; |
36 | | #[cfg(target_os = "macos")] |
37 | | mod hotkey; |
38 | | #[cfg(target_os = "macos")] |
39 | | mod service; |
40 | | |
41 | | const APP_ID: AppId = super_voice_shared::daemon::session::app_id("super-voice-cli"); |
42 | | const APP_NAME: &str = "Super Voice CLI"; |
43 | | /// Both features' commands run on one token, so it asks for both. |
44 | | const SCOPES: &[&str] = &["transcribe", "speak", "status"]; |
45 | | /// The commands that read or change a setting take `settings` too: |
46 | | /// `assistant-hook`, which reads its assistant's key, and `updates`. Only |
47 | | /// those, so a CLI that is not the one installed beside the daemon asks the |
48 | | /// user for `settings` only when it needs it. The token it gets covers the |
49 | | /// other commands as well. |
50 | | const SETTINGS_SCOPES: &[&str] = &["transcribe", "speak", "status", "settings"]; |
51 | | /// What the shortcut listener (`voice hotkey`) asks for, under its own |
52 | | /// identity: to record (`transcribe`) and read aloud (`speak`), `status` to |
53 | | /// know whether either is running, to read its keys (`settings`), and to |
54 | | /// hear when they change (`daemon_status`, which [`HOTKEY_TOPICS`] needs). It |
55 | | /// is an official client in the app bundle, so the daemon grants these |
56 | | /// without a dialog. |
57 | | #[cfg(any(target_os = "macos", test))] |
58 | | const HOTKEY_SCOPES: &[&str] = &["transcribe", "speak", "status", "settings", "daemon_status"]; |
59 | | /// The events the shortcut listener follows: `settings_changed` is one. |
60 | | #[cfg(any(target_os = "macos", test))] |
61 | | const HOTKEY_TOPICS: &[&str] = &["daemon_status_changed"]; |
62 | | |
63 | 20 | fn main() -> Result<()> { |
64 | | // The CLI previously had no logging at all; initialize it like the other |
65 | | // binaries (RUST_LOG wins, else Info) (Tier 2 #6). |
66 | 20 | super_voice_shared::logging::init(); |
67 | | |
68 | 20 | let matches = build_cli().get_matches(); |
69 | | |
70 | 20 | let socket_path = matches |
71 | 20 | .get_one::<PathBuf>("socket") |
72 | 20 | .cloned() |
73 | 20 | .unwrap_or_else(get_http_socket_path); |
74 | | |
75 | | // `hotkey` runs AppKit's event loop, which has to own the main thread, so |
76 | | // it is dispatched before any runtime exists and builds its own on worker |
77 | | // threads. Every other subcommand is one request and out. |
78 | | #[cfg(target_os = "macos")] |
79 | | if let Some(("hotkey", sub)) = matches.subcommand() { |
80 | | let binding = sub |
81 | | .get_one::<String>("key") |
82 | | .map_or(hotkey::DEFAULT_BINDING, String::as_str); |
83 | | if sub.get_flag("check") { |
84 | | return hotkey::check(binding); |
85 | | } |
86 | | return hotkey::run(socket_path, binding); |
87 | | } |
88 | | // Talks to launchd rather than the daemon, and needs no runtime. |
89 | | #[cfg(target_os = "macos")] |
90 | | if let Some(("service", sub)) = matches.subcommand() { |
91 | | return service::run(sub); |
92 | | } |
93 | | |
94 | 20 | tokio::runtime::Builder::new_multi_thread() |
95 | 20 | .enable_all() |
96 | 20 | .build() |
97 | 20 | .context("could not start the async runtime")?0 |
98 | 20 | .block_on(dispatch(&matches, socket_path)) |
99 | 20 | } |
100 | | |
101 | 19 | async fn dispatch(matches: &ArgMatches, socket_path: PathBuf) -> Result<()> { |
102 | 19 | match matches.subcommand() { |
103 | | Some(("ping", _)) => { |
104 | 1 | run_with_token(socket_path.clone(), |t| cmd_ping(socket_path.clone(), t)) |
105 | 1 | .await |
106 | 1 | .context("ping failed") |
107 | | } |
108 | | Some(("status", _)) => { |
109 | 1 | run_with_token(socket_path.clone(), |t| cmd_status(socket_path.clone(), t)) |
110 | 1 | .await |
111 | 1 | .context("status failed") |
112 | | } |
113 | 1 | Some(("record", sub)) if matches!(sub.subcommand(), Some(("stop", _))) => { |
114 | 1 | run_with_token(socket_path.clone(), |t| cmd_stop(socket_path.clone(), t)) |
115 | 1 | .await |
116 | 1 | .context("stop failed") |
117 | | } |
118 | | Some(("record", sub)) => { |
119 | 0 | let write = sub.get_flag("write"); |
120 | 0 | let wait = sub.get_flag("wait"); |
121 | 0 | let stop_mode = sub.get_one::<String>("stop-mode").cloned(); |
122 | 0 | let context = record_context(sub); |
123 | 0 | run_with_token(socket_path.clone(), |t| { |
124 | 0 | cmd_record( |
125 | 0 | socket_path.clone(), |
126 | 0 | t, |
127 | 0 | write, |
128 | 0 | wait, |
129 | 0 | stop_mode.clone(), |
130 | 0 | context.clone(), |
131 | 0 | ) |
132 | 0 | }) |
133 | 0 | .await |
134 | 0 | .context("record failed") |
135 | | } |
136 | 5 | Some(("speak", sub)) if matches!(sub.subcommand(), Some(("stop", _))) => { |
137 | 2 | run_with_token(socket_path.clone(), |t| { |
138 | 2 | cmd_speak_stop(socket_path.clone(), t) |
139 | 2 | }) |
140 | 2 | .await |
141 | 2 | .context("stop failed") |
142 | | } |
143 | | #[cfg(any(target_os = "linux", target_os = "macos"))] |
144 | 3 | Some(("speak", sub)) if sub.get_flag("read") => run_with_token1 (socket_path.clone()1 , |t| {1 |
145 | 1 | cmd_speak_read(socket_path.clone(), t) |
146 | 1 | }) |
147 | 1 | .await |
148 | 1 | .context("speak failed"), |
149 | | Some(("speak", sub)) => { |
150 | 2 | let text = read_text(sub)?0 ; |
151 | 2 | run_with_token(socket_path.clone(), |t| { |
152 | 2 | cmd_speak(socket_path.clone(), t, text.clone()) |
153 | 2 | }) |
154 | 2 | .await |
155 | 2 | .context("speak failed") |
156 | | } |
157 | | // `betas` is its one subcommand, and clap requires it. |
158 | | Some(("updates", sub)) => { |
159 | 10 | let value = sub |
160 | 10 | .subcommand_matches("betas") |
161 | 10 | .and_then(|betas| betas.get_one::<String>("value").cloned()); |
162 | 10 | run_with_token_as( |
163 | 10 | APP_ID, |
164 | 10 | APP_NAME, |
165 | 10 | SETTINGS_SCOPES, |
166 | 10 | socket_path.clone(), |
167 | 10 | |t| cmd_updates_betas(socket_path.clone(), t, value.clone()), |
168 | | ) |
169 | 10 | .await |
170 | 10 | .context("updates betas failed") |
171 | | } |
172 | 1 | Some(("logout", _)) => cmd_logout(), |
173 | | Some(("assistant-hook", sub)) => { |
174 | 0 | let assistant = assistant_of(sub)?; |
175 | 0 | let event = sub |
176 | 0 | .get_one::<String>("event") |
177 | 0 | .context("an event is required")?; |
178 | 0 | assistant_hook::run(socket_path, assistant, event).await; |
179 | 0 | Ok(()) |
180 | | } |
181 | | _ => { |
182 | 0 | println!("Run with --help for usage."); |
183 | 0 | Ok(()) |
184 | | } |
185 | | } |
186 | 19 | } |
187 | | |
188 | | /// The command-line interface. A function rather than inline in `main` so the |
189 | | /// tests can parse the arguments the hotkey `LaunchAgent` is installed with. |
190 | 39 | fn build_cli() -> Command { |
191 | 39 | platform_subcommands( |
192 | 39 | Command::new("voice") |
193 | 39 | .version(env!("CARGO_PKG_VERSION")) |
194 | 39 | .about("Super Voice: speech to text and text to speech") |
195 | 39 | .arg( |
196 | 39 | Arg::new("socket") |
197 | 39 | .long("socket") |
198 | 39 | .help("Path to the daemon HTTP Unix socket") |
199 | 39 | .value_parser(value_parser!(PathBuf)) |
200 | 39 | .global(true), |
201 | 39 | ) |
202 | 39 | .subcommand(Command::new("ping").about("Check that the daemon is reachable")) |
203 | 39 | .subcommand(Command::new("status").about("Print each feature's model, device and state")) |
204 | 39 | .subcommand( |
205 | 39 | Command::new("record") |
206 | 39 | .about("Start a recording, or stop the one in progress") |
207 | 39 | .args_conflicts_with_subcommands(true) |
208 | 39 | .subcommand(Command::new("stop").about("Stop the recording in progress")) |
209 | 39 | .arg( |
210 | 39 | Arg::new("write") |
211 | 39 | .short('w') |
212 | 39 | .long("write") |
213 | 39 | .help("Type the transcription into the focused window when done") |
214 | 39 | .action(ArgAction::SetTrue), |
215 | 39 | ) |
216 | 39 | .arg( |
217 | 39 | Arg::new("wait") |
218 | 39 | .long("wait") |
219 | 39 | .help("Hold the connection open and print the final transcription") |
220 | 39 | .action(ArgAction::SetTrue), |
221 | 39 | ) |
222 | 39 | .arg( |
223 | 39 | Arg::new("stop-mode") |
224 | 39 | .long("stop-mode") |
225 | 39 | .help("Override the configured stop mode") |
226 | 39 | // Drive the accepted values from the shared wire-enum |
227 | 39 | // table so they can't drift from the daemon (Tier 2 #8). |
228 | 39 | .value_parser(clap::builder::PossibleValuesParser::new( |
229 | 39 | super_voice_shared::models::recording_stop_mode::RecordingStopMode::WIRE_VARIANTS |
230 | 39 | .iter() |
231 | 39 | .copied(), |
232 | 39 | )), |
233 | 39 | ) |
234 | 39 | .arg( |
235 | 39 | Arg::new("prompt") |
236 | 39 | .long("prompt") |
237 | 39 | .value_name("TEXT") |
238 | 39 | .help( |
239 | 39 | "Context for this recording, added to your selected context: \ |
240 | 39 | what you are about to talk about", |
241 | 39 | ), |
242 | 39 | ) |
243 | 39 | .arg( |
244 | 39 | Arg::new("term") |
245 | 39 | .long("term") |
246 | 39 | .value_name("WORD") |
247 | 39 | .help( |
248 | 39 | "A word or name you may say, added to your selected context's \ |
249 | 39 | vocabulary for this recording. Repeat it for more", |
250 | 39 | ) |
251 | 39 | .action(ArgAction::Append), |
252 | 39 | ), |
253 | 39 | ) |
254 | 39 | .subcommand(read_arg( |
255 | 39 | Command::new("speak") |
256 | 39 | .about("Speak text with the active model") |
257 | 39 | .args_conflicts_with_subcommands(true) |
258 | 39 | .subcommand(Command::new("stop").about("Stop the speech now playing")) |
259 | 39 | .arg( |
260 | 39 | Arg::new("text") |
261 | 39 | .help("The text to speak; omit to read it from stdin. To speak the word \"stop\", put `--` before it") |
262 | 39 | .num_args(0..) |
263 | 39 | .trailing_var_arg(true), |
264 | 39 | ), // No --voice/--language/--speed/--instructions: how the |
265 | 39 | // machine speaks is the user's configuration, not a flag on the |
266 | 39 | // thing that makes it talk. Set a voice with the app |
267 | 39 | // or `POST /tts/pipeline/{stage}/model/{model}/voice`. |
268 | 39 | )) |
269 | 39 | .subcommand(updates_command()) |
270 | 39 | .subcommand( |
271 | 39 | Command::new("logout") |
272 | 39 | .about("Forget the cached session token (forces re-consent next call)"), |
273 | 39 | ) |
274 | 39 | .subcommand(assistant_hook::command()), |
275 | 39 | ) |
276 | 39 | } |
277 | | |
278 | | /// `voice updates`: how Super Voice updates itself. `betas` prints or saves |
279 | | /// whether updates include betas, the app's "Include betas". The installer |
280 | | /// runs it to keep a beta install on betas, so with no value it prints the |
281 | | /// setting alone. |
282 | 39 | fn updates_command() -> Command { |
283 | | use clap::builder::{PossibleValue, PossibleValuesParser}; |
284 | | use super_voice_shared::models::update_beta_optin::UpdateBetaOptIn; |
285 | 117 | let help = |value: UpdateBetaOptIn| match value { |
286 | 39 | UpdateBetaOptIn::Auto => "Include betas while a beta is installed", |
287 | 39 | UpdateBetaOptIn::Enabled => "Include betas", |
288 | 39 | UpdateBetaOptIn::Disabled => "Include stable releases only", |
289 | 117 | }; |
290 | 117 | let values = UpdateBetaOptIn::WIRE_VARIANTS.iter()39 .map(|name| { |
291 | 117 | let value = name |
292 | 117 | .parse::<UpdateBetaOptIn>() |
293 | 117 | .expect("a wire variant parses"); |
294 | 117 | PossibleValue::new(*name).help(help(value)) |
295 | 117 | }); |
296 | 39 | Command::new("updates") |
297 | 39 | .about("How Super Voice updates itself") |
298 | 39 | .subcommand_required(true) |
299 | 39 | .subcommand( |
300 | 39 | Command::new("betas") |
301 | 39 | .about("Print or set whether updates include betas") |
302 | 39 | .arg( |
303 | 39 | Arg::new("value") |
304 | 39 | .help("What to set it to. Omit it to print the setting") |
305 | 39 | .value_parser(PossibleValuesParser::new(values)), |
306 | 39 | ), |
307 | 39 | ) |
308 | 39 | } |
309 | | |
310 | | #[cfg(target_os = "macos")] |
311 | | fn platform_subcommands(cli: Command) -> Command { |
312 | | cli.subcommand(hotkey::command()) |
313 | | .subcommand(service::command()) |
314 | | } |
315 | | |
316 | | /// Nothing to add on Linux: the desktop environment binds the shortcuts there |
317 | | /// and runs `voice record --write` and `voice speak --read` itself, and |
318 | | /// systemd runs the daemon. |
319 | | #[cfg(not(target_os = "macos"))] |
320 | 39 | fn platform_subcommands(cli: Command) -> Command { |
321 | 39 | cli |
322 | 39 | } |
323 | | |
324 | | /// `voice speak --read`, which the desktop environment's shortcut runs: the |
325 | | /// text to speech counterpart of `voice record --write`. On Linux the daemon |
326 | | /// reads the selection and the clipboard from the Wayland session; on a Mac |
327 | | /// it asks Accessibility or copies, and the listener (`voice hotkey`) runs |
328 | | /// the same function on its Read aloud keys. |
329 | | #[cfg(any(target_os = "linux", target_os = "macos"))] |
330 | 39 | fn read_arg(speak: Command) -> Command { |
331 | 39 | speak.arg( |
332 | 39 | Arg::new("read") |
333 | 39 | .long("read") |
334 | 39 | .help("Speak the selected or copied text, as the read method in the app says. If speech is playing, stop it instead") |
335 | 39 | .action(ArgAction::SetTrue) |
336 | 39 | .conflicts_with("text"), |
337 | 39 | ) |
338 | 39 | } |
339 | | |
340 | | #[cfg(not(any(target_os = "linux", target_os = "macos")))] |
341 | | fn read_arg(speak: Command) -> Command { |
342 | | speak |
343 | | } |
344 | | |
345 | | /// Thin wrapper over `session::with_token` that adapts its |
346 | | /// `Result<T, String>` return into `anyhow::Result<T>` and supplies |
347 | | /// the CLI's app identity. All commands route through here. |
348 | 8 | async fn run_with_token<F, Fut, T>(socket_path: PathBuf, op: F) -> Result<T> |
349 | 8 | where |
350 | 8 | F: Fn(String) -> Fut, |
351 | 8 | Fut: std::future::Future<Output = super_voice_shared::daemon::http_client::HttpResult<T>>, |
352 | 8 | { |
353 | 8 | run_with_token_as(APP_ID, APP_NAME, SCOPES, socket_path, op).await |
354 | 8 | } |
355 | | |
356 | | /// [`run_with_token`] under another app identity, asking for `scopes`. See |
357 | | /// `hotkey::APP_ID`. |
358 | 18 | async fn run_with_token_as<F, Fut, T>( |
359 | 18 | app_id: AppId, |
360 | 18 | app_name: &str, |
361 | 18 | scopes: &[&str], |
362 | 18 | socket_path: PathBuf, |
363 | 18 | op: F, |
364 | 18 | ) -> Result<T> |
365 | 18 | where |
366 | 18 | F: Fn(String) -> Fut, |
367 | 18 | Fut: std::future::Future<Output = super_voice_shared::daemon::http_client::HttpResult<T>>, |
368 | 18 | { |
369 | 18 | session::with_token(socket_path, app_id, app_name, scopes, op) |
370 | 18 | .await |
371 | 3 | .map_err(|e| anyhow!(e)) |
372 | 18 | } |
373 | | |
374 | | // ----------------------------------------------------------------------------- |
375 | | // Per-subcommand handlers |
376 | | // ----------------------------------------------------------------------------- |
377 | | // |
378 | | // Handlers return `Result<(), String>` to match the shape `session::with_token` |
379 | | // expects. On `invalid_session` from the daemon the shared helper transparently |
380 | | // re-runs consent and retries the op, so handlers don't need to classify |
381 | | // auth-vs-non-auth errors themselves. |
382 | | |
383 | 1 | async fn cmd_ping( |
384 | 1 | socket_path: PathBuf, |
385 | 1 | token: String, |
386 | 1 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
387 | 1 | let msg = http_client::ping(socket_path, &token).await?0 ; |
388 | 1 | println!("{msg}"); |
389 | 1 | Ok(()) |
390 | 1 | } |
391 | | |
392 | 1 | async fn cmd_status( |
393 | 1 | socket_path: PathBuf, |
394 | 1 | token: String, |
395 | 1 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
396 | 1 | let status = http_client::status(socket_path, &token).await?0 ; |
397 | 1 | for (feature, part, at_work, not_at_work) in [ |
398 | 1 | ("Speech to text", &status.stt, "recording", "not recording"), |
399 | 1 | ("Text to speech", &status.tts, "speaking", "not speaking"), |
400 | 1 | ] { |
401 | 2 | println!("{feature}"); |
402 | 2 | println!(" Model: {}", model_line(part)); |
403 | 2 | println!(" Device: {}", part.device); |
404 | | // Not "idle": that is a model asleep, which the Model line says. |
405 | 2 | println!( |
406 | | " State: {}", |
407 | 2 | if part.busy { at_work0 } else { not_at_work } |
408 | | ); |
409 | | } |
410 | 1 | Ok(()) |
411 | 1 | } |
412 | | |
413 | | /// What `voice status` says about a feature's model: the one selected, and |
414 | | /// whether it is in memory. |
415 | | /// |
416 | | /// With idle unload on, a selected model is out of memory most of the time, |
417 | | /// and this said "(none loaded)" for it, as if nothing were selected. |
418 | 8 | fn model_line(part: &super_voice_shared::models::status::FeatureStatus) -> String { |
419 | | use super_voice_shared::models::protocol::ModelState; |
420 | 8 | match (part.selected_model.as_deref(), part.model_state) { |
421 | 1 | (Some(model), Some(ModelState::Loaded)) => model.to_string(), |
422 | 1 | (Some(model), Some(ModelState::Idle)) => format!("{model} (asleep; loads when next used)"), |
423 | 1 | (Some(model), Some(ModelState::NotLoaded)) => format!("{model} (not loaded)"), |
424 | 3 | (None, Some(_)) => "(none selected)".to_string(), |
425 | | // A daemon older than `selected_model` and `model_state`. |
426 | 2 | _ => part |
427 | 2 | .current_model |
428 | 2 | .clone() |
429 | 1 | .unwrap_or_else(|| "(none loaded)".to_string()), |
430 | | } |
431 | 8 | } |
432 | | |
433 | | /// The context `voice record --prompt` and `--term` add to the user's for |
434 | | /// this recording, if they add any. |
435 | 2 | fn record_context(sub: &clap::ArgMatches) -> Option<ExtraContext> { |
436 | | let context = ExtraContext { |
437 | 2 | prompt: sub.get_one::<String>("prompt").cloned().unwrap_or_default(), |
438 | 2 | vocabulary: sub |
439 | 2 | .get_many::<String>("term") |
440 | 2 | .map_or_else(Vec::new, |terms| terms.cloned()1 .collect()), |
441 | | }; |
442 | 2 | (!context.is_empty()).then_some(context) |
443 | 2 | } |
444 | | |
445 | 0 | async fn cmd_record( |
446 | 0 | socket_path: PathBuf, |
447 | 0 | token: String, |
448 | 0 | write_mode: bool, |
449 | 0 | wait: bool, |
450 | 0 | stop_mode: Option<String>, |
451 | 0 | context: Option<ExtraContext>, |
452 | 0 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
453 | | // Toggle behavior: probe `/v1/status` first. If a daemon-mic |
454 | | // capture is already in progress, this invocation acts as a stop |
455 | | // signal; otherwise we start a fresh recording. The daemon's |
456 | | // `/v1/stt/transcribe` endpoint refuses with `409 recording_in_progress` |
457 | | // when something is already running — the protocol places the |
458 | | // start-or-stop decision on the client (see |
459 | | // `docs/protocol/endpoints/v1/transcribe.md`). |
460 | 0 | let status = http_client::status(socket_path.clone(), &token).await?; |
461 | 0 | if status.stt.busy { |
462 | 0 | return cmd_stop(socket_path, token).await; |
463 | 0 | } |
464 | | |
465 | 0 | let resp = http_client::transcribe( |
466 | 0 | socket_path, |
467 | 0 | &token, |
468 | 0 | TranscribeOptions { |
469 | 0 | write_mode, |
470 | 0 | stop_mode, |
471 | 0 | wait, |
472 | 0 | // The CLI prints the final result (or fire-and-forgets); it does not |
473 | 0 | // render incremental preview, so it never asks to stream it. |
474 | 0 | stream_realtime: false, |
475 | 0 | context, |
476 | 0 | }, |
477 | 0 | ) |
478 | 0 | .await?; |
479 | 0 | if resp.status != "success" { |
480 | | return Err(http_client::HttpError::Other( |
481 | 0 | resp.message.unwrap_or_else(|| "record failed".to_string()), |
482 | | )); |
483 | 0 | } |
484 | 0 | if let Some(transcription) = resp.transcription { |
485 | 0 | if transcription.trim().is_empty() { |
486 | 0 | println!("(no speech detected)"); |
487 | | } else { |
488 | 0 | println!("{transcription}"); |
489 | | } |
490 | 0 | } else if let Some(message) = resp.message { |
491 | 0 | println!("{message}"); |
492 | | } else { |
493 | 0 | println!("Recording started."); |
494 | | } |
495 | 0 | Ok(()) |
496 | 0 | } |
497 | | |
498 | 1 | async fn cmd_stop( |
499 | 1 | socket_path: PathBuf, |
500 | 1 | token: String, |
501 | 1 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
502 | 1 | let resp = http_client::transcribe_stop(socket_path, &token).await?0 ; |
503 | 1 | if resp.status != "success" { |
504 | | return Err(http_client::HttpError::Other( |
505 | 0 | resp.message.unwrap_or_else(|| "stop failed".to_string()), |
506 | | )); |
507 | 1 | } |
508 | 1 | println!( |
509 | | "{}", |
510 | 1 | resp.message |
511 | 0 | .unwrap_or_else(|| "stop signal sent".to_string()) |
512 | | ); |
513 | 1 | Ok(()) |
514 | 1 | } |
515 | | |
516 | | /// The text to speak: the trailing arguments, or all of stdin when none were |
517 | | /// given. Reading stdin is what makes `... | voice speak` work, which is how a |
518 | | /// shell pipeline reaches the daemon without a client of its own. |
519 | 2 | fn read_text(sub: &ArgMatches) -> Result<String> { |
520 | 2 | let words: Vec<&str> = sub |
521 | 2 | .get_many::<String>("text") |
522 | 1 | .map_or_default(|v| v.map(String::as_str).collect()); |
523 | 2 | if !words.is_empty() { |
524 | 1 | return Ok(words.join(" ")); |
525 | 1 | } |
526 | 1 | let mut buf = String::new(); |
527 | 1 | std::io::stdin() |
528 | 1 | .read_to_string(&mut buf) |
529 | 1 | .context("reading text from stdin")?0 ; |
530 | 1 | if buf.trim().is_empty() { |
531 | 0 | return Err(anyhow!("no text given: pass it as arguments or on stdin")); |
532 | 1 | } |
533 | 1 | Ok(buf) |
534 | 2 | } |
535 | | |
536 | 2 | async fn cmd_speak( |
537 | 2 | socket_path: PathBuf, |
538 | 2 | token: String, |
539 | 2 | text: String, |
540 | 2 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
541 | | // Not a toggle: a second `speak` deliberately preempts the first, which is |
542 | | // what "say this instead" means. Use `speak stop` to fall silent. |
543 | | let resp = |
544 | 2 | super_voice_shared::tts::daemon::http_client::speak(socket_path, &token, &text).await?; |
545 | 0 | report_speaking(resp) |
546 | 2 | } |
547 | | |
548 | | /// Say that an utterance started, or why it did not. |
549 | 0 | fn report_speaking( |
550 | 0 | resp: super_voice_shared::tts::models::protocol::DaemonResponse, |
551 | 0 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
552 | 0 | if resp.status != "success" { |
553 | | return Err(http_client::HttpError::Other( |
554 | 0 | resp.message.unwrap_or_else(|| "speak failed".to_string()), |
555 | | )); |
556 | 0 | } |
557 | | // The daemon answers once the utterance is queued, while the device is |
558 | | // still playing it out, so the id is all there is to report. |
559 | 0 | if let Some(id) = resp.utterance_id { |
560 | 0 | println!("Speaking ({id})."); |
561 | | } else { |
562 | 0 | println!("Speaking."); |
563 | | } |
564 | 0 | Ok(()) |
565 | 0 | } |
566 | | |
567 | | /// `voice speak --read`: speak the selected or copied text, or stop. The |
568 | | /// daemon reads it, from wherever the user's read method says. Pressed while |
569 | | /// anything is speaking, the shortcut that runs this stops it rather than |
570 | | /// reading again, the way `record` stops a recording. Without that, a long |
571 | | /// passage could only be stopped from another command. |
572 | | #[cfg(any(target_os = "linux", target_os = "macos"))] |
573 | 1 | async fn cmd_speak_read( |
574 | 1 | socket_path: PathBuf, |
575 | 1 | token: String, |
576 | 1 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
577 | 1 | let status = http_client::status(socket_path.clone(), &token).await?0 ; |
578 | 1 | if status.tts.busy { |
579 | 0 | return cmd_speak_stop(socket_path, token).await; |
580 | 1 | } |
581 | 1 | let resp = super_voice_shared::tts::daemon::http_client::speak_read(socket_path, &token) |
582 | 1 | .await |
583 | 1 | .map_err(said_plainly)?; |
584 | 0 | report_speaking(resp) |
585 | 1 | } |
586 | | |
587 | | /// The refusals of `POST /tts/speak/read` the user fixes themselves, said in |
588 | | /// the daemon's words alone: what to switch on, or what to select, without |
589 | | /// the error's code and status. The listener logs what this says too. |
590 | | #[cfg(any(target_os = "linux", target_os = "macos"))] |
591 | 5 | fn said_plainly( |
592 | 5 | e: super_voice_shared::daemon::http_client::HttpError, |
593 | 5 | ) -> super_voice_shared::daemon::http_client::HttpError { |
594 | | use super_voice_shared::daemon::http_client::HttpError; |
595 | | const THE_USERS_TO_FIX: [&str; 3] = ["not_allowed", "secure_input", "nothing_to_read"]; |
596 | 5 | match &e { |
597 | | HttpError::Other(text) |
598 | 5 | if THE_USERS_TO_FIX |
599 | 5 | .iter() |
600 | 12 | .any(|code| text.starts_with(&format!("{code}: "))) => |
601 | | { |
602 | 3 | HttpError::Other(e.user_message(&super_voice_shared::SUPER_VOICE)) |
603 | | } |
604 | 2 | _ => e, |
605 | | } |
606 | 5 | } |
607 | | |
608 | 2 | async fn cmd_speak_stop( |
609 | 2 | socket_path: PathBuf, |
610 | 2 | token: String, |
611 | 2 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
612 | | let resp = |
613 | 2 | super_voice_shared::tts::daemon::http_client::speak_stop(socket_path, &token).await?0 ; |
614 | 2 | if resp.status != "success" { |
615 | | return Err(http_client::HttpError::Other( |
616 | 0 | resp.message.unwrap_or_else(|| "stop failed".to_string()), |
617 | | )); |
618 | 2 | } |
619 | | // Stopping when nothing is speaking is a success, not an error — so say |
620 | | // which of the two happened rather than claiming to have stopped something. |
621 | 2 | match resp.utterance_id { |
622 | 0 | Some(id) => println!("Stopped ({id})."), |
623 | 2 | None => println!("Nothing was speaking."), |
624 | | } |
625 | 2 | Ok(()) |
626 | 2 | } |
627 | | |
628 | | /// `voice updates betas [value]`: save `value` when given, then print the |
629 | | /// setting, `auto`, `enabled` or `disabled`, on a line of its own. |
630 | 10 | async fn cmd_updates_betas( |
631 | 10 | socket_path: PathBuf, |
632 | 10 | token: String, |
633 | 10 | value: Option<String>, |
634 | 10 | ) -> super_voice_shared::daemon::http_client::HttpResult<()> { |
635 | | use super_voice_shared::daemon::http_client::transport; |
636 | | const PATH: &str = "/settings/update_beta_optin"; |
637 | 10 | let resp = match value { |
638 | | Some(value) => { |
639 | 4 | transport::settings_post( |
640 | 4 | socket_path, |
641 | 4 | &token, |
642 | 4 | PATH, |
643 | 4 | &serde_json::json!({ "value": value }), |
644 | 4 | ) |
645 | 4 | .await?0 |
646 | | } |
647 | 6 | None => transport::settings_get(socket_path, &token, PATH).await?0 , |
648 | | }; |
649 | 10 | let setting = resp.update_beta_optin.ok_or_else(|| {0 |
650 | 0 | http_client::HttpError::Other("the daemon answered without the setting".to_string()) |
651 | 0 | })?; |
652 | 10 | println!("{setting}"); |
653 | 10 | Ok(()) |
654 | 10 | } |
655 | | |
656 | | /// The key the daemon made `assistant`, and where it reaches Super Voice's |
657 | | /// MCP server with it. `None` when the daemon gave none, as for an assistant |
658 | | /// not connected. |
659 | 0 | pub(crate) async fn assistant_access( |
660 | 0 | socket_path: PathBuf, |
661 | 0 | assistant: AssistantId, |
662 | 0 | ) -> Option<(String, String)> { |
663 | 0 | let body = assistant_key_body(socket_path, assistant).await.ok()?; |
664 | | Some(( |
665 | 0 | body["key"].as_str()?.to_string(), |
666 | 0 | body["address"].as_str()?.to_string(), |
667 | | )) |
668 | 0 | } |
669 | | |
670 | | /// `GET /assistants/{assistant}/key`, as the daemon answers it. |
671 | 0 | async fn assistant_key_body( |
672 | 0 | socket_path: PathBuf, |
673 | 0 | assistant: AssistantId, |
674 | 0 | ) -> super_voice_shared::daemon::http_client::HttpResult<serde_json::Value> { |
675 | 0 | let path = format!("/assistants/{assistant}/key"); |
676 | 0 | session::with_token( |
677 | 0 | socket_path.clone(), |
678 | 0 | APP_ID, |
679 | 0 | APP_NAME, |
680 | 0 | SETTINGS_SCOPES, |
681 | 0 | |token| { |
682 | 0 | let socket_path = socket_path.clone(); |
683 | 0 | let path = path.clone(); |
684 | 0 | async move { |
685 | 0 | http_client::transport::get_json::<serde_json::Value>(socket_path, &token, &path) |
686 | 0 | .await |
687 | 0 | } |
688 | 0 | }, |
689 | | ) |
690 | 0 | .await |
691 | 0 | } |
692 | | |
693 | | /// The assistant `assistant-hook` names. |
694 | 0 | fn assistant_of(sub: &clap::ArgMatches) -> Result<AssistantId> { |
695 | 0 | sub.get_one::<String>("assistant") |
696 | 0 | .and_then(|id| id.parse::<AssistantId>().ok()) |
697 | 0 | .context("an assistant is required") |
698 | 0 | } |
699 | | |
700 | 1 | fn cmd_logout() -> Result<()> { |
701 | 1 | session::forget(APP_ID).map_err(|e| anyhow!0 (e0 ))?0 ; |
702 | 1 | println!("Cached session token removed. Next invocation will trigger re-consent."); |
703 | 1 | Ok(()) |
704 | 1 | } |
705 | | |
706 | | #[cfg(test)] |
707 | | mod tests { |
708 | | /// A refusal of `voice speak --read` the user fixes reads as the daemon's |
709 | | /// sentence; anything else keeps its code and status for the log. |
710 | | #[cfg(any(target_os = "linux", target_os = "macos"))] |
711 | | #[test] |
712 | 1 | fn a_refusal_the_user_fixes_is_said_plainly() { |
713 | | use super::said_plainly; |
714 | | use super_voice_shared::daemon::http_client::HttpError; |
715 | 4 | let said = |text: &str| said_plainly(HttpError::Other(text.to_string())).to_string(); |
716 | 1 | assert_eq!( |
717 | 1 | said( |
718 | 1 | "not_allowed: Super Voice is not allowed to read the selected text. \ |
719 | 1 | Switch on Super Voice under Device Control. (HTTP 409)" |
720 | 1 | ), |
721 | 1 | "Super Voice is not allowed to read the selected text. \ |
722 | 1 | Switch on Super Voice under Device Control." |
723 | | ); |
724 | 1 | assert_eq!( |
725 | 1 | said("secure_input: Another app has secure keyboard entry on. (HTTP 409)"), |
726 | 1 | "Another app has secure keyboard entry on." |
727 | | ); |
728 | 1 | assert_eq!( |
729 | 1 | said("nothing_to_read: Nothing is selected. (HTTP 409)"), |
730 | 1 | "Nothing is selected." |
731 | | ); |
732 | 1 | assert_eq!( |
733 | 1 | said("internal: could_not_read (HTTP 500)"), |
734 | 1 | "internal: could_not_read (HTTP 500)" |
735 | | ); |
736 | 1 | } |
737 | | |
738 | | /// A feature's status as a daemon reports it, for [`super::model_line`]. |
739 | 6 | fn part( |
740 | 6 | selected_model: Option<&str>, |
741 | 6 | model_state: Option<super_voice_shared::models::protocol::ModelState>, |
742 | 6 | current_model: Option<&str>, |
743 | 6 | ) -> super_voice_shared::models::status::FeatureStatus { |
744 | 6 | super_voice_shared::models::status::FeatureStatus { |
745 | 6 | device: "unknown".to_string(), |
746 | 6 | model_loaded: current_model.is_some(), |
747 | 6 | current_model: current_model.map(str::to_string), |
748 | 6 | selected_model: selected_model.map(str::to_string), |
749 | 6 | model_state, |
750 | 6 | busy: false, |
751 | 6 | can_type: None, |
752 | 6 | can_record: None, |
753 | 6 | } |
754 | 6 | } |
755 | | |
756 | | #[test] |
757 | 1 | fn status_names_the_selected_model_and_whether_it_is_in_memory() { |
758 | | use super::model_line; |
759 | | use super_voice_shared::models::protocol::ModelState; |
760 | 1 | assert_eq!( |
761 | 1 | model_line(&part( |
762 | 1 | Some("whisper-tiny"), |
763 | 1 | Some(ModelState::Loaded), |
764 | 1 | Some("whisper-tiny") |
765 | 1 | )), |
766 | 1 | "whisper-tiny" |
767 | | ); |
768 | | // What it said "(none loaded)" for. |
769 | 1 | assert_eq!( |
770 | 1 | model_line(&part(Some("whisper-tiny"), Some(ModelState::Idle), None)), |
771 | 1 | "whisper-tiny (asleep; loads when next used)" |
772 | | ); |
773 | 1 | assert_eq!( |
774 | 1 | model_line(&part( |
775 | 1 | Some("whisper-tiny"), |
776 | 1 | Some(ModelState::NotLoaded), |
777 | 1 | None |
778 | 1 | )), |
779 | 1 | "whisper-tiny (not loaded)" |
780 | | ); |
781 | 1 | assert_eq!( |
782 | 1 | model_line(&part(None, Some(ModelState::NotLoaded), None)), |
783 | 1 | "(none selected)" |
784 | | ); |
785 | 1 | } |
786 | | |
787 | | /// A daemon older than the fields reports only the loaded model. |
788 | | #[test] |
789 | 1 | fn status_from_an_older_daemon_reads_as_before() { |
790 | | use super::model_line; |
791 | 1 | assert_eq!( |
792 | 1 | model_line(&part(None, None, Some("whisper-tiny"))), |
793 | 1 | "whisper-tiny" |
794 | | ); |
795 | 1 | assert_eq!(model_line(&part(None, None, None)), "(none loaded)"); |
796 | 1 | } |
797 | | |
798 | | use super::SCOPES; |
799 | | use super_voice_shared::daemon::scopes::is_known_scope; |
800 | | |
801 | | /// The CLI's requested scope set must be a subset of the daemon's shared |
802 | | /// catalog. Without this, a wire-scope rename in `scopes::known_scopes` |
803 | | /// would leave `SCOPES` requesting a token the daemon rejects, and the |
804 | | /// break would only surface at runtime as a failed `/auth/request`. Mirrors |
805 | | /// the consent binary's `scope_conformance` guard (audit 2 Tier 3 #33). |
806 | | #[test] |
807 | 1 | fn requested_scopes_are_known() { |
808 | 1 | for scope in SCOPES |
809 | 1 | .iter() |
810 | 1 | .chain(super::SETTINGS_SCOPES) |
811 | 1 | .chain(super::HOTKEY_SCOPES) |
812 | | { |
813 | 12 | assert!( |
814 | 12 | is_known_scope(scope), |
815 | | "CLI requests scope `{scope}` that is not in scopes::known_scopes" |
816 | | ); |
817 | | } |
818 | 1 | } |
819 | | |
820 | | /// Reading an assistant's key or a setting asks for what every other |
821 | | /// command does, so its token serves them too, and `settings`, which |
822 | | /// their routes take. |
823 | | #[test] |
824 | 1 | fn reading_a_setting_asks_for_settings_as_well() { |
825 | 1 | let settings = super::SETTINGS_SCOPES; |
826 | 1 | assert!( |
827 | 3 | SCOPES.iter()1 .all(|scope| settings.contains(scope)), |
828 | | "{settings:?}" |
829 | | ); |
830 | 1 | assert!(settings.contains(&"settings")); |
831 | 1 | assert!( |
832 | 1 | !SCOPES.contains(&"settings"), |
833 | | "only those commands ask for it" |
834 | | ); |
835 | 1 | } |
836 | | |
837 | | /// `voice updates betas` takes the setting's own values, or none to |
838 | | /// print it. |
839 | | #[test] |
840 | 1 | fn updates_betas_takes_the_setting_s_values() { |
841 | 4 | let value = |args: &[&str]| { |
842 | 4 | let matches = super::build_cli() |
843 | 4 | .try_get_matches_from(args) |
844 | 4 | .expect("parses"); |
845 | 4 | let (_, updates) = matches.subcommand().expect("updates"); |
846 | 4 | let (_, betas) = updates.subcommand().expect("betas"); |
847 | 4 | betas.get_one::<String>("value").cloned() |
848 | 4 | }; |
849 | 1 | assert_eq!(value(&["voice", "updates", "betas"]), None); |
850 | 1 | for setting in ["auto", "enabled", "disabled"] { |
851 | 3 | assert_eq!( |
852 | 3 | value(&["voice", "updates", "betas", setting]).as_deref(), |
853 | 3 | Some(setting) |
854 | | ); |
855 | | } |
856 | 1 | for args in [ |
857 | 1 | &["voice", "updates", "betas", "on"][..], |
858 | 1 | &["voice", "updates", "betas", "Enabled"][..], |
859 | 1 | ] { |
860 | 2 | assert!( |
861 | 2 | super::build_cli().try_get_matches_from(args).is_err(), |
862 | | "{args:?}" |
863 | | ); |
864 | | } |
865 | 1 | } |
866 | | |
867 | | /// `stop` belongs to a feature: `voice record stop` and `voice speak stop`. |
868 | | #[test] |
869 | 1 | fn each_feature_has_its_own_stop() { |
870 | 1 | for feature in ["record", "speak"] { |
871 | 2 | let matches = super::build_cli() |
872 | 2 | .try_get_matches_from(["voice", feature, "stop"]) |
873 | 2 | .expect("parses"); |
874 | 2 | let (name, sub) = matches.subcommand().expect("a subcommand"); |
875 | 2 | assert_eq!(name, feature); |
876 | 2 | assert!( |
877 | 2 | matches!(sub.subcommand(), Some(("stop", _))), |
878 | | "{feature} stop" |
879 | | ); |
880 | | } |
881 | 1 | assert!( |
882 | 1 | super::build_cli() |
883 | 1 | .try_get_matches_from(["voice", "stop"]) |
884 | 1 | .is_err(), |
885 | | "a bare `stop` would not say which feature to stop" |
886 | | ); |
887 | 1 | } |
888 | | |
889 | | /// Words after `speak` are the text, and `--` lets the text be the word |
890 | | /// "stop". |
891 | | #[test] |
892 | 1 | fn speak_takes_its_text_from_the_rest_of_the_line() { |
893 | 3 | let text = |args: &[&str]| { |
894 | 3 | let matches = super::build_cli() |
895 | 3 | .try_get_matches_from(args) |
896 | 3 | .expect("parses"); |
897 | 3 | let (_, sub) = matches.subcommand().expect("speak"); |
898 | 3 | assert!( |
899 | 3 | sub.subcommand().is_none(), |
900 | | "{args:?} is text, not a subcommand" |
901 | | ); |
902 | 3 | sub.get_many::<String>("text") |
903 | 3 | .expect("text") |
904 | 3 | .cloned() |
905 | 3 | .collect::<Vec<_>>() |
906 | 3 | .join(" ") |
907 | 3 | }; |
908 | 1 | assert_eq!(text(&["voice", "speak", "hello", "there"]), "hello there"); |
909 | 1 | assert_eq!(text(&["voice", "speak", "please", "stop"]), "please stop"); |
910 | 1 | assert_eq!(text(&["voice", "speak", "--", "stop"]), "stop"); |
911 | 1 | } |
912 | | |
913 | | /// The binding the installer writes parses. What is read is all the text |
914 | | /// there is, so it goes with neither text nor `stop`. |
915 | | #[cfg(any(target_os = "linux", target_os = "macos"))] |
916 | | #[test] |
917 | 1 | fn speak_read_takes_no_text() { |
918 | 1 | let matches = super::build_cli() |
919 | 1 | .try_get_matches_from(["voice", "speak", "--read"]) |
920 | 1 | .expect("the COSMIC binding parses"); |
921 | 1 | let (_, sub) = matches.subcommand().expect("speak"); |
922 | 1 | assert!(sub.get_flag("read")); |
923 | 1 | for args in [ |
924 | 1 | &["voice", "speak", "--read", "hello"][..], |
925 | 1 | &["voice", "speak", "--read", "stop"][..], |
926 | 1 | ] { |
927 | 2 | assert!( |
928 | 2 | super::build_cli().try_get_matches_from(args).is_err(), |
929 | | "{args:?}" |
930 | | ); |
931 | | } |
932 | 1 | } |
933 | | |
934 | | /// The binding the installer writes parses, and a recording's flags do |
935 | | /// not go with `record stop`. |
936 | | #[test] |
937 | 1 | fn record_takes_its_flags_or_stop() { |
938 | 1 | let matches = super::build_cli() |
939 | 1 | .try_get_matches_from(["voice", "record", "--write"]) |
940 | 1 | .expect("the COSMIC binding parses"); |
941 | 1 | let (_, sub) = matches.subcommand().expect("record"); |
942 | 1 | assert!(sub.get_flag("write")); |
943 | 1 | assert!( |
944 | 1 | super::build_cli() |
945 | 1 | .try_get_matches_from(["voice", "record", "--write", "stop"]) |
946 | 1 | .is_err() |
947 | | ); |
948 | 1 | } |
949 | | |
950 | | /// `--prompt` and each `--term` make the recording's own context, and |
951 | | /// a recording without them has none. |
952 | | #[test] |
953 | 1 | fn record_takes_a_context_of_its_own() { |
954 | 1 | let matches = super::build_cli() |
955 | 1 | .try_get_matches_from([ |
956 | 1 | "voice", |
957 | 1 | "record", |
958 | 1 | "--wait", |
959 | 1 | "--prompt", |
960 | 1 | "About the release.", |
961 | 1 | "--term", |
962 | 1 | "agy", |
963 | 1 | "--term", |
964 | 1 | "Antigravity", |
965 | 1 | ]) |
966 | 1 | .expect("the context flags parse"); |
967 | 1 | let (_, sub) = matches.subcommand().expect("record"); |
968 | 1 | let context = super::record_context(sub).expect("a context"); |
969 | 1 | assert_eq!(context.prompt, "About the release."); |
970 | 1 | assert_eq!(context.vocabulary, ["agy", "Antigravity"]); |
971 | | |
972 | 1 | let matches = super::build_cli() |
973 | 1 | .try_get_matches_from(["voice", "record"]) |
974 | 1 | .expect("a bare record parses"); |
975 | 1 | let (_, sub) = matches.subcommand().expect("record"); |
976 | 1 | assert_eq!(super::record_context(sub), None); |
977 | 1 | } |
978 | | |
979 | | /// The hotkey `LaunchAgent`'s arguments must parse. launchd restarts the |
980 | | /// listener whenever it exits, so arguments clap rejects would become a |
981 | | /// restart every few seconds with nothing listening — and the only symptom |
982 | | /// would be a shortcut that silently does nothing. Mirrors the daemon's |
983 | | /// `every_shipped_execstart_parses`. |
984 | | #[cfg(target_os = "macos")] |
985 | | #[test] |
986 | | fn hotkey_launch_agent_arguments_parse() { |
987 | | let args = hotkey_launch_agent_arguments(); |
988 | | assert_eq!(args.get(1).map(String::as_str), Some("hotkey")); |
989 | | let matches = super::build_cli() |
990 | | .try_get_matches_from(&args) |
991 | | .expect("the hotkey LaunchAgent's arguments must parse"); |
992 | | let (_, sub) = matches.subcommand().expect("a subcommand"); |
993 | | let binding = sub.get_one::<String>("key").expect("--key has a value"); |
994 | | super::hotkey::check(binding).expect("the default binding must be valid"); |
995 | | } |
996 | | |
997 | | /// The `ProgramArguments` of the hotkey `LaunchAgent`. |
998 | 1 | fn hotkey_launch_agent_arguments() -> Vec<String> { |
999 | 1 | let plist = include_str!("../launchd/org.superlibre.super-voice.hotkey.plist"); |
1000 | 1 | let array = plist |
1001 | 1 | .split("<key>ProgramArguments</key>") |
1002 | 1 | .nth(1) |
1003 | 1 | .and_then(|rest| rest.split("</array>").next()) |
1004 | 1 | .expect("the plist has a ProgramArguments array"); |
1005 | 1 | array |
1006 | 1 | .split("<string>") |
1007 | 1 | .skip(1) |
1008 | 2 | .filter_map(|s| s.split("</string>").next()) |
1009 | 1 | .map(str::to_string) |
1010 | | .collect() |
1011 | 1 | } |
1012 | | |
1013 | | /// The agent names no keys: the listener reads them from the daemon, and |
1014 | | /// a binding baked in at bundle time could not be changed from the app. |
1015 | | #[test] |
1016 | 1 | fn the_hotkey_agent_takes_its_keys_from_the_daemon() { |
1017 | 1 | assert_eq!( |
1018 | 1 | hotkey_launch_agent_arguments(), |
1019 | 1 | ["super-voice-cli", "hotkey"] |
1020 | | ); |
1021 | 1 | } |
1022 | | |
1023 | | /// The listener's token covers what a press of Read aloud asks: whether |
1024 | | /// speech is playing, to speak the selection, and to stop. |
1025 | | #[test] |
1026 | 1 | fn the_listener_may_read_aloud() { |
1027 | 1 | for scope in ["speak", "status", "transcribe", "settings"] { |
1028 | 4 | assert!(super::HOTKEY_SCOPES.contains(&scope), "{scope}"); |
1029 | | } |
1030 | 1 | } |
1031 | | |
1032 | | /// Both shortcuts' default keys register with `global-hotkey`, and as |
1033 | | /// different keys, so the listener can hold both from the start. |
1034 | | #[test] |
1035 | 1 | fn both_default_bindings_register_apart() { |
1036 | | use global_hotkey::hotkey::HotKey; |
1037 | | use super_voice_shared::models::hotkey::{self, Binding}; |
1038 | | use super_voice_shared::models::shortcuts::ShortcutId; |
1039 | | |
1040 | 1 | let keys: Vec<HotKey> = ShortcutId::ALL |
1041 | 1 | .into_iter() |
1042 | 2 | .map(|shortcut| { |
1043 | 2 | let written: HotKey = hotkey::default_binding_for(shortcut) |
1044 | 2 | .parse() |
1045 | 2 | .expect("the default parses"); |
1046 | | // As the daemon stores it, too. |
1047 | 2 | let stored: HotKey = Binding::default_for(shortcut) |
1048 | 2 | .to_string() |
1049 | 2 | .parse() |
1050 | 2 | .expect("the stored default parses"); |
1051 | 2 | assert_eq!(written, stored); |
1052 | 2 | stored |
1053 | 2 | }) |
1054 | | .collect(); |
1055 | 1 | assert_ne!(keys[0], keys[1]); |
1056 | 1 | assert_ne!(keys[0].id(), keys[1].id()); |
1057 | 1 | } |
1058 | | |
1059 | | /// The listener's token covers the events it follows. |
1060 | | #[test] |
1061 | 1 | fn the_listener_may_follow_its_events() { |
1062 | | use super_voice_shared::daemon::widget_subscription::uncovered_topic; |
1063 | 1 | assert_eq!( |
1064 | 1 | uncovered_topic(super::HOTKEY_SCOPES, super::HOTKEY_TOPICS), |
1065 | 1 | None |
1066 | | ); |
1067 | 1 | } |
1068 | | |
1069 | | /// The shared binding grammar, which the daemon and the apps check a |
1070 | | /// binding with, reads every binding as `global-hotkey`'s parser does, |
1071 | | /// which the listener registers it with: the same bindings accepted, with |
1072 | | /// the same modifiers and key, and the same refused. |
1073 | | #[test] |
1074 | 1 | fn the_shared_binding_grammar_is_global_hotkeys() { |
1075 | | use global_hotkey::hotkey::{HotKey, Modifiers}; |
1076 | | use super_voice_shared::models::hotkey::{self, Binding}; |
1077 | | |
1078 | 1 | let mut samples: Vec<String> = [ |
1079 | 1 | "", |
1080 | 1 | " ", |
1081 | 1 | "+", |
1082 | 1 | "ctrl+", |
1083 | 1 | "+space", |
1084 | 1 | "ctrl++space", |
1085 | 1 | "ctrl+alt+space", |
1086 | 1 | "ctrl+alt+shift+space", |
1087 | 1 | "Ctrl + Alt + Space", |
1088 | 1 | " space", |
1089 | 1 | "space ", |
1090 | 1 | "shift+ctrl", |
1091 | 1 | "ctrl", |
1092 | 1 | "shift+KeyQ+alt", |
1093 | 1 | "ctrl+a+b", |
1094 | 1 | "super", |
1095 | 1 | "super+space", |
1096 | 1 | "meta+r", |
1097 | 1 | "command+option+control+shift+F5", |
1098 | 1 | "OPTION+digit1", |
1099 | 1 | "ctrl+banana", |
1100 | 1 | "ctrl+ ", |
1101 | 1 | "ctrl+Super", |
1102 | 1 | "alt+Fn", |
1103 | 1 | "cmd+shift+KeyR", |
1104 | 1 | "ctrl+f35", |
1105 | 1 | "ctrl+F36", |
1106 | 1 | "ctrl+ß", |
1107 | 1 | "hyper+space", |
1108 | 1 | "ctrl+\\", |
1109 | 1 | "cmd+,", |
1110 | 1 | ] |
1111 | 1 | .map(str::to_string) |
1112 | 1 | .to_vec(); |
1113 | | // `cmdorctrl` is `cmd` only on a Mac; `global-hotkey` reads it as |
1114 | | // `ctrl` elsewhere. |
1115 | 1 | if cfg!(target_os = "macos") { |
1116 | 0 | samples.push("CmdOrCtrl+Space".to_string()); |
1117 | 1 | } |
1118 | 1 | for spelling in Binding::key_spellings() { |
1119 | 298 | samples.push(spelling.to_string()); |
1120 | 298 | samples.push(spelling.to_lowercase()); |
1121 | 298 | samples.push(format!("ctrl+shift+{spelling}")); |
1122 | 298 | samples.push(format!("alt + {}", spelling.to_lowercase())); |
1123 | 298 | samples.push(format!("{spelling}+ctrl")); |
1124 | | } |
1125 | | |
1126 | 1 | for sample in &samples { |
1127 | 1.52k | let ours = Binding::parse(sample); |
1128 | 1.52k | let theirs = sample.parse::<HotKey>(); |
1129 | 1.52k | match (&ours, &theirs) { |
1130 | | (Ok(ours), Ok(theirs)) => { |
1131 | 1.20k | assert_eq!(ours.key(), theirs.key.to_string(), "key of `{sample}`"); |
1132 | 1.20k | let mods = ours.modifiers(); |
1133 | 1.20k | for (shared, global) in [ |
1134 | 1.20k | (hotkey::Modifiers::CONTROL, Modifiers::CONTROL), |
1135 | 1.20k | (hotkey::Modifiers::OPTION, Modifiers::ALT), |
1136 | 1.20k | (hotkey::Modifiers::SHIFT, Modifiers::SHIFT), |
1137 | 1.20k | (hotkey::Modifiers::COMMAND, Modifiers::META), |
1138 | 1.20k | ] { |
1139 | 4.81k | assert_eq!( |
1140 | 4.81k | mods.contains(shared), |
1141 | 4.81k | theirs.mods.contains(global), |
1142 | | "modifiers of `{sample}`" |
1143 | | ); |
1144 | | } |
1145 | | } |
1146 | 318 | (Err(_), Err(_)) => {} |
1147 | 0 | _ => panic!("`{sample}`: ours {ours:?}, global-hotkey's {theirs:?}"), |
1148 | | } |
1149 | | } |
1150 | 1 | assert!(samples.len() > 1000, "every key is tried"); |
1151 | 1 | } |
1152 | | } |