BlueGit

ict rusty-teams

feat(browser): park the idle Teams tab on Linux (#63)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

metis Victor Wingert · pushed by metis

Authored 2026-11-18 · 13 days ago

Hash
d0b90869acb82887b8c61a0c0b58daf388958cb7
Parent
0a0e0a53
5 files changed +169 −0
crates/app/src/linux_browser.rs +14 −0
@@ -6,6 +6,7 @@ use tokio::sync::{Notify, mpsc, watch};
6 6
7 7 use crate::backend::BackendEvent;
8 8 use crate::browser_sign_in::BrowserSignInState;
9 use crate::linux_park::{self, ParkClock};
9 10
10 11 const STARTUP_WAIT: Duration = Duration::from_secs(20);
11 12 const RELAUNCH_WAIT: Duration = Duration::from_secs(5);
@@ -207,11 +208,18 @@ pub fn start(endpoint: &str) -> Arc<dyn session::Transport> {
207 208 }
208 209 }
209 210 });
211 let park = ParkClock::new();
212 // Parking checks the MSAL cache over CDP, so it runs with a Chromium browser only.
213 // macOS keeps the clock but never parks: nobody has run it there yet.
214 if cfg!(target_os = "linux") && browser.bidi().is_none() {
215 linux_park::spawn(park.clone(), browser.clone(), endpoint);
216 }
210 217 Arc::new(LinuxTransport::new(
211 218 endpoint,
212 219 browser,
213 220 init_done_rx,
214 221 headless_notify,
222 park,
215 223 ))
216 224 }
217 225
@@ -229,6 +237,7 @@ struct LinuxTransport {
229 237 browser: browser::Browser,
230 238 init_done: watch::Receiver<bool>,
231 239 headless_notify: Arc<Notify>,
240 park: Arc<ParkClock>,
232 241 }
233 242
234 243 impl LinuxTransport {
@@ -237,12 +246,14 @@ impl LinuxTransport {
237 246 browser: browser::Browser,
238 247 init_done: watch::Receiver<bool>,
239 248 headless_notify: Arc<Notify>,
249 park: Arc<ParkClock>,
240 250 ) -> Self {
241 251 LinuxTransport {
242 252 inner: browser::session_transport(&browser, endpoint),
243 253 browser,
244 254 init_done,
245 255 headless_notify,
256 park,
246 257 }
247 258 }
248 259
@@ -293,6 +304,7 @@ impl session::Transport for LinuxTransport {
293 304 if self.browser.is_visible_managed() {
294 305 return Ok(None);
295 306 }
307 self.park.touch();
296 308 self.inner.open(app, with_events).await
297 309 })
298 310 }
@@ -303,6 +315,7 @@ impl session::Transport for LinuxTransport {
303 315 if self.browser.is_visible_managed() {
304 316 return Ok(());
305 317 }
318 self.park.touch();
306 319 self.inner.wake(app).await
307 320 })
308 321 }
@@ -321,6 +334,7 @@ impl session::Transport for LinuxTransport {
321 334 }
322 335
323 336 fn hold(&self, app: session::App, held: bool) {
337 self.park.hold(held);
324 338 self.inner.hold(app, held)
325 339 }
326 340 }
@@ -6,6 +6,7 @@ use tokio::sync::{Notify, mpsc, watch};
6
6
7use crate::backend::BackendEvent;
7use crate::backend::BackendEvent;
8use crate::browser_sign_in::BrowserSignInState;
8use crate::browser_sign_in::BrowserSignInState;
9use crate::linux_park::{self, ParkClock};
9
10
10const STARTUP_WAIT: Duration = Duration::from_secs(20);
11const STARTUP_WAIT: Duration = Duration::from_secs(20);
11const RELAUNCH_WAIT: Duration = Duration::from_secs(5);
12const RELAUNCH_WAIT: Duration = Duration::from_secs(5);
@@ -207,11 +208,18 @@ pub fn start(endpoint: &str) -> Arc<dyn session::Transport> {
207 }
208 }
208 }
209 }
209 });
210 });
211 let park = ParkClock::new();
212 // Parking checks the MSAL cache over CDP, so it runs with a Chromium browser only.
213 // macOS keeps the clock but never parks: nobody has run it there yet.
214 if cfg!(target_os = "linux") && browser.bidi().is_none() {
215 linux_park::spawn(park.clone(), browser.clone(), endpoint);
216 }
210 Arc::new(LinuxTransport::new(
217 Arc::new(LinuxTransport::new(
211 endpoint,
218 endpoint,
212 browser,
219 browser,
213 init_done_rx,
220 init_done_rx,
214 headless_notify,
221 headless_notify,
222 park,
215 ))
223 ))
216}
224}
217
225
@@ -229,6 +237,7 @@ struct LinuxTransport {
229 browser: browser::Browser,
237 browser: browser::Browser,
230 init_done: watch::Receiver<bool>,
238 init_done: watch::Receiver<bool>,
231 headless_notify: Arc<Notify>,
239 headless_notify: Arc<Notify>,
240 park: Arc<ParkClock>,
232}
241}
233
242
234impl LinuxTransport {
243impl LinuxTransport {
@@ -237,12 +246,14 @@ impl LinuxTransport {
237 browser: browser::Browser,
246 browser: browser::Browser,
238 init_done: watch::Receiver<bool>,
247 init_done: watch::Receiver<bool>,
239 headless_notify: Arc<Notify>,
248 headless_notify: Arc<Notify>,
249 park: Arc<ParkClock>,
240 ) -> Self {
250 ) -> Self {
241 LinuxTransport {
251 LinuxTransport {
242 inner: browser::session_transport(&browser, endpoint),
252 inner: browser::session_transport(&browser, endpoint),
243 browser,
253 browser,
244 init_done,
254 init_done,
245 headless_notify,
255 headless_notify,
256 park,
246 }
257 }
247 }
258 }
248
259
@@ -293,6 +304,7 @@ impl session::Transport for LinuxTransport {
293 if self.browser.is_visible_managed() {
304 if self.browser.is_visible_managed() {
294 return Ok(None);
305 return Ok(None);
295 }
306 }
307 self.park.touch();
296 self.inner.open(app, with_events).await
308 self.inner.open(app, with_events).await
297 })
309 })
298 }
310 }
@@ -303,6 +315,7 @@ impl session::Transport for LinuxTransport {
303 if self.browser.is_visible_managed() {
315 if self.browser.is_visible_managed() {
304 return Ok(());
316 return Ok(());
305 }
317 }
318 self.park.touch();
306 self.inner.wake(app).await
319 self.inner.wake(app).await
307 })
320 })
308 }
321 }
@@ -321,6 +334,7 @@ impl session::Transport for LinuxTransport {
321 }
334 }
322
335
323 fn hold(&self, app: session::App, held: bool) {
336 fn hold(&self, app: session::App, held: bool) {
337 self.park.hold(held);
324 self.inner.hold(app, held)
338 self.inner.hold(app, held)
325 }
339 }
326}
340}
crates/app/src/linux_park.rs added +132 −0
@@ -0,0 +1,132 @@
1 //! Linux with a Chromium browser: parks the hidden Teams tab on a static page of its own
2 //! origin, like the WebView2 host does on Windows. The running Teams web app holds close to a
3 //! gigabyte; the parked page keeps the MSAL cache reachable for token refreshes at a fraction
4 //! of that. The session wakes the tab when it needs the running app again
5 //! (`Transport::wake`), and this parks it once more.
6 //!
7 //! The quiet period counts from the last time the session opened or woke the tab, not from
8 //! the last command: commands go over a connection the session keeps, which this transport
9 //! does not see. Windows counts commands in flight (`webview::park`); here a page-run call
10 //! that overlaps the navigation loses its page connection (a read retries, a write fails).
11
12 use std::sync::atomic::{AtomicUsize, Ordering};
13 use std::sync::{Arc, Mutex};
14 use std::time::{Duration, Instant};
15
16 use serde_json::json;
17 use session::Transport as _;
18
19 const PARK_DELAY: Duration = Duration::from_secs(60);
20 const PARK_POLL: Duration = Duration::from_secs(15);
21
22 /// When the session last opened or woke the tab, and who needs it to stay loaded.
23 pub struct ParkClock {
24 holds: AtomicUsize,
25 last_use: Mutex<Instant>,
26 }
27
28 impl ParkClock {
29 pub fn new() -> Arc<Self> {
30 Arc::new(ParkClock {
31 holds: AtomicUsize::new(0),
32 last_use: Mutex::new(Instant::now()),
33 })
34 }
35
36 /// The tab was just opened or woken: leave it running for the quiet period.
37 pub fn touch(&self) {
38 if let Ok(mut last_use) = self.last_use.lock() {
39 *last_use = Instant::now();
40 }
41 }
42
43 /// A call holds the tab: a navigation would cut its page sockets.
44 pub fn hold(&self, held: bool) {
45 if held {
46 self.holds.fetch_add(1, Ordering::SeqCst);
47 } else {
48 let _ = self
49 .holds
50 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |holds| {
51 Some(holds.saturating_sub(1))
52 });
53 }
54 }
55
56 fn due(&self, now: Instant) -> bool {
57 self.holds.load(Ordering::SeqCst) == 0
58 && self
59 .last_use
60 .lock()
61 .is_ok_and(|last_use| now.duration_since(*last_use) >= PARK_DELAY)
62 }
63 }
64
65 pub fn spawn(clock: Arc<ParkClock>, browser: browser::Browser, endpoint: &str) {
66 let transport = session::CdpTransport::new(endpoint);
67 app_base::runtime::handle().spawn(async move {
68 loop {
69 tokio::time::sleep(PARK_POLL).await;
70 if !clock.due(Instant::now()) || browser.is_busy() || browser.is_visible_managed() {
71 continue;
72 }
73 // False for a parked tab, a login page and a Teams that has not signed in yet.
74 if !browser.teams_has_msal_cache().await {
75 continue;
76 }
77 match park(&transport).await {
78 Ok(true) => log::info!("Teams tab parked"),
79 Ok(false) => {}
80 Err(error) => log::warn!("parking the Teams tab failed: {error}"),
81 }
82 }
83 });
84 }
85
86 async fn park(transport: &session::CdpTransport) -> session::Result<bool> {
87 let app = session::App::Teams;
88 let Some((control, _)) = transport.open(app, false).await? else {
89 return Ok(false);
90 };
91 control
92 .call("Page.navigate", json!({ "url": app.park_url() }))
93 .await?;
94 Ok(true)
95 }
96
97 #[cfg(test)]
98 mod tests {
99 use super::*;
100
101 fn clock_used(ago: Duration) -> Arc<ParkClock> {
102 let clock = ParkClock::new();
103 *clock.last_use.lock().unwrap() = Instant::now() - ago;
104 clock
105 }
106
107 #[test]
108 fn a_tab_parks_only_after_the_quiet_period() {
109 assert!(!clock_used(Duration::from_secs(5)).due(Instant::now()));
110 assert!(clock_used(PARK_DELAY).due(Instant::now()));
111 }
112
113 #[test]
114 fn a_wake_restarts_the_quiet_period() {
115 let clock = clock_used(PARK_DELAY);
116 clock.touch();
117 assert!(!clock.due(Instant::now()));
118 }
119
120 #[test]
121 fn a_held_tab_never_parks_and_releases_are_counted() {
122 let clock = clock_used(PARK_DELAY);
123 clock.hold(true);
124 clock.hold(true);
125 clock.hold(false);
126 assert!(!clock.due(Instant::now()));
127 clock.hold(false);
128 assert!(clock.due(Instant::now()));
129 clock.hold(false);
130 assert!(clock.due(Instant::now()));
131 }
132 }
@@ -0,0 +1,132 @@
1//! Linux with a Chromium browser: parks the hidden Teams tab on a static page of its own
2//! origin, like the WebView2 host does on Windows. The running Teams web app holds close to a
3//! gigabyte; the parked page keeps the MSAL cache reachable for token refreshes at a fraction
4//! of that. The session wakes the tab when it needs the running app again
5//! (`Transport::wake`), and this parks it once more.
6//!
7//! The quiet period counts from the last time the session opened or woke the tab, not from
8//! the last command: commands go over a connection the session keeps, which this transport
9//! does not see. Windows counts commands in flight (`webview::park`); here a page-run call
10//! that overlaps the navigation loses its page connection (a read retries, a write fails).
11
12use std::sync::atomic::{AtomicUsize, Ordering};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15
16use serde_json::json;
17use session::Transport as _;
18
19const PARK_DELAY: Duration = Duration::from_secs(60);
20const PARK_POLL: Duration = Duration::from_secs(15);
21
22/// When the session last opened or woke the tab, and who needs it to stay loaded.
23pub struct ParkClock {
24 holds: AtomicUsize,
25 last_use: Mutex<Instant>,
26}
27
28impl ParkClock {
29 pub fn new() -> Arc<Self> {
30 Arc::new(ParkClock {
31 holds: AtomicUsize::new(0),
32 last_use: Mutex::new(Instant::now()),
33 })
34 }
35
36 /// The tab was just opened or woken: leave it running for the quiet period.
37 pub fn touch(&self) {
38 if let Ok(mut last_use) = self.last_use.lock() {
39 *last_use = Instant::now();
40 }
41 }
42
43 /// A call holds the tab: a navigation would cut its page sockets.
44 pub fn hold(&self, held: bool) {
45 if held {
46 self.holds.fetch_add(1, Ordering::SeqCst);
47 } else {
48 let _ = self
49 .holds
50 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |holds| {
51 Some(holds.saturating_sub(1))
52 });
53 }
54 }
55
56 fn due(&self, now: Instant) -> bool {
57 self.holds.load(Ordering::SeqCst) == 0
58 && self
59 .last_use
60 .lock()
61 .is_ok_and(|last_use| now.duration_since(*last_use) >= PARK_DELAY)
62 }
63}
64
65pub fn spawn(clock: Arc<ParkClock>, browser: browser::Browser, endpoint: &str) {
66 let transport = session::CdpTransport::new(endpoint);
67 app_base::runtime::handle().spawn(async move {
68 loop {
69 tokio::time::sleep(PARK_POLL).await;
70 if !clock.due(Instant::now()) || browser.is_busy() || browser.is_visible_managed() {
71 continue;
72 }
73 // False for a parked tab, a login page and a Teams that has not signed in yet.
74 if !browser.teams_has_msal_cache().await {
75 continue;
76 }
77 match park(&transport).await {
78 Ok(true) => log::info!("Teams tab parked"),
79 Ok(false) => {}
80 Err(error) => log::warn!("parking the Teams tab failed: {error}"),
81 }
82 }
83 });
84}
85
86async fn park(transport: &session::CdpTransport) -> session::Result<bool> {
87 let app = session::App::Teams;
88 let Some((control, _)) = transport.open(app, false).await? else {
89 return Ok(false);
90 };
91 control
92 .call("Page.navigate", json!({ "url": app.park_url() }))
93 .await?;
94 Ok(true)
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 fn clock_used(ago: Duration) -> Arc<ParkClock> {
102 let clock = ParkClock::new();
103 *clock.last_use.lock().unwrap() = Instant::now() - ago;
104 clock
105 }
106
107 #[test]
108 fn a_tab_parks_only_after_the_quiet_period() {
109 assert!(!clock_used(Duration::from_secs(5)).due(Instant::now()));
110 assert!(clock_used(PARK_DELAY).due(Instant::now()));
111 }
112
113 #[test]
114 fn a_wake_restarts_the_quiet_period() {
115 let clock = clock_used(PARK_DELAY);
116 clock.touch();
117 assert!(!clock.due(Instant::now()));
118 }
119
120 #[test]
121 fn a_held_tab_never_parks_and_releases_are_counted() {
122 let clock = clock_used(PARK_DELAY);
123 clock.hold(true);
124 clock.hold(true);
125 clock.hold(false);
126 assert!(!clock.due(Instant::now()));
127 clock.hold(false);
128 assert!(clock.due(Instant::now()));
129 clock.hold(false);
130 assert!(clock.due(Instant::now()));
131 }
132}
crates/app/src/main.rs +2 −0
@@ -16,6 +16,8 @@ mod layout_guard;
16 16 mod linux_browser;
17 17 #[cfg(target_os = "linux")]
18 18 mod linux_install;
19 #[cfg(any(target_os = "linux", target_os = "macos"))]
20 mod linux_park;
19 21 #[cfg(target_os = "linux")]
20 22 mod linux_update;
21 23 mod main_window;
@@ -16,6 +16,8 @@ mod layout_guard;
16mod linux_browser;
16mod linux_browser;
17#[cfg(target_os = "linux")]
17#[cfg(target_os = "linux")]
18mod linux_install;
18mod linux_install;
19#[cfg(any(target_os = "linux", target_os = "macos"))]
20mod linux_park;
19#[cfg(target_os = "linux")]
21#[cfg(target_os = "linux")]
20mod linux_update;
22mod linux_update;
21mod main_window;
23mod main_window;
docs/decisions/0022-linux-parks-the-idle-teams-tab.md added +20 −0
@@ -0,0 +1,20 @@
1 ---
2 status: proposed
3 date: 2026-11-17
4 ---
5
6 # ADR 0022: Linux parks the idle Teams tab in a Chromium browser
7
8 ## Context
9
10 On Windows the WebView2 host parks the Teams page on `robots.txt` of its own origin after a quiet minute. The MSAL cache stays reachable for token refreshes and the running Teams web app is unloaded. On Linux the managed browser kept the whole Teams web app loaded, close to a gigabyte, although Rust sends most requests itself. Options were: leave it loaded, unload it some other way (memory pressure flags, discarding the tab), or park it the way Windows does.
11
12 ## Decision
13
14 On Linux with a Chromium browser, the app parks the Teams tab the way Windows does: a minute after the session last opened or woke the tab, when no call holds it and the tab has its MSAL cache, it navigates the tab to the park URL over CDP. The session wakes it as before when it needs the running app.
15
16 ## Consequences
17
18 - The managed Chromium drops from about 1 GB to a few hundred MB once parked.
19 - The quiet minute counts from the last open or wake, not from the last command. The session keeps its own connection to the tab, so the transport does not see commands. A page-run call that overlaps the navigation loses its page connection: a read wakes the tab and runs again, a write fails with `WriteInterrupted`. Most requests go out from Rust and do not run in the page.
20 - Firefox browsers (BiDi) and macOS are left out: the MSAL check runs over CDP, and nobody has run parking on macOS yet.
@@ -0,0 +1,20 @@
1---
2status: proposed
3date: 2026-11-17
4---
5
6# ADR 0022: Linux parks the idle Teams tab in a Chromium browser
7
8## Context
9
10On Windows the WebView2 host parks the Teams page on `robots.txt` of its own origin after a quiet minute. The MSAL cache stays reachable for token refreshes and the running Teams web app is unloaded. On Linux the managed browser kept the whole Teams web app loaded, close to a gigabyte, although Rust sends most requests itself. Options were: leave it loaded, unload it some other way (memory pressure flags, discarding the tab), or park it the way Windows does.
11
12## Decision
13
14On Linux with a Chromium browser, the app parks the Teams tab the way Windows does: a minute after the session last opened or woke the tab, when no call holds it and the tab has its MSAL cache, it navigates the tab to the park URL over CDP. The session wakes it as before when it needs the running app.
15
16## Consequences
17
18- The managed Chromium drops from about 1 GB to a few hundred MB once parked.
19- The quiet minute counts from the last open or wake, not from the last command. The session keeps its own connection to the tab, so the transport does not see commands. A page-run call that overlaps the navigation loses its page connection: a read wakes the tab and runs again, a write fails with `WriteInterrupted`. Most requests go out from Rust and do not run in the page.
20- Firefox browsers (BiDi) and macOS are left out: the MSAL check runs over CDP, and nobody has run parking on macOS yet.
docs/decisions/README.md +1 −0
@@ -37,5 +37,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
37 37 | [0019](0019-caldav-app-password-and-keyring.md) | CalDAV with app password and OS keyring |
38 38 | [0020](0020-macos-tray-and-close-to-tray.md) | macOS tray and close-to-tray match Linux |
39 39 | [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40 | [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
40 41
41 42 Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -37,5 +37,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
37| [0019](0019-caldav-app-password-and-keyring.md) | CalDAV with app password and OS keyring |
37| [0019](0019-caldav-app-password-and-keyring.md) | CalDAV with app password and OS keyring |
38| [0020](0020-macos-tray-and-close-to-tray.md) | macOS tray and close-to-tray match Linux |
38| [0020](0020-macos-tray-and-close-to-tray.md) | macOS tray and close-to-tray match Linux |
39| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
39| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
40
41
41Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
42Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.