diff --git a/src/app.rs b/src/app.rs index 3991592..b081d0b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1301,12 +1301,8 @@ impl App { if !group_continues { self.channels_settled(bot_id, outcome); } - if outcome == TurnOutcome::Success && !self.demo { - 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.filter(|_| self.can_speak()) { - self.read_aloud(bot_id, &a); - } + if outcome == TurnOutcome::Success { + self.read_reply(bot_id); } if outcome == TurnOutcome::Success { let now = self.faces.get(&bot_id).map(|f| f.now()).unwrap_or(0.0); diff --git a/src/app/attach_ui.rs b/src/app/attach_ui.rs index e85c21d..90c0273 100644 --- a/src/app/attach_ui.rs +++ b/src/app/attach_ui.rs @@ -18,6 +18,11 @@ pub struct AttachUi { pub call: Option<(u64, CallPhase)>, pub(super) call_rec: Option, pub(super) call_rx: Option>>, + /// What was just said: the chat's length just before it was sent (its answer comes after), + /// when it was sent, and whether the bot has been seen working on it since. + pub(super) call_from: usize, + pub(super) call_asked: Option, + pub(super) call_seen: bool, } #[derive(Clone, Copy, PartialEq, Debug)] diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 410e87d..10b86d7 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -363,6 +363,21 @@ enum Out { Move { ops: Vec, n: usize }, } +/// The bots whose turn ended well since the last update (`seen` keeps when each bot's last turn +/// ended). Only an end heard while connected counts, and only a recent one: connecting, or coming +/// back after a while, never reads old answers out. +fn just_finished<'a>(seen: &mut HashMap, turns: impl IntoIterator)>, now_ms: i64) -> Vec { + let mut out = vec![]; + for (id, t) in turns { + let Some(t) = t else { continue }; + let before = seen.insert(id, t.settled_at_ms); + if before.is_some_and(|s| s < t.settled_at_ms) && t.outcome == TurnOutcome::Success && now_ms - t.settled_at_ms < 120_000 { + out.push(id); + } + } + out +} + /// An edit sent to the brain and not yet confirmed: (its number, the operations). type Pending = (u64, Vec); @@ -410,6 +425,8 @@ pub struct Mirror { pub(super) box_state: Value, /// Each bot's computers on the brain, by bot id: {names: [{name, kind}], current, missing}. pub(super) computers: HashMap, + /// When each bot's last turn ended, as last heard (a newer one ending well is read aloud). + settled: HashMap, } /// What a computer is, in a word a screen can show next to its name. @@ -806,6 +823,7 @@ impl App { self.mir.outbox = None; self.streams.clear(); self.approvals.clear(); + self.mir.settled.clear(); if let Some(mut local) = self.mir.local.take() { let mut remote = self.state.remote.clone(); remote.brain_id.clear(); @@ -1066,6 +1084,12 @@ impl App { if self.state.bot(self.state.selected).is_none() { self.state.selected = self.state.primary_bot; } + // 朗讀每個回答: the brain finishes the turns, this screen reads them (a brain on a server + // has nobody to read to). Its answer came in this same update. + let turns: Vec<(u64, Option)> = self.state.bots.iter().map(|b| (b.id, b.last_turn.clone())).collect(); + for id in just_finished(&mut self.mir.settled, turns.iter().map(|(id, t)| (*id, t.as_ref())), chrono::Utc::now().timestamp_millis()) { + self.read_reply(id); + } self.mirror_save_copy(); } @@ -1300,6 +1324,25 @@ impl App { mod tests { use super::*; + #[test] + fn a_screen_reads_only_turns_it_saw_end() { + let turn = |at: i64, outcome| TurnSettlement { turn_id: format!("t{at}"), outcome, settled_at_ms: at }; + let now = 1_000_000; + let mut seen = HashMap::new(); + // Connecting: turns that ended before are not read out. + let (a, b) = (turn(now - 5_000, TurnOutcome::Success), turn(now - 9_000, TurnOutcome::Success)); + assert!(just_finished(&mut seen, [(1, Some(&a)), (2, Some(&b)), (3, None)], now).is_empty()); + // Nothing new: nothing read (every update says the same). + assert!(just_finished(&mut seen, [(1, Some(&a)), (2, Some(&b))], now).is_empty()); + // Bot 1 finished again: read; bot 2 failed: not. + let (a2, b2) = (turn(now - 100, TurnOutcome::Success), turn(now - 50, TurnOutcome::Error)); + assert_eq!(just_finished(&mut seen, [(1, Some(&a2)), (2, Some(&b2))], now), vec![1]); + // Long ago (heard only after being away): not read. + let a3 = turn(now - 600_000 + 1, TurnOutcome::Success); + let mut seen2 = HashMap::from([(1, now - 700_000)]); + assert!(just_finished(&mut seen2, [(1, Some(&a3))], now).is_empty()); + } + #[test] fn edits_become_small_operations() { let base = json!({"theme": "light", "folders": ["a"], "bots": [{"id": 1, "name": "A", "unread": true}, {"id": 2, "name": "B"}]}); diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs index 3de87f9..f7777f8 100644 --- a/src/app/panel_ui.rs +++ b/src/app/panel_ui.rs @@ -32,7 +32,7 @@ impl App { let avail = root.available_width(); if avail - PANEL_MIN_WIDTH >= CHAT_MIN_WIDTH { let w = (avail - CHAT_MIN_WIDTH).min(PANEL_WIDTH); - egui::Panel::right("bot-panel").exact_size(w).resizable(false).frame(Frame::new().fill(p.pane).inner_margin(Margin { left: 16, right: 16, top: 10, bottom: 12 })).show(root, |ui| self.panel_contents(ui, &ctx, bot, tab)); + egui::Panel::right("bot-panel").exact_size(w).resizable(false).frame(Frame::new().fill(p.pane).inner_margin(Margin { left: 16, right: 16, top: 10, bottom: 12 })).show(root, |ui| keep_width(ui, |ui| self.panel_contents(ui, &ctx, bot, tab))); } else { let screen = ctx.content_rect(); let w = PANEL_WIDTH.min(avail - 16.0).max(220.0); @@ -412,6 +412,16 @@ impl App { } /// A 36 px round button with ✕ (the original's close). +/// Lays out a side panel's contents so they can't widen it. Contents wider than a right panel make +/// egui move the panel's left edge in by the overflow (it trims the panel from its far end), and +/// the chat then covers that much of it, as the voice row once did; this way too-wide contents are +/// cut off at the right edge instead. +fn keep_width(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let rect = ui.max_rect(); + let mut inner = ui.new_child(egui::UiBuilder::new().id_salt("keep-width").max_rect(rect).layout(Layout::top_down(Align::Min))); + add(&mut inner) +} + fn round_button(ui: &mut egui::Ui, p: Palette, size: f32) -> egui::Response { let (rect, r) = ui.allocate_exact_size(vec2(size, size), egui::Sense::click()); ui.painter().circle_filled(rect.center(), size / 2.0, if r.hovered() { p.hover } else { p.elevated }); @@ -552,3 +562,42 @@ fn file_glyph(painter: &egui::Painter, r: egui::Rect, name: &str, p: Palette) { }; crate::icons::paint(painter, egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)), crate::icons::for_file(name), col); } + +#[cfg(test)] +mod tests { + use super::*; + + /// Where the chat ends (= the side panel's left edge) in a 1000 px window with a 280 px panel + /// whose contents want 400 px. + fn chat_right_edge(guarded: bool) -> f32 { + let ctx = egui::Context::default(); + let mut edge = 0.0; + for _ in 0..2 { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |root| { + let wide = |ui: &mut egui::Ui| { + ui.horizontal(|ui| { + ui.allocate_exact_size(vec2(400.0, 20.0), egui::Sense::hover()); + }); + }; + egui::Panel::right("p").exact_size(PANEL_WIDTH).resizable(false).frame(Frame::NONE).show(root, |ui| { + if guarded { + keep_width(ui, wide); + } else { + wide(ui); + } + }); + edge = root.available_rect_before_wrap().right(); + }); + out.textures_delta.clear(); // (no renderer here to hand the font atlas to) + } + edge + } + + #[test] + fn too_wide_contents_keep_the_panel_in_place() { + // What egui does on its own: the panel's left edge moves in by the overflow, under the chat. + assert!(chat_right_edge(false) > 1000.0 - PANEL_WIDTH + 50.0, "{}", chat_right_edge(false)); + assert_eq!(chat_right_edge(true), 1000.0 - PANEL_WIDTH); + } +} diff --git a/src/app/voice_ui.rs b/src/app/voice_ui.rs index 552a112..e2bc9b8 100644 --- a/src/app/voice_ui.rs +++ b/src/app/voice_ui.rs @@ -263,6 +263,20 @@ impl App { // ---------- 朗讀 ---------- + /// 朗讀每個回答: 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); + } + } + /// 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 }; @@ -339,7 +353,11 @@ impl App { 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); self.send(ctx, bot_id); + self.att.call_asked = Some(std::time::Instant::now()); + self.att.call_seen = false; self.att.call = Some((bot_id, CallPhase::Thinking)); } // Nothing said: keep listening; a real error ends the call. @@ -352,13 +370,22 @@ impl App { } } CallPhase::Thinking => { - if !self.streams.contains_key(&bot_id) && !self.approvals.contains_key(&bot_id) { - let answer = self.state.bot(bot_id).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty())).map(|m| m.text.clone()); + 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 { // Answers are read here, not by the 朗讀 switch (no double reading). - if let Some(a) = answer { - self.read_aloud(bot_id, &a); - } + self.read_aloud(bot_id, &a); 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)); } } CallPhase::Speaking => { @@ -509,37 +536,66 @@ impl App { } } } - 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)); - 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(); - }); - } - }); + // 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); + }); + } 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 { + msgs.iter().skip(from).rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty()).map(|m| m.text.clone()) +} + +/// 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; + /// 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| { @@ -598,3 +654,23 @@ fn engine_form(ui: &mut egui::Ui, p: Palette, e: &mut VoiceEngine, speak: bool, } } } + +#[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("新的回答")); + } +}