Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-app-core/src/pages/model_voice.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! The synthesis model's voice, on its Models card: which voice it speaks in,
3
//! which it could, and setting or clearing its own.
4
//!
5
//! The sibling of [`super::model_language`], and shaped the same way: what is
6
//! set and what may be set arrive from two endpoints and are held apart,
7
//! because choosing a voice rewrites the first and cannot change the second.
8
//!
9
//! One model is focused at a time ([`VoiceState::target`]), and answers for
10
//! any other are dropped: a read that lands after the user moved to another
11
//! model belongs to the model they left.
12
13
use crate::daemon::client::v1::pipeline::voice as client;
14
use crate::state::voice::{VoiceChoice, VoiceResolution, VoiceState};
15
16
/// What happened.
17
#[derive(Debug, Clone, PartialEq)]
18
pub enum Input {
19
    /// The card shows this model: read its voice. An empty pair shows none.
20
    Focus { source: String, model: String },
21
    /// Read the focused model's voice again: the library it draws on, or its
22
    /// voice, changed.
23
    Reload,
24
    /// The daemon said how the model's voice resolves.
25
    Loaded {
26
        source: String,
27
        model: String,
28
        block: VoiceResolution,
29
    },
30
    /// The voices the model can be set to.
31
    Listed {
32
        source: String,
33
        model: String,
34
        voices: Vec<VoiceChoice>,
35
    },
36
    /// The user picked a voice for the focused model, or its own default
37
    /// (`None`).
38
    Picked(Option<String>),
39
    /// Reading or storing it failed: why.
40
    Failed(String),
41
}
42
43
/// What the app should do.
44
#[derive(Debug, Clone, PartialEq, Eq)]
45
pub enum Effect {
46
    /// [`run_read`].
47
    Read { source: String, model: String },
48
    /// [`run_list`].
49
    List { source: String, model: String },
50
    /// [`run_save`]: a voice id, or `None` to clear the model's own.
51
    Save {
52
        source: String,
53
        model: String,
54
        voice: Option<String>,
55
    },
56
}
57
58
/// Something to tell the user. The app says it in its own words.
59
#[derive(Debug, Clone, PartialEq, Eq)]
60
pub enum Notice {
61
    CouldNotSaveVoice(String),
62
}
63
64
/// What an input came to.
65
#[derive(Debug, Default, PartialEq, Eq)]
66
pub struct Outcome {
67
    pub effects: Vec<Effect>,
68
    /// Take the voice's notice down.
69
    pub clear_notice: bool,
70
    pub notice: Option<Notice>,
71
}
72
73
impl Outcome {
74
15
    fn effect(effect: Effect) -> Self {
75
15
        Self {
76
15
            effects: vec![effect],
77
15
            ..Self::default()
78
15
        }
79
15
    }
80
}
81
82
19
fn focused(state: &VoiceState, source: &str, model: &str) -> bool {
83
19
    state
84
19
        .target
85
19
        .as_ref()
86
12
        .is_some_and(|(s, m)| s == source && m == model)
87
19
}
88
89
/// Take in `input`, and say what to do.
90
20
pub fn update(state: &mut VoiceState, input: Input) -> Outcome {
91
20
    match input {
92
        Input::Focus { source, model } => {
93
10
            if !focused(state, &source, &model) {
94
9
                state.resolution = None;
95
9
                state.choices.clear();
96
1
            }
97
10
            if source.is_empty() || model.is_empty() {
98
0
                state.target = None;
99
0
                return Outcome::default();
100
10
            }
101
10
            state.target = Some((source.clone(), model.clone()));
102
10
            Outcome::effect(Effect::Read { source, model })
103
        }
104
0
        Input::Reload => match state.target.clone() {
105
0
            Some((source, model)) => Outcome::effect(Effect::Read { source, model }),
106
0
            None => Outcome::default(),
107
        },
108
        // The list is read once the block is held: the two describe one
109
        // model, and a list for a model with no block would be read as
110
        // another's.
111
        Input::Loaded {
112
            source,
113
            model,
114
            block,
115
        } => {
116
6
            if !focused(state, &source, &model) {
117
1
                return Outcome::default();
118
5
            }
119
5
            state.resolution = Some(block);
120
5
            Outcome::effect(Effect::List { source, model })
121
        }
122
        Input::Listed {
123
            source,
124
            model,
125
            voices,
126
        } => {
127
1
            if focused(state, &source, &model) {
128
0
                state.choices = voices;
129
1
            }
130
1
            Outcome::default()
131
        }
132
        // Addressed to the model the card shows, never to "the active model",
133
        // so a pick landing after a model switch writes nothing rather than
134
        // the wrong model's voice.
135
2
        Input::Picked(voice) => match state.target.clone() {
136
1
            Some((source, model)) => Outcome {
137
1
                effects: vec![Effect::Save {
138
1
                    source,
139
1
                    model,
140
1
                    voice,
141
1
                }],
142
1
                clear_notice: true,
143
1
                notice: None,
144
1
            },
145
1
            None => Outcome::default(),
146
        },
147
1
        Input::Failed(e) => Outcome {
148
1
            notice: Some(Notice::CouldNotSaveVoice(e)),
149
1
            ..Outcome::default()
150
1
        },
151
    }
152
20
}
153
154
/// Whether `state` describes `(source, model)`: a card drawing another model
155
/// must not read it.
156
#[must_use]
157
2
pub fn shows(state: &VoiceState, source: &str, model: &str) -> bool {
158
2
    focused(state, source, model)
159
2
}
160
161
/// The first row of the voice picker: the model's own default.
162
#[derive(Debug, Clone, PartialEq, Eq)]
163
pub enum DefaultVoice {
164
    /// The default voice, by its label.
165
    Named(String),
166
    /// The model declares none: nothing is chosen, and it can't speak until
167
    /// something is. Every cloning model starts here.
168
    NoneChosen,
169
}
170
171
/// The voice picker for the focused model: its default row, then each voice
172
/// with whether it is cloned. `None` when there is nothing to pick from: a
173
/// model whose voices are all described takes free text and has no list, and
174
/// one that clones has none before a voice is recorded.
175
#[must_use]
176
3
pub fn picker(state: &VoiceState) -> Option<(DefaultVoice, Vec<(&VoiceChoice, bool)>)> {
177
3
    let block = state.resolution.as_ref()
?0
;
178
3
    if state.choices.is_empty() {
179
1
        return None;
180
2
    }
181
    // Named, not just "Default": a user comparing two rows should not have to
182
    // remember which voice the manifest picked.
183
2
    let default = block
184
2
        .default
185
2
        .as_ref()
186
2
        .map_or(DefaultVoice::NoneChosen, |id| 
{1
187
            DefaultVoice::Named(
188
1
                state
189
1
                    .choices
190
1
                    .iter()
191
1
                    .find(|v| &v.id == id)
192
1
                    .map_or_else(|| 
id0
.clone(), |v| v.label.clone()),
193
            )
194
1
        });
195
    // Cloned voices are marked. They sit with the presets because they are the
196
    // same choice to the user, but one is a recording they made, and a list
197
    // that did not say could put two identical labels side by side.
198
2
    let voices = state
199
2
        .choices
200
2
        .iter()
201
3
        .map(|v| (v, v.kind == "cloned"))
202
        .collect();
203
2
    Some((default, voices))
204
3
}
205
206
/// The voice the model is set to, or `None` while it speaks in its default:
207
/// the row the picker selects. The stored voice, not the one in effect: with
208
/// none stored, the default row is the one selected.
209
#[must_use]
210
2
pub fn chosen(state: &VoiceState) -> Option<&str> {
211
2
    let id = state.resolution.as_ref()
?0
.model_override.as_deref()
?1
;
212
2
    
state.choices.iter()1
.any(|v| v.id == id).then_some(
id1
)
213
2
}
214
215
/// Which way out of "nothing to speak in" the user has.
216
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217
pub enum VoiceWarning {
218
    /// Voices to pick from, in the picker above.
219
    PickACloned,
220
    /// None yet, and the model clones: record one on the Voices tab.
221
    RecordOne,
222
    /// Neither a list nor a way to fill one: a manifest that declares preset
223
    /// voices and ships none. Nothing to send the user to.
224
    NoneChosen,
225
}
226
227
/// The warning for the one state in which the model can't speak at all: no
228
/// voice in effect, and no free-text description to fall back on. `None` when
229
/// it can.
230
#[must_use]
231
3
pub fn warning(state: &VoiceState) -> Option<VoiceWarning> {
232
3
    let block = state.resolution.as_ref()
?0
;
233
3
    if !block.has_no_voice() {
234
1
        return None;
235
2
    }
236
2
    Some(warning_for(
237
2
        !state.choices.is_empty(),
238
2
        block.kinds.iter().any(|k| k == "cloned"),
239
    ))
240
3
}
241
242
/// The warning for a model with `has_choices` voices to pick, which `clones`
243
/// or not. Never sends someone who has a voice to pick off to record one.
244
#[must_use]
245
6
pub const fn warning_for(has_choices: bool, clones: bool) -> VoiceWarning {
246
6
    match (has_choices, clones) {
247
3
        (true, _) => VoiceWarning::PickACloned,
248
2
        (false, true) => VoiceWarning::RecordOne,
249
1
        (false, false) => VoiceWarning::NoneChosen,
250
    }
251
6
}
252
253
/// Read how the model's voice resolves.
254
0
pub async fn run_read(source: String, model: String) -> Input {
255
0
    loaded(source, model.clone(), client::get_model_voice(model).await)
256
0
}
257
258
/// Read the voices the model can be set to.
259
0
pub async fn run_list(source: String, model: String) -> Input {
260
0
    match client::list_model_voices(model.clone()).await {
261
0
        Ok(voices) => Input::Listed {
262
0
            source,
263
0
            model,
264
0
            voices,
265
0
        },
266
0
        Err(e) => Input::Failed(e.to_string()),
267
    }
268
0
}
269
270
/// Set the model's voice, or clear it back to its default with `None`. The
271
/// daemon answers with how it now resolves.
272
0
pub async fn run_save(source: String, model: String, voice: Option<String>) -> Input {
273
0
    let result = match voice {
274
0
        Some(voice) => client::set_model_voice(model.clone(), voice).await,
275
0
        None => client::clear_model_voice(model.clone()).await,
276
    };
277
0
    loaded(source, model, result)
278
0
}
279
280
0
fn loaded(
281
0
    source: String,
282
0
    model: String,
283
0
    result: super_voice_shared::daemon::http_client::HttpResult<VoiceResolution>,
284
0
) -> Input {
285
0
    match result {
286
0
        Ok(block) => Input::Loaded {
287
0
            source,
288
0
            model,
289
0
            block,
290
0
        },
291
0
        Err(e) => Input::Failed(e.to_string()),
292
    }
293
0
}
294
295
#[cfg(test)]
296
mod tests {
297
    use super::*;
298
299
10
    fn focus(source: &str, model: &str) -> Input {
300
10
        Input::Focus {
301
10
            source: source.into(),
302
10
            model: model.into(),
303
10
        }
304
10
    }
305
306
6
    fn block(effective: Option<&str>, default: Option<&str>, kinds: &[&str]) -> VoiceResolution {
307
6
        VoiceResolution {
308
6
            effective: effective.map(String::from),
309
6
            model_override: None,
310
6
            default: default.map(String::from),
311
6
            kinds: kinds.iter().map(ToString::to_string).collect(),
312
6
        }
313
6
    }
314
315
5
    fn choice(id: &str, label: &str, kind: &str) -> VoiceChoice {
316
5
        VoiceChoice {
317
5
            id: id.into(),
318
5
            label: label.into(),
319
5
            kind: kind.into(),
320
5
        }
321
5
    }
322
323
6
    fn loaded(state: &mut VoiceState, model: &str, block: VoiceResolution) -> Outcome {
324
6
        update(
325
6
            state,
326
6
            Input::Loaded {
327
6
                source: "src".into(),
328
6
                model: model.into(),
329
6
                block,
330
6
            },
331
6
        )
332
6
    }
333
334
    #[test]
335
1
    fn focusing_reads_the_block_and_then_the_list() {
336
1
        let mut state = VoiceState::default();
337
1
        let outcome = update(&mut state, focus("src", "kokoro"));
338
1
        assert_eq!(
339
1
            outcome.effects,
340
1
            [Effect::Read {
341
1
                source: "src".into(),
342
1
                model: "kokoro".into()
343
1
            }]
344
        );
345
1
        let outcome = loaded(
346
1
            &mut state,
347
1
            "kokoro",
348
1
            block(Some("af"), Some("af"), &["preset"]),
349
1
        );
350
1
        assert_eq!(
351
1
            outcome.effects,
352
1
            [Effect::List {
353
1
                source: "src".into(),
354
1
                model: "kokoro".into()
355
1
            }]
356
        );
357
1
    }
358
359
    #[test]
360
1
    fn answers_for_a_model_no_longer_focused_are_dropped() {
361
1
        let mut state = VoiceState::default();
362
1
        update(&mut state, focus("src", "old"));
363
1
        update(&mut state, focus("src", "new"));
364
1
        let outcome = loaded(&mut state, "old", block(Some("af"), None, &[]));
365
1
        assert!(outcome.effects.is_empty());
366
1
        assert!(state.resolution.is_none());
367
1
        update(
368
1
            &mut state,
369
1
            Input::Listed {
370
1
                source: "src".into(),
371
1
                model: "old".into(),
372
1
                voices: vec![choice("af", "Af", "preset")],
373
1
            },
374
1
        );
375
1
        assert!(state.choices.is_empty());
376
1
    }
377
378
    /// Reading the same model again keeps its list on screen until the new
379
    /// one lands.
380
    #[test]
381
1
    fn refocusing_the_same_model_keeps_what_it_shows() {
382
1
        let mut state = VoiceState::default();
383
1
        update(&mut state, focus("src", "kokoro"));
384
1
        loaded(
385
1
            &mut state,
386
1
            "kokoro",
387
1
            block(Some("af"), Some("af"), &["preset"]),
388
1
        );
389
1
        state.choices = vec![choice("af", "Af", "preset")];
390
1
        update(&mut state, focus("src", "kokoro"));
391
1
        assert!(state.resolution.is_some());
392
1
        assert_eq!(state.choices.len(), 1);
393
1
        update(&mut state, focus("src", "other"));
394
1
        assert!(state.resolution.is_none());
395
1
        assert!(state.choices.is_empty());
396
1
    }
397
398
    #[test]
399
1
    fn a_pick_goes_to_the_focused_model() {
400
1
        let mut state = VoiceState::default();
401
1
        assert_eq!(
402
1
            update(&mut state, Input::Picked(Some("af".into()))),
403
1
            Outcome::default()
404
        );
405
1
        update(&mut state, focus("src", "kokoro"));
406
1
        let outcome = update(&mut state, Input::Picked(None));
407
1
        assert!(outcome.clear_notice);
408
1
        assert_eq!(
409
1
            outcome.effects,
410
1
            [Effect::Save {
411
1
                source: "src".into(),
412
1
                model: "kokoro".into(),
413
1
                voice: None
414
1
            }]
415
        );
416
1
        assert_eq!(
417
1
            update(&mut state, Input::Failed("down".into())).notice,
418
1
            Some(Notice::CouldNotSaveVoice("down".into()))
419
        );
420
1
    }
421
422
    #[test]
423
1
    fn the_picker_names_the_default_and_marks_cloned_voices() {
424
1
        let mut state = VoiceState::default();
425
1
        update(&mut state, focus("src", "kokoro"));
426
1
        loaded(
427
1
            &mut state,
428
1
            "kokoro",
429
1
            block(Some("af"), Some("af"), &["preset", "cloned"]),
430
1
        );
431
1
        assert!(picker(&state).is_none());
432
1
        state.choices = vec![
433
1
            choice("af", "Bella", "preset"),
434
1
            choice("me", "Me", "cloned"),
435
1
        ];
436
1
        let (default, voices) = picker(&state).unwrap();
437
1
        assert_eq!(default, DefaultVoice::Named("Bella".into()));
438
2
        let marks: Vec<bool> = 
voices.iter()1
.map(|(_, cloned)| *cloned).collect();
439
1
        assert_eq!(marks, [false, true]);
440
1
        assert_eq!(chosen(&state), None);
441
442
1
        state.resolution.as_mut().unwrap().model_override = Some("me".into());
443
1
        assert_eq!(chosen(&state), Some("me"));
444
1
    }
445
446
    #[test]
447
1
    fn a_cloning_model_without_a_default_has_none_chosen() {
448
1
        let mut state = VoiceState::default();
449
1
        update(&mut state, focus("src", "clone"));
450
1
        loaded(&mut state, "clone", block(None, None, &["cloned"]));
451
1
        state.choices = vec![choice("me", "Me", "cloned")];
452
1
        assert_eq!(picker(&state).unwrap().0, DefaultVoice::NoneChosen);
453
1
        assert_eq!(warning(&state), Some(VoiceWarning::PickACloned));
454
455
1
        state.choices.clear();
456
1
        assert_eq!(warning(&state), Some(VoiceWarning::RecordOne));
457
1
    }
458
459
    /// A model that takes described voices needs nothing chosen.
460
    #[test]
461
1
    fn a_described_voice_needs_no_warning() {
462
1
        let mut state = VoiceState::default();
463
1
        update(&mut state, focus("src", "describe"));
464
1
        loaded(&mut state, "describe", block(None, None, &["described"]));
465
1
        assert_eq!(warning(&state), None);
466
1
    }
467
468
    #[test]
469
1
    fn the_warning_never_sends_a_user_with_voices_to_record() {
470
1
        assert_eq!(warning_for(true, true), VoiceWarning::PickACloned);
471
1
        assert_eq!(warning_for(true, false), VoiceWarning::PickACloned);
472
1
        assert_eq!(warning_for(false, true), VoiceWarning::RecordOne);
473
1
        assert_eq!(warning_for(false, false), VoiceWarning::NoneChosen);
474
1
    }
475
}