Serialize receive-only capture transitions and retain playback on command failure
android-ci / android-arm64 (push) Failing after 8m40s

This commit is contained in:
bit9992 committed 2026-11-12 20:59:06 +03:00
1 parent 3c0593b3be
commit 65707789a7
11 files changed
+163 -47

No files matched your search

+11
View File
@@ -269,6 +269,17 @@ Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c
revocation and do not close TX for unrelated command/notification errors. Actual engine faults still revocation and do not close TX for unrelated command/notification errors. Actual engine faults still
revoke immediately and emit stopped state. Explicit microphone resume intent separated from activity. revoke immediately and emit stopped state. Explicit microphone resume intent separated from activity.
Four real CallAudioState regression tests passed under local guard; new APK/live voice proof pending. Four real CallAudioState regression tests passed under local guard; new APK/live voice proof pending.
- Run4877 SUCCESS; installed verified APK SHA256 `b7328c8953073958daeea952b7fc77ef7ea7ba167b379588712b5e443b3faf43`.
New connection selected automatically; channel tree and acknowledged `Channel: cs` visible. Owner
confirms **RX silence and TX failure persist**. Private Record/Listen also failed with audio/privacy
epoch errors; AAudio open success does not prove PCM/capture/playback. Do not repeat old failed tests.
- Further source-confirmed cause: receive-only refresh returned before recording transmission owner,
making20ms ticker repeatedly StopInput/revoke while explicit activation was in flight. Record owner
before authorization exit; hold one configuration guard through freshness check and activation; private
test actions share that guard. Stage-labelled errors contain no private data.
- Nonterminal configuration/file/whisper failures previously tore down playback/session consumers as if
the core died. ConnectionEvent::Failure now carries explicit terminal state; only core stream death
tears down routes, with exact SessionKey matching. Ordinary errors remain visible. Verification pending.
## First Android APK build ## First Android APK build
+3 -3
View File
@@ -133,7 +133,7 @@ pub enum ConnectionEvent {
Playback { key: SessionKey, frame: PlaybackFrame }, Playback { key: SessionKey, frame: PlaybackFrame },
/// The media owner must clear held PTT/whisper and its capture buffers here. /// The media owner must clear held PTT/whisper and its capture buffers here.
InputReset, InputReset,
Failure { key: Option<SessionKey>, error: ConnectionError }, Failure { key: Option<SessionKey>, error: ConnectionError, terminal: bool },
} }
pub trait ConnectionSink: Send + Sync + 'static { pub trait ConnectionSink: Send + Sync + 'static {
fn on_event(&self, event: ConnectionEvent); fn on_event(&self, event: ConnectionEvent);
@@ -399,7 +399,7 @@ impl Actor {
self.snapshots.send_replace(Arc::new(snapshot)); self.snapshots.send_replace(Arc::new(snapshot));
} }
fn failure(&self, key: Option<SessionKey>, error: ConnectionError) { fn failure(&self, key: Option<SessionKey>, error: ConnectionError) {
self.sink.on_event(ConnectionEvent::Failure { key, error }); self.sink.on_event(ConnectionEvent::Failure { key, error, terminal: false });
} }
fn revoke(&mut self) -> u64 { fn revoke(&mut self) -> u64 {
let revision = self.capture.lock().expect("capture route poisoned").revoke(); let revision = self.capture.lock().expect("capture route poisoned").revoke();
@@ -789,7 +789,7 @@ impl Actor {
Internal::Ended { .. } => { Internal::Ended { .. } => {
let key = self.entries[index].key(); let key = self.entries[index].key();
if self.input.as_ref() == Some(&key.connection_id) { self.revoke(); self.restore_input(); } if self.input.as_ref() == Some(&key.connection_id) { self.revoke(); self.restore_input(); }
self.failure(Some(key), ConnectionError::Worker("core event stream ended".into())); self.sink.on_event(ConnectionEvent::Failure { key: Some(key), error: ConnectionError::Worker("core event stream ended".into()), terminal: true });
let mut entry = self.entries.remove(index); let mut entry = self.entries.remove(index);
self.stop(&mut entry, StopPurpose::Failed); self.stop(&mut entry, StopPurpose::Failed);
self.entries.insert(index, entry); self.entries.insert(index, entry);
+12 -5
View File
@@ -56,13 +56,20 @@ impl ConnectionSink for AudioSessionBinding {
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting)))); self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
} }
}, },
ConnectionEvent::Failure{key:Some(key),error}=>{ ConnectionEvent::Failure{key,error,terminal}=>{
let mut routes=self.routes.lock().expect("playback routes poisoned"); // A rejected command does not end the session or invalidate its playback epoch.
if let Some(old)=routes.remove(&key.connection_id){self.report(audio.send(AudioCommand::RemoveConnection{key:old.key}));} // Only the manager's terminal notification may remove the matching route.
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting)))); if terminal{
if let Some(key)=key{
let mut routes=self.routes.lock().expect("playback routes poisoned");
if routes.get(&key.connection_id).is_some_and(|route|route.key==key){
if let Some(old)=routes.remove(&key.connection_id){self.report(audio.send(AudioCommand::RemoveConnection{key:old.key}));}
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
}
}
}
(self.errors)(ServiceError::new("connection_failed",error.to_string())); (self.errors)(ServiceError::new("connection_failed",error.to_string()));
}, },
ConnectionEvent::Failure{key:None,error}=>(self.errors)(ServiceError::new("connection_failed",error.to_string())),
} }
} }
} }
+73 -7
View File
@@ -10,6 +10,20 @@ fn unavailable(message:&str)->ServiceError{ServiceError::new("desktop_only",mess
struct CommitCancellation(Arc<AtomicBool>); struct CommitCancellation(Arc<AtomicBool>);
impl Drop for CommitCancellation{fn drop(&mut self){self.0.store(true,Ordering::Release);}} impl Drop for CommitCancellation{fn drop(&mut self){self.0.store(true,Ordering::Release);}}
impl super::context::TransmissionState {
/// Observe receive-only owners too: authorization is separate from owner identity.
fn observe_owner(&mut self,key:Option<SessionKey>)->bool {
if self.key==key{return false}
self.key=key;self.ptt_holders.clear();self.deactivated.clear();self.release_at=None;self.whisper.release(None);self.configured=None;
self.revision=self.revision.wrapping_add(1);true
}
}
/// Activation diagnostics contain only a fixed stage, error code and session counters.
pub(super) fn capture_stage<T>(result:Result<T>,stage:&'static str,key:&SessionKey)->Result<T>{
result.map_err(|error|ServiceError::new(&error.code,format!("Microphone activation failed at {stage} ({}; generation={}; session={})",error.code,key.generation,key.session)))
}
impl RuntimeServices { impl RuntimeServices {
pub fn color_scheme(&self)->ColorScheme {self.system_scheme.lock().ok().and_then(|scheme|*scheme).unwrap_or(ColorScheme::Dark)} pub fn color_scheme(&self)->ColorScheme {self.system_scheme.lock().ok().and_then(|scheme|*scheme).unwrap_or(ColorScheme::Dark)}
pub async fn sync_notifications(&self)->Result<()>{super::settings_actions::sync_notifications(self).await} pub async fn sync_notifications(&self)->Result<()>{super::settings_actions::sync_notifications(self).await}
@@ -112,16 +126,25 @@ impl RuntimeServices {
} }
/// A closed forwarding gate invalidates the old permit; obtain fresh real acknowledgements before opening. /// A closed forwarding gate invalidates the old permit; obtain fresh real acknowledgements before opening.
pub async fn refresh_capture(self:&Arc<Self>)->Result<()> { pub async fn refresh_capture(self:&Arc<Self>)->Result<()> {
let _configuration=self.audio_configuration.lock().await; let configuration=self.audio_configuration.lock().await;
if lock(&self.microphone_test_resume)?.is_some(){return Ok(())} self.refresh_capture_locked(&configuration,false).await.map(|_|())
}
/// The ticker must compare the owner under the same lock as the eventual refresh.
/// A queued or completed explicit activation must not be revoked by an old observation.
pub async fn refresh_capture_owner_changed(self:&Arc<Self>)->Result<bool> {
let Ok(configuration)=self.audio_configuration.try_lock() else{return Ok(false)};
self.refresh_capture_locked(&configuration,true).await
}
async fn refresh_capture_locked(self:&Arc<Self>,_configuration:&tokio::sync::MutexGuard<'_,()>,owner_changed_only:bool)->Result<bool> {
if lock(&self.microphone_test_resume)?.is_some(){return Ok(false)}
let snapshot=self.connected.connections.snapshot(); let snapshot=self.connected.connections.snapshot();
let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.is_connected()).map(|entry|entry.key.clone()); let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.is_connected()).map(|entry|entry.key.clone());
let Some(key)=key else{self.audio.set_transmission_enabled(false);self.audio.revoke_capture();return Ok(())}; let (revision,whisper)={let mut state=lock(&self.transmission)?;if owner_changed_only&&state.key==key{return Ok(false)}state.observe_owner(key.clone());(state.revision,state.whisper.held())};
let Some(key)=key else{self.audio_input_active.store(false,Ordering::Release);self.audio.set_transmission_enabled(false);self.audio.request(AudioCommand::StopInput).await?;return Ok(true)};
#[cfg(target_os="android")] #[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(&key,true){self.audio_input_active.store(false,Ordering::Release);self.audio.request(AudioCommand::StopInput).await?;return Ok(())} if !crate::platform::android::voice_audio_allowed(&key,true){self.audio_input_active.store(false,Ordering::Release);self.audio.set_transmission_enabled(false);self.audio.request(AudioCommand::StopInput).await?;return Ok(true)}
let (prefs,allowed)={let profile=self.profile()?;(profile.prefs.get(),profile.prefs.capture_allowed(profile.migration.is_some()))}; let (prefs,allowed)={let profile=self.profile()?;(profile.prefs.get(),profile.prefs.capture_allowed(profile.migration.is_some()))};
let (revision,whisper)={let mut state=lock(&self.transmission)?;if state.key.as_ref()!=Some(&key){state.key=Some(key.clone());state.ptt_holders.clear();state.deactivated.clear();state.release_at=None;state.whisper.release(None);state.revision=state.revision.wrapping_add(1);}(state.revision,state.whisper.held())}; if whisper{return self.refresh_transmission_gate(&key,&prefs).map(|_|true)}
if whisper{return self.refresh_transmission_gate(&key,&prefs)}
let config=self.capture_configuration(&key,&prefs)?; let config=self.capture_configuration(&key,&prefs)?;
self.audio.revoke_capture(); self.audio.revoke_capture();
let permit=self.connected.connections.set_input(Some(&key),config).await.map_err(connection_error)?; let permit=self.connected.connections.set_input(Some(&key),config).await.map_err(connection_error)?;
@@ -134,7 +157,7 @@ impl RuntimeServices {
if lock(&self.transmission)?.revision!=revision{self.audio.revoke_capture();return Err(changed())} if lock(&self.transmission)?.revision!=revision{self.audio.revoke_capture();return Err(changed())}
lock(&self.transmission)?.configured=Some(config); lock(&self.transmission)?.configured=Some(config);
if allowed&&self.microphone_granted.load(Ordering::Acquire)&&self.audio_input_active.load(Ordering::Acquire){self.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;} if allowed&&self.microphone_granted.load(Ordering::Acquire)&&self.audio_input_active.load(Ordering::Acquire){self.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;}
self.refresh_transmission_gate(&key,&prefs) self.refresh_transmission_gate(&key,&prefs).map(|_|true)
} }
pub async fn apply_key_events(self:&Arc<Self>,events:Vec<ActionEvent>)->Result<()> { pub async fn apply_key_events(self:&Arc<Self>,events:Vec<ActionEvent>)->Result<()> {
let prefs=self.profile()?.prefs.get();let mut forwarded=Vec::new();let mut refresh=false; let prefs=self.profile()?.prefs.get();let mut forwarded=Vec::new();let mut refresh=false;
@@ -212,3 +235,46 @@ impl RuntimeServices {
Ok(WorkflowResult::effect(UiEffect::Detail{target:Target{session:Some(key),entity:Entity::Connection,name:String::new(),own_channel_id:None},detail})) Ok(WorkflowResult::effect(UiEffect::Detail{target:Target{session:Some(key),entity:Entity::Connection,name:String::new(),own_channel_id:None},detail}))
} }
} }
#[cfg(test)]
mod capture_transition_tests {
use super::*;
use super::super::context::TransmissionState;
fn key(session:u64)->SessionKey{SessionKey{connection_id:"private-connection".into(),session,generation:7}}
#[test]
fn receive_only_owner_is_observed_once_without_authorizing_capture(){
let mut state=TransmissionState::default();let owner=key(1);
assert!(state.observe_owner(Some(owner.clone())));
let revision=state.revision;
// The receive-only early return has no permit/configuration, but the next
// ticker observation must not request another StopInput/revoke cycle.
assert!(state.configured.is_none());
for _ in 0..1000{assert!(!state.observe_owner(Some(owner.clone())));}
assert_eq!(state.revision,revision);assert_eq!(state.key,Some(owner));
assert!(state.configured.is_none());
}
#[test]
fn owner_changes_clear_old_forwarding_state_and_configuration(){
let mut state=TransmissionState::default();state.observe_owner(Some(key(1)));
state.ptt_holders.insert("held".into());state.deactivated.insert("muted".into());
state.release_at=Some(Instant::now());state.configured=Some(InputConfiguration::default());
assert!(state.observe_owner(Some(key(2))));
assert!(state.ptt_holders.is_empty());assert!(state.deactivated.is_empty());
assert!(state.release_at.is_none());assert!(state.configured.is_none());
assert!(state.observe_owner(None));assert!(!state.observe_owner(None));
assert!(state.key.is_none());
}
#[test]
fn activation_failure_exposes_stage_and_counters_without_private_details(){
let owner=key(42);
let error=capture_stage::<()>(Err(ServiceError::new("target_changed","private server response")),"bind_permit",&owner).unwrap_err();
assert_eq!(error.code,"target_changed");
assert!(error.message.contains("bind_permit"));assert!(error.message.contains("generation=7"));assert!(error.message.contains("session=42"));
assert!(!error.message.contains(&owner.connection_id));assert!(!error.message.contains("private server response"));
assert_eq!(capture_stage(Ok(13),"start_input",&owner).unwrap(),13);
}
}
+20 -12
View File
@@ -3,6 +3,7 @@ use std::sync::{Arc,atomic::Ordering};
use crate::{app::{connections::SessionKey,server_actions},services::{Result,ServiceError},ui::shell::*}; use crate::{app::{connections::SessionKey,server_actions},services::{Result,ServiceError},ui::shell::*};
use super::{context::{RuntimeServices,changed,connection_error},events::{UiEffect,WorkflowResult}}; use super::{context::{RuntimeServices,changed,connection_error},events::{UiEffect,WorkflowResult}};
use crate::media::audio::{engine::AudioCommand,devices::StartPermission}; use crate::media::audio::{engine::AudioCommand,devices::StartPermission};
use super::context_helpers::capture_stage;
pub fn release_immediate(ctx:&RuntimeServices){ pub fn release_immediate(ctx:&RuntimeServices){
ctx.audio.revoke_capture();ctx.audio.set_transmission_enabled(false); ctx.audio.revoke_capture();ctx.audio.set_transmission_enabled(false);
if let Ok(mut tx)=ctx.transmission.lock(){tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.deactivated.clear();} if let Ok(mut tx)=ctx.transmission.lock(){tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.deactivated.clear();}
@@ -15,26 +16,33 @@ pub async fn release_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()
ctx.require_key(key,false) ctx.require_key(key,false)
} }
pub async fn set_microphone_owner(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{ pub async fn set_microphone_owner(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{
ctx.require_key(key,true)?;ctx.policy.check()?;let snapshots=ctx.connected.connections.snapshot();if let Some(previous)=snapshots.input_id.as_deref().and_then(|id|snapshots.get(id)){release_voice(ctx,&previous.key).await?;}else{release_immediate(ctx);} ctx.require_key(key,true)?;ctx.policy.check()?;let generation=ctx.current_ui_generation()?;
ctx.request_microphone_permission().await?;ctx.require_key(key,true)?; let configuration=ctx.audio_configuration.lock().await;
capture_stage(ctx.require_key(key,true),"validate_owner",key)?;ctx.require_ui_generation(generation)?;
let snapshots=ctx.connected.connections.snapshot();if let Some(previous)=snapshots.input_id.as_deref().and_then(|id|snapshots.get(id)){capture_stage(release_voice(ctx,&previous.key).await,"release",key)?;}else{release_immediate(ctx);}
ctx.audio_input_active.store(false,Ordering::Release);
capture_stage(ctx.request_microphone_permission().await,"permission",key)?;capture_stage(ctx.require_key(key,true),"permission_owner",key)?;ctx.require_ui_generation(generation)?;
#[cfg(any(target_os="android",target_os="ios"))] #[cfg(any(target_os="android",target_os="ios"))]
ctx.ensure_mobile_call(key,true).await?; capture_stage(ctx.ensure_mobile_call_locked(key,true,&configuration).await,"mobile_call",key)?;
let allowed={let profile=ctx.profile()?;profile.prefs.capture_allowed(profile.migration.is_some())}; let allowed={let profile=ctx.profile()?;profile.prefs.capture_allowed(profile.migration.is_some())};
if !allowed{return Err(ServiceError::new("device_mapping_required","Confirm the imported microphone device before capture"))} if !allowed{return Err(ServiceError::new("device_mapping_required","Confirm the imported microphone device before capture"))}
let configuration=ctx.audio_configuration.lock().await; let prefs=ctx.profile()?.prefs.get();let mut config=capture_stage(ctx.capture_configuration(key,&prefs),"owner_configuration",key)?;config.input_muted=false;
let prefs=ctx.profile()?.prefs.get();let mut config=ctx.capture_configuration(key,&prefs)?;config.input_muted=false; capture_stage(ctx.connected.connections.set_input(Some(key),config).await.map_err(connection_error),"select_owner",key)?;
ctx.connected.connections.set_input(Some(key),config).await.map_err(connection_error)?; capture_stage(ctx.require_key(key,true),"selected_owner",key)?;ctx.require_ui_generation(generation)?;ctx.output_granted.store(true,Ordering::Release);
ctx.require_key(key,true)?;ctx.output_granted.store(true,Ordering::Release); {let mut transmission=ctx.transmission.lock().map_err(|_|changed())?;transmission.key=Some(key.clone());transmission.configured=None;transmission.revision=transmission.revision.wrapping_add(1);}
{let mut transmission=ctx.transmission.lock().map_err(|_|changed())?;transmission.key=Some(key.clone());transmission.revision=transmission.revision.wrapping_add(1);} super::settings_actions::activate_microphone(ctx.clone(),key,&configuration).await?;
drop(configuration);super::settings_actions::activate_microphone(ctx.clone(),key).await?;ctx.changed().await drop(configuration);ctx.changed().await
} }
pub async fn set_audio_flags(ctx:&Arc<RuntimeServices>,key:&SessionKey,input:Option<bool>,output:Option<bool>)->Result<()>{ pub async fn set_audio_flags(ctx:&Arc<RuntimeServices>,key:&SessionKey,input:Option<bool>,output:Option<bool>)->Result<()>{
use teamspeach_core::protocol::Command; use teamspeach_core::protocol::Command;
ctx.require_key(key,false)?;release_voice(ctx,key).await?; ctx.require_key(key,false)?;
if input==Some(false){ctx.policy.check()?;ctx.request_microphone_permission().await?;ctx.require_key(key,true)?;} // Owner configuration already sends the unmuted state with its fresh permit.
// Sending SetAudio first races that acknowledgement and asks permission twice.
if input==Some(false){if let Some(muted)=output{ctx.request(key,Command::SetAudio{input_muted:None,output_muted:Some(muted)}).await?;ctx.require_key(key,false)?;}return set_microphone_owner(ctx,key).await}
release_voice(ctx,key).await?;
if let Some(muted)=input{ctx.request(key,Command::SetAudio{input_muted:Some(muted),output_muted:None}).await?;ctx.require_key(key,false)?;} if let Some(muted)=input{ctx.request(key,Command::SetAudio{input_muted:Some(muted),output_muted:None}).await?;ctx.require_key(key,false)?;}
if let Some(muted)=output{ctx.request(key,Command::SetAudio{input_muted:None,output_muted:Some(muted)}).await?;ctx.require_key(key,false)?;} if let Some(muted)=output{ctx.request(key,Command::SetAudio{input_muted:None,output_muted:Some(muted)}).await?;ctx.require_key(key,false)?;}
if ctx.connected.connections.snapshot().get(&key.connection_id).is_some_and(|c|c.is_connected()){if input==Some(false){set_microphone_owner(ctx,key).await?;}else{ctx.refresh_capture().await?;}}ctx.changed().await if ctx.connected.connections.snapshot().get(&key.connection_id).is_some_and(|c|c.is_connected()){ctx.refresh_capture().await?;}ctx.changed().await
} }
pub async fn dispatch(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,values:Values)->Result<WorkflowResult>{ pub async fn dispatch(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,values:Values)->Result<WorkflowResult>{
if let Some(key)=&target.session{ctx.require_key(key,false)?;} if let Some(key)=&target.session{ctx.require_key(key,false)?;}
+5 -1
View File
@@ -24,7 +24,11 @@ async fn control(ctx:&Arc<RuntimeServices>,event:ConnectionEvent)->Result<()> {
} }
ctx.changed().await?; ctx.changed().await?;
}, },
ConnectionEvent::Failure{key,error}=>{if let Some(key)=key{ctx.streams.disconnect(&key,"connection_failure");local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;}ctx.effect(UiEffect::Error(context::connection_error(error))).await?;}, ConnectionEvent::Failure{key,error,terminal}=>{
// Configuration/command rejection is visible without closing live session workflows.
if terminal{if let Some(key)=key{ctx.streams.disconnect(&key,"connection_failure");local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;}}
ctx.effect(UiEffect::Error(context::connection_error(error))).await?;
},
// Runtime's composite sink invokes AudioSessionBinding synchronously before // Runtime's composite sink invokes AudioSessionBinding synchronously before
// queueing this observation. Revoking again can invalidate a newer permit. // queueing this observation. Revoking again can invalidate a newer permit.
ConnectionEvent::InputReset=>{}, ConnectionEvent::InputReset=>{},
+5 -2
View File
@@ -6,10 +6,13 @@ use crate::{app::connections::SessionKey,services::Result};
impl RuntimeServices { impl RuntimeServices {
/// Created only by a current foreground Connect/microphone action, never profile load or resume. /// Created only by a current foreground Connect/microphone action, never profile load or resume.
pub async fn ensure_mobile_call(self:&Arc<Self>,key:&SessionKey,microphone:bool)->Result<()> { pub async fn ensure_mobile_call(self:&Arc<Self>,key:&SessionKey,microphone:bool)->Result<()> {
let configuration=self.audio_configuration.lock().await;
self.ensure_mobile_call_locked(key,microphone,&configuration).await
}
/// Callers retain this guard through capture permit binding and hardware startup.
pub async fn ensure_mobile_call_locked(self:&Arc<Self>,key:&SessionKey,microphone:bool,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
self.policy.check()?;self.require_key(key,true)?;let generation=self.current_ui_generation()?; self.policy.check()?;self.require_key(key,true)?;let generation=self.current_ui_generation()?;
let mut call=self.mobile_call.lock().await; let mut call=self.mobile_call.lock().await;
#[cfg(target_os="android")]
let _configuration=self.audio_configuration.lock().await;
let cached=call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone)); let cached=call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone));
#[cfg(target_os="android")] #[cfg(target_os="android")]
let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone); let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone);
+2 -3
View File
@@ -68,7 +68,7 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
let binding=Arc::new(AudioSessionBinding::new(errors));let binding_sink=binding.clone();let overflow_runtime=runtime.clone(); let binding=Arc::new(AudioSessionBinding::new(errors));let binding_sink=binding.clone();let overflow_runtime=runtime.clone();
let consumer:Arc<dyn ConnectionSink>=Arc::new(move|event:ConnectionEvent|{ let consumer:Arc<dyn ConnectionSink>=Arc::new(move|event:ConnectionEvent|{
if matches!(&event,ConnectionEvent::Playback{..}){binding_sink.on_event(event);return} if matches!(&event,ConnectionEvent::Playback{..}){binding_sink.on_event(event);return}
match &event{ConnectionEvent::Control{key,value}=>binding_sink.on_event(ConnectionEvent::Control{key:key.clone(),value:value.clone()}),ConnectionEvent::Playback{..}=>unreachable!(),ConnectionEvent::InputReset=>binding_sink.on_event(ConnectionEvent::InputReset),ConnectionEvent::Failure{key,error}=>binding_sink.on_event(ConnectionEvent::Failure{key:key.clone(),error:error.clone()})} match &event{ConnectionEvent::Control{key,value}=>binding_sink.on_event(ConnectionEvent::Control{key:key.clone(),value:value.clone()}),ConnectionEvent::Playback{..}=>unreachable!(),ConnectionEvent::InputReset=>binding_sink.on_event(ConnectionEvent::InputReset),ConnectionEvent::Failure{key,error,terminal}=>binding_sink.on_event(ConnectionEvent::Failure{key:key.clone(),error:error.clone(),terminal:*terminal})}
if controls.try_send(event).is_err(){if let Some(runtime)=overflow_runtime.upgrade(){runtime.release_held();runtime.cancel.send_replace(true);}} if controls.try_send(event).is_err(){if let Some(runtime)=overflow_runtime.upgrade(){runtime.release_held();runtime.cancel.send_replace(true);}}
}); });
let connected=Arc::new(crate::services::connected::ConnectedServices::start(root.clone(),profile.files.clone(),config.network_enabled,consumer)?); let connected=Arc::new(crate::services::connected::ConnectedServices::start(root.clone(),profile.files.clone(),config.network_enabled,consumer)?);
@@ -235,8 +235,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
if let Some(owner)=&owner{ if let Some(owner)=&owner{
while let Ok(event)=owner.audio_events.try_recv(){audio_event(&owner.ctx,&mut state,event);dirty=true;} while let Ok(event)=owner.audio_events.try_recv(){audio_event(&owner.ctx,&mut state,event);dirty=true;}
if let Err(error)=owner.ctx.tick_transmission().await{state.snapshot.error=error.message;dirty=true;} if let Err(error)=owner.ctx.tick_transmission().await{state.snapshot.error=error.message;dirty=true;}
let snapshot=owner.ctx.connected.connections.snapshot();let current=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.is_connected()).map(|entry|entry.key.clone());let configured=owner.ctx.transmission.lock().map_err(|_|failed("Transmission state unavailable"))?.key.clone(); match owner.ctx.refresh_capture_owner_changed().await{Ok(changed)=>dirty|=changed,Err(error)=>{state.snapshot.error=error.message;dirty=true;}}
if current!=configured&&owner.ctx.audio_configuration.try_lock().is_ok(){if current.is_some(){if let Err(error)=owner.ctx.refresh_capture().await{state.snapshot.error=error.message;}}else{controller::release_immediate(&owner.ctx);owner.ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;owner.ctx.transmission.lock().map_err(|_|failed("Transmission state unavailable"))?.key=None;}dirty=true;}
#[cfg(not(any(target_os="android",target_os="ios")))] #[cfg(not(any(target_os="android",target_os="ios")))]
{let key_events={let mut keys=owner.ctx.keys.lock().await;let mut events=vec![];let context::KeyState{runtime,global,..}=&mut *keys;if let Some(global)=global{if let Err(error)=global.dispatch(runtime,|event|events.push(event)){state.snapshot.error=error.message;}}events};if !key_events.is_empty(){owner.ctx.apply_key_events(key_events).await?;}} {let key_events={let mut keys=owner.ctx.keys.lock().await;let mut events=vec![];let context::KeyState{runtime,global,..}=&mut *keys;if let Some(global)=global{if let Err(error)=global.dispatch(runtime,|event|events.push(event)){state.snapshot.error=error.message;}}events};if !key_events.is_empty(){owner.ctx.apply_key_events(key_events).await?;}}
if !startup_done&&config.allow_os_actions&&runtime.upgrade().and_then(|r|r.current_ui_generation()).is_some(){ if !startup_done&&config.allow_os_actions&&runtime.upgrade().and_then(|r|r.current_ui_generation()).is_some(){
@@ -10,14 +10,16 @@ pub(crate) fn capture_settings(prefs:&Value)->CaptureSettings{let input=profile(
pub(crate) fn gate(prefs:&Value)->Option<teamspeach_core::vad::GateMode>{use teamspeach_core::vad::{GateMode,Sensitivity};let input=profile(prefs,DeviceKind::Input);if input["vad"]!=true{return None}let sensitivity=match input["vadSensitivity"].as_str(){Some("high")=>Sensitivity::High,Some("low")=>Sensitivity::Low,_=>Sensitivity::Normal};let level_db=input["vadLevel"].as_f64().unwrap_or(-30.) as f32;Some(match input["vadMode"].as_str(){Some("volume_gate")=>GateMode::VolumeGate{level_db},Some("hybrid")=>GateMode::Hybrid{sensitivity,level_db},_=>GateMode::Automatic(sensitivity)})} pub(crate) fn gate(prefs:&Value)->Option<teamspeach_core::vad::GateMode>{use teamspeach_core::vad::{GateMode,Sensitivity};let input=profile(prefs,DeviceKind::Input);if input["vad"]!=true{return None}let sensitivity=match input["vadSensitivity"].as_str(){Some("high")=>Sensitivity::High,Some("low")=>Sensitivity::Low,_=>Sensitivity::Normal};let level_db=input["vadLevel"].as_f64().unwrap_or(-30.) as f32;Some(match input["vadMode"].as_str(){Some("volume_gate")=>GateMode::VolumeGate{level_db},Some("hybrid")=>GateMode::Hybrid{sensitivity,level_db},_=>GateMode::Automatic(sensitivity)})}
/// Loading preferences never opens hardware. Reconfiguration only resumes previously active, granted routes. /// Loading preferences never opens hardware. Reconfiguration only resumes previously active, granted routes.
pub async fn sync_audio(ctx:Arc<RuntimeServices>)->Result<()> { pub async fn sync_audio(ctx:Arc<RuntimeServices>)->Result<()> {
sync_audio_to(ctx,None,None).await let configuration=ctx.audio_configuration.lock().await;
sync_audio_to(&ctx,None,None,&configuration).await
} }
/// Explicit activation carries resume intent separately from acknowledged hardware state. /// Explicit activation carries resume intent separately from acknowledged hardware state.
pub(crate) async fn activate_microphone(ctx:Arc<RuntimeServices>,key:&crate::app::connections::SessionKey)->Result<()> { pub(crate) async fn activate_microphone(ctx:Arc<RuntimeServices>,key:&crate::app::connections::SessionKey,configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
sync_audio_to(ctx,Some((true,true)),Some(key)).await sync_audio_to(&ctx,Some((true,true)),Some(key),configuration).await
} }
async fn sync_audio_to(ctx:Arc<RuntimeServices>,resume:Option<(bool,bool)>,expected_owner:Option<&crate::app::connections::SessionKey>)->Result<()> { async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expected_owner:Option<&crate::app::connections::SessionKey>,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
let _configuration=ctx.audio_configuration.lock().await; let mut stage="validate_activation";
let result:Result<()>=async {
if lock(&ctx.microphone_test_resume)?.is_some(){return Err(ServiceError::new("microphone_test_active","Finish the private microphone test before applying voice settings"))} if lock(&ctx.microphone_test_resume)?.is_some(){return Err(ServiceError::new("microphone_test_active","Finish the private microphone test before applying voice settings"))}
let active=resume.unwrap_or_else(||(ctx.audio_input_active.load(Ordering::Acquire),ctx.audio_output_active.load(Ordering::Acquire))); let active=resume.unwrap_or_else(||(ctx.audio_input_active.load(Ordering::Acquire),ctx.audio_output_active.load(Ordering::Acquire)));
let (prefs,allowed)={let p=ctx.profile()?;(p.prefs.get(),p.prefs.capture_allowed(p.migration.is_some()))}; let (prefs,allowed)={let p=ctx.profile()?;(p.prefs.get(),p.prefs.capture_allowed(p.migration.is_some()))};
@@ -27,29 +29,44 @@ async fn sync_audio_to(ctx:Arc<RuntimeServices>,resume:Option<(bool,bool)>,expec
let active=(active.0&&owner.as_ref().is_some_and(|key|crate::platform::android::voice_audio_allowed(key,true)),active.1&&snapshot.connections.iter().any(|session|crate::platform::android::voice_audio_allowed(&session.key,false))); let active=(active.0&&owner.as_ref().is_some_and(|key|crate::platform::android::voice_audio_allowed(key,true)),active.1&&snapshot.connections.iter().any(|session|crate::platform::android::voice_audio_allowed(&session.key,false)));
if expected_owner.is_some()&&(!active.0||!allowed||!ctx.microphone_granted.load(Ordering::Acquire)){return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended before audio startup; enable it explicitly"))} if expected_owner.is_some()&&(!active.0||!allowed||!ctx.microphone_granted.load(Ordering::Acquire)){return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended before audio startup; enable it explicitly"))}
ctx.audio.revoke_capture(); ctx.audio.revoke_capture();
stage="configure_workflow";
ctx.connected.connections.configure_workflow(WorkflowSettings{auto_enable_microphone:prefs["autoEnableMicrophone"]==true,auto_reactivate_previous:prefs["autoReactivateMicOnPreviousTarget"]==true}).await.map_err(super::super::context::connection_error)?; ctx.connected.connections.configure_workflow(WorkflowSettings{auto_enable_microphone:prefs["autoEnableMicrophone"]==true,auto_reactivate_previous:prefs["autoReactivateMicOnPreviousTarget"]==true}).await.map_err(super::super::context::connection_error)?;
let selected=(prefs["inputDeviceId"].as_str().unwrap_or_default().to_owned(),prefs["outputDeviceId"].as_str().unwrap_or_default().to_owned()); let selected=(prefs["inputDeviceId"].as_str().unwrap_or_default().to_owned(),prefs["outputDeviceId"].as_str().unwrap_or_default().to_owned());
let previous=lock(&ctx.applied_audio_selections)?.clone(); let previous=lock(&ctx.applied_audio_selections)?.clone();
if previous.as_ref().is_none_or(|p|p.0!=selected.0){ctx.audio.request(AudioCommand::SelectInput(selection(&selected.0))).await?;} if previous.as_ref().is_none_or(|p|p.0!=selected.0){stage="select_input";ctx.audio.request(AudioCommand::SelectInput(selection(&selected.0))).await?;}
if previous.as_ref().is_none_or(|p|p.1!=selected.1){ctx.audio.request(AudioCommand::SelectOutput(selection(&selected.1))).await?;} if previous.as_ref().is_none_or(|p|p.1!=selected.1){stage="select_output";ctx.audio.request(AudioCommand::SelectOutput(selection(&selected.1))).await?;}
*lock(&ctx.applied_audio_selections)?=Some(selected); *lock(&ctx.applied_audio_selections)?=Some(selected);
let output=profile(&prefs,DeviceKind::Output); let output=profile(&prefs,DeviceKind::Output);
stage="playback_settings";
ctx.audio.request(AudioCommand::SetPlaybackDsp(PlaybackDsp{comfort_noise:output["comfortNoise"]==true,comfort_noise_level_db:output["comfortNoiseLevel"].as_f64().unwrap_or(-60.) as f32,echo_reduction_db:output["echoReduction"].as_f64().unwrap_or(0.) as f32})).await?; ctx.audio.request(AudioCommand::SetPlaybackDsp(PlaybackDsp{comfort_noise:output["comfortNoise"]==true,comfort_noise_level_db:output["comfortNoiseLevel"].as_f64().unwrap_or(-60.) as f32,echo_reduction_db:output["echoReduction"].as_f64().unwrap_or(0.) as f32})).await?;
let level=prefs["outputLevelDb"].as_f64().unwrap_or(0.);ctx.audio.request(AudioCommand::SetVoiceGain(if level<=-200.{0.}else{10f32.powf(level as f32/20.)})).await?; let level=prefs["outputLevelDb"].as_f64().unwrap_or(0.);ctx.audio.request(AudioCommand::SetVoiceGain(if level<=-200.{0.}else{10f32.powf(level as f32/20.)})).await?;
ctx.audio.request(AudioCommand::TypingEnabled(profile(&prefs,DeviceKind::Input)["typing"]==true)).await?; ctx.audio.request(AudioCommand::TypingEnabled(profile(&prefs,DeviceKind::Input)["typing"]==true)).await?;
stage="notification_route";
sync_notifications(&ctx).await?; sync_notifications(&ctx).await?;
if active.1&&ctx.output_granted.load(Ordering::Acquire){ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);} if active.1&&ctx.output_granted.load(Ordering::Acquire){stage="start_output";ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);}
stage="server_playback_dsp";
for session in snapshot.connections.iter().filter(|s|s.is_connected()) {ctx.request(&session.key,teamspeach_core::protocol::Command::SetPlaybackDsp{agc:output["agc"]==true}).await?;ctx.require_key(&session.key,true)?;} for session in snapshot.connections.iter().filter(|s|s.is_connected()) {ctx.request(&session.key,teamspeach_core::protocol::Command::SetPlaybackDsp{agc:output["agc"]==true}).await?;ctx.require_key(&session.key,true)?;}
if let Some(key)=owner { if let Some(key)=owner {
stage="configure_capture";
ctx.require_key(&key,true)?; ctx.require_key(&key,true)?;
if ctx.connected.connections.snapshot().input_id.as_deref()!=Some(key.connection_id.as_str()){return Err(super::super::context::changed())} if ctx.connected.connections.snapshot().input_id.as_deref()!=Some(key.connection_id.as_str()){return Err(super::super::context::changed())}
let mut config=ctx.capture_configuration(&key,&prefs)?;config.vad=gate(&prefs);config.input_muted|=!allowed||!ctx.microphone_granted.load(Ordering::Acquire); let mut config=ctx.capture_configuration(&key,&prefs)?;config.vad=gate(&prefs);config.input_muted|=!allowed||!ctx.microphone_granted.load(Ordering::Acquire);
let permit=ctx.connected.connections.set_input(Some(&key),config).await.map_err(super::super::context::connection_error)?; let permit=ctx.connected.connections.set_input(Some(&key),config).await.map_err(super::super::context::connection_error)?;
if expected_owner.is_some()&&permit.is_none(){return Err(super::super::context::changed())} if expected_owner.is_some()&&permit.is_none(){return Err(super::super::context::changed())}
ctx.require_key(&key,true)?; ctx.require_key(&key,true)?;
if let Some(permit)=permit{ctx.audio.request(AudioCommand::BindPermit{permit,settings:capture_settings(&prefs)}).await?;ctx.require_key(&key,true)?;if active.0&&allowed&&ctx.microphone_granted.load(Ordering::Acquire){ctx.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;ctx.audio_input_active.store(true,Ordering::Release);ctx.refresh_transmission_gate(&key,&prefs)?;}} if let Some(permit)=permit{
stage="bind_permit";ctx.audio.request(AudioCommand::BindPermit{permit,settings:capture_settings(&prefs)}).await?;ctx.require_key(&key,true)?;
lock(&ctx.transmission)?.configured=Some(config);
if active.0&&allowed&&ctx.microphone_granted.load(Ordering::Acquire){
stage="start_input";ctx.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;
ctx.audio_input_active.store(true,Ordering::Release);
stage="transmission_gate";ctx.refresh_transmission_gate(&key,&prefs)?;
}
}
} }
Ok(()) Ok(())
}.await;
if let Some(key)=expected_owner{super::super::context_helpers::capture_stage(result,stage,key)}else{result}
} }
pub(crate) async fn sync_notifications(ctx:&RuntimeServices)->Result<()> { pub(crate) async fn sync_notifications(ctx:&RuntimeServices)->Result<()> {
let prefs=ctx.profile()?.prefs.get();let settings:crate::services::notifications::NotificationPrefs=serde_json::from_value(prefs.clone())?; let prefs=ctx.profile()?.prefs.get();let settings:crate::services::notifications::NotificationPrefs=serde_json::from_value(prefs.clone())?;
@@ -74,6 +91,7 @@ pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<Workfl
Operation::CopyDspToTemplate{kind,device}=>{ctx.mutate(move|p|{let key=dsp_key(kind)?;let mut dsp=p.prefs.get()[key].clone();dsp["template"]=dsp["devices"].get(&device).cloned().ok_or_else(||bad("Device profile no longer exists"))?;p.prefs.set(json!({key:dsp}))?;Ok(())}).await?;}, Operation::CopyDspToTemplate{kind,device}=>{ctx.mutate(move|p|{let key=dsp_key(kind)?;let mut dsp=p.prefs.get()[key].clone();dsp["template"]=dsp["devices"].get(&device).cloned().ok_or_else(||bad("Device profile no longer exists"))?;p.prefs.set(json!({key:dsp}))?;Ok(())}).await?;},
Operation::ApplyDspTemplate{kind,device}=>{ctx.mutate(move|p|{let key=dsp_key(kind)?;let mut dsp=p.prefs.get()[key].clone();if dsp["devices"].get(&device).is_none(){return Err(bad("Device profile no longer exists"))}dsp["devices"][&device]=dsp["template"].clone();p.prefs.set(json!({key:dsp}))?;Ok(())}).await?;}, Operation::ApplyDspTemplate{kind,device}=>{ctx.mutate(move|p|{let key=dsp_key(kind)?;let mut dsp=p.prefs.get()[key].clone();if dsp["devices"].get(&device).is_none(){return Err(bad("Device profile no longer exists"))}dsp["devices"][&device]=dsp["template"].clone();p.prefs.set(json!({key:dsp}))?;Ok(())}).await?;},
Operation::AudioTest(action)=>{ Operation::AudioTest(action)=>{
let configuration=ctx.audio_configuration.lock().await;
match action { match action {
AudioTest::Record=>{ctx.policy.check()?;let allowed={let p=ctx.profile()?;p.prefs.capture_allowed(p.migration.is_some())};if !allowed{return Err(ServiceError::new("device_mapping_required","Confirm the imported microphone device first"))} AudioTest::Record=>{ctx.policy.check()?;let allowed={let p=ctx.profile()?;p.prefs.capture_allowed(p.migration.is_some())};if !allowed{return Err(ServiceError::new("device_mapping_required","Confirm the imported microphone device first"))}
let snapshot=ctx.connected.connections.snapshot();let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone()); let snapshot=ctx.connected.connections.snapshot();let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone());
@@ -86,7 +104,7 @@ pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<Workfl
if let Err(error)=ctx.audio.request(AudioCommand::BeginMicrophoneTest{permission:StartPermission::Granted,settings}).await{lock(&ctx.microphone_test_resume)?.take();return Err(error)}}, if let Err(error)=ctx.audio.request(AudioCommand::BeginMicrophoneTest{permission:StartPermission::Granted,settings}).await{lock(&ctx.microphone_test_resume)?.take();return Err(error)}},
AudioTest::Stop=>ctx.audio.request(AudioCommand::StopMicrophoneTest).await?, AudioTest::Stop=>ctx.audio.request(AudioCommand::StopMicrophoneTest).await?,
AudioTest::Play=>{ctx.policy.check()?;ctx.output_granted.store(true,Ordering::Release);ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio.request(AudioCommand::ListenMicrophoneTest).await?;}, AudioTest::Play=>{ctx.policy.check()?;ctx.output_granted.store(true,Ordering::Release);ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio.request(AudioCommand::ListenMicrophoneTest).await?;},
AudioTest::Clear=>{ctx.audio.request(AudioCommand::FinishMicrophoneTest).await?;let resume=lock(&ctx.microphone_test_resume)?.take();if let Some((owner,input,output))=resume{let snapshot=ctx.connected.connections.snapshot();let current=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone());if current!=owner{return Err(super::super::context::changed())}if !output{ctx.audio.request(AudioCommand::StopOutput).await?;}sync_audio_to(ctx.clone(),Some((input,output)),None).await?;}}, AudioTest::Clear=>{ctx.audio.request(AudioCommand::FinishMicrophoneTest).await?;let resume=lock(&ctx.microphone_test_resume)?.take();if let Some((owner,input,output))=resume{let snapshot=ctx.connected.connections.snapshot();let current=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone());if current!=owner{return Err(super::super::context::changed())}if !output{ctx.audio.request(AudioCommand::StopOutput).await?;}drop(configuration);sync_audio_to(ctx.clone(),Some((input,output)),None).await?;}},
}return done() }return done()
}, },
Operation::PreviewNotification(name)=>{ Operation::PreviewNotification(name)=>{
+3 -3
View File
@@ -30,7 +30,7 @@ impl ConnectedServices {
let routed = Arc::new(move |event: ConnectionEvent| { let routed = Arc::new(move |event: ConnectionEvent| {
let packet = match &event { let packet = match &event {
ConnectionEvent::Control {key,value} if value["event"] == "file_transfer" => Some(FileEvent::Control(key.clone(),value.clone())), ConnectionEvent::Control {key,value} if value["event"] == "file_transfer" => Some(FileEvent::Control(key.clone(),value.clone())),
ConnectionEvent::Failure {key:Some(key),..} => Some(FileEvent::Closed(key.clone())), ConnectionEvent::Failure {key:Some(key),terminal:true,..} => Some(FileEvent::Closed(key.clone())),
_ => None, _ => None,
}; };
if packet.is_some_and(|packet| sender.try_send(packet).is_err()) { if packet.is_some_and(|packet| sender.try_send(packet).is_err()) {
@@ -54,12 +54,12 @@ impl ConnectedServices {
event = incoming.recv() => match event { event = incoming.recv() => match event {
Some(FileEvent::Control(key,value)) => { Some(FileEvent::Control(key,value)) => {
if let Err(error) = files.lock().await.on_event(owner.as_ref(), &key, &value).await { if let Err(error) = files.lock().await.on_event(owner.as_ref(), &key, &value).await {
observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()) }); observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()), terminal: false });
} }
}, },
Some(FileEvent::Closed(key)) => { Some(FileEvent::Closed(key)) => {
if let Err(error) = files.lock().await.on_closed(owner.as_ref(), &key).await { if let Err(error) = files.lock().await.on_closed(owner.as_ref(), &key).await {
observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()) }); observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()), terminal: false });
} }
}, },
None => break, None => break,
+1 -1
View File
@@ -38,7 +38,7 @@ impl ConnectionSink for ServiceEvents {
_ => {}, _ => {},
} }
self.icon_transfers.on_control(key, value.clone()); self.icon_transfers.on_control(key, value.clone());
} else if let ConnectionEvent::Failure { key: Some(key), .. } = &event { } else if let ConnectionEvent::Failure { key: Some(key), terminal: true, .. } = &event {
self.close(key); self.close(key);
} }
self.consumer.on_event(event); self.consumer.on_event(event);