diff --git a/cli/src/bridge/v2/faults.rs b/cli/src/bridge/v2/faults.rs index 3e9f9ce8f..a75eb435d 100644 --- a/cli/src/bridge/v2/faults.rs +++ b/cli/src/bridge/v2/faults.rs @@ -3146,3 +3146,356 @@ async fn stop_ends_background_work_left_running_after_its_turn() { Some("Nothing is running.") ); } + +/// A voice message from the owner in the DM. `transcript` is the text the +/// server edits in; the audio URL is never fetched (not HTTPS). +fn voice_message(message_id: i64, duration_ms: u64, transcript: Option<&str>) -> MessageRecord { + MessageRecord { + chat_id: InlineId::new(9), + message_id: InlineId::new(message_id), + sender_id: InlineId::new(1), + timestamp: 1, + is_outgoing: false, + reply_to_message_id: None, + transaction: None, + content: inline_client::MessageContent::Media { + kind: inline_client::MediaKind::Voice, + file_id: format!("voice-{message_id}"), + url: Some(format!("http://127.0.0.1:9/voice-{message_id}.m4a")), + mime_type: Some("audio/mp4".into()), + file_name: Some("voice.m4a".into()), + caption: transcript.map(str::to_owned), + size_bytes: Some(2048), + width: None, + height: None, + duration_ms: Some(duration_ms), + }, + metadata: inline_client::MessageMetadata { + sender_is_bot: Some(false), + edit_timestamp: transcript.map(|_| 2), + ..Default::default() + }, + } +} + +fn received(harness: &FakeHarness) -> Vec { + harness.session.received.lock().unwrap().clone() +} + +fn sends(harness: &FakeHarness) -> usize { + harness.session.sends.load(Ordering::SeqCst) +} + +fn voice_holds(runtime: &Runtime) -> usize { + runtime.agent.ledger.voice_holds().unwrap().len() +} + +/// Past every voice deadline. +fn after_deadlines() -> i64 { + super::voice::now_ms() + 100_000 +} + +#[tokio::test] +async fn a_voice_message_waits_for_its_transcript_and_goes_out_without_its_audio() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + let id = input_id(2, 9, 300, "direct"); + runtime + .on_message(&voice_message(300, 4_000, None)) + .await + .unwrap(); + assert_eq!(state(&runtime, &id), Some(InputState::Pending)); + assert_eq!(voice_holds(&runtime), 1); + // The sender sees the agent working while it waits, repeated until the + // transcript comes. + assert_eq!(runtime.voice_working_sent, [(9, true)]); + runtime.voice_tick(super::voice::now_ms()).await; + assert_eq!(runtime.voice_working_sent.len(), 1, "not yet due again"); + runtime.voice_working_due = Some(tokio::time::Instant::now()); + runtime.voice_tick(super::voice::now_ms()).await; + assert_eq!(runtime.voice_working_sent, [(9, true), (9, true)]); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(sends(&harness), 0, "held for the transcript"); + runtime + .on_message(&voice_message(300, 4_000, Some("Ship the fix today."))) + .await + .unwrap(); + until(|| sends(&harness) == 1).await; + let input = &received(&harness)[0]; + assert_eq!(input.id.as_str(), id); + assert_eq!( + input.content.text, + "Voice message (0:04), transcribed by Inline:\n\nShip the fix today." + ); + assert!(input.content.attachments.is_empty(), "no audio download"); + assert_eq!(voice_holds(&runtime), 0); + // A replayed edit is the same message. + runtime + .on_message(&voice_message(300, 4_000, Some("Ship the fix today."))) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(sends(&harness), 1); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn past_its_deadline_a_voice_message_goes_out_with_its_audio_and_a_late_transcript_follows() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + let id = input_id(2, 9, 301, "direct"); + runtime + .on_message(&voice_message(301, 42_000, None)) + .await + .unwrap(); + // Not yet due: nothing goes out. + runtime.voice_tick(super::voice::now_ms()).await; + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(sends(&harness), 0); + runtime.voice_tick(after_deadlines()).await; + until(|| sends(&harness) == 1).await; + let input = &received(&harness)[0]; + assert_eq!(input.id.as_str(), id); + assert!( + input.content.text.starts_with( + "Review the attached voice message (0:42). Inline hasn't transcribed it yet" + ), + "{}", + input.content.text + ); + assert_eq!(input.content.attachments.len(), 1); + assert_eq!( + input.content.attachments[0].kind, + inline_agent_bridge::InputAttachmentKind::Audio + ); + // The hold stays for a late transcript. + assert!(runtime.agent.ledger.voice_holds().unwrap()[0].delivered_audio); + runtime + .on_message(&voice_message(301, 42_000, Some("Late words."))) + .await + .unwrap(); + until(|| sends(&harness) == 2).await; + let follow_up = &received(&harness)[1]; + assert_eq!( + follow_up.id.as_str(), + input_id(2, 9, 301, "voice-transcript") + ); + assert_eq!( + follow_up.content.text, + "Transcript of the voice message you received earlier (message 301), transcribed by Inline:\n\nLate words." + ); + assert!(follow_up.content.attachments.is_empty()); + assert_eq!(voice_holds(&runtime), 0); + runtime + .on_message(&voice_message(301, 42_000, Some("Late words."))) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(sends(&harness), 2, "the follow-up goes out once"); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn a_held_voice_message_survives_a_restart_and_is_never_reported_lost() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + let found = input_id(2, 9, 302, "direct"); + let waiting = input_id(2, 9, 303, "direct"); + for message_id in [302, 303] { + runtime + .on_message(&voice_message(message_id, 8_000, None)) + .await + .unwrap(); + } + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); + drop(runtime); + let mut restarted = super::faults::runtime(&mut cleanup, harness.clone()); + // Inline has the first transcript by now, not the second. + restarted.voice_lookups.insert( + (9, 302), + proto::Message { + id: 302, + message: Some("Written while you were away.".into()), + edit_date: Some(2), + ..Default::default() + }, + ); + restarted.voice_lookups.insert( + (9, 303), + proto::Message { + id: 303, + ..Default::default() + }, + ); + restarted.recover().await; + until(|| sends(&harness) == 1).await; + let input = &received(&harness)[0]; + assert_eq!(input.id.as_str(), found); + assert_eq!( + input.content.text, + "Voice message (0:08), transcribed by Inline:\n\nWritten while you were away." + ); + // The other keeps waiting for its original deadline: not "restarted + // before this ran". + assert_eq!(state(&restarted, &waiting), Some(InputState::Pending)); + assert_eq!(voice_holds(&restarted), 1); + restarted.voice_tick(after_deadlines()).await; + until(|| sends(&harness) == 2).await; + assert_eq!(received(&harness)[1].id.as_str(), waiting); + assert_eq!(received(&harness)[1].content.attachments.len(), 1); + cleanup.tasks.push(restarted.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn a_restart_past_the_deadline_sends_the_audio_without_asking_again() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + runtime + .on_message(&voice_message(304, 8_000, None)) + .await + .unwrap(); + // The deadline passed while the bridge was down. + { + let mut hold = runtime.agent.ledger.voice_holds().unwrap().remove(0); + runtime + .agent + .ledger + .remove_voice_hold(&hold.input_id) + .unwrap(); + hold.deadline_at_ms = 1; + runtime.agent.ledger.hold_voice(&hold).unwrap(); + } + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); + drop(runtime); + let mut restarted = super::faults::runtime(&mut cleanup, harness.clone()); + restarted.recover().await; + until(|| sends(&harness) == 1).await; + let input = &received(&harness)[0]; + assert_eq!(input.id.as_str(), input_id(2, 9, 304, "direct")); + assert_eq!(input.content.attachments.len(), 1); + assert!( + restarted.agent.ledger.voice_holds().unwrap()[0].delivered_audio, + "a late transcript still follows" + ); + cleanup.tasks.push(restarted.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn voice_too_long_to_transcribe_goes_out_with_its_audio_at_once() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + runtime + .on_message(&voice_message(305, 601_000, None)) + .await + .unwrap(); + until(|| sends(&harness) == 1).await; + let input = &received(&harness)[0]; + assert_eq!(input.content.text, "Review the attached voice message."); + assert_eq!(input.content.attachments.len(), 1); + assert_eq!(voice_holds(&runtime), 0); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn voice_with_its_transcript_goes_out_at_once_without_its_audio() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + runtime + .on_message(&voice_message(306, 12_000, Some("Already transcribed."))) + .await + .unwrap(); + until(|| sends(&harness) == 1).await; + let input = &received(&harness)[0]; + assert_eq!( + input.content.text, + "Voice message (0:12), transcribed by Inline:\n\nAlready transcribed." + ); + assert!(input.content.attachments.is_empty()); + assert_eq!(voice_holds(&runtime), 0); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn stop_drops_a_held_voice_message() { + let (mut runtime, harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + let id = input_id(2, 9, 307, "direct"); + runtime + .on_message(&voice_message(307, 4_000, None)) + .await + .unwrap(); + assert_eq!(voice_holds(&runtime), 1); + let stop = MessageRecord { + chat_id: InlineId::new(9), + message_id: InlineId::new(308), + sender_id: InlineId::new(1), + timestamp: 1, + is_outgoing: false, + reply_to_message_id: None, + transaction: None, + content: inline_client::MessageContent::Text { + text: "/stop".into(), + }, + metadata: inline_client::MessageMetadata { + sender_is_bot: Some(false), + entities: vec![inline_client::MessageEntityRecord { + kind: "TYPE_BOT_COMMAND".into(), + offset: 0, + length: 5, + user_id: None, + agent_id: None, + group_id: None, + chat_id: None, + value: None, + }], + ..Default::default() + }, + }; + runtime.on_message(&stop).await.unwrap(); + assert_eq!(state(&runtime, &id), Some(InputState::Discarded)); + assert_eq!(voice_holds(&runtime), 0); + assert_eq!(runtime.voice_working_sent.last(), Some(&(9, false))); + // Neither the transcript nor the deadline brings it back. + runtime + .on_message(&voice_message(307, 4_000, Some("Never mind."))) + .await + .unwrap(); + runtime.voice_tick(after_deadlines()).await; + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(sends(&harness), 0); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} + +#[tokio::test] +async fn the_apps_stop_drops_held_voice_only_for_someone_who_may_stop() { + let (mut runtime, _harness, mut cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + runtime + .on_message(&voice_message(309, 4_000, None)) + .await + .unwrap(); + until(|| runtime.works[&9].agent_session_id() == Some(1)).await; + let stop = |actor: i64| ClientEvent::AgentSessionControlRequested { + interaction_id: InlineId::new(1), + chat_id: InlineId::new(9), + agent_session_id: InlineId::new(1), + actor_user_id: InlineId::new(actor), + op: proto::AgentSessionControl::Stop as i32, + }; + // Someone without access to this agent. + tokio::time::timeout(Duration::from_secs(5), runtime.handle(&stop(5))) + .await + .expect("handled") + .unwrap(); + assert_eq!(voice_holds(&runtime), 1); + tokio::time::timeout(Duration::from_secs(5), runtime.handle(&stop(1))) + .await + .expect("handled") + .unwrap(); + assert_eq!(voice_holds(&runtime), 0); + assert_eq!( + state(&runtime, &input_id(2, 9, 309, "direct")), + Some(InputState::Discarded) + ); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} diff --git a/cli/src/bridge/v2/ledger.rs b/cli/src/bridge/v2/ledger.rs index ef77e20b4..11de13558 100644 --- a/cli/src/bridge/v2/ledger.rs +++ b/cli/src/bridge/v2/ledger.rs @@ -183,6 +183,16 @@ impl Ledger { key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS v2_voice_holds ( + input_id TEXT PRIMARY KEY, + chat_id INTEGER NOT NULL, + message_id INTEGER NOT NULL, + duration_ms INTEGER, + deadline_at INTEGER NOT NULL, + delivered_audio INTEGER NOT NULL DEFAULT 0, + held TEXT NOT NULL, + created_at INTEGER NOT NULL );", )?; Ok(Self { @@ -586,6 +596,71 @@ impl Ledger { Ok(()) } + /// Holds a recorded voice message until its transcript arrives: the + /// input becomes `pending` and its hold is saved, in one transaction. + pub(crate) fn hold_voice(&self, hold: &VoiceHoldRecord) -> rusqlite::Result<()> { + let mut connection = self.connection.lock().expect("ledger poisoned"); + let tx = connection.transaction()?; + tx.execute( + "UPDATE v2_inputs SET state = ?2, updated_at = ?3 WHERE input_id = ?1", + params![hold.input_id, InputState::Pending.as_str(), now_seconds()], + )?; + tx.execute( + "INSERT INTO v2_voice_holds (input_id, chat_id, message_id, duration_ms, deadline_at, delivered_audio, held, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) ON CONFLICT (input_id) DO NOTHING", + params![ + hold.input_id, + hold.chat_id, + hold.message_id, + hold.duration_ms, + hold.deadline_at_ms, + hold.delivered_audio, + hold.held, + now_seconds() + ], + )?; + tx.commit() + } + + /// Every saved voice hold, oldest first. + pub(crate) fn voice_holds(&self) -> rusqlite::Result> { + let connection = self.connection.lock().expect("ledger poisoned"); + let mut statement = connection.prepare( + "SELECT input_id, chat_id, message_id, duration_ms, deadline_at, delivered_audio, held + FROM v2_voice_holds ORDER BY created_at, rowid", + )?; + statement + .query_map([], |row| { + Ok(VoiceHoldRecord { + input_id: row.get(0)?, + chat_id: row.get(1)?, + message_id: row.get(2)?, + duration_ms: row.get(3)?, + deadline_at_ms: row.get(4)?, + delivered_audio: row.get(5)?, + held: row.get(6)?, + }) + })? + .collect() + } + + /// The voice message went out with its audio; a late transcript still + /// follows it. + pub(crate) fn voice_audio_delivered(&self, input_id: &str) -> rusqlite::Result<()> { + let connection = self.connection.lock().expect("ledger poisoned"); + connection.execute( + "UPDATE v2_voice_holds SET delivered_audio = 1 WHERE input_id = ?1", + [input_id], + )?; + Ok(()) + } + + pub(crate) fn remove_voice_hold(&self, input_id: &str) -> rusqlite::Result<()> { + let connection = self.connection.lock().expect("ledger poisoned"); + connection.execute("DELETE FROM v2_voice_holds WHERE input_id = ?1", [input_id])?; + Ok(()) + } + /// Drops settled records older than `max_age_secs`. pub(crate) fn prune(&self, max_age_secs: i64) -> rusqlite::Result { let connection = self.connection.lock().expect("ledger poisoned"); @@ -620,6 +695,22 @@ fn row_child(row: &rusqlite::Row<'_>) -> rusqlite::Result { }) } +/// A voice message waiting for Inline's transcript (`runtime/voice.rs`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct VoiceHoldRecord { + pub input_id: String, + pub chat_id: i64, + pub message_id: i64, + pub duration_ms: Option, + /// Unix milliseconds: past it, the audio goes out without a transcript. + pub deadline_at_ms: i64, + /// The audio went out at the deadline; the hold stays for a late + /// transcript. + pub delivered_audio: bool, + /// The held input and its routing, as JSON. + pub held: String, +} + /// A task's report waiting for its lead. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct LeadEventRecord { @@ -813,6 +904,43 @@ mod tests { ); } + #[test] + fn a_voice_hold_survives_reopening_and_keeps_its_input_pending() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ledger.sqlite"); + let hold = VoiceHoldRecord { + input_id: "voice".to_owned(), + chat_id: 5, + message_id: 10, + duration_ms: Some(42_000), + deadline_at_ms: 1_700_000_036_000, + delivered_audio: false, + held: r#"{"input":{}}"#.to_owned(), + }; + { + let ledger = Ledger::open(&path).unwrap(); + ledger.begin("voice", 5, 10, 7).unwrap(); + ledger.hold_voice(&hold).unwrap(); + // A replayed hold keeps the first one. + ledger + .hold_voice(&VoiceHoldRecord { + deadline_at_ms: 1, + ..hold.clone() + }) + .unwrap(); + } + let ledger = Ledger::open(&path).unwrap(); + assert_eq!(ledger.voice_holds().unwrap(), vec![hold.clone()]); + assert_eq!( + ledger.get("voice").unwrap().unwrap().state, + InputState::Pending + ); + ledger.voice_audio_delivered("voice").unwrap(); + assert!(ledger.voice_holds().unwrap()[0].delivered_audio); + ledger.remove_voice_hold("voice").unwrap(); + assert!(ledger.voice_holds().unwrap().is_empty()); + } + #[test] fn task_links_and_lead_reports_survive_reopening() { let dir = tempfile::tempdir().unwrap(); diff --git a/cli/src/bridge/v2/runtime.rs b/cli/src/bridge/v2/runtime.rs index b101e0b45..d9db2e158 100644 --- a/cli/src/bridge/v2/runtime.rs +++ b/cli/src/bridge/v2/runtime.rs @@ -486,9 +486,20 @@ pub(crate) struct Runtime { /// Agent messages addressed to this agent that took a loop hop, acted on or /// not: a refused mention streamed in many edits takes one. counted_agent_messages: RecentMessages, + /// Input ID → a voice message waiting for its transcript, as saved in + /// the ledger (`voice.rs`). + voice_holds: HashMap, + /// When "working" is next repeated for held voice messages. + voice_working_due: Option, /// Tests: sent messages as Inline holds them, read instead of asking. #[cfg(test)] cards: HashMap<(i64, i64), super::doc::Doc>, + /// Tests: messages as Inline holds them, read instead of asking. + #[cfg(test)] + voice_lookups: HashMap<(i64, i64), proto::Message>, + /// Tests: the "working" states sent for held voice messages. + #[cfg(test)] + voice_working_sent: Vec<(i64, bool)>, } /// Recent (chat, message) IDs, bounded so a long-lived bridge doesn't grow. @@ -634,8 +645,14 @@ impl Runtime { agent_profiles: None, acted_agent_messages: RecentMessages::default(), counted_agent_messages: RecentMessages::default(), + voice_holds: HashMap::new(), + voice_working_due: None, #[cfg(test)] cards: HashMap::new(), + #[cfg(test)] + voice_lookups: HashMap::new(), + #[cfg(test)] + voice_working_sent: Vec::new(), }) } @@ -734,6 +751,7 @@ impl Runtime { self.publish_pending = false; self.beat(false); } + let voice_wake = self.voice_wake(); tokio::select! { biased; _ = &mut shutdown => break Ok(()), @@ -753,6 +771,16 @@ impl Runtime { self.lead_request(request).await; note_slow("lead", started); } + () = async { + match voice_wake { + Some(at) => tokio::time::sleep_until(at).await, + None => std::future::pending().await, + } + } => { + let started = Instant::now(); + self.voice_tick(voice::now_ms()).await; + note_slow("voice", started); + } _ = connection.tick() => { let started = Instant::now(); self.keep_connected().await; @@ -853,10 +881,16 @@ impl Runtime { return; } }; + // Voice messages waiting for their transcript were never lost: they + // resume below. + let held = self.saved_voice_holds(); // Written but unconfirmed: the thread's session settles them when it // opens, by what it shows it already consumed. let mut uncertain: HashMap> = HashMap::new(); for record in unresolved { + if held.contains(&record.input_id) { + continue; + } if matches!(record.state, InputState::Unknown | InputState::Sent) && let Ok(input) = InputId::new(record.input_id.clone()) { @@ -942,6 +976,7 @@ impl Runtime { for lead in leads { self.deliver_lead_events(lead).await; } + self.resume_voice_holds().await; let _ = self.agent.ledger.prune(LEDGER_RETENTION_SECS); } @@ -1230,6 +1265,17 @@ impl Runtime { Ok(proto::AgentSessionControl::Resume) => Some(Control::Resume), _ => None, }; + // Only someone who may stop the work stops its voice holds; + // the work checks its own controls. + if let (Some(chat), Some(Control::Stop)) = (chat, control) + && self + .access + .grants(actor_user_id.get()) + .await + .permits(Operation::Stop) + { + self.cancel_voice_holds(chat); + } let toast = match (chat, control) { (Some(chat), Some(control)) => { self.ask(chat, |reply| Command::Control { @@ -2023,16 +2069,16 @@ impl Runtime { skills.into_iter().find(|skill| skill.answers_to(name)) } - /// Applies the thread's or mentioned Skilled Agent to a message. False - /// when the message must not run. - async fn apply_agent_profile( + /// The thread's or mentioned Skilled Agent this message runs as (`Ok(None)`: this bot's + /// default), applied with [`Self::as_skilled_agent`]. `Err` when it + /// cannot run; the sender was told. + async fn agent_profile( &self, message: &MessageRecord, chat_id: i64, - input: &mut Input, - ) -> bool { + ) -> Result, ()> { let Some((resolver, store)) = &self.agent_profiles else { - return true; + return Ok(None); }; let bot_user_id = self.config.bot_user_id; let thread_agent = store @@ -2046,14 +2092,10 @@ impl Runtime { .map(InlineId::get); let Some(agent_id) = thread_agent.or_else(|| mentioned_agent_id(message, bot_user_id)) else { - return true; + return Ok(None); }; match resolver.resolve(agent_id).await { - Some(agent) if agent.bot_user_id == bot_user_id => { - input.content.text = - skills::specialized_task(self.config.vocabulary, &agent, &input.content.text); - true - } + Some(agent) if agent.bot_user_id == bot_user_id => Ok(Some(agent_id)), Some(_) => { self.reply( chat_id, @@ -2061,7 +2103,7 @@ impl Runtime { "The selected Skilled Agent does not belong to this provider.", ) .await; - false + Err(()) } None => { self.reply( @@ -2070,7 +2112,7 @@ impl Runtime { "The selected Skilled Agent is unavailable, so I’m continuing with this bot’s default behavior.", ) .await; - true + Ok(None) } } } @@ -2935,6 +2977,11 @@ impl Runtime { { return Ok(None); } + // A held voice message's transcript edit releases it; it was decided + // on when it arrived. + if widget_call.is_none() && self.voice_update(message).await { + return Ok(None); + } // A sender the local store has not met yet: ask Inline whether it is // an agent, so the loop cap sees agents it never saw before. let resolved; @@ -3363,6 +3410,12 @@ impl Runtime { } else { 0 }; + // Voice messages waiting for their transcript stop waiting. + let stopped_voice = if matches!(control, Control::Stop) { + self.cancel_voice_holds(chat_id) + } else { + 0 + }; let toast = if self.works.contains_key(&chat_id) { self.ask(chat_id, |reply| Command::Control { control, @@ -3373,6 +3426,20 @@ impl Runtime { } else { Some("Nothing is running in this thread.".to_owned()) }; + let toast = match toast { + Some(toast) if stopped_voice > 0 && toast.starts_with("Nothing is running") => { + Some(format!( + "Stopped waiting for {} voice message{}.", + if stopped_voice == 1 { + "the".to_owned() + } else { + stopped_voice.to_string() + }, + plural(stopped_voice) + )) + } + toast => toast, + }; let toast = match (stopped_tasks, toast) { (0, toast) => toast, (count, None) => Some(format!( @@ -3449,24 +3516,8 @@ impl Runtime { // A command this agent does not handle. return Ok(()); }; - // Media reaches the harness as local files, like v1. - if let Some(content) = crate::bridge::runtime::normalize_inbound_content( - &message.content, - &message.metadata.entities, - self.config.bot_user_id, - ) { - if !content.attachments.is_empty() { - input.content.attachments = - crate::bridge::runtime::materialize_inbound_attachments( - &content.attachments, - &self.config.attachments_dir, - ) - .await; - } - if input.content.text.trim().is_empty() { - input.content.text = content.text; - } - } + // Recorded before any download: an edit or a replay of a message + // already taken never fetches its media again. match self .agent .ledger @@ -3475,11 +3526,33 @@ impl Runtime { Begin::Seen(_) => return Ok(()), Begin::New { .. } => {} } - if group.command().is_none() - && !self.apply_agent_profile(message, chat_id, &mut input).await - { - self.agent.ledger.set(&id, InputState::Consumed)?; - return Ok(()); + let agent_id = if group.command().is_none() { + match self.agent_profile(message, chat_id).await { + Ok(agent_id) => agent_id, + Err(()) => { + self.agent.ledger.set(&id, InputState::Consumed)?; + return Ok(()); + } + } + } else { + None + }; + let voice = voice::VoiceText::of(message); + // Media reaches the harness as local files, like v1. A voice + // message's transcript stands in for its audio. + let mut attachments = Vec::new(); + if let Some(content) = crate::bridge::runtime::normalize_inbound_content( + &message.content, + &message.metadata.entities, + self.config.bot_user_id, + ) { + attachments = content.attachments; + if let voice::VoiceText::Transcript { duration_ms } = voice { + input.content.text = voice::transcript_text(duration_ms, &content.text); + attachments.clear(); + } else if input.content.text.trim().is_empty() { + input.content.text = content.text; + } } if let Err(error) = self.ensure_work(chat_id, participation.as_ref()).await { if error.downcast_ref::().is_some() { @@ -3495,18 +3568,74 @@ impl Runtime { sender: UserId(group.author.user_id), required, }; - let work = self.works.get(&chat_id).expect("work"); + // An agent's answer to this agent's request is not quoted: quoting + // would wake it again. + let answer_reply = matches!(group.conversation, Conversation::Group) + && !(required == Operation::HandBack && group.author.kind.is_agent()); + let reply_to = group.reply_to.as_ref().map(|reply| reply.message_id); + if let voice::VoiceText::Awaiting { duration_ms } = voice { + // Held without text or download; the transcript, or the audio + // at the deadline, fills it in. + let mut held = input.clone(); + held.content.text.clear(); + held.content.attachments = attachments.clone(); + let held = voice::Held { + input: held, + sender: group.author.user_id, + required, + answer_reply, + reply_to, + agent_id, + }; + if self + .hold_voice(chat_id, group.message_id, duration_ms, &held) + .await + { + return Ok(()); + } + } + if !attachments.is_empty() { + input.content.attachments = crate::bridge::runtime::materialize_inbound_attachments( + &attachments, + &self.config.attachments_dir, + ) + .await; + } + input.content.text = self.as_skilled_agent(agent_id, input.content.text).await; + self.send_input( + chat_id, + input, + pending, + group.message_id, + answer_reply, + reply_to, + ) + .await + } + + /// Hands recorded input to the thread's work. + async fn send_input( + &mut self, + chat_id: i64, + input: Input, + pending: PendingInput, + message_id: i64, + answer_reply: bool, + reply_to: Option, + ) -> Result<(), Box> { + let id = input.id.as_str().to_owned(); + let Some(work) = self.works.get(&chat_id) else { + self.agent.ledger.set(&id, InputState::Failed)?; + return Err("the work stopped; send the message again".into()); + }; if work .tx .send(Command::Input { input: Box::new(input), pending, - message_id: group.message_id, - // An agent's answer to this agent's request is not quoted: - // quoting would wake it again. - answer_reply: matches!(group.conversation, Conversation::Group) - && !(required == Operation::HandBack && group.author.kind.is_agent()), - reply_to: group.reply_to.as_ref().map(|reply| reply.message_id), + message_id, + answer_reply, + reply_to, }) .await .is_err() @@ -6160,6 +6289,9 @@ mod tests { } } +#[path = "voice.rs"] +mod voice; + #[cfg(test)] #[path = "faults.rs"] mod faults; diff --git a/cli/src/bridge/v2/voice.rs b/cli/src/bridge/v2/voice.rs new file mode 100644 index 000000000..af41d0078 --- /dev/null +++ b/cli/src/bridge/v2/voice.rs @@ -0,0 +1,665 @@ +//! Voice messages wait for Inline's transcript (voice transcription, phase 0). +//! +//! The server transcribes a voice message sent without text in the +//! background, and edits the transcript into the message's text seconds +//! later. When it skips one (the sender turned transcription off, audio over +//! ten minutes, a failure), nothing arrives. So once the runtime decides to +//! act on a voice message with no text, it holds the input, saved in the +//! ledger, until the transcript edit or a deadline set by the audio's length: +//! +//! - the transcript first: the agent gets it as the message's text, and the +//! audio is never downloaded; +//! - the deadline first: the agent gets the audio, as before, and a later +//! transcript follows as its own input; +//! - a restart: each hold resumes from the ledger, and Inline is asked for +//! the message again. +//! +//! `/stop` and the apps' Stop drop the thread's holds. + +use inline_agent_bridge::InputAttachment; +use serde::{Deserialize, Serialize}; + +use super::*; +use crate::bridge::v2::ledger::VoiceHoldRecord; + +/// The shortest wait: the server usually answers within a few seconds. +const BASE_WAIT_MS: u64 = 15_000; +const MAX_WAIT_MS: u64 = 90_000; +/// The server never transcribes longer audio. +const MAX_TRANSCRIBED_MS: u64 = 600_000; +/// After the audio went out, how long a transcript still follows it. +const LATE_TRANSCRIPT_WINDOW_MS: i64 = 10 * 60 * 1000; +/// Like v1: past this many open holds, voice goes out right away. +const MAX_OPEN_HOLDS: usize = 64; +/// The apps drop "working" after a few seconds unless it is repeated. +const WORKING_REFRESH: Duration = Duration::from_secs(3); +const WORKING_SEND_TIMEOUT: Duration = Duration::from_secs(2); + +/// What a message's text is, for voice. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum VoiceText { + /// Not a voice message. + NotVoice, + /// No text and never edited: a transcript may still come. + Awaiting { duration_ms: Option }, + /// No text, and none will come: too long to transcribe, or edited and + /// still empty. + Missing, + /// Text the server edited in: the transcript. + Transcript { duration_ms: Option }, + /// Sent with text: the sender's own caption, so the audio matters. + Caption, +} + +impl VoiceText { + pub(super) fn of(message: &MessageRecord) -> Self { + let inline_client::MessageContent::Media { + kind: inline_client::MediaKind::Voice, + caption, + duration_ms, + .. + } = &message.content + else { + return Self::NotVoice; + }; + let duration_ms = *duration_ms; + let has_text = caption + .as_deref() + .is_some_and(|caption| !caption.trim().is_empty()); + // The server only transcribes voice sent without text, and writes + // the transcript with an edit. + match (has_text, message.metadata.edit_timestamp.is_some()) { + (true, true) => Self::Transcript { duration_ms }, + (true, false) => Self::Caption, + (false, true) => Self::Missing, + (false, false) if duration_ms.is_some_and(|ms| ms > MAX_TRANSCRIBED_MS) => { + Self::Missing + } + (false, false) => Self::Awaiting { duration_ms }, + } + } +} + +/// How long a voice message waits for its transcript: 15 s plus half its +/// length, at most 90 s. +pub(super) fn wait_ms(duration_ms: Option) -> u64 { + BASE_WAIT_MS + .saturating_add(duration_ms.unwrap_or_default() / 2) + .min(MAX_WAIT_MS) +} + +/// " (1:05)", or nothing when the length is unknown. +fn length(duration_ms: Option) -> String { + duration_ms.map_or_else(String::new, |ms| { + let seconds = ms.div_ceil(1000); + format!(" ({}:{:02})", seconds / 60, seconds % 60) + }) +} + +pub(super) fn transcript_text(duration_ms: Option, transcript: &str) -> String { + format!( + "Voice message{}, transcribed by Inline:\n\n{transcript}", + length(duration_ms) + ) +} + +fn audio_text(duration_ms: Option) -> String { + format!( + "Review the attached voice message{}. Inline hasn't transcribed it yet; if a transcript arrives, it follows as a separate message.", + length(duration_ms) + ) +} + +fn follow_up_text(message_id: i64, transcript: &str) -> String { + format!( + "Transcript of the voice message you received earlier (message {message_id}), transcribed by Inline:\n\n{transcript}" + ) +} + +pub(super) fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_millis() as i64) +} + +/// A held input and how it goes to the work once its text is known. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(super) struct Held { + /// Without text; the audio's attachment is not downloaded yet. + pub input: Input, + pub sender: i64, + pub required: Operation, + pub answer_reply: bool, + pub reply_to: Option, + /// The Skilled Agent the input runs as, applied once its text is known. + pub agent_id: Option, +} + +impl VoiceHoldRecord { + fn held(&self) -> Option { + serde_json::from_str(&self.held) + .map_err(|error| { + log::warn!(target: "inline::bridge::v2", "voice hold {} unreadable: {error}", self.input_id); + }) + .ok() + } + + fn duration(&self) -> Option { + self.duration_ms.and_then(|ms| u64::try_from(ms).ok()) + } + + /// When the hold next needs attention: its deadline, or the end of the + /// late-transcript window once the audio went out. + fn due_ms(&self) -> i64 { + if self.delivered_audio { + self.deadline_at_ms + .saturating_add(LATE_TRANSCRIPT_WINDOW_MS) + } else { + self.deadline_at_ms + } + } +} + +impl Runtime { + /// Holds an acted-on voice message until its transcript or deadline. + /// False when it should go out now instead. + pub(super) async fn hold_voice( + &mut self, + chat_id: i64, + message_id: i64, + duration_ms: Option, + held: &Held, + ) -> bool { + let open = self + .voice_holds + .values() + .filter(|hold| !hold.delivered_audio) + .count(); + if open >= MAX_OPEN_HOLDS { + log::warn!(target: "inline::bridge::v2", "chat={chat_id} message={message_id} voice not held: {open} already waiting"); + return false; + } + let record = VoiceHoldRecord { + input_id: held.input.id.as_str().to_owned(), + chat_id, + message_id, + duration_ms: duration_ms.and_then(|ms| i64::try_from(ms).ok()), + deadline_at_ms: now_ms().saturating_add(wait_ms(duration_ms) as i64), + delivered_audio: false, + held: match serde_json::to_string(held) { + Ok(held) => held, + Err(error) => { + log::warn!(target: "inline::bridge::v2", "chat={chat_id} voice not held: {error}"); + return false; + } + }, + }; + if let Err(error) = self.agent.ledger.hold_voice(&record) { + log::warn!(target: "inline::bridge::v2", "chat={chat_id} voice not held: {error}"); + return false; + } + log::debug!( + target: "inline::bridge::v2", + "chat={chat_id} message={message_id} voice held for its transcript, {} ms", + record.deadline_at_ms - now_ms() + ); + self.voice_holds.insert(record.input_id.clone(), record); + // Show the sender the agent has it while it waits. + self.voice_working_due = None; + self.refresh_voice_working(); + true + } + + /// A later copy of a message (its transcript edit, a replay). True when + /// it belonged to a hold and needs nothing more. + pub(super) async fn voice_update(&mut self, message: &MessageRecord) -> bool { + if self.voice_holds.is_empty() || VoiceText::of(message) == VoiceText::NotVoice { + return false; + } + let id = input_id( + self.config.bot_user_id, + message.chat_id.get(), + message.message_id.get(), + "direct", + ); + let Some(hold) = self.voice_holds.get(&id).cloned() else { + return false; + }; + if let VoiceText::Transcript { .. } = VoiceText::of(message) + && let Some(content) = crate::bridge::runtime::normalize_inbound_content( + &message.content, + &message.metadata.entities, + self.config.bot_user_id, + ) + { + self.transcribed(hold, &content.text).await; + } + true + } + + /// The transcript arrived: it goes out as the held input, or after the + /// audio as a follow-up. + async fn transcribed(&mut self, hold: VoiceHoldRecord, transcript: &str) { + self.forget_voice_hold(&hold.input_id); + let Some(mut held) = hold.held() else { + return; + }; + if hold.delivered_audio { + let id = input_id( + self.config.bot_user_id, + hold.chat_id, + hold.message_id, + "voice-transcript", + ); + match self + .agent + .ledger + .begin(&id, hold.chat_id, hold.message_id, held.sender) + { + Ok(Begin::New { .. }) => {} + Ok(Begin::Seen(_)) => return, + Err(error) => { + log::warn!(target: "inline::bridge::v2", "chat={} voice transcript not recorded: {error}", hold.chat_id); + return; + } + } + let Ok(id) = InputId::new(id) else { + return; + }; + held.input.id = id; + held.input.content.context = None; + held.input.delivery = Delivery::Turn; + let text = follow_up_text(hold.message_id, transcript); + self.send_held(&hold, held, text, Vec::new()).await; + } else { + let text = transcript_text(hold.duration(), transcript); + self.send_held(&hold, held, text, Vec::new()).await; + } + } + + /// The deadline passed first: the audio goes out, and the hold stays for + /// a late transcript. + async fn voice_deadline(&mut self, hold: VoiceHoldRecord) { + let Some(held) = hold.held() else { + self.forget_voice_hold(&hold.input_id); + return; + }; + let attachments = crate::bridge::runtime::materialize_inbound_attachments( + &held.input.content.attachments, + &self.config.attachments_dir, + ) + .await; + let _ = self.agent.ledger.voice_audio_delivered(&hold.input_id); + if let Some(open) = self.voice_holds.get_mut(&hold.input_id) { + open.delivered_audio = true; + } + self.send_held(&hold, held, audio_text(hold.duration()), attachments) + .await; + } + + async fn send_held( + &mut self, + hold: &VoiceHoldRecord, + mut held: Held, + text: String, + attachments: Vec, + ) { + held.input.content.text = self.as_skilled_agent(held.agent_id, text).await; + held.input.content.attachments = attachments; + let pending = PendingInput { + id: held.input.id.clone(), + sender: UserId(held.sender), + required: held.required, + }; + let id = held.input.id.as_str().to_owned(); + let opened = self + .ensure_work(hold.chat_id, None) + .await + .map_err(|error| error.to_string()); + let sent = match opened { + Ok(()) => self + .send_input( + hold.chat_id, + held.input, + pending, + hold.message_id, + held.answer_reply, + held.reply_to, + ) + .await + .map_err(|error| error.to_string()), + Err(error) => { + let _ = self.agent.ledger.set(&id, InputState::Failed); + Err(error) + } + }; + if let Err(error) = sent { + // Nothing reached the agent, so no late transcript follows it. + self.forget_voice_hold(&hold.input_id); + log::warn!(target: "inline::bridge::v2", "chat={} voice message not delivered: {error}", hold.chat_id); + self.reply( + hold.chat_id, + hold.message_id, + &format!( + "{} could not take this voice message: {error}", + self.config.agent_name + ), + ) + .await; + } + } + + /// The Skilled Agent's instructions around `text`, as the input had them + /// when it was held. + pub(super) async fn as_skilled_agent(&self, agent_id: Option, text: String) -> String { + let (Some(agent_id), Some((resolver, _))) = (agent_id, &self.agent_profiles) else { + return text; + }; + match resolver.resolve(agent_id).await { + Some(agent) if agent.bot_user_id == self.config.bot_user_id => { + skills::specialized_task(self.config.vocabulary, &agent, &text) + } + _ => text, + } + } + + fn forget_voice_hold(&mut self, input_id: &str) { + self.voice_holds.remove(input_id); + if let Err(error) = self.agent.ledger.remove_voice_hold(input_id) { + log::warn!(target: "inline::bridge::v2", "voice hold not removed: {error}"); + } + } + + /// `/stop` and the apps' Stop: the thread's voice messages stop waiting + /// and their late transcripts no longer follow. How many were still + /// waiting. + pub(super) fn cancel_voice_holds(&mut self, chat_id: i64) -> usize { + let holds: Vec = self + .voice_holds + .values() + .filter(|hold| hold.chat_id == chat_id) + .cloned() + .collect(); + for hold in &holds { + if !hold.delivered_audio { + let _ = self.agent.ledger.set(&hold.input_id, InputState::Discarded); + } + self.forget_voice_hold(&hold.input_id); + } + let waiting = holds.iter().filter(|hold| !hold.delivered_audio).count(); + if waiting > 0 { + self.send_voice_working(chat_id, false); + } + waiting + } + + /// When the run loop next calls [`Self::voice_tick`]. + pub(super) fn voice_wake(&self) -> Option { + let due_ms = self + .voice_holds + .values() + .map(VoiceHoldRecord::due_ms) + .min()?; + let wait = u64::try_from(due_ms.saturating_sub(now_ms())).unwrap_or_default(); + let due = tokio::time::Instant::now() + Duration::from_millis(wait); + Some(match self.voice_working_due { + Some(working) if self.awaiting_voice() => due.min(working), + _ => due, + }) + } + + /// Delivers holds past their deadline, drops late-transcript windows that + /// ended, and keeps "working" showing for the rest. + pub(super) async fn voice_tick(&mut self, now_ms: i64) { + let mut due: Vec = self + .voice_holds + .values() + .filter(|hold| hold.due_ms() <= now_ms) + .cloned() + .collect(); + due.sort_by_key(|hold| hold.deadline_at_ms); + for hold in due { + if hold.delivered_audio { + self.forget_voice_hold(&hold.input_id); + } else { + self.voice_deadline(hold).await; + } + } + self.refresh_voice_working(); + } + + fn awaiting_voice(&self) -> bool { + self.voice_holds.values().any(|hold| !hold.delivered_audio) + } + + fn refresh_voice_working(&mut self) { + let now = tokio::time::Instant::now(); + if self.voice_working_due.is_some_and(|due| due > now) { + return; + } + let chats: HashSet = self + .voice_holds + .values() + .filter(|hold| !hold.delivered_audio) + .map(|hold| hold.chat_id) + .collect(); + if chats.is_empty() { + self.voice_working_due = None; + return; + } + self.voice_working_due = Some(now + WORKING_REFRESH); + for chat_id in chats { + self.send_voice_working(chat_id, true); + } + } + + /// Best effort and off the run loop, like the work's own "working". + fn send_voice_working(&mut self, chat_id: i64, working: bool) { + #[cfg(test)] + self.voice_working_sent.push((chat_id, working)); + let bot = self.agent.bot.clone(); + tokio::spawn(async move { + let _ = tokio::time::timeout( + WORKING_SEND_TIMEOUT, + api::send_working(&bot, chat_id, working), + ) + .await; + }); + } + + /// Inputs held for a transcript a previous run saved: `recover` must not + /// report them as lost. + pub(super) fn saved_voice_holds(&self) -> HashSet { + self.agent + .ledger + .voice_holds() + .unwrap_or_default() + .into_iter() + .filter(|hold| !hold.delivered_audio) + .map(|hold| hold.input_id) + .collect() + } + + /// After a restart: each saved hold looks its message up again. A + /// transcript goes out now; otherwise the hold waits out its original + /// deadline, or goes out with its audio if that passed. + pub(super) async fn resume_voice_holds(&mut self) { + let holds = match self.agent.ledger.voice_holds() { + Ok(holds) => holds, + Err(error) => { + log::warn!(target: "inline::bridge::v2", "voice holds unreadable: {error}"); + return; + } + }; + let now = now_ms(); + for hold in holds { + let open = !hold.delivered_audio + && self + .agent + .ledger + .get(&hold.input_id) + .ok() + .flatten() + .is_some_and(|record| record.state == InputState::Pending); + let following = hold.delivered_audio && hold.due_ms() > now; + if !open && !following { + self.forget_voice_hold(&hold.input_id); + continue; + } + self.voice_holds.insert(hold.input_id.clone(), hold.clone()); + if let Some(transcript) = self + .voice_transcript_in_inline(hold.chat_id, hold.message_id) + .await + { + self.transcribed(hold, &transcript).await; + } + } + self.voice_tick(now_ms()).await; + } + + /// The message's text as Inline holds it now. + async fn voice_transcript_in_inline(&self, chat_id: i64, message_id: i64) -> Option { + #[cfg(test)] + let fetched: Result, String> = self + .voice_lookups + .get(&(chat_id, message_id)) + .cloned() + .map(|message| vec![message]) + .ok_or_else(|| "not in this test's Inline".to_owned()); + #[cfg(not(test))] + let fetched = api::get_messages(&self.agent.bot, chat_id, vec![message_id]) + .await + .map_err(|error| error.to_string()); + match fetched { + Ok(messages) => text_of(messages, message_id), + Err(error) => { + log::warn!(target: "inline::bridge::v2", "chat={chat_id} voice message lookup failed: {error}"); + None + } + } + } +} + +/// A looked-up message's text, when it has any. +fn text_of(messages: Vec, message_id: i64) -> Option { + messages + .into_iter() + .find(|message| message.id == message_id) + .and_then(|message| message.message) + .map(|text| text.trim().to_owned()) + .filter(|text| !text.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn voice(caption: Option<&str>, edited: bool, duration_ms: Option) -> MessageRecord { + MessageRecord { + chat_id: InlineId::new(9), + message_id: InlineId::new(1), + sender_id: InlineId::new(1), + timestamp: 1, + is_outgoing: false, + reply_to_message_id: None, + transaction: None, + content: inline_client::MessageContent::Media { + kind: inline_client::MediaKind::Voice, + file_id: "v".into(), + url: None, + mime_type: None, + file_name: None, + caption: caption.map(str::to_owned), + size_bytes: None, + width: None, + height: None, + duration_ms, + }, + metadata: inline_client::MessageMetadata { + edit_timestamp: edited.then_some(2), + ..Default::default() + }, + } + } + + #[test] + fn the_wait_grows_with_the_audio_and_stops_at_ninety_seconds() { + assert_eq!(wait_ms(None), 15_000); + assert_eq!(wait_ms(Some(0)), 15_000); + assert_eq!(wait_ms(Some(42_000)), 36_000); + assert_eq!(wait_ms(Some(150_000)), 90_000); + assert_eq!(wait_ms(Some(600_000)), 90_000); + } + + #[test] + fn only_voice_without_text_that_can_be_transcribed_waits() { + assert_eq!( + VoiceText::of(&voice(None, false, Some(42_000))), + VoiceText::Awaiting { + duration_ms: Some(42_000) + } + ); + assert_eq!( + VoiceText::of(&voice(Some(" "), false, None)), + VoiceText::Awaiting { duration_ms: None } + ); + assert_eq!( + VoiceText::of(&voice(None, false, Some(600_000))), + VoiceText::Awaiting { + duration_ms: Some(600_000) + } + ); + assert_eq!( + VoiceText::of(&voice(None, false, Some(600_001))), + VoiceText::Missing + ); + assert_eq!(VoiceText::of(&voice(None, true, None)), VoiceText::Missing); + assert_eq!( + VoiceText::of(&voice(Some("hello"), true, Some(3_000))), + VoiceText::Transcript { + duration_ms: Some(3_000) + } + ); + assert_eq!( + VoiceText::of(&voice(Some("listen"), false, None)), + VoiceText::Caption + ); + let mut text = voice(None, false, None); + text.content = inline_client::MessageContent::Text { text: "hi".into() }; + assert_eq!(VoiceText::of(&text), VoiceText::NotVoice); + } + + #[test] + fn a_looked_up_message_gives_its_own_text() { + let message = |id: i64, text: Option<&str>| proto::Message { + id, + message: text.map(str::to_owned), + ..Default::default() + }; + assert_eq!( + text_of( + vec![message(4, Some("other")), message(5, Some(" Hello. \n"))], + 5 + ) + .as_deref(), + Some("Hello.") + ); + assert_eq!(text_of(vec![message(5, Some(" "))], 5), None); + assert_eq!(text_of(vec![message(5, None)], 5), None); + assert_eq!(text_of(vec![message(4, Some("other"))], 5), None); + } + + #[test] + fn texts_name_the_voice_message_and_its_length() { + assert_eq!( + transcript_text(Some(65_000), "Ship it."), + "Voice message (1:05), transcribed by Inline:\n\nShip it." + ); + assert_eq!( + transcript_text(None, "Ship it."), + "Voice message, transcribed by Inline:\n\nShip it." + ); + assert!(audio_text(Some(1_200)).starts_with("Review the attached voice message (0:02).")); + assert!(follow_up_text(12, "Ship it.").contains("(message 12)")); + } +}