feat(app): call detection and the four response policies

- calls.rs: wake words anywhere in the utterance with near matches by
  edit distance on NFKD-normalised letters (Hangul splits into its
  letters), call modes (wakeWord, addressed, everything), designated
  people with both switches, and a voice stop (wake word + stop word).
- policy.rs: first, inOrder, latest and important as an event-driven
  state machine with the time passed in: ordering by end time, waiting
  for an earlier-ended utterance still being transcribed, queue limit,
  interruption, importance ranking only on a tie with a timeout, stop
  dropping the queue, and a reason for every missed request.
- settings: new call and response sections, validated with the key.
- conversation.spec.md documents the contract; registry and roadmap
  updated. Wiring into the Discord core and the brain comes next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 22:05:50 +09:00
parent b88b28140f
commit 6fc3983a40
10 changed files with 1082 additions and 8 deletions

View File

@@ -31,6 +31,7 @@ Any code change must either adhere to our spec files perfectly or you should ask
| `src/jarvis/memory/summariser.spec.md` | Diary summariser prompt contract, hygiene rules (deflection, attribution, topic separation), post-process scrub, and bulk-sweep clean button | Two-layer defence: prompt + deterministic scrub; corrupted summaries poison every downstream consumer |
| `src/jarvis/memory/recall_gate.spec.md` | Deterministic skip-enrichment heuristic when the hot window covers a follow-up | Fail-open; language-agnostic via `\w{3,}` + `re.UNICODE`; planner intent always wins |
| `src/voice_worker/voice_worker.spec.md` | v2 voice worker: multi-speaker streaming STT (shared Whisper, batched) and sentence TTS over a local WebSocket | Loopback only with an app token; no transcript text in logs; finals before partials; language-agnostic |
| `app/src/conversation.spec.md` | v2 call detection and response policies in the Rust app: wake words with near matches, call modes, designated people, voice stop, the four response policies with settling, interruption and missed requests | Pure types tested with fake times; language-agnostic matching on normalised letters; nothing dropped silently |
| `app/src/discord_core.spec.md` | v2 Discord voice core in the Rust app: join/leave, per-speaker receive (own reorder window and Opus decoding after songbird decrypts) to the voice worker, sentence playback and stop, slash command, registered chat channels (read/send), voice worker process | Hears only the channel it is in and reads only registered channels; join notice on every join; chat is data and sent text never pings; no transcript or chat text in logs |
The LLM contexts graph at `docs/llm_contexts.md` maps every LLM call in the app (model, gating, inputs, outputs, limits, flow). Keep it up-to-date at all times: any change that adds, removes, or alters an LLM context (model resolution, timeout, cap, prompt source, gating flag, data-flow edge) must update `docs/llm_contexts.md` in the same PR.

10
app/Cargo.lock generated
View File

@@ -1457,6 +1457,7 @@ dependencies = [
"symphonia",
"tokio",
"tokio-tungstenite 0.26.2",
"unicode-normalization",
]
[[package]]
@@ -3922,6 +3923,15 @@ version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
version = "1.13.3"

View File

@@ -28,6 +28,7 @@ rand = "0.9"
base64 = "0.22"
async-trait = "0.1"
opus2 = "0.4"
unicode-normalization = "0.1"
[profile.release]
lto = "thin"

244
app/src/calls.rs Normal file
View File

