BlueGit

ict rusty-teams

fix(calls): do not park the Teams tab under a running write or a live call

- park of the Teams tab (60 s after every load) destroyed the page context of in-flight Runtime.evaluate writes; WebView2 reports that protocol error as E_INVALIDARG
- park now waits while a protocol call of that tab is in flight or a call holds the tab (Session::hold_tab, held from dial to end)
- protocol failures name the CDP message and code, method, params size, coarse tab state and calls in flight; no URL, params or tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-04 · 3 weeks ago

Hash
3afeb53015650baad597f774c7b65fd2d76affd4
Parent
4a422910
9 files changed +322 −19
crates/calling/src/call.rs +1 −0
@@ -441,6 +441,7 @@ impl CallEngine {
441 441 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
442 442 let inner = self.inner.as_ref();
443 443 let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };
444 let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);
444 445 let timeline = Timeline::new(options.trace);
445 446 let mut report = CallReport::default();
446 447 let mut state = CallState::Idle;
@@ -441,6 +441,7 @@ impl CallEngine {
441 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
441 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
442 let inner = self.inner.as_ref();
442 let inner = self.inner.as_ref();
443 let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };
443 let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };
444 let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);
444 let timeline = Timeline::new(options.trace);
445 let timeline = Timeline::new(options.trace);
445 let mut report = CallReport::default();
446 let mut report = CallReport::default();
446 let mut state = CallState::Idle;
447 let mut state = CallState::Idle;
crates/session/src/lib.rs +1 −1
@@ -14,5 +14,5 @@ pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
14 14 pub use page_script::token_acquirer_script;
15 15 pub use request::{ApiResponse, BodyToken, Method, Request};
16 16 pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};
17 pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};
17 pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
18 18 pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
@@ -14,5 +14,5 @@ pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
14pub use page_script::token_acquirer_script;
14pub use page_script::token_acquirer_script;
15pub use request::{ApiResponse, BodyToken, Method, Request};
15pub use request::{ApiResponse, BodyToken, Method, Request};
16pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};
16pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};
17pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};
17pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
18pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
18pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
crates/session/src/session.rs +60 −0
@@ -139,6 +139,15 @@ impl Session {
139 139 Ok(results.into_iter().flatten().collect())
140 140 }
141 141
142 /// Keeps the app tab where it is until the guard drops, e.g. for the length of a call.
143 pub fn hold_tab(&self, app: App) -> TabHold {
144 self.transport.hold(app, true);
145 TabHold {
146 transport: self.transport.clone(),
147 app,
148 }
149 }
150
142 151 pub async fn close(&self) {
143 152 self.drop_all().await;
144 153 }
@@ -270,6 +279,17 @@ impl Session {
270 279 }
271 280 }
272 281
282 pub struct TabHold {
283 transport: Arc<dyn Transport>,
284 app: App,
285 }
286
287 impl Drop for TabHold {
288 fn drop(&mut self) {
289 self.transport.hold(self.app, false);
290 }
291 }
292
273 293 pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
274 294 header
275 295 .and_then(|value| value.trim().parse::<f64>().ok())
@@ -280,7 +300,47 @@ pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
280 300
281 301 #[cfg(test)]
282 302 mod tests {
303 use std::sync::Mutex as StdMutex;
304
283 305 use super::*;
306 use crate::transport::{BoxFuture, Diagnosis, OpenedTab};
307
308 #[derive(Default)]
309 struct HoldRecorder {
310 holds: StdMutex<Vec<(App, bool)>>,
311 }
312
313 impl Transport for HoldRecorder {
314 fn check(&self) -> BoxFuture<'_, Result<()>> {
315 Box::pin(async { Ok(()) })
316 }
317
318 fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
319 Box::pin(async { Ok(None) })
320 }
321
322 fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> {
323 Box::pin(async { Ok(()) })
324 }
325
326 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
327 Box::pin(async { Ok(Diagnosis::default()) })
328 }
329
330 fn hold(&self, app: App, held: bool) {
331 self.holds.lock().unwrap().push((app, held));
332 }
333 }
334
335 #[tokio::test]
336 async fn tab_hold_releases_the_tab_when_dropped() {
337 let recorder = Arc::new(HoldRecorder::default());
338 let session = Session::with_transport(recorder.clone(), SessionConfig::default()).await.unwrap();
339 let hold = session.hold_tab(App::Teams);
340 assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]);
341 drop(hold);
342 assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true), (App::Teams, false)]);
343 }
284 344
285 345 #[test]
286 346 fn retry_after_seconds_parse() {
@@ -139,6 +139,15 @@ impl Session {
139 Ok(results.into_iter().flatten().collect())
139 Ok(results.into_iter().flatten().collect())
140 }
140 }
141
141
142 /// Keeps the app tab where it is until the guard drops, e.g. for the length of a call.
143 pub fn hold_tab(&self, app: App) -> TabHold {
144 self.transport.hold(app, true);
145 TabHold {
146 transport: self.transport.clone(),
147 app,
148 }
149 }
150
142 pub async fn close(&self) {
151 pub async fn close(&self) {
143 self.drop_all().await;
152 self.drop_all().await;
144 }
153 }
@@ -270,6 +279,17 @@ impl Session {
270 }
279 }
271}
280}
272
281
282pub struct TabHold {
283 transport: Arc<dyn Transport>,
284 app: App,
285}
286
287impl Drop for TabHold {
288 fn drop(&mut self) {
289 self.transport.hold(self.app, false);
290 }
291}
292
273pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
293pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
274 header
294 header
275 .and_then(|value| value.trim().parse::<f64>().ok())
295 .and_then(|value| value.trim().parse::<f64>().ok())
@@ -280,7 +300,47 @@ pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
280
300
281#[cfg(test)]
301#[cfg(test)]
282mod tests {
302mod tests {
303 use std::sync::Mutex as StdMutex;
304
283 use super::*;
305 use super::*;
306 use crate::transport::{BoxFuture, Diagnosis, OpenedTab};
307
308 #[derive(Default)]
309 struct HoldRecorder {
310 holds: StdMutex<Vec<(App, bool)>>,
311 }
312
313 impl Transport for HoldRecorder {
314 fn check(&self) -> BoxFuture<'_, Result<()>> {
315 Box::pin(async { Ok(()) })
316 }
317
318 fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
319 Box::pin(async { Ok(None) })
320 }
321
322 fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> {
323 Box::pin(async { Ok(()) })
324 }
325
326 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
327 Box::pin(async { Ok(Diagnosis::default()) })
328 }
329
330 fn hold(&self, app: App, held: bool) {
331 self.holds.lock().unwrap().push((app, held));
332 }
333 }
334
335 #[tokio::test]
336 async fn tab_hold_releases_the_tab_when_dropped() {
337 let recorder = Arc::new(HoldRecorder::default());
338 let session = Session::with_transport(recorder.clone(), SessionConfig::default()).await.unwrap();
339 let hold = session.hold_tab(App::Teams);
340 assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]);
341 drop(hold);
342 assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true), (App::Teams, false)]);
343 }
284
344
285 #[test]
345 #[test]
286 fn retry_after_seconds_parse() {
346 fn retry_after_seconds_parse() {
crates/session/src/transport.rs +3 −0
@@ -28,6 +28,9 @@ pub trait Transport: Send + Sync {
28 28 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;
29 29
30 30 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
31
32 /// While held the host must not navigate the app on its own (no parking).
33 fn hold(&self, _app: App, _held: bool) {}
31 34 }
32 35
33 36 pub struct CdpTransport {
@@ -28,6 +28,9 @@ pub trait Transport: Send + Sync {
28 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;
28 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;
29
29
30 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
30 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
31
32 /// While held the host must not navigate the app on its own (no parking).
33 fn hold(&self, _app: App, _held: bool) {}
31}
34}
32
35
33pub struct CdpTransport {
36pub struct CdpTransport {
crates/webview/src/cdp_failure.rs added +93 −0
@@ -0,0 +1,93 @@
1 use serde_json::Value;
2 use session::{App, is_login_url};
3
4 /// Coarse state of the app tab for error reports, never the URL itself.
5 pub(crate) fn tab_state(app: App, url: &str) -> &'static str {
6 if url.is_empty() {
7 "no document"
8 } else if app.is_park_url(url) {
9 "parked"
10 } else if is_login_url(url) {
11 "login"
12 } else if app.origins().iter().any(|origin| url.starts_with(origin)) {
13 "app"
14 } else if url.starts_with("about:") {
15 "about"
16 } else if url.starts_with("chrome-error:") {
17 "error page"
18 } else {
19 "other"
20 }
21 }
22
23 pub(crate) struct CallContext<'a> {
24 pub method: &'a str,
25 pub params_bytes: usize,
26 pub tab: &'static str,
27 pub in_flight: usize,
28 }
29
30 /// WebView2 answers every protocol error with E_INVALIDARG; the protocol's own error sits in the JSON.
31 pub(crate) fn failure_reason(context: &CallContext, hresult: &str, json: &str) -> String {
32 let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);
33 let error = parsed.get("error").unwrap_or(&parsed);
34 let message = error.get("message").and_then(Value::as_str).unwrap_or(hresult);
35 let code = error
36 .get("code")
37 .and_then(Value::as_i64)
38 .map(|code| format!(" code {code},"))
39 .unwrap_or_default();
40 format!(
41 "{message} [{}{code} params {} bytes, tab {}, {} call(s) in flight]",
42 context.method, context.params_bytes, context.tab, context.in_flight,
43 )
44 }
45
46 #[cfg(test)]
47 mod tests {
48 use super::*;
49
50 const HRESULT: &str = "The parameter is incorrect. (0x80070057)";
51
52 fn context() -> CallContext<'static> {
53 CallContext {
54 method: "Runtime.evaluate",
55 params_bytes: 48213,
56 tab: "parked",
57 in_flight: 2,
58 }
59 }
60
61 #[test]
62 fn the_protocol_message_leads_the_reason() {
63 let json = r#"{"code":-32000,"message":"Execution context was destroyed."}"#;
64 assert_eq!(
65 failure_reason(&context(), HRESULT, json),
66 "Execution context was destroyed. [Runtime.evaluate code -32000, params 48213 bytes, tab parked, 2 call(s) in flight]"
67 );
68 }
69
70 #[test]
71 fn a_nested_protocol_error_is_read_too() {
72 let json = r#"{"error":{"code":-32601,"message":"'Foo.bar' wasn't found"}}"#;
73 assert!(failure_reason(&context(), HRESULT, json).starts_with("'Foo.bar' wasn't found [Runtime.evaluate code -32601,"));
74 }
75
76 #[test]
77 fn without_a_protocol_error_the_hresult_and_the_call_are_named() {
78 assert_eq!(
79 failure_reason(&context(), HRESULT, ""),
80 "The parameter is incorrect. (0x80070057) [Runtime.evaluate params 48213 bytes, tab parked, 2 call(s) in flight]"
81 );
82 }
83
84 #[test]
85 fn the_tab_state_never_carries_the_url() {
86 assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/robots.txt"), "parked");
87 assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/v2/?ctx=chat"), "app");
88 assert_eq!(tab_state(App::Teams, "about:blank"), "about");
89 assert_eq!(tab_state(App::Teams, "chrome-error://chromewebdata/"), "error page");
90 assert_eq!(tab_state(App::Teams, ""), "no document");
91 assert_eq!(tab_state(App::Teams, "https://example.com/private/path"), "other");
92 }
93 }
@@ -0,0 +1,93 @@
1use serde_json::Value;
2use session::{App, is_login_url};
3
4/// Coarse state of the app tab for error reports, never the URL itself.
5pub(crate) fn tab_state(app: App, url: &str) -> &'static str {
6 if url.is_empty() {
7 "no document"
8 } else if app.is_park_url(url) {
9 "parked"
10 } else if is_login_url(url) {
11 "login"
12 } else if app.origins().iter().any(|origin| url.starts_with(origin)) {
13 "app"
14 } else if url.starts_with("about:") {
15 "about"
16 } else if url.starts_with("chrome-error:") {
17 "error page"
18 } else {
19 "other"
20 }
21}
22
23pub(crate) struct CallContext<'a> {
24 pub method: &'a str,
25 pub params_bytes: usize,
26 pub tab: &'static str,
27 pub in_flight: usize,
28}
29
30/// WebView2 answers every protocol error with E_INVALIDARG; the protocol's own error sits in the JSON.
31pub(crate) fn failure_reason(context: &CallContext, hresult: &str, json: &str) -> String {
32 let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);
33 let error = parsed.get("error").unwrap_or(&parsed);
34 let message = error.get("message").and_then(Value::as_str).unwrap_or(hresult);
35 let code = error
36 .get("code")
37 .and_then(Value::as_i64)
38 .map(|code| format!(" code {code},"))
39 .unwrap_or_default();
40 format!(
41 "{message} [{}{code} params {} bytes, tab {}, {} call(s) in flight]",
42 context.method, context.params_bytes, context.tab, context.in_flight,
43 )
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 const HRESULT: &str = "The parameter is incorrect. (0x80070057)";
51
52 fn context() -> CallContext<'static> {
53 CallContext {
54 method: "Runtime.evaluate",
55 params_bytes: 48213,
56 tab: "parked",
57 in_flight: 2,
58 }
59 }
60
61 #[test]
62 fn the_protocol_message_leads_the_reason() {
63 let json = r#"{"code":-32000,"message":"Execution context was destroyed."}"#;
64 assert_eq!(
65 failure_reason(&context(), HRESULT, json),
66 "Execution context was destroyed. [Runtime.evaluate code -32000, params 48213 bytes, tab parked, 2 call(s) in flight]"
67 );
68 }
69
70 #[test]
71 fn a_nested_protocol_error_is_read_too() {
72 let json = r#"{"error":{"code":-32601,"message":"'Foo.bar' wasn't found"}}"#;
73 assert!(failure_reason(&context(), HRESULT, json).starts_with("'Foo.bar' wasn't found [Runtime.evaluate code -32601,"));
74 }
75
76 #[test]
77 fn without_a_protocol_error_the_hresult_and_the_call_are_named() {
78 assert_eq!(
79 failure_reason(&context(), HRESULT, ""),
80 "The parameter is incorrect. (0x80070057) [Runtime.evaluate params 48213 bytes, tab parked, 2 call(s) in flight]"
81 );
82 }
83
84 #[test]
85 fn the_tab_state_never_carries_the_url() {
86 assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/robots.txt"), "parked");
87 assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/v2/?ctx=chat"), "app");
88 assert_eq!(tab_state(App::Teams, "about:blank"), "about");
89 assert_eq!(tab_state(App::Teams, "chrome-error://chromewebdata/"), "error page");
90 assert_eq!(tab_state(App::Teams, ""), "no document");
91 assert_eq!(tab_state(App::Teams, "https://example.com/private/path"), "other");
92 }
93}
crates/webview/src/host.rs +49 −18
@@ -6,7 +6,7 @@ use std::sync::{Arc, mpsc};
6 6 use std::time::{Duration, Instant};
7 7
8 8 use serde_json::Value;
9 use session::{App, Error, Result, TabCommand, TabEvent, is_login_url};
9 use session::{App, Error, TabCommand, TabEvent, is_login_url};
10 10 use tokio::sync::watch;
11 11 use webview2_com::Microsoft::Web::WebView2::Win32::*;
12 12 use webview2_com::{
@@ -21,8 +21,10 @@ use windows::Win32::System::LibraryLoader::GetModuleHandleW;
21 21 use windows::Win32::UI::WindowsAndMessaging::*;
22 22 use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23 23
24 use crate::cdp_failure::{CallContext, failure_reason, tab_state};
24 25 use crate::fanout::Subscribers;
25 26 use crate::host_dialog::{self, Dialog};
27 use crate::park::{ParkDecision, ParkGate};
26 28 use crate::transport::{HostState, UiRequest, WebViewTransport};
27 29 use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28 30
@@ -55,6 +57,7 @@ pub(crate) struct Shared {
55 57 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56 58 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
57 59 subscribers: RefCell<Subscribers>,
60 park_gate: RefCell<ParkGate>,
58 61 state: watch::Sender<HostState>,
59 62 requests: mpsc::Receiver<UiRequest>,
60 63 restarting: Cell<bool>,
@@ -115,6 +118,7 @@ fn run(
115 118 environment: RefCell::new(None),
116 119 dialogs: RefCell::new(HashMap::new()),
117 120 subscribers: RefCell::new(Subscribers::default()),
121 park_gate: RefCell::new(ParkGate::default()),
118 122 state,
119 123 requests,
120 124 restarting: Cell::new(false),
@@ -426,6 +430,7 @@ fn drain(shared: &Rc<Shared>) {
426 430 UiRequest::Call { app, command } => call(shared, app, command),
427 431 UiRequest::Subscribe { app, sink } => shared.subscribers.borrow_mut().add(app, sink),
428 432 UiRequest::Wake { app } => wake(shared, app),
433 UiRequest::Hold { app, held } => shared.park_gate.borrow_mut().hold(app, held),
429 434 UiRequest::Retry => {
430 435 if !shared.state.borrow().ready && !shared.restarting.replace(true) {
431 436 restart(shared);
@@ -443,14 +448,30 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
443 448 let Some(webview) = webview_of(shared, app) else {
444 449 return command.respond(Err(Error::Cdp("webview is restarting".into())));
445 450 };
451 let parameters_json = command.params.to_string();
452 let parameters_bytes = parameters_json.len();
446 453 let method = HSTRING::from(command.method.as_str());
447 let parameters = HSTRING::from(command.params.to_string());
454 let parameters = HSTRING::from(parameters_json);
448 455 let pending = Rc::new(RefCell::new(Some(command)));
449 456 let answered = pending.clone();
457 shared.park_gate.borrow_mut().command_started(app);
450 458 let handler =
451 459 CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {
452 460 if let Some(command) = answered.borrow_mut().take() {
453 command.respond(answer(code, &json));
461 let result = match code {
462 Ok(()) => Ok(serde_json::from_str(&json).unwrap_or(Value::Null)),
463 Err(error) => Err(Error::Cdp(describe_failure(
464 app,
465 &command.method,
466 parameters_bytes,
467 &error.to_string(),
468 &json,
469 ))),
470 };
471 if let Some(shared) = self::shared() {
472 shared.park_gate.borrow_mut().command_finished(app);
473 }
474 command.respond(result);
454 475 }
455 476 Ok(())
456 477 }));
@@ -458,24 +479,27 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
458 479 unsafe { webview.CallDevToolsProtocolMethod(&method, &parameters, &handler) }
459 480 && let Some(command) = pending.borrow_mut().take()
460 481 {
461 let reason = format!("{}: {error}", command.method);
482 let reason = describe_failure(app, &command.method, parameters_bytes, &error.to_string(), "");
483 shared.park_gate.borrow_mut().command_finished(app);
462 484 command.respond(Err(Error::Cdp(reason)));
463 485 }
464 486 }
465 487
466 fn answer(code: windows::core::Result<()>, json: &str) -> Result<Value> {
467 let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);
468 match code {
469 Ok(()) => Ok(parsed),
470 Err(error) => {
471 let reason = parsed
472 .get("message")
473 .and_then(Value::as_str)
474 .map(str::to_owned)
475 .unwrap_or_else(|| error.to_string());
476 Err(Error::Cdp(reason))
477 }
478 }
488 fn describe_failure(app: App, method: &str, parameters_bytes: usize, hresult: &str, json: &str) -> String {
489 let (tab, in_flight) = match shared() {
490 Some(shared) => (
491 tab_state(app, &current_url(&shared, app)),
492 shared.park_gate.borrow().in_flight(app),
493 ),
494 None => ("unknown", 0),
495 };
496 let context = CallContext {
497 method,
498 params_bytes: parameters_bytes,
499 tab,
500 in_flight,
501 };
502 failure_reason(&context, hresult, json)
479 503 }
480 504
481 505 fn wake(shared: &Shared, app: App) {
@@ -523,6 +547,7 @@ fn show(shared: &Shared, app: App) {
523 547 fn restart(shared: &Rc<Shared>) {
524 548 shared.state.send_modify(|state| state.ready = false);
525 549 shared.subscribers.borrow_mut().clear();
550 shared.park_gate.borrow_mut().forget_commands();
526 551 host_dialog::close_all(shared);
527 552 let views: Vec<View> = shared
528 553 .views
@@ -590,7 +615,13 @@ extern "system" fn window_procedure(
590 615 let _ = KillTimer(Some(window), PARK_TIMER);
591 616 }
592 617 if let Some(app) = app_of(&shared, window) {
593 park(&shared, app);
618 let decision = shared.park_gate.borrow().decide(app);
619 match decision {
620 ParkDecision::Park => park(&shared, app),
621 ParkDecision::Wait => unsafe {
622 SetTimer(Some(window), PARK_TIMER, PARK_DELAY_MS, None);
623 },
624 }
594 625 }
595 626 }
596 627 WM_CLOSE => unsafe {
@@ -6,7 +6,7 @@ use std::sync::{Arc, mpsc};
6use std::time::{Duration, Instant};
6use std::time::{Duration, Instant};
7
7
8use serde_json::Value;
8use serde_json::Value;
9use session::{App, Error, Result, TabCommand, TabEvent, is_login_url};
9use session::{App, Error, TabCommand, TabEvent, is_login_url};
10use tokio::sync::watch;
10use tokio::sync::watch;
11use webview2_com::Microsoft::Web::WebView2::Win32::*;
11use webview2_com::Microsoft::Web::WebView2::Win32::*;
12use webview2_com::{
12use webview2_com::{
@@ -21,8 +21,10 @@ use windows::Win32::System::LibraryLoader::GetModuleHandleW;
21use windows::Win32::UI::WindowsAndMessaging::*;
21use windows::Win32::UI::WindowsAndMessaging::*;
22use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
22use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23
23
24use crate::cdp_failure::{CallContext, failure_reason, tab_state};
24use crate::fanout::Subscribers;
25use crate::fanout::Subscribers;
25use crate::host_dialog::{self, Dialog};
26use crate::host_dialog::{self, Dialog};
27use crate::park::{ParkDecision, ParkGate};
26use crate::transport::{HostState, UiRequest, WebViewTransport};
28use crate::transport::{HostState, UiRequest, WebViewTransport};
27use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
29use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28
30
@@ -55,6 +57,7 @@ pub(crate) struct Shared {
55 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
57 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
58 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
57 subscribers: RefCell<Subscribers>,
59 subscribers: RefCell<Subscribers>,
60 park_gate: RefCell<ParkGate>,
58 state: watch::Sender<HostState>,
61 state: watch::Sender<HostState>,
59 requests: mpsc::Receiver<UiRequest>,
62 requests: mpsc::Receiver<UiRequest>,
60 restarting: Cell<bool>,
63 restarting: Cell<bool>,
@@ -115,6 +118,7 @@ fn run(
115 environment: RefCell::new(None),
118 environment: RefCell::new(None),
116 dialogs: RefCell::new(HashMap::new()),
119 dialogs: RefCell::new(HashMap::new()),
117 subscribers: RefCell::new(Subscribers::default()),
120 subscribers: RefCell::new(Subscribers::default()),
121 park_gate: RefCell::new(ParkGate::default()),
118 state,
122 state,
119 requests,
123 requests,
120 restarting: Cell::new(false),
124 restarting: Cell::new(false),
@@ -426,6 +430,7 @@ fn drain(shared: &Rc<Shared>) {
426 UiRequest::Call { app, command } => call(shared, app, command),
430 UiRequest::Call { app, command } => call(shared, app, command),
427 UiRequest::Subscribe { app, sink } => shared.subscribers.borrow_mut().add(app, sink),
431 UiRequest::Subscribe { app, sink } => shared.subscribers.borrow_mut().add(app, sink),
428 UiRequest::Wake { app } => wake(shared, app),
432 UiRequest::Wake { app } => wake(shared, app),
433 UiRequest::Hold { app, held } => shared.park_gate.borrow_mut().hold(app, held),
429 UiRequest::Retry => {
434 UiRequest::Retry => {
430 if !shared.state.borrow().ready && !shared.restarting.replace(true) {
435 if !shared.state.borrow().ready && !shared.restarting.replace(true) {
431 restart(shared);
436 restart(shared);
@@ -443,14 +448,30 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
443 let Some(webview) = webview_of(shared, app) else {
448 let Some(webview) = webview_of(shared, app) else {
444 return command.respond(Err(Error::Cdp("webview is restarting".into())));
449 return command.respond(Err(Error::Cdp("webview is restarting".into())));
445 };
450 };
451 let parameters_json = command.params.to_string();
452 let parameters_bytes = parameters_json.len();
446 let method = HSTRING::from(command.method.as_str());
453 let method = HSTRING::from(command.method.as_str());
447 let parameters = HSTRING::from(command.params.to_string());
454 let parameters = HSTRING::from(parameters_json);
448 let pending = Rc::new(RefCell::new(Some(command)));
455 let pending = Rc::new(RefCell::new(Some(command)));
449 let answered = pending.clone();
456 let answered = pending.clone();
457 shared.park_gate.borrow_mut().command_started(app);
450 let handler =
458 let handler =
451 CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {
459 CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {
452 if let Some(command) = answered.borrow_mut().take() {
460 if let Some(command) = answered.borrow_mut().take() {
453 command.respond(answer(code, &json));
461 let result = match code {
462 Ok(()) => Ok(serde_json::from_str(&json).unwrap_or(Value::Null)),
463 Err(error) => Err(Error::Cdp(describe_failure(
464 app,
465 &command.method,
466 parameters_bytes,
467 &error.to_string(),
468 &json,
469 ))),
470 };
471 if let Some(shared) = self::shared() {
472 shared.park_gate.borrow_mut().command_finished(app);
473 }
474 command.respond(result);
454 }
475 }
455 Ok(())
476 Ok(())
456 }));
477 }));
@@ -458,24 +479,27 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
458 unsafe { webview.CallDevToolsProtocolMethod(&method, &parameters, &handler) }
479 unsafe { webview.CallDevToolsProtocolMethod(&method, &parameters, &handler) }
459 && let Some(command) = pending.borrow_mut().take()
480 && let Some(command) = pending.borrow_mut().take()
460 {
481 {
461 let reason = format!("{}: {error}", command.method);
482 let reason = describe_failure(app, &command.method, parameters_bytes, &error.to_string(), "");
483 shared.park_gate.borrow_mut().command_finished(app);
462 command.respond(Err(Error::Cdp(reason)));
484 command.respond(Err(Error::Cdp(reason)));
463 }
485 }
464}
486}
465
487
466fn answer(code: windows::core::Result<()>, json: &str) -> Result<Value> {
488fn describe_failure(app: App, method: &str, parameters_bytes: usize, hresult: &str, json: &str) -> String {
467 let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);
489 let (tab, in_flight) = match shared() {
468 match code {
490 Some(shared) => (
469 Ok(()) => Ok(parsed),
491 tab_state(app, &current_url(&shared, app)),
470 Err(error) => {
492 shared.park_gate.borrow().in_flight(app),
471 let reason = parsed
493 ),
472 .get("message")
494 None => ("unknown", 0),
473 .and_then(Value::as_str)
495 };
474 .map(str::to_owned)
496 let context = CallContext {
475 .unwrap_or_else(|| error.to_string());
497 method,
476 Err(Error::Cdp(reason))
498 params_bytes: parameters_bytes,
477 }
499 tab,
478 }
500 in_flight,
501 };
502 failure_reason(&context, hresult, json)
479}
503}
480
504
481fn wake(shared: &Shared, app: App) {
505fn wake(shared: &Shared, app: App) {
@@ -523,6 +547,7 @@ fn show(shared: &Shared, app: App) {
523fn restart(shared: &Rc<Shared>) {
547fn restart(shared: &Rc<Shared>) {
524 shared.state.send_modify(|state| state.ready = false);
548 shared.state.send_modify(|state| state.ready = false);
525 shared.subscribers.borrow_mut().clear();
549 shared.subscribers.borrow_mut().clear();
550 shared.park_gate.borrow_mut().forget_commands();
526 host_dialog::close_all(shared);
551 host_dialog::close_all(shared);
527 let views: Vec<View> = shared
552 let views: Vec<View> = shared
528 .views
553 .views
@@ -590,7 +615,13 @@ extern "system" fn window_procedure(
590 let _ = KillTimer(Some(window), PARK_TIMER);
615 let _ = KillTimer(Some(window), PARK_TIMER);
591 }
616 }
592 if let Some(app) = app_of(&shared, window) {
617 if let Some(app) = app_of(&shared, window) {
593 park(&shared, app);
618 let decision = shared.park_gate.borrow().decide(app);
619 match decision {
620 ParkDecision::Park => park(&shared, app),
621 ParkDecision::Wait => unsafe {
622 SetTimer(Some(window), PARK_TIMER, PARK_DELAY_MS, None);
623 },
624 }
594 }
625 }
595 }
626 }
596 WM_CLOSE => unsafe {
627 WM_CLOSE => unsafe {
crates/webview/src/lib.rs +4 −0
@@ -1,3 +1,5 @@
1 #[cfg(any(windows, test))]
2 mod cdp_failure;
1 3 #[cfg(windows)]
2 4 mod dialog;
3 5 #[cfg(windows)]
@@ -11,6 +13,8 @@ mod host;
11 13 mod host_dialog;
12 14 #[cfg(windows)]
13 15 mod main_embed;
16 #[cfg(any(windows, test))]
17 mod park;
14 18 #[cfg(windows)]
15 19 mod transport;
16 20
@@ -1,3 +1,5 @@
1#[cfg(any(windows, test))]
2mod cdp_failure;
1#[cfg(windows)]
3#[cfg(windows)]
2mod dialog;
4mod dialog;
3#[cfg(windows)]
5#[cfg(windows)]
@@ -11,6 +13,8 @@ mod host;
11mod host_dialog;
13mod host_dialog;
12#[cfg(windows)]
14#[cfg(windows)]
13mod main_embed;
15mod main_embed;
16#[cfg(any(windows, test))]
17mod park;
14#[cfg(windows)]
18#[cfg(windows)]
15mod transport;
19mod transport;
16
20
crates/webview/src/park.rs added +103 −0
@@ -0,0 +1,103 @@
1 use std::collections::HashMap;
2
3 use session::App;
4
5 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6 pub(crate) enum ParkDecision {
7 Park,
8 Wait,
9 }
10
11 /// A navigation of the app tab destroys the page context of every running protocol call
12 /// and the Trouter sockets of a live call, so parking waits until the tab is idle.
13 #[derive(Debug, Default)]
14 pub(crate) struct ParkGate {
15 holds: HashMap<App, usize>,
16 in_flight: HashMap<App, usize>,
17 }
18
19 impl ParkGate {
20 pub(crate) fn hold(&mut self, app: App, held: bool) {
21 adjust(&mut self.holds, app, held);
22 }
23
24 pub(crate) fn command_started(&mut self, app: App) {
25 adjust(&mut self.in_flight, app, true);
26 }
27
28 pub(crate) fn command_finished(&mut self, app: App) {
29 adjust(&mut self.in_flight, app, false);
30 }
31
32 pub(crate) fn forget_commands(&mut self) {
33 self.in_flight.clear();
34 }
35
36 pub(crate) fn in_flight(&self, app: App) -> usize {
37 self.in_flight.get(&app).copied().unwrap_or(0)
38 }
39
40 pub(crate) fn decide(&self, app: App) -> ParkDecision {
41 let held = self.holds.get(&app).copied().unwrap_or(0) > 0;
42 if held || self.in_flight(app) > 0 {
43 ParkDecision::Wait
44 } else {
45 ParkDecision::Park
46 }
47 }
48 }
49
50 fn adjust(counts: &mut HashMap<App, usize>, app: App, up: bool) {
51 let count = counts.entry(app).or_default();
52 *count = if up { *count + 1 } else { count.saturating_sub(1) };
53 }
54
55 #[cfg(test)]
56 mod tests {
57 use super::*;
58
59 #[test]
60 fn an_idle_tab_parks() {
61 assert_eq!(ParkGate::default().decide(App::Teams), ParkDecision::Park);
62 }
63
64 #[test]
65 fn a_running_command_delays_the_park_until_it_answers() {
66 let mut gate = ParkGate::default();
67 gate.command_started(App::Teams);
68 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
69 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
70 gate.command_finished(App::Teams);
71 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
72 }
73
74 #[test]
75 fn a_held_tab_waits_for_every_hold_to_end() {
76 let mut gate = ParkGate::default();
77 gate.hold(App::Teams, true);
78 gate.hold(App::Teams, true);
79 gate.hold(App::Teams, false);
80 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
81 gate.hold(App::Teams, false);
82 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
83 }
84
85 #[test]
86 fn extra_releases_do_not_underflow() {
87 let mut gate = ParkGate::default();
88 gate.hold(App::Teams, false);
89 gate.command_finished(App::Teams);
90 gate.hold(App::Teams, true);
91 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
92 }
93
94 #[test]
95 fn a_restart_forgets_unanswered_commands_but_keeps_holds() {
96 let mut gate = ParkGate::default();
97 gate.command_started(App::Outlook);
98 gate.hold(App::Teams, true);
99 gate.forget_commands();
100 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
101 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
102 }
103 }
@@ -0,0 +1,103 @@
1use std::collections::HashMap;
2
3use session::App;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub(crate) enum ParkDecision {
7 Park,
8 Wait,
9}
10
11/// A navigation of the app tab destroys the page context of every running protocol call
12/// and the Trouter sockets of a live call, so parking waits until the tab is idle.
13#[derive(Debug, Default)]
14pub(crate) struct ParkGate {
15 holds: HashMap<App, usize>,
16 in_flight: HashMap<App, usize>,
17}
18
19impl ParkGate {
20 pub(crate) fn hold(&mut self, app: App, held: bool) {
21 adjust(&mut self.holds, app, held);
22 }
23
24 pub(crate) fn command_started(&mut self, app: App) {
25 adjust(&mut self.in_flight, app, true);
26 }
27
28 pub(crate) fn command_finished(&mut self, app: App) {
29 adjust(&mut self.in_flight, app, false);
30 }
31
32 pub(crate) fn forget_commands(&mut self) {
33 self.in_flight.clear();
34 }
35
36 pub(crate) fn in_flight(&self, app: App) -> usize {
37 self.in_flight.get(&app).copied().unwrap_or(0)
38 }
39
40 pub(crate) fn decide(&self, app: App) -> ParkDecision {
41 let held = self.holds.get(&app).copied().unwrap_or(0) > 0;
42 if held || self.in_flight(app) > 0 {
43 ParkDecision::Wait
44 } else {
45 ParkDecision::Park
46 }
47 }
48}
49
50fn adjust(counts: &mut HashMap<App, usize>, app: App, up: bool) {
51 let count = counts.entry(app).or_default();
52 *count = if up { *count + 1 } else { count.saturating_sub(1) };
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn an_idle_tab_parks() {
61 assert_eq!(ParkGate::default().decide(App::Teams), ParkDecision::Park);
62 }
63
64 #[test]
65 fn a_running_command_delays_the_park_until_it_answers() {
66 let mut gate = ParkGate::default();
67 gate.command_started(App::Teams);
68 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
69 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
70 gate.command_finished(App::Teams);
71 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
72 }
73
74 #[test]
75 fn a_held_tab_waits_for_every_hold_to_end() {
76 let mut gate = ParkGate::default();
77 gate.hold(App::Teams, true);
78 gate.hold(App::Teams, true);
79 gate.hold(App::Teams, false);
80 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
81 gate.hold(App::Teams, false);
82 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
83 }
84
85 #[test]
86 fn extra_releases_do_not_underflow() {
87 let mut gate = ParkGate::default();
88 gate.hold(App::Teams, false);
89 gate.command_finished(App::Teams);
90 gate.hold(App::Teams, true);
91 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
92 }
93
94 #[test]
95 fn a_restart_forgets_unanswered_commands_but_keeps_holds() {
96 let mut gate = ParkGate::default();
97 gate.command_started(App::Outlook);
98 gate.hold(App::Teams, true);
99 gate.forget_commands();
100 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
101 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
102 }
103}
crates/webview/src/transport.rs +8 −0
@@ -29,6 +29,10 @@ pub(crate) enum UiRequest {
29 29 Wake {
30 30 app: App,
31 31 },
32 Hold {
33 app: App,
34 held: bool,
35 },
32 36 Retry,
33 37 OpenDialog {
34 38 id: u64,
@@ -147,6 +151,10 @@ impl Transport for WebViewTransport {
147 151 Box::pin(async move { self.send(UiRequest::Wake { app }) })
148 152 }
149 153
154 fn hold(&self, app: App, held: bool) {
155 let _ = self.send(UiRequest::Hold { app, held });
156 }
157
150 158 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
151 159 Box::pin(async move {
152 160 let state = self.state.borrow();
@@ -29,6 +29,10 @@ pub(crate) enum UiRequest {
29 Wake {
29 Wake {
30 app: App,
30 app: App,
31 },
31 },
32 Hold {
33 app: App,
34 held: bool,
35 },
32 Retry,
36 Retry,
33 OpenDialog {
37 OpenDialog {
34 id: u64,
38 id: u64,
@@ -147,6 +151,10 @@ impl Transport for WebViewTransport {
147 Box::pin(async move { self.send(UiRequest::Wake { app }) })
151 Box::pin(async move { self.send(UiRequest::Wake { app }) })
148 }
152 }
149
153
154 fn hold(&self, app: App, held: bool) {
155 let _ = self.send(UiRequest::Hold { app, held });
156 }
157
150 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
158 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
151 Box::pin(async move {
159 Box::pin(async move {
152 let state = self.state.borrow();
160 let state = self.state.borrow();