Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-daemon/src/daemon/http/mcp/tools.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! The tools: `speak` and `listen`, and the plugin's `stop`, `status`,
3
//! `announce`, `session` and `turn`, run on the daemon itself.
4
//!
5
//! What a session speaks and records is its own
6
//! ([`crate::assistants::sessions::Sessions`]): `stop` and `status` see only
7
//! the caller's.
8
//!
9
//! A tool runs on a task of its own, so it ends as the daemon's work does,
10
//! never midway because its client went away. It is cancelled through its
11
//! [`CancellationToken`], by `notifications/cancelled`, by its connection
12
//! closing, or by its key being revoked, and then answers nothing:
13
//!
14
//! 1. `speak` goes on speaking, as `POST /v1/tts/speak` does when its client
15
//!    hangs up. Only the wait for it ends.
16
//! 2. `listen` asking its question stops the question, if it is still the one
17
//!    speaking.
18
//! 3. `listen` recording stops the recording, and the take is finished all
19
//!    the same, so the microphone is freed as at any other stop.
20
21
use super::protocol::{Hook, SessionEvent, Tool, TurnEvent};
22
use crate::assistants::dictation::holds_what_was_said;
23
use crate::assistants::sessions::Who;
24
use crate::daemon::events::Topic;
25
use crate::daemon::recording::{Stopped, TakeSettings};
26
use crate::daemon::types::SuperSTTDaemon;
27
use crate::output::typer::Typer;
28
use std::sync::Arc;
29
use std::time::Duration;
30
use super_voice_shared::models::contexts::ExtraContext;
31
use super_voice_shared::models::protocol::{DaemonResponse, ErrorCode};
32
use super_voice_shared::models::recording_stop_mode::RecordingStopMode;
33
use super_voice_shared::tts::models::protocol::{
34
    DaemonResponse as SpeechResponse, ErrorCode as SpeechErrorCode,
35
};
36
use tokio::task::{JoinError, JoinHandle};
37
use tokio_util::sync::CancellationToken;
38
39
/// How often `listen` looks again whether its question is still playing,
40
/// besides when speech starts or stops.
41
const TICK: Duration = Duration::from_millis(100);
42
43
/// Who a call is for: its session, whether the user lets its assistant
44
/// announce, whether its `listen` calls are heard with the context they
45
/// bring, whether its plugin shows Talk, whether it sends a prompt dictated
46
/// into it by itself, and the hook that made the call, if one did.
47
#[allow(
48
    clippy::struct_excessive_bools,
49
    reason = "each flag is one of the assistant's switches, as the call found them"
50
)]
51
pub(crate) struct CallContext {
52
    pub(crate) who: Who,
53
    pub(crate) announces: bool,
54
    pub(crate) uses_context: bool,
55
    pub(crate) shows_talk: bool,
56
    pub(crate) autosends: bool,
57
    pub(crate) hook: Option<Hook>,
58
}
59
60
/// Why `speak` and `listen` are refused in a turn the user typed.
61
const NOT_SPOKEN_TO: &str = "The user typed this prompt, so answer in writing. Super Voice \
62
    speaks and listens only while the user is talking to you by voice.";
63
64
/// Why a `speak` waiting for the session's speech to end was not said.
65
const NOT_SAID_STOPPED: &str = "Not said: the user stopped your speech while this waited its turn.";
66
67
/// What the assistant is told beside a prompt the user said aloud, so it
68
/// answers for listening and works as it always does.
69
const SPOKEN_NOTE: &str = "The user said this aloud, through Super Voice. Do the work as you \
70
    normally would. Only your final reply is read aloud to them: keep that reply short and \
71
    plain to listen to, and end it with any question you have.";
72
73
/// Whether `who`'s plugin said the turn under way was typed.
74
10
fn is_typed_turn(daemon: &SuperSTTDaemon, who: &Who) -> bool {
75
10
    daemon.assistants.sessions.spoken(who) == Some(false)
76
10
}
77
78
/// `answer`, or for a hook, which reads the text as its own output,
79
/// nothing.
80
13
fn for_caller(call: &CallContext, answer: String) -> String {
81
13
    if call.hook.is_some() {
82
2
        String::new()
83
    } else {
84
11
        answer
85
    }
86
13
}
87
88
/// What `tool` comes to: its text, or the error the model sees. `None` when
89
/// it was cancelled, which is answered with nothing.
90
50
pub(crate) async fn run(
91
50
    daemon: &Arc<SuperSTTDaemon>,
92
50
    tool: Tool,
93
50
    call: &CallContext,
94
50
    cancel: &CancellationToken,
95
50
) -> Option<Result<String, String>> {
96
50
    let who = &call.who;
97
50
    let sessions = &daemon.assistants.sessions;
98
50
    match tool {
99
        Tool::Speak { asked: false, .. } | Tool::Listen { asked: false, .. }
100
5
            if is_typed_turn(daemon, who) =>
101
        {
102
1
            Some(Err(NOT_SPOKEN_TO.to_string()))
103
        }
104
        // What the user asked to hear, like a reply read again, speaks at once.
105
1
        Tool::Speak { text, asked: true } => speak(daemon, who, text, cancel).await,
106
4
        Tool::Speak { text, asked: false } => speak_in_turn(daemon, who, text, cancel).await,
107
        Tool::Listen {
108
            question,
109
            context,
110
            asked,
111
        } => {
112
            // The model's own speech plays to its end first: `speak` answers
113
            // as soon as the speech starts, and a question or a recording
114
            // would cut it off. What the user asked for, like Talk, does not
115
            // wait: they mean to talk over it.
116
6
            if !asked && !
own_speech_ended5
(
daemon5
, who, cancel).
await5
{
117
1
                return None;
118
5
            }
119
5
            let extra = take_context(question.as_deref(), context, call.uses_context);
120
5
            listen(daemon, who, question, extra, cancel).await
121
        }
122
2
        Tool::Stop => Some(Ok(stop(daemon, who).await)),
123
5
        Tool::Status => Some(Ok(status(daemon, who, call))),
124
2
        Tool::Announce { text } if call.announces => 
speak0
(
daemon0
,
who0
, text, cancel)
125
0
            .await
126
0
            .map(|said| said.map(|answer| for_caller(call, answer))),
127
2
        Tool::Announce { .. } => Some(Ok(for_caller(
128
2
            call,
129
2
            "Not said: the user turned announcing off for this assistant.".to_string(),
130
2
        ))),
131
7
        Tool::Session(event) => Some(Ok(for_caller(
132
7
            call,
133
7
            match event {
134
                SessionEvent::Start => {
135
3
                    sessions.open(who);
136
3
                    "Started."
137
                }
138
                SessionEvent::End => {
139
2
                    sessions.close(who);
140
2
                    "Ended."
141
                }
142
                SessionEvent::Seen => {
143
2
                    sessions.touch(who);
144
2
                    "Seen."
145
                }
146
            }
147
            .to_string(),
148
        ))),
149
        Tool::Turn(TurnEvent::Prompt {
150
            text,
151
            spoken,
152
            heard,
153
            again,
154
14
        }) => Some(Ok(if let Some(request) = read_request(&text) {
155
            // A turn of its own, typed, that ends before the assistant runs.
156
5
            sessions.set_spoken(who, false);
157
5
            let outcome = read_again(daemon, who, request).await;
158
5
            read_answer(call.hook, outcome)
159
        } else {
160
            // The same prompt said again keeps its turn: its dictation is
161
            // used up by now.
162
9
            let again = sessions.prompted(who, &text, again);
163
9
            let spoken = spoken.or(again).unwrap_or_else(|| 
{5
164
5
                heard.is_some_and(|heard| 
holds_what_was_said2
(
&text2
,
&heard2
))
165
4
                    || daemon
166
4
                        .assistants
167
4
                        .dictation
168
4
                        .matches(&text, std::time::Instant::now())
169
5
            });
170
9
            sessions.set_spoken(who, spoken);
171
9
            prompt_answer(call.hook, spoken, again.is_none())
172
        })),
173
5
        Tool::Turn(TurnEvent::Reply { text }) => read_reply(daemon, call, text, cancel).await,
174
3
        Tool::Turn(TurnEvent::Draft { text }) => Some(Ok(serde_json::json!({
175
3
            "dictated": daemon
176
3
                .assistants
177
3
                .dictation
178
3
                .matches(&text, std::time::Instant::now()),
179
3
        })
180
3
        .to_string())),
181
    }
182
50
}
183
184
/// The answer to a prompt's turn: for a Codex hook, the context that goes
185
/// beside a spoken prompt, or nothing; for a plugin, whether it was spoken
186
/// and, when the turn is `new`, that context. A plugin whose hook runs before
187
/// each model call adds it to the turn once.
188
9
fn prompt_answer(hook: Option<Hook>, spoken: bool, new: bool) -> String {
189
9
    match hook {
190
2
        Some(Hook::Codex) if spoken => 
serde_json::json!1
({
191
1
            "hookSpecificOutput": {
192
1
                "hookEventName": "UserPromptSubmit",
193
1
                "additionalContext": SPOKEN_NOTE,
194
1
            },
195
1
        })
196
1
        .to_string(),
197
1
        Some(Hook::Codex) => String::new(),
198
7
        None => serde_json::json!({
199
7
            "spoken": spoken,
200
7
            "note": (spoken && 
new3
).then_some(SPOKEN_NOTE),
201
        })
202
        .to_string(),
203
    }
204
9
}
205
206
/// What a `/read` prompt asks for.
207
#[derive(Debug, PartialEq)]
208
enum ReadRequest {
209
    /// Plain `/read`: the last reply, or to stop what the session says.
210
    Last,
211
    /// `/read 3`: the reply that many before the last one.
212
    Back(usize),
213
    /// `/read` with something other than a number from 0 to 9.
214
    Unclear,
215
}
216
217
/// How a prompt asks to read a reply again: as a command, or as the
218
/// plugin's skill is named, typed or picked from the assistant's list: agy
219
/// names it `/super-voice:read`, and Codex `$super-voice:read`.
220
const READ_COMMANDS: [&str; 4] = ["/read", "/super-voice:read", "$read", "$super-voice:read"];
221
222
/// What `prompt` asks, when it is one of [`READ_COMMANDS`], alone or with
223
/// what follows it after a space.
224
26
fn read_request(prompt: &str) -> Option<ReadRequest> {
225
26
    let prompt = prompt.trim();
226
26
    let rest = READ_COMMANDS
227
26
        .iter()
228
66
        .find_map(|command| prompt.strip_prefix(command))
?10
;
229
16
    if !rest.is_empty() && 
!rest.starts_with(char::is_whitespace)12
{
230
2
        return None;
231
14
    }
232
14
    let rest = rest.trim();
233
14
    Some(match rest.parse::<usize>() {
234
14
        _ if rest.is_empty() => 
ReadRequest::Last4
,
235
8
        Ok(back) if rest.len() == 1 => 
ReadRequest::Back(back)6
,
236
4
        _ => ReadRequest::Unclear,
237
    })
238
26
}
239
240
/// What `/read` takes.
241
const READ_USAGE: &str = "Read takes a number from 0, the last reply, to 9. Alone, it reads \
242
    the last reply, or stops the one being read.";
