Join retired Android runtime and recover acknowledged headset routes
android-ci / android-arm64 (push) Failing after 12m25s
android-ci / android-arm64 (push) Failing after 12m25s
This commit is contained in:
1 parent
505a784235
commit
2565e5526a
17 files changed
+644
-53
No files matched your search
@@ -9,6 +9,17 @@ fn suspend_immediate(ctx:&RuntimeServices,retain_capture:bool){
|
||||
if let Ok(mut tx)=ctx.transmission.lock(){if !retain_capture{tx.capture_desired=false;tx.deactivated.clear();}tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.bound_permit=None;}
|
||||
}
|
||||
pub fn release_immediate(ctx:&RuntimeServices){suspend_immediate(ctx,false);}
|
||||
/// Fence old PCM immediately; only already-granted steady capture may migrate.
|
||||
#[cfg(any(target_os="android",test))]
|
||||
pub fn suspend_route_immediate(ctx:&RuntimeServices,key:&SessionKey,authorized:bool)->Option<crate::services::whisper::RoutedCommand>{
|
||||
ctx.audio.revoke_capture();ctx.audio.set_transmission_enabled(false);
|
||||
let mut tx=ctx.transmission.lock().ok()?;
|
||||
let preserve=authorized&&ctx.microphone_granted.load(Ordering::Acquire)&&tx.key.as_ref()==Some(key)
|
||||
&&tx.capture_desired&&tx.ptt_holders.is_empty()&&tx.release_at.is_none()&&tx.deactivated.is_empty()&&!tx.whisper.held();
|
||||
if !preserve{tx.capture_desired=false;tx.deactivated.clear();}
|
||||
tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.bound_permit=None;
|
||||
tx.whisper.release(None)
|
||||
}
|
||||
/// A foreground call owns steady-state capture; momentary controls remain UI-owned.
|
||||
pub fn release_ui_immediate(ctx:&RuntimeServices,background_capture:bool)->Option<crate::services::whisper::RoutedCommand>{
|
||||
if let Ok(mut tx)=ctx.transmission.lock(){tx.ui_controls_suspended=true;}
|
||||
|
||||
@@ -103,7 +103,7 @@ async fn platform(ctx:&Arc<RuntimeServices>,runtime:&Weak<AppRuntime>,state:&mut
|
||||
AndroidCallAudio{key,token,revision,restart_output}=>{
|
||||
if !crate::platform::android::voice_audio_current(key,*token,*revision){return Ok(false)}
|
||||
ctx.android_audio_changed(key,*token,*revision,*restart_output).await?;
|
||||
state.snapshot.status=if crate::platform::android::voice_audio_allowed(key,false){"Listening resumed. Enable the microphone explicitly."}else{"Audio paused by Android. Waiting for audio focus."}.into();
|
||||
state.snapshot.status=if crate::platform::android::voice_audio_allowed(key,true)&&ctx.audio.input_active(){"Audio route updated."}else if crate::platform::android::voice_audio_allowed(key,false){"Listening resumed. Enable the microphone explicitly."}else{"Audio paused by Android. Waiting for audio focus."}.into();
|
||||
},
|
||||
AudioInterruption{began,should_resume}=>{if *began{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopOutput).await?;}else if *should_resume{state.snapshot.status="Audio interruption ended. Resume the call with an explicit microphone action.".into();}},
|
||||
AudioRouteChanged|NetworkChanged=>{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;state.snapshot.status="Audio/network route changed; stale capture was discarded. Resume microphone explicitly.".into();},
|
||||
|
||||
@@ -191,3 +191,98 @@ async fn audit_lifecycle_network_change_fences_old_capture_without_automatic_res
|
||||
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||
cleanup(owner).await;
|
||||
}
|
||||
|
||||
async fn route_capture_fixture(owner:&Owner)->crate::app::connections::SessionKey {
|
||||
let ctx=&owner.ctx;let key=ctx.connected.connections.snapshot().connections[0].key.clone();
|
||||
// Only connected server presentation is reduced locally. Configuration,
|
||||
// permits, BindPermit, ingress rejection and startup use production consumers.
|
||||
ctx.profile().unwrap().prefs.set(json!({"pttEnabled":false})).unwrap();
|
||||
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":key.generation,"own_channel_id":1,"channels":[{"id":1,"codec":"opus_voice"}],"clients":[]})).await.unwrap();
|
||||
let prefs=ctx.profile().unwrap().prefs.get();
|
||||
let config=crate::app::connections::InputConfiguration{vad:settings_actions::capture_gate(&prefs),input_muted:false,output_muted:false};
|
||||
ctx.connected.connections.set_input(Some(&key),config).await.unwrap().unwrap();
|
||||
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;}
|
||||
ctx.microphone_granted.store(true,Ordering::Release);key
|
||||
}
|
||||
fn route_capture_barrier(owner:&mut Owner)->(std::sync::mpsc::Receiver<()>,std::sync::mpsc::SyncSender<()>) {
|
||||
let(entered,observed)=std::sync::mpsc::sync_channel(1);let(release,released)=std::sync::mpsc::sync_channel(1);
|
||||
owner.audio.set_test_capture_start(entered,released);(observed,release)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn audit_lifecycle_route_ack_replaces_revoked_capture_once_and_reverses() {
|
||||
let(_directory,mut owner,_events,_controls)=fixture().await;
|
||||
let key=route_capture_fixture(&owner).await;let ctx=owner.ctx.clone();
|
||||
let(_,release)=route_capture_barrier(&mut owner);release.send(()).unwrap();ctx.refresh_capture().await.unwrap();
|
||||
for route in ["headset acknowledged","phone return acknowledged"] {
|
||||
let old=ctx.connected.connections.current_capture_permit().unwrap();
|
||||
assert!(controller::suspend_route_immediate(&ctx,&key,true).is_none());
|
||||
assert!(!ctx.audio.input_active(),"{route}: PCM must be fenced before any worker await");
|
||||
assert!(ctx.transmission.lock().unwrap().capture_desired);
|
||||
assert!(ctx.connected.connections.current_capture_permit().is_none());
|
||||
let stale=teamspeach_core::audio::CapturedFrame{pcm:[1;960],captured_at:Instant::now(),connection_generation:key.generation,capture_epoch:old.capture_epoch,whisper:None};
|
||||
assert_eq!(ctx.connected.connections.push_audio(&key,stale),crate::app::connections::CaptureIngress::PermitRevoked);
|
||||
let revision=ctx.transmission.lock().unwrap().revision;
|
||||
ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await.unwrap();
|
||||
let(entered,release)=route_capture_barrier(&mut owner);
|
||||
// This is the production post-OS-ACK capture continuation, not a fabricated
|
||||
// physical headset or network success. The synthetic device owns its barrier.
|
||||
let recovery=tokio::spawn({let ctx=ctx.clone();let key=key.clone();async move{
|
||||
let configuration=ctx.audio_configuration.lock().await;
|
||||
ctx.resume_mobile_route_capture_locked(&key,revision,&configuration).await
|
||||
}});
|
||||
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
|
||||
let fresh=ctx.connected.connections.current_capture_permit().unwrap();assert_ne!(old,fresh);
|
||||
assert_eq!(ctx.transmission.lock().unwrap().bound_permit.as_ref(),Some(&fresh),"fresh manager + BindPermit ACK must precede StartInput");
|
||||
assert!(!ctx.audio.input_active(),"startup must not acknowledge before its backend barrier");
|
||||
release.send(()).unwrap();assert!(recovery.await.unwrap().unwrap());assert!(ctx.audio.input_active());
|
||||
let manager_revision=ctx.connected.connections.snapshot().capture_revision;
|
||||
assert!(!ctx.refresh_capture_owner_changed().await.unwrap(),"queued old observations must not replace the acknowledged route again");
|
||||
assert_eq!(manager_revision,ctx.connected.connections.snapshot().capture_revision);
|
||||
}
|
||||
controller::suspend_route_immediate(&ctx,&key,true);let stale=ctx.transmission.lock().unwrap().revision;
|
||||
controller::suspend_route_immediate(&ctx,&key,true);
|
||||
let configuration=ctx.audio_configuration.lock().await;
|
||||
assert!(!ctx.resume_mobile_route_capture_locked(&key,stale,&configuration).await.unwrap(),"superseded route ACK cannot start capture");
|
||||
drop(configuration);cleanup(owner).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn audit_lifecycle_newer_mute_supersedes_pending_route_start() {
|
||||
let(_directory,mut owner,_events,_controls)=fixture().await;
|
||||
let key=route_capture_fixture(&owner).await;let ctx=owner.ctx.clone();
|
||||
controller::suspend_route_immediate(&ctx,&key,true);let revision=ctx.transmission.lock().unwrap().revision;
|
||||
let(entered,release)=route_capture_barrier(&mut owner);
|
||||
let recovery=tokio::spawn({let ctx=ctx.clone();let key=key.clone();async move{
|
||||
let configuration=ctx.audio_configuration.lock().await;
|
||||
ctx.resume_mobile_route_capture_locked(&key,revision,&configuration).await
|
||||
}});
|
||||
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
|
||||
let mut mute=Box::pin(controller::set_audio_flags(&ctx,&key,Some(true),None));
|
||||
std::future::poll_fn(|cx|{assert!(Future::poll(mute.as_mut(),cx).is_pending());std::task::Poll::Ready(())}).await;
|
||||
assert!(!ctx.transmission.lock().unwrap().capture_desired);assert!(ctx.connected.connections.current_capture_permit().is_none());
|
||||
release.send(()).unwrap();assert!(recovery.await.unwrap().is_err());mute.await.unwrap();
|
||||
assert!(!ctx.audio.input_active());assert!(ctx.connected.connections.current_capture_permit().is_none());
|
||||
let configuration=ctx.audio_configuration.lock().await;
|
||||
assert!(!ctx.resume_mobile_route_capture_locked(&key,revision,&configuration).await.unwrap(),"late route completion is not a microphone regrant");
|
||||
drop(configuration);cleanup(owner).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn audit_lifecycle_route_fence_never_promotes_receive_only_or_momentary_capture() {
|
||||
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||
let key=route_capture_fixture(&owner).await;
|
||||
for boundary in ["receive only","permission denied","held PTT","PTT release delay","held whisper"] {
|
||||
ctx.microphone_granted.store(boundary!="permission denied",Ordering::Release);
|
||||
{let mut tx=ctx.transmission.lock().unwrap();tx.capture_desired=boundary!="receive only";
|
||||
if boundary=="held PTT"{tx.ptt_holders.insert("screen".into());}
|
||||
if boundary=="PTT release delay"{tx.release_at=Some(Instant::now()+Duration::from_secs(30));}
|
||||
if boundary=="held whisper"{tx.whisper.prepare("route-whisper",key.clone());}
|
||||
}
|
||||
controller::suspend_route_immediate(ctx,&key,boundary!="receive only");
|
||||
let tx=ctx.transmission.lock().unwrap();assert!(!tx.capture_desired,"{boundary} is not migratable steady capture");assert!(tx.ptt_holders.is_empty());assert!(tx.release_at.is_none());assert!(!tx.whisper.held());
|
||||
}
|
||||
controller::suspend_route_immediate(ctx,&key,true);
|
||||
assert!(!ctx.transmission.lock().unwrap().capture_desired,"another route observation is never a new grant");
|
||||
assert!(!ctx.audio.input_active());cleanup(owner).await;
|
||||
}
|
||||
@@ -10,7 +10,7 @@ impl RuntimeServices {
|
||||
{
|
||||
if !self.policy.allow_os_actions||!self.microphone_granted.load(std::sync::atomic::Ordering::Acquire){return false}
|
||||
let snapshot=self.connected.connections.snapshot();
|
||||
return snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).is_some_and(|session|session.is_connected()&&crate::platform::android::voice_audio_allowed(&session.key,true));
|
||||
return snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).is_some_and(|session|session.is_connected()&&crate::platform::android::voice_capture_retained(&session.key));
|
||||
}
|
||||
#[cfg(not(target_os="android"))]
|
||||
false
|
||||
@@ -46,17 +46,35 @@ impl RuntimeServices {
|
||||
if !crate::platform::android::voice_audio_allowed(key,microphone){return Err(crate::services::ServiceError::new("audio_focus_unavailable","Android revoked call audio authorization during startup"))}
|
||||
Ok(())
|
||||
}
|
||||
/// Complete only the steady intent captured by the synchronous route fence.
|
||||
/// Shared with host consumer regressions; hardware/core ACKs remain real.
|
||||
#[cfg(any(target_os="android",test))]
|
||||
pub(super) async fn resume_mobile_route_capture_locked(self:&Arc<Self>,key:&SessionKey,intent_revision:u64,configuration:&tokio::sync::MutexGuard<'_,()>)->Result<bool>{
|
||||
self.require_key(key,true)?;
|
||||
if self.transmission.lock().map_err(|_|super::context::changed())?.capture_intent(key,intent_revision).is_err(){return Ok(false)}
|
||||
self.refresh_capture_locked(configuration,false).await
|
||||
}
|
||||
#[cfg(target_os="android")]
|
||||
pub async fn android_audio_changed(self:&Arc<Self>,key:&SessionKey,token:u64,revision:u64,restart_output:bool)->Result<()> {
|
||||
use crate::media::audio::{engine::AudioCommand,devices::StartPermission};
|
||||
use std::sync::atomic::Ordering;
|
||||
let current=||self.require_key(key,true).is_ok()&&crate::platform::android::voice_audio_current(key,token,revision);
|
||||
if !current(){return Ok(())}
|
||||
let _configuration=self.audio_configuration.lock().await;
|
||||
let configuration=self.audio_configuration.lock().await;
|
||||
if !current(){return Ok(())}
|
||||
super::controller::release_immediate(self);
|
||||
let migrate=crate::platform::android::voice_audio_allowed(key,true);
|
||||
// The callback already fenced PCM and dropped momentary controls. Do not
|
||||
// revoke retained steady consent a second time on the queued worker.
|
||||
if !migrate{super::controller::release_immediate(self);}
|
||||
let intent_revision=self.transmission.lock().map_err(|_|super::context::changed())?.revision;
|
||||
self.audio.request(AudioCommand::StopInput).await?;
|
||||
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
||||
if !current(){return Ok(())}
|
||||
let prefs=self.profile()?.prefs.get();
|
||||
self.audio.request(AudioCommand::SelectInput(crate::platform::android::voice_device_selection(prefs["inputDeviceId"].as_str().unwrap_or_default())?)).await?;
|
||||
if !current(){return Ok(())}
|
||||
self.audio.request(AudioCommand::SelectOutput(crate::platform::android::voice_device_selection(prefs["outputDeviceId"].as_str().unwrap_or_default())?)).await?;
|
||||
if !current(){return Ok(())}
|
||||
if restart_output {
|
||||
self.audio.request(AudioCommand::StopOutput).await?;
|
||||
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
||||
@@ -67,7 +85,13 @@ impl RuntimeServices {
|
||||
}
|
||||
if current(){crate::platform::android::acknowledge_voice_output(key,token,revision,self.audio.output_active());}
|
||||
}
|
||||
if current()&&self.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()) {
|
||||
if !current(){return Ok(())}
|
||||
// Permission/mute/owner changes that arrived while hardware was replaced
|
||||
// supersede this migration. Never infer consent from an old route event.
|
||||
if self.transmission.lock().map_err(|_|super::context::changed())?.revision!=intent_revision{return Ok(())}
|
||||
if migrate&&self.microphone_granted.load(Ordering::Acquire){
|
||||
self.resume_mobile_route_capture_locked(key,intent_revision,&configuration).await?;
|
||||
}else if self.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()) {
|
||||
self.request(key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(true),output_muted:None}).await?;
|
||||
}
|
||||
if current(){self.audio.request(AudioCommand::Enumerate).await?;}
|
||||
|
||||
@@ -4,7 +4,12 @@ use teamspeach_denoise::CaptureSettings;
|
||||
|
||||
pub(super) fn dsp_key(kind:DeviceKind)->Result<&'static str>{match kind{DeviceKind::Input=>Ok("inputDsp"),DeviceKind::Output=>Ok("outputDsp"),DeviceKind::Notification=>Err(bad("Notification devices have no voice DSP profile"))}}
|
||||
fn selection_key(kind:DeviceKind)->&'static str{match kind{DeviceKind::Input=>"inputDeviceId",DeviceKind::Output=>"outputDeviceId",DeviceKind::Notification=>"notificationDeviceId"}}
|
||||
fn selection(id:&str)->DeviceSelection{if id.is_empty(){DeviceSelection::SystemDefault}else{DeviceSelection::Exact(id.into())}}
|
||||
fn selection(id:&str)->Result<DeviceSelection>{
|
||||
#[cfg(target_os="android")]
|
||||
{return crate::platform::android::voice_device_selection(id)}
|
||||
#[cfg(not(target_os="android"))]
|
||||
Ok(if id.is_empty(){DeviceSelection::SystemDefault}else{DeviceSelection::Exact(id.into())})
|
||||
}
|
||||
pub(super) fn profile<'a>(prefs:&'a Value,kind:DeviceKind)->&'a Value{let key=if kind==DeviceKind::Input{"inputDsp"}else{"outputDsp"};let id=prefs[selection_key(kind)].as_str().filter(|s|!s.is_empty()).unwrap_or("default");prefs[key]["devices"].get(id).unwrap_or(&prefs[key]["template"])}
|
||||
pub(crate) fn capture_settings(prefs:&Value)->CaptureSettings{let input=profile(prefs,DeviceKind::Input);let output=profile(prefs,DeviceKind::Output);CaptureSettings{echo_cancellation:output["aec"]==true,noise_suppression:if input["denoise"]==true{Some(input["denoiseLevel"].as_u64().unwrap_or(1) as u8)}else{None},automatic_gain_control:input["agc"]==true}}
|
||||
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)})}
|
||||
@@ -34,11 +39,15 @@ async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expe
|
||||
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)?;
|
||||
let selected=(prefs["inputDeviceId"].as_str().unwrap_or_default().to_owned(),prefs["outputDeviceId"].as_str().unwrap_or_default().to_owned());
|
||||
let selected=(selection(prefs["inputDeviceId"].as_str().unwrap_or_default())?,selection(prefs["outputDeviceId"].as_str().unwrap_or_default())?);
|
||||
let selected_id=|selection:&DeviceSelection|match selection{DeviceSelection::SystemDefault=>String::new(),DeviceSelection::Exact(id)=>id.clone()};
|
||||
// Cache the applied role, not a persisted phone endpoint that becomes the
|
||||
// communication default only after the foreground call lease is acquired.
|
||||
let applied=(selected_id(&selected.0),selected_id(&selected.1));
|
||||
let previous=lock(&ctx.applied_audio_selections)?.clone();
|
||||
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){stage="select_output";ctx.audio.request(AudioCommand::SelectOutput(selection(&selected.1))).await?;}
|
||||
*lock(&ctx.applied_audio_selections)?=Some(selected);
|
||||
if previous.as_ref().is_none_or(|p|p.0!=applied.0){stage="select_input";ctx.audio.request(AudioCommand::SelectInput(selected.0)).await?;}
|
||||
if previous.as_ref().is_none_or(|p|p.1!=applied.1){stage="select_output";ctx.audio.request(AudioCommand::SelectOutput(selected.1)).await?;}
|
||||
*lock(&ctx.applied_audio_selections)?=Some(applied);
|
||||
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?;
|
||||
|
||||
+33
-4
@@ -13,6 +13,9 @@ pub mod platform;
|
||||
pub mod ui;
|
||||
#[cfg(feature="test-harness")]
|
||||
pub mod smoke;
|
||||
#[cfg(any(target_os="android",test))]
|
||||
#[path="platform/android/runtime_attachment.rs"]
|
||||
mod runtime_attachment;
|
||||
slint::include_modules!();
|
||||
|
||||
#[derive(Clone,Debug)]
|
||||
@@ -81,8 +84,22 @@ impl AppRuntime {
|
||||
pub fn release_held(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){app::runtime::controller::release_immediate(&ctx);let stop=ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None));if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
|
||||
/// UI loss releases momentary controls, not an already-authorized Android call.
|
||||
pub fn release_ui_holds(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){let stop=app::runtime::controller::release_ui_immediate(&ctx,ctx.background_capture_authorized());if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
|
||||
/// Runs on the OS callback before the route request or any worker await.
|
||||
#[cfg(target_os="android")]
|
||||
pub(crate) fn fence_android_audio_route(&self,key:&app::connections::SessionKey,authorized:bool){
|
||||
if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
|
||||
if let Some(stop)=app::runtime::controller::suspend_route_immediate(&ctx,key,authorized){
|
||||
if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Nonblocking OS shutdown: synchronous capture fence followed by worker cleanup.
|
||||
pub(crate) fn request_shutdown(&self){self.release_held();self.cancel.send_replace(true);}
|
||||
/// Lifecycle truth comes from the worker, not its last presentation snapshot.
|
||||
#[cfg(any(target_os="android",test))]
|
||||
pub(crate) fn accepts_ui_attachment(&self)->bool{
|
||||
!*self.cancel.borrow()&&self.finished.borrow().is_none()&&!self.commands.is_closed()
|
||||
}
|
||||
fn release_screen(&self,target:&ui::shell::Target){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
|
||||
let delay=ctx.profile().ok().map(|profile|profile.prefs.get()["pttReleaseDelay"].clone());
|
||||
let revoke=if let Ok(mut tx)=ctx.transmission.lock(){if tx.key.as_ref()!=target.session.as_ref(){return}let removed=tx.ptt_holders.remove("screen");if removed{tx.revision=tx.revision.wrapping_add(1);if tx.ptt_holders.is_empty(){tx.release_at=delay.filter(|d|d["active"]==true).and_then(|d|d["ms"].as_u64()).map(|ms|std::time::Instant::now()+std::time::Duration::from_millis(ms));}}removed&&!tx.whisper.held()}else{true};
|
||||
@@ -102,12 +119,12 @@ impl AppRuntime {
|
||||
#[cfg(target_os="android")]
|
||||
if let AndroidCallAudio{key,token,revision,..}=&event {
|
||||
if !platform::android::voice_audio_current(key,*token,*revision){return}
|
||||
self.release_held();
|
||||
if platform::android::voice_audio_allowed(key,true){self.fence_android_audio_route(key,true);}else{self.release_held();}
|
||||
}
|
||||
if matches!(&event,Focus{focused:false,..}|UiDestroyed{..}){self.release_ui_holds();}
|
||||
#[cfg(target_os="android")]
|
||||
if matches!(&event,Visibility{visible:false,..}){self.release_ui_holds();}
|
||||
if matches!(&event,AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Quit){self.release_held();}
|
||||
if matches!(&event,AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Notification{action:platform::lifecycle::NotificationAction::Mute|platform::lifecycle::NotificationAction::Disconnect,..}|Quit){self.release_held();}
|
||||
if matches!(&event,ScreenLocked(true))&&self.services.lock().expect("runtime services").upgrade().is_some_and(|ctx|ctx.profile().is_ok_and(|profile|profile.prefs.get()["osMuteWhenLocked"]==true)){self.release_held();}
|
||||
if self.enqueue(app::runtime::RuntimeCommand::Platform(event)).is_err(){self.cancel.send_replace(true);}
|
||||
}
|
||||
@@ -117,9 +134,21 @@ impl AppRuntime {
|
||||
pub(crate) fn drain_effects(&self)->Vec<app::runtime::events::UiEffect>{self.pending_wake.store(false,Ordering::Release);let mut effects=self.effects.lock().expect("UI effects");let mut batch=Vec::new();while let Ok(effect)=effects.try_recv(){batch.push(effect)}batch}
|
||||
#[cfg(not(any(target_os="android",target_os="ios")))]
|
||||
pub fn desktop_handle(&self)->Option<platform::desktop::DesktopHandle>{self.desktop.lock().expect("desktop handle").clone()}
|
||||
async fn finished_result(&self)->services::Result<()> {
|
||||
let mut done=self.finished.clone();
|
||||
loop{if let Some(result)=done.borrow_and_update().clone(){return result}done.changed().await.map_err(|_|services::ServiceError::new("worker_stopped","Application worker ended without a shutdown result"))?;}
|
||||
}
|
||||
/// Android's new native Activity thread must join the retired owner before reopening storage.
|
||||
/// No runtime/attachment mutex is held while waiting for the dedicated worker.
|
||||
#[cfg(any(target_os="android",test))]
|
||||
pub(crate) fn join_shutdown(&self)->services::Result<()> {
|
||||
self.request_shutdown();
|
||||
let worker=self.worker.lock().expect("runtime worker").take();
|
||||
if let Some(worker)=worker{worker.join().map_err(|_|services::ServiceError::new("worker_panicked","Application worker panicked"))?;}
|
||||
futures::executor::block_on(self.finished_result())
|
||||
}
|
||||
pub async fn shutdown(&self)->services::Result<()> {
|
||||
self.release_held();self.cancel.send_replace(true);let mut done=self.finished.clone();
|
||||
let result=loop{if let Some(result)=done.borrow_and_update().clone(){break result}done.changed().await.map_err(|_|services::ServiceError::new("worker_stopped","Application worker ended without a shutdown result"))?;};
|
||||
self.request_shutdown();let result=self.finished_result().await;
|
||||
let worker=self.worker.lock().expect("runtime worker").take();
|
||||
if let Some(worker)=worker{tokio::task::spawn_blocking(move||worker.join()).await.map_err(|_|services::ServiceError::new("worker_join","Application worker join failed"))?.map_err(|_|services::ServiceError::new("worker_panicked","Application worker panicked"))?;}result
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Android owns OS capabilities, never a second UI or server model.
|
||||
use std::{collections::HashMap, ffi::c_void, path::PathBuf, sync::{Arc, LazyLock, Mutex, OnceLock, Weak, atomic::{AtomicBool, AtomicU64, Ordering}}};
|
||||
use std::{collections::HashMap, ffi::c_void, path::PathBuf, sync::{Arc, LazyLock, Mutex, OnceLock, atomic::{AtomicBool, AtomicU64, Ordering}}};
|
||||
use jni::{JNIEnv, JavaVM, objects::{GlobalRef, JClass, JObject, JString, JValue}, sys::{jboolean, jfloat, jint, jlong}};
|
||||
use tokio::sync::oneshot;
|
||||
use crate::{AppConfig, AppRuntime, app::connections::SessionKey, services::{Result, ServiceError}};
|
||||
@@ -15,7 +15,8 @@ pub use accessibility::{attach_accessibility, AccessibilityLease};
|
||||
|
||||
struct Binding { vm: JavaVM, application: GlobalRef, class: GlobalRef, files: PathBuf }
|
||||
static BINDING: OnceLock<Binding> = OnceLock::new();
|
||||
static RUNTIME: LazyLock<Mutex<Weak<AppRuntime>>> = LazyLock::new(|| Mutex::new(Weak::new()));
|
||||
// Retain the join owner until a new Activity has retired it, even after its last UI/call lease drops.
|
||||
static RUNTIME: LazyLock<Mutex<Option<Arc<AppRuntime>>>> = LazyLock::new(|| Mutex::new(None));
|
||||
static UI: AtomicU64 = AtomicU64::new(0);
|
||||
static SCREEN_READER: AtomicBool = AtomicBool::new(false);
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
@@ -65,27 +66,22 @@ pub fn run(app: slint::android::AndroidApp) {
|
||||
let smoke = smoke_request(&app)?;
|
||||
#[cfg(feature="test-harness")]
|
||||
let prepared = if let Some(request) = &smoke {
|
||||
if RUNTIME.lock().expect("Android runtime").upgrade().is_some() {
|
||||
if RUNTIME.lock().expect("Android runtime").is_some() {
|
||||
return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into());
|
||||
}
|
||||
Some(crate::smoke::prepare(&request.scenario, request.profile.clone(), request.output.clone())?)
|
||||
} else { None };
|
||||
let runtime = {
|
||||
let mut weak = RUNTIME.lock().expect("Android runtime");
|
||||
if let Some(runtime) = weak.upgrade() {
|
||||
if smoke.is_some() { return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into()); }
|
||||
runtime
|
||||
} else {
|
||||
let config = AppConfig {
|
||||
mobile_container: Some(binding()?.files.clone()),
|
||||
profile_dir: smoke.as_ref().map(|request|request.profile.clone()),
|
||||
allow_os_actions: smoke.is_none(),
|
||||
network_enabled: smoke.is_none(),
|
||||
..AppConfig::default()
|
||||
};
|
||||
let runtime = AppRuntime::start(config)?; *weak = Arc::downgrade(&runtime); runtime
|
||||
}
|
||||
};
|
||||
let previous = RUNTIME.lock().expect("Android runtime").clone();
|
||||
if smoke.is_some() && previous.is_some() { return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into()); }
|
||||
// The process mutex is released before joining the old actor or starting its replacement.
|
||||
let runtime = crate::runtime_attachment::runtime_for_attachment(previous, || Ok(AppConfig {
|
||||
mobile_container: Some(binding()?.files.clone()),
|
||||
profile_dir: smoke.as_ref().map(|request|request.profile.clone()),
|
||||
allow_os_actions: smoke.is_none(),
|
||||
network_enabled: smoke.is_none(),
|
||||
..AppConfig::default()
|
||||
}))?;
|
||||
*RUNTIME.lock().expect("Android runtime") = Some(runtime.clone());
|
||||
i_slint_backend_android_activity::set_clipboard_enabled(smoke.is_none());
|
||||
let generation = runtime.next_ui_generation(); UI.store(generation, Ordering::Release);
|
||||
struct AttachmentGeneration(u64);
|
||||
@@ -186,18 +182,43 @@ pub async fn set_voice_capture(key: &SessionKey, enabled: bool, policy: ActionPo
|
||||
}
|
||||
fn voice_audio_changed(token:u64, focused:Option<bool>, restart_output:bool) {
|
||||
let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token).map(|voice|{
|
||||
voice.microphone=false;voice.capture_revision=0;
|
||||
let revision=match focused{Some(focused)=>voice.audio.interrupt(focused),None if restart_output=>voice.audio.route_changed(),None=>voice.audio.revoke_capture()};
|
||||
let route=focused.is_none()&&restart_output;
|
||||
// Only completed consent can survive endpoint replacement. A route may
|
||||
// cancel a pending activation, but can never acknowledge it on its behalf.
|
||||
if !route||voice.capture_change.is_some(){voice.microphone=false;voice.capture_revision=0;}
|
||||
let revision=match focused{Some(focused)=>voice.audio.interrupt(focused),None if route=>{
|
||||
if !voice.microphone{voice.audio.revoke_capture();}voice.audio.route_changed()
|
||||
},None=>voice.audio.revoke_capture()};
|
||||
(voice.key.clone(),revision,voice.capture_change.take(),voice.audio.restart_output())
|
||||
})};
|
||||
if let Some((key,revision,pending,restart_output))=changed {
|
||||
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone authorization ended; resume explicitly")));}
|
||||
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by an Android audio change")));}
|
||||
lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token,revision,restart_output});
|
||||
}
|
||||
}
|
||||
/// Phone endpoints follow Android's communication route during an active call.
|
||||
/// Explicit external and unknown endpoints keep their exact-ID failure behavior.
|
||||
pub(crate) fn voice_device_selection(raw:&str)->Result<crate::media::audio::devices::DeviceSelection>{
|
||||
use crate::media::audio::devices::DeviceSelection;
|
||||
if raw.is_empty(){return Ok(DeviceSelection::SystemDefault)}
|
||||
if VOICE.lock().expect("Android voice").is_some(){
|
||||
if let Ok(id)=raw.parse::<cpal::DeviceId>(){
|
||||
if id.host()==cpal::HostId::AAudio {
|
||||
if let Ok(endpoint)=id.id().parse::<i32>(){
|
||||
let builtin=with_env(|env,class|java(env.call_static_method(class,"voiceDeviceIsBuiltin","(I)Z",&[JValue::Int(endpoint)]))?.z().map_err(|_|error("android_os_error","Invalid audio endpoint metadata")))?;
|
||||
if builtin{return Ok(DeviceSelection::SystemDefault)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(DeviceSelection::Exact(raw.into()))
|
||||
}
|
||||
pub(crate) fn voice_audio_allowed(key:&SessionKey,microphone:bool)->bool {
|
||||
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.audio.allows(microphone))
|
||||
}
|
||||
pub(crate) fn voice_capture_retained(key:&SessionKey)->bool {
|
||||
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.audio.retains_capture())
|
||||
}
|
||||
pub(crate) fn voice_audio_current(key:&SessionKey,token:u64,revision:u64)->bool {
|
||||
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision))
|
||||
}
|
||||
@@ -350,7 +371,11 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeEvent(_en
|
||||
0 if generation!=0 && UI.load(Ordering::Acquire)==generation=>PlatformEvent::Visibility{ui_generation:generation,visible:value},
|
||||
8 if generation!=0&&UI.load(Ordering::Acquire)==generation=>PlatformEvent::Focus{ui_generation:generation,focused:value},
|
||||
1=>{destroy_ui(generation);return;}, 2=>PlatformEvent::AudioInterruption{began:value,should_resume:!value},
|
||||
7 if generation!=0&&UI.load(Ordering::Acquire)==generation=>{if let Some(runtime)=RUNTIME.lock().expect("Android runtime").upgrade(){runtime.request_shutdown();}return;},
|
||||
7 if generation!=0&&UI.load(Ordering::Acquire)==generation=>{
|
||||
let runtime=RUNTIME.lock().expect("Android runtime").clone();
|
||||
if let Some(runtime)=runtime{crate::runtime_attachment::request_shutdown_for_ui(&runtime,generation);}
|
||||
return;
|
||||
},
|
||||
3=>PlatformEvent::AudioRouteChanged,4=>PlatformEvent::NetworkChanged,5=>PlatformEvent::ScreenLocked(value),6=>PlatformEvent::MemoryPressure,_=>return,
|
||||
}; lifecycle::emit(event);
|
||||
}
|
||||
@@ -380,7 +405,25 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStar
|
||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStopped(_env:JNIEnv,_class:JClass,token:jlong)->jboolean{end_voice(token as u64) as u8}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEvent(_env:JNIEnv,_class:JClass,token:jlong,event:jint,value:jboolean){
|
||||
match event{2=>voice_audio_changed(token as u64,Some(value==0),true),3=>voice_audio_changed(token as u64,None,true),7=>{end_voice_with_shutdown(token as u64,true);},_=>{}}
|
||||
match event{
|
||||
2=>voice_audio_changed(token as u64,Some(value==0),true),
|
||||
3=>voice_audio_changed(token as u64,None,true),
|
||||
// Fence before AudioManager changes hardware. Recovery is emitted only
|
||||
// after the communication-device/SCO acknowledgement (or bounded failure).
|
||||
8=>{
|
||||
let owner={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token as u64).map(|voice|{
|
||||
let pending=voice.capture_change.take();
|
||||
if pending.is_some(){voice.microphone=false;voice.capture_revision=0;voice.audio.revoke_capture();}
|
||||
let authorized=voice.audio.retains_capture();voice.audio.begin_route();
|
||||
(voice._runtime.clone(),voice.key.clone(),authorized,pending)
|
||||
})};
|
||||
if let Some((runtime,key,authorized,pending))=owner{
|
||||
runtime.fence_android_audio_route(&key,authorized);
|
||||
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by a route change")));}
|
||||
}
|
||||
},
|
||||
7=>{end_voice_with_shutdown(token as u64,true);},_=>{}
|
||||
}
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureValid(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
//! Android call authorization; focus/route changes never restore microphone consent.
|
||||
//! Android call authorization; route replacement retains consent, interruptions revoke it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct CallAudioState {
|
||||
revision: u64,
|
||||
focused: bool,
|
||||
capture: bool,
|
||||
restart_output: bool,
|
||||
route_pending: bool,
|
||||
}
|
||||
impl CallAudioState {
|
||||
pub fn start(&mut self, capture: bool) { self.focused = true; self.capture = capture; }
|
||||
pub fn start(&mut self, capture: bool) { self.focused = true; self.capture = capture; self.route_pending = false; }
|
||||
pub fn change_capture(&mut self, enabled: bool) -> bool {
|
||||
if enabled && !self.focused { return false; }
|
||||
if enabled && (!self.focused || self.route_pending) { return false; }
|
||||
self.capture = enabled;
|
||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||
true
|
||||
@@ -24,9 +25,19 @@ impl CallAudioState {
|
||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||
self.revision
|
||||
}
|
||||
pub fn route_changed(&mut self) -> u64 {
|
||||
pub fn begin_route(&mut self) -> u64 {
|
||||
self.route_pending = true;
|
||||
self.restart_output = true;
|
||||
self.revoke_capture()
|
||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||
self.revision
|
||||
}
|
||||
pub fn route_changed(&mut self) -> u64 {
|
||||
self.route_pending = false;
|
||||
self.restart_output = true;
|
||||
// A replacement endpoint is not a new microphone activation. Focus loss,
|
||||
// permission denial and explicit mute still call revoke_capture instead.
|
||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||
self.revision
|
||||
}
|
||||
pub fn restart_output(&self) -> bool { self.restart_output }
|
||||
pub fn acknowledge_output(&mut self, revision: u64, active: bool) {
|
||||
@@ -34,7 +45,8 @@ impl CallAudioState {
|
||||
// capture or receiving an early route callback is not a playback ack.
|
||||
if self.is_current(revision) && (!self.focused || active) { self.restart_output = false; }
|
||||
}
|
||||
pub fn allows(&self, microphone: bool) -> bool { self.focused && (!microphone || self.capture) }
|
||||
pub fn retains_capture(&self) -> bool { self.focused && self.capture }
|
||||
pub fn allows(&self, microphone: bool) -> bool { !self.route_pending && self.focused && (!microphone || self.capture) }
|
||||
pub fn is_current(&self, revision: u64) -> bool { self.revision == revision }
|
||||
}
|
||||
|
||||
@@ -59,7 +71,7 @@ mod tests {
|
||||
assert!(!state.is_current(gained), "queued recovery must not mute a newer explicit activation");
|
||||
}
|
||||
#[test]
|
||||
fn route_or_permission_revocation_keeps_receive_only() {
|
||||
fn permission_revocation_keeps_receive_only() {
|
||||
let mut state = CallAudioState::default();
|
||||
state.start(true);
|
||||
let route = state.revoke_capture();
|
||||
@@ -103,4 +115,23 @@ mod tests {
|
||||
state.acknowledge_output(lost, false);
|
||||
assert!(!state.restart_output(), "a focus loss is acknowledged by stopping output");
|
||||
}
|
||||
#[test]
|
||||
fn acknowledged_route_reversal_preserves_only_completed_consent() {
|
||||
let mut state=CallAudioState::default();state.start(true);
|
||||
let plugging=state.begin_route();
|
||||
assert!(state.retains_capture());assert!(!state.allows(true));assert!(!state.allows(false));
|
||||
assert!(!state.change_capture(true),"a pending route is not an activation acknowledgement");
|
||||
let plugged=state.route_changed();assert!(!state.is_current(plugging));assert!(state.allows(true));
|
||||
let unplugging=state.begin_route();assert!(!state.is_current(plugged));assert!(!state.allows(true));
|
||||
let unplugged=state.route_changed();assert!(!state.is_current(unplugging));assert!(state.is_current(unplugged));assert!(state.allows(true));
|
||||
}
|
||||
#[test]
|
||||
fn newer_privacy_or_focus_loss_wins_pending_route() {
|
||||
for focus_loss in [false,true]{
|
||||
let mut state=CallAudioState::default();state.start(true);let pending=state.begin_route();
|
||||
if focus_loss{state.interrupt(false);}else{state.revoke_capture();}
|
||||
state.route_changed();assert!(!state.is_current(pending));assert!(!state.retains_capture());assert!(!state.allows(true));
|
||||
}
|
||||
let mut state=CallAudioState::default();state.start(false);state.begin_route();state.route_changed();assert!(!state.allows(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Select Android's process service owner before creating an Activity-bound Slint backend.
|
||||
use std::sync::Arc;
|
||||
use crate::{AppConfig, AppError, AppRuntime};
|
||||
|
||||
/// The caller clones the process lease and releases its mutex before entering here.
|
||||
/// A terminal owner's immutable snapshot may still look connected; never use it as lifecycle truth.
|
||||
pub(crate) fn runtime_for_attachment(previous: Option<Arc<AppRuntime>>, config: impl FnOnce() -> Result<AppConfig, AppError>) -> Result<Arc<AppRuntime>, AppError> {
|
||||
if let Some(runtime) = previous {
|
||||
if runtime.accepts_ui_attachment() { return Ok(runtime); }
|
||||
// Join even when asynchronous callbacks still retain this Arc. This releases the original
|
||||
// profile/core/audio workers before the new owner opens the same persistent profile.
|
||||
if let Err(error) = runtime.join_shutdown() { eprintln!("Android retired runtime: {error}"); }
|
||||
}
|
||||
AppRuntime::start(config()?)
|
||||
}
|
||||
|
||||
/// Revalidate against the captured owner after reading the process slot: a stale Activity must not
|
||||
/// shut down a replacement whose generation was published between the JNI callback's checks.
|
||||
pub(crate) fn request_shutdown_for_ui(runtime: &AppRuntime, generation: u64) -> bool {
|
||||
if !runtime.is_ui_current(generation) { return false; }
|
||||
runtime.request_shutdown();
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
use crate::{app::{connections::ConnectionState, runtime::model::{BootstrapState, Snapshot}}, ui::shell::{FieldValue, Operation, ShellAction, Target, Values}};
|
||||
|
||||
async fn snapshot_when(runtime: &AppRuntime, predicate: impl Fn(&Snapshot) -> bool) -> Arc<Snapshot> {
|
||||
let mut snapshots = runtime.subscribe();
|
||||
tokio::time::timeout(Duration::from_secs(20), async {
|
||||
loop {
|
||||
let snapshot = snapshots.borrow_and_update().clone();
|
||||
if predicate(&snapshot) { return snapshot; }
|
||||
snapshots.changed().await.expect("real runtime snapshot publisher stopped");
|
||||
}
|
||||
}).await.expect("real runtime did not publish its expected state")
|
||||
}
|
||||
|
||||
async fn fixture() -> (tempfile::TempDir, AppConfig, Arc<AppRuntime>) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("native");
|
||||
crate::services::profile_import::initialize_native_root(&root).unwrap();
|
||||
let config = AppConfig::isolated(root);
|
||||
let runtime = AppRuntime::start(config.clone()).unwrap();
|
||||
snapshot_when(&runtime, |snapshot| snapshot.bootstrap == BootstrapState::Username).await;
|
||||
runtime.dispatch_shell(ShellAction::Submit {
|
||||
editor_id: "attachment-profile".into(),
|
||||
target: Target::application(),
|
||||
operation: Operation::CreateProfile,
|
||||
values: Values::from([
|
||||
("nickname".into(), FieldValue::Text("Attachment test".into())),
|
||||
("theme".into(), FieldValue::Choice("light".into())),
|
||||
]),
|
||||
confirmation: String::new(),
|
||||
}).unwrap();
|
||||
snapshot_when(&runtime, |snapshot| snapshot.bootstrap == BootstrapState::Ready && snapshot.settings.loaded).await;
|
||||
(directory, config, runtime)
|
||||
}
|
||||
|
||||
async fn stop(runtime: &AppRuntime) {
|
||||
tokio::time::timeout(Duration::from_secs(20), runtime.shutdown()).await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
async fn attach(previous: Arc<AppRuntime>, config: AppConfig) -> Arc<AppRuntime> {
|
||||
tokio::time::timeout(Duration::from_secs(20), tokio::task::spawn_blocking(move || runtime_for_attachment(Some(previous), || Ok(config))))
|
||||
.await.expect("retired worker did not join").unwrap().unwrap()
|
||||
}
|
||||
|
||||
fn assert_disconnected(snapshot: &Snapshot) {
|
||||
assert_eq!(snapshot.connections.connections.len(), 1);
|
||||
assert!(snapshot.connections.connections.iter().all(|connection| connection.state == ConnectionState::Disconnected && connection.server.is_none()));
|
||||
assert!(snapshot.connections.connections.iter().all(|connection| !connection.input_enabled));
|
||||
assert!(snapshot.connections.capture.is_none());
|
||||
assert!(snapshot.voice.is_none());
|
||||
assert!(!snapshot.audio_input_active && !snapshot.audio_output_active);
|
||||
assert!(snapshot.tree.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn android_attachment_reuses_live_actor_across_home_and_activity_recreation() {
|
||||
let (_directory, _config, runtime) = fixture().await;
|
||||
let old_generation = runtime.next_ui_generation();
|
||||
runtime.platform_event(crate::platform::lifecycle::PlatformEvent::Visibility { ui_generation: old_generation, visible: false });
|
||||
runtime.release_ui(old_generation);
|
||||
assert!(runtime.accepts_ui_attachment());
|
||||
let reused = runtime_for_attachment(Some(runtime.clone()), || panic!("live Activity recreation must not rebuild runtime configuration")).unwrap();
|
||||
assert!(runtime.worker.lock().unwrap().is_some(), "nonterminal UI loss must not join the live worker");
|
||||
let new_generation = reused.next_ui_generation();
|
||||
assert_ne!(old_generation, new_generation);
|
||||
runtime.release_ui(old_generation);
|
||||
assert!(reused.is_ui_current(new_generation));
|
||||
assert!(!request_shutdown_for_ui(&reused, old_generation));
|
||||
assert!(reused.accepts_ui_attachment());
|
||||
stop(&reused).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn android_attachment_joins_terminal_actor_with_retained_arc_before_same_profile_restart() {
|
||||
let (_directory, config, runtime) = fixture().await;
|
||||
let uid = runtime.services.lock().unwrap().upgrade().unwrap().profile().unwrap().identities.list().unwrap().default_id;
|
||||
let old_generation = runtime.next_ui_generation();
|
||||
assert!(request_shutdown_for_ui(&runtime, old_generation));
|
||||
assert!(!runtime.accepts_ui_attachment(), "shutdown is terminal before its worker finishes");
|
||||
// The old Arc deliberately remains alive, just like a delayed OS/async callback.
|
||||
let fresh = attach(runtime.clone(), config.clone()).await;
|
||||
assert!(!Arc::ptr_eq(&runtime, &fresh));
|
||||
assert!(runtime.worker.lock().unwrap().is_none(), "the old worker must be joined, not just cancelled");
|
||||
assert!(runtime.finished.borrow().is_some());
|
||||
let snapshot = snapshot_when(&fresh, |snapshot| snapshot.bootstrap == BootstrapState::Ready && snapshot.settings.loaded).await;
|
||||
assert_disconnected(&snapshot);
|
||||
assert_eq!(snapshot.root.as_ref(), config.profile_dir.as_ref());
|
||||
assert_eq!(snapshot.settings.prefs["theme"], "light");
|
||||
let generation = fresh.next_ui_generation();
|
||||
assert!(!request_shutdown_for_ui(&fresh, old_generation));
|
||||
runtime.release_ui(old_generation);
|
||||
assert!(fresh.is_ui_current(generation));
|
||||
assert!(fresh.accepts_ui_attachment());
|
||||
stop(&fresh).await;
|
||||
let saved = crate::services::profile::ProfileServices::open(config.profile_dir.as_ref().unwrap()).unwrap();
|
||||
assert_eq!(saved.identities.list().unwrap().default_id, uid);
|
||||
assert_eq!(saved.identities.list().unwrap().identities.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn android_attachment_restarts_worker_that_finished_without_shutdown_request() {
|
||||
let (_directory, config, runtime) = fixture().await;
|
||||
stop(&runtime).await;
|
||||
let mut failing = config.clone();
|
||||
failing.build_version = "invalid-version";
|
||||
let failed = AppRuntime::start(failing).unwrap();
|
||||
let error = tokio::time::timeout(Duration::from_secs(20), failed.finished_result()).await.unwrap().unwrap_err();
|
||||
assert_eq!(error.code, "services_initialization_failed");
|
||||
assert!(!*failed.cancel.borrow(), "this must exercise worker completion, not a fabricated shutdown flag");
|
||||
assert_eq!(failed.snapshot().bootstrap, BootstrapState::Failed);
|
||||
assert!(!failed.accepts_ui_attachment());
|
||||
let fresh = attach(failed.clone(), config).await;
|
||||
assert!(!Arc::ptr_eq(&failed, &fresh));
|
||||
assert!(failed.worker.lock().unwrap().is_none());
|
||||
let snapshot = snapshot_when(&fresh, |snapshot| snapshot.bootstrap == BootstrapState::Ready && snapshot.settings.loaded).await;
|
||||
assert_disconnected(&snapshot);
|
||||
stop(&fresh).await;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user