@@ -0,0 +1,244 @@
//! Call detection: does Jarvis answer this utterance? (`app/src/conversation.spec.md`).
//!
//! A pure function of the settings, the speaker and the text. Wake words and stop words are settings;
//! matching works on Unicode-normalised letters, so it behaves the same in any script.
use std::collections::HashSet;
use unicode_normalization::UnicodeNormalization;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallMode {
/// Answer only when called by a wake word (default).
WakeWord,
/// Also answer what the brain judges to be said to Jarvis.
Addressed,
/// Answer every utterance.
Everything,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CallSettings {
pub wake_words: Vec<String>,
/// Share of a wake word's normalised letters a heard word may differ by (0-0.5).
pub similarity: f64,
pub mode: CallMode,
pub designated: HashSet<u64>,
pub designated_only: bool,
pub designated_no_wake_word: bool,
pub stop_words: Vec<String>,
}
impl Default for CallSettings {
fn default() -> Self {
Self {
wake_words: vec!["자비스".into()],
similarity: 0.2,
mode: CallMode::WakeWord,
designated: HashSet::new(),
designated_only: false,
designated_no_wake_word: false,
stop_words: ["멈춰", "그만", "정지", "stop"].map(String::from).to_vec(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Call {
Ignore,
/// Answer it. `direct`: called by a wake word.
Request { direct: bool },
/// Ask the brain whether it was said to Jarvis (`call.mode` `addressed`).
Ask,
/// Stop the current answer and drop the waiting requests.
Stop,
}
/// Most letters after a stop word that still count as the stop ("멈춰 줘", "그만해").
const STOP_TAIL: usize = 3;
/// NFKD, lower case, letters and digits only.
pub fn normalise(text: &str) -> Vec<char> {
text.nfkd().flat_map(char::to_lowercase).filter(|c| c.is_alphanumeric()).collect()
}
/// The stretch `[start, end)` of `text` closest to `word`, if within `max_edits` edits
/// (approximate substring matching: the match may start and end anywhere in `text`).
fn find(text: &[char], word: &[char], max_edits: usize) -> Option<(usize, usize)> {
if word.is_empty() || text.is_empty() {
return None;
}
let (n, m) = (text.len(), word.len());
// d[i][j]: fewest edits turning word[..i] into a stretch of text ending at j; start[i][j] where it began.
let mut d = vec![vec![0usize; n + 1]; m + 1];
let mut start = vec![vec![0usize; n + 1]; m + 1];
for j in 0..=n {
start[0][j] = j;
}
for i in 1..=m {
d[i][0] = i;
start[i][0] = 0;
for j in 1..=n {
let sub = d[i - 1][j - 1] + usize::from(word[i - 1] != text[j - 1]);
let del = d[i - 1][j] + 1; // word letter missing from text
let ins = d[i][j - 1] + 1; // extra letter in text
let (best, from) = if sub <= del && sub <= ins {
(sub, start[i - 1][j - 1])
} else if del <= ins {
(del, start[i - 1][j])
} else {
(ins, start[i][j - 1])
};
d[i][j] = best;
start[i][j] = from;
}
}
(1..=n)
.filter(|&j| d[m][j] <= max_edits)
.min_by_key(|&j| (d[m][j], j))
.map(|j| (start[m][j], j))
}
impl CallSettings {
fn allowed_edits(&self, word: &[char]) -> usize {
(self.similarity.clamp(0.0, 0.5) * word.len() as f64 + 1e-9).floor() as usize
}
/// The text with the first heard wake word removed, if one is heard.
fn without_wake_word(&self, text: &[char]) -> Option<Vec<char>> {
// The earliest heard wake word is the one used to address Jarvis.
let (s, e) = self
.wake_words
.iter()
.map(|w| normalise(w))
.filter_map(|word| find(text, &word, self.allowed_edits(&word)))
.min()?;
Some(text[..s].iter().chain(&text[e..]).copied().collect())
}
fn is_stop(&self, rest: &[char]) -> bool {
self.stop_words.iter().map(|w| normalise(w)).any(|w| {
!w.is_empty() && rest.starts_with(&w) && rest.len() - w.len() <= STOP_TAIL
})
}
/// Decide what to do with one finished utterance.
pub fn judge(&self, speaker: u64, text: &str) -> Call {
let norm = normalise(text);
if norm.is_empty() {
return Call::Ignore;
}
let designated = self.designated.contains(&speaker);
if self.designated_only && !designated {
return Call::Ignore;
}
if let Some(rest) = self.without_wake_word(&norm) {
if self.is_stop(&rest) {
return Call::Stop;
}
return Call::Request { direct: true };
}
if self.designated_no_wake_word && designated {
return Call::Request { direct: false };
}
match self.mode {
CallMode::Everything => Call::Request { direct: false },
CallMode::Addressed => Call::Ask,
CallMode::WakeWord => Call::Ignore,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const A: u64 = 1;
const B: u64 = 2;
fn s() -> CallSettings {
CallSettings::default()
}
#[test]
fn exact_and_near_wake_words_call_but_a_different_word_does_not() {
let c = s();
assert_eq!(c.judge(A, "자비스, 오늘 날씨 어때?"), Call::Request { direct: true });
assert_eq!(c.judge(A, "자비즈 날씨 알려 줘"), Call::Request { direct: true });
assert_eq!(c.judge(A, "오늘 날씨 어때 자비스"), Call::Request { direct: true });
assert_eq!(c.judge(A, "서비스 센터 몇 시에 열어?"), Call::Ignore);
assert_eq!(c.judge(A, "오늘 날씨 어때?"), Call::Ignore);
}
#[test]
fn latin_wake_words_ignore_case_spacing_and_accents() {
let c = CallSettings { wake_words: vec!["Jarvis".into()], ..s() };
assert_eq!(c.judge(A, "hey JARVIS, what's up"), Call::Request { direct: true });
assert_eq!(c.judge(A, "Jervis, lights on"), Call::Request { direct: true });
assert_eq!(c.judge(A, "Jär vis?"), Call::Request { direct: true });
assert_eq!(c.judge(A, "the service is down"), Call::Ignore);
}
#[test]
fn similarity_zero_needs_the_exact_word() {
let c = CallSettings { similarity: 0.0, ..s() };
assert_eq!(c.judge(A, "자비즈 날씨"), Call::Ignore);
assert_eq!(c.judge(A, "자비스 날씨"), Call::Request { direct: true });
}
#[test]
fn stop_needs_the_wake_word_and_little_else() {
let c = s();
assert_eq!(c.judge(A, "자비스, 멈춰!"), Call::Stop);
assert_eq!(c.judge(A, "자비스 그만해"), Call::Stop);
assert_eq!(c.judge(A, "자비스 멈춰 줘"), Call::Stop);
assert_eq!(c.judge(A, "멈춰"), Call::Ignore);
assert_eq!(c.judge(A, "자비스 그만 얘기하고 날씨 알려 줘"), Call::Request { direct: true });
}
#[test]
fn empty_and_punctuation_only_text_is_ignored() {
let c = CallSettings { mode: CallMode::Everything, ..s() };
assert_eq!(c.judge(A, ""), Call::Ignore);
assert_eq!(c.judge(A, " ... ?! "), Call::Ignore);
}
#[test]
fn modes_decide_utterances_without_a_wake_word() {
let every = CallSettings { mode: CallMode::Everything, ..s() };
assert_eq!(every.judge(A, "날씨 어때"), Call::Request { direct: false });
let addressed = CallSettings { mode: CallMode::Addressed, ..s() };
assert_eq!(addressed.judge(A, "날씨 어때"), Call::Ask);
assert_eq!(addressed.judge(A, "자비스 날씨 어때"), Call::Request { direct: true });
}
#[test]
fn designated_switches_combine_as_the_design_table_says() {
let base = CallSettings { designated: [A].into(), ..s() };
// only on, no-wake off: designated people answered only when called.
let c = CallSettings { designated_only: true, ..base.clone() };
assert_eq!(c.judge(A, "자비스 날씨"), Call::Request { direct: true });
assert_eq!(c.judge(A, "날씨"), Call::Ignore);
assert_eq!(c.judge(B, "자비스 날씨"), Call::Ignore);
assert_eq!(c.judge(B, "자비스 멈춰"), Call::Ignore);
// only on, no-wake on: designated people only, without a wake word.
let c = CallSettings { designated_only: true, designated_no_wake_word: true, ..base.clone() };
assert_eq!(c.judge(A, "날씨"), Call::Request { direct: false });
assert_eq!(c.judge(B, "자비스 날씨"), Call::Ignore);
// only off, no-wake on: anyone by wake word, designated people without.
let c = CallSettings { designated_no_wake_word: true, ..base.clone() };
assert_eq!(c.judge(A, "날씨"), Call::Request { direct: false });
assert_eq!(c.judge(B, "날씨"), Call::Ignore);
assert_eq!(c.judge(B, "자비스 날씨"), Call::Request { direct: true });
// both off (default): anyone, by wake word only.
assert_eq!(base.judge(A, "날씨"), Call::Ignore);
assert_eq!(base.judge(B, "자비스 날씨"), Call::Request { direct: true });
}
#[test]
fn several_wake_words_all_count() {
let c = CallSettings { wake_words: vec!["자비스".into(), "javis".into()], ..s() };
assert_eq!(c.judge(A, "javis 날씨"), Call::Request { direct: true });
assert_eq!(c.judge(A, "javis stop"), Call::Stop);
}
}

View File

@@ -0,0 +1,109 @@
# Conversation spec: call detection and response policies (v2 M4)
The part of the app that decides which finished utterances (and, later, chat messages) Jarvis answers
and in what order, and when an answer that is being spoken stops. It sits between the Discord voice
core (`discord_core.spec.md`), which reports what was heard and plays speech, and the voice worker's
brain (`src/voice_worker/voice_worker.spec.md`, `reply`), which writes the answer. The user-facing
design is `docs/v2/conversation.md`; this spec is the contract the code follows.
## Principles
- **Plain types, tested without Discord.** Call detection (`app/src/calls.rs`) is a pure function of
the settings, the speaker and the text. The response policy (`app/src/policy.rs`) is a state machine
driven by events with the time passed in, so every rule is tested with fake times.
- **Language-agnostic.** Nothing matches a language's words in code. Wake words and stop words are
settings; matching works on Unicode-normalised letters, so it behaves the same in any script.
- **No text in logs.** Logs carry speaker IDs, decisions, reasons, counts and timings, never what was
said.
- **Nothing is dropped silently.** Every request the policy does not answer, and every answer it stops,
is reported as missed with a reason (the dashboard's "놓친 요청" list, M5).
## Call detection
Settings (`settings.json`, section `call`; wake words stay in `voice.wakeWords`):
| Key | Default | Meaning |
|---|---|---|
| `voice.wakeWords` | `["자비스"]` | Wake words for voice (also the STT hint). |
| `call.chatWakeWords` | `null` | Wake words for chat; `null` uses `voice.wakeWords`. |
| `call.similarity` | `0.2` | How far a heard word may be from a wake word, as a share of the wake word's normalised letters (0-0.5). `0` needs an exact match. |
| `call.mode` | `"wakeWord"` | `wakeWord`: answer only when called by a wake word. `addressed`: also answer what is judged to be said to Jarvis. `everything`: answer every utterance. |
| `call.designated` | `[]` | Discord user IDs of the designated people. |
| `call.designatedOnly` | `false` | Answer only designated people. |
| `call.designatedNoWakeWord` | `false` | Answer designated people without a wake word. |
| `call.stopWords` | `["멈춰", "그만", "정지", "stop"]` | Said together with a wake word, they stop Jarvis in any policy. |
Normalisation: Unicode NFKD, lower case, and only letters and digits kept (spaces, punctuation and
combining marks dropped). NFKD splits Hangul syllables into their letters, so "자비즈" is one letter
away from "자비스" (of six) while "서비스" is two away.
A wake word is heard when some stretch of the normalised text is at most
`floor(similarity × letters of the wake word)` edits (insert, delete, substitute) from it. With the
default 0.2, "자비스" (six letters) allows one edit. A wake word anywhere in the utterance counts.
Decision for one utterance (`judge(speaker, text)`), in order:
1. Empty text (after normalisation): ignore.
2. `designatedOnly` and the speaker is not designated: ignore.
3. A wake word is heard and the rest of the text, with that stretch removed, starts with a stop word
and has at most 3 more letters ("멈춰", "멈춰 줘", "그만해"): **stop**.
4. A wake word is heard: **request**, `direct` (called by name).
5. `designatedNoWakeWord` and the speaker is designated: **request**, not direct.
6. `call.mode` `everything`: **request**, not direct. `addressed`: **ask** (the brain judges whether it
was said to Jarvis; a yes becomes a request, not direct). `wakeWord`: ignore.
The text sent to the brain is the utterance as heard; the brain treats the wake word as address.
## Response policy
Settings (section `response`):
| Key | Default | Meaning |
|---|---|---|
| `response.policy` | `"first"` | `first` (처음 대화만), `inOrder` (들어온 순서대로), `latest` (마지막 대화만), `important` (제일 중요한 대화만). |
| `response.queueMax` | `5` | `inOrder`: most waiting requests; past it the oldest is dropped. 1-20. |
| `response.collectMs` | `700` | `important`: how long candidates are collected before choosing. 0-3000. |
| `response.settleMs` | `800` | Longest wait for an earlier-ended utterance that is still being transcribed. 0-3000. |
| `response.priorities` | `{}` | `important`: user ID → priority (higher first, default 0). |
Terms:
- A **request** has an id, the speaker, the text, whether it was `direct`, and `ended_at`: when the
utterance ended (the final's arrival minus its `wait_ms`).
- An **answer** runs from the moment the policy starts it until it is done (its speech ended, failed or
was stopped). There is at most one answer at a time: Jarvis has one voice.
- An utterance is **open** from its `speech_start` until its final. An open utterance whose speaker
has stopped speaking (`speaking_end` sent) is **ending**: its final may still turn out to be a call.
Rules shared by every policy:
- **Ordering by end time.** Requests are compared by `ended_at`, not by when their final arrived, so a
long utterance is not pushed back by its transcription time.
- **Settling.** When a request could start now but some other utterance is ending and stopped earlier
than the request's `ended_at` (in `important`: any ending utterance, since it competes on score), the
policy waits for that final, at most `settleMs` from the first waiting request's arrival. A final that
is not a call ends the wait for it. `latest` does not settle: an earlier utterance would lose anyway.
- **Stop.** A stop decision stops the current answer and drops every waiting request, in every policy.
The stopped answer and the dropped requests are missed (`stopped`).
- An answer that is already done is never started again.
Per policy:
| Policy | No answer running | A new request while an answer runs |
|---|---|---|
| `first` | Answer the request that ended first (after settling). | Missed (`busy`). |
| `inOrder` | Answer the earliest-ended waiting request. | Queued by `ended_at`. Past `queueMax`, the earliest-ended waiting one is missed (`queue_full`). |
| `latest` | Answer the latest-ended waiting request; the others are missed (`replaced`). | The current answer stops (missed, `interrupted`) and the new request is answered. A request that ended before the current one is missed (`replaced`). |
| `important` | Collect for `collectMs` from the first request, then answer the best; the other candidates are missed (`lower_score`). | Kept as a candidate. If it beats the current answer, the current answer stops (missed, `interrupted`) and the best candidate is answered at once; otherwise, when the current answer ends, the best of the candidates collected meanwhile is answered and the rest are missed (`lower_score`). |
`important` ranks by (1) priority, (2) `direct`, then (3) the brain's importance ranking, asked for only
when two or more candidates tie on (1) and (2). While the ranking is pending nothing new starts; if it
does not come within 1.5 s, or fails, the earliest-ended of the tied candidates wins. A candidate
beats the running answer only on (1) or (2); the ranking is not asked for an interruption.
## Tests
`cargo test` covers call detection (exact and near wake words in Hangul and Latin, a different word
two letters away, wake word anywhere, stop with and without a wake word, designated combinations,
modes) and every policy rule above with fake times (settling, ordering by end time, busy, queue limit,
interruption, ranking tie, ranking timeout, stop dropping the queue).

View File

@@ -65,13 +65,16 @@ strings (numbers would lose precision).
| `voice.maxSpeakers` | `10` | Most people transcribed at once, 1-10. |
| `voice.listenToBots` | `false` | Also transcribe other bots (music bots are ignored by default). |
| `voice.joinNotice` | "자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다." | Posted in the voice channel's chat on every join. Must not be empty. |
| `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`. |
| `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`, and the voice wake words of call detection. |
| `voice.stt` | `{}` | Other worker STT settings (`partials`, `end_silence_ms`, `final_beam`, `language`, ...); the worker validates them. |
| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false)}` per channel. |
| `voiceWorker.python` | `python3` (`python.exe` on Windows) | Python of the worker venv. |
| `voiceWorker.cwd` | the repo's `src/` (development builds) | Folder holding the `voice_worker` package. |
| `voiceWorker.args` | `[]` | Extra worker arguments, e.g. `["--melo-python", "<MeloTTS venv python>"]`. |
The `call` and `response` sections (call detection and response policies, M4) are in
`conversation.spec.md`.
## Voice worker process
The app starts `python -m voice_worker --host 127.0.0.1 --port <port> <args>` in `voiceWorker.cwd`

View File

@@ -1,10 +1,12 @@
//! Jarvis v2 app core (see `app/src/discord_core.spec.md`).
pub mod log;
pub mod calls;
pub mod chat;
pub mod discord;
pub mod frames;
pub mod playback;
pub mod policy;
pub mod receive;
pub mod services;
pub mod settings;

552
app/src/policy.rs Normal file
View File

@@ -0,0 +1,552 @@
//! Response policy: which call Jarvis answers, in what order, and when an answer stops
//! (`app/src/conversation.spec.md`).
//!
//! A state machine driven by events with the time passed in. It never plays or asks anything itself:
//! every call returns the actions for the caller to carry out.
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyKind {
/// 처음 대화만: new requests are dropped while an answer runs (default).
First,
/// 들어온 순서대로: answered one after another in end-time order.
InOrder,
/// 마지막 대화만: the newest request replaces everything else, even a running answer.
Latest,
/// 제일 중요한 대화만: candidates are collected and the best one is answered.
Important,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PolicySettings {
pub kind: PolicyKind,
pub queue_max: usize,
pub collect: Duration,
pub settle: Duration,
pub priorities: HashMap<u64, i64>,
/// How long the brain's importance ranking is waited for.
pub rank_timeout: Duration,
}
impl Default for PolicySettings {
fn default() -> Self {
Self {
kind: PolicyKind::First,
queue_max: 5,
collect: Duration::from_millis(700),
settle: Duration::from_millis(800),
priorities: HashMap::new(),
rank_timeout: Duration::from_millis(1500),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
pub id: u64,
pub speaker: u64,
pub text: String,
/// Called by a wake word.
pub direct: bool,
/// When the utterance ended.
pub ended_at: Instant,
/// When its final arrived.
pub arrived_at: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissReason {
/// `first`: an answer was running or another caller finished first.
Busy,
/// `inOrder`: the queue was full.
QueueFull,
/// `latest`: a newer request took its place.
Replaced,
/// The answer was stopped for a newer or more important request.
Interrupted,
/// `important`: another candidate was chosen.
LowerScore,
/// A stop command.
Stopped,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
/// Start answering this request.
Answer(Request),
/// Stop the running answer with this id (its speech and its reply).
StopAnswer(u64),
/// Not answered, or stopped: for the "놓친 요청" list.
Missed(Request, MissReason),
/// Ask the brain to rank these tied candidates by importance; answer with `ranked`.
Rank(Vec<Request>),
}
#[derive(Debug, Default)]
struct Open {
/// When the speaker stopped sending audio, if they have.
stopped_at: Option<Instant>,
}
pub struct Policy {
s: PolicySettings,
current: Option<Request>,
waiting: Vec<Request>,
open: HashMap<u64, Open>,
/// `important`: no choice before this.
collect_until: Option<Instant>,
/// `important`: the tied candidates being ranked and when to give up waiting.
ranking: Option<(HashSet<u64>, Instant)>,
}
impl Policy {
pub fn new(s: PolicySettings) -> Self {
Self { s, current: None, waiting: vec![], open: HashMap::new(), collect_until: None, ranking: None }
}
pub fn settings(&self) -> &PolicySettings {
&self.s
}
/// The id of the running answer.
pub fn current(&self) -> Option<u64> {
self.current.as_ref().map(|r| r.id)
}
pub fn waiting(&self) -> usize {
self.waiting.len()
}
/// An utterance started (`speech_start`).
pub fn utterance_open(&mut self, speaker: u64) {
self.open.insert(speaker, Open::default());
}
/// The speaker stopped sending audio; their final is still to come.
pub fn speaking_stopped(&mut self, speaker: u64, at: Instant) {
if let Some(o) = self.open.get_mut(&speaker) {
o.stopped_at.get_or_insert(at);
}
}
/// The speaker's final arrived and was not a call (or the speaker left).
pub fn utterance_closed(&mut self, speaker: u64, now: Instant) -> Vec<Action> {
self.open.remove(&speaker);
self.choose(now, None)
}
fn score(&self, r: &Request) -> (i64, bool) {
(self.s.priorities.get(&r.speaker).copied().unwrap_or(0), r.direct)
}
/// The speaker's final was a call.
pub fn request(&mut self, req: Request, now: Instant) -> Vec<Action> {
self.open.remove(&req.speaker);
let mut out = vec![];
if let Some(cur) = self.current.clone() {
match self.s.kind {
PolicyKind::First => out.push(Action::Missed(req, MissReason::Busy)),
PolicyKind::InOrder => self.enqueue(req, &mut out),
PolicyKind::Latest => {
if req.ended_at > cur.ended_at {
self.interrupt(&mut out);
for r in self.waiting.drain(..) {
out.push(Action::Missed(r, MissReason::Replaced));
}
self.waiting.push(req);
} else {
out.push(Action::Missed(req, MissReason::Replaced));
}
}
PolicyKind::Important => {
let beats = self.score(&req) > self.score(&cur);
self.waiting.push(req);
if beats {
self.interrupt(&mut out);
self.collect_until = None;
}
}
}
} else {
if self.s.kind == PolicyKind::Important && self.waiting.is_empty() && self.ranking.is_none() {
self.collect_until = Some(now + self.s.collect);
}
self.enqueue(req, &mut out);
}
out.extend(self.choose(now, None));
out
}
fn enqueue(&mut self, req: Request, out: &mut Vec<Action>) {
let at = self.waiting.partition_point(|r| r.ended_at <= req.ended_at);
self.waiting.insert(at, req);
if self.s.kind == PolicyKind::InOrder {
while self.waiting.len() > self.s.queue_max.max(1) {
out.push(Action::Missed(self.waiting.remove(0), MissReason::QueueFull));
}
}
}
fn interrupt(&mut self, out: &mut Vec<Action>) {
if let Some(cur) = self.current.take() {
out.push(Action::StopAnswer(cur.id));
out.push(Action::Missed(cur, MissReason::Interrupted));
}
}
/// A stop command: stop the answer and drop everything waiting.
pub fn stop(&mut self) -> Vec<Action> {
let mut out = vec![];
if let Some(cur) = self.current.take() {
out.push(Action::StopAnswer(cur.id));
out.push(Action::Missed(cur, MissReason::Stopped));
}
for r in self.waiting.drain(..) {
out.push(Action::Missed(r, MissReason::Stopped));
}
self.collect_until = None;
self.ranking = None;
out
}
/// The answer's speech ended, failed or was stopped.
pub fn answer_done(&mut self, id: u64, now: Instant) -> Vec<Action> {
if self.current.as_ref().map(|r| r.id) != Some(id) {
return vec![];
}
self.current = None;
self.choose(now, None)
}
/// The brain's ranking of the tied candidates, best first.
pub fn ranked(&mut self, order: &[u64], now: Instant) -> Vec<Action> {
let Some((tied, _)) = self.ranking.take() else { return vec![] };
let winner = order.iter().copied().find(|id| tied.contains(id));
self.choose(now, Some(winner))
}
/// Timers: settling, collecting and the ranking timeout.
pub fn tick(&mut self, now: Instant) -> Vec<Action> {
if let Some((_, deadline)) = &self.ranking {
if now >= *deadline {
self.ranking = None;
return self.choose(now, Some(None));
}
}
self.choose(now, None)
}
/// When `tick` should run next.
pub fn next_deadline(&self) -> Option<Instant> {
if let Some((_, t)) = &self.ranking {
return Some(*t);
}
let mut d: Vec<Instant> = vec![];
if self.current.is_none() && !self.waiting.is_empty() {
if let Some(t) = self.collect_until {
d.push(t);
}
if let Some(first) = self.waiting.iter().map(|r| r.arrived_at).min() {
d.push(first + self.s.settle);
}
}
d.into_iter().min()
}
/// Wait for an ending utterance that may still be a call that should come first.
fn blocked(&self, now: Instant) -> bool {
let ending: Vec<Instant> = self.open.values().filter_map(|o| o.stopped_at).collect();
if ending.is_empty() {
return false;
}
let Some(first_arrival) = self.waiting.iter().map(|r| r.arrived_at).min() else { return false };
if now >= first_arrival + self.s.settle {
return false;
}
match self.s.kind {
PolicyKind::Latest => false,
PolicyKind::First | PolicyKind::InOrder => {
let head = self.waiting[0].ended_at;
ending.iter().any(|t| *t < head)
}
PolicyKind::Important => true,
}
}
/// Start the next answer if the policy allows one now. `rank`: `Some(winner)` once a ranking
/// finished or gave up.
fn choose(&mut self, now: Instant, rank: Option<Option<u64>>) -> Vec<Action> {
let mut out = vec![];
if self.current.is_some() || self.waiting.is_empty() || (self.ranking.is_some() && rank.is_none()) {
return out;
}
if rank.is_none() {
if let Some(t) = self.collect_until {
if now < t {
return out;
}
}
if self.blocked(now) {
return out;
}
}
let winner = match self.s.kind {
PolicyKind::First | PolicyKind::InOrder => 0,
PolicyKind::Latest => self.waiting.len() - 1,
PolicyKind::Important => {
let best = self.waiting.iter().map(|r| self.score(r)).max().expect("not empty");
let tied: Vec<usize> = (0..self.waiting.len()).filter(|&i| self.score(&self.waiting[i]) == best).collect();
match rank {
Some(Some(id)) if tied.iter().any(|&i| self.waiting[i].id == id) => {
tied.into_iter().find(|&i| self.waiting[i].id == id).expect("present")
}
// A ranking that failed, timed out, or named nobody still tied: the earliest-ended.
Some(_) => tied[0],
None if tied.len() >= 2 => {
let cands: Vec<Request> = tied.iter().map(|&i| self.waiting[i].clone()).collect();
self.ranking = Some((cands.iter().map(|r| r.id).collect(), now + self.s.rank_timeout));
out.push(Action::Rank(cands));
return out;
}
None => tied[0],
}
}
};
let chosen = self.waiting.remove(winner);
let others = match self.s.kind {
PolicyKind::InOrder => vec![],
PolicyKind::First => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Busy)).collect(),
PolicyKind::Latest => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Replaced)).collect(),
PolicyKind::Important => {
std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::LowerScore)).collect()
}
};
for (r, why) in others {
out.push(Action::Missed(r, why));
}
self.collect_until = None;
self.current = Some(chosen.clone());
out.push(Action::Answer(chosen));
out
}
}
#[cfg(test)]
mod tests {
use super::*;
const A: u64 = 1;
const B: u64 = 2;
const C: u64 = 3;
struct T {
p: Policy,
t0: Instant,
next_id: u64,
}
impl T {
fn new(kind: PolicyKind) -> Self {
Self::with(PolicySettings { kind, ..PolicySettings::default() })
}
fn with(s: PolicySettings) -> Self {
Self { p: Policy::new(s), t0: Instant::now(), next_id: 0 }
}
fn at(&self, ms: u64) -> Instant {
self.t0 + Duration::from_millis(ms)
}
/// A call from `speaker` that ended at `ended` ms and arrived at `arrived` ms.
fn call(&mut self, speaker: u64, direct: bool, ended: u64, arrived: u64) -> (u64, Vec<Action>) {
self.next_id += 1;
let r = Request { id: self.next_id, speaker, text: String::new(), direct, ended_at: self.at(ended),
arrived_at: self.at(arrived) };
let now = self.at(arrived);
(self.next_id, self.p.request(r, now))
}
}
fn answered(a: &[Action]) -> Vec<u64> {
a.iter().filter_map(|x| if let Action::Answer(r) = x { Some(r.id) } else { None }).collect()
}
fn missed(a: &[Action]) -> Vec<(u64, MissReason)> {
a.iter().filter_map(|x| if let Action::Missed(r, w) = x { Some((r.id, *w)) } else { None }).collect()
}
fn stopped(a: &[Action]) -> Vec<u64> {
a.iter().filter_map(|x| if let Action::StopAnswer(id) = x { Some(*id) } else { None }).collect()
}
#[test]
fn first_answers_at_once_and_drops_what_comes_while_busy() {
let mut t = T::new(PolicyKind::First);
let (a, out) = t.call(A, true, 0, 200);
assert_eq!(answered(&out), vec![a]);
let (b, out) = t.call(B, true, 300, 500);
assert_eq!(missed(&out), vec![(b, MissReason::Busy)]);
assert!(t.p.answer_done(a, t.at(2000)).is_empty());
let (c, out) = t.call(C, true, 2100, 2300);
assert_eq!(answered(&out), vec![c]);
}
#[test]
fn first_waits_for_an_earlier_ended_utterance_and_answers_it_if_it_is_a_call() {
let mut t = T::new(PolicyKind::First);
// B stopped talking at 100 ms but is still being transcribed; A ended at 150 ms.
t.p.utterance_open(B);
t.p.speaking_stopped(B, t.at(100));
let (a, out) = t.call(A, true, 150, 300);
assert!(answered(&out).is_empty(), "waits for B");
let (b, out) = t.call(B, true, 100, 500);
assert_eq!(answered(&out), vec![b], "B finished speaking first");
assert_eq!(missed(&out), vec![(a, MissReason::Busy)]);
}
#[test]
fn settling_ends_when_the_earlier_utterance_is_not_a_call_or_takes_too_long() {
let mut t = T::new(PolicyKind::First);
t.p.utterance_open(B);
t.p.speaking_stopped(B, t.at(100));
let (a, _) = t.call(A, true, 150, 300);
assert_eq!(answered(&t.p.utterance_closed(B, t.at(400))), vec![a]);
let mut t = T::new(PolicyKind::First);
t.p.utterance_open(B);
t.p.speaking_stopped(B, t.at(100));
let (a, _) = t.call(A, true, 150, 300);
assert_eq!(t.p.next_deadline(), Some(t.at(300 + 800)));
assert!(answered(&t.p.tick(t.at(1000))).is_empty());
assert_eq!(answered(&t.p.tick(t.at(1100))), vec![a]);
}
#[test]
fn an_utterance_still_being_spoken_or_ended_later_does_not_hold_up_the_answer() {
let mut t = T::new(PolicyKind::First);
t.p.utterance_open(B); // still talking
t.p.utterance_open(C);
t.p.speaking_stopped(C, t.at(400)); // ended after A
let (a, out) = t.call(A, true, 150, 300);
assert_eq!(answered(&out), vec![a]);
}
#[test]
fn in_order_follows_end_times_not_arrival_and_drops_the_oldest_when_full() {
let mut t = T::with(PolicySettings { kind: PolicyKind::InOrder, queue_max: 2, ..PolicySettings::default() });
let (a, out) = t.call(A, true, 0, 100);
assert_eq!(answered(&out), vec![a]);
let (c, _) = t.call(C, true, 900, 1000); // ended later, arrived first
let (b, _) = t.call(B, true, 600, 1500); // long utterance: ended earlier, arrived later
assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]);
assert_eq!(answered(&t.p.answer_done(b, t.at(3000))), vec![c]);
let (_, out) = t.call(A, true, 3100, 3200);
assert!(answered(&out).is_empty());
let (e, _) = t.call(B, true, 3300, 3400);
let (_f, out) = t.call(C, true, 3500, 3600);
assert_eq!(t.p.waiting(), 2);
assert_eq!(missed(&out).len(), 1, "third waiting request pushes the oldest out");
assert_eq!(answered(&t.p.answer_done(c, t.at(4000))), vec![e]);
}
#[test]
fn latest_interrupts_for_a_newer_request_and_drops_older_ones() {
let mut t = T::new(PolicyKind::Latest);
let (a, _) = t.call(A, true, 0, 100);
let (b, out) = t.call(B, true, 500, 700);
assert_eq!(stopped(&out), vec![a]);
assert_eq!(missed(&out), vec![(a, MissReason::Interrupted)]);
assert_eq!(answered(&out), vec![b]);
// A late final from before B's end is not newer.
let (c, out) = t.call(C, true, 400, 900);
assert_eq!(missed(&out), vec![(c, MissReason::Replaced)]);
assert!(stopped(&out).is_empty());
// The stopped answer's late "done" changes nothing.
assert!(t.p.answer_done(a, t.at(1000)).is_empty());
assert_eq!(t.p.current(), Some(b));
}
#[test]
fn latest_answers_the_newest_of_several_waiting() {
let mut t = T::new(PolicyKind::Latest);
t.p.utterance_open(C);
let (a, out) = t.call(A, true, 0, 100);
assert_eq!(answered(&out), vec![a], "latest never settles");
let (b, _) = t.call(B, true, 200, 300);
assert_eq!(t.p.current(), Some(b));
}
#[test]
fn important_collects_then_answers_the_best_by_priority_then_wake_word() {
let mut s = PolicySettings { kind: PolicyKind::Important, ..PolicySettings::default() };
s.priorities.insert(C, 5);
let mut t = T::with(s);
let (a, out) = t.call(A, true, 0, 100);
assert!(answered(&out).is_empty(), "collecting for 700 ms");
let (b, _) = t.call(B, false, 100, 200);
let (c, _) = t.call(C, false, 200, 300);
assert_eq!(t.p.next_deadline(), Some(t.at(800)));
let out = t.p.tick(t.at(800));
assert_eq!(answered(&out), vec![c], "priority wins over the wake word");
let mut m = missed(&out);
m.sort_by_key(|(id, _)| *id);
assert_eq!(m, vec![(a, MissReason::LowerScore), (b, MissReason::LowerScore)]);
}
#[test]
fn important_asks_for_a_ranking_only_on_a_tie_and_falls_back_on_timeout() {
let mut t = T::new(PolicyKind::Important);
let (a, _) = t.call(A, true, 0, 100);
let (b, _) = t.call(B, true, 50, 200);
let out = t.p.tick(t.at(800));
let ranks: Vec<Vec<u64>> = out.iter().filter_map(|x| if let Action::Rank(c) = x {
Some(c.iter().map(|r| r.id).collect()) } else { None }).collect();
assert_eq!(ranks, vec![vec![a, b]]);
assert!(answered(&out).is_empty());
assert_eq!(answered(&t.p.ranked(&[b, a], t.at(900))), vec![b]);
let mut t = T::new(PolicyKind::Important);
let (a, _) = t.call(A, true, 0, 100);
let (_b, _) = t.call(B, true, 50, 200);
t.p.tick(t.at(800));
assert_eq!(t.p.next_deadline(), Some(t.at(800 + 1500)));
assert_eq!(answered(&t.p.tick(t.at(2300))), vec![a], "timeout: earliest-ended wins");
assert!(t.p.ranked(&[2], t.at(2400)).is_empty(), "a late ranking is ignored");
// One candidate: no ranking, no extra delay beyond collecting.
let mut t = T::new(PolicyKind::Important);
let (a, _) = t.call(A, true, 0, 100);
assert_eq!(answered(&t.p.tick(t.at(800))), vec![a]);
}
#[test]
fn important_interrupts_only_for_a_higher_score_and_otherwise_answers_after() {
let mut s = PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() };
s.priorities.insert(C, 1);
let mut t = T::with(s);
let (a, out) = t.call(A, false, 0, 100);
assert_eq!(answered(&out), vec![a]);
let (b, out) = t.call(B, false, 200, 300);
assert!(stopped(&out).is_empty(), "same score: keep going");
assert_eq!(answered(&t.p.answer_done(a, t.at(1000))), vec![b]);
let (c, out) = t.call(C, false, 1100, 1200);
assert_eq!(stopped(&out), vec![b]);
assert_eq!(missed(&out), vec![(b, MissReason::Interrupted)]);
assert_eq!(answered(&out), vec![c]);
}
#[test]
fn stop_ends_the_answer_and_drops_the_queue_in_every_policy() {
for kind in [PolicyKind::First, PolicyKind::InOrder, PolicyKind::Latest, PolicyKind::Important] {
let mut t = T::with(PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() });
let _ = t.call(A, true, 0, 100);
let _ = t.call(B, true, 50, 200);
let running = t.p.current().expect("an answer runs");
let out = t.p.stop();
assert_eq!(stopped(&out), vec![running], "{kind:?}");
assert!(missed(&out).iter().any(|(id, _)| *id == running), "{kind:?}");
assert!(missed(&out).iter().all(|(_, w)| *w == MissReason::Stopped), "{kind:?}");
assert_eq!(t.p.current(), None);
assert_eq!(t.p.waiting(), 0);
}
}
}

View File

@@ -5,7 +5,12 @@
//! are ignored.
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::calls::{CallMode, CallSettings};
use crate::policy::{PolicyKind, PolicySettings};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatChannelSettings {
@@ -46,7 +51,7 @@ pub struct VoiceSettings {
pub listen_to_bots: bool,
/// Posted in the voice channel's chat on every join (privacy.md).
pub join_notice: String,
/// Wake words; passed to the STT as a hint now, used for call detection from M4.
/// Wake words: the STT hint and the voice wake words of call detection (`conversation.spec.md`).
pub wake_words: Vec<String>,
/// Voice worker STT settings (voice_worker.spec.md); the worker validates them.
pub stt: Map<String, Value>,
@@ -68,6 +73,11 @@ pub struct Settings {
pub voice: VoiceSettings,
pub chat_channels: Vec<ChatChannelSettings>,
pub voice_worker: WorkerSettings,
/// Call detection for voice (`conversation.spec.md`); its wake words are `voice.wakeWords`.
pub call: CallSettings,
/// Wake words for chat; `None` uses `voice.wakeWords`.
pub chat_wake_words: Option<Vec<String>>,
pub response: PolicySettings,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -106,6 +116,9 @@ impl Default for Settings {
cwd: Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src"),
args: vec![],
},
call: CallSettings::default(),
chat_wake_words: None,
response: PolicySettings::default(),
}
}
}
@@ -169,6 +182,107 @@ fn get_str_list(m: Option<&Map<String, Value>>, key: &str, path: &str, default:
}
}
fn get_ms(m: Option<&Map<String, Value>>, key: &str, path: &str, default: Duration, max: u64)
-> Result<Duration, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(v) => match v.as_u64() {
Some(n) if n <= max => Ok(Duration::from_millis(n)),
_ => err(format!("{path}.{key} must be an integer 0-{max} (milliseconds)")),
},
}
}
fn snowflake_list(m: Option<&Map<String, Value>>, key: &str, path: &str) -> Result<Vec<u64>, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(vec![]),
Some(Value::Array(a)) => a
.iter()
.map(snowflake)
.collect::<Option<Vec<_>>>()
.ok_or_else(|| SettingsError(format!("{path}.{key} must be a list of Discord user IDs"))),
Some(_) => err(format!("{path}.{key} must be a list of Discord user IDs")),
}
}
fn clean_words(words: Vec<String>) -> Vec<String> {
words.into_iter().map(|w| w.trim().to_owned()).filter(|w| !w.is_empty()).collect()
}
fn parse_call(raw: &Map<String, Value>, wake_words: &[String], d: &CallSettings)
-> Result<(CallSettings, Option<Vec<String>>), SettingsError> {
let call = section(raw, "call")?;
let similarity = match call.and_then(|m| m.get("similarity")) {
None => d.similarity,
Some(v) => match v.as_f64() {
Some(x) if (0.0..=0.5).contains(&x) => x,
_ => return err("call.similarity must be a number 0-0.5"),
},
};
let mode = match get_str(call, "mode", "call", "wakeWord")?.as_str() {
"wakeWord" => CallMode::WakeWord,
"addressed" => CallMode::Addressed,
"everything" => CallMode::Everything,
_ => return err("call.mode must be wakeWord, addressed or everything"),
};
let chat_wake_words = match call.and_then(|m| m.get("chatWakeWords")) {
None | Some(Value::Null) => None,
Some(_) => Some(clean_words(get_str_list(call, "chatWakeWords", "call", &[])?)),
};
let stop_words = clean_words(get_str_list(call, "stopWords", "call", &d.stop_words)?);
Ok((
CallSettings {
wake_words: wake_words.to_vec(),
similarity,
mode,
designated: snowflake_list(call, "designated", "call")?.into_iter().collect(),
designated_only: get_bool(call, "designatedOnly", "call", d.designated_only)?,
designated_no_wake_word: get_bool(call, "designatedNoWakeWord", "call", d.designated_no_wake_word)?,
stop_words,
},
chat_wake_words,
))
}
fn parse_response(raw: &Map<String, Value>, d: &PolicySettings) -> Result<PolicySettings, SettingsError> {
let r = section(raw, "response")?;
let kind = match get_str(r, "policy", "response", "first")?.as_str() {
"first" => PolicyKind::First,
"inOrder" => PolicyKind::InOrder,
"latest" => PolicyKind::Latest,
"important" => PolicyKind::Important,
_ => return err("response.policy must be first, inOrder, latest or important"),
};
let queue_max = match r.and_then(|m| m.get("queueMax")) {
None => d.queue_max,
Some(v) => match v.as_u64() {
Some(n @ 1..=20) => n as usize,
_ => return err("response.queueMax must be an integer 1-20"),
},
};
let mut priorities = HashMap::new();
match r.and_then(|m| m.get("priorities")) {
None => {}
Some(Value::Object(p)) => {
for (k, v) in p {
let id = snowflake(&Value::String(k.clone()))
.ok_or_else(|| SettingsError("response.priorities keys must be Discord user IDs".into()))?;
let n = v.as_i64().ok_or_else(|| SettingsError("response.priorities values must be integers".into()))?;
priorities.insert(id, n);
}
}
Some(_) => return err("response.priorities must be an object of user ID to priority"),
}
Ok(PolicySettings {
kind,
queue_max,
collect: get_ms(r, "collectMs", "response", d.collect, 3000)?,
settle: get_ms(r, "settleMs", "response", d.settle, 3000)?,
priorities,
rank_timeout: d.rank_timeout,
})
}
/// Discord's rule for command names: 1-32 lowercase letters, digits, `-` or `_`.
fn valid_command_name(s: &str) -> bool {
let n = s.chars().count();
@@ -196,11 +310,9 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
_ => return err("voice.maxSpeakers must be an integer 1-10"),
},
};
let wake_words: Vec<String> = get_str_list(voice, "wakeWords", "voice", &d.voice.wake_words)?
.into_iter()
.map(|w| w.trim().to_owned())
.filter(|w| !w.is_empty())
.collect();
let wake_words = clean_words(get_str_list(voice, "wakeWords", "voice", &d.voice.wake_words)?);
let (call, chat_wake_words) = parse_call(raw, &wake_words, &d.call)?;
let response = parse_response(raw, &d.response)?;
let join_notice = get_str(voice, "joinNotice", "voice", &d.voice.join_notice)?.trim().to_owned();
if join_notice.is_empty() {
return err("voice.joinNotice must not be empty: people must be told they are transcribed");
@@ -265,6 +377,9 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
},
args: get_str_list(worker, "args", "voiceWorker", &d.voice_worker.args)?,
},
call,
chat_wake_words,
response,
})
}
@@ -347,6 +462,43 @@ mod tests {
}
}
#[test]
fn call_and_response_sections_are_read_and_checked() {
let s = parse_settings(&json!({
"voice": {"wakeWords": ["자비스", "javis"]},
"call": {"similarity": 0.3, "mode": "addressed", "designated": [ID], "designatedOnly": true,
"designatedNoWakeWord": true, "stopWords": ["멈춰", " "], "chatWakeWords": ["봇"]},
"response": {"policy": "important", "queueMax": 3, "collectMs": 500, "settleMs": 0,
"priorities": {ID: 2}}
})).unwrap();
assert_eq!(s.call.wake_words, vec!["자비스", "javis"]);
assert_eq!(s.call.similarity, 0.3);
assert_eq!(s.call.mode, CallMode::Addressed);
assert!(s.call.designated.contains(&IDN));
assert!(s.call.designated_only && s.call.designated_no_wake_word);
assert_eq!(s.call.stop_words, vec!["멈춰"]);
assert_eq!(s.chat_wake_words, Some(vec!["봇".to_string()]));
assert_eq!(s.response.kind, PolicyKind::Important);
assert_eq!(s.response.queue_max, 3);
assert_eq!(s.response.collect, Duration::from_millis(500));
assert_eq!(s.response.settle, Duration::ZERO);
assert_eq!(s.response.priorities.get(&IDN), Some(&2));
let cases = [
(json!({"call": {"similarity": 0.9}}), "call.similarity"),
(json!({"call": {"mode": "sometimes"}}), "call.mode"),
(json!({"call": {"designated": ["1"]}}), "call.designated"),
(json!({"response": {"policy": "random"}}), "response.policy"),
(json!({"response": {"queueMax": 0}}), "response.queueMax"),
(json!({"response": {"collectMs": 5000}}), "response.collectMs"),
(json!({"response": {"priorities": {"x": 1}}}), "response.priorities"),
];
for (raw, key) in cases {
let e = parse_settings(&raw).unwrap_err();
assert!(e.0.contains(key), "{raw} -> {e}");
}
}
#[test]
fn null_ids_clear_them() {
let s = parse_settings(&json!({"discord": {"guildId": null, "voiceChannelId": null}})).unwrap();

File diff suppressed because one or more lines are too long