Keep participant details bound to the selected session and UID

This commit is contained in:
omar committed 2026-11-27 14:45:58 +03:00
1 parent 0b4a707637
commit 89a2b21746
13 files changed
+443 -94

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
## Unreleased ## Unreleased
- Participant Info retains previously returned fields when a later update omits them. Superseded replies and errors cannot populate the next tab or a new participant reusing the same client number.
- The participant menu offers Grant or Revoke according to the current talker flag. Manual grants no longer require a pending request. Queue grants still require the selected request in the moderator's current channel. - The participant menu offers Grant or Revoke according to the current talker flag. Manual grants no longer require a pending request. Queue grants still require the selected request in the moderator's current channel.
- Reject explicitly null away and talk-request messages. Omitting a message remains valid. - Reject explicitly null away and talk-request messages. Omitting a message remains valid.
+2
View File
@@ -2,6 +2,8 @@
## Current Windows account-free checkpoint (2026-11-26) ## Current Windows account-free checkpoint (2026-11-26)
**Participant Info on Windows:** On private beta14, two muted guests opened the rendered participant Info menus. The test compared displayed properties with targeted core reads, required nonempty version and platform for self, checked the peer result against the server's actual permission response, and verified tab-switch cleanup. A separate reconnect scenario checked the same tab with a new identity. Matching rows merge the last explicitly supplied value for each field; an empty field can clear it. An acknowledgement without a matching row fails. Ten native and two core tests passed. Physical devices were not used.
**Talk power on Windows:** On private beta14 the moderator granted and revoked talk power from a participant's Slint menu without a pending request. Both guests observed the new talker flag. A queue grant succeeded for a pending request, a withdrawn request was rejected locally, and an ordinary guest's manual grant was refused by the server without changing either roster. Four native checks and a stdio validation test passed. Queue identity checks occur before dispatch; the server remains authoritative. Both guests were muted. **Talk power on Windows:** On private beta14 the moderator granted and revoked talk power from a participant's Slint menu without a pending request. Both guests observed the new talker flag. A queue grant succeeded for a pending request, a withdrawn request was rejected locally, and an ordinary guest's manual grant was refused by the server without changing either roster. Four native checks and a stdio validation test passed. Queue identity checks occur before dispatch; the server remains authoritative. Both guests were muted.
**Away status and talk requests:** Two muted beta14 clients observed the submitted away message and return to online. Cancelling the Slint form left both rosters unchanged; reconnecting one recipient before submission prevented the old prompt from changing its replacement. In a temporary moderated channel, both clients observed talk requests with and without a message, grant and revocation, then withdrawal. The core stdio test verified Unicode length limits, rejected null and forbidden controls, and distinguished malformed requests from valid offline commands. No physical voice equipment was used. **Away status and talk requests:** Two muted beta14 clients observed the submitted away message and return to online. Cancelling the Slint form left both rosters unchanged; reconnecting one recipient before submission prevented the old prompt from changing its replacement. In a temporary moderated channel, both clients observed talk requests with and without a message, grant and revocation, then withdrawal. The core stdio test verified Unicode length limits, rejected null and forbidden controls, and distinguished malformed requests from valid offline commands. No physical voice equipment was used.
+6 -1
View File
@@ -705,7 +705,9 @@ impl ClientInfoReply {
pub(crate) fn finish(self, current_uid: Option<&str>) -> Result<Value, ErrorObj> { pub(crate) fn finish(self, current_uid: Option<&str>) -> Result<Value, ErrorObj> {
if current_uid != Some(self.uid.as_str()) { return Err(Self::target_changed()); } if current_uid != Some(self.uid.as_str()) { return Err(Self::target_changed()); }
Ok(json!({"rows": self.rows?})) let rows = self.rows?;
if rows.is_empty() { return Err(ErrorObj::new(ErrorCode::ServerError,"The server returned no information for the requested client")); }
Ok(json!({"rows": rows}))
} }
} }
@@ -1060,6 +1062,9 @@ mod tests {
#[test] #[test]
fn client_info_checks_identity_at_ack_even_when_updates_omit_uid() { fn client_info_checks_identity_at_ack_even_when_updates_omit_uid() {
let mut missing = ClientInfoReply::new(7, "original=".into());
missing.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other").unwrap());
assert_eq!(missing.finish(Some("original=")).unwrap_err().code, ErrorCode::ServerError);
let collect = |extra: Option<&[u8]>| { let collect = |extra: Option<&[u8]>| {
let mut r = Reply::ClientInfo(ClientInfoReply::new(7, "original=".into())); let mut r = Reply::ClientInfo(ClientInfoReply::new(7, "original=".into()));
r.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other|clid=7 client_version=test|client_platform=unscoped").unwrap()); r.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other|clid=7 client_version=test|client_platform=unscoped").unwrap());
+10
View File
@@ -355,6 +355,16 @@ fn status_messages_are_optional_but_must_be_valid_when_present() {
core.shutdown(); core.shutdown();
} }
#[test]
fn client_info_requires_explicit_client_identity() {
let dir = TempDir::new("client-info-args"); let mut core = Core::start(&dir.0);
for args in [json!({"client_id":0,"uid":"peer="}),json!({"client_id":65536,"uid":"peer="}),json!({"client_id":7}),json!({"client_id":7,"uid":""}),json!({"client_id":7,"uid":"peer=","unknown":true})] {
let (reply,_) = core.request("invalid-info","client_info",args); assert_eq!(reply["error"]["code"],"bad_request","{reply}");
}
let (reply,_) = core.request("offline-info","client_info",json!({"client_id":7,"uid":"peer="}));
assert_eq!(reply["error"]["code"],"not_connected","{reply}"); core.shutdown();
}
#[test] #[test]
fn channel_queries_validate_arguments_before_connection_lookup() { fn channel_queries_validate_arguments_before_connection_lookup() {
let dir = TempDir::new("channel-query-args"); let dir = TempDir::new("channel-query-args");
+2
View File
@@ -4,6 +4,8 @@
## Возврат к разработке на ПК, 2026-11-26 ## Возврат к разработке на ПК, 2026-11-26
Windows, база `0b4a707`: закрыт `command:client_info`. Карточка Slint привязана к запросу, вкладке, номеру клиента и UID; частичные ответы не стирают ранее полученные поля. Прошли десять нативных проверок, включая два сценария на beta14, и два теста ядра. Стенд остановлен.
Windows, база `c80219b`: закрыты `command:talk_power` и `feature:client.away_talkpower`. На beta14 проверены ручная выдача и отзыв без заявки, выдача из очереди, устаревшая заявка и отказ обычному гостю. После интервала между сценариями четыре нативных теста прошли; отдельно прошла проверка stdio. Физический звук не использовался, ограничения сервера не менялись; стенд остановлен. Windows, база `c80219b`: закрыты `command:talk_power` и `feature:client.away_talkpower`. На beta14 проверены ручная выдача и отзыв без заявки, выдача из очереди, устаревшая заявка и отказ обычному гостю. После интервала между сценариями четыре нативных теста прошли; отдельно прошла проверка stdio. Физический звук не использовался, ограничения сервера не менялись; стенд остановлен.
Windows, база `380e9d4`: проверены `command:set_away` и `command:talk_request`. На beta14 обе вкладки увидели изменения статуса и запрос права голоса, включая его отзыв. Явный null и неверные сообщения отклоняются до подключения; прошли тест stdio и тест протокольных команд. Физический звук не использовался; стенд остановлен. Windows, база `380e9d4`: проверены `command:set_away` и `command:talk_request`. На beta14 обе вкладки увидели изменения статуса и запрос права голоса, включая его отзыв. Явный null и неверные сообщения отклоняются до подключения; прошли тест stdio и тест протокольных команд. Физический звук не использовался; стенд остановлен.
+1 -1
View File
@@ -45,7 +45,7 @@ pub enum UiEffect {
} }
pub enum ServiceEvent { pub enum ServiceEvent {
Changed, Prompt(Prompt), Effect(UiEffect), Workflow(Result<WorkflowResult>), Changed, Prompt(Prompt), Effect(UiEffect), Workflow(Result<WorkflowResult>),
ChannelInfoComplete { serial: u64, ui_generation: u64, target: Target, result: Result<Detail> }, ScopedDetailComplete { serial: u64, ui_generation: u64, target: Target, operation: crate::ui::shell::Operation, result: Result<Detail> },
RecordingChanged(crate::app::connections::SessionKey), RecordingChanged(crate::app::connections::SessionKey),
SnapshotStarted { serial: u64, cancel: std::sync::Weak<crate::services::server_icons::OperationCancellation> }, SnapshotStarted { serial: u64, cancel: std::sync::Weak<crate::services::server_icons::OperationCancellation> },
SnapshotUpdated { serial: u64, update: SnapshotUpdate }, SnapshotUpdated { serial: u64, update: SnapshotUpdate },
+23 -20
View File
@@ -27,7 +27,7 @@ use crate::app::connections::SessionKey;
use context::RuntimeServices; use context::RuntimeServices;
use events::{UiEffect,ServiceEvent,Prompt,SnapshotUpdate}; use events::{UiEffect,ServiceEvent,Prompt,SnapshotUpdate};
use model::{AppState,BootstrapState}; use model::{AppState,BootstrapState};
pub enum RuntimeCommand {Shell(ShellAction),SnapshotShell{action:ShellAction,ui_generation:u64},DiscoverChannelStreams{key:SessionKey,visit:u64,ui_generation:u64},Settings(crate::ui::settings::SettingsAction),IdentitySettings{generation:u64,action:crate::ui::settings::SettingsAction},Chat(crate::ui::chat::ChatAction),Platform(crate::platform::lifecycle::PlatformEvent),Detached(u64),WhisperStop(crate::services::whisper::RoutedCommand),Pip{target:Target,rect:[f64;4]}} pub enum RuntimeCommand {Shell(ShellAction),AttachmentShell{action:ShellAction,ui_generation:u64},DiscoverChannelStreams{key:SessionKey,visit:u64,ui_generation:u64},Settings(crate::ui::settings::SettingsAction),IdentitySettings{generation:u64,action:crate::ui::settings::SettingsAction},Chat(crate::ui::chat::ChatAction),Platform(crate::platform::lifecycle::PlatformEvent),Detached(u64),WhisperStop(crate::services::whisper::RoutedCommand),Pip{target:Target,rect:[f64;4]}}
pub fn start(config:AppConfig)->std::result::Result<Arc<AppRuntime>,AppError>{ pub fn start(config:AppConfig)->std::result::Result<Arc<AppRuntime>,AppError>{
let executor=tokio::runtime::Builder::new_current_thread().enable_all().build()?; let executor=tokio::runtime::Builder::new_current_thread().enable_all().build()?;
let(commands,incoming)=mpsc::channel(256);let(cancel,cancelled)=watch::channel(false); let(commands,incoming)=mpsc::channel(256);let(cancel,cancelled)=watch::channel(false);
@@ -144,8 +144,8 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
tokio::select! { tokio::select! {
_=cancelled.changed()=>{if *cancelled.borrow(){break}}, _=cancelled.changed()=>{if *cancelled.borrow(){break}},
command=commands.recv()=>{let Some(command)=command else{break}; command=commands.recv()=>{let Some(command)=command else{break};
let (command,snapshot_ui)=match command{ let (command,attachment_ui)=match command{
RuntimeCommand::SnapshotShell{action,ui_generation}=>{ RuntimeCommand::AttachmentShell{action,ui_generation}=>{
if !runtime.upgrade().is_some_and(|app|app.is_ui_current(ui_generation)){continue} if !runtime.upgrade().is_some_and(|app|app.is_ui_current(ui_generation)){continue}
(RuntimeCommand::Shell(action),Some(ui_generation)) (RuntimeCommand::Shell(action),Some(ui_generation))
}, },
@@ -162,7 +162,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
let cancel_snapshot=matches!(&command,RuntimeCommand::Shell(ShellAction::Invoke{target,operation:Operation::SnapshotCancel}) if matches!(target.entity,Entity::SnapshotJob(_))); let cancel_snapshot=matches!(&command,RuntimeCommand::Shell(ShellAction::Invoke{target,operation:Operation::SnapshotCancel}) if matches!(target.entity,Entity::SnapshotJob(_)));
if jobs.len()>=64&&!cancel_snapshot&&matches!(&command,RuntimeCommand::Settings(_)|RuntimeCommand::Chat(_)|RuntimeCommand::Shell(ShellAction::Invoke{..})){state.snapshot.error="Too many pending application actions; complete or cancel the current dialog first".into();dirty=true;continue} if jobs.len()>=64&&!cancel_snapshot&&matches!(&command,RuntimeCommand::Settings(_)|RuntimeCommand::Chat(_)|RuntimeCommand::Shell(ShellAction::Invoke{..})){state.snapshot.error="Too many pending application actions; complete or cancel the current dialog first".into();dirty=true;continue}
match command { match command {
RuntimeCommand::SnapshotShell{..}=>unreachable!("attachment command already unwrapped"), RuntimeCommand::AttachmentShell{..}=>unreachable!("attachment command already unwrapped"),
RuntimeCommand::Shell(ShellAction::Cancel{editor_id,target})=>{ RuntimeCommand::Shell(ShellAction::Cancel{editor_id,target})=>{
if prompts.front().is_some_and(|dialog|dialog.form().id==editor_id&&(matches!(dialog,Dialog::Prompt(_))||dialog.form().target==target)){ if prompts.front().is_some_and(|dialog|dialog.form().id==editor_id&&(matches!(dialog,Dialog::Prompt(_))||dialog.form().target==target)){
if let Some(Dialog::Prompt(prompt))=prompts.pop_front(){let _=prompt.answer.send(Err(ServiceError::new("cancelled","Dialog cancelled")));} if let Some(Dialog::Prompt(prompt))=prompts.pop_front(){let _=prompt.answer.send(Err(ServiceError::new("cancelled","Dialog cancelled")));}
@@ -197,7 +197,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
if snapshot_operation(operation){ if snapshot_operation(operation){
let Some(owner)=&owner else{continue}; let Some(owner)=&owner else{continue};
let ctx=&owner.ctx; let ctx=&owner.ctx;
let Some(ui_generation)=snapshot_ui.or_else(||ctx.current_ui_generation().ok()) else{continue}; let Some(ui_generation)=attachment_ui.or_else(||ctx.current_ui_generation().ok()) else{continue};
if operation==Operation::SnapshotApply&&!snapshot_apply_current(&state,ctx,&target){continue} if operation==Operation::SnapshotApply&&!snapshot_apply_current(&state,ctx,&target){continue}
let connections=ctx.connected.connections.snapshot(); let connections=ctx.connected.connections.snapshot();
if state.snapshot_requested_for(&target,&connections,ui_generation){continue} if state.snapshot_requested_for(&target,&connections,ui_generation){continue}
@@ -234,7 +234,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
if let Some(owner)=&owner{let ctx=owner.ctx.clone();match action { if let Some(owner)=&owner{let ctx=owner.ctx.clone();match action {
ShellAction::Navigate(destination)=>{close_recording_panel(&ctx,&mut state).await;state.apply(&UiEffect::Navigate(destination));dirty=true;}, ShellAction::Navigate(destination)=>{close_recording_panel(&ctx,&mut state).await;state.apply(&UiEffect::Navigate(destination));dirty=true;},
ShellAction::Back=>{close_recording_panel(&ctx,&mut state).await;state.back();dirty=true;}, ShellAction::Back=>{close_recording_panel(&ctx,&mut state).await;state.back();dirty=true;},
ShellAction::LeaveRecordingDetail=>{state.cancel_channel_info();state.leave_snapshot();close_recording_panel(&ctx,&mut state).await;dirty=true;}, ShellAction::LeaveRecordingDetail=>{state.cancel_scoped_detail();state.leave_snapshot();close_recording_panel(&ctx,&mut state).await;dirty=true;},
ShellAction::Select(target)=>{ ShellAction::Select(target)=>{
let result=match (&target.session,&target.entity){ let result=match (&target.session,&target.entity){
(Some(key),Entity::Connection)=>ctx.connected.connections.view(key).await.map_err(context::connection_error), (Some(key),Entity::Connection)=>ctx.connected.connections.view(key).await.map_err(context::connection_error),
@@ -269,7 +269,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
ShellAction::Invoke{target,operation:Operation::RecordingOpen}=>{ ShellAction::Invoke{target,operation:Operation::RecordingOpen}=>{
match file_actions::begin_recording_view(&ctx,target).await { match file_actions::begin_recording_view(&ctx,target).await {
Ok(view)=>{ Ok(view)=>{
state.cancel_channel_info(); state.cancel_scoped_detail();
state.leave_snapshot(); state.leave_snapshot();
let sender=events.clone(); let sender=events.clone();
jobs.spawn(async move { jobs.spawn(async move {
@@ -303,22 +303,23 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
}); });
} }
}, },
ShellAction::Invoke{target,operation:Operation::ChannelInfo}=>{ ShellAction::Invoke{target,operation} if scoped_detail_query(operation)=>{
let Ok(ui_generation)=ctx.current_ui_generation() else{continue}; let Some(ui_generation)=attachment_ui.or_else(||ctx.current_ui_generation().ok()) else{continue};
state.leave_snapshot(); state.leave_snapshot();
dirty=true; dirty=true;
let serial=state.begin_channel_info(); let serial=state.begin_scoped_detail();
let sender=events.clone(); let sender=events.clone();
jobs.spawn(async move { jobs.spawn(async move {
let result=async { let result=async {
ctx.require_ui_generation(ui_generation)?;
ctx.require_target(&target)?; ctx.require_target(&target)?;
query_detail(&ctx,&target,Operation::ChannelInfo,&Default::default()).await query_detail(&ctx,&target,operation,&Default::default()).await
}.await; }.await;
let _=sender.send(ServiceEvent::ChannelInfoComplete{serial,ui_generation,target,result}).await; let _=sender.send(ServiceEvent::ScopedDetailComplete{serial,ui_generation,target,operation,result}).await;
}); });
}, },
ShellAction::Invoke{target,operation} if snapshot_operation(operation)=>{ ShellAction::Invoke{target,operation} if snapshot_operation(operation)=>{
let Some(ui_generation)=snapshot_ui.or_else(||ctx.current_ui_generation().ok()) else{continue}; let Some(ui_generation)=attachment_ui.or_else(||ctx.current_ui_generation().ok()) else{continue};
let connections=ctx.connected.connections.snapshot(); let connections=ctx.connected.connections.snapshot();
if state.snapshot_requested_for(&target,&connections,ui_generation){continue} if state.snapshot_requested_for(&target,&connections,ui_generation){continue}
let serial=state.begin_snapshot(target.clone(),operation,ui_generation,&connections); let serial=state.begin_snapshot(target.clone(),operation,ui_generation,&connections);
@@ -344,14 +345,14 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
Operation::FileBrowse|Operation::FileRefresh|Operation::TransferList|Operation::ServerIcons Operation::FileBrowse|Operation::FileRefresh|Operation::TransferList|Operation::ServerIcons
|Operation::WhisperHistory|Operation::StreamStats |Operation::WhisperHistory|Operation::StreamStats
|Operation::CaptureChoose|Operation::ServerChat|Operation::ClientPrivateChat|Operation::ContactChat |Operation::CaptureChoose|Operation::ServerChat|Operation::ClientPrivateChat|Operation::ContactChat
){state.cancel_channel_info();state.leave_snapshot();dirty=true;} ){state.cancel_scoped_detail();state.leave_snapshot();dirty=true;}
if operation==Operation::SnapshotChoose{state.cancel_channel_info();state.supersede_snapshot();dirty=true;} if operation==Operation::SnapshotChoose{state.cancel_scoped_detail();state.supersede_snapshot();dirty=true;}
if !matches!(operation,Operation::RecordingStart|Operation::RecordingPause|Operation::RecordingResume|Operation::RecordingStop|Operation::RecordingChooseFolder|Operation::RecordingReveal){state.detail_operation=Some(operation);} if !matches!(operation,Operation::RecordingStart|Operation::RecordingPause|Operation::RecordingResume|Operation::RecordingStop|Operation::RecordingChooseFolder|Operation::RecordingReveal){state.detail_operation=Some(operation);}
spawn_workflow(&mut jobs,events.clone(),ctx,target,operation,Values::new()); spawn_workflow(&mut jobs,events.clone(),ctx,target,operation,Values::new());
}, },
ShellAction::PushToTalk{target,held}=>{let sender=events.clone();jobs.spawn(async move{let result=controller::ptt(ctx,target,held).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});}, ShellAction::PushToTalk{target,held}=>{let sender=events.clone();jobs.spawn(async move{let result=controller::ptt(ctx,target,held).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});},
ShellAction::Search{target,query}=>{state.query.search=query;state.query.offset=0;if let Some(operation)=state.detail_operation.filter(|op|*op!=Operation::ChannelInfo){state.cancel_channel_info();spawn_query(&mut jobs,events.clone(),ctx,target,operation,state.query.clone());}}, ShellAction::Search{target,query}=>{state.query.search=query;state.query.offset=0;if let Some(operation)=state.detail_operation.filter(|op|!scoped_detail_query(*op)){state.cancel_scoped_detail();spawn_query(&mut jobs,events.clone(),ctx,target,operation,state.query.clone());}},
ShellAction::Page{target,offset}=>{state.query.offset=offset.min(u32::MAX as usize) as u32;if let Some(operation)=state.detail_operation.filter(|op|*op!=Operation::ChannelInfo){state.cancel_channel_info();spawn_query(&mut jobs,events.clone(),ctx,target,operation,state.query.clone());}}, ShellAction::Page{target,offset}=>{state.query.offset=offset.min(u32::MAX as usize) as u32;if let Some(operation)=state.detail_operation.filter(|op|!scoped_detail_query(*op)){state.cancel_scoped_detail();spawn_query(&mut jobs,events.clone(),ctx,target,operation,state.query.clone());}},
ShellAction::ToggleBookmarks=>{let sender=events.clone();jobs.spawn(async move{let result=ctx.mutate(|p|{let collapsed=p.prefs.get()["savedServersCollapsed"]==true;p.prefs.set(serde_json::json!({"savedServersCollapsed":!collapsed}))?;Ok(())}).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});}, ShellAction::ToggleBookmarks=>{let sender=events.clone();jobs.spawn(async move{let result=ctx.mutate(|p|{let collapsed=p.prefs.get()["savedServersCollapsed"]==true;p.prefs.set(serde_json::json!({"savedServersCollapsed":!collapsed}))?;Ok(())}).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});},
ShellAction::PaneWidths{sidebar,server}=>{let sender=events.clone();jobs.spawn(async move{let result=ctx.mutate(move|p|{p.prefs.set(serde_json::json!({"sidebarWidth":sidebar.round() as i32,"serverPaneWidth":server.round() as i32}))?;Ok(())}).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});},_=>{} ShellAction::PaneWidths{sidebar,server}=>{let sender=events.clone();jobs.spawn(async move{let result=ctx.mutate(move|p|{p.prefs.set(serde_json::json!({"sidebarWidth":sidebar.round() as i32,"serverPaneWidth":server.round() as i32}))?;Ok(())}).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});},_=>{}
}}else if let ShellAction::Invoke{target,operation}=action{ }}else if let ShellAction::Invoke{target,operation}=action{
@@ -414,13 +415,13 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
dirty=true; dirty=true;
} }
}, },
ServiceEvent::ChannelInfoComplete{serial,ui_generation,target,result}=>{ ServiceEvent::ScopedDetailComplete{serial,ui_generation,target,operation,result}=>{
let Some(owner)=&owner else{continue}; let Some(owner)=&owner else{continue};
let ctx=&owner.ctx; let ctx=&owner.ctx;
if ctx.require_ui_generation(ui_generation).is_err(){continue} if ctx.require_ui_generation(ui_generation).is_err(){continue}
let opens_detail=result.is_ok(); let opens_detail=result.is_ok();
// An unscoped UI error effect could outlive the accepted snapshot. // An unscoped UI error effect could outlive the accepted snapshot.
if state.finish_channel_info(serial,target,result,&ctx.connected.connections.snapshot()){ if state.finish_scoped_detail(serial,target,operation,result,&ctx.connected.connections.snapshot()){
if opens_detail{file_actions::close_recording_view(ctx).await;} if opens_detail{file_actions::close_recording_view(ctx).await;}
dirty=true; dirty=true;
} }
@@ -455,7 +456,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
match file_actions::finish_recording_view(&owner.ctx,&view,result).await { match file_actions::finish_recording_view(&owner.ctx,&view,result).await {
Ok(result)=>for effect in result.effects { Ok(result)=>for effect in result.effects {
if let UiEffect::Detail{target,detail}=effect { if let UiEffect::Detail{target,detail}=effect {
state.cancel_channel_info(); state.cancel_scoped_detail();
state.leave_snapshot(); state.leave_snapshot();
state.snapshot.destination=Destination::Servers; state.snapshot.destination=Destination::Servers;
state.detail_operation=Some(Operation::RecordingOpen); state.detail_operation=Some(Operation::RecordingOpen);
@@ -673,6 +674,8 @@ fn spawn_snapshot(jobs:&mut tokio::task::JoinSet<()>,ctx:Arc<RuntimeServices>,ta
let _=sender.send(ServiceEvent::SnapshotUpdated{serial,update:SnapshotUpdate::Finished(result)}).await; let _=sender.send(ServiceEvent::SnapshotUpdated{serial,update:SnapshotUpdate::Finished(result)}).await;
}); });
} }
pub(crate) fn scoped_detail_query(operation:Operation)->bool{matches!(operation,Operation::ChannelInfo|Operation::ClientInfo)}
async fn query_detail(ctx:&Arc<RuntimeServices>,target:&Target,operation:Operation,options:&crate::app::server_actions::QueryOptions)->Result<Detail>{ async fn query_detail(ctx:&Arc<RuntimeServices>,target:&Target,operation:Operation,options:&crate::app::server_actions::QueryOptions)->Result<Detail>{
let command=crate::app::server_actions::query(target,operation,options)?; let command=crate::app::server_actions::query(target,operation,options)?;
let key=target.session.as_ref().ok_or_else(context::changed)?; let key=target.session.as_ref().ok_or_else(context::changed)?;
+147 -48
View File
@@ -60,22 +60,22 @@ fn snapshot_session_viewed(key: &SessionKey, connections: &ConnectionsSnapshot)
pub struct AppState { pub struct AppState {
pub snapshot:Snapshot,pub selected:Option<Target>,pub folder:Option<String>, pub snapshot:Snapshot,pub selected:Option<Target>,pub folder:Option<String>,
pub detail_target:Option<Target>,pub detail_operation:Option<Operation>,pub query:crate::app::server_actions::QueryOptions, pub detail_target:Option<Target>,pub detail_operation:Option<Operation>,pub query:crate::app::server_actions::QueryOptions,
channel_info_serial: u64, scoped_detail_serial: u64,
pending_channel_info: Option<u64>, pending_scoped_detail: Option<u64>,
snapshot_serial: u64, snapshot_serial: u64,
snapshot_job: Option<SnapshotJobView>, snapshot_job: Option<SnapshotJobView>,
recent_events_stamp: Option<super::notification_actions::RecentEventsStamp>, recent_events_stamp: Option<super::notification_actions::RecentEventsStamp>,
} }
impl Default for AppState{fn default()->Self{Self{snapshot:Snapshot::default(),selected:None,folder:None,detail_target:None,detail_operation:None,query:Default::default(),channel_info_serial:0,pending_channel_info:None,snapshot_serial:0,snapshot_job:None,recent_events_stamp:None}}} impl Default for AppState{fn default()->Self{Self{snapshot:Snapshot::default(),selected:None,folder:None,detail_target:None,detail_operation:None,query:Default::default(),scoped_detail_serial:0,pending_scoped_detail:None,snapshot_serial:0,snapshot_job:None,recent_events_stamp:None}}}
impl AppState { impl AppState {
pub(super) fn begin_channel_info(&mut self) -> u64 { pub(super) fn begin_scoped_detail(&mut self) -> u64 {
self.channel_info_serial = self.channel_info_serial.wrapping_add(1); self.scoped_detail_serial = self.scoped_detail_serial.wrapping_add(1);
self.pending_channel_info = Some(self.channel_info_serial); self.pending_scoped_detail = Some(self.scoped_detail_serial);
self.channel_info_serial self.scoped_detail_serial
} }
pub(super) fn cancel_channel_info(&mut self) { pub(super) fn cancel_scoped_detail(&mut self) {
self.pending_channel_info = None; self.pending_scoped_detail = None;
} }
pub(super) fn snapshot_preview_viewed(&self, target: &Target, connections: &ConnectionsSnapshot) -> bool { pub(super) fn snapshot_preview_viewed(&self, target: &Target, connections: &ConnectionsSnapshot) -> bool {
@@ -104,7 +104,7 @@ impl AppState {
.map(|action| action.target.clone()) .map(|action| action.target.clone())
} else { None }; } else { None };
self.supersede_snapshot(); self.supersede_snapshot();
self.cancel_channel_info(); self.cancel_scoped_detail();
self.snapshot_job = Some(SnapshotJobView { serial, ui_generation, target, operation, server }); self.snapshot_job = Some(SnapshotJobView { serial, ui_generation, target, operation, server });
} }
serial serial
@@ -233,31 +233,39 @@ impl AppState {
} }
pub(super) fn select(&mut self, target: Target) { pub(super) fn select(&mut self, target: Target) {
self.cancel_channel_info(); self.cancel_scoped_detail();
self.leave_snapshot(); self.leave_snapshot();
self.selected = Some(target); self.selected = Some(target);
} }
pub(super) fn back(&mut self) { pub(super) fn back(&mut self) {
self.cancel_channel_info(); self.cancel_scoped_detail();
self.leave_snapshot(); self.leave_snapshot();
self.selected = None; self.selected = None;
self.detail_target = None; self.detail_target = None;
self.snapshot.detail = Detail::default(); self.snapshot.detail = Detail::default();
} }
pub(super) fn finish_channel_info(&mut self, serial: u64, target: Target, result: crate::services::Result<Detail>, connections: &ConnectionsSnapshot) -> bool { pub(super) fn finish_scoped_detail(&mut self, serial: u64, target: Target, operation: Operation, result: crate::services::Result<Detail>, connections: &ConnectionsSnapshot) -> bool {
// A repeat for the same channel still belongs to a different panel request. if self.pending_scoped_detail != Some(serial) { return false; }
if self.pending_channel_info != Some(serial) { return false; } self.cancel_scoped_detail();
self.cancel_channel_info();
let viewed = connections.viewed_id.as_deref().and_then(|id| connections.get(id)); let viewed = connections.viewed_id.as_deref().and_then(|id| connections.get(id));
let Some(viewed) = viewed.filter(|tab| target.session.as_ref() == Some(&tab.key)) else { return false; }; let Some(viewed) = viewed.filter(|tab| target.session.as_ref() == Some(&tab.key)) else { return false; };
// Client IDs can be reused in the same session; an error from the departed client is stale too.
if operation == Operation::ClientInfo {
let Entity::Client { id, uid, .. } = &target.entity else { return false; };
if !viewed.is_connected() || !viewed.server.as_ref().and_then(|server| server["clients"].as_array())
.is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(u64::from(*id))
&& row["uid"].as_str() == Some(uid.as_str()))) { return false; }
} else if result.is_ok() {
// Preserve Channel Info's existing error handling for the viewed session.
let Entity::Channel { id } = target.entity else { return false; };
if !viewed.is_connected() || !viewed.server.as_ref().and_then(|server| server["channels"].as_array())
.is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(id))) { return false; }
}
match result { match result {
Ok(detail) => { Ok(detail) => {
let Entity::Channel { id } = target.entity else { return false; }; self.detail_operation = Some(operation);
if !viewed.is_connected() || !viewed.server.as_ref().and_then(|server| server["channels"].as_array())
.is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(id))) { return false; }
self.detail_operation = Some(Operation::ChannelInfo);
self.detail_target = Some(target); self.detail_target = Some(target);
self.snapshot.detail = detail; self.snapshot.detail = detail;
} }
@@ -270,18 +278,18 @@ impl AppState {
} }
pub fn apply(&mut self,effect:&UiEffect){match effect{ pub fn apply(&mut self,effect:&UiEffect){match effect{
UiEffect::Detail{target,detail}=>{self.cancel_channel_info();self.leave_snapshot();self.detail_target=Some(target.clone());self.snapshot.detail=detail.clone();}, UiEffect::Detail{target,detail}=>{self.cancel_scoped_detail();self.leave_snapshot();self.detail_target=Some(target.clone());self.snapshot.detail=detail.clone();},
UiEffect::SnapshotPreviewOpened{target,detail,..}=>{ UiEffect::SnapshotPreviewOpened{target,detail,..}=>{
self.cancel_channel_info();self.leave_snapshot();self.detail_target=Some(target.clone()); self.cancel_scoped_detail();self.leave_snapshot();self.detail_target=Some(target.clone());
self.detail_operation=Some(Operation::SnapshotChoose);self.snapshot.detail=detail.clone(); self.detail_operation=Some(Operation::SnapshotChoose);self.snapshot.detail=detail.clone();
}, },
UiEffect::SnapshotPreviewDismissed{target} if self.snapshot_preview_matches(target) && self.detail_target.as_ref()==Some(target)=>{ UiEffect::SnapshotPreviewDismissed{target} if self.snapshot_preview_matches(target) && self.detail_target.as_ref()==Some(target)=>{
self.leave_snapshot();self.detail_target=None;self.detail_operation=None;self.snapshot.detail=Detail::default(); self.leave_snapshot();self.detail_target=None;self.detail_operation=None;self.snapshot.detail=Detail::default();
self.snapshot.status=self.snapshot.catalog.text("snapshots.cancelled"); self.snapshot.status=self.snapshot.catalog.text("snapshots.cancelled");
}, },
UiEffect::Navigate(destination)=>{self.cancel_channel_info();self.leave_snapshot();self.snapshot.destination=*destination;}, UiEffect::Navigate(destination)=>{self.cancel_scoped_detail();self.leave_snapshot();self.snapshot.destination=*destination;},
UiEffect::BookmarkFolder(folder)=>self.folder=folder.clone(), UiEffect::BookmarkFolder(folder)=>self.folder=folder.clone(),
UiEffect::SettingsNavigate(nav)=>{self.cancel_channel_info();self.leave_snapshot();self.snapshot.settings_view.navigate(nav);self.snapshot.destination=Destination::Settings;}, UiEffect::SettingsNavigate(nav)=>{self.cancel_scoped_detail();self.leave_snapshot();self.snapshot.settings_view.navigate(nav);self.snapshot.destination=Destination::Settings;},
UiEffect::Status(value)=>self.snapshot.status=value.clone(),UiEffect::Error(error)=>{self.snapshot.error=error.message.clone();self.snapshot.last_error=Some(error.clone());}, UiEffect::Status(value)=>self.snapshot.status=value.clone(),UiEffect::Error(error)=>{self.snapshot.error=error.message.clone();self.snapshot.last_error=Some(error.clone());},
UiEffect::SettingsComplete{serial,result}=>{self.snapshot.settings_completed=*serial;self.snapshot.last_error=result.as_ref().err().cloned();self.snapshot.error=result.as_ref().err().map(|e|e.message.clone()).unwrap_or_default();}, UiEffect::SettingsComplete{serial,result}=>{self.snapshot.settings_completed=*serial;self.snapshot.last_error=result.as_ref().err().cloned();self.snapshot.error=result.as_ref().err().map(|e|e.message.clone()).unwrap_or_default();},
UiEffect::Theme(theme)=>self.snapshot.theme=Some(theme.clone()),_=>{} UiEffect::Theme(theme)=>self.snapshot.theme=Some(theme.clone()),_=>{}
@@ -291,7 +299,7 @@ impl AppState {
if !matches!(target.entity,Entity::Connection|Entity::Server{..})||!viewed.is_some_and(|view|target.session.as_ref()==Some(&view.key)){ if !matches!(target.entity,Entity::Connection|Entity::Server{..})||!viewed.is_some_and(|view|target.session.as_ref()==Some(&view.key)){
return Err(super::context::changed()); return Err(super::context::changed());
} }
self.cancel_channel_info(); self.cancel_scoped_detail();
self.leave_snapshot(); self.leave_snapshot();
self.detail_target=None; self.detail_target=None;
self.detail_operation=None; self.detail_operation=None;
@@ -405,7 +413,11 @@ impl AppState {
if self.snapshot.detail.recent_server_events { if self.snapshot.detail.recent_server_events {
let notifications=ctx.notifications.lock().map_err(|_|super::notification_actions::unavailable())?; let notifications=ctx.notifications.lock().map_err(|_|super::notification_actions::unavailable())?;
self.project_recent_server_events(viewed,&notifications,&c,prefs["chatUse24hTime"]!=false,ctx.notification_clock.epoch_ms()); self.project_recent_server_events(viewed,&notifications,&c,prefs["chatUse24hTime"]!=false,ctx.notification_clock.epoch_ms());
} else if self.detail_target.as_ref().is_some_and(|t|ctx.require_target(t).is_err()){ } else if self.detail_target.as_ref().is_some_and(|t|{
(self.detail_operation == Some(Operation::ClientInfo)
&& viewed.is_none_or(|tab| t.session.as_ref() != Some(&tab.key)))
|| ctx.require_target(t).is_err()
}){
if self.snapshot.snapshot_progress.is_some() { self.leave_snapshot(); } if self.snapshot.snapshot_progress.is_some() { self.leave_snapshot(); }
self.detail_target=None;self.snapshot.detail=Detail::default(); self.detail_target=None;self.snapshot.detail=Detail::default();
} }
@@ -664,19 +676,19 @@ mod tests {
let (connections, target, _) = channel_info_fixture(); let (connections, target, _) = channel_info_fixture();
let mut state = AppState::default(); let mut state = AppState::default();
state.select(target.clone()); state.select(target.clone());
let old_error = state.begin_channel_info(); let old_error = state.begin_scoped_detail();
let old_success = state.begin_channel_info(); let old_success = state.begin_scoped_detail();
let latest = state.begin_channel_info(); let latest = state.begin_scoped_detail();
assert!(!state.finish_channel_info(old_error, target.clone(), Err(ServiceError::new("bad_response", "old failure")), &connections)); assert!(!state.finish_scoped_detail(old_error, target.clone(), Operation::ChannelInfo, Err(ServiceError::new("bad_response", "old failure")), &connections));
assert!(state.snapshot.last_error.is_none()); assert!(state.snapshot.last_error.is_none());
assert!(state.finish_channel_info(latest, target.clone(), Ok(channel_info_detail("latest")), &connections)); assert!(state.finish_scoped_detail(latest, target.clone(), Operation::ChannelInfo, Ok(channel_info_detail("latest")), &connections));
assert!(!state.finish_channel_info(old_success, target.clone(), Ok(channel_info_detail("old detail")), &connections)); assert!(!state.finish_scoped_detail(old_success, target.clone(), Operation::ChannelInfo, Ok(channel_info_detail("old detail")), &connections));
assert_eq!(state.snapshot.detail.title, "latest"); assert_eq!(state.snapshot.detail.title, "latest");
let current = state.begin_channel_info(); let current = state.begin_scoped_detail();
let error = ServiceError::new("target_changed", "Channel reply belongs to another channel"); let error = ServiceError::new("target_changed", "Channel reply belongs to another channel");
assert!(state.finish_channel_info(current, target.clone(), Err(error), &connections)); assert!(state.finish_scoped_detail(current, target.clone(), Operation::ChannelInfo, Err(error), &connections));
assert_eq!(state.snapshot.error, "Channel reply belongs to another channel"); assert_eq!(state.snapshot.error, "Channel reply belongs to another channel");
assert_eq!(state.snapshot.last_error.as_ref().unwrap().code, "target_changed"); assert_eq!(state.snapshot.last_error.as_ref().unwrap().code, "target_changed");
assert_eq!(state.detail_target.as_ref(), Some(&target)); assert_eq!(state.detail_target.as_ref(), Some(&target));
@@ -689,26 +701,26 @@ mod tests {
let (connections, first, second) = channel_info_fixture(); let (connections, first, second) = channel_info_fixture();
let mut state = AppState::default(); let mut state = AppState::default();
state.select(first.clone()); state.select(first.clone());
let old = state.begin_channel_info(); let old = state.begin_scoped_detail();
state.select(second.clone()); state.select(second.clone());
state.select(first.clone()); state.select(first.clone());
assert!(!state.finish_channel_info(old, first.clone(), Ok(channel_info_detail("abandoned selection")), &connections)); assert!(!state.finish_scoped_detail(old, first.clone(), Operation::ChannelInfo, Ok(channel_info_detail("abandoned selection")), &connections));
let old = state.begin_channel_info(); let old = state.begin_scoped_detail();
state.apply(&UiEffect::Detail { target: second.clone(), detail: channel_info_detail("new panel") }); state.apply(&UiEffect::Detail { target: second.clone(), detail: channel_info_detail("new panel") });
assert!(!state.finish_channel_info(old, first.clone(), Ok(channel_info_detail("old panel")), &connections)); assert!(!state.finish_scoped_detail(old, first.clone(), Operation::ChannelInfo, Ok(channel_info_detail("old panel")), &connections));
assert_eq!(state.detail_target, Some(second)); assert_eq!(state.detail_target, Some(second));
assert_eq!(state.snapshot.detail.title, "new panel"); assert_eq!(state.snapshot.detail.title, "new panel");
let old = state.begin_channel_info(); let old = state.begin_scoped_detail();
state.apply(&UiEffect::Navigate(Destination::Settings)); state.apply(&UiEffect::Navigate(Destination::Settings));
state.apply(&UiEffect::Navigate(Destination::Servers)); state.apply(&UiEffect::Navigate(Destination::Servers));
assert!(!state.finish_channel_info(old, first.clone(), Err(ServiceError::new("bad_response", "abandoned navigation")), &connections)); assert!(!state.finish_scoped_detail(old, first.clone(), Operation::ChannelInfo, Err(ServiceError::new("bad_response", "abandoned navigation")), &connections));
assert!(state.snapshot.error.is_empty()); assert!(state.snapshot.error.is_empty());
let old = state.begin_channel_info(); let old = state.begin_scoped_detail();
state.back(); state.back();
assert!(!state.finish_channel_info(old, first, Ok(channel_info_detail("dismissed")), &connections)); assert!(!state.finish_scoped_detail(old, first, Operation::ChannelInfo, Ok(channel_info_detail("dismissed")), &connections));
assert!(state.detail_target.is_none()); assert!(state.detail_target.is_none());
assert!(state.snapshot.detail.title.is_empty()); assert!(state.snapshot.detail.title.is_empty());
} }
@@ -718,22 +730,109 @@ mod tests {
use crate::services::ServiceError; use crate::services::ServiceError;
let (mut connections, old, _) = channel_info_fixture(); let (mut connections, old, _) = channel_info_fixture();
let mut state = AppState::default(); let mut state = AppState::default();
let stale_success = state.begin_channel_info(); let stale_success = state.begin_scoped_detail();
connections.connections[0].key.session += 1; connections.connections[0].key.session += 1;
assert!(!state.finish_channel_info(stale_success, old.clone(), Ok(channel_info_detail("prior session")), &connections)); assert!(!state.finish_scoped_detail(stale_success, old.clone(), Operation::ChannelInfo, Ok(channel_info_detail("prior session")), &connections));
assert!(state.detail_target.is_none()); assert!(state.detail_target.is_none());
let stale_error = state.begin_channel_info(); let stale_error = state.begin_scoped_detail();
assert!(!state.finish_channel_info(stale_error, old.clone(), Err(ServiceError::new("target_changed", "old session")), &connections)); assert!(!state.finish_scoped_detail(stale_error, old.clone(), Operation::ChannelInfo, Err(ServiceError::new("target_changed", "old session")), &connections));
assert!(state.snapshot.last_error.is_none()); assert!(state.snapshot.last_error.is_none());
let current = state.begin_channel_info(); let current = state.begin_scoped_detail();
let target = Target { session: Some(connections.connections[0].key.clone()), ..old }; let target = Target { session: Some(connections.connections[0].key.clone()), ..old };
assert!(state.finish_channel_info(current, target.clone(), Ok(channel_info_detail("reconnected")), &connections)); assert!(state.finish_scoped_detail(current, target.clone(), Operation::ChannelInfo, Ok(channel_info_detail("reconnected")), &connections));
assert_eq!(state.detail_target, Some(target)); assert_eq!(state.detail_target, Some(target));
assert_eq!(state.snapshot.detail.title, "reconnected"); assert_eq!(state.snapshot.detail.title, "reconnected");
} }
fn rostered_client(connections: &mut ConnectionsSnapshot, uid: &str) -> Target {
let tab = &mut connections.connections[0];
Arc::make_mut(tab.server.as_mut().unwrap())["clients"] = json!([{"id": 42, "uid": uid}]);
Target { session: Some(tab.key.clone()), entity: Entity::Client { id: 42, uid: uid.into(), channel_id: 7 }, name: uid.into(), own_channel_id: Some(7) }
}
#[test]
fn client_info_reused_id_rejects_old_uid_success_and_error() {
use crate::services::ServiceError;
for outcome in [Ok(channel_info_detail("departed client")), Err(ServiceError::new("target_changed", "old UID"))] {
let (mut connections, _, _) = channel_info_fixture();
let old = rostered_client(&mut connections, "Old=");
let mut state = AppState::default();
let serial = state.begin_scoped_detail();
let replacement = rostered_client(&mut connections, "Replacement=");
assert!(!state.finish_scoped_detail(serial, old, Operation::ClientInfo, outcome, &connections));
assert!(state.detail_target.is_none());
assert!(state.snapshot.error.is_empty());
assert!(state.snapshot.last_error.is_none());
let serial = state.begin_scoped_detail();
assert!(state.finish_scoped_detail(serial, replacement.clone(), Operation::ClientInfo, Ok(channel_info_detail("replacement")), &connections));
let serial = state.begin_scoped_detail();
let error = ServiceError::new("bad_response", "current client query failed");
assert!(state.finish_scoped_detail(serial, replacement.clone(), Operation::ClientInfo, Err(error), &connections));
assert_eq!(state.detail_target, Some(replacement));
assert_eq!(state.detail_operation, Some(Operation::ClientInfo));
assert_eq!(state.snapshot.detail.title, "replacement");
assert_eq!(state.snapshot.error, "current client query failed");
assert_eq!(state.snapshot.last_error.as_ref().unwrap().code, "bad_response");
}
}
#[test]
fn client_and_channel_info_share_the_latest_request() {
use crate::services::ServiceError;
let (mut connections, channel, _) = channel_info_fixture();
let client = rostered_client(&mut connections, "Peer=");
let mut state = AppState::default();
let old_client = state.begin_scoped_detail();
let latest_channel = state.begin_scoped_detail();
assert!(!state.finish_scoped_detail(old_client, client.clone(), Operation::ClientInfo, Err(ServiceError::new("bad_response", "old client failure")), &connections));
assert!(state.finish_scoped_detail(latest_channel, channel.clone(), Operation::ChannelInfo, Ok(channel_info_detail("channel")), &connections));
assert_eq!(state.detail_operation, Some(Operation::ChannelInfo));
let old_channel = state.begin_scoped_detail();
let latest_client = state.begin_scoped_detail();
assert!(state.finish_scoped_detail(latest_client, client.clone(), Operation::ClientInfo, Ok(channel_info_detail("client")), &connections));
assert!(!state.finish_scoped_detail(old_channel, channel, Operation::ChannelInfo, Ok(channel_info_detail("old channel")), &connections));
assert_eq!(state.detail_target, Some(client));
assert_eq!(state.detail_operation, Some(Operation::ClientInfo));
assert_eq!(state.snapshot.detail.title, "client");
assert!(state.snapshot.last_error.is_none());
}
#[test]
fn client_info_drops_results_after_selection_or_tab_changes() {
use crate::services::ServiceError;
let (mut connections, channel, _) = channel_info_fixture();
let client = rostered_client(&mut connections, "Peer=");
let mut state = AppState::default();
let old_selection = state.begin_scoped_detail();
state.select(channel);
assert!(!state.finish_scoped_detail(old_selection, client.clone(), Operation::ClientInfo, Err(ServiceError::new("bad_response", "old selection")), &connections));
let old_tab = state.begin_scoped_detail();
let mut other = connections.connections[0].clone();
other.key.connection_id = "other".into();
connections.viewed_id = Some(other.key.connection_id.clone());
connections.connections.push(other);
assert!(!state.finish_scoped_detail(old_tab, client.clone(), Operation::ClientInfo, Ok(channel_info_detail("not viewed")), &connections));
connections.viewed_id = Some(connections.connections[0].key.connection_id.clone());
let replaced = state.begin_scoped_detail();
connections.connections[0].key.generation += 1;
assert!(!state.finish_scoped_detail(replaced, client.clone(), Operation::ClientInfo, Err(ServiceError::new("target_changed", "replaced tab")), &connections));
let closed = state.begin_scoped_detail();
let current = Target { session: Some(connections.connections[0].key.clone()), ..client };
connections.connections.remove(0);
connections.viewed_id = Some(connections.connections[0].key.connection_id.clone());
assert!(!state.finish_scoped_detail(closed, current, Operation::ClientInfo, Err(ServiceError::new("target_changed", "closed tab")), &connections));
assert!(state.detail_target.is_none());
assert!(state.snapshot.last_error.is_none());
}
#[test] #[test]
fn recent_server_events_follow_selection_and_drop_closed_connection() { fn recent_server_events_follow_selection_and_drop_closed_connection() {
use crate::app::connections::{ConnectionSnapshot,ConnectionState,CoreStatus}; use crate::app::connections::{ConnectionSnapshot,ConnectionState,CoreStatus};
+14 -1
View File
@@ -97,7 +97,20 @@ pub fn project_with_context(t:&Target,op:Operation,reply:&Value,c:&Catalog,conte
let mut edit=action(t,Operation::ChannelEdit,c,context,"b_channel_modify_name");edit.form=None;d.actions.push(edit); let mut edit=action(t,Operation::ChannelEdit,c,context,"b_channel_modify_name");edit.form=None;d.actions.push(edit);
}, },
Operation::ServerInfo=>{server(t)?;if let Some(row)=rows.first(){d.description=string(row,"virtualserver_welcomemessage");for(key,value)in row.as_object().ok_or_else(||bad("Server properties must be an object"))?{if let Some(name)=key.strip_prefix("virtualserver_"){if name=="password"{continue}if matches!(value,Value::String(_)|Value::Number(_)|Value::Bool(_)){d.rows.push(InfoRow{label:c.text(&format!("admin.serverField.{name}")),value:string(row,key)})}}}let mut edit=action(t,Operation::ServerEdit,c,context,"b_virtualserver_modify_name");edit.form=None;d.actions.push(edit);}}, Operation::ServerInfo=>{server(t)?;if let Some(row)=rows.first(){d.description=string(row,"virtualserver_welcomemessage");for(key,value)in row.as_object().ok_or_else(||bad("Server properties must be an object"))?{if let Some(name)=key.strip_prefix("virtualserver_"){if name=="password"{continue}if matches!(value,Value::String(_)|Value::Number(_)|Value::Bool(_)){d.rows.push(InfoRow{label:c.text(&format!("admin.serverField.{name}")),value:string(row,key)})}}}let mut edit=action(t,Operation::ServerEdit,c,context,"b_virtualserver_modify_name");edit.form=None;d.actions.push(edit);}},
Operation::ClientInfo|Operation::ClientConnectionInfo=>{let target=client(t)?;for row in rows{if row.get("clid").is_some()&&id(row,"clid")?!=u64::from(target.client_id){return Err(ServiceError::new("target_changed","Client query belongs to another target"))}if row.get("client_unique_identifier").is_some()&&string(row,"client_unique_identifier")!=target.uid{return Err(ServiceError::new("target_changed","Client UID changed"))}d.description=string(row,"client_description");row_fields(&mut d,row,&[("client_nickname","ui.nickname"),("client_unique_identifier","admin.uid"),("client_version","admin.version"),("client_platform","admin.platform"),("client_totalconnections","admin.totalConnections"),("connection_connected_time","admin.connectedTime"),("connection_ping","admin.ping"),("connection_packetloss_total","admin.packetLoss")],c);}}, Operation::ClientInfo|Operation::ClientConnectionInfo=>{
let target=client(t)?;
if op==Operation::ClientInfo && rows.is_empty(){return Err(ServiceError::new("bad_response","Missing client information"))}
for row in rows{
if (op==Operation::ClientInfo || row.get("clid").is_some()) && id(row,"clid")?!=u64::from(target.client_id){return Err(ServiceError::new("target_changed","Client query belongs to another target"))}
if row.get("client_unique_identifier").is_some_and(|uid|uid.as_str()!=Some(target.uid.as_str())){return Err(ServiceError::new("target_changed","Client UID changed"))}
}
// Notifications may update only a subset of the requested client's properties.
let latest=|key:&str|rows.iter().rev().find(|row|row.get(key).is_some()).map(|row|string(row,key)).unwrap_or_default();
d.description=latest("client_description");
for (key,label) in [("client_nickname","ui.nickname"),("client_unique_identifier","admin.uid"),("client_version","admin.version"),("client_platform","admin.platform"),("client_totalconnections","admin.totalConnections"),("connection_connected_time","admin.connectedTime"),("connection_ping","admin.ping"),("connection_packetloss_total","admin.packetLoss")]{
let value=latest(key);if !value.is_empty(){d.rows.push(InfoRow{label:c.text(label),value});}
}
},
Operation::GroupPermissions|Operation::ClientPermissions=>{ Operation::GroupPermissions|Operation::ClientPermissions=>{
let scope=scoped(t); let scope=scoped(t);
let identity=match &scope.entity{Entity::Channel{id}=>Some(("cid",*id)),Entity::ServerGroup{id}=>Some(("sgid",*id)),Entity::ChannelGroup{id}=>Some(("cgid",*id)),Entity::Client{..}=>{client(&scope)?;None},_=>return Err(bad("Invalid permission query scope"))}; let identity=match &scope.entity{Entity::Channel{id}=>Some(("cid",*id)),Entity::ServerGroup{id}=>Some(("sgid",*id)),Entity::ChannelGroup{id}=>Some(("cgid",*id)),Entity::Client{..}=>{client(&scope)?;None},_=>return Err(bad("Invalid permission query scope"))};
+9
View File
@@ -12,6 +12,15 @@ fn recycled_client_number_cannot_discard_uid(){
assert!(project(&t,Operation::ClientInfo,&reply,&crate::ui::i18n::Catalog::default()).is_err()); assert!(project(&t,Operation::ClientInfo,&reply,&crate::ui::i18n::Catalog::default()).is_err());
} }
#[test] #[test]
fn client_info_merges_only_scoped_fields_and_honors_explicit_clears(){
let t=target(Entity::Client{id:7,uid:"peer=".into(),channel_id:2});let c=crate::ui::i18n::Catalog::default();
let mut reply=serde_json::json!({"rows":[{"clid":"7","client_description":"retained","client_version":"old"},{"clid":"7","client_version":"new"}]});
let d=project(&t,Operation::ClientInfo,&reply,&c).unwrap();assert_eq!(d.description,"retained");
assert!(d.rows.iter().map(|r|r.value.as_str()).eq(["new"]));
reply["rows"][1]["client_description"]="".into();assert!(project(&t,Operation::ClientInfo,&reply,&c).unwrap().description.is_empty());
reply["rows"][0].as_object_mut().unwrap().remove("clid");assert!(project(&t,Operation::ClientInfo,&reply,&c).is_err());
}
#[test]
fn channel_client_permissions_never_become_channel_permissions(){ fn channel_client_permissions_never_become_channel_permissions(){
let v=values(&[("permission_id",FieldValue::Choice("42".into())),("value",FieldValue::Integer(1))]); let v=values(&[("permission_id",FieldValue::Choice("42".into())),("value",FieldValue::Integer(1))]);
assert!(prepare(&target(Entity::Channel{id:2}),Operation::ClientChannelPermissionSet,&v).is_err()); assert!(prepare(&target(Entity::Channel{id:2}),Operation::ClientChannelPermissionSet,&v).is_err());
+1 -1
View File
@@ -195,7 +195,7 @@ async fn roundtrip(runtime: &AppRuntime, ui: &AppWindow, key: &SessionKey, uid:
let ui_generation = runtime.current_ui_generation().ok_or("snapshot UI detached")?; let ui_generation = runtime.current_ui_generation().ok_or("snapshot UI detached")?;
for (target, operation) in [(first.target.clone(), Operation::SnapshotCancel), for (target, operation) in [(first.target.clone(), Operation::SnapshotCancel),
(first.target, Operation::SnapshotApply), (first.row_target, Operation::SnapshotApply)] { (first.target, Operation::SnapshotApply), (first.row_target, Operation::SnapshotApply)] {
runtime.enqueue(RuntimeCommand::SnapshotShell { action: ShellAction::Invoke { target, operation }, ui_generation }) runtime.enqueue(RuntimeCommand::AttachmentShell { action: ShellAction::Invoke { target, operation }, ui_generation })
.map_err(|error| format!("queue stale snapshot action {operation:?}: {error}"))?; .map_err(|error| format!("queue stale snapshot action {operation:?}: {error}"))?;
} }
let apply = row_apply(runtime, ui, &second.row)?; let apply = row_apply(runtime, ui, &second.row)?;
+221 -19
View File
@@ -642,13 +642,200 @@ fn moderation_toggle_filters_existing_and_new_channel_events_without_persisting_
assert!(page.messages.iter().map(|r|r.record.text.as_str()).eq(["Before toggle","After toggle"])); assert!(page.messages.iter().map(|r|r.record.text.as_str()).eq(["Before toggle","After toggle"]));
} }
#[cfg(target_os = "windows")]
#[test]
#[ignore = "requires exclusive use of private beta14 at 127.0.0.1:19987"]
fn participant_info_menu_reads_exact_muted_beta14_guest() {
use super::key_profiles::until;
use crate::{app::connections::ConnectionState, ui::shell::{Entity, Operation, TreeAppearance}};
use serde_json::Value;
use teamspeach_core::{admin::{AdminCommand, extra}, protocol::ConnectArgs};
const NAMES: [&str; 2] = ["Info QA First", "Info QA Second"];
const FIELDS: [(&str, &str); 5] = [("client_nickname", "ui.nickname"), ("client_unique_identifier", "admin.uid"),
("client_version", "admin.version"), ("client_platform", "admin.platform"), ("client_totalconnections", "admin.totalConnections")];
if !headless::install_for_test() { return; }
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("profile");
initialize_native_root(&root).unwrap();
let identities = {
let profile = ProfileServices::open(&root).unwrap();
[profile.identities.onboard(NAMES[0]).unwrap()["uid"].as_str().unwrap().to_owned(),
profile.identities.create(NAMES[1], NAMES[1]).unwrap().uid]
};
run_ui(&AppConfig { network_enabled: true, ..AppConfig::isolated(root) }, async move |runtime, ui| {
ui.show().map_err(|e| e.to_string())?;
until("profile ready", || runtime.snapshot().settings.loaded).await?;
let owner = runtime.services.lock().unwrap().upgrade().ok_or("runtime closed")?;
let manager = &owner.connected.connections;
let mut tabs = [manager.key("c1").await.map_err(|e| e.to_string())?, manager.create().await.map_err(|e| e.to_string())?];
let pace = async || -> SmokeResult<()> {
// Both guests share beta14's loopback command budget.
let (tx, rx) = tokio::sync::oneshot::channel();
slint::Timer::single_shot(std::time::Duration::from_secs(5), move || { let _ = tx.send(()); });
rx.await.map_err(|e| e.to_string())
};
let silent = || {
let s = runtime.snapshot();
!s.audio_input_active && !s.audio_output_active && s.audio_input_starts == 0 && s.audio_output_starts == 0
&& s.voice.as_ref().is_none_or(|v| v.muted && v.deafened && !v.transmitting)
};
let exercise: SmokeResult<()> = async {
let mut clients = [0u16; 2];
for (i, identity_id) in identities.into_iter().enumerate() {
if i > 0 { pace().await?; }
let key = &tabs[i];
owner.request(key, Command::SetAudio { input_muted: Some(true), output_muted: Some(true) }).await.map_err(|e| e.message)?;
let reply = owner.request(key, Command::Connect(ConnectArgs {
address: "127.0.0.1:19987".into(), identity_id: Some(identity_id), nickname: None,
channel: None, server_password: None, channel_password: None,
})).await.map_err(|e| e.message)?;
clients[i] = reply["own_client_id"].as_u64().and_then(|id| u16::try_from(id).ok())
.filter(|id| *id != 0).ok_or("missing beta14 guest client ID")?;
tabs[i] = manager.key(&key.connection_id).await.map_err(|e| e.to_string())?;
}
let roster_uids = |s: &Value| -> Option<[String; 2]> {
let rows = s["clients"].as_array().filter(|rows| rows.len() == 2)?;
let exact = |i: usize| rows.iter().find(|r| r["id"] == clients[i] && r["nickname"] == NAMES[i]
&& r["channel_id"] == s["own_channel_id"] && r["input_muted"] == true && r["output_muted"] == true)
.and_then(|r| r["uid"].as_str()).filter(|uid| !uid.is_empty()).map(str::to_owned);
Some([exact(0)?, exact(1)?])
};
let matching_uids = || {
let state=runtime.snapshot();
let read = |i: usize| {
let key = &tabs[i];
let tab = state.connections.get(&key.connection_id).filter(|tab| tab.key == *key && tab.is_connected()
&& tab.audio.input_muted && tab.audio.output_muted && !tab.audio.transmitting)?;
let s = tab.server.as_deref()?;
(s["own_client_id"] == clients[i] && s["server"]["version"].as_str().is_some_and(|v| v.contains("beta14")))
.then(|| roster_uids(s)).flatten()
};
let [first, second] = [read(0)?, read(1)?];
(clients[0] != clients[1] && first[0] != first[1] && first == second).then_some(first)
};
until("the same two muted disposable guests in both beta14 rosters", || matching_uids().is_some()).await?;
let uids = matching_uids().ok_or("participant roster changed")?;
let shell = ui.global::<ShellBridge>();
let catalog = runtime.snapshot().catalog;
let info = catalog.text("admin.info");
let labels = FIELDS.map(|(_, label)| catalog.text(label));
let cleared = || shell.get_info().row_count() == 0 && shell.get_description().is_empty();
for (view, peer) in [(0, 0), (1, 1), (1, 0)] {
let key = &tabs[view];
let name = NAMES[peer];
let viewed = || runtime.snapshot().connections.viewed_id.as_deref() == Some(key.connection_id.as_str());
until("two connected Slint tabs", || shell.get_sidebar_tabs().iter().filter(|tab| tab.connected).count() == 2).await?;
let visible_tabs = rendered_tabs(ui)?;
let (bounds, selected) = *visible_tabs.get(view).ok_or("missing rendered connection tab")?;
if !selected {
click_tab(ui, bounds)?;
until("new tab selected and old participant properties cleared", || {
viewed() && cleared() && shell.get_title().is_empty()
}).await?;
let rendered = rendered_detail_text(ui)?;
if rendered.iter().any(|text| labels.iter().any(|label| text.as_str() == label.as_str())) {
return Err("participant properties remained rendered on the new tab".into());
}
}
until("exact participant row on the viewed session", || runtime.snapshot().tree.iter().any(|entry| {
let target = &entry.row.target;
entry.row.title == name && target.session.as_ref() == Some(key)
&& matches!(&target.entity, Entity::Client { id, uid, .. } if *id == clients[peer] && uid == &uids[peer])
&& matches!(entry.appearance, TreeAppearance::Client { own, .. } if own == (view == peer))
})).await?;
// Determine the permissions of this exact guest-to-participant request without changing ACLs.
pace().await?;
let readback = owner.request(key, Command::Admin(AdminCommand::Extra(extra::Command::ClientInfo {
client_id: clients[peer], uid: uids[peer].clone(),
}))).await;
if !silent() { return Err("the muted Info workflow started an audio device".into()); }
let refused = |error: &crate::services::ServiceError| view != peer && error.code == "server_error"
&& error.message.contains("PermissionsClientInsufficient");
if readback.as_ref().is_err_and(refused) {
// A current refusal can leave the previous panel open, so dismiss it first.
ui.invoke_back_requested();
until("previous participant details closed before the refused read", cleared).await?;
}
pace().await?;
invoke_tree_info_menu(runtime, ui, name, Operation::ClientInfo).await?;
match readback {
Ok(reply) => {
let rows = reply["rows"].as_array().filter(|rows| !rows.is_empty()).ok_or("no scoped client information read back")?;
if !rows.iter().all(|r| r["clid"].as_str().and_then(|s| s.parse::<u16>().ok()) == Some(clients[peer])) {
return Err("client information readback belonged to another participant".into());
}
let fields = FIELDS.map(|(field, _)| rows.iter().rev().find_map(|r| r.get(field))
.and_then(Value::as_str).filter(|value| !value.is_empty()));
if fields.iter().all(Option::is_none) || (view == peer && (fields[2].is_none() || fields[3].is_none()))
|| fields[0].is_some_and(|nick| nick != name) || fields[1].is_some_and(|uid| uid != uids[peer]) {
return Err("client information readback lacked identifying properties or named a different guest".into());
}
until("exact permitted participant properties in the Info pane", || {
viewed() && shell.get_stage() == 0 && !shell.get_menu_visible() && shell.get_title() == name && shell.get_subtitle().as_str() == info
&& labels.iter().zip(fields).all(|(label, value)| {
let model = shell.get_info();
model.iter().filter(|row| row.label.as_str() == label.as_str())
.map(|row| row.value).eq(value.map(slint::SharedString::from))
})
}).await.map_err(|e| format!("{e} ({name}, {}): {}", key.connection_id, shell.get_error()))?;
let rendered = rendered_detail_text(ui)?;
let shows = |value: &str| rendered.iter().any(|text| text.as_str() == value);
if !shows(name) || labels.iter().zip(fields).any(|(label, value)| {
shows(label) != value.is_some() || value.is_some_and(|value| !shows(value))
}) {
return Err(format!("permitted client properties for {name} did not render"));
}
}
Err(expected) if refused(&expected) => {
until("visible server refusal of the other guest's Info", || {
let state = runtime.snapshot();
viewed() && !shell.get_menu_visible() && cleared() && shell.get_error().as_str() == expected.message
&& state.last_error.as_ref().is_some_and(|err| err.code == expected.code && err.message == expected.message)
}).await?;
let mut visible = false;
headless::visit_named_items(ui.window(), |id, item| {
visible |= id == "parity-shell-error" && headless::visible_bounds(ui.window(), item).is_some()
&& item.accessible_string_property(Property::Label).is_some_and(|text| text.as_str() == expected.message);
})?;
if !visible { return Err("the server's Client Info refusal did not render".into()); }
}
Err(error) => return Err(format!("client information readback for {name}: {}", error.message)),
}
}
Ok(())
}.await;
let mut failures = Vec::new();
for tab in &tabs {
let state = manager.snapshot();
if let Some(connection) = state.get(&tab.connection_id).filter(|c| c.state != ConnectionState::Disconnected) {
if let Err(e) = pace().await { failures.push(e); }
if let Err(e) = owner.request(&connection.key, Command::Disconnect { message: None }).await {
failures.push(format!("disconnect {}: {}", tab.connection_id, e.message));
}
}
}
if let Err(e) = until("both Info fixture guests disconnected", || !runtime.snapshot().connections.any_active()).await { failures.push(e); }
if !silent() { failures.push("the muted Info fixture used an audio device".into()); }
match (exercise, failures.is_empty()) {
(result, true) => result,
(Ok(()), false) => Err(failures.join("; ")),
(Err(primary), false) => Err(format!("{primary}; cleanup: {}", failures.join("; "))),
}
}).unwrap();
}
#[test] #[test]
#[ignore = "requires the private loopback beta14 fixture"] #[ignore = "requires the private loopback beta14 fixture"]
fn participant_info_menu_rejects_a_previous_session_target() { fn participant_info_menu_rejects_a_previous_session_target() {
use super::key_profiles::until; use super::key_profiles::until;
use crate::ui::shell::{forms,Operation,ShellAction}; use crate::ui::shell::{forms,Operation,ShellAction};
use teamspeach_core::protocol::ConnectArgs; use teamspeach_core::protocol::ConnectArgs;
headless::install().unwrap(); if !headless::install_for_test() { return; }
let temp=tempfile::tempdir().unwrap();let root=temp.path().join("profile"); let temp=tempfile::tempdir().unwrap();let root=temp.path().join("profile");
initialize_native_root(&root).unwrap(); initialize_native_root(&root).unwrap();
let identities={let p=ProfileServices::open(&root).unwrap(); let identities={let p=ProfileServices::open(&root).unwrap();
@@ -672,7 +859,7 @@ fn participant_info_menu_rejects_a_previous_session_target() {
if let Some(old)=old_target.take() { if let Some(old)=old_target.take() {
assert!(!shown()); assert!(!shown());
runtime.dispatch_shell(ShellAction::Invoke{target:old,operation:Operation::ClientInfo}).map_err(|e|e.message)?; runtime.dispatch_shell(ShellAction::Invoke{target:old,operation:Operation::ClientInfo}).map_err(|e|e.message)?;
until("stale participant error",||runtime.snapshot().last_error.as_ref().is_some_and(|e|e.code=="target_changed" && shell.get_error().as_str()==e.message)).await?; // Superseded detail replies are silent; the current request below must still win.
assert!(!shown()); assert!(!shown());
} }
shell.invoke_context(own_row().unwrap().id,20.,20.); shell.invoke_context(own_row().unwrap().id,20.,20.);
@@ -800,31 +987,46 @@ fn channel_create_parent_change_drops_old_order_until_explicit_selection() {
} }
} }
async fn invoke_channel_info_menu(runtime: &AppRuntime, ui: &AppWindow, channel: &str) -> SmokeResult<()> { async fn invoke_tree_info_menu(runtime: &AppRuntime, ui: &AppWindow, title: &str, operation: crate::ui::shell::Operation) -> SmokeResult<()> {
use super::key_profiles::until; use super::{focus, key_profiles::until};
use super::focus; use crate::ui::shell::forms;
use crate::ui::shell::{Operation, forms};
use i_slint_core::{accessibility::accessible_descendents, items::AccessibleRole}; use i_slint_core::{accessibility::accessible_descendents, items::AccessibleRole};
let row = focus::visible_selector(ui, channel, AccessibleRole::ListItem)?; let row = focus::visible_selector(ui, title, AccessibleRole::ListItem)?;
let bounds = headless::visible_bounds(ui.window(), &row).ok_or("channel row is not visible")?; let bounds = headless::visible_bounds(ui.window(), &row).ok_or("tree row is not visible")?;
let position = LogicalPosition::new(bounds.origin.x + 40.0_f32.min(bounds.size.width / 2.0), bounds.center().y); let position = LogicalPosition::new(bounds.origin.x + 40.0_f32.min(bounds.size.width / 2.0), bounds.center().y);
let button = PointerEventButton::Right; let button = PointerEventButton::Right;
for event in [WindowEvent::PointerMoved { position }, WindowEvent::PointerPressed { position, button }, for event in [WindowEvent::PointerMoved { position }, WindowEvent::PointerPressed { position, button },
WindowEvent::PointerReleased { position, button }] { WindowEvent::PointerReleased { position, button }] {
ui.window().dispatch_event_with_result(event).map_err(|e| e.to_string())?; ui.window().dispatch_event_with_result(event).map_err(|e| e.to_string())?;
} }
let label = runtime.snapshot().catalog.text(forms::label_key(Operation::ChannelInfo)); let label = runtime.snapshot().catalog.text(forms::label_key(operation));
let mut action = None; let mut result = None;
until("Channel Info in the channel's context menu", || { let mut scrolls = 0;
action = focus::visible_selector(ui, channel, AccessibleRole::List).ok().and_then(|popup| { until(&format!("{label} in {title}'s context menu"), || {
accessible_descendents(&popup).find(|item| item.accessible_role() == AccessibleRole::Button let Ok(popup) = focus::visible_selector(ui, title, AccessibleRole::List) else { return false; };
&& item.accessible_string_property(Property::Label).is_some_and(|value| value == label) let Some(bounds) = headless::visible_bounds(ui.window(), &popup) else { return false; };
&& headless::visible_bounds(ui.window(), item).is_some()) let action = accessible_descendents(&popup).find(|item| item.accessible_role() == AccessibleRole::Button
}); && item.accessible_string_property(Property::Label).is_some_and(|value| value == label)
action.is_some() && headless::visible_bounds(ui.window(), item).is_some_and(|row| {
let y = row.center().y;
y >= bounds.origin.y + 30.0 && y < bounds.origin.y + bounds.size.height
}));
if let Some(action) = action {
result = Some(focus::activate(action));
} else if scrolls == 10 {
result = Some(Err(format!("missing visible {label} action for {title}")));
} else {
// Participant menus can place Info below the clipped menu viewport.
let position = LogicalPosition::new(bounds.center().x, bounds.center().y);
if let Err(e) = ui.window().dispatch_event_with_result(WindowEvent::PointerScrolled { position, delta_x: 0.0, delta_y: -160.0 }) {
result = Some(Err(e.to_string()));
}
scrolls += 1;
}
result.is_some()
}).await?; }).await?;
focus::activate(action.ok_or("missing Channel Info action")?) result.ok_or("missing menu activation result")?
} }
fn rendered_detail_text(ui: &AppWindow) -> SmokeResult<Vec<slint::SharedString>> { fn rendered_detail_text(ui: &AppWindow) -> SmokeResult<Vec<slint::SharedString>> {
@@ -978,7 +1180,7 @@ fn channel_create_from_toolbar_and_edit_on_beta14() {
c.key == key && c.selected_channel_id == Some(channel_id) c.key == key && c.selected_channel_id == Some(channel_id)
&& c.server.as_ref().is_some_and(|server| server["own_channel_id"] == joined_channel))).await?; && c.server.as_ref().is_some_and(|server| server["own_channel_id"] == joined_channel))).await?;
quiet().await?; quiet().await?;
invoke_channel_info_menu(runtime, ui, channel_name).await?; invoke_tree_info_menu(runtime, ui, channel_name, Operation::ChannelInfo).await?;
until("Channel Info details for the selected menu target", || { until("Channel Info details for the selected menu target", || {
let state = runtime.snapshot(); let state = runtime.snapshot();
shell.get_stage() == 0 && !shell.get_menu_visible() && shell.get_title() == channel_name shell.get_stage() == 0 && !shell.get_menu_visible() && shell.get_title() == channel_name
+5 -3
View File
@@ -37,9 +37,11 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)) else{return}; let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)) else{return};
let result=match action { let result=match action {
shell::ShellAction::DiscoverChannelStreams{key,visit}=>runtime.enqueue(crate::app::runtime::RuntimeCommand::DiscoverChannelStreams{key,visit,ui_generation:generation}), shell::ShellAction::DiscoverChannelStreams{key,visit}=>runtime.enqueue(crate::app::runtime::RuntimeCommand::DiscoverChannelStreams{key,visit,ui_generation:generation}),
action if matches!(&action,shell::ShellAction::Invoke{operation,..}|shell::ShellAction::Submit{operation,..} action if matches!(&action,shell::ShellAction::Invoke{operation,..}
if matches!(operation,shell::Operation::SnapshotApply|shell::Operation::SnapshotExport|shell::Operation::SnapshotCancel))=>{ if crate::app::runtime::scoped_detail_query(*operation))
runtime.enqueue(crate::app::runtime::RuntimeCommand::SnapshotShell{action,ui_generation:generation}) || matches!(&action,shell::ShellAction::Invoke{operation,..}|shell::ShellAction::Submit{operation,..}
if matches!(operation,shell::Operation::SnapshotApply|shell::Operation::SnapshotExport|shell::Operation::SnapshotCancel))=>{
runtime.enqueue(crate::app::runtime::RuntimeCommand::AttachmentShell{action,ui_generation:generation})
}, },
action=>runtime.dispatch_shell(action), action=>runtime.dispatch_shell(action),
}; };