AnyBot/src/app/voice_ui.rs

677 lines
31 KiB
Rust
Raw Normal View History

Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// 語音 in the window: 語音輸入 (the mic), 會議錄音, 語音聊天 and 朗讀, and 設定 › 語音.
// Only recording and playing happen here. The words and the sound come from the brain's voice
// service (speech.rs): this AnyBot's own when it is the brain, else its brain's, through the
// account. With no service set up there is no mic, no 語音聊天 and no 朗讀 at all.
use super::attach_ui::CallPhase;
use super::*;
use crate::model::{VoiceEngine, VoiceKind};
use crate::remote::Cmd;
use crate::speech;
/// Where this window's voice goes.
#[derive(Clone)]
pub(super) enum VoiceVia {
/// A screen of another AnyBot: its brain, through the account.
Brain(crate::remote::Settings),
/// This AnyBot is the brain: its own 設定 › 語音.
Here(speech::Engines),
}
impl VoiceVia {
/// A recording as text.
pub(super) fn hear(&self, file: &std::path::Path, lang: &str) -> Result<String, String> {
let audio = std::fs::read(file).map_err(|e| format!("讀不到錄音:{e}"))?;
let name = format!("voice.{}", file.extension().and_then(|e| e.to_str()).unwrap_or("m4a"));
match self {
VoiceVia::Brain(s) => crate::remote::sync_voice_transcribe(s, &audio, &name, lang),
VoiceVia::Here(e) => match &e.listen {
Some(l) => speech::transcribe(l, &audio, &name, lang, &crate::i18n::lang()),
None => Err(speech::NOT_SET.into()),
},
}
}
/// Words as MP3.
pub(super) fn sound(&self, text: &str, voice: &str, lang: &str, speed: f32) -> Result<Vec<u8>, String> {
match self {
VoiceVia::Brain(s) => crate::remote::sync_voice_speech(s, &serde_json::json!({"text": text, "voice": voice, "lang": lang, "speed": speed})),
VoiceVia::Here(e) => match &e.speak {
Some(sp) => speech::speak(sp, text, voice, lang, speed),
None => Err(speech::NOT_SET.into()),
},
}
}
fn voices(&self) -> Result<Vec<(String, String)>, String> {
match self {
VoiceVia::Brain(s) => crate::remote::sync_voice_voices(s),
VoiceVia::Here(e) => e.speak.as_ref().map(speech::voices).unwrap_or_else(|| Err(speech::NOT_SET.into())),
}
}
}
/// 會議錄音 prompt: what the bot is asked to do with the transcript.
const MEETING_ASK: &str = "這是剛才會議的文字記錄,請整理:重點、做了哪些決定、待辦事項(誰、做什麼、什麼時候)。";
/// What 試聽 says.
const SAMPLE: &str = "你好,我是你的 Bot。這是我說話的聲音。";
#[derive(Default)]
pub struct VoiceUi {
/// What went wrong getting or playing sound (a thread's), shown under the message box.
note: Arc<Mutex<Option<String>>>,
/// 會議錄音 being turned into text here (on the brain): (bot, answer).
meetings: Vec<(u64, Receiver<Result<String, String>>)>,
/// 設定 › 語音 › 試試看: recording, then waiting for its text, then what was heard.
test_rec: Option<crate::voice::Recording>,
test_rx: Option<Receiver<Result<String, String>>>,
test_said: Option<Result<String, String>>,
/// 試聽's trouble.
test_note: Arc<Mutex<Option<String>>>,
/// The voices 說 offers (loaded when asked).
voices_rx: Option<Receiver<Result<Vec<(String, String)>, String>>>,
pub(super) voice_list: Vec<(String, String)>,
voices_err: String,
}
impl App {
pub(super) fn voice_via(&self) -> VoiceVia {
if self.mir.on {
VoiceVia::Brain(self.state.remote.clone())
} else {
VoiceVia::Here(speech::Engines::of(&self.state))
}
}
/// 設定 › 語音 has 聽 (on a screen: the brain's, whose keys show as set).
pub(super) fn can_listen(&self) -> bool {
speech::resolve(&self.state.voice.listen, &self.state, false).is_some()
}
pub(super) fn can_speak(&self) -> bool {
speech::resolve(&self.state.voice.speak, &self.state, true).is_some()
}
// ---------- 語音輸入、會議錄音 ----------
pub(super) fn voice_recording(&self, bot_id: u64) -> Option<Instant> {
self.att.voice.as_ref().filter(|(id, _)| *id == bot_id).map(|(_, r)| r.started)
}
pub(super) fn voice_busy(&self) -> bool {
self.att.voice_rx.is_some()
}
/// The mic button: start, or stop and turn the recording into text.
pub(super) fn voice_toggle(&mut self, ctx: &egui::Context, bot_id: u64) {
if self.voice_stop(ctx) {
return;
}
if !self.can_listen() {
self.att.error = Some(speech::NOT_SET.into());
return;
}
crate::voice::stop_speaking();
match crate::voice::start() {
Ok(r) => self.att.voice = Some((bot_id, r)),
Err(e) => self.att.error = Some(e),
}
}
/// Stop the recording that is running and turn it into text (false: none was running).
fn voice_stop(&mut self, ctx: &egui::Context) -> bool {
let Some((id, rec)) = self.att.voice.take() else { return false };
let lang = self.state.bot(id).map(|b| b.voice_lang.clone()).unwrap_or_default();
let via = self.voice_via();
if std::mem::take(&mut self.att.meeting) {
self.meeting_hand_over(id, rec, lang, via);
return true;
}
let (tx, rx) = channel();
self.att.voice_rx = Some(rx);
let c = ctx.clone();
std::thread::spawn(move || {
let r = rec.finish().and_then(|f| {
let t = via.hear(&f, &lang);
let _ = std::fs::remove_file(&f);
t
});
let _ = tx.send((id, r));
c.request_repaint();
});
true
}
/// 會議記錄: a long recording that becomes a transcript for the bot to summarize.
pub(super) fn start_meeting(&mut self, ctx: &egui::Context, bot_id: u64) {
if self.att.voice.is_some() {
return;
}
self.att.meeting = true;
self.voice_toggle(ctx, bot_id);
if self.att.voice.is_none() {
self.att.meeting = false;
}
}
pub(super) fn meeting_on(&self) -> bool {
self.att.meeting && self.att.voice.is_some()
}
/// A meeting can run longer than the account lets one request wait (35 s): the recording goes
/// to the brain, which turns it into text when it can and gives it to the bot itself.
fn meeting_hand_over(&mut self, bot: u64, rec: crate::voice::Recording, lang: String, via: VoiceVia) {
let VoiceVia::Brain(s) = via else {
match rec.finish() {
Ok(f) => self.meeting_job(bot, f, lang, true),
Err(e) => self.att.error = Some(e),
}
return;
};
let note = self.vo.note.clone();
std::thread::spawn(move || {
let r = rec.finish().and_then(|f| {
let bytes = std::fs::read(&f).map_err(|e| e.to_string());
let _ = std::fs::remove_file(&f);
let ext = f.extension().and_then(|e| e.to_str()).unwrap_or("m4a").to_string();
let path = crate::remote::sync_upload(&s, bot, &format!("會議錄音.{ext}"), &bytes?)?;
crate::remote::sync_post(&s, "act", &serde_json::json!({"bot": bot, "action": "meeting", "path": path, "lang": lang})).map(|_| ())
});
*note.lock().unwrap() = Some(match r {
Ok(()) => "會議錄音交給大腦了:轉成文字後會自動交給 Bot 整理。".into(),
Err(e) => format!("會議錄音沒能交給大腦:{e}"),
});
});
}
/// Here, on the brain: the recording becomes text, then goes to the bot with the ask.
pub(super) fn meeting_job(&mut self, bot: u64, file: PathBuf, lang: String, remove: bool) {
let via = VoiceVia::Here(speech::Engines::of(&self.state));
let (tx, rx) = channel();
self.vo.meetings.push((bot, rx));
std::thread::spawn(move || {
let r = via.hear(&file, &lang);
if remove {
let _ = std::fs::remove_file(&file);
}
let _ = tx.send(r);
});
}
/// Put the text where the person was typing; hand finished meetings to their bot.
pub(super) fn voice_poll(&mut self, ctx: &egui::Context) {
let max = if self.att.meeting { crate::voice::MEETING_MAX_SECS } else { crate::voice::MAX_SECS };
if self.att.voice.as_ref().is_some_and(|(_, r)| r.started.elapsed().as_secs() >= max) {
// What was recorded up to the limit is kept and turned into text like any recording.
self.att.error = Some(format!("錄音最長 {},已經停止;錄到的部分正在轉成文字。", crate::voice::length_words(max)));
self.voice_stop(ctx);
}
if let Some(e) = self.vo.note.lock().unwrap().take() {
self.att.error = Some(e);
}
let Some(rx) = &self.att.voice_rx else { return };
if let Ok((id, r)) = rx.try_recv() {
self.att.voice_rx = None;
match r {
Ok(t) if t.is_empty() => self.att.error = Some("沒有聽到說話。".into()),
Ok(t) => {
let d = self.drafts.entry(id).or_default();
if !d.is_empty() && !d.ends_with([' ', '\n']) {
d.push(' ');
}
d.push_str(&t);
}
Err(e) => self.att.error = Some(e),
}
}
}
pub(super) fn meetings_poll(&mut self, ctx: &egui::Context) {
let mut done = vec![];
self.vo.meetings.retain(|(bot, rx)| match rx.try_recv() {
Ok(r) => {
done.push((*bot, r));
false
}
Err(std::sync::mpsc::TryRecvError::Empty) => true,
Err(_) => false,
});
for (bot, r) in done {
let stored = r.and_then(|t| if t.is_empty() { Err("錄音裡沒有聽到說話".into()) } else { Ok(t) }).and_then(|t| {
let dir = std::env::temp_dir().join("anybot-meetings");
let _ = std::fs::create_dir_all(&dir);
let file = dir.join(format!("會議記錄 {}.txt", chrono::Local::now().format("%Y-%m-%d %H%M")));
std::fs::write(&file, &t).map_err(|e| e.to_string())?;
let a = crate::attach::store(bot, &file);
let _ = std::fs::remove_file(&file);
a
});
match stored {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
Ok(a) => self.remote_cmd(ctx, Cmd::Send { bot, text: MEETING_ASK.into(), attachments: vec![a.path], from: String::new(), memories: None, member: false }),
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// Said in the chat: the person may be at another screen, or the phone.
Err(e) => {
if let Some(b) = self.state.bot_mut(bot) {
let mut m = Message::assistant(&format!("會議錄音沒能轉成文字:{e}"), "");
m.error = true;
b.messages.push(m);
}
self.mark();
}
}
}
}
// ---------- 朗讀 ----------
/// 朗讀每個回答: the answer of a turn that just ended well, read on this computer. Not in a
/// call (it reads its own answers), and not on a brain without a window: nobody hears it there,
/// and a server's voice service would be paid for nothing.
pub(super) fn read_reply(&mut self, bot_id: u64) {
if self.demo || self.headless || !self.can_speak() {
return;
}
let in_call = self.call_state().map(|c| c.0 == bot_id).unwrap_or(false);
let answer = self.state.bot(bot_id).filter(|b| b.speak_replies && !in_call).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty() && !m.error)).map(|m| m.text.clone());
if let Some(a) = answer {
self.read_aloud(bot_id, &a);
}
}
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
/// Read `text` aloud with this bot's voice, speed and language.
pub(super) fn read_aloud(&mut self, bot_id: u64, text: &str) {
let Some(b) = self.state.bot(bot_id) else { return };
let (voice, lang, speed) = (b.voice.clone(), b.voice_lang.clone(), if b.voice_rate > 0.0 { b.voice_rate } else { 1.0 });
let (via, text) = (self.voice_via(), text.to_string());
crate::voice::say(move || via.sound(&text, &voice, &lang, speed), self.vo.note.clone());
}
// ---------- 通話模式 ----------
pub(super) fn call_start(&mut self, bot_id: u64) {
if !self.can_listen() || !self.can_speak() {
self.att.error = Some(speech::NOT_SET.into());
return;
}
crate::voice::stop_speaking();
self.att.call = Some((bot_id, CallPhase::Listening));
self.att.call_rec = None;
self.att.call_rx = None;
}
pub(super) fn call_end(&mut self) {
if let Some(r) = self.att.call_rec.take() {
r.cancel();
}
crate::voice::stop_speaking();
self.att.call = None;
self.att.call_rx = None;
}
pub(super) fn call_state(&self) -> Option<(u64, CallPhase)> {
self.att.call
}
/// Listen → understand → the bot answers → it's read aloud → listen again.
pub(super) fn call_poll(&mut self, ctx: &egui::Context) {
let Some((bot_id, phase)) = self.att.call else { return };
ctx.request_repaint_after(std::time::Duration::from_millis(150));
match phase {
CallPhase::Listening => {
if self.att.call_rec.is_none() {
match crate::voice::listen() {
Ok(r) => self.att.call_rec = Some(r),
Err(e) => {
self.att.error = Some(e);
self.call_end();
}
}
return;
}
if self.att.call_rec.as_mut().map(|r| r.done()).unwrap_or(false) {
let rec = self.att.call_rec.take().unwrap();
let lang = self.state.bot(bot_id).map(|b| b.voice_lang.clone()).unwrap_or_default();
let via = self.voice_via();
let (tx, rx) = channel();
self.att.call_rx = Some(rx);
let c = ctx.clone();
std::thread::spawn(move || {
let r = rec.finish().and_then(|f| {
let t = via.hear(&f, &lang);
let _ = std::fs::remove_file(&f);
t
});
let _ = tx.send(r);
c.request_repaint();
});
self.att.call = Some((bot_id, CallPhase::Transcribing));
}
}
CallPhase::Transcribing => {
let Some(rx) = &self.att.call_rx else { return };
if let Ok(r) = rx.try_recv() {
self.att.call_rx = None;
match r {
Ok(t) if !t.trim().is_empty() => {
self.drafts.insert(bot_id, t);
// Before sending: here the answer's (empty) message is added at once.
self.att.call_from = self.state.bot(bot_id).map(|b| b.messages.len()).unwrap_or(0);
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
self.send(ctx, bot_id);
self.att.call_asked = Some(std::time::Instant::now());
self.att.call_seen = false;
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
self.att.call = Some((bot_id, CallPhase::Thinking));
}
// Nothing said: keep listening; a real error ends the call.
Err(e) if !e.contains("沒有聽到") && !e.contains("沒有錄到") => {
self.att.error = Some(e);
self.call_end();
}
_ => self.att.call = Some((bot_id, CallPhase::Listening)),
}
}
}
CallPhase::Thinking => {
if self.streams.contains_key(&bot_id) || self.approvals.contains_key(&bot_id) {
self.att.call_seen = true;
return;
}
// Read the answer to what was just said: one after it in the chat. On a screen of a
// brain the question goes to the brain first and the bot shows up as working only a
// moment later; until then "not working" isn't "done", and the last answer in the
// chat is the one before (it was read instead, and the new one never).
let answer = self.state.bot(bot_id).and_then(|b| call_answer(&b.messages, self.att.call_from));
if let Some(a) = answer {
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// Answers are read here, not by the 朗讀 switch (no double reading).
self.read_aloud(bot_id, &a);
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
self.att.call = Some((bot_id, CallPhase::Speaking));
} else if self.att.call_seen || self.att.call_asked.map(|t| t.elapsed() > CALL_NO_START).unwrap_or(true) {
// It worked and said nothing, or the question never got going: listen again.
self.att.call = Some((bot_id, CallPhase::Listening));
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
}
}
CallPhase::Speaking => {
if !crate::voice::speaking() {
// A read-aloud that failed ends the call, said under the box.
if self.vo.note.lock().unwrap().is_some() {
self.call_end();
} else {
self.att.call = Some((bot_id, CallPhase::Listening));
}
}
}
}
}
// ---------- 設定 › 語音 ----------
pub(super) fn voice_settings(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
hint(ui, t("語音由大腦處理:每台電腦和手機都把錄音送到這裡設定的服務轉成文字,朗讀也一樣。沒有設定時,麥克風、語音聊天、會議錄音和朗讀都不會出現。"), p);
if self.mir.on {
hint(ui, t("這些是大腦的設定,改了會存在大腦上;金鑰也只放在大腦。"), p);
}
ui.add_space(4.0);
let mut v = self.state.voice.clone();
setting_card(ui, p, |ui| {
setting_title(ui, "聽", "把你說的話變成文字:語音輸入、語音聊天和會議錄音都用它。", p);
engine_form(ui, p, &mut v.listen, false, "listen");
if v.listen.kind != VoiceKind::Off {
let ok = speech::resolve(&v.listen, &self.state, false).is_some();
ui.add_space(4.0);
self.status_line(ui, ok, speech::missing(&v.listen, false));
if ok {
self.listen_test(ui);
}
}
});
ui.add_space(10.0);
setting_card(ui, p, |ui| {
setting_title(ui, "說", "把回答唸出來:朗讀和語音聊天都用它。", p);
engine_form(ui, p, &mut v.speak, true, "speak");
if v.speak.kind == VoiceKind::Off {
return;
}
self.voice_picker(ui, &mut v.speak.voice, "speak-voice");
let ok = speech::resolve(&v.speak, &self.state, true).is_some();
ui.add_space(4.0);
self.status_line(ui, ok, speech::missing(&v.speak, true));
if !ok {
return;
}
ui.horizontal(|ui| {
if ui.button(t("試聽")).clicked() {
let via = self.voice_via();
let voice = v.speak.voice.clone();
*self.vo.test_note.lock().unwrap() = None;
crate::voice::say(move || via.sound(SAMPLE, &voice, "", 1.0), self.vo.test_note.clone());
}
if crate::voice::speaking() {
chat_ui::spinner(ui, 14.0, p.text3);
ui.ctx().request_repaint_after(std::time::Duration::from_millis(200));
}
if let Some(e) = self.vo.test_note.lock().unwrap().clone() {
ui.label(RichText::new(e).size(FONT_XS).color(p.danger));
}
});
});
if v != self.state.voice {
self.state.voice = v;
self.mark();
}
}
fn status_line(&self, ui: &mut egui::Ui, ok: bool, why: &str) {
let p = self.pal;
let (mark, text, col) = if ok { ("✓", t("可以用"), Color32::from_rgb(0x2e, 0xa0, 0x43)) } else { ("·", t(why), p.text3) };
ui.label(RichText::new(format!("{mark} {text}")).size(FONT_SM).color(col));
}
/// 試試看: record a sentence, show what the service heard.
fn listen_test(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
if let Some(rx) = &self.vo.test_rx {
if let Ok(r) = rx.try_recv() {
self.vo.test_rx = None;
self.vo.test_said = Some(r);
}
}
ui.horizontal(|ui| {
if self.vo.test_rec.is_some() {
if ui.button(t("● 說完了")).clicked() {
let rec = self.vo.test_rec.take().unwrap();
let via = self.voice_via();
let (tx, rx) = channel();
self.vo.test_rx = Some(rx);
let c = ui.ctx().clone();
std::thread::spawn(move || {
let r = rec.finish().and_then(|f| {
let t = via.hear(&f, "");
let _ = std::fs::remove_file(&f);
t
});
let _ = tx.send(r);
c.request_repaint();
});
}
ui.label(RichText::new(t("正在錄音:說一句話,再按「說完了」")).size(FONT_XS).color(p.text3));
ui.ctx().request_repaint_after(std::time::Duration::from_millis(200));
} else if self.vo.test_rx.is_some() {
chat_ui::spinner(ui, 14.0, p.text3);
ui.label(RichText::new(t("聽懂中…")).size(FONT_XS).color(p.text3));
ui.ctx().request_repaint_after(std::time::Duration::from_millis(200));
} else if ui.button(t("試試看(說一句話)")).clicked() {
crate::voice::stop_speaking();
self.vo.test_said = None;
match crate::voice::start() {
Ok(r) => self.vo.test_rec = Some(r),
Err(e) => self.vo.test_said = Some(Err(e)),
}
}
});
match &self.vo.test_said {
Some(Ok(text)) if text.is_empty() => {
ui.label(RichText::new(t("沒有聽到說話。")).size(FONT_SM).color(p.text3));
}
Some(Ok(text)) => {
ui.label(RichText::new(format!("{}「{text}」", t("聽到:"))).size(FONT_SM).color(p.text));
}
Some(Err(e)) => {
ui.label(RichText::new(e).size(FONT_SM).color(p.danger));
}
None => {}
}
}
/// The voice: picked from what the service offers (loaded when asked), or typed.
pub(super) fn voice_picker(&mut self, ui: &mut egui::Ui, voice: &mut String, salt: &str) {
let p = self.pal;
if let Some(rx) = &self.vo.voices_rx {
if let Ok(r) = rx.try_recv() {
self.vo.voices_rx = None;
match r {
Ok(list) => {
self.vo.voice_list = list;
self.vo.voices_err.clear();
}
Err(e) => self.vo.voices_err = e,
}
}
}
// Somewhere narrow (the bot's side panel) the box gets a line of its own: the one long row
// was wider than the panel, and that pushed the whole panel under the chat.
if ui.available_width() < VOICE_ROW_MIN_WIDTH {
ui.horizontal(|ui| {
ui.label(RichText::new(t("聲音")).size(FONT_SM).color(p.text2));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| self.voice_list_button(ui, voice, salt));
});
ui.add(egui::TextEdit::singleline(voice).hint_text(t("留空:服務預設的聲音")).desired_width(f32::INFINITY));
} else {
ui.horizontal(|ui| {
ui.label(RichText::new(t("聲音")).size(FONT_SM).color(p.text2));
ui.add(egui::TextEdit::singleline(voice).hint_text(t("留空:服務預設的聲音")).desired_width(200.0));
self.voice_list_button(ui, voice, salt);
});
}
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
if !self.vo.voices_err.is_empty() {
ui.label(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3));
}
}
/// 「選一個…」 once the service's voices are loaded, 「載入聲音清單」 before.
fn voice_list_button(&mut self, ui: &mut egui::Ui, voice: &mut String, salt: &str) {
let p = self.pal;
if !self.vo.voice_list.is_empty() {
egui::ComboBox::from_id_salt(salt).selected_text(t("選一個…")).height(320.0).show_ui(ui, |ui| {
for (id, name) in &self.vo.voice_list {
let label = if name.is_empty() || name == id { id.clone() } else { format!("{name}({id})") };
if ui.selectable_label(voice == id, label).clicked() {
*voice = id.clone();
}
}
});
} else if self.vo.voices_rx.is_some() {
chat_ui::spinner(ui, 14.0, p.text3);
} else if ui.button(t("載入聲音清單")).clicked() {
let via = self.voice_via();
let (tx, rx) = channel();
self.vo.voices_rx = Some(rx);
let c = ui.ctx().clone();
std::thread::spawn(move || {
let _ = tx.send(via.voices());
c.request_repaint();
});
}
}
}
/// The answer to what was said in a call: the last thing the bot wrote after message `from` (the
/// chat's length when it was sent), never an answer from before it.
fn call_answer(msgs: &[Message], from: usize) -> Option<String> {
msgs.iter().skip(from).rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty()).map(|m| m.text.clone())
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
}
/// How long a call waits for the bot to start on what was said before it listens again (a brain
/// reached through the account server shows it working within a second or two).
const CALL_NO_START: std::time::Duration = std::time::Duration::from_secs(45);
/// Room the one-row voice picker needs (聲音, a 200 px box, 載入聲音清單); narrower, it takes two.
const VOICE_ROW_MIN_WIDTH: f32 = 360.0;
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
/// One side of 設定 › 語音: which service, and how to reach it.
fn engine_form(ui: &mut egui::Ui, p: Palette, e: &mut VoiceEngine, speak: bool, salt: &str) {
ui.horizontal(|ui| {
ui.label(RichText::new(t("服務")).size(FONT_SM).color(p.text2));
egui::ComboBox::from_id_salt(("voice-kind", salt)).selected_text(t(speech::label(e.kind))).show_ui(ui, |ui| {
for k in [VoiceKind::Off, VoiceKind::OpenAi, VoiceKind::Xai, VoiceKind::ElevenLabs] {
if ui.selectable_label(e.kind == k, t(speech::label(k))).clicked() && e.kind != k {
// Another service: its own address, model and voice (the key may carry over
// only when it was borrowed, i.e. empty).
*e = VoiceEngine { kind: k, ..Default::default() };
}
}
});
});
let field = |ui: &mut egui::Ui, label: &str, v: &mut String, hint_text: &str, secret: bool| {
ui.horizontal(|ui| {
ui.label(RichText::new(t(label)).size(FONT_SM).color(p.text2));
ui.add(egui::TextEdit::singleline(v).hint_text(t(hint_text)).password(secret).desired_width(f32::INFINITY));
});
};
match e.kind {
VoiceKind::Off => {}
VoiceKind::OpenAi => {
ui.horizontal(|ui| {
ui.label(RichText::new(t("快速填入")).size(FONT_SM).color(p.text2));
// (base, listen model, speak model, speak voice)
let presets: [(&str, &str, &str, &str, &str); 3] = [
("OpenAI", "", "", "", ""),
("Groq", "https://api.groq.com/openai/v1", "whisper-large-v3-turbo", "", ""),
// `make server` with voice (speaches). It can't say Chinese, so only for 聽.
("自己的伺服器", "http://voice:8000/v1", "deepdml/faster-whisper-large-v3-turbo-ct2", "", ""),
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
];
for (name, base, lm, sm, sv) in presets {
if speak && name != "OpenAI" {
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
continue;
}
if ui.small_button(t(name)).clicked() {
e.base_url = base.into();
e.model = if speak { sm.into() } else { lm.into() };
if speak {
e.voice = sv.into();
}
}
}
});
field(ui, "網址", &mut e.base_url, "留空:OpenAI(https://api.openai.com/v1)", false);
field(ui, "金鑰", &mut e.api_key, "留空:OpenAI 用 設定 › 模型 的金鑰;自己的伺服器可以不用", true);
field(ui, "模型", &mut e.model, if speak { "留空:gpt-4o-mini-tts(OpenAI)/tts-1" } else { "留空:OpenAI 用最新的轉文字模型/whisper-1" }, false);
}
VoiceKind::Xai => {
field(ui, "金鑰", &mut e.api_key, "留空:用 設定 › 模型 › xAI 的金鑰", true);
}
VoiceKind::ElevenLabs => {
field(ui, "金鑰", &mut e.api_key, "ElevenLabs 的 API 金鑰", true);
field(ui, "模型", &mut e.model, if speak { "留空:eleven_multilingual_v2" } else { "留空:scribe_v2" }, false);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_call_reads_the_new_answer_never_the_one_before() {
let mut msgs = vec![Message::user("第一句"), Message::assistant("上一個回答", "")];
let from = msgs.len();
// Sent: on a screen of a brain only the question is there at first, and the bot isn't
// working yet. The answer before must not be taken for this one.
msgs.push(Message::user("第二句"));
assert_eq!(call_answer(&msgs, from), None);
// Here: the answer's message is added empty at once, then fills in.
msgs.push(Message::assistant("", ""));
assert_eq!(call_answer(&msgs, from), None);
msgs.last_mut().unwrap().text = "新的回答".into();
assert_eq!(call_answer(&msgs, from).as_deref(), Some("新的回答"));
}
}