From bab3b6f8ea225f40ac3095d5d084b6d4daab7c69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Mon, 16 Nov 2026 23:37:38 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=81=B8=E8=81=B2=E9=9F=B3=E6=94=B9?= =?UTF-8?q?=E6=88=90=E4=B8=80=E5=80=8B=E9=81=B8=E5=96=AE=EF=BC=9B=E6=90=9C?= =?UTF-8?q?=E5=B0=8B=E6=A1=86=E4=B8=8D=E5=86=8D=E6=90=B6=E8=B5=B0=E8=BC=B8?= =?UTF-8?q?=E5=85=A5=E6=A1=86=E7=9A=84=E6=B8=B8=E6=A8=99=EF=BC=9B=E5=81=B4?= =?UTF-8?q?=E6=AC=84=E9=81=B8=E4=B8=AD=E7=9A=84=20Bot=20=E6=8B=BF=E6=8E=89?= =?UTF-8?q?=E5=B7=A6=E9=82=8A=E8=89=B2=E6=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 聲音(對話詳細資訊 › 語音聊天、設定 › 語音 › 說):原本是「聲音」字+「載入聲音清單」鈕+要自己打代號的框,載入後又多一個不顯示目前選擇的「選一個…」。現在和速度、語言一樣是一列一個選單:第一項「預設(eve)」,下面是服務的聲音(ElevenLabs 顯示名字),選了試唸一句;清單在那一列出現時就拿(每種「說」設定一次)。拿不到時選單裡寫一行原因,可以直接輸入名稱或「再試一次」。 - egui 的選單停在打開時的高度,清單或錯誤後來才到時下面被切掉:內容到了就在選單畫出前清掉它記住的大小,重新量一次。 - 語音服務的錯誤不再貼原始 JSON:金鑰被拒(含 xAI 用 400 回的)只說「不接受這把金鑰」,其他取服務回的 message。各服務不選時用的聲音集中在 speech::usual_voice。 - 側欄搜尋:搜尋框開著而且是空的時候,每一格都把游標拿回去,點輸入框打字的字會跑進搜尋框。改成只在按 🔍(下一格)或 ⌘F 時給一次。 - 側欄選中的 Bot 不再有強調色細條,只有淺底(比滑過深一階)。 已驗證:cargo test --bin anybot 525 通過(新增 a_refusal_reads_as_words_not_json、each_service_says_which_voice_it_uses_unasked);截圖:面板與設定的聲音選單(載入中打開、載入後打開都看得到輸入框和「再試一次」)、打開搜尋後點輸入框打「你好」留在輸入框、按 🔍 直接打「台南」進搜尋框、選中列沒有色條。 未驗證:用真的 xAI/ElevenLabs 金鑰載入清單和試唸。 --- FEATURES.md | 7 +- docs/feature-map/bots.md | 3 +- docs/feature-map/settings.md | 2 +- src/app.rs | 2 +- src/app/panel_ui.rs | 19 ++- src/app/sidebar_ui.rs | 26 ++-- src/app/voice_ui.rs | 241 +++++++++++++++++++++++++---------- src/speech.rs | 63 ++++++++- 8 files changed, 271 insertions(+), 92 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 3d50e11..9259e8a 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1421,7 +1421,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 金鑰留空時,借用「設定 › 模型」裡同一家的金鑰(xAI;OpenAI 的網址才借 OpenAI 的)。自己架的伺服器可以不用金鑰。 - 全部在大腦處理:每台電腦和手機只負責錄音和播放,錄音送到大腦轉文字,朗讀的聲音也由大腦產生,所以每一台的結果都一樣;金鑰只放在大腦。 - **沒有設定時,麥克風、語音聊天、會議錄音、朗讀都不會出現**;設定好就自動出現在每台電腦和手機上。 -- 每一邊顯示「✓ 可以用」或缺什麼;「聽」有「試試看(說一句話)」,「說」有「試聽」和「載入聲音清單」。 +- 每一邊顯示「✓ 可以用」或缺什麼;「聽」有「試試看(說一句話)」,「說」有「聲音」選單和「試聽」。 +- 「聲音」選單(這裡和每個 Bot 的 對話詳細資訊 › 語音聊天 是同一種):第一項「預設(eve)」(括號裡是不選時用的那個:Bot 的預設是這裡選的聲音,這裡的預設是服務自己的,OpenAI 是 alloy、xAI 是 eve;ElevenLabs 沒有預設,要選一個,沒選時寫「還沒選」),下面是服務列出的聲音(ElevenLabs 顯示名字)。清單在那一列出現時就去拿,每種「說」設定拿一次。選了會用那個聲音試唸一句。拿不到清單時(金鑰不對、自己架的服務沒有清單),選單裡寫一行原因(金鑰被拒時只說「不接受這把金鑰」,不貼服務回的原文),下面可以直接輸入聲音名稱,並有「再試一次」。 - 中文辨識結果會轉成繁體和台灣用語(xAI 和 Whisper 常回簡體);日文不轉。 - 從舊版升級:原本有 OpenAI 金鑰(語音輸入本來就能用)的人,「聽」自動設成 OpenAI;其他人預設關閉。舊的 macOS 聲音名稱(美佳…)會清掉。 - OpenAI 的轉文字模型依序試 gpt-transcribe、gpt-4o-mini-transcribe、whisper-1(後兩個 OpenAI 在 2027-02-26 停用)。 @@ -1858,7 +1859,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 淺色:米白紙底、側欄深一階、卡片純白;文字是帶暖調的黑。深色:暖黑三階(不藍黑)。 - 強調色(連結、選中、新訊息點、focus)是黏土橘;殼本身幾乎全灰階,**黃色只代表「需要你」**,紅只代表危險,圖表才有意識地用色(一套暖家族六色,見第 27 節頁面圖表)。 -- 設定 › 一般 › 外觀有三個旋紐:**底色**(藍灰→米白)、**對比**(柔和→鮮明,整個殼的階層、細線、文字深淺一起調)、**強調色**(黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑八色,圖表六色跟著轉);預設就是「紙」。調了立刻整個殼跟著換(淺色、深色、跟著系統都一樣,不用重開)。同處有**密度**(寬鬆/緊湊)和**慶祝動畫**開關;「外殼顏色重設」把三個旋紐歸零。側欄選中的 Bot 是一條強調色細條+淺底,不整條上色。 +- 設定 › 一般 › 外觀有三個旋紐:**底色**(藍灰→米白)、**對比**(柔和→鮮明,整個殼的階層、細線、文字深淺一起調)、**強調色**(黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑八色,圖表六色跟著轉);預設就是「紙」。調了立刻整個殼跟著換(淺色、深色、跟著系統都一樣,不用重開)。同處有**密度**(寬鬆/緊湊)和**慶祝動畫**開關;「外殼顏色重設」把三個旋紐歸零。側欄選中的 Bot 只有淺底(比滑過深一階),左邊沒有細條。 - 工作完成撒彩帶:只在 /goal 目標達成時(不是每輪結束),落在該 Bot 的聊天上約 1.4 秒;設定 › 一般可關。 ### 頭像 @@ -2355,7 +2356,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 點了打開「Bot 的電腦」視窗,看完整畫面,也可以取得控制權。休眠中會先叫醒。 - 成員:只有群組才有。 - 語音聊天: - - 語音:自動,或這台 Mac 上任何一個聲音,選了會試唸一句; + - 聲音:和速度、語言一樣是一列,右邊是選單(「預設(…)」或服務列出的聲音,選了會試唸一句;見「語音設定」); - 速度:0.75x–2x; - 語言:自動偵測、中文、English 等,用來轉文字; - 朗讀每個回答。 diff --git a/docs/feature-map/bots.md b/docs/feature-map/bots.md index c688bb0..50cfea3 100644 --- a/docs/feature-map/bots.md +++ b/docs/feature-map/bots.md @@ -5,7 +5,8 @@ ## 子功能 - 側邊欄:最上面是主要 Bot(大頭像),接著是釘選的格子(把 Bot 拖進去就釘選,格子裡可以拖曳排序),再來是各分區和「未分區」(分區見 [team](team.md))。每一列第二行是「正在工作…」「需要你允許」「等你回答」「等你處理」,或最後一則訊息。 -- 搜尋「搜尋 Bot 和訊息」:上面列名字或描述相符的 Bot,下面「訊息」列你和 Bot 說過的話和附件檔名(含過去的對話,最多 40 筆),點一筆就捲到那則訊息。 +- 搜尋「搜尋 Bot 和訊息」:上面列名字或描述相符的 Bot,下面「訊息」列你和 Bot 說過的話和附件檔名(含過去的對話,最多 40 筆),點一筆就捲到那則訊息。按 🔍 或 ⌘F 打開時游標在搜尋框;之後點輸入框打字,字就留在輸入框(搜尋框開著也不會把游標搶回去)。 +- 側欄選中的 Bot:整列淺底(比滑過深一階),左邊沒有色條。 - Bot 選單:「釘選」/「取消釘選」、「移至」、「標示為已讀」/「標示為未讀」、「設為主要 Bot」、「編輯 Bot…」、「記憶…」、「開始新對話」、「過去的對話」、「分享與匯出」(「匯出 Bot(分享給別人)…」「匯出文字記錄…」「匯入 Bot…」「複製對話 ID」)、「重新啟動這個 Bot」、「清除聊天記錄」、「刪除」。 - 建立:「新增 Bot」,或「從範本建立」(研究助理、寫作夥伴、電腦助手、客服助理、開發助手)。新 Bot 沿用目前選中 Bot 的供應商和模型,電腦工具關著。 - 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀平均排成兩列;10 種顏色和「自訂」同一列;按「自訂」出現一格一格的色盤——12 個色相各四種深淺加一列灰階,直接點,沒有滑桿——和「色碼」欄,打完整的 #rrggbb 才換色);「AI 供應商與模型」(供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」——欄位名稱在上,說明在名稱旁的「?」);接著「電腦操作」「能力」「技能」「記憶」四張預設收起,各只有一行:名稱、目前怎麼設(例如「11 / 11 類」「會 8 / 8」「還沒有」)和 ▸,點了才展開;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot」(「?」說明:團隊成員看得到它的聊天、頁面和檔案)。 diff --git a/docs/feature-map/settings.md b/docs/feature-map/settings.md index 740667c..384c4e4 100644 --- a/docs/feature-map/settings.md +++ b/docs/feature-map/settings.md @@ -26,7 +26,7 @@ - 「AnyBot 瀏覽器設定檔」:每個設定檔自己的登入,「做完就關掉瀏覽器」、「發布前檢查」和另外的規則([browser](browser.md))。 - 「權限」:直接操作開關、自動審核開關、「無需詢問直接允許」和「一律詢問」規則([safety](safety.md))。 - 「保險庫」:登入資訊、卡片、聯絡資訊([vault](vault.md))。 -- 「語音」:「語音服務」一張清單,「聽(語音轉文字)」把說的話變文字(語音輸入、語音聊天、會議錄音),「說(朗讀)」把回答唸出來;各自在右邊選服務,選了在那一列下面展開要填的欄位(快速填入、網址、金鑰、模型;「說」還有聲音),能用了列上寫「可以用」,並有「試試看(說一句話)」或「試聽」。 +- 「語音」:「語音服務」一張清單,「聽(語音轉文字)」把說的話變文字(語音輸入、語音聊天、會議錄音),「說(朗讀)」把回答唸出來;各自在右邊選服務,選了在那一列下面展開要填的欄位(快速填入、網址、金鑰、模型;「說」還有「聲音」選單),能用了列上寫「可以用」,並有「試試看(說一句話)」或「試聽」。「聲音」選單第一項是「預設(eve)」,下面是服務列出的聲音,選了試唸一句;拿不到清單時選單裡寫原因、可以直接輸入名稱或「再試一次」。每個 Bot 的 對話詳細資訊 › 語音聊天 ›「聲音」是同一個選單(預設是這裡選的聲音)。 - 「更新」:「版本」、「自動更新」(你離開時換新版)、「園丁報告」、「待改進」清單([garden](garden.md))、「重新啟動」。 Bot 設定(每個 Bot 一個視窗,[bots](bots.md)): diff --git a/src/app.rs b/src/app.rs index 7788fd9..c84b935 100644 --- a/src/app.rs +++ b/src/app.rs @@ -6139,7 +6139,7 @@ impl eframe::App for App { ctx.memory_mut(|m| m.request_focus(egui::Id::unique("page-find"))); } else { self.search_open = true; - ctx.memory_mut(|m| m.request_focus(egui::Id::unique("sidebar-search"))); + ctx.memory_mut(|m| m.request_focus(egui::Id::unique(sidebar_ui::SEARCH_ID))); } } // A click on one of AnyBot's banners: that bot's chat (macOS brings AnyBot to the front). diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs index d7e54a9..13731ab 100644 --- a/src/app/panel_ui.rs +++ b/src/app/panel_ui.rs @@ -336,10 +336,18 @@ impl App { let mut changed = false; panel_card(ui, p, |ui| { if speak { + // 聲音 like 速度 and 語言: one row, its menu offers 預設 and the service's voices. let before = b2.voice.clone(); - ui.add_space(4.0); - Frame::new().inner_margin(Margin::symmetric(10, 0)).show(ui, |ui| self.voice_picker(ui, &mut b2.voice, &format!("bot-voice-{}", bot.id))); + let inherit = self.state.voice.speak.voice.clone(); + let row = self.voice_row(ui.ctx(), &b2.voice, &inherit); + let at = format!("bot-voice-{}", bot.id); + panel_select_with(ui, p, "聲音", ("voice", bot.id), &row.shown, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| self.voice_menu(ui, &mut b2.voice, &row, &at)); changed |= b2.voice != before; + if let Some(e) = self.voice_note(&at) { + Frame::new().inner_margin(Margin::symmetric(10, 0)).show(ui, |ui| { + ui.add(egui::Label::new(RichText::new(&e).size(FONT_XS).color(p.danger)).truncate()).on_hover_text(e); + }); + } let rate = if b2.voice_rate > 0.0 { b2.voice_rate } else { 1.0 }; panel_select(ui, p, "速度", ("rate", bot.id), &format!("{}x", trim_rate(rate)), |ui| { for s in crate::voice::SPEEDS { @@ -546,6 +554,11 @@ fn panel_row_sub(ui: &mut egui::Ui, p: Palette, title: &str, sub: &str) -> egui: /// A label with a small drop-down on the right (語音 Helix ⌄). fn panel_select(ui: &mut egui::Ui, p: Palette, label: &str, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, menu: impl FnOnce(&mut egui::Ui)) { + panel_select_with(ui, p, label, id, shown, egui::PopupCloseBehavior::CloseOnClick, menu); +} + +/// The same, choosing how its menu closes (one with a field in it stays open while typing). +fn panel_select_with(ui: &mut egui::Ui, p: Palette, label: &str, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, close: egui::PopupCloseBehavior, menu: impl FnOnce(&mut egui::Ui)) { ui.horizontal(|ui| { ui.set_height(ROW_H); ui.add_space(10.0); @@ -561,7 +574,7 @@ fn panel_select(ui: &mut egui::Ui, p: Palette, label: &str, id: impl std::hash:: } w.hovered.weak_bg_fill = p.hover; w.open.weak_bg_fill = p.hover; - egui::ComboBox::from_id_salt(id).selected_text(RichText::new(shown).size(FONT_SM).color(p.text2)).icon(chevron_down).width(0.0).height(320.0).show_ui(ui, menu); + egui::ComboBox::from_id_salt(id).selected_text(RichText::new(shown).size(FONT_SM).color(p.text2)).icon(chevron_down).width(0.0).height(320.0).close_behavior(close).show_ui(ui, menu); }); }); } diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index d07d54b..2e4f51e 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -38,6 +38,10 @@ pub enum Poke { Look, } +/// The sidebar's 搜尋 field (⌘F and the 🔍 button put the caret in it). +pub(super) const SEARCH_ID: &str = "sidebar-search"; +/// The frame the 🔍 button opened 搜尋 on (the field takes the caret the frame after). +const SEARCH_FOCUS: &str = "sidebar-search-focus"; const BLINK: f64 = 0.24; const SPLASH: f64 = 1.6; const SPLASH_FADE: f64 = 0.35; @@ -270,6 +274,13 @@ impl App { self.search_open = !open; if open { self.search.clear(); + } else { + // The caret goes in once, on the next frame (this frame's click lands + // outside the field, which would let go of it at once). Asking for it + // every frame took it back from the message box whenever you clicked + // there to type. + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(SEARCH_FOCUS), frame)); } } }); @@ -280,8 +291,10 @@ impl App { ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(16.0, 18.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(14.0, 14.0)), crate::icons::Icon::Search, p.text3); - let resp = ui.add(egui::TextEdit::singleline(&mut self.search).id(egui::Id::unique("sidebar-search")).hint_text(t("搜尋 Bot 和訊息")).frame(Frame::NONE).desired_width(f32::INFINITY)); - if self.search_open && self.search.is_empty() && !resp.has_focus() && !resp.lost_focus() { + let resp = ui.add(egui::TextEdit::singleline(&mut self.search).id(egui::Id::unique(SEARCH_ID)).hint_text(t("搜尋 Bot 和訊息")).frame(Frame::NONE).desired_width(f32::INFINITY)); + let now = ui.ctx().cumulative_frame_nr(); + if ui.data(|d| d.get_temp::(egui::Id::unique(SEARCH_FOCUS))).is_some_and(|at| at < now) { + ui.data_mut(|d| d.remove::(egui::Id::unique(SEARCH_FOCUS))); resp.request_focus(); } }); @@ -834,14 +847,9 @@ impl App { // Drag a bot onto another group to move it. resp.dnd_set_drag_payload(id); let dragged = resp.dragged(); - // 選中不再整條上色(細條在下方說「你在這」);選中和滑過同色,靜一點。 - let fill = if selected || resp.hovered() || dragged { p.hover } else { Color32::TRANSPARENT }; + // 選中:只有淺底(比滑過深一階,滑過別列時還認得出),左邊不再有強調色細條。 + let fill = if selected { p.active } else if resp.hovered() || dragged { p.hover } else { Color32::TRANSPARENT }; ui.painter().rect_filled(rect, R_M, fill); - if selected { - // 「你在這」的安靜說法:一條 3 px 的強調色細條,不整條上色(Linear 的選中)。 - let strip = egui::Rect::from_min_size(rect.left_center() + vec2(3.0, -11.0), vec2(3.0, 22.0)); - ui.painter().rect_filled(strip, R_S, p.accent); - } let face = egui::Rect::from_min_size(rect.min + vec2(8.0, 7.0), vec2(40.0, 40.0)); self.live_face(ui, id, face, true); let tx = rect.left() + 56.0; diff --git a/src/app/voice_ui.rs b/src/app/voice_ui.rs index 166db05..776c6bd 100644 --- a/src/app/voice_ui.rs +++ b/src/app/voice_ui.rs @@ -9,6 +9,7 @@ use crate::model::{VoiceEngine, VoiceKind}; use crate::remote::Cmd; use crate::speech; use crate::theme::sp; +use std::hash::{Hash, Hasher}; /// Where this window's voice goes. #[derive(Clone)] @@ -67,14 +68,35 @@ pub struct VoiceUi { test_rec: Option, test_rx: Option>>, test_said: Option>, - /// 試聽's trouble. + /// 試聽's trouble, or a picked voice's, and which 聲音 row it belongs under. test_note: Arc>>, - /// The voices 說 offers (loaded when asked). + test_note_at: String, + /// The voices 說 offers: fetched the first time a 聲音 menu opens, kept until 說 changes. voices_rx: Option, String>>>, - pub(super) voice_list: Vec<(String, String)>, + voice_list: Vec<(String, String)>, voices_err: String, + /// Which 說 (service, address, key) the list is for. + voices_for: u64, + /// The list (or why there is none) came this frame: an open menu is measured again. + voices_arrived: bool, + /// The layer the last 聲音 menu was drawn on (to measure it again, before it draws). + menu_layer: Option, } +/// What a 聲音 row shows and offers. +pub(super) struct VoiceRow { + /// The chosen voice by name, or what an empty choice means. + pub(super) shown: String, + /// 「預設(eve)」, the menu's first item; none when there is nothing to fall back on + /// (ElevenLabs: a voice must be picked). + default: Option, + /// The voice an empty choice speaks in (played when 預設 is picked). + fallback: String, +} + +/// Where 設定 › 語音's 試聽 and 聲音 put their trouble. +const SETTINGS_NOTE: &str = "settings"; + impl App { pub(super) fn voice_via(&self) -> VoiceVia { if self.mir.on { @@ -426,7 +448,7 @@ impl App { card_row(ui, p, "說(朗讀)", &status, "把回答唸出來:朗讀和語音聊天都用它。每台電腦和手機的朗讀都由大腦用這裡選的服務產生。", |ui| engine_picker(ui, &mut v.speak, "speak")); if v.speak.kind != VoiceKind::Off { engine_fields(ui, p, &mut v.speak, true); - self.voice_field(ui, &mut v.speak.voice, "speak-voice"); + self.voice_field(ui, &mut v.speak.voice); if ok { self.speak_test(ui, &v.speak.voice); } @@ -450,17 +472,14 @@ impl App { ui.add_space(sp::S3); ui.horizontal(|ui| { if ui.add(secondary_button("試聽")).clicked() { - let via = self.voice_via(); - let voice = voice.to_string(); - *self.vo.test_note.lock().unwrap() = None; - crate::voice::say(move || via.sound(SAMPLE, &voice, "", 1.0), self.vo.test_note.clone()); + self.voice_preview(voice, SETTINGS_NOTE); } 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.add(egui::Label::new(RichText::new(e).size(FONT_XS).color(p.danger)).truncate()); + if let Some(e) = self.voice_note(SETTINGS_NOTE) { + ui.add(egui::Label::new(RichText::new(&e).size(FONT_XS).color(p.danger)).truncate()).on_hover_text(e); } }); } @@ -525,51 +544,145 @@ impl App { } } - /// 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; + /// The sample sentence in `voice` (empty: what 說 uses unasked); trouble shows under the row + /// named `at`. + pub(super) fn voice_preview(&mut self, voice: &str, at: &str) { + let via = self.voice_via(); + let voice = voice.to_string(); + *self.vo.test_note.lock().unwrap() = None; + self.vo.test_note_at = at.to_string(); + crate::voice::say(move || via.sound(SAMPLE, &voice, "", 1.0), self.vo.test_note.clone()); + } + + /// What went wrong playing a voice, when it was played from the row named `at`. + pub(super) fn voice_note(&self, at: &str) -> Option { + (self.vo.test_note_at == at).then(|| self.vo.test_note.lock().unwrap().clone()).flatten() + } + + /// A 聲音 row: the chosen voice by name, or 「預設(…)」 for an empty one. `inherit` is what an + /// empty choice falls back to before the service's own voice (a bot's: 設定 › 語音's). + pub(super) fn voice_row(&mut self, ctx: &egui::Context, voice: &str, inherit: &str) -> VoiceRow { self.voices_poll(); - // 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)); + // (Here, before the menu draws: the menu saves its own size at the end of its frame.) + if let (true, Some(layer)) = (self.vo.voices_arrived, self.vo.menu_layer) { + remeasure_menu(ctx, layer); + } + let kind = self.state.voice.speak.kind; + // Fetched as the row shows, not when its menu opens: the menu then opens with them (and + // ElevenLabs' ids like 21m00Tcm4TlvDq8ikWAM show as names). Once per 說. + self.voices_want(ctx); + let fallback = if inherit.is_empty() { speech::usual_voice(kind).unwrap_or_default().to_string() } else { inherit.to_string() }; + let default = (!fallback.is_empty()).then(|| format!("{}({})", t("預設"), self.voice_name(&fallback))); + let shown = if !voice.is_empty() { + self.voice_name(voice) } 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); - }); - } - if !self.vo.voices_err.is_empty() { - ui.label(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)); - } + default.clone().unwrap_or_else(|| t("還沒選")) + }; + VoiceRow { shown, default, fallback } } - /// 設定 › 語音's 聲音: a field like the others (its name above), the box and the list button. - fn voice_field(&mut self, ui: &mut egui::Ui, voice: &mut String, salt: &str) { + /// The 聲音 menu: 「預設(…)」, then the voices the service offers (fetched the first time it + /// opens). With no list (the service has none, or it failed) the name is typed instead. + /// Picking one plays the sample sentence in it; trouble shows under the row named `at`. + pub(super) fn voice_menu(&mut self, ui: &mut egui::Ui, voice: &mut String, row: &VoiceRow, at: &str) { let p = self.pal; - self.voices_poll(); - form_row(ui, "聲音", p, |ui| { - 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(ui.available_width())); + self.voices_want(ui.ctx()); + self.vo.menu_layer = Some(ui.layer_id()); + ui.set_min_width(VOICE_MENU_WIDTH); + let mut picked = None; + if let Some(d) = &row.default { + if ui.selectable_label(voice.is_empty(), d).clicked() { + picked = Some(String::new()); + } + } + // A name typed before (one the list doesn't have) still shows as the chosen one. + if !voice.is_empty() && !self.vo.voice_list.is_empty() && !self.vo.voice_list.iter().any(|(id, _)| id == voice) { + let _ = ui.selectable_label(true, voice.as_str()); + } + for (id, name) in &self.vo.voice_list { + if ui.selectable_label(voice == id, voice_label(id, name)).clicked() { + picked = Some(id.clone()); + } + } + if self.vo.voices_rx.is_some() { + ui.horizontal(|ui| { + chat_ui::spinner(ui, 14.0, p.text3); + ui.label(RichText::new(t("正在載入聲音…")).size(FONT_SM).color(p.text3)); }); - }); - if !self.vo.voices_err.is_empty() { - ui.add(egui::Label::new(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)).truncate()); + } else if !self.vo.voices_err.is_empty() { + ui.add_space(sp::S1); + ui.add(egui::Label::new(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)).wrap()); + // (A width of its own: in a menu, "as wide as there is room" has no end.) + ui.add(egui::TextEdit::singleline(voice).hint_text(t("輸入聲音名稱")).desired_width(ui.available_width().min(VOICE_MENU_WIDTH))); + if ui.add(egui::Button::new(RichText::new(t("再試一次")).size(FONT_XS).color(p.text2)).frame(false)).clicked() { + // (The next frame fetches it again.) + self.vo.voices_err.clear(); + } + } + if let Some(v) = picked { + let play = if v.is_empty() { row.fallback.clone() } else { v.clone() }; + *voice = v; + if !play.is_empty() { + self.voice_preview(&play, at); + } + ui.close(); } } - /// The list of voices, when it has come. + /// 設定 › 語音 › 說's 聲音: a field like the others (its name above), the menu in it. + fn voice_field(&mut self, ui: &mut egui::Ui, voice: &mut String) { + let p = self.pal; + let row = self.voice_row(ui.ctx(), voice, ""); + form_row(ui, "聲音", p, |ui| { + egui::ComboBox::from_id_salt("speak-voice") + .selected_text(RichText::new(&row.shown).size(FONT_SM)) + .width(ui.available_width()) + .height(VOICE_MENU_HEIGHT) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show_ui(ui, |ui| self.voice_menu(ui, voice, &row, SETTINGS_NOTE)); + }); + } + + /// The voice's name from the service's list (ElevenLabs': "Rachel"), else as given. + fn voice_name(&self, id: &str) -> String { + self.vo.voice_list.iter().find(|(v, _)| v == id).map(|(v, name)| voice_label(v, name)).unwrap_or_else(|| id.to_string()) + } + + /// Fetch the voices, unless they are here, coming, or just failed (「再試一次」 clears that). + fn voices_want(&mut self, ctx: &egui::Context) { + if !self.vo.voice_list.is_empty() || self.vo.voices_rx.is_some() || !self.vo.voices_err.is_empty() { + return; + } + let via = self.voice_via(); + let (tx, rx) = channel(); + self.vo.voices_rx = Some(rx); + let c = ctx.clone(); + std::thread::spawn(move || { + let _ = tx.send(via.voices()); + c.request_repaint(); + }); + } + + /// The list of voices, when it has come; dropped when 說 is changed (another service, address + /// or key offers other voices). fn voices_poll(&mut self) { + let mut h = std::collections::hash_map::DefaultHasher::new(); + let e = &self.state.voice.speak; + (e.kind, &e.base_url, &e.api_key).hash(&mut h); + let now = h.finish(); + self.vo.voices_arrived = false; + if now != self.vo.voices_for { + self.vo.voices_for = now; + self.vo.voice_list.clear(); + self.vo.voices_err.clear(); + self.vo.voices_rx = None; + } if let Some(rx) = &self.vo.voices_rx { if let Ok(r) = rx.try_recv() { self.vo.voices_rx = None; + self.vo.voices_arrived = true; match r { + Ok(list) if list.is_empty() => self.vo.voices_err = t("這個服務沒有列出聲音。"), Ok(list) => { self.vo.voice_list = list; self.vo.voices_err.clear(); @@ -579,31 +692,24 @@ impl App { } } } +} - /// 「選一個…」 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(); - }); - } +/// Let an open menu take its new size: egui keeps a menu the height it opened at, so the list or +/// the 「輸入聲音名稱」 field arriving under 「正在載入聲音…」 was cut off. +fn remeasure_menu(ctx: &egui::Context, layer: egui::LayerId) { + if let Some(mut st) = egui::AreaState::load(ctx, layer.id) { + st.size = None; + ctx.memory_mut(|m| m.areas_mut().set_state(layer, st)); + ctx.request_repaint(); + } +} + +/// A voice in the menu: its name when the service gives one, else its id. +fn voice_label(id: &str, name: &str) -> String { + if name.trim().is_empty() { + id.to_string() + } else { + name.to_string() } } @@ -617,8 +723,9 @@ fn call_answer(msgs: &[Message], from: usize) -> Option { /// 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; +/// The 聲音 menu: wide enough for 「預設(Rachel)」 and a typed name, tall enough for ElevenLabs' list. +const VOICE_MENU_WIDTH: f32 = 220.0; +const VOICE_MENU_HEIGHT: f32 = 320.0; /// The service menu on 聽's and 說's rows: wide enough for 「OpenAI 相容」 and 「xAI(Grok)」. const VOICE_KIND_WIDTH: f32 = 140.0; diff --git a/src/speech.rs b/src/speech.rs index 5ac8825..47485f5 100644 --- a/src/speech.rs +++ b/src/speech.rs @@ -277,12 +277,12 @@ fn speak_with(e: &Engine, words: &str, voice: String, lang: &str, speed: f32) -> VoiceKind::OpenAi => { let at_openai = e.base == OPENAI_BASE; let model = if !e.model.is_empty() { e.model.clone() } else if at_openai { "gpt-4o-mini-tts".into() } else { "tts-1".into() }; - let voice = if voice.is_empty() { "alloy".to_string() } else { voice }; + let voice = if voice.is_empty() { usual_voice(e.kind).unwrap_or_default().to_string() } else { voice }; let body = json!({"model": model, "input": words, "voice": voice, "response_format": "mp3", "speed": speed}); post_json(&format!("{}/audio/speech", e.base), &bearer(&e.key), &body, "OpenAI 相容") } VoiceKind::Xai => { - let voice = if voice.is_empty() { "eve".to_string() } else { voice }; + let voice = if voice.is_empty() { usual_voice(e.kind).unwrap_or_default().to_string() } else { voice }; let lang = if lang.is_empty() { "auto" } else { lang }; let body = json!({"text": words, "voice_id": voice, "language": lang, "output_format": {"codec": "mp3"}, "speed": speed}); post_json(&format!("{}/tts", e.base), &bearer(&e.key), &body, "xAI") @@ -328,6 +328,15 @@ pub fn speakable(text: &str) -> String { out.trim().to_string() } +/// The voice a service speaks in when none is chosen; ElevenLabs has none (one must be picked). +pub fn usual_voice(kind: VoiceKind) -> Option<&'static str> { + match kind { + VoiceKind::OpenAi => Some("alloy"), + VoiceKind::Xai => Some("eve"), + VoiceKind::Off | VoiceKind::ElevenLabs => None, + } +} + /// The voices the service offers: (id, what to show). pub fn voices(e: &Engine) -> Result, String> { match e.kind { @@ -422,13 +431,33 @@ fn answer(r: Result, ureq::Error>, who: &str) - if status == 200 { return Ok((status, bytes)); } - let said: String = String::from_utf8_lossy(&bytes).chars().take(200).collect(); - Err(match status { - 401 | 403 => format!("{who} 不接受這把金鑰(HTTP {status}):{said}"), - _ => format!("{who} 的語音服務失敗(HTTP {status}):{said}"), - }) + Err(refused(status, &bytes, who)) } +/// A service's refusal in words: a key it won't take said as that (xAI answers a wrong key with a +/// 400), anything else with the service's own message, not its raw JSON. +fn refused(status: u16, bytes: &[u8], who: &str) -> String { + let said = service_said(bytes); + let low = said.to_lowercase(); + if matches!(status, 401 | 403) || low.contains("api key") || low.contains("api_key") { + format!("{who} 不接受這把金鑰(HTTP {status})") + } else { + format!("{who} 的語音服務失敗(HTTP {status}):{said}") + } +} + +/// The message in an error body ({"error": {"message"}}, {"error": "…"}, {"message"}, {"detail"} +/// or ElevenLabs' {"detail": {"message"}}), else the start of the body. +fn service_said(bytes: &[u8]) -> String { + let v: Value = serde_json::from_slice(bytes).unwrap_or(Value::Null); + let found = [&v["error"]["message"], &v["error"], &v["message"], &v["detail"]["message"], &v["detail"]].into_iter().find_map(|x| x.as_str().map(str::to_string)); + let text = found.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned()); + text.trim().chars().take(MAX_SAID_CHARS).collect() +} + +/// How much of a service's error message is kept. +const MAX_SAID_CHARS: usize = 200; + #[cfg(test)] mod tests { use super::*; @@ -695,4 +724,24 @@ mod tests { assert_eq!(audio_type("voice.webm"), "audio/webm"); assert_eq!(audio_type("voice.M4A"), "audio/mp4"); } + + /// 載入聲音 with a wrong key showed xAI's whole JSON in the side panel. + #[test] + fn a_refusal_reads_as_words_not_json() { + let xai = br#"{"code":"Client specified an invalid argument","error":"Incorrect API key provided. You can obtain an API key from https://console.x.ai."}"#; + assert_eq!(refused(400, xai, "xAI"), "xAI 不接受這把金鑰(HTTP 400)"); + let eleven = br#"{"detail":{"status":"voice_not_found","message":"A voice with that ID does not exist."}}"#; + assert_eq!(refused(404, eleven, "ElevenLabs"), "ElevenLabs 的語音服務失敗(HTTP 404):A voice with that ID does not exist."); + let openai = br#"{"error":{"message":"Rate limit reached","type":"requests"}}"#; + assert_eq!(refused(429, openai, "OpenAI 相容"), "OpenAI 相容 的語音服務失敗(HTTP 429):Rate limit reached"); + assert_eq!(refused(502, b" Bad Gateway ", "xAI"), "xAI 的語音服務失敗(HTTP 502):Bad Gateway"); + assert_eq!(refused(401, b"", "xAI"), "xAI 不接受這把金鑰(HTTP 401)"); + } + + #[test] + fn each_service_says_which_voice_it_uses_unasked() { + assert_eq!(usual_voice(VoiceKind::OpenAi), Some("alloy")); + assert_eq!(usual_voice(VoiceKind::Xai), Some("eve")); + assert_eq!(usual_voice(VoiceKind::ElevenLabs), None); + } }