From 20240c1027bb50a75c522e3421cf6d7974e829fb Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 27 Nov 2026 16:33:15 +0300 Subject: [PATCH] Bind received whispers and replies to the original sender identity --- CHANGELOG.md | 2 + FEATURE_COMPATIBILITY.md | 2 + core/examples/duplex_qa.rs | 83 ++++++------ core/src/output.rs | 13 +- core/src/session.rs | 37 +++++- docs/bridge.md | 4 +- docs/mobile-port-progress.md | 2 + .../src/app/runtime/local_actions/whispers.rs | 119 +++++++++++++----- .../src/app/runtime/notification_actions.rs | 4 +- .../media/audio/notification_sound_cases.rs | 2 +- native/src/services/notifications.rs | 7 +- native/src/services/notifications_tests.rs | 10 +- 12 files changed, 205 insertions(+), 80 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3091dc5..56831ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Whisper history and notifications use the sender captured at receipt. A guest who later receives the same client number cannot inherit the original guest's reply action. + - Channel commanders have a separate indicator in the detailed tree. The compact tree uses the saved commander lamp setting. Only the user's own row offers a commander change, and its confirmation reflects the current server flag. - Participant volume changes while dragging the fader; releasing it saves the gain by UID. Mute stays local to the connection. Reset removes the saved modifier and unmutes the participant. diff --git a/FEATURE_COMPATIBILITY.md b/FEATURE_COMPATIBILITY.md index 9ca9d8e..5193251 100644 --- a/FEATURE_COMPATIBILITY.md +++ b/FEATURE_COMPATIBILITY.md @@ -2,6 +2,8 @@ ## Current Windows account-free checkpoint (2026-11-26) +**Whisper sender identity on Windows:** The native client records the UID and nickname captured by the receiving core. A later roster cannot turn an unknown sender or a recycled client number into a reply target. On private beta14, two diagnostic cores matched the receipt to the sender roster under Allow All, observed neither playback nor a receipt under Deny All, then received an identified whisper after re-enabling. The connected Slint receive selector persisted Deny All across profile reopen. Three core and four native regression checks passed separately. A physical Reply shortcut and live recipient-number reassignment were not exercised. + **Channel commander on Windows:** Slint rendering tests verified the compact lamp versus separate icon, the detailed-tree icon, and preference persistence in English/dark and Russian/light fixtures. On private beta14 the other guest's menu had no commander action. The server refused the self change with PermissionsClientInsufficient; both flags remained off and the old confirmation could not affect the replacement identity. Four native checks and two core checks passed. A successful authorized commander change on beta14 remains unverified. **Participant volume:** On private beta14 the Slint fader applied -10 dB during the drag without saving it, then persisted it on release. Muting the peer did not change the listener's own gain. Reconnecting the listener restored -10 dB for the peer without restoring mute; Reset returned the gain to 0 dB and removed the stored modifier. Twelve native checks covered ordering, persistence and error handling. Three core tests covered two-speaker Opus mixing, stale queued audio and reused client numbers. No physical capture or playback device was used. diff --git a/core/examples/duplex_qa.rs b/core/examples/duplex_qa.rs index 055a83b..2eb02cb 100644 --- a/core/examples/duplex_qa.rs +++ b/core/examples/duplex_qa.rs @@ -96,12 +96,12 @@ struct Line { value: Value, } -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(PartialEq, Eq)] enum Seen { Playback { from: u64, tone: Option }, RemoteStarted(u64), RemoteStopped, - WhisperReceived(u64), + WhisperReceived(Value), LocalStarted, Muted, Offline, @@ -264,10 +264,7 @@ impl Peer { Some(Seen::RemoteStopped) } } - Some("whisper_received") => { - let from = value["client_id"].as_u64().ok_or("whisper_received without client ID")?; - Some(Seen::WhisperReceived(from)) - } + Some("whisper_received") => Some(Seen::WhisperReceived(value)), Some("audio") => { let from = value["speakers"].as_array().filter(|s| s.len() == 1) .and_then(|s| s[0].as_u64()).ok_or("expected exactly one decoded speaker")?; @@ -448,8 +445,8 @@ impl Duplex { fn receipt(peer: &Peer, phase: &str, from: u64, expected: usize, since: Instant) -> Result { let mut found: Option = None; let mut remote_started = false; - for &(at, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) { - match seen { + for &(at, ref seen) in peer.seen.iter().filter(|(at, _)| *at >= since) { + match *seen { Seen::RemoteStarted(id) if id == from => remote_started = true, Seen::RemoteStarted(_) => { return Err(format!("{phase}: {}: talking start from the wrong peer; {}", @@ -483,8 +480,8 @@ impl Duplex { fn evidence(peer: &Peer, since: Instant) -> String { let mut tones = [0usize; HZ.len()]; let (mut unknown, mut starts, mut stops, mut whispers, mut tx_starts, mut muted, mut offline) = (0, 0, 0, 0, 0, 0, 0); - for &(_, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) { - match seen { + for &(_, ref seen) in peer.seen.iter().filter(|(at, _)| *at >= since) { + match *seen { Seen::Playback { tone: Some(tone), .. } => tones[tone] += 1, Seen::Playback { tone: None, .. } => unknown += 1, Seen::RemoteStarted(_) => starts += 1, @@ -503,8 +500,8 @@ impl Duplex { let block_remote = !matches!(receive, ReceiveGate::Open); let mut permitted_tail = 0; let mut blocked_events = 0; - for &(at, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) { - let forbidden = match seen { + for &(at, ref seen) in peer.seen.iter().filter(|(at, _)| *at >= since) { + let forbidden = match *seen { Seen::LocalStarted => block_local, Seen::RemoteStarted(_) | Seen::WhisperReceived(_) => block_remote, Seen::Playback { from, tone } => match receive { @@ -604,7 +601,7 @@ fn exercise(exe: &Path, root: &Path) -> Result { let mute_phase = "input mute (900 Hz blocked marker)"; Duplex::check_gate(&qa.a, mute_phase, muted.first, true, ReceiveGate::Open)?; Duplex::check_gate(&qa.b, mute_phase, muted.first, false, ReceiveGate::Closed)?; - if !qa.a.seen.iter().any(|&(at, seen)| at >= muted.first && seen == Seen::Muted) { + if !qa.a.seen.iter().any(|(at, seen)| *at >= muted.first && *seen == Seen::Muted) { return Err(format!("{mute_phase}: no core input rejection; {}", Duplex::evidence(&qa.a, muted.first))); } qa.mute_a(false)?; @@ -636,7 +633,7 @@ fn exercise(exe: &Path, root: &Path) -> Result { let offline_phase = "old session (1450 Hz blocked marker)"; Duplex::check_gate(&qa.a, offline_phase, disconnected, true, ReceiveGate::Closed)?; Duplex::check_gate(&qa.b, offline_phase, old, true, ReceiveGate::Closed)?; - if !qa.a.seen.iter().any(|&(at, seen)| at >= old && seen == Seen::Offline) + if !qa.a.seen.iter().any(|(at, seen)| *at >= old && *seen == Seen::Offline) || qa.a.state_changes != offline_changes { return Err(format!("{offline_phase}: no offline rejection or connection state changed; {}", Duplex::evidence(&qa.a, old))); @@ -687,7 +684,7 @@ fn whisper_spurt(qa: &mut Duplex, target_id: u64, target_uid: &str, tone: usize) let epoch = WHISPER_TAGS[tone].ok_or("whisper probe must carry an epoch")?; start_whisper(qa, target_id, target_uid, epoch)?; let burst = qa.burst(Some(tone), None, 42)?; - if !qa.a.transmitting || !qa.a.seen.iter().any(|&(at, seen)| at >= burst.first && seen == Seen::LocalStarted) { + if !qa.a.transmitting || !qa.a.seen.iter().any(|(at, seen)| *at >= burst.first && *seen == Seen::LocalStarted) { return Err(format!("{} Hz whisper did not start transmitting; {}", HZ[tone], Duplex::evidence(&qa.a, burst.first))); } @@ -703,21 +700,30 @@ fn whisper_spurt(qa: &mut Duplex, target_id: u64, target_uid: &str, tone: usize) Ok(burst) } -fn check_whisper_event(peer: &Peer, phase: &str, since: Instant, expected: Option) -> Result<()> { - let mut received = peer.seen.iter().filter_map(|&(at, seen)| match seen { - Seen::WhisperReceived(from) if at >= since => Some(from), +fn check_whisper_event(peer: &Peer, phase: &str, since: Instant, expected: Option<&Value>) -> Result<()> { + let mut received = peer.seen.iter().filter_map(|(at, seen)| match seen { + Seen::WhisperReceived(event) if *at >= since => Some(event), _ => None, }); - if received.next() != expected || received.next().is_some() { - return Err(format!("{phase}: unexpected whisper_received count or sender; {}", Duplex::evidence(peer, since))); + let matched = match (received.next(), expected) { + (Some(actual), Some(expected)) => ["client_id", "generation", "uid", "nickname"] + .into_iter().all(|key| actual[key] == expected[key]), + (None, None) => true, + _ => false, + }; + if !matched || received.next().is_some() { + return Err(format!("{phase}: unexpected whisper_received count or sender identity; {}", Duplex::evidence(peer, since))); } Ok(()) } -fn roster_uid(peer: &Peer, client_id: u64, is_self: bool) -> Option<&str> { - peer.snapshot["clients"].as_array()?.iter().find(|client| { +fn roster_identity(peer: &Peer, client_id: u64, is_self: bool) -> Option<(&str, &str)> { + let client = peer.snapshot["clients"].as_array()?.iter().find(|client| { client["id"].as_u64() == Some(client_id) && client["is_self"].as_bool() == Some(is_self) - })?["uid"].as_str().filter(|uid| !uid.is_empty()) + })?; + let uid = client["uid"].as_str().filter(|uid| !uid.is_empty())?; + let nickname = client["nickname"].as_str().filter(|name| !name.is_empty())?; + Some((uid, nickname)) } fn is_beta14_default(snapshot: &Value) -> bool { @@ -740,21 +746,28 @@ fn exercise_whisper(exe: &Path, root: &Path) -> Result { } } - // The server's live UID can differ from the local profile's key-derived UID. - // Match the receiver's own roster entry to the sender's view of that same client. - qa.wait_until("receiver UID in both rosters", CONTROL, |qa| { - roster_uid(&qa.b, b_id, true).is_some() && roster_uid(&qa.a, b_id, false).is_some() + // Use independent live rosters, not the profile's key-derived UID or the receipt itself. + qa.wait_until("peer identities in both rosters", CONTROL, |qa| { + roster_identity(&qa.a, a_id, true).is_some() && roster_identity(&qa.b, a_id, false).is_some() + && roster_identity(&qa.b, b_id, true).is_some() && roster_identity(&qa.a, b_id, false).is_some() })?; - let b_uid = roster_uid(&qa.b, b_id, true).ok_or("receiver self roster lacks a UID")?; - if roster_uid(&qa.a, b_id, false) != Some(b_uid) { - return Err("receiver UID does not match the sender's live roster".into()); + let sender = roster_identity(&qa.a, a_id, true).ok_or("sender self roster lacks identity")?; + if roster_identity(&qa.b, a_id, false) != Some(sender) { + return Err("sender identity does not match the receiver's live roster".into()); } - let b_uid = b_uid.to_owned(); + let receiver = roster_identity(&qa.b, b_id, true).ok_or("receiver self roster lacks identity")?; + if roster_identity(&qa.a, b_id, false) != Some(receiver) { + return Err("receiver identity does not match the sender's live roster".into()); + } + let b_uid = receiver.0.to_owned(); + let generation = qa.b.snapshot["generation"].as_u64().filter(|generation| *generation > 0) + .ok_or("receiver roster lacks a connection generation")?; + let sender_receipt = json!({ "client_id": a_id, "generation": generation, "uid": sender.0, "nickname": sender.1 }); set_whisper_receive(&mut qa, "allow_all")?; let initial = whisper_spurt(&mut qa, b_id, &b_uid, A_TONE)?; let first = Duplex::receipt(&qa.b, "direct whisper", a_id, A_TONE, initial.first)?; - check_whisper_event(&qa.b, "direct whisper", initial.first, Some(a_id))?; + check_whisper_event(&qa.b, "direct whisper", initial.first, Some(&sender_receipt))?; let denied = Instant::now(); set_whisper_receive(&mut qa, "deny_all")?; @@ -764,7 +777,7 @@ fn exercise_whisper(exe: &Path, root: &Path) -> Result { set_whisper_receive(&mut qa, "allow_all")?; let restored = whisper_spurt(&mut qa, b_id, &b_uid, B_TONE)?; let again = Duplex::receipt(&qa.b, "restored allow_all", a_id, B_TONE, restored.first)?; - check_whisper_event(&qa.b, "restored allow_all", restored.first, Some(a_id))?; + check_whisper_event(&qa.b, "restored allow_all", restored.first, Some(&sender_receipt))?; // Both peers are still connected and receive policy is open. A fallback to either // whisper or ordinary voice would be visible; the new tone cannot be the old audio tail. @@ -780,7 +793,7 @@ fn exercise_whisper(exe: &Path, root: &Path) -> Result { start_whisper(&mut qa, b_id, &b_uid, held_epoch)?; let held = qa.burst(Some(OLD_TONE), None, 42)?; Duplex::receipt(&qa.b, "held whisper before disconnect", a_id, OLD_TONE, held.first)?; - check_whisper_event(&qa.b, "held whisper before disconnect", held.first, Some(a_id))?; + check_whisper_event(&qa.b, "held whisper before disconnect", held.first, Some(&sender_receipt))?; if !qa.a.transmitting { return Err("sender was not transmitting at disconnect".into()); } let held_confirmed = Duplex::disconnect(&mut qa.a, &qa.tones)?; qa.wait_until("held whisper sender leaving roster", CONTROL, |qa| { @@ -806,7 +819,7 @@ fn exercise_whisper(exe: &Path, root: &Path) -> Result { qa.a.shutdown(&qa.tones)?; qa.b.shutdown(&qa.tones)?; let confirmed = [held_confirmed, a_confirmed, b_confirmed].into_iter().filter(|confirmed| *confirmed).count(); - Ok(format!("Whisper IPC passed: direct 650 Hz + whisper_received ({} frames); deny_all 900 Hz suppressed (no playback or whisper_received); restored allow_all 1150 Hz + whisper_received ({} frames); stale tag 1450 Hz dropped after stop and after reconnect during a live whisper; untagged 1750 Hz ordinary voice after reconnect ({} frames, no whisper_received). Server confirmed {confirmed}/3 disconnects. No device audio.", + Ok(format!("Whisper IPC passed: direct 650 Hz + roster-matched whisper_received ({} frames); deny_all 900 Hz suppressed (no playback or whisper_received); restored allow_all 1150 Hz + roster-matched whisper_received ({} frames); stale tag 1450 Hz dropped after stop and after reconnect during a live whisper; untagged 1750 Hz ordinary voice after reconnect ({} frames, no whisper_received). Server confirmed {confirmed}/3 disconnects. No device audio.", first.frames, again.frames, voice.frames)) } diff --git a/core/src/output.rs b/core/src/output.rs index 583d61c..4cd210b 100644 --- a/core/src/output.rs +++ b/core/src/output.rs @@ -84,7 +84,8 @@ impl Out { pub fn set_generation(&self, generation: u64) { self.inner.generation.store(generation, Ordering::Release); } pub async fn control(&self, mut value: Value) { if let Some(object) = value.as_object_mut().filter(|o| o.contains_key("event")) { - object.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire))); + object.entry("generation".to_owned()) + .or_insert_with(|| Value::from(self.inner.generation.load(Ordering::Acquire))); } let _ = self.inner.control.send(value).await; } @@ -122,6 +123,16 @@ impl Out { mod tests { use super::*; + #[tokio::test(flavor = "current_thread")] + async fn control_preserves_an_explicit_event_generation() { + let (out, mut control, _playback) = Out::new(); + out.set_generation(8); + out.control(json!({"event":"whisper_received","generation":7})).await; + out.control(json!({"event":"talking"})).await; + assert_eq!(control.try_recv().unwrap()["generation"], 7); + assert_eq!(control.try_recv().unwrap()["generation"], 8); + } + #[tokio::test(flavor = "current_thread")] async fn playback_discards_oldest_without_relabeling_reconnected_frames() { let (out, _control, mut playback) = Out::new(); diff --git a/core/src/session.rs b/core/src/session.rs index fa447e0..2c45f67 100644 --- a/core/src/session.rs +++ b/core/src/session.rs @@ -983,13 +983,19 @@ impl Session { } let ignored = c.rx.set_deny_whispers(self.whisper.deny_incoming); let event = c.rx.handle_packet(packet); - let whisper_starts: Vec = c.rx.take_whisper_starts().collect(); for cid in ignored { self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await; } - for cid in whisper_starts { - // Official `onWhisperStart`: feeds the reply history and the whisper notification. - self.out.json(&json!({ "event": "whisper_received", "client_id": cid })).await; + for cid in c.rx.take_whisper_starts() { + // Capture the sender from this connection before another roster update can recycle the ID. + let client = c.con.get_state().ok().and_then(|book| book.clients.get(&ClientId(cid))); + let uid = client.and_then(|client| client.uid.as_ref()).filter(|uid| !uid.0.is_empty()) + .map(|uid| format!("{}", &**uid)); + let nickname = client.map(|client| client.name.as_str()).filter(|name| !name.is_empty()); + self.out.control(json!({ + "event": "whisper_received", "generation": c.generation, "client_id": cid, + "uid": uid, "nickname": nickname, + })).await; } match event { RxEvent::None => {} @@ -1818,6 +1824,29 @@ mod disconnect_tests { } } + #[tokio::test] + async fn whisper_receipt_without_a_roster_entry_does_not_infer_sender_identity() { + use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio}; + let dir = TempDir::new("unknown-whisper-sender"); + let store = Store::new(&dir.0); + store.create("Whisper Test").unwrap(); + let (out, mut events, _playback) = Out::new(); + let mut session = Session::new(store, out, Arc::new(AudioInQueue::new())); + let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap(); + session.connect("join", args).await.unwrap(); + let generation = session.conn.as_ref().unwrap().generation; + // Drive receipt handling with no book data, as when audio precedes the sender's roster entry. + let audio = OutAudio::new(&AudioData::S2CWhisper { id: 1, from: 7, codec: CodecType::OpusVoice, data: &[1, 2, 3] }); + let audio = InAudioBuf::try_new(Direction::S2C, audio.into_vec()).unwrap(); + session.on_item(StreamItem::Audio(audio)).await; + let receipt = std::iter::from_fn(|| events.try_recv().ok()) + .find(|event| event["event"] == "whisper_received").unwrap(); + assert_eq!(receipt, json!({ + "event": "whisper_received", "generation": generation, "client_id": 7, + "uid": null, "nickname": null, + })); + } + #[tokio::test] async fn terminal_state_preserves_which_phase_failed_or_finished() { for (phase, previous_state, transport_error, expected_code) in [ diff --git a/docs/bridge.md b/docs/bridge.md index c58f236..517b702 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -733,7 +733,9 @@ A client number is not an identity. An individual recipient needs a nonempty UID `whisper_start {epoch:u32,target}` resolves a route against the live connection; epoch must be nonzero. Target is `{kind:"list",entries:[{type:1|2,uuid,name}]}`, `{kind:"group",group_type:0..3,target_mode:0..6,group_id,server_uuid}`, or `{kind:"ids",clients:[{id,uid}],channel_ids:[…]}`. At most 255 resolved clients and channels. `whisper_stop {epoch}` stops that route; `set_whisper_receive {mode:"allow_all"|"deny_all"}` controls incoming whispers. -`audio_frame` accepts optional `whisper:epoch`; stale/stopped/other-generation tags drop, never fall back to ordinary voice. Untagged queued frames also drop while a whisper route is held. Transitions end the previous spurt and discard capture queued before the transition. Incoming `whisper_received {client_id}` feeds reply history; receive deny mode removes queued whispers. This is real TeamSpeak whisper packet routing, not local recipient filtering. +`audio_frame` accepts optional `whisper:epoch`; stale/stopped/other-generation tags drop, never fall back to ordinary voice. Untagged queued frames also drop while a whisper route is held. Transitions end the previous spurt and discard capture queued before the transition. Receive deny mode removes queued whispers. + +`whisper_received` carries the receiver's connection `generation` and the sender's numeric `client_id`. When known, `uid` and `nickname` identify the sender at receipt; a later roster cannot supply missing identity. An unidentified whisper can notify but cannot become a reply target. Reply requires the original UID and client number to still match in the same session. ### Local recording (`recording_*`) diff --git a/docs/mobile-port-progress.md b/docs/mobile-port-progress.md index e132f4d..c0cf7e5 100644 --- a/docs/mobile-port-progress.md +++ b/docs/mobile-port-progress.md @@ -4,6 +4,8 @@ ## Возврат к разработке на ПК, 2026-11-26 +Windows, база `d145043`: история шёпота использует UID отправителя на момент приёма; замена клиента с тем же номером проверена нативным тестом. На закрытом beta14 `duplex_qa --whisper` подтвердил получение с UID, отсутствие звука и события при запрете, возврат приёма и 3/3 отключения. Отдельно прошли тест настройки на двух вкладках, три теста ядра и четыре нативных теста. Системную клавишу ответа не нажимали. Стенд остановлен; push в feature/desktop-parity отклонён при аутентификации. + Windows, база `d9570f3`: закрыт `preference:channelCommanderAsLamp` по отрисовке Slint и восстановлению настройки. Для `client-action:commander` проверены меню собственной строки, отказ гостю на beta14 и устаревшее подтверждение; положительное изменение флага не подтверждено. Прошли четыре нативные и две проверки ядра. Стенд остановлен. Windows, база `b266f4f`: закрыты `preload:setClientVolume` и `client-action:volume`. На beta14 проверены движение ползунка, сохранение при отпускании, локальный mute, переподключение и сброс. Прошли 12 нативных и три проверки ядра. Два источника Opus проверялись отдельно в микшере, без физических устройств. Стенд остановлен. diff --git a/native/src/app/runtime/local_actions/whispers.rs b/native/src/app/runtime/local_actions/whispers.rs index acb0d82..d7e8a10 100644 --- a/native/src/app/runtime/local_actions/whispers.rs +++ b/native/src/app/runtime/local_actions/whispers.rs @@ -4,33 +4,24 @@ use crate::services::whisper::WhisperEntry; use crate::ui::settings::{Category,Navigation}; type SessionId=(String,u64,u64); fn session_id(key:&SessionKey)->SessionId{(key.connection_id.clone(),key.session,key.generation)} -#[derive(Clone)] struct Received {id:u16,uid:String,nickname:String,at:u64} #[derive(Default)] -struct History {entries:Vec,pending:Vec<(u16,u64)>} -#[derive(Default)] -pub struct LocalWorkflows {history:HashMap} +pub struct LocalWorkflows {history:HashMap>} fn now()->u64{std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d|d.as_millis().min(u64::MAX as u128) as u64).unwrap_or(0)} -fn peer(snapshot:&Value,id:u16)->Option<&Value>{snapshot["clients"].as_array()?.iter().find(|c|c["id"].as_u64()==Some(u64::from(id)))} -fn present(snapshot:&Value,received:&Received)->bool{peer(snapshot,received.id).is_some_and(|p|p["uid"].as_str()==Some(received.uid.as_str()))} -fn record(history:&mut History,client:&Value,at:u64){ - let Some(id)=client["id"].as_u64().and_then(|id|u16::try_from(id).ok())else{return}; - let Some(uid)=client["uid"].as_str().filter(|uid|!uid.is_empty())else{return}; - history.entries.retain(|entry|entry.uid!=uid&&entry.id!=id); - history.entries.push(Received{id,uid:uid.into(),nickname:client["nickname"].as_str().unwrap_or_default().into(),at}); +fn peer<'a>(snapshot:&'a Value,id:u16,uid:&str)->Option<&'a Value>{ + snapshot["clients"].as_array()?.iter().find(|client|client["id"].as_u64()==Some(u64::from(id))&&client["uid"].as_str()==Some(uid)) } /// Called by the lossless core event consumer, never by the coalesced UI projector. pub fn on_control(ctx:&RuntimeServices,key:&SessionKey,value:&Value)->Result<()>{ - let event=value["event"].as_str().unwrap_or_default();if !matches!(event,"snapshot"|"whisper_received"){return Ok(())} - if ctx.require_key(key,true).is_err(){return Ok(())} - let snapshots=ctx.connected.connections.snapshot();let Some(snapshot)=snapshots.get(&key.connection_id).and_then(|s|s.server.as_deref())else{return Ok(())}; + if value["event"]!="whisper_received"||value["generation"].as_u64()!=Some(key.generation){return Ok(())} + let Some(id)=value["client_id"].as_u64().and_then(|id|u16::try_from(id).ok())else{return Ok(())}; + let Some(uid)=value["uid"].as_str().filter(|uid|!uid.is_empty())else{return Ok(())}; + // The event owns the sender identity; the published roster may already have reused the ID. + if ctx.require_key(key,false).is_err(){return Ok(())} let mut workflows=ctx.local_workflows.lock().map_err(|_|bad("Whisper history unavailable"))?; - let history=workflows.history.entry(session_id(key)).or_default(); - if event=="whisper_received"{ - if let Some(id)=value["client_id"].as_u64().and_then(|id|u16::try_from(id).ok()){ - if let Some(client)=peer(snapshot,id){record(history,client,now());}else{history.pending.push((id,now()));} - } - }else{for(id,at)in std::mem::take(&mut history.pending){if let Some(client)=peer(value,id){record(history,client,at);}}} + let entries=workflows.history.entry(session_id(key)).or_default(); + entries.retain(|entry|entry.uid!=uid); + entries.push(Received{id,uid:uid.into(),nickname:value["nickname"].as_str().unwrap_or(uid).into(),at:now()}); Ok(()) } pub fn on_closed(ctx:&RuntimeServices,key:&SessionKey)->Result<()>{ @@ -39,15 +30,15 @@ pub fn on_closed(ctx:&RuntimeServices,key:&SessionKey)->Result<()>{ if settings.pending_whisper.as_ref().is_some_and(|(captured,_)|captured==key){settings.pending_whisper=None;}Ok(()) } pub fn last_whisperer(ctx:&RuntimeServices,key:&SessionKey)->Result>{ - ctx.require_key(key,true)?;let snapshots=ctx.connected.connections.snapshot();let snapshot=snapshots.get(&key.connection_id).and_then(|s|s.server.as_deref()).ok_or_else(changed)?; - Ok(ctx.local_workflows.lock().map_err(|_|bad("Whisper history unavailable"))?.history.get(&session_id(key)).and_then(|history|history.entries.iter().rev().find(|entry|present(snapshot,entry))).map(|entry|(entry.id,entry.uid.clone()))) + ctx.require_key(key,true)?;let snapshots=ctx.connected.connections.snapshot();let snapshot=snapshots.get(&key.connection_id).filter(|s|s.key==*key&&s.is_connected()).and_then(|s|s.server.as_deref()).ok_or_else(changed)?; + Ok(ctx.local_workflows.lock().map_err(|_|bad("Whisper history unavailable"))?.history.get(&session_id(key)).and_then(|entries|entries.iter().rev().find(|entry|peer(snapshot,entry.id,&entry.uid).is_some())).map(|entry|(entry.id,entry.uid.clone()))) } pub(super) async fn handle(ctx:Arc,target:Target,operation:Operation,_values:Values)->Result{ ctx.require_target(&target)?;let key=key(&target)?;ctx.require_key(&key,true)?; if operation==Operation::WhisperHistory{return history(&ctx,target,&key)} let snapshots=ctx.connected.connections.snapshot();let snapshot=snapshots.get(&key.connection_id).and_then(|s|s.server.as_deref()).ok_or_else(changed)?; let entry=match (&target.entity,operation){ - (Entity::Client{id,uid,..},Operation::ClientWhisperAdd)=>{let client=peer(snapshot,*id).filter(|client|client["uid"].as_str()==Some(uid.as_str())).ok_or_else(changed)?;WhisperEntry{kind:1,uuid:uid.clone(),name:client["nickname"].as_str().unwrap_or_default().into()}}, + (Entity::Client{id,uid,..},Operation::ClientWhisperAdd)=>{let client=peer(snapshot,*id,uid).ok_or_else(changed)?;WhisperEntry{kind:1,uuid:uid.clone(),name:client["nickname"].as_str().unwrap_or_default().into()}}, (Entity::Channel{id},Operation::ChannelWhisperAdd)=>{let path=crate::services::bookmarks::channel_path(snapshot["channels"].as_array().ok_or_else(changed)?,*id).ok_or_else(||bad("The channel path cannot be represented as a whisper target"))?;WhisperEntry{kind:2,uuid:snapshot["server"]["uid"].as_str().ok_or_else(changed)?.into(),name:path}}, _=>return Err(bad("The whisper target does not match this action")), }; @@ -55,16 +46,88 @@ pub(super) async fn handle(ctx:Arc,target:Target,operation:Oper ctx.changed().await?;Ok(WorkflowResult::effect(UiEffect::SettingsNavigate(Navigation::Category(Category::Whispers)))) } fn history(ctx:&RuntimeServices,target:Target,key:&SessionKey)->Result{ - let snapshots=ctx.connected.connections.snapshot();let snapshot=snapshots.get(&key.connection_id).and_then(|s|s.server.as_deref()).ok_or_else(changed)?; - let entries=ctx.local_workflows.lock().map_err(|_|bad("Whisper history unavailable"))?.history.get(&session_id(key)).map(|history|history.entries.clone()).unwrap_or_default(); + let snapshots=ctx.connected.connections.snapshot();let snapshot=snapshots.get(&key.connection_id).filter(|s|s.key==*key&&s.is_connected()).and_then(|s|s.server.as_deref()).ok_or_else(changed)?; let use_24h=ctx.profile()?.prefs.get()["chatUse24hTime"]==true; - let c=catalog(ctx)?;let entries=entries.into_iter().rev().map(|received|{ - let live=present(snapshot,&received);let channel_id=peer(snapshot,received.id).and_then(|p|p["channel_id"].as_u64()).unwrap_or(0); + let c=catalog(ctx)?; + let entries=ctx.local_workflows.lock().map_err(|_|bad("Whisper history unavailable"))?.history.get(&session_id(key)).into_iter().flatten().rev().map(|received|{ + let client=peer(snapshot,received.id,&received.uid); + let live=client.is_some();let channel_id=client.and_then(|p|p["channel_id"].as_u64()).unwrap_or(0); let target=Target{session:Some(key.clone()),entity:Entity::Client{id:received.id,uid:received.uid.clone(),channel_id},name:received.nickname.clone(),own_channel_id:snapshot["own_channel_id"].as_u64()}; let actions=[Operation::ClientPrivateChat,Operation::ClientWhisperAdd,Operation::ContactAdd].into_iter().map(|op|{let mut action=Action::new(format!("whisper-history/{op:?}"),op,target.clone(),&c);super::prepare_action(&mut action);if !live{action.enabled=false;action.reason="This client is no longer present in this session".into();}action}).collect(); let (_,clock)=super::super::chat_actions::format_timestamp(received.at,use_24h); - Entry{id:format!("whisper/{}/{}",received.id,received.uid),target,title:received.nickname,subtitle:format!("{} · {}{}",received.uid,clock,if live{""}else{" · Offline"}),depth:0,selected:false,expanded:false,expandable:false,talking:false,muted:false,unread:0,actions,waveform:Vec::new()} + Entry{id:format!("whisper/{}/{}",received.id,received.uid),target,title:received.nickname.clone(),subtitle:format!("{} · {}{}",received.uid,clock,if live{""}else{" · Offline"}),depth:0,selected:false,expanded:false,expandable:false,talking:false,muted:false,unread:0,actions,waveform:Vec::new()} }).collect::>(); let description=if entries.is_empty(){"No whispers have been received in this server session.".into()}else{String::new()}; Ok(WorkflowResult::effect(UiEffect::Detail{target,detail:Detail{title:c.text("settings.whisper.history"),description,entries,..Detail::default()}})) } + +#[cfg(test)] +#[tokio::test(flavor = "current_thread")] +async fn received_whisper_identity_survives_recycled_client_id() { + use crate::{AppConfig, AppRuntime, services::profile_import::initialize_native_root}; + use super::super::model::BootstrapState; + + const ORIGINAL: &str = "FixturePeer="; + const REPLACEMENT: &str = "fixturePeer="; + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("profile"); + initialize_native_root(&root).unwrap(); + ProfileServices::open(&root).unwrap().identities.onboard("Whisper history fixture").unwrap(); + let runtime = AppRuntime::start(AppConfig::isolated(root)).unwrap(); + let mut updates = runtime.subscribe(); + let ready = tokio::time::timeout(std::time::Duration::from_secs(5), updates.wait_for(|s| { + s.bootstrap == BootstrapState::Ready && !s.connections.connections.is_empty() + })).await.unwrap().unwrap().clone(); + let key = ready.connections.connections[0].key.clone(); + let ctx = runtime.services.lock().unwrap().upgrade().unwrap(); + let manager = &ctx.connected.connections; + let roster = |uid, nickname| json!({ + "event":"snapshot", "generation":key.generation, "own_client_id":1, "own_channel_id":7, + "server":{"uid":"FixtureServer=", "name":"Fixture"}, "channels":[{"id":7,"name":"Lobby"}], + "clients":[{"id":1,"uid":"Owner=","nickname":"Owner","channel_id":7}, + {"id":4,"uid":uid,"nickname":nickname,"channel_id":7}] + }); + let receipt = |generation, uid, nickname| json!({ + "event":"whisper_received", "generation":generation, "client_id":4, "uid":uid, "nickname":nickname + }); + let rows = || { + let target = Target { session: Some(key.clone()), entity: Entity::Connection, ..Target::application() }; + match history(&ctx, target, &key).unwrap().effects.pop().unwrap() { + UiEffect::Detail { detail, .. } => detail.entries, + _ => panic!("expected whisper history detail"), + } + }; + + // The receipt can reach history before the first roster is available there. + on_control(&ctx, &key, &receipt(key.generation, ORIGINAL, "Original at receipt")).unwrap(); + manager.fixture_control(&key, roster(ORIGINAL, "Original renamed")).await.unwrap(); + assert_eq!(last_whisperer(&ctx, &key).unwrap(), Some((4, ORIGINAL.into()))); + assert!(rows()[0].actions.iter().all(|action| action.enabled)); + + manager.fixture_control(&key, roster(REPLACEMENT, "Replacement")).await.unwrap(); + assert_eq!(last_whisperer(&ctx, &key).unwrap(), None); + for rejected in [ + json!({"event":"whisper_received", "generation":key.generation, "client_id":4}), + receipt(key.generation, "", "Missing UID"), + json!({"event":"whisper_received", "client_id":4, "uid":REPLACEMENT}), + receipt(key.generation ^ 1, REPLACEMENT, "Wrong generation"), + ] { + on_control(&ctx, &key, &rejected).unwrap(); + assert_eq!(last_whisperer(&ctx, &key).unwrap(), None); + } + let entries = rows(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].title, "Original at receipt"); + assert!(entries[0].subtitle.contains(ORIGINAL) && entries[0].subtitle.ends_with("Offline")); + assert_eq!(entries[0].actions.len(), 3); + assert!(entries[0].actions.iter().all(|action| !action.enabled)); + + on_control(&ctx, &key, &receipt(key.generation, REPLACEMENT, "Verified replacement")).unwrap(); + assert_eq!(last_whisperer(&ctx, &key).unwrap(), Some((4, REPLACEMENT.into()))); + let entries = rows(); + assert_eq!(entries.len(), 2); + assert_eq!(entries[0].title, "Verified replacement"); + assert_eq!(entries[1].title, "Original at receipt"); + assert!(entries[1].actions.iter().all(|action| !action.enabled)); + runtime.shutdown().await.unwrap(); +} diff --git a/native/src/app/runtime/notification_actions.rs b/native/src/app/runtime/notification_actions.rs index 2e2cb7d..63f52ef 100644 --- a/native/src/app/runtime/notification_actions.rs +++ b/native/src/app/runtime/notification_actions.rs @@ -125,7 +125,9 @@ fn control_input(key: &SessionKey, value: &Value) -> Option { let ts_error_id = error["ts_error"]["id"].as_u64().and_then(|id| u32::try_from(id).ok()); Some(NotificationInput::Error { ts_error_id }) } - Some("whisper_received") => Some(NotificationInput::WhisperReceived { client_id: value["client_id"].as_u64()?, history_name: value["nickname"].as_str().map(str::to_owned) }), + Some("whisper_received") if value["generation"].as_u64() == Some(key.generation) + && value["client_id"].as_u64().is_some_and(|id| (1..=u64::from(u16::MAX)).contains(&id)) => + Some(NotificationInput::WhisperReceived { nickname: text("nickname") }), Some("recording_state") => super::notification_media::recording_input(value), Some("server_event")=>{let reason=match value["reason"].as_str(){Some("moved")=>MoveReason::Moved,Some("kick_channel")=>MoveReason::KickChannel,Some("kick_server")=>MoveReason::KickServer,Some("ban")=>MoveReason::Ban,Some("lost_connection")=>MoveReason::LostConnection,Some("none")|None=>MoveReason::None,_=>MoveReason::Other};let event=match value["kind"].as_str(){ Some("client_enter" | "client_leave") if value["reason"] == "subscription" => return None, diff --git a/native/src/media/audio/notification_sound_cases.rs b/native/src/media/audio/notification_sound_cases.rs index eea19f5..b8d17eb 100644 --- a/native/src/media/audio/notification_sound_cases.rs +++ b/native/src/media/audio/notification_sound_cases.rs @@ -207,7 +207,7 @@ impl Case { change, channel_id: HERE, name: "Room".into(), details: actor(own), }), ServerEdit => NotificationInput::Server(ServerEvent::ServerEdited { details: actor(true) }), - Source::WhisperReceived => NotificationInput::WhisperReceived { client_id: PEER, history_name: None }, + Source::WhisperReceived => NotificationInput::WhisperReceived { nickname: String::new() }, Accepted(event) => NotificationInput::Direct(event), Error(ts_error_id) => NotificationInput::Error { ts_error_id }, }; diff --git a/native/src/services/notifications.rs b/native/src/services/notifications.rs index 1f37695..c6f4b5d 100644 --- a/native/src/services/notifications.rs +++ b/native/src/services/notifications.rs @@ -355,7 +355,7 @@ pub enum NotificationInput { Snapshot(Snapshot), Server(ServerEvent), Text(TextEvent), State { state: ConnectionState, address: String }, AudioState { input_muted: bool, output_muted: bool }, - WhisperReceived { client_id: u64, history_name: Option }, + WhisperReceived { nickname: String }, LocalRecordingState(LocalRecordingState), /// Already-accepted feature events: MessageSent only after a successful send acknowledgement; /// streams only after the stream directory accepts a transition; TalkingWhileMuted only on @@ -600,9 +600,8 @@ impl Notifications { if output != output_muted { self.notify(&mut conn, "output_status", if output_muted { "sound_muted" } else { "sound_on" }, None, BTreeMap::new(), now_ms, &mut out); } } } - NotificationInput::WhisperReceived { client_id, history_name } => { - let name = history_name.unwrap_or_else(|| conn.snapshot.client(client_id).map(|c| c.nickname.clone()).unwrap_or_default()); - self.notify(&mut conn, "whisper_received", "whisper_received", None, params([("name", name)]), now_ms, &mut out); + NotificationInput::WhisperReceived { nickname } => { + self.notify(&mut conn, "whisper_received", "whisper_received", None, params([("name", nickname)]), now_ms, &mut out); } NotificationInput::LocalRecordingState(next) => { let previous = std::mem::replace(&mut conn.recording, next); diff --git a/native/src/services/notifications_tests.rs b/native/src/services/notifications_tests.rs index d1627ac..407e254 100644 --- a/native/src/services/notifications_tests.rs +++ b/native/src/services/notifications_tests.rs @@ -433,15 +433,15 @@ fn invalid_configuration_is_atomic_and_remote_notification_body_is_bounded() { } #[test] -fn whisper_history_name_wins_and_throttling_does_not_drop_log_entries() { +fn whisper_notifications_never_borrow_a_roster_name_or_drop_throttled_log_entries() { let (mut p, k) = setup(); - let first = emit(&mut p, &k, NotificationInput::WhisperReceived { client_id: 2, history_name: Some("Saved nickname".into()) }, 0); + let first = emit(&mut p, &k, NotificationInput::WhisperReceived { nickname: "Saved nickname".into() }, 0); assert_eq!(files(&first), ["whisper_received"]); assert!(first.iter().any(|e| matches!(e, NotificationEffect::Log { entry, .. } if entry.params["name"] == "Saved nickname"))); - let second = emit(&mut p, &k, NotificationInput::WhisperReceived { client_id: 2, history_name: None }, 100); + let second = emit(&mut p, &k, NotificationInput::WhisperReceived { nickname: String::new() }, 100); assert!(files(&second).is_empty()); - assert!(second.iter().any(|e| matches!(e, NotificationEffect::Log { entry, .. } if entry.params["name"] == "Peer"))); - let missing = emit(&mut p, &k, NotificationInput::WhisperReceived { client_id: 999, history_name: None }, 2000); + assert!(second.iter().any(|e| matches!(e, NotificationEffect::Log { entry, .. } if entry.params["name"].is_empty()))); + let missing = emit(&mut p, &k, NotificationInput::WhisperReceived { nickname: String::new() }, 2000); assert_eq!(files(&missing), ["whisper_received"]); assert!(missing.iter().any(|e| matches!(e, NotificationEffect::Log { entry, .. } if entry.params["name"].is_empty()))); }