243
244
/// How long `/read` waits for its reply to start being read, so what keeps
245
/// it from being read is told at once. A long reply goes on being made after.
246
const READ_START: Duration = Duration::from_secs(2);
247
248
/// Read one of `who`'s kept replies aloud again, or stop the one it reads.
249
/// What to tell the user that it did, or why it could not.
250
5
async fn read_again(
251
5
    daemon: &Arc<SuperSTTDaemon>,
252
5
    who: &Who,
253
5
    request: ReadRequest,
254
5
) -> Result<String, String> {
255
5
    let back = match request {
256
1
        ReadRequest::Unclear => return Err(READ_USAGE.to_string()),
257
1
        ReadRequest::Last if is_speaking(daemon, who) => {
258
0
            stop(daemon, who).await;
259
0
            return Ok("Stopped reading.".to_string());
260
        }
261
1
        ReadRequest::Last => 0,
262
3
        ReadRequest::Back(back) => back,
263
    };
264
4
    let reply = match daemon.assistants.sessions.reply(who, back) {
265
1
        Ok(reply) => reply,
266
1
        Err(0) => return Err("There is no reply to read yet.".to_string()),
267
0
        Err(1) => return Err("There is only one reply to read: 0.".to_string()),
268
        Err(count) => {
269
2
            return Err(format!(
270
2
                "There are {count} replies to read: 0 to {}.",
271
2
                count - 1
272
2
            ));
273
        }
274
    };
275
1
    let mut spoken = start_speaking(daemon, who, reply);
276
1
    let started = match tokio::time::timeout(READ_START, &mut spoken).await {
277
1
        Ok(joined) => spoken_outcome(joined).map(|_| ()),
278
        // Still being made: it is read as it is.
279
0
        Err(_) => Ok(()),
280
    };
281
1
    started.map(|()| 
{0
282
0
        if back == 0 {
283
0
            "Reading the last reply aloud.".to_string()
284
        } else {
285
0
            format!("Reading reply {back} aloud.")
286
        }
287
0
    })
288
5
}
289
290
/// The answer to a `/read` prompt, which the assistant never sees: for a
291
/// Codex hook, the prompt blocked with what was done, or why not, as the
292
/// reason; for a plugin, that as what answered it, and whether it `failed`,
293
/// so a plugin that can only show it as an error shows it only then.
294
8
fn read_answer(hook: Option<Hook>, outcome: Result<String, String>) -> String {
295
8
    let failed = outcome.is_err();
296
8
    let said = outcome.unwrap_or_else(|error| error);
297
8
    match hook {
298
2
        Some(Hook::Codex) => serde_json::json!({ "decision": "block", "reason": said }),
299
6
        None => serde_json::json!({ "spoken": false, "answered": said, "failed": failed }),
300
    }
301
    .to_string()
302
8
}
303
304
5
async fn speak(
305
5
    daemon: &Arc<SuperSTTDaemon>,
306
5
    who: &Who,
307
5
    text: String,
308
5
    cancel: &CancellationToken,
309
5
) -> Option<Result<String, String>> {
310
5
    let mut spoken = start_speaking(daemon, who, text);
311
5
    tokio::select! {
312
        biased;
313
        // The utterance is the session's from its start: a newer one of the
314
        // session's may have started by now, and stays the one recorded.
315
5
        joined = &mut spoken => Some(spoken_outcome(joined).map(|_| 
"Speaking."0
.to_string())),
316
        // The speech goes on: it is on a task of its own.
317
5
        () = cancel.cancelled() => 
None0
,
318
    }
319
5
}
320
321
/// The model's `speak`: said once `who`'s own speech has ended, not over it,
322
/// as `speak` answers as soon as the speech starts. Stopped meanwhile, it is
323
/// not said at all.
324
4
async fn speak_in_turn(
325
4
    daemon: &Arc<SuperSTTDaemon>,
326
4
    who: &Who,
327
4
    text: String,
328
4
    cancel: &CancellationToken,
329
4
) -> Option<Result<String, String>> {
330
4
    if !turn_to_speak(daemon, who, cancel).await
?0
{
331
1
        return Some(Ok(NOT_SAID_STOPPED.to_string()));
332
3
    }
333
3
    speak(daemon, who, text, cancel).await
334
4
}
335
336
/// The reply to `call`'s turn, kept, and read aloud when the turn was
337
/// spoken. Read once the session's own speech has ended, like the model's
338
/// `speak`: a turn can end while the reply to the one before is still read,
339
/// as when a background task's end starts one. Stopped meanwhile, it is not
340
/// read.
341
5
async fn read_reply(
342
5
    daemon: &Arc<SuperSTTDaemon>,
343
5
    call: &CallContext,
344
5
    text: String,
345
5
    cancel: &CancellationToken,
346
5
) -> Option<Result<String, String>> {
347
5
    let who = &call.who;
348
5
    let sessions = &daemon.assistants.sessions;
349
5
    sessions.replied(who, &text);
350
5
    let mut read = sessions.spoken(who) == Some(true) && 
!text.trim().is_empty()2
;
351
5
    if read {
352
2
        read = turn_to_speak(daemon, who, cancel).await
?0
;
353
3
    }
354
5
    if read {
355
1
        match speak(daemon, who, text, cancel).await {
356
0
            Some(Ok(_)) => {}
357
1
            other => return other,
358
        }
359
4
    }
360
4
    Some(Ok(for_caller(
361
4
        call,
362
4
        serde_json::json!({ "read": read }).to_string(),
363
4
    )))
364
5
}
365
366
/// Wait for `who`'s turn to speak: its own speech has ended. `false` when
367
/// the user stopped that speech meanwhile, which asks for quiet, so what
368
/// waited is not said; `None` when the call was cancelled first.
369
6
async fn turn_to_speak(
370
6
    daemon: &SuperSTTDaemon,
371
6
    who: &Who,
372
6
    cancel: &CancellationToken,
373
6
) -> Option<bool> {
374
6
    let sessions = &daemon.assistants.sessions;
375
6
    let stops = sessions.stops(who);
376
6
    if !own_speech_ended(daemon, who, cancel).await {
377
0
        return None;
378
6
    }
379
6
    Some(sessions.stops(who) == stops)
380
6
}
381
382
/// Stop `who`'s own speech, if it still plays, and end its own recording,
383
/// which is transcribed all the same. Another session's are left alone.
384
6
async fn stop(daemon: &SuperSTTDaemon, who: &Who) -> String {
385
6
    let sessions = &daemon.assistants.sessions;
386
6
    let mut stopped = Vec::new();
387
    // Its speech still waiting for the model, or still being made, is called
388
    // off; what of it already plays is silenced.
389
    // Each stop is counted before the speech ends, so a speech of the
390
    // session's waiting its turn sees why it ended.
391
6
    let making = sessions.speaking(who);
392
6
    if let Some(task) = &making {
393
3
        sessions.speech_stopped(who);
394
3
        task.abort();
395
3
    }
396
6
    let playing = sessions
397
6
        .utterance(who)
398
1
        .filter(|utterance| is_playing(daemon, utterance));
399
6
    if let Some(utterance) = &playing {
400
0
        sessions.speech_stopped(who);
401
0
        silence_if_speaking(daemon, utterance).await;
402
6
    }
403
6
    if making.is_some() || 
playing.is_some()3
{
404
3
        stopped.push("speech");
405
3
    }
406
6
    if sessions.is_recording(who)
407
0
        && matches!(
408
0
            daemon.recording.stop(),
409
            Stopped::Signalled | Stopped::Cancelled
410
        )
411
    {
412
0
        stopped.push("recording");
413
6
    }
414
6
    if stopped.is_empty() {
415
3
        "Nothing of this session's was playing or recording.".to_string()
416
    } else {
417
3
        format!("Stopped its {}.", stopped.join(" and "))
418
    }
419
6
}
420
421
/// Whether `utterance` is the speech playing.
422
1
fn is_playing(daemon: &SuperSTTDaemon, utterance: &str) -> bool {
423
1
    daemon.tts.speech.current().as_deref() == Some(utterance)
424
1
}
425
426
/// Whether `who`'s own speech plays, or is on its way: waiting for the
427
/// model, or being made.
428
37
fn is_speaking(daemon: &SuperSTTDaemon, who: &Who) -> bool {
429
37
    let sessions = &daemon.assistants.sessions;
430
37
    sessions.speaking(who).is_some()
431
18
        || sessions
432
18
            .utterance(who)
433
0
            .is_some_and(|utterance| is_playing(daemon, &utterance))
434
37
}
435
436
/// Wait until `who`'s own speech has ended: waited for the model, been made,
437
/// and played. `false` when the call was cancelled first.
438
11
async fn own_speech_ended(daemon: &SuperSTTDaemon, who: &Who, cancel: &CancellationToken) -> bool {
439
    // Before looking, so the speech's end is never missed.
440
11
    let mut states = daemon.events.subscribe(Topic::SpeakingState);
441
11
    let mut listening = true;
442
28
    while is_speaking(daemon, who) {
443
18
        tokio::select! {
444
            biased;
445
18
            () = cancel.cancelled() => 
return false1
,
446
            // Speech started or stopped: look again.
447
18
            changed = states.recv_json_str(), if listening => {
448
0
                if matches!(changed, Err(tokio::sync::broadcast::error::RecvError::Closed)) {
449
0
                    listening = false;
450
0
                }
451
            }
452
18
            () = tokio::time::sleep(TICK) => {}
453
        }
454
    }
455
10
    true
456
11
}
457
458
/// Whether `who`'s own speech plays and whether it records; whether the user
459
/// shows its plugin's Talk, and lets it send a prompt dictated into it by
460
/// itself; as JSON.
461
5
fn status(daemon: &SuperSTTDaemon, who: &Who, call: &CallContext) -> String {
462
5
    serde_json::json!({
463
5
        "speaking": is_speaking(daemon, who),
464
5
        "listening": daemon.assistants.sessions.is_recording(who),
465
5
        "talk": call.shows_talk,
466
5
        "autosend": call.autosends,
467
5
    })
468
5
    .to_string()
469
5
}
470
471
/// `text` spoken on a task of its own, so it is never dropped midway: a
472
/// speech dropped while it is produced stops speaking. The task is `who`'s
473
/// from the moment it is asked for, and its utterance from the moment it
474
/// starts, so `who`'s `stop` finds the speech while it waits for the model
475
/// and while the rest of a long text is still being made.
476
7
fn start_speaking(
477
7
    daemon: &Arc<SuperSTTDaemon>,
478
7
    who: &Who,
479
7
    text: String,
480
7
) -> JoinHandle<SpeechResponse> {
481
7
    let tts = daemon.tts.clone();
482
7
    let owner = Arc::clone(daemon);
483
7
    let speaker = who.clone();
484
7
    let task = tokio::spawn(async move {
485
7
        tts.handle_speak_noting(text, move |utterance| 
{0
486
0
            owner
487
0
                .assistants
488
0
                .sessions
489
0
                .spoke(&speaker, utterance.to_string());
490
0
        })
491
7
        .await
492
7
    });
493
7
    daemon
494
7
        .assistants
495
7
        .sessions
496
7
        .asked_to_speak(who, task.abort_handle());
497
7
    task
498
7
}
499
500
/// The utterance a finished speech is speaking, or what the model is told
501
/// when it could not speak. A speech stopped before it played has none.
502
9
fn spoken_outcome(joined: Result<SpeechResponse, JoinError>) -> Result<Option<String>, String> {
503
9
    let response = match joined {
504
7
        Ok(response) => response,
505
        // Stopped before anything of it played: nothing of it is playing.
506
2
        Err(e) if e.is_cancelled() => return Ok(None),
507
0
        Err(e) => return Err(format!("Super Voice could not speak: {e}")),
508
    };
509
7
    if response.status == "success" {
510
0
        return Ok(response.utterance_id);
511
7
    }
512
7
    Err(match response.error_code {
513
        Some(SpeechErrorCode::ModelNotLoaded) => {
514
7
            "Super Voice has no text to speech model loaded. The user can choose one in the \
515
7
             Super Voice app."
516
7
                .to_string()
517
        }
518
        Some(SpeechErrorCode::RecordingInProgress) => {
519
0
            "Super Voice is recording the user, so it cannot speak until the recording ends."
520
0
                .to_string()
521
        }
522
        Some(SpeechErrorCode::VoiceRequired) => {
523
0
            "The text to speech model speaks only in a voice the user chooses, and none is \
524
0
             chosen. The user can choose one in the Super Voice app."
525
0
                .to_string()
526
        }
527
0
        _ => response
528
0
            .message
529
0
            .unwrap_or_else(|| "Super Voice could not speak.".to_string()),
530
    })
531
9
}
532
533
/// How asking the question went.
534
enum Asked {
535
    /// It was spoken, and has finished.
536
    Done,
537
    Failed(String),
538
    Cancelled,
539
}
540
541
/// What a `listen` take is heard with besides the user's own context: the
542
/// conversation's, with the question it answers at the front of its prompt.
543
/// Nothing when the user turned the conversation's context off for the
544
/// assistant.
545
9
fn take_context(
546
9
    question: Option<&str>,
547
9
    context: Option<ExtraContext>,
548
9
    uses_context: bool,
549
9
) -> Option<ExtraContext> {
550
9
    if !uses_context {
551
1
        return None;
552
8
    }
553
8
    let mut context = context.unwrap_or_default();
554
8
    if let Some(question) = question.map(str::trim).filter(|q| !
q.is_empty()3
) {
555
3
        let answering = format!("The user is answering: {question}");
556
3
        let prompt = context.prompt.trim();
557
3
        context.prompt = if prompt.is_empty() {
558
2
            answering
559
        } else {
560
1
            format!("{answering}\n{prompt}")
561
        };
562
5
    }
563
8
    (!context.is_empty()).then_some(context)
564
9
}
565
566
5
async fn listen(
567
5
    daemon: &Arc<SuperSTTDaemon>,
568
5
    who: &Who,
569
5
    question: Option<String>,
570
5
    extra: Option<ExtraContext>,
571
5
    cancel: &CancellationToken,
572
5
) -> Option<Result<String, String>> {
573
5
    if let Some(question) = question {
574
1
        match ask(daemon, who, question, cancel).await {
575
0
            Asked::Done => {}
576
1
            Asked::Failed(e) => return Some(Err(e)),
577
0
            Asked::Cancelled => return None,
578
        }
579
4
    }
580
4
    if cancel.is_cancelled() {
581
1
        return None;
582
3
    }
583
    // Never the toggling `record` command: that would stop someone else's
584
    // recording. This one reserves the microphone or is refused.
585
3
    let _recording = daemon.assistants.sessions.recording(who);
586
3
    let mut typer = Typer::without_keyboard();
587
3
    let take = daemon.handle_record_internal(
588
3
        &mut typer,
589
3
        false,
590
3
        TakeSettings {
591
3
            // Ends when the user stops talking, and their shortcut still
592
3
            // stops it early.
593
3
            stop_mode: RecordingStopMode::SilenceAndManual,
594
3
            preview_typing: false,
595
3
            cue_theme: daemon.get_audio_theme(),
596
3
            context: extra,
597
3
        },
598
3
        None,
599
3
    );
600
3
    let mut take = std::pin::pin!(take);
601
3
    let response = tokio::select! {
602
        biased;
603
3
        response = &mut take => response,
604
3
        () = cancel.cancelled() => {
605
            // Cancels it while it is starting; stops its capture after. The
606
            // take is finished, never dropped, so the microphone is freed as
607
            // at any other stop.
608
0
            let _ = daemon.recording.stop();
609
0
            let _ = take.await;
610
0
            return None;
611
        }
612
    };
613
3
    Some(heard(response))
614
5
}
615
616
/// What the user said, or what the model is told when nothing was recorded.
617
6
fn heard(response: DaemonResponse) -> Result<String, String> {
618
6
    if response.status == "success" {
619
2
        return Ok(response
620
2
            .transcription
621
2
            .filter(|text| !text.trim().is_empty())
622
1
            .unwrap_or_else(|| "(no speech detected)".to_string()));
623
4
    }
624
4
    Err(match response.error_code {
625
        Some(ErrorCode::ModelNotLoaded) => {
626
3
            "Super Voice has no speech to text model loaded. The user can choose one in the \
627
3
             Super Voice app."
628
3
                .to_string()
629
        }
630
        Some(ErrorCode::RecordingInProgress) => {
631
1
            "Super Voice is already recording. Try again once that recording ends.".to_string()
632
        }
633
0
        _ => response
634
0
            .message
635
0
            .unwrap_or_else(|| "Super Voice could not record.".to_string()),
636
    })
637
6
}
638
639
/// Speak `question`, and wait for it to finish playing, so the recording
640
/// after it hears the answer and not the question.
641
1
async fn ask(
642
1
    daemon: &Arc<SuperSTTDaemon>,
643
1
    who: &Who,
644
1
    question: String,
645
1
    cancel: &CancellationToken,
646
1
) -> Asked {
647
    // Before speaking, so the question's end is never missed.
648
1
    let mut states = daemon.events.subscribe(Topic::SpeakingState);
649
1
    let mut spoken = start_speaking(daemon, who, question);
650
1
    let utterance = tokio::select! {
651
        biased;
652
1
        joined = &mut spoken => match spoken_outcome(joined) {
653
0
            Ok(utterance) => utterance,
654
1
            Err(e) => return Asked::Failed(e),
655
        },
656
1
        () = cancel.cancelled() => {
657
0
            call_off(daemon, spoken).await;
658
0
            return Asked::Cancelled;
659
        }
660
    };
661
    // A question a newer speech overtook was never spoken, and has no
662
    // utterance of its own playing.
663
0
    let Some(utterance) = utterance else {
664
0
        return Asked::Done;
665
    };
666
0
    let mut listening = true;
667
    loop {
668
0
        if !is_playing(daemon, &utterance) {
669
0
            return Asked::Done;
670
0
        }
671
0
        tokio::select! {
672
            biased;
673
0
            () = cancel.cancelled() => {
674
0
                silence_if_speaking(daemon, &utterance).await;
675
0
                return Asked::Cancelled;
676
            }
677
            // Speech started or stopped: look again.
678
0
            changed = states.recv_json_str(), if listening => {
679
0
                if matches!(changed, Err(tokio::sync::broadcast::error::RecvError::Closed)) {
680
0
                    listening = false;
681
0
                }
682
            }
683
0
            () = tokio::time::sleep(TICK) => {}
684
        }
685
    }
686
1
}
687
688
/// Stop `utterance`, if it is still the one speaking. Speech the user or
689
/// another client started since is left alone.
690
0
async fn silence_if_speaking(daemon: &SuperSTTDaemon, utterance: &str) {
691
0
    if is_playing(daemon, utterance) {
692
0
        let _ = daemon.tts.stop_speaking().await;
693
0
    }
694
0
}
695
696
/// Call off the question `spoken` is asking: the call asking it was
697
/// cancelled. Still waiting for the model or being made, the question never
698
/// plays, and what of it was made stops; made already, it is silenced if it
699
/// still plays.
700
1
async fn call_off(daemon: &SuperSTTDaemon, spoken: JoinHandle<SpeechResponse>) {
701
1
    spoken.abort();
702
1
    if let Ok(Some(utterance)) = spoken_outcome(spoken.await) {
703
0
        silence_if_speaking(daemon, &utterance).await;
704
1
    }
705
1
}
706
707
#[cfg(test)]
708
mod tests {
709
    use super::*;
710
    use crate::assistants::calls::Caller;
711
    use crate::assistants::sessions::Named;
712
    use crate::daemon::types::test_daemon;
713
714
45
    fn call() -> CallContext {
715
45
        CallContext {
716
45
            who: Who {
717
45
                caller: Caller::Key("k".to_string()),
718
45
                named: Named::default(),
719
45
                connection: None,
720
45
            },
721
45
            announces: true,
722
45
            uses_context: true,
723
45
            shows_talk: true,
724
45
            autosends: true,
725
45
            hook: None,
726
45
        }
727
45
    }
728
729
    /// A take is heard with the conversation's context and the question it
730
    /// answers, unless the user turned the conversation's context off.
731
    #[test]
732
1
    fn a_take_is_heard_with_its_conversation() {
733
2
        let context = || {
734
2
            Some(ExtraContext {
735
2
                prompt: "About the release.".to_string(),
736
2
                vocabulary: vec!["agy".to_string()],
737
2
            })
738
2
        };
739
1
        let heard = take_context(Some("Which one? "), context(), true).expect("a context");
740
1
        assert_eq!(
741
1
            heard.prompt,
742
1
            "The user is answering: Which one?\nAbout the release."
743
        );
744
1
        assert_eq!(heard.vocabulary, ["agy"]);
745
1
        let asked = take_context(Some("Which one?"), None, true).expect("the question");
746
1
        assert_eq!(asked.prompt, "The user is answering: Which one?");
747
1
        assert_eq!(take_context(None, None, true), None);
748
1
        assert_eq!(take_context(Some("Which one?"), context(), false), None);
749
1
    }
750
751
    #[tokio::test]
752
1
    async fn listen_with_no_model_says_so_and_records_nothing() {
753
1
        let daemon = Arc::new(test_daemon().await);
754
1
        let outcome = run(
755
1
            &daemon,
756
1
            Tool::Listen {
757
1
                question: None,
758
1
                context: None,
759
1
                asked: false,
760
1
            },
761
1
            &call(),
762
1
            &CancellationToken::new(),
763
1
        )
764
1
        .await;
765
1
        let Some(Err(text)) = outcome else {
766
0
            panic!("expected an error, got {outcome:?}");
767
        };
768
1
        assert!(text.contains("speech to text model"), "{text}");
769
1
        assert!(!daemon.recording.is_busy());
770
1
    }
771
772
    #[tokio::test]
773
1
    async fn speak_with_no_model_is_an_error() {
774
1
        let daemon = Arc::new(test_daemon().await);
775
1
        let outcome = run(
776
1
            &daemon,
777
1
            Tool::Speak {
778
1
                text: "Hello.".to_string(),
779
1
                asked: false,
780
1
            },
781
1
            &call(),
782
1
            &CancellationToken::new(),
783
1
        )
784
1
        .await;
785
1
        assert!(matches!(outcome, Some(Err(_))), "{outcome:?}");
786
1
    }
787
788
    /// A call cancelled before it records answers nothing, and never opens
789
    /// the microphone.
790
    #[tokio::test]
791
1
    async fn a_cancelled_listen_answers_nothing() {
792
1
        let daemon = Arc::new(test_daemon().await);
793
1
        let cancel = CancellationToken::new();
794
1
        cancel.cancel();
795
1
        let outcome = run(
796
1
            &daemon,
797
1
            Tool::Listen {
798
1
                question: None,
799
1
                context: None,
800
1
                asked: false,
801
1
            },
802
1
            &call(),
803
1
            &cancel,
804
1
        )
805
1
        .await;
806
1
        assert_eq!(outcome, None);
807
1
        assert!(!daemon.recording.is_busy());
808
1
    }
809
810
    /// `stop` and `status` see only the caller's own speech and recording.
811
    #[tokio::test]
812
1
    async fn stop_and_status_see_only_the_callers_own() {
813
1
        let daemon = Arc::new(test_daemon().await);
814
1
        let mine = call();
815
1
        let cancel = CancellationToken::new();
816
1
        let Some(Ok(status)) = run(&daemon, Tool::Status, &mine, &cancel).await else {
817
0
            panic!("status answers");
818
        };
819
1
        assert_eq!(
820
1
            serde_json::from_str::<serde_json::Value>(&status).expect("JSON"),
821
1
            serde_json::json!({
822
1
                "speaking": false,
823
1
                "listening": false,
824
1
                "talk": true,
825
1
                "autosend": true,
826
            })
827
        );
828
        // An utterance of its own that is not the one playing is not stopped.
829
1
        daemon
830
1
            .assistants
831
1
            .sessions
832
1
            .spoke(&mine.who, "utt_gone".to_string());
833
1
        let stopped = run(&daemon, Tool::Stop, &mine, &cancel).await;
834
1
        assert_eq!(
835
1
            stopped,
836
1
            Some(Ok(
837
1
                "Nothing of this session's was playing or recording.".to_string()
838
1
            ))
839
1
        );
840
1
    }
841
842
    /// A session's speech is its own from the moment it is asked for:
843
    /// `status` and `stop` see it while it still waits for the model.
844
    #[tokio::test]
845
1
    async fn stop_reaches_speech_still_waiting_to_start() {
846
1
        let daemon = Arc::new(test_daemon().await);
847
1
        let mine = call();
848
1
        let waiting = tokio::spawn(std::future::pending::<SpeechResponse>());
849
1
        daemon
850
1
            .assistants
851
1
            .sessions
852
1
            .asked_to_speak(&mine.who, waiting.abort_handle());
853
1
        assert!(is_speaking(&daemon, &mine.who));
854
1
        assert!(!is_speaking(
855
1
            &daemon,
856
1
            &Who {
857
1
                named: Named {
858
1
                    id: Some("other".into()),
859
1
                    ..Named::default()
860
1
                },
861
1
                ..call().who
862
1
            }
863
1
        ));
864
865
1
        assert_eq!(stop(&daemon, &mine.who).await, "Stopped its speech.");
866
1
        let joined = waiting.await;
867
1
        assert!(joined.as_ref().is_err_and(JoinError::is_cancelled));
868
1
        assert_eq!(
869
1
            spoken_outcome(joined),
870
1
            Ok(None),
871
            "a stopped speech has nothing playing"
872
        );
873
1
        assert!(!is_speaking(&daemon, &mine.who));
874
1
        assert_eq!(
875
1
            stop(&daemon, &mine.who).await,
876
1
            "Nothing of this session's was playing or recording."
877
1
        );
878
1
    }
879
880
    /// The model's `listen` lets the session's own speech finish first, so
881
    /// its question or recording never cuts off what the model just said.
882
    #[tokio::test]
883
1
    async fn a_models_listen_waits_for_its_own_speech() {
884
1
        let daemon = Arc::new(test_daemon().await);
885
1
        let mine = call();
886
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
887
1
        daemon
888
1
            .assistants
889
1
            .sessions
890
1
            .asked_to_speak(&mine.who, speech.abort_handle());
891
1
        let listening = tokio::spawn({
892
1
            let daemon = Arc::clone(&daemon);
893
1
            async move {
894
1
                run(
895
1
                    &daemon,
896
1
                    Tool::Listen {
897
1
                        question: Some("Did you hear it?".to_string()),
898
1
                        context: None,
899
1
                        asked: false,
900
1
                    },
901
1
                    &call(),
902
1
                    &CancellationToken::new(),
903
1
                )
904
1
                .await
905
1
            }
906
        });
907
1
        tokio::time::sleep(TICK * 3).await;
908
1
        assert!(!listening.is_finished(), "it waits while the speech plays");
909
910
1
        speech.abort();
911
1
        let outcome = tokio::time::timeout(Duration::from_secs(5), listening)
912
1
            .await
913
1
            .expect("it goes on once the speech ends")
914
1
            .expect("the call runs to its end");
915
1
        assert!(matches!(outcome, Some(Err(_))), "{outcome:?}");
916
1
    }
917
918
    /// The user's own `listen`, as Talk asks for it, records at once: the
919
    /// user means to talk over the speech.
920
    #[tokio::test]
921
1
    async fn a_listen_the_user_asked_for_does_not_wait() {
922
1
        let daemon = Arc::new(test_daemon().await);
923
1
        let mine = call();
924
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
925
1
        daemon
926
1
            .assistants
927
1
            .sessions
928
1
            .asked_to_speak(&mine.who, speech.abort_handle());
929
1
        let outcome = tokio::time::timeout(
930
1
            Duration::from_secs(5),
931
1
            run(
932
1
                &daemon,
933
1
                Tool::Listen {
934
1
                    question: None,
935
1
                    context: None,
936
1
                    asked: true,
937
1
                },
938
1
                &mine,
939
1
                &CancellationToken::new(),
940
1
            ),
941
1
        )
942
1
        .await
943
1
        .expect("it does not wait for the speech");
944
1
        let Some(Err(text)) = outcome else {
945
0
            panic!("expected an error, got {outcome:?}");
946
        };
947
1
        assert!(text.contains("speech to text model"), "{text}");
948
1
        speech.abort();
949
1
    }
950
951
    /// A model's `listen` cancelled while it waits for the session's speech
952
    /// answers nothing, and never asks or records.
953
    #[tokio::test]
954
1
    async fn a_listen_cancelled_while_it_waits_answers_nothing() {
955
1
        let daemon = Arc::new(test_daemon().await);
956
1
        let mine = call();
957
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
958
1
        daemon
959
1
            .assistants
960
1
            .sessions
961
1
            .asked_to_speak(&mine.who, speech.abort_handle());
962
1
        let cancel = CancellationToken::new();
963
1
        let listening = tokio::spawn({
964
1
            let daemon = Arc::clone(&daemon);
965
1
            let cancel = cancel.clone();
966
1
            async move {
967
1
                run(
968
1
                    &daemon,
969
1
                    Tool::Listen {
970
1
                        question: None,
971
1
                        context: None,
972
1
                        asked: false,
973
1
                    },
974
1
                    &call(),
975
1
                    &cancel,
976
1
                )
977
1
                .await
978
1
            }
979
        });
980
1
        tokio::time::sleep(TICK * 3).await;
981
1
        cancel.cancel();
982
1
        let outcome = tokio::time::timeout(Duration::from_secs(5), listening)
983
1
            .await
984
1
            .expect("the cancel ends the wait")
985
1
            .expect("the call runs to its end");
986
1
        assert_eq!(outcome, None);
987
1
        assert!(!daemon.recording.is_busy());
988
1
        speech.abort();
989
1
    }
990
991
    /// The model's `speak` lets the session's own speech finish first, so
992
    /// two in a row are both heard, in order.
993
    #[tokio::test]
994
1
    async fn a_models_speak_waits_for_its_own_speech() {
995
1
        let daemon = Arc::new(test_daemon().await);
996
1
        let mine = call();
997
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
998
1
        daemon
999
1
            .assistants
1000
1
            .sessions
1001
1
            .asked_to_speak(&mine.who, speech.abort_handle());
1002
1
        let speaking = tokio::spawn({
1003
1
            let daemon = Arc::clone(&daemon);
1004
1
            async move {
1005
1
                run(
1006
1
                    &daemon,
1007
1
                    Tool::Speak {
1008
1
                        text: "And then this.".to_string(),
1009
1
                        asked: false,
1010
1
                    },
1011
1
                    &call(),
1012
1
                    &CancellationToken::new(),
1013
1
                )
1014
1
                .await
1015
1
            }
1016
        });
1017
1
        tokio::time::sleep(TICK * 3).await;
1018
1
        assert!(!speaking.is_finished(), "it waits while the speech plays");
1019
1020
1
        speech.abort();
1021
1
        let outcome = tokio::time::timeout(Duration::from_secs(5), speaking)
1022
1
            .await
1023
1
            .expect("it goes on once the speech ends")
1024
1
            .expect("the call runs to its end");
1025
        // There is no model to speak with: it tried.
1026
1
        assert!(matches!(outcome, Some(Err(_))), "{outcome:?}");
1027
1
    }
1028
1029
    /// What the user asked to hear, like a reply read again, speaks at once.
1030
    #[tokio::test]
1031
1
    async fn a_speak_the_user_asked_for_does_not_wait() {
1032
1
        let daemon = Arc::new(test_daemon().await);
1033
1
        let mine = call();
1034
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
1035
1
        daemon
1036
1
            .assistants
1037
1
            .sessions
1038
1
            .asked_to_speak(&mine.who, speech.abort_handle());
1039
1
        let outcome = tokio::time::timeout(
1040
1
            Duration::from_secs(5),
1041
1
            run(
1042
1
                &daemon,
1043
1
                Tool::Speak {
1044
1
                    text: "Read again.".to_string(),
1045
1
                    asked: true,
1046
1
                },
1047
1
                &mine,
1048
1
                &CancellationToken::new(),
1049
1
            ),
1050
1
        )
1051
1
        .await
1052
1
        .expect("it does not wait for the speech");
1053
1
        assert!(matches!(outcome, Some(Err(_))), "{outcome:?}");
1054
1
        speech.abort();
1055
1
    }
1056
1057
    /// A `speak` waiting its turn when the user stops the session's speech is
1058
    /// not said: the user asked for quiet.
1059
    #[tokio::test]
1060
1
    async fn a_waiting_speak_is_not_said_once_the_user_stops() {
1061
1
        let daemon = Arc::new(test_daemon().await);
1062
1
        let mine = call();
1063
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
1064
1
        daemon
1065
1
            .assistants
1066
1
            .sessions
1067
1
            .asked_to_speak(&mine.who, speech.abort_handle());
1068
1
        let speaking = tokio::spawn({
1069
1
            let daemon = Arc::clone(&daemon);
1070
1
            async move {
1071
1
                run(
1072
1
                    &daemon,
1073
1
                    Tool::Speak {
1074
1
                        text: "And then this.".to_string(),
1075
1
                        asked: false,
1076
1
                    },
1077
1
                    &call(),
1078
1
                    &CancellationToken::new(),
1079
1
                )
1080
1
                .await
1081
1
            }
1082
        });
1083
1
        tokio::time::sleep(TICK * 3).await;
1084
1
        assert_eq!(stop(&daemon, &mine.who).await, "Stopped its speech.");
1085
1
        let outcome = tokio::time::timeout(Duration::from_secs(5), speaking)
1086
1
            .await
1087
1
            .expect("the stop ends the wait")
1088
1
            .expect("the call runs to its end");
1089
        // Ok, not the missing model's error: it never tried to speak.
1090
1
        assert_eq!(outcome, Some(Ok(NOT_SAID_STOPPED.to_string())));
1091
1
    }
1092
1093
    /// The reply to a turn waits for the session's own speech, like the
1094
    /// reply to the turn before, which a background task's turn can end
1095
    /// while it is still read. Stopped meanwhile, it is not read.
1096
    #[tokio::test]
1097
1
    async fn a_reply_waits_for_its_own_speech() {
1098
1
        let daemon = Arc::new(test_daemon().await);
1099
1
        let mine = call();
1100
1
        daemon.assistants.sessions.set_spoken(&mine.who, true);
1101
2
        let reply = || {
1102
2
            let daemon = Arc::clone(&daemon);
1103
2
            tokio::spawn(async move {
1104
2
                let reply = Tool::Turn(TurnEvent::Reply {
1105
2
                    text: "Done.".to_string(),
1106
2
                });
1107
2
                run(&daemon, reply, &call(), &CancellationToken::new()).await
1108
2
            })
1109
2
        };
1110
1111
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
1112
1
        daemon
1113
1
            .assistants
1114
1
            .sessions
1115
1
            .asked_to_speak(&mine.who, speech.abort_handle());
1116
1
        let reading = reply();
1117
1
        tokio::time::sleep(TICK * 3).await;
1118
1
        assert!(!reading.is_finished(), "it waits while the speech plays");
1119
1
        speech.abort();
1120
1
        let outcome = tokio::time::timeout(Duration::from_secs(5), reading)
1121
1
            .await
1122
1
            .expect("it goes on once the speech ends")
1123
1
            .expect("the call runs to its end");
1124
        // There is no model to speak with: it tried.
1125
1
        assert!(matches!(outcome, Some(Err(_))), "{outcome:?}");
1126
1127
1
        let speech = tokio::spawn(std::future::pending::<SpeechResponse>());
1128
1
        daemon
1129
1
            .assistants
1130
1
            .sessions
1131
1
            .asked_to_speak(&mine.who, speech.abort_handle());
1132
1
        let reading = reply();
1133
1
        tokio::time::sleep(TICK * 3).await;
1134
1
        assert_eq!(stop(&daemon, &mine.who).await, "Stopped its speech.");
1135
1
        let outcome = tokio::time::timeout(Duration::from_secs(5), reading)
1136
1
            .await
1137
1
            .expect("the stop ends the wait")
1138
1
            .expect("the call runs to its end");
1139
1
        assert_eq!(outcome, Some(Ok(r#"{"read":false}"#.to_string())));
1140
1
    }
1141
1142
    /// A question whose `listen` was cancelled while it waited for the model
1143
    /// is called off then, not left to play once the model is in.
1144
    #[tokio::test]
1145
1
    async fn a_cancelled_question_is_called_off_before_it_plays() {
1146
1
        let daemon = test_daemon().await;
1147
1
        let asking = tokio::spawn(std::future::pending::<SpeechResponse>());
1148
1
        let task = asking.abort_handle();
1149
1
        call_off(&daemon, asking).await;
1150
1
        assert!(task.is_finished(), "the question's task is called off");
1151
1
    }
1152
1153
    /// With announcing off, `announce` says nothing and says why.
1154
    #[tokio::test]
1155
1
    async fn announce_says_nothing_when_announcing_is_off() {
1156
1
        let daemon = Arc::new(test_daemon().await);
1157
1
        let quiet = CallContext {
1158
1
            announces: false,
1159
1
            ..call()
1160
1
        };
1161
1
        let outcome = run(
1162
1
            &daemon,
1163
1
            Tool::Announce {
1164
1
                text: "Claude needs your permission.".to_string(),
1165
1
            },
1166
1
            &quiet,
1167
1
            &CancellationToken::new(),
1168
1
        )
1169
1
        .await;
1170
1
        let Some(Ok(text)) = outcome else {
1171
0
            panic!("expected an answer, got {outcome:?}");
1172
        };
1173
1
        assert!(text.contains("turned announcing off"), "{text}");
1174
1
        assert!(daemon.tts.speech.current().is_none());
1175
1
    }
1176
1177
    /// A session opens and closes on its plugin's word.
1178
    #[tokio::test]
1179
1
    async fn a_session_opens_and_closes() {
1180
1
        let daemon = Arc::new(test_daemon().await);
1181
1
        let cancel = CancellationToken::new();
1182
1
        run(
1183
1
            &daemon,
1184
1
            Tool::Session(SessionEvent::Start),
1185
1
            &call(),
1186
1
            &cancel,
1187
1
        )
1188
1
        .await;
1189
1
        assert_eq!(daemon.assistants.sessions.list().len(), 1);
1190
1
        run(&daemon, Tool::Session(SessionEvent::End), &call(), &cancel).await;
1191
1
        assert!(daemon.assistants.sessions.list().is_empty());
1192
1
        run(&daemon, Tool::Session(SessionEvent::Seen), &call(), &cancel).await;
1193
1
        assert_eq!(daemon.assistants.sessions.list().len(), 1);
1194
1
    }
1195
1196
    /// A typed turn refuses speaking and listening; a spoken one, or one no
1197
    /// plugin has said anything of, does not. A prompt holding the user's
1198
    /// dictation is spoken.
1199
    #[tokio::test]
1200
1
    async fn a_typed_turn_is_answered_in_writing() {
1201
1
        let daemon = Arc::new(test_daemon().await);
1202
1
        let cancel = CancellationToken::new();
1203
3
        let prompt = |text: &str, spoken| {
1204
3
            Tool::Turn(TurnEvent::Prompt {
1205
3
                text: text.to_string(),
1206
3
                spoken,
1207
3
                heard: None,
1208
3
                again: false,
1209
3
            })
1210
3
        };
1211
1
        let typed = run(&daemon, prompt("Hi.", Some(false)), &call(), &cancel)
1212
1
            .await
1213
            .unwrap()
1214
            .unwrap();
1215
1
        assert_eq!(
1216
1
            serde_json::from_str::<serde_json::Value>(&typed).unwrap(),
1217
1
            serde_json::json!({ "spoken": false, "note": null })
1218
        );
1219
1
        let refused = run(
1220
1
            &daemon,
1221
1
            Tool::Speak {
1222
1
                text: "Hello.".to_string(),
1223
1
                asked: false,
1224
1
            },
1225
1
            &call(),
1226
1
            &cancel,
1227
1
        )
1228
1
        .await;
1229
1
        assert_eq!(refused, Some(Err(NOT_SPOKEN_TO.to_string())));
1230
1231
1
        daemon.assistants.dictation.remember("Open the notes");
1232
1
        let spoken = run(&daemon, prompt("open the notes.", None), &call(), &cancel)
1233
1
            .await
1234
            .unwrap()
1235
            .unwrap();
1236
1
        assert_eq!(
1237
1
            serde_json::from_str::<serde_json::Value>(&spoken).unwrap(),
1238
1
            serde_json::json!({ "spoken": true, "note": SPOKEN_NOTE })
1239
        );
1240
1
        assert_eq!(daemon.assistants.sessions.spoken(&call().who), Some(true));
1241
        // Said again before each model call, it stays spoken, and the note
1242
        // is added once.
1243
1
        let said_again = Tool::Turn(TurnEvent::Prompt {
1244
1
            text: "open the notes.".to_string(),
1245
1
            spoken: None,
1246
1
            heard: None,
1247
1
            again: true,
1248
1
        });
1249
1
        let again = run(&daemon, said_again, &call(), &cancel)
1250
1
            .await
1251
            .unwrap()
1252
            .unwrap();
1253
1
        assert_eq!(
1254
1
            serde_json::from_str::<serde_json::Value>(&again).unwrap(),
1255
1
            serde_json::json!({ "spoken": true, "note": null })
1256
        );
1257
        // The same words in a new turn are a new turn: typed, they are
1258
        // answered in writing.
1259
1
        let retyped = run(&daemon, prompt("open the notes.", None), &call(), &cancel)
1260
1
            .await
1261
            .unwrap()
1262
            .unwrap();
1263
1
        assert_eq!(
1264
1
            serde_json::from_str::<serde_json::Value>(&retyped).unwrap(),
1265
1
            serde_json::json!({ "spoken": false, "note": null })
1266
        );
1267
1268
        // What Talk put in the box is spoken, touched up by hand too; a
1269
        // prompt typed in its place is not.
1270
2
        let with_talk = |text: &str| {
1271
2
            Tool::Turn(TurnEvent::Prompt {
1272
2
                text: text.to_string(),
1273
2
                spoken: None,
1274
2
                heard: Some("Rename the super boys folder".to_string()),
1275
2
                again: false,
1276
2
            })
1277
2
        };
1278
1
        for (text, spoken) in [
1279
1
            ("Rename the super voice folder", true),
1280
1
            ("What does this function do?", false),
1281
1
        ] {
1282
2
            let answer = run(&daemon, with_talk(text), &call(), &cancel)
1283
2
                .await
1284
1
                .unwrap()
1285
1
                .unwrap();
1286
2
            let answer: serde_json::Value = serde_json::from_str(&answer).unwrap();
1287
2
            assert_eq!(answer["spoken"], spoken, "{text}");
1288
1
        }
1289
1
    }
1290
1291
    /// A draft that holds what the user just dictated is said to, once: the
1292
    /// match uses the dictation up. A draft changes no turn.
1293
    #[tokio::test]
1294
1
    async fn a_draft_holding_the_dictation_is_said_to_once() {
1295
1
        let daemon = Arc::new(test_daemon().await);
1296
1
        let cancel = CancellationToken::new();
1297
6
        let draft = async |text: &str| -> serde_json::Value {
1298
3
            let tool = Tool::Turn(TurnEvent::Draft {
1299
3
                text: text.to_string(),
1300
3
            });
1301
3
            let answer = run(&daemon, tool, &call(), &cancel).await.unwrap().unwrap();
1302
3
            serde_json::from_str(&answer).unwrap()
1303
6
        };
1304
1
        assert_eq!(
1305
1
            draft("Please open the notes.").await,
1306
1
            serde_json::json!({ "dictated": false })
1307
        );
1308
1
        daemon.assistants.dictation.remember("Open the notes");
1309
1
        assert_eq!(draft("Please open the notes.").await["dictated"], true);
1310
1
        assert_eq!(draft("Please open the notes.").await["dictated"], false);
1311
1
        assert_eq!(daemon.assistants.sessions.spoken(&call().who), None);
1312
1
    }
1313
1314
    /// A Codex hook reads the answer as its own output: the context beside a
1315
    /// spoken prompt, and nothing else.
1316
    #[tokio::test]
1317
1
    async fn a_hook_gets_its_own_output() {
1318
1
        let daemon = Arc::new(test_daemon().await);
1319
1
        let cancel = CancellationToken::new();
1320
1
        let hook = CallContext {
1321
1
            hook: Some(Hook::Codex),
1322
1
            ..call()
1323
1
        };
1324
2
        let prompt = |spoken| {
1325
2
            Tool::Turn(TurnEvent::Prompt {
1326
2
                text: "Hi.".to_string(),
1327
2
                spoken: Some(spoken),
1328
2
                heard: None,
1329
2
                again: false,
1330
2
            })
1331
2
        };
1332
1
        let spoken = run(&daemon, prompt(true), &hook, &cancel)
1333
1
            .await
1334
            .unwrap()
1335
            .unwrap();
1336
1
        let output: serde_json::Value = serde_json::from_str(&spoken).unwrap();
1337
1
        assert_eq!(
1338
1
            output["hookSpecificOutput"]["hookEventName"],
1339
1
            "UserPromptSubmit"
1340
        );
1341
1
        assert_eq!(
1342
1
            output["hookSpecificOutput"]["additionalContext"],
1343
1
            SPOKEN_NOTE
1344
        );
1345
1
        assert_eq!(
1346
1
            run(&daemon, prompt(false), &hook, &cancel).await,
1347
1
            Some(Ok(String::new()))
1348
        );
1349
        // A typed turn's reply is not read, and the hook hears nothing.
1350
1
        let reply = Tool::Turn(TurnEvent::Reply {
1351
1
            text: "Done.".to_string(),
1352
1
        });
1353
1
        assert_eq!(
1354
1
            run(&daemon, reply, &hook, &cancel).await,
1355
1
            Some(Ok(String::new()))
1356
        );
1357
1
        let seen = Tool::Session(SessionEvent::Seen);
1358
1
        assert_eq!(
1359
1
            run(&daemon, seen, &hook, &cancel).await,
1360
1
            Some(Ok(String::new()))
1361
1
        );
1362
1
    }
1363
1364
    /// `/read`, or `$read`, alone or with one digit; anything else after it
1365
    /// is unclear, and a prompt that only starts with the word is not one.
1366
    #[test]
1367
1
    fn read_asks_for_a_reply_by_how_far_back_it_is() {
1368
1
        assert_eq!(read_request(" /read "), Some(ReadRequest::Last));
1369
1
        assert_eq!(read_request("$read"), Some(ReadRequest::Last));
1370
1
        assert_eq!(read_request("/read 0"), Some(ReadRequest::Back(0)));
1371
1
        assert_eq!(read_request("$read  9\n"), Some(ReadRequest::Back(9)));
1372
1
        assert_eq!(
1373
1
            read_request("$super-voice:read 2"),
1374
1
            Some(ReadRequest::Back(2))
1375
        );
1376
1
        assert_eq!(read_request("/super-voice:read"), Some(ReadRequest::Last));
1377
1
        assert_eq!(read_request("/read 10"), Some(ReadRequest::Unclear));
1378
1
        assert_eq!(read_request("/read +1"), Some(ReadRequest::Unclear));
1379
1
        assert_eq!(read_request("/read the notes"), Some(ReadRequest::Unclear));
1380
1
        assert_eq!(read_request("/readme"), None);
1381
1
        assert_eq!(read_request("read 1"), None);
1382
1
        assert_eq!(read_request("Please /read 1"), None);
1383
1
    }
1384
1385
    /// A `/read` prompt is answered by Super Voice, as a typed turn the
1386
    /// assistant never sees: Codex's hook blocks it with the answer.
1387
    #[tokio::test]
1388
1
    async fn a_read_prompt_is_answered_without_the_assistant() {
1389
1
        let daemon = Arc::new(test_daemon().await);
1390
1
        let cancel = CancellationToken::new();
1391
1
        let codex = CallContext {
1392
1
            hook: Some(Hook::Codex),
1393
1
            ..call()
1394
1
        };
1395
12
        let ask = async |text: &str, call: &CallContext| {
1396
6
            let prompt = Tool::Turn(TurnEvent::Prompt {
1397
6
                text: text.to_string(),
1398
6
                spoken: None,
1399
6
                heard: None,
1400
6
                again: false,
1401
6
            });
1402
6
            let answer = run(&daemon, prompt, call, &cancel).await.unwrap().unwrap();
1403
6
            serde_json::from_str::<serde_json::Value>(&answer).unwrap()
1404
12
        };
1405
        let answered =
1406
3
            |said: &str| serde_json::json!({ "spoken": false, "answered": said, "failed": true });
1407
1408
1
        assert_eq!(
1409
1
            ask("/read", &call()).await,
1410
1
            answered("There is no reply to read yet.")
1411
        );
1412
1
        for text in ["First.", "Second."] {
1413
2
            let reply = Tool::Turn(TurnEvent::Reply {
1414
2
                text: text.to_string(),
1415
2
            });
1416
2
            run(&daemon, reply, &call(), &cancel).await;
1417
        }
1418
1
        assert_eq!(
1419
1
            ask("/read 5", &call()).await,
1420
1
            answered("There are 2 replies to read: 0 to 1.")
1421
        );
1422
1
        assert_eq!(ask("/read x", &call()).await, answered(READ_USAGE));
1423
        // The test daemon has no model to read it with.
1424
1
        let unread = ask("/read 1", &call()).await;
1425
1
        assert!(
1426
1
            unread["answered"]
1427
1
                .as_str()
1428
1
                .is_some_and(|said| said.contains("no text to speech model")),
1429
            "{unread}"
1430
        );
1431
1
        assert_eq!(unread["failed"], true);
1432
1
        assert_eq!(daemon.assistants.sessions.spoken(&call().who), Some(false));
1433
1434
1
        assert_eq!(
1435
1
            ask("$read 9", &codex).await,
1436
1
            serde_json::json!({
1437
1
                "decision": "block",
1438
1
                "reason": "There are 2 replies to read: 0 to 1.",
1439
            })
1440
        );
1441
        // A prompt that only starts like it goes to the assistant.
1442
1
        assert_eq!(
1443
1
            ask("/readme is out of date", &call()).await,
1444
1
            serde_json::json!({ "spoken": false, "note": null })
1445
1
        );
1446
1
    }
1447
1448
    /// A plugin learns whether `/read` did what was asked, or what kept it
1449
    /// from it; Codex, which shows the reason either way, is not told.
1450
    #[test]
1451
1
    fn a_read_answer_says_whether_it_failed() {
1452
3
        let answer = |hook, outcome| {
1453
3
            serde_json::from_str::<serde_json::Value>(&read_answer(hook, outcome)).unwrap()
1454
3
        };
1455
1
        assert_eq!(
1456
1
            answer(None, Ok("Stopped reading.".to_string())),
1457
1
            serde_json::json!({ "spoken": false, "answered": "Stopped reading.", "failed": false })
1458
        );
1459
1
        assert_eq!(answer(None, Err(READ_USAGE.to_string()))["failed"], true);
1460
1
        assert_eq!(
1461
1
            answer(Some(Hook::Codex), Ok("Reading reply 2 aloud.".to_string())),
1462
1
            serde_json::json!({ "decision": "block", "reason": "Reading reply 2 aloud." })
1463
        );
1464
1
    }
1465
1466
    #[test]
1467
1
    fn what_was_heard_is_the_text_or_says_there_was_none() {
1468
1
        let said = DaemonResponse::success().with_transcription("Yes.".to_string());
1469
1
        assert_eq!(heard(said), Ok("Yes.".to_string()));
1470
1
        let silence = DaemonResponse::success().with_transcription("  ".to_string());
1471
1
        assert_eq!(heard(silence), Ok("(no speech detected)".to_string()));
1472
1
        let busy = DaemonResponse::error_with_code(ErrorCode::RecordingInProgress, "busy");
1473
1
        assert!(heard(busy).is_err_and(|e| e.contains("already recording")));
1474
1
    }
1475
}