BlueGit

ict rusty-teams

fix(presence): register our endpoint and report real activity, so the app no longer shows Away while in use

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-11 · 7 weeks ago

Hash
7b6dcd7463c37de2add3427e5bc4b8522fc8e84d
Parent
8f6c0ed7
13 files changed +723 −22
crates/app/Cargo.toml +2 −0
@@ -48,8 +48,10 @@ windows = { version = "0.62", features = [
48 48 "Win32_Storage_FileSystem",
49 49 "Win32_System_Com",
50 50 "Win32_System_Pipes",
51 "Win32_System_SystemInformation",
51 52 "Win32_System_Threading",
52 53 "Win32_UI_HiDpi",
54 "Win32_UI_Input_KeyboardAndMouse",
53 55 "Win32_UI_Shell",
54 56 "Win32_UI_WindowsAndMessaging",
55 57 ] }
@@ -48,8 +48,10 @@ windows = { version = "0.62", features = [
48 "Win32_Storage_FileSystem",
48 "Win32_Storage_FileSystem",
49 "Win32_System_Com",
49 "Win32_System_Com",
50 "Win32_System_Pipes",
50 "Win32_System_Pipes",
51 "Win32_System_SystemInformation",
51 "Win32_System_Threading",
52 "Win32_System_Threading",
52 "Win32_UI_HiDpi",
53 "Win32_UI_HiDpi",
54 "Win32_UI_Input_KeyboardAndMouse",
53 "Win32_UI_Shell",
55 "Win32_UI_Shell",
54 "Win32_UI_WindowsAndMessaging",
56 "Win32_UI_WindowsAndMessaging",
55] }
57] }
crates/app/src/backend.rs +50 −6
@@ -2,15 +2,16 @@ use std::sync::Arc;
2 2 use std::time::Duration;
3 3
4 4 use calling::EngineEvent;
5 use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5 use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent};
6 6 use chrono::{DateTime, Local, Offset, Utc};
7 7 use graph::Graph;
8 8 use session::{Session, SessionConfig, Transport};
9 9 use store::Store;
10 10 use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
11 use tokio::sync::mpsc;
11 use tokio::sync::{mpsc, watch};
12 12
13 13 use crate::call::{CallLauncher, fetch_window};
14 use crate::presence_link::{self, LinkSignal};
14 15
15 16 pub type Engine = SyncEngine<Graph>;
16 17
@@ -99,17 +100,31 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
99 100 }
100 101 }
101 102
103 fn link_signal_for(kind: StatusKind) -> LinkSignal {
104 match kind {
105 StatusKind::Connected | StatusKind::MessageLoss => LinkSignal::Connected,
106 StatusKind::Disconnected | StatusKind::Error => LinkSignal::Disconnected,
107 }
108 }
109
102 110 pub fn start(
103 111 store: Arc<Store>,
104 112 transport: Arc<dyn Transport>,
105 113 ringable: bool,
114 activity: watch::Receiver<bool>,
106 115 ) -> mpsc::UnboundedReceiver<BackendEvent> {
107 116 let (sender, receiver) = mpsc::unbounded_channel();
108 crate::runtime::handle().spawn(supervise(store, transport, ringable, sender));
117 crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));
109 118 receiver
110 119 }
111 120
112 async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: bool, events: EventSender) {
121 async fn supervise(
122 store: Arc<Store>,
123 transport: Arc<dyn Transport>,
124 ringable: bool,
125 activity: watch::Receiver<bool>,
126 events: EventSender,
127 ) {
113 128 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
114 129 let session = loop {
115 130 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
@@ -140,11 +155,14 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: b
140 155 let _ = events.send(BackendEvent::Calls(launcher));
141 156 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
142 157 let (nudge, nudges) = mpsc::unbounded_channel();
158 let link = presence_link::start(&session, activity.clone());
143 159 tokio::spawn(realtime_loop(
144 160 session.clone(),
145 161 engine.clone(),
146 162 events.clone(),
147 163 nudge,
164 activity,
165 link,
148 166 ));
149 167 tokio::spawn(calendar_loop(session.clone(), events.clone()));
150 168 tokio::spawn(pins_loop(session, events.clone()));
@@ -206,12 +224,26 @@ async fn realtime_loop(
206 224 engine: Arc<Engine>,
207 225 events: EventSender,
208 226 nudge: mpsc::UnboundedSender<()>,
227 mut activity: watch::Receiver<bool>,
228 link: mpsc::UnboundedSender<LinkSignal>,
209 229 ) {
210 230 loop {
211 231 let _ = events.send(BackendEvent::Live(LiveState::Connecting));
212 match Realtime::start(&session).await {
232 let config = RealtimeConfig {
233 initially_active: *activity.borrow(),
234 ..RealtimeConfig::default()
235 };
236 match Realtime::start_with(&session, config).await {
213 237 Ok(mut realtime) => {
214 while let Some(event) = realtime.recv().await {
238 loop {
239 let event = tokio::select! {
240 event = realtime.recv() => event,
241 Ok(()) = activity.changed() => {
242 realtime.set_activity(*activity.borrow_and_update());
243 continue;
244 }
245 };
246 let Some(event) = event else { break };
215 247 match event {
216 248 RealtimeEvent::Message(message) => {
217 249 let _ = events.send(BackendEvent::Live(LiveState::Live));
@@ -235,6 +267,7 @@ async fn realtime_loop(
235 267 }
236 268 RealtimeEvent::Status(status) => {
237 269 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
270 let _ = link.send(link_signal_for(status.kind));
238 271 let receipt_engine = engine.clone();
239 272 let receipt_status = status.clone();
240 273 tokio::spawn(async move {
@@ -249,15 +282,18 @@ async fn realtime_loop(
249 282 }
250 283 }
251 284 RealtimeEvent::Endpoint(endpoint) => {
285 let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
252 286 let engine = engine.clone();
253 287 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
254 288 }
255 289 }
256 290 }
257 291 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
292 let _ = link.send(LinkSignal::Disconnected);
258 293 }
259 294 Err(_) => {
260 295 let _ = events.send(BackendEvent::Live(LiveState::Failed));
296 let _ = link.send(LinkSignal::Disconnected);
261 297 }
262 298 }
263 299 tokio::time::sleep(REALTIME_RETRY).await;
@@ -468,4 +504,12 @@ mod tests {
468 504 );
469 505 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
470 506 }
507
508 #[test]
509 fn only_a_closed_or_failed_trouter_counts_as_down() {
510 assert_eq!(link_signal_for(StatusKind::Connected), LinkSignal::Connected);
511 assert_eq!(link_signal_for(StatusKind::MessageLoss), LinkSignal::Connected);
512 assert_eq!(link_signal_for(StatusKind::Disconnected), LinkSignal::Disconnected);
513 assert_eq!(link_signal_for(StatusKind::Error), LinkSignal::Disconnected);
514 }
471 515 }
@@ -2,15 +2,16 @@ use std::sync::Arc;
2use std::time::Duration;
2use std::time::Duration;
3
3
4use calling::EngineEvent;
4use calling::EngineEvent;
5use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent};
6use chrono::{DateTime, Local, Offset, Utc};
6use chrono::{DateTime, Local, Offset, Utc};
7use graph::Graph;
7use graph::Graph;
8use session::{Session, SessionConfig, Transport};
8use session::{Session, SessionConfig, Transport};
9use store::Store;
9use store::Store;
10use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
10use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
11use tokio::sync::mpsc;
11use tokio::sync::{mpsc, watch};
12
12
13use crate::call::{CallLauncher, fetch_window};
13use crate::call::{CallLauncher, fetch_window};
14use crate::presence_link::{self, LinkSignal};
14
15
15pub type Engine = SyncEngine<Graph>;
16pub type Engine = SyncEngine<Graph>;
16
17
@@ -99,17 +100,31 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
99 }
100 }
100}
101}
101
102
103fn link_signal_for(kind: StatusKind) -> LinkSignal {
104 match kind {
105 StatusKind::Connected | StatusKind::MessageLoss => LinkSignal::Connected,
106 StatusKind::Disconnected | StatusKind::Error => LinkSignal::Disconnected,
107 }
108}
109
102pub fn start(
110pub fn start(
103 store: Arc<Store>,
111 store: Arc<Store>,
104 transport: Arc<dyn Transport>,
112 transport: Arc<dyn Transport>,
105 ringable: bool,
113 ringable: bool,
114 activity: watch::Receiver<bool>,
106) -> mpsc::UnboundedReceiver<BackendEvent> {
115) -> mpsc::UnboundedReceiver<BackendEvent> {
107 let (sender, receiver) = mpsc::unbounded_channel();
116 let (sender, receiver) = mpsc::unbounded_channel();
108 crate::runtime::handle().spawn(supervise(store, transport, ringable, sender));
117 crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));
109 receiver
118 receiver
110}
119}
111
120
112async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: bool, events: EventSender) {
121async fn supervise(
122 store: Arc<Store>,
123 transport: Arc<dyn Transport>,
124 ringable: bool,
125 activity: watch::Receiver<bool>,
126 events: EventSender,
127) {
113 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
128 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
114 let session = loop {
129 let session = loop {
115 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
130 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
@@ -140,11 +155,14 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: b
140 let _ = events.send(BackendEvent::Calls(launcher));
155 let _ = events.send(BackendEvent::Calls(launcher));
141 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
156 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
142 let (nudge, nudges) = mpsc::unbounded_channel();
157 let (nudge, nudges) = mpsc::unbounded_channel();
158 let link = presence_link::start(&session, activity.clone());
143 tokio::spawn(realtime_loop(
159 tokio::spawn(realtime_loop(
144 session.clone(),
160 session.clone(),
145 engine.clone(),
161 engine.clone(),
146 events.clone(),
162 events.clone(),
147 nudge,
163 nudge,
164 activity,
165 link,
148 ));
166 ));
149 tokio::spawn(calendar_loop(session.clone(), events.clone()));
167 tokio::spawn(calendar_loop(session.clone(), events.clone()));
150 tokio::spawn(pins_loop(session, events.clone()));
168 tokio::spawn(pins_loop(session, events.clone()));
@@ -206,12 +224,26 @@ async fn realtime_loop(
206 engine: Arc<Engine>,
224 engine: Arc<Engine>,
207 events: EventSender,
225 events: EventSender,
208 nudge: mpsc::UnboundedSender<()>,
226 nudge: mpsc::UnboundedSender<()>,
227 mut activity: watch::Receiver<bool>,
228 link: mpsc::UnboundedSender<LinkSignal>,
209) {
229) {
210 loop {
230 loop {
211 let _ = events.send(BackendEvent::Live(LiveState::Connecting));
231 let _ = events.send(BackendEvent::Live(LiveState::Connecting));
212 match Realtime::start(&session).await {
232 let config = RealtimeConfig {
233 initially_active: *activity.borrow(),
234 ..RealtimeConfig::default()
235 };
236 match Realtime::start_with(&session, config).await {
213 Ok(mut realtime) => {
237 Ok(mut realtime) => {
214 while let Some(event) = realtime.recv().await {
238 loop {
239 let event = tokio::select! {
240 event = realtime.recv() => event,
241 Ok(()) = activity.changed() => {
242 realtime.set_activity(*activity.borrow_and_update());
243 continue;
244 }
245 };
246 let Some(event) = event else { break };
215 match event {
247 match event {
216 RealtimeEvent::Message(message) => {
248 RealtimeEvent::Message(message) => {
217 let _ = events.send(BackendEvent::Live(LiveState::Live));
249 let _ = events.send(BackendEvent::Live(LiveState::Live));
@@ -235,6 +267,7 @@ async fn realtime_loop(
235 }
267 }
236 RealtimeEvent::Status(status) => {
268 RealtimeEvent::Status(status) => {
237 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
269 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
270 let _ = link.send(link_signal_for(status.kind));
238 let receipt_engine = engine.clone();
271 let receipt_engine = engine.clone();
239 let receipt_status = status.clone();
272 let receipt_status = status.clone();
240 tokio::spawn(async move {
273 tokio::spawn(async move {
@@ -249,15 +282,18 @@ async fn realtime_loop(
249 }
282 }
250 }
283 }
251 RealtimeEvent::Endpoint(endpoint) => {
284 RealtimeEvent::Endpoint(endpoint) => {
285 let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
252 let engine = engine.clone();
286 let engine = engine.clone();
253 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
287 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
254 }
288 }
255 }
289 }
256 }
290 }
257 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
291 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
292 let _ = link.send(LinkSignal::Disconnected);
258 }
293 }
259 Err(_) => {
294 Err(_) => {
260 let _ = events.send(BackendEvent::Live(LiveState::Failed));
295 let _ = events.send(BackendEvent::Live(LiveState::Failed));
296 let _ = link.send(LinkSignal::Disconnected);
261 }
297 }
262 }
298 }
263 tokio::time::sleep(REALTIME_RETRY).await;
299 tokio::time::sleep(REALTIME_RETRY).await;
@@ -468,4 +504,12 @@ mod tests {
468 );
504 );
469 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
505 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
470 }
506 }
507
508 #[test]
509 fn only_a_closed_or_failed_trouter_counts_as_down() {
510 assert_eq!(link_signal_for(StatusKind::Connected), LinkSignal::Connected);
511 assert_eq!(link_signal_for(StatusKind::MessageLoss), LinkSignal::Connected);
512 assert_eq!(link_signal_for(StatusKind::Disconnected), LinkSignal::Disconnected);
513 assert_eq!(link_signal_for(StatusKind::Error), LinkSignal::Disconnected);
514 }
471}
515}
crates/app/src/main.rs +8 −1
@@ -42,6 +42,7 @@ mod notify;
42 42 mod outbox;
43 43 mod pending_rows;
44 44 mod people;
45 mod presence_link;
45 46 mod profile_model;
46 47 mod profile_state;
47 48 mod reaction_model;
@@ -63,6 +64,7 @@ mod translation;
63 64 mod translation_actions;
64 65 mod typing;
65 66 mod updater;
67 mod user_activity;
66 68 mod views;
67 69
68 70 use std::path::PathBuf;
@@ -83,6 +85,7 @@ const WINDOW_WIDTH: f32 = 1240.;
83 85 const WINDOW_HEIGHT: f32 = 820.;
84 86 const WINDOW_MIN_WIDTH: f32 = 640.;
85 87 const WINDOW_MIN_HEIGHT: f32 = 480.;
88 const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);
86 89 const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
87 90 const DATABASE_FILE: &str = "cache.sqlite3";
88 91 #[cfg(windows)]
@@ -218,10 +221,12 @@ fn main() {
218 221 open_store(&path)
219 222 };
220 223 let store = Arc::new(store);
224 let user_input = user_activity::UserInput::new();
221 225 let receiver = (!arguments.demo)
222 226 .then(|| {
223 227 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
224 backend::start(store.clone(), transport, !arguments.read_only)
228 let activity = user_activity::track(user_input.clone());
229 backend::start(store.clone(), transport, !arguments.read_only, activity)
225 230 });
226 231
227 232 let mut application = gpui_kit::application();
@@ -247,6 +252,7 @@ fn main() {
247 252 state
248 253 });
249 254 cx.set_global(app_state::AppHandle(state.clone()));
255 cx.set_global(views::shell::UserInputHandle(user_input));
250 256 if arguments.demo {
251 257 state.update(cx, |state, cx| {
252 258 demo::seed_directory(state);
@@ -290,6 +296,7 @@ fn main() {
290 296 .detach();
291 297 cx.activate(true);
292 298 });
299 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
293 300 #[cfg(windows)]
294 301 updater::exit_now();
295 302 }
@@ -42,6 +42,7 @@ mod notify;
42mod outbox;
42mod outbox;
43mod pending_rows;
43mod pending_rows;
44mod people;
44mod people;
45mod presence_link;
45mod profile_model;
46mod profile_model;
46mod profile_state;
47mod profile_state;
47mod reaction_model;
48mod reaction_model;
@@ -63,6 +64,7 @@ mod translation;
63mod translation_actions;
64mod translation_actions;
64mod typing;
65mod typing;
65mod updater;
66mod updater;
67mod user_activity;
66mod views;
68mod views;
67
69
68use std::path::PathBuf;
70use std::path::PathBuf;
@@ -83,6 +85,7 @@ const WINDOW_WIDTH: f32 = 1240.;
83const WINDOW_HEIGHT: f32 = 820.;
85const WINDOW_HEIGHT: f32 = 820.;
84const WINDOW_MIN_WIDTH: f32 = 640.;
86const WINDOW_MIN_WIDTH: f32 = 640.;
85const WINDOW_MIN_HEIGHT: f32 = 480.;
87const WINDOW_MIN_HEIGHT: f32 = 480.;
88const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);
86const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
89const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
87const DATABASE_FILE: &str = "cache.sqlite3";
90const DATABASE_FILE: &str = "cache.sqlite3";
88#[cfg(windows)]
91#[cfg(windows)]
@@ -218,10 +221,12 @@ fn main() {
218 open_store(&path)
221 open_store(&path)
219 };
222 };
220 let store = Arc::new(store);
223 let store = Arc::new(store);
224 let user_input = user_activity::UserInput::new();
221 let receiver = (!arguments.demo)
225 let receiver = (!arguments.demo)
222 .then(|| {
226 .then(|| {
223 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
227 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
224 backend::start(store.clone(), transport, !arguments.read_only)
228 let activity = user_activity::track(user_input.clone());
229 backend::start(store.clone(), transport, !arguments.read_only, activity)
225 });
230 });
226
231
227 let mut application = gpui_kit::application();
232 let mut application = gpui_kit::application();
@@ -247,6 +252,7 @@ fn main() {
247 state
252 state
248 });
253 });
249 cx.set_global(app_state::AppHandle(state.clone()));
254 cx.set_global(app_state::AppHandle(state.clone()));
255 cx.set_global(views::shell::UserInputHandle(user_input));
250 if arguments.demo {
256 if arguments.demo {
251 state.update(cx, |state, cx| {
257 state.update(cx, |state, cx| {
252 demo::seed_directory(state);
258 demo::seed_directory(state);
@@ -290,6 +296,7 @@ fn main() {
290 .detach();
296 .detach();
291 cx.activate(true);
297 cx.activate(true);
292 });
298 });
299 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
293 #[cfg(windows)]
300 #[cfg(windows)]
294 updater::exit_now();
301 updater::exit_now();
295}
302}
crates/app/src/user_activity.rs added +128 −0
@@ -0,0 +1,128 @@
1 use std::sync::Arc;
2 use std::sync::atomic::{AtomicU64, Ordering};
3 use std::time::{Duration, Instant};
4
5 use tokio::sync::watch;
6
7 pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
8 const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
9
10 pub struct UserInput {
11 origin: Instant,
12 last_input_millis: AtomicU64,
13 }
14
15 impl UserInput {
16 pub fn new() -> Arc<Self> {
17 Arc::new(UserInput {
18 origin: Instant::now(),
19 last_input_millis: AtomicU64::new(0),
20 })
21 }
22
23 pub fn touch(&self) {
24 let elapsed = self.origin.elapsed().as_millis() as u64;
25 self.last_input_millis.store(elapsed, Ordering::Relaxed);
26 }
27
28 fn last_input(&self) -> Instant {
29 self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))
30 }
31 }
32
33 pub fn latest_input(app_input: Instant, system_idle: Option<Duration>, now: Instant) -> Instant {
34 match system_idle.and_then(|idle| now.checked_sub(idle)) {
35 Some(system_input) => app_input.max(system_input),
36 None => app_input,
37 }
38 }
39
40 pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {
41 now.saturating_duration_since(last_input) < idle_after
42 }
43
44 pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {
45 let current = is_active(last_input, now, idle_after);
46 (current != previous).then_some(current)
47 }
48
49 pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
50 let (sender, receiver) = watch::channel(true);
51 crate::runtime::handle().spawn(async move {
52 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
53 loop {
54 interval.tick().await;
55 let now = Instant::now();
56 let last_input = latest_input(input.last_input(), system_idle(), now);
57 let previous = *sender.borrow();
58 if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) {
59 sender.send_replace(current);
60 }
61 }
62 });
63 receiver
64 }
65
66 #[cfg(windows)]
67 fn system_idle() -> Option<Duration> {
68 use windows::Win32::System::SystemInformation::GetTickCount;
69 use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
70
71 let mut info = LASTINPUTINFO {
72 cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32,
73 dwTime: 0,
74 };
75 unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| {
76 let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime);
77 Duration::from_millis(u64::from(idle_millis))
78 })
79 }
80
81 #[cfg(not(windows))]
82 fn system_idle() -> Option<Duration> {
83 None
84 }
85
86 #[cfg(test)]
87 mod tests {
88 use super::*;
89
90 fn seconds(count: u64) -> Duration {
91 Duration::from_secs(count)
92 }
93
94 #[test]
95 fn active_until_the_idle_threshold() {
96 let last_input = Instant::now();
97 assert!(is_active(last_input, last_input + seconds(299), IDLE_AFTER));
98 assert!(!is_active(last_input, last_input + seconds(300), IDLE_AFTER));
99 assert!(is_active(last_input + seconds(10), last_input, IDLE_AFTER));
100 }
101
102 #[test]
103 fn only_a_change_of_state_is_reported() {
104 let last_input = Instant::now();
105 assert_eq!(activity_change(true, last_input, last_input + seconds(10), IDLE_AFTER), None);
106 assert_eq!(activity_change(true, last_input, last_input + seconds(301), IDLE_AFTER), Some(false));
107 assert_eq!(activity_change(false, last_input, last_input + seconds(301), IDLE_AFTER), None);
108 assert_eq!(activity_change(false, last_input + seconds(400), last_input + seconds(401), IDLE_AFTER), Some(true));
109 }
110
111 #[test]
112 fn system_input_counts_when_newer_than_app_input() {
113 let now = Instant::now() + seconds(1000);
114 let app_input = now - seconds(900);
115 assert_eq!(latest_input(app_input, Some(seconds(20)), now), now - seconds(20));
116 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
117 assert_eq!(latest_input(app_input, None, now), app_input);
118 }
119
120 #[test]
121 fn touch_moves_the_last_input_forward() {
122 let input = UserInput::new();
123 let before = input.last_input();
124 std::thread::sleep(Duration::from_millis(5));
125 input.touch();
126 assert!(input.last_input() > before);
127 }
128 }
@@ -0,0 +1,128 @@
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::time::{Duration, Instant};
4
5use tokio::sync::watch;
6
7pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
8const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
9
10pub struct UserInput {
11 origin: Instant,
12 last_input_millis: AtomicU64,
13}
14
15impl UserInput {
16 pub fn new() -> Arc<Self> {
17 Arc::new(UserInput {
18 origin: Instant::now(),
19 last_input_millis: AtomicU64::new(0),
20 })
21 }
22
23 pub fn touch(&self) {
24 let elapsed = self.origin.elapsed().as_millis() as u64;
25 self.last_input_millis.store(elapsed, Ordering::Relaxed);
26 }
27
28 fn last_input(&self) -> Instant {
29 self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))
30 }
31}
32
33pub fn latest_input(app_input: Instant, system_idle: Option<Duration>, now: Instant) -> Instant {
34 match system_idle.and_then(|idle| now.checked_sub(idle)) {
35 Some(system_input) => app_input.max(system_input),
36 None => app_input,
37 }
38}
39
40pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {
41 now.saturating_duration_since(last_input) < idle_after
42}
43
44pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {
45 let current = is_active(last_input, now, idle_after);
46 (current != previous).then_some(current)
47}
48
49pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
50 let (sender, receiver) = watch::channel(true);
51 crate::runtime::handle().spawn(async move {
52 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
53 loop {
54 interval.tick().await;
55 let now = Instant::now();
56 let last_input = latest_input(input.last_input(), system_idle(), now);
57 let previous = *sender.borrow();
58 if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) {
59 sender.send_replace(current);
60 }
61 }
62 });
63 receiver
64}
65
66#[cfg(windows)]
67fn system_idle() -> Option<Duration> {
68 use windows::Win32::System::SystemInformation::GetTickCount;
69 use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
70
71 let mut info = LASTINPUTINFO {
72 cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32,
73 dwTime: 0,
74 };
75 unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| {
76 let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime);
77 Duration::from_millis(u64::from(idle_millis))
78 })
79}
80
81#[cfg(not(windows))]
82fn system_idle() -> Option<Duration> {
83 None
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 fn seconds(count: u64) -> Duration {
91 Duration::from_secs(count)
92 }
93
94 #[test]
95 fn active_until_the_idle_threshold() {
96 let last_input = Instant::now();
97 assert!(is_active(last_input, last_input + seconds(299), IDLE_AFTER));
98 assert!(!is_active(last_input, last_input + seconds(300), IDLE_AFTER));
99 assert!(is_active(last_input + seconds(10), last_input, IDLE_AFTER));
100 }
101
102 #[test]
103 fn only_a_change_of_state_is_reported() {
104 let last_input = Instant::now();
105 assert_eq!(activity_change(true, last_input, last_input + seconds(10), IDLE_AFTER), None);
106 assert_eq!(activity_change(true, last_input, last_input + seconds(301), IDLE_AFTER), Some(false));
107 assert_eq!(activity_change(false, last_input, last_input + seconds(301), IDLE_AFTER), None);
108 assert_eq!(activity_change(false, last_input + seconds(400), last_input + seconds(401), IDLE_AFTER), Some(true));
109 }
110
111 #[test]
112 fn system_input_counts_when_newer_than_app_input() {
113 let now = Instant::now() + seconds(1000);
114 let app_input = now - seconds(900);
115 assert_eq!(latest_input(app_input, Some(seconds(20)), now), now - seconds(20));
116 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
117 assert_eq!(latest_input(app_input, None, now), app_input);
118 }
119
120 #[test]
121 fn touch_moves_the_last_input_forward() {
122 let input = UserInput::new();
123 let before = input.last_input();
124 std::thread::sleep(Duration::from_millis(5));
125 input.touch();
126 assert!(input.last_input() > before);
127 }
128}
crates/app/src/views/shell.rs +14 −0
@@ -1,3 +1,5 @@
1 use std::sync::Arc;
2
1 3 use gpui_kit::component::{h_flex, v_flex};
2 4 use gpui_kit::*;
3 5
@@ -29,6 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
29 31 use crate::call::{CallMedia, CallWindows};
30 32 use crate::embedded_web::{Overlays, RootFocus};
31 33 use crate::notice::NoticeAction;
34 use crate::user_activity::UserInput;
32 35 use crate::notify::{NotificationCenter, selection_for};
33 36 use crate::sidebar_model::Step;
34 37 use crate::theme;
@@ -56,6 +59,10 @@ pub struct Startup {
56 59
57 60 pub const ISLAND_GAP: f32 = 6.;
58 61
62 pub struct UserInputHandle(pub Arc<UserInput>);
63
64 impl Global for UserInputHandle {}
65
59 66 pub struct AppShell {
60 67 state: Entity<AppState>,
61 68 rail: Entity<RailView>,
@@ -73,6 +80,7 @@ pub struct AppShell {
73 80 focus_handle: FocusHandle,
74 81 open_target: Option<OpenTarget>,
75 82 update: UpdateStatus,
83 user_input: Arc<UserInput>,
76 84 _subscription: Subscription,
77 85 _call_media_observation: Subscription,
78 86 _panel_subscriptions: [Subscription; 2],
@@ -156,7 +164,9 @@ impl AppShell {
156 164 cx.set_global(RootFocus(focus_handle.clone()));
157 165 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
158 166 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
167 let user_input = cx.global::<UserInputHandle>().0.clone();
159 168 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
169 this.user_input.touch();
160 170 if event.keystroke.key == "escape" {
161 171 this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
162 172 }
@@ -185,6 +195,7 @@ impl AppShell {
185 195 focus_handle,
186 196 open_target,
187 197 update: UpdateStatus::UpToDate,
198 user_input,
188 199 _subscription: subscription,
189 200 _call_media_observation: call_media_observation,
190 201 _panel_subscriptions: panel_subscriptions,
@@ -615,6 +626,9 @@ impl Render for AppShell {
615 626 .id("app-shell")
616 627 .key_context("AppShell")
617 628 .track_focus(&self.focus_handle)
629 .on_mouse_move(cx.listener(|this, _, _, _| this.user_input.touch()))
630 .capture_any_mouse_down(cx.listener(|this, _, _, _| this.user_input.touch()))
631 .on_scroll_wheel(cx.listener(|this, _, _, _| this.user_input.touch()))
618 632 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
619 633 this.toggle_switcher("", window, cx);
620 634 }))
@@ -1,3 +1,5 @@
1use std::sync::Arc;
2
1use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::*;
4use gpui_kit::*;
3
5
@@ -29,6 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
29use crate::call::{CallMedia, CallWindows};
31use crate::call::{CallMedia, CallWindows};
30use crate::embedded_web::{Overlays, RootFocus};
32use crate::embedded_web::{Overlays, RootFocus};
31use crate::notice::NoticeAction;
33use crate::notice::NoticeAction;
34use crate::user_activity::UserInput;
32use crate::notify::{NotificationCenter, selection_for};
35use crate::notify::{NotificationCenter, selection_for};
33use crate::sidebar_model::Step;
36use crate::sidebar_model::Step;
34use crate::theme;
37use crate::theme;
@@ -56,6 +59,10 @@ pub struct Startup {
56
59
57pub const ISLAND_GAP: f32 = 6.;
60pub const ISLAND_GAP: f32 = 6.;
58
61
62pub struct UserInputHandle(pub Arc<UserInput>);
63
64impl Global for UserInputHandle {}
65
59pub struct AppShell {
66pub struct AppShell {
60 state: Entity<AppState>,
67 state: Entity<AppState>,
61 rail: Entity<RailView>,
68 rail: Entity<RailView>,
@@ -73,6 +80,7 @@ pub struct AppShell {
73 focus_handle: FocusHandle,
80 focus_handle: FocusHandle,
74 open_target: Option<OpenTarget>,
81 open_target: Option<OpenTarget>,
75 update: UpdateStatus,
82 update: UpdateStatus,
83 user_input: Arc<UserInput>,
76 _subscription: Subscription,
84 _subscription: Subscription,
77 _call_media_observation: Subscription,
85 _call_media_observation: Subscription,
78 _panel_subscriptions: [Subscription; 2],
86 _panel_subscriptions: [Subscription; 2],
@@ -156,7 +164,9 @@ impl AppShell {
156 cx.set_global(RootFocus(focus_handle.clone()));
164 cx.set_global(RootFocus(focus_handle.clone()));
157 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
165 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
158 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
166 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
167 let user_input = cx.global::<UserInputHandle>().0.clone();
159 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
168 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
169 this.user_input.touch();
160 if event.keystroke.key == "escape" {
170 if event.keystroke.key == "escape" {
161 this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
171 this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
162 }
172 }
@@ -185,6 +195,7 @@ impl AppShell {
185 focus_handle,
195 focus_handle,
186 open_target,
196 open_target,
187 update: UpdateStatus::UpToDate,
197 update: UpdateStatus::UpToDate,
198 user_input,
188 _subscription: subscription,
199 _subscription: subscription,
189 _call_media_observation: call_media_observation,
200 _call_media_observation: call_media_observation,
190 _panel_subscriptions: panel_subscriptions,
201 _panel_subscriptions: panel_subscriptions,
@@ -615,6 +626,9 @@ impl Render for AppShell {
615 .id("app-shell")
626 .id("app-shell")
616 .key_context("AppShell")
627 .key_context("AppShell")
617 .track_focus(&self.focus_handle)
628 .track_focus(&self.focus_handle)
629 .on_mouse_move(cx.listener(|this, _, _, _| this.user_input.touch()))
630 .capture_any_mouse_down(cx.listener(|this, _, _, _| this.user_input.touch()))
631 .on_scroll_wheel(cx.listener(|this, _, _, _| this.user_input.touch()))
618 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
632 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
619 this.toggle_switcher("", window, cx);
633 this.toggle_switcher("", window, cx);
620 }))
634 }))
crates/chatsvc/assets/trouter.js +32 −5
@@ -1,5 +1,5 @@
1 1 (() => {
2 const VERSION = 5;
2 const VERSION = 6;
3 3 const GLOBAL_NAME = '__chatsvcTrouter';
4 4 const BINDING_NAME = '__chatsvcRealtime';
5 5 const EPID_KEY = '__chatsvcEpid';
@@ -12,6 +12,8 @@
12 12 const REREGISTER_MS = 40 * 60 * 1000;
13 13 const CONNECT_TIMEOUT_MS = 20000;
14 14 const MAX_BACKOFF_MS = 30000;
15 const ACTIVITY_DEBOUNCE_MS = 1000;
16 const ACTIVITY_ACK_TIMEOUT_MS = 10000;
15 17 const MAX_QUEUE = 200;
16 18 const MAX_PRESENCE_ENTRIES = 1000;
17 19 const MAX_PRESENCE_FIELD = 128;
@@ -40,7 +42,7 @@
40 42
41 43 const state = {
42 44 token: null, host: null, epid: loadEpid(), socket: null, ready: false,
43 closed: false, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
45 closed: false, activity: 'inactive', sentActivity: null, activityAckId: 0, activityTimer: null, activityResendTimer: null, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
44 46 };
45 47
46 48 const flush = () => {
@@ -142,7 +144,25 @@
142 144 };
143 145 const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };
144 146 const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));
145 const activity = () => sendEvent('user.activity', [{state: 'active', cv: crypto.randomUUID()}]);
147 const transmitActivity = (resend) => {
148 clearTimeout(state.activityTimer);
149 clearTimeout(state.activityResendTimer);
150 if (!state.ready) return;
151 sendEvent('user.activity', [{state: state.activity, cv: crypto.randomUUID()}]);
152 state.sentActivity = state.activity;
153 state.activityAckId = state.ackCounter;
154 if (!resend) state.activityResendTimer = setTimeout(() => transmitActivity(true), ACTIVITY_ACK_TIMEOUT_MS);
155 };
156 const setActivity = (next) => {
157 if (next !== 'active' && next !== 'inactive') return;
158 state.activity = next;
159 clearTimeout(state.activityTimer);
160 if (!state.ready || next === state.sentActivity) return;
161 state.activityTimer = setTimeout(() => transmitActivity(false), ACTIVITY_DEBOUNCE_MS);
162 };
163 const acknowledgeActivity = (data) => {
164 if (Number.parseInt(data, 10) === state.activityAckId) clearTimeout(state.activityResendTimer);
165 };
146 166
147 167 const register = async (surl) => {
148 168 state.surl = surl || state.surl;
@@ -192,8 +212,8 @@
192 212 if (event.name === 'trouter.connected') {
193 213 try {
194 214 await register(event.args[0].surl);
195 activity();
196 215 state.ready = true;
216 transmitActivity(false);
197 217 state.retry = 0;
198 218 announceEndpoint();
199 219 status('connected');
@@ -206,6 +226,8 @@
206 226 const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];
207 227 status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));
208 228 }
229 } else if (packet.type === '6') {
230 acknowledgeActivity(packet.data);
209 231 } else if (packet.type === '3') {
210 232 let request;
211 233 try { request = JSON.parse(packet.data); } catch (error) { return; }
@@ -240,6 +262,8 @@
240 262 const wasReady = state.ready;
241 263 state.socket = null;
242 264 state.ready = false;
265 clearTimeout(state.activityTimer);
266 clearTimeout(state.activityResendTimer);
243 267 if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');
244 268 scheduleReconnect();
245 269 };
@@ -249,7 +273,6 @@
249 273 if (!state.socket || state.socket.readyState !== 1) return;
250 274 if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }
251 275 sendEvent('ping', []);
252 activity();
253 276 if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {
254 277 register().catch((error) => status('error', registerDetail(error)));
255 278 }
@@ -259,6 +282,8 @@
259 282 state.closed = true;
260 283 clearInterval(maintain);
261 284 clearTimeout(state.reconnectTimer);
285 clearTimeout(state.activityTimer);
286 clearTimeout(state.activityResendTimer);
262 287 for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer);
263 288 state.pendingReplies.clear();
264 289 if (state.socket) state.socket.close();
@@ -270,6 +295,7 @@
270 295 ensure: (config) => {
271 296 state.token = config.token;
272 297 state.host = config.host;
298 setActivity(config.activity);
273 299 connect();
274 300 if (state.ready) {
275 301 announceEndpoint();
@@ -279,6 +305,7 @@
279 305 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
280 306 },
281 307 shutdown,
308 setActivity,
282 309 reply: (id, status, body) => answer(id, status, body),
283 310 stop: async () => {
284 311 let unregistered = null;
@@ -1,5 +1,5 @@
1(() => {
1(() => {
2 const VERSION = 5;
2 const VERSION = 6;
3 const GLOBAL_NAME = '__chatsvcTrouter';
3 const GLOBAL_NAME = '__chatsvcTrouter';
4 const BINDING_NAME = '__chatsvcRealtime';
4 const BINDING_NAME = '__chatsvcRealtime';
5 const EPID_KEY = '__chatsvcEpid';
5 const EPID_KEY = '__chatsvcEpid';
@@ -12,6 +12,8 @@
12 const REREGISTER_MS = 40 * 60 * 1000;
12 const REREGISTER_MS = 40 * 60 * 1000;
13 const CONNECT_TIMEOUT_MS = 20000;
13 const CONNECT_TIMEOUT_MS = 20000;
14 const MAX_BACKOFF_MS = 30000;
14 const MAX_BACKOFF_MS = 30000;
15 const ACTIVITY_DEBOUNCE_MS = 1000;
16 const ACTIVITY_ACK_TIMEOUT_MS = 10000;
15 const MAX_QUEUE = 200;
17 const MAX_QUEUE = 200;
16 const MAX_PRESENCE_ENTRIES = 1000;
18 const MAX_PRESENCE_ENTRIES = 1000;
17 const MAX_PRESENCE_FIELD = 128;
19 const MAX_PRESENCE_FIELD = 128;
@@ -40,7 +42,7 @@
40
42
41 const state = {
43 const state = {
42 token: null, host: null, epid: loadEpid(), socket: null, ready: false,
44 token: null, host: null, epid: loadEpid(), socket: null, ready: false,
43 closed: false, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
45 closed: false, activity: 'inactive', sentActivity: null, activityAckId: 0, activityTimer: null, activityResendTimer: null, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
44 };
46 };
45
47
46 const flush = () => {
48 const flush = () => {
@@ -142,7 +144,25 @@
142 };
144 };
143 const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };
145 const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };
144 const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));
146 const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));
145 const activity = () => sendEvent('user.activity', [{state: 'active', cv: crypto.randomUUID()}]);
147 const transmitActivity = (resend) => {
148 clearTimeout(state.activityTimer);
149 clearTimeout(state.activityResendTimer);
150 if (!state.ready) return;
151 sendEvent('user.activity', [{state: state.activity, cv: crypto.randomUUID()}]);
152 state.sentActivity = state.activity;
153 state.activityAckId = state.ackCounter;
154 if (!resend) state.activityResendTimer = setTimeout(() => transmitActivity(true), ACTIVITY_ACK_TIMEOUT_MS);
155 };
156 const setActivity = (next) => {
157 if (next !== 'active' && next !== 'inactive') return;
158 state.activity = next;
159 clearTimeout(state.activityTimer);
160 if (!state.ready || next === state.sentActivity) return;
161 state.activityTimer = setTimeout(() => transmitActivity(false), ACTIVITY_DEBOUNCE_MS);
162 };
163 const acknowledgeActivity = (data) => {
164 if (Number.parseInt(data, 10) === state.activityAckId) clearTimeout(state.activityResendTimer);
165 };
146
166
147 const register = async (surl) => {
167 const register = async (surl) => {
148 state.surl = surl || state.surl;
168 state.surl = surl || state.surl;
@@ -192,8 +212,8 @@
192 if (event.name === 'trouter.connected') {
212 if (event.name === 'trouter.connected') {
193 try {
213 try {
194 await register(event.args[0].surl);
214 await register(event.args[0].surl);
195 activity();
196 state.ready = true;
215 state.ready = true;
216 transmitActivity(false);
197 state.retry = 0;
217 state.retry = 0;
198 announceEndpoint();
218 announceEndpoint();
199 status('connected');
219 status('connected');
@@ -206,6 +226,8 @@
206 const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];
226 const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];
207 status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));
227 status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));
208 }
228 }
229 } else if (packet.type === '6') {
230 acknowledgeActivity(packet.data);
209 } else if (packet.type === '3') {
231 } else if (packet.type === '3') {
210 let request;
232 let request;
211 try { request = JSON.parse(packet.data); } catch (error) { return; }
233 try { request = JSON.parse(packet.data); } catch (error) { return; }
@@ -240,6 +262,8 @@
240 const wasReady = state.ready;
262 const wasReady = state.ready;
241 state.socket = null;
263 state.socket = null;
242 state.ready = false;
264 state.ready = false;
265 clearTimeout(state.activityTimer);
266 clearTimeout(state.activityResendTimer);
243 if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');
267 if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');
244 scheduleReconnect();
268 scheduleReconnect();
245 };
269 };
@@ -249,7 +273,6 @@
249 if (!state.socket || state.socket.readyState !== 1) return;
273 if (!state.socket || state.socket.readyState !== 1) return;
250 if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }
274 if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }
251 sendEvent('ping', []);
275 sendEvent('ping', []);
252 activity();
253 if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {
276 if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {
254 register().catch((error) => status('error', registerDetail(error)));
277 register().catch((error) => status('error', registerDetail(error)));
255 }
278 }
@@ -259,6 +282,8 @@
259 state.closed = true;
282 state.closed = true;
260 clearInterval(maintain);
283 clearInterval(maintain);
261 clearTimeout(state.reconnectTimer);
284 clearTimeout(state.reconnectTimer);
285 clearTimeout(state.activityTimer);
286 clearTimeout(state.activityResendTimer);
262 for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer);
287 for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer);
263 state.pendingReplies.clear();
288 state.pendingReplies.clear();
264 if (state.socket) state.socket.close();
289 if (state.socket) state.socket.close();
@@ -270,6 +295,7 @@
270 ensure: (config) => {
295 ensure: (config) => {
271 state.token = config.token;
296 state.token = config.token;
272 state.host = config.host;
297 state.host = config.host;
298 setActivity(config.activity);
273 connect();
299 connect();
274 if (state.ready) {
300 if (state.ready) {
275 announceEndpoint();
301 announceEndpoint();
@@ -279,6 +305,7 @@
279 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
305 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
280 },
306 },
281 shutdown,
307 shutdown,
308 setActivity,
282 reply: (id, status, body) => answer(id, status, body),
309 reply: (id, status, body) => answer(id, status, body),
283 stop: async () => {
310 stop: async () => {
284 let unregistered = null;
311 let unregistered = null;
crates/chatsvc/examples/presence_endpoint_probe.rs added +87 −0
@@ -0,0 +1,87 @@
1 use std::time::Duration;
2
3 use chatsvc::{PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
4 use session::{DEFAULT_ENDPOINT, Session};
5
6 const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
7 const SETTLE: Duration = Duration::from_secs(10);
8
9 #[tokio::main]
10 async fn main() {
11 let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12 let inactive_wait = std::env::args()
13 .nth(2)
14 .and_then(|value| value.parse().ok())
15 .map_or(SETTLE, Duration::from_secs);
16 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
17 let session = Session::connect(&endpoint).await.expect("browser");
18 let presence = PresenceService::new(&session);
19
20 let config = RealtimeConfig {
21 initially_active: true,
22 ..RealtimeConfig::default()
23 };
24 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 println!("# trouter connected");
27
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id).await));
29 realtime.set_activity(true);
30 println!("# sent active");
31 tokio::time::sleep(SETTLE).await;
32 print_own_presence(&presence, &user_id).await;
33
34 realtime.set_activity(false);
35 println!("# sent inactive");
36 tokio::time::sleep(inactive_wait).await;
37 print_own_presence(&presence, &user_id).await;
38
39 println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
40 println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
41 realtime.stop().await;
42 println!("# stopped");
43 }
44
45 async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
46 let wait = async {
47 let mut endpoint_id = None;
48 let mut connected = false;
49 while let Some(event) = realtime.recv().await {
50 match event {
51 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
53 _ => {}
54 }
55 if connected && let Some(endpoint_id) = endpoint_id.take() {
56 return endpoint_id;
57 }
58 }
59 panic!("realtime closed before connecting");
60 };
61 tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
62 }
63
64 async fn print_own_presence(presence: &PresenceService, user_id: &str) {
65 match presence.status(user_id).await {
66 Ok(status) => println!(
67 "own presence: availability={} activity={}",
68 status.availability,
69 status.activity.as_deref().unwrap_or("-")
70 ),
71 Err(error) => println!("own presence: failed {}", status_of(&error)),
72 }
73 }
74
75 fn outcome(result: chatsvc::Result<()>) -> String {
76 match result {
77 Ok(()) => "ok".to_owned(),
78 Err(error) => format!("failed {}", status_of(&error)),
79 }
80 }
81
82 fn status_of(error: &chatsvc::Error) -> String {
83 match error {
84 chatsvc::Error::Session(session::Error::Api { status, .. }) => format!("http {status}"),
85 _ => "no http status".to_owned(),
86 }
87 }
@@ -0,0 +1,87 @@
1use std::time::Duration;
2
3use chatsvc::{PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
4use session::{DEFAULT_ENDPOINT, Session};
5
6const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
7const SETTLE: Duration = Duration::from_secs(10);
8
9#[tokio::main]
10async fn main() {
11 let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12 let inactive_wait = std::env::args()
13 .nth(2)
14 .and_then(|value| value.parse().ok())
15 .map_or(SETTLE, Duration::from_secs);
16 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
17 let session = Session::connect(&endpoint).await.expect("browser");
18 let presence = PresenceService::new(&session);
19
20 let config = RealtimeConfig {
21 initially_active: true,
22 ..RealtimeConfig::default()
23 };
24 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 println!("# trouter connected");
27
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id).await));
29 realtime.set_activity(true);
30 println!("# sent active");
31 tokio::time::sleep(SETTLE).await;
32 print_own_presence(&presence, &user_id).await;
33
34 realtime.set_activity(false);
35 println!("# sent inactive");
36 tokio::time::sleep(inactive_wait).await;
37 print_own_presence(&presence, &user_id).await;
38
39 println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
40 println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
41 realtime.stop().await;
42 println!("# stopped");
43}
44
45async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
46 let wait = async {
47 let mut endpoint_id = None;
48 let mut connected = false;
49 while let Some(event) = realtime.recv().await {
50 match event {
51 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
53 _ => {}
54 }
55 if connected && let Some(endpoint_id) = endpoint_id.take() {
56 return endpoint_id;
57 }
58 }
59 panic!("realtime closed before connecting");
60 };
61 tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
62}
63
64async fn print_own_presence(presence: &PresenceService, user_id: &str) {
65 match presence.status(user_id).await {
66 Ok(status) => println!(
67 "own presence: availability={} activity={}",
68 status.availability,
69 status.activity.as_deref().unwrap_or("-")
70 ),
71 Err(error) => println!("own presence: failed {}", status_of(&error)),
72 }
73}
74
75fn outcome(result: chatsvc::Result<()>) -> String {
76 match result {
77 Ok(()) => "ok".to_owned(),
78 Err(error) => format!("failed {}", status_of(&error)),
79 }
80}
81
82fn status_of(error: &chatsvc::Error) -> String {
83 match error {
84 chatsvc::Error::Session(session::Error::Api { status, .. }) => format!("http {status}"),
85 _ => "no http status".to_owned(),
86 }
87}
crates/chatsvc/src/lib.rs +1 −1
@@ -44,7 +44,7 @@ pub use pins::{
44 44 };
45 45 pub use presence::{
46 46 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47 WorkLocationKind, WorkLocationSource,
47 WorkLocationKind, WorkLocationSource, is_endpoint_missing,
48 48 };
49 49 pub use reactions::{emotion_key, emotion_keys};
50 50 pub use realtime::{
@@ -44,7 +44,7 @@ pub use pins::{
44};
44};
45pub use presence::{
45pub use presence::{
46 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
46 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47 WorkLocationKind, WorkLocationSource,
47 WorkLocationKind, WorkLocationSource, is_endpoint_missing,
48};
48};
49pub use reactions::{emotion_key, emotion_keys};
49pub use reactions::{emotion_key, emotion_keys};
50pub use realtime::{
50pub use realtime::{
crates/chatsvc/src/presence.rs +134 −3
@@ -14,6 +14,9 @@ const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>";
14 14 const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";
15 15 const NEVER_YEAR: i32 = 9999;
16 16 const OFFLINE_ACTIVITY: &str = "OffWork";
17 const DESKTOP_USER_AGENT: &str = "Teams-V2-Desktop";
18 const WEB_USER_AGENT: &str = "Teams-V2-Web";
19 const ENDPOINT_ID_HEADER: &str = "x-ms-endpoint-id";
17 20
18 21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 22 pub enum ForcedKind {
@@ -129,6 +132,31 @@ impl<T: CardTransport> PresenceService<T> {
129 132 self.send(request, &url).await.map(drop)
130 133 }
131 134
135 pub async fn register_endpoint(&self, endpoint_id: &str) -> Result<()> {
136 let url = format!("{BASE_URL}/me/endpoints/");
137 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id));
138 request.headers = endpoint_headers(endpoint_id);
139 self.send(request, &url).await.map(drop)
140 }
141
142 pub async fn unregister_endpoint(&self, endpoint_id: &str) -> Result<()> {
143 let url = format!("{BASE_URL}/me/endpoints/{endpoint_id}");
144 let mut request = Request {
145 method: Method::Delete,
146 ..Request::get(&url)
147 };
148 request.headers = endpoint_headers(endpoint_id);
149 self.send(request, &url).await.map(drop)
150 }
151
152 pub async fn report_activity(&self, endpoint_id: &str, active: bool) -> Result<()> {
153 let url = format!("{BASE_URL}/me/reportmyactivity/");
154 let body = json!({"endpointId": endpoint_id, "isActive": active});
155 let mut request = Request::with_body(Method::Post, &url, body);
156 request.headers = endpoint_headers(endpoint_id);
157 self.send(request, &url).await.map(drop)
158 }
159
132 160 pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {
133 161 let url = format!("{BASE_URL}/me/publishnote");
134 162 let body = note.map_or_else(|| json!({"message": ""}), note_body);
@@ -165,7 +193,9 @@ impl<T: CardTransport> PresenceService<T> {
165 193 }
166 194
167 195 async fn send(&self, mut request: Request, url: &str) -> Result<Value> {
168 request.headers = service_headers();
196 if request.headers.is_empty() {
197 request.headers = service_headers(WEB_USER_AGENT);
198 }
169 199 let answer = self
170 200 .transport
171 201 .send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))
@@ -181,9 +211,29 @@ impl<T: CardTransport> PresenceService<T> {
181 211 }
182 212 }
183 213
184 fn service_headers() -> Vec<(String, String)> {
214 pub fn is_endpoint_missing(error: &Error) -> bool {
215 matches!(error, Error::Session(session::Error::Api { status: 404, .. }))
216 }
217
218 fn endpoint_body(endpoint_id: &str) -> Value {
219 json!({
220 "id": endpoint_id,
221 "availability": "Available",
222 "activity": "Available",
223 "activityReporting": "Transport",
224 "deviceType": "Desktop",
225 })
226 }
227
228 fn endpoint_headers(endpoint_id: &str) -> Vec<(String, String)> {
229 let mut headers = service_headers(DESKTOP_USER_AGENT);
230 headers.insert(1, (ENDPOINT_ID_HEADER.into(), endpoint_id.to_owned()));
231 headers
232 }
233
234 fn service_headers(user_agent: &str) -> Vec<(String, String)> {
185 235 vec![
186 ("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
236 ("x-ms-client-user-agent".into(), user_agent.into()),
187 237 ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
188 238 ("x-ms-client-version".into(), CLIENT_VERSION.into()),
189 239 ]
@@ -418,6 +468,87 @@ mod tests {
418 468 );
419 469 }
420 470
471 fn header_pairs(request: &Request) -> Vec<(&str, &str)> {
472 request
473 .headers
474 .iter()
475 .filter(|(name, _)| name != "x-ms-correlation-id")
476 .map(|(name, value)| (name.as_str(), value.as_str()))
477 .collect()
478 }
479
480 #[tokio::test]
481 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
482 let service = service(200, Value::Null);
483 service.register_endpoint("epid-1").await.unwrap();
484 let (request, scope) = only_request(&service);
485 assert_eq!(request.method, Method::Put);
486 assert_eq!(
487 request.url,
488 "https://presence.teams.microsoft.com/v1/me/endpoints/"
489 );
490 assert_eq!(
491 request.body,
492 Some(json!({
493 "id": "epid-1",
494 "availability": "Available",
495 "activity": "Available",
496 "activityReporting": "Transport",
497 "deviceType": "Desktop",
498 }))
499 );
500 assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));
501 assert_eq!(
502 header_pairs(&request),
503 [
504 ("x-ms-client-user-agent", "Teams-V2-Desktop"),
505 ("x-ms-endpoint-id", "epid-1"),
506 ("x-ms-client-version", CLIENT_VERSION),
507 ]
508 );
509 }
510
511 #[tokio::test]
512 async fn unregister_endpoint_deletes_by_id_without_body() {
513 let service = service(200, Value::Null);
514 service.unregister_endpoint("epid-1").await.unwrap();
515 let (request, _) = only_request(&service);
516 assert_eq!(request.method, Method::Delete);
517 assert_eq!(
518 request.url,
519 "https://presence.teams.microsoft.com/v1/me/endpoints/epid-1"
520 );
521 assert_eq!(request.body, None);
522 assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));
523 }
524
525 #[tokio::test]
526 async fn report_activity_posts_the_state_for_the_endpoint() {
527 let service = service(200, Value::Null);
528 service.report_activity("epid-1", false).await.unwrap();
529 let (request, _) = only_request(&service);
530 assert_eq!(request.method, Method::Post);
531 assert_eq!(
532 request.url,
533 "https://presence.teams.microsoft.com/v1/me/reportmyactivity/"
534 );
535 assert_eq!(
536 request.body,
537 Some(json!({"endpointId": "epid-1", "isActive": false}))
538 );
539 assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));
540 }
541
542 #[tokio::test]
543 async fn not_found_marks_the_endpoint_as_missing() {
544 let service = service(404, Value::Null);
545 let error = service.report_activity("epid-1", true).await.unwrap_err();
546 assert!(is_endpoint_missing(&error));
547 let service = self::service(500, Value::Null);
548 let error = service.report_activity("epid-1", true).await.unwrap_err();
549 assert!(!is_endpoint_missing(&error));
550 }
551
421 552 #[tokio::test]
422 553 async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {
423 554 let service = service(200, Value::Null);
@@ -14,6 +14,9 @@ const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>";
14const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";
14const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";
15const NEVER_YEAR: i32 = 9999;
15const NEVER_YEAR: i32 = 9999;
16const OFFLINE_ACTIVITY: &str = "OffWork";
16const OFFLINE_ACTIVITY: &str = "OffWork";
17const DESKTOP_USER_AGENT: &str = "Teams-V2-Desktop";
18const WEB_USER_AGENT: &str = "Teams-V2-Web";
19const ENDPOINT_ID_HEADER: &str = "x-ms-endpoint-id";
17
20
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ForcedKind {
22pub enum ForcedKind {
@@ -129,6 +132,31 @@ impl<T: CardTransport> PresenceService<T> {
129 self.send(request, &url).await.map(drop)
132 self.send(request, &url).await.map(drop)
130 }
133 }
131
134
135 pub async fn register_endpoint(&self, endpoint_id: &str) -> Result<()> {
136 let url = format!("{BASE_URL}/me/endpoints/");
137 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id));
138 request.headers = endpoint_headers(endpoint_id);
139 self.send(request, &url).await.map(drop)
140 }
141
142 pub async fn unregister_endpoint(&self, endpoint_id: &str) -> Result<()> {
143 let url = format!("{BASE_URL}/me/endpoints/{endpoint_id}");
144 let mut request = Request {
145 method: Method::Delete,
146 ..Request::get(&url)
147 };
148 request.headers = endpoint_headers(endpoint_id);
149 self.send(request, &url).await.map(drop)
150 }
151
152 pub async fn report_activity(&self, endpoint_id: &str, active: bool) -> Result<()> {
153 let url = format!("{BASE_URL}/me/reportmyactivity/");
154 let body = json!({"endpointId": endpoint_id, "isActive": active});
155 let mut request = Request::with_body(Method::Post, &url, body);
156 request.headers = endpoint_headers(endpoint_id);
157 self.send(request, &url).await.map(drop)
158 }
159
132 pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {
160 pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {
133 let url = format!("{BASE_URL}/me/publishnote");
161 let url = format!("{BASE_URL}/me/publishnote");
134 let body = note.map_or_else(|| json!({"message": ""}), note_body);
162 let body = note.map_or_else(|| json!({"message": ""}), note_body);
@@ -165,7 +193,9 @@ impl<T: CardTransport> PresenceService<T> {
165 }
193 }
166
194
167 async fn send(&self, mut request: Request, url: &str) -> Result<Value> {
195 async fn send(&self, mut request: Request, url: &str) -> Result<Value> {
168 request.headers = service_headers();
196 if request.headers.is_empty() {
197 request.headers = service_headers(WEB_USER_AGENT);
198 }
169 let answer = self
199 let answer = self
170 .transport
200 .transport
171 .send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))
201 .send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))
@@ -181,9 +211,29 @@ impl<T: CardTransport> PresenceService<T> {
181 }
211 }
182}
212}
183
213
184fn service_headers() -> Vec<(String, String)> {
214pub fn is_endpoint_missing(error: &Error) -> bool {
215 matches!(error, Error::Session(session::Error::Api { status: 404, .. }))
216}
217
218fn endpoint_body(endpoint_id: &str) -> Value {
219 json!({
220 "id": endpoint_id,
221 "availability": "Available",
222 "activity": "Available",
223 "activityReporting": "Transport",
224 "deviceType": "Desktop",
225 })
226}
227
228fn endpoint_headers(endpoint_id: &str) -> Vec<(String, String)> {
229 let mut headers = service_headers(DESKTOP_USER_AGENT);
230 headers.insert(1, (ENDPOINT_ID_HEADER.into(), endpoint_id.to_owned()));
231 headers
232}
233
234fn service_headers(user_agent: &str) -> Vec<(String, String)> {
185 vec![
235 vec![
186 ("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
236 ("x-ms-client-user-agent".into(), user_agent.into()),
187 ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
237 ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
188 ("x-ms-client-version".into(), CLIENT_VERSION.into()),
238 ("x-ms-client-version".into(), CLIENT_VERSION.into()),
189 ]
239 ]
@@ -418,6 +468,87 @@ mod tests {
418 );
468 );
419 }
469 }
420
470
471 fn header_pairs(request: &Request) -> Vec<(&str, &str)> {
472 request
473 .headers
474 .iter()
475 .filter(|(name, _)| name != "x-ms-correlation-id")
476 .map(|(name, value)| (name.as_str(), value.as_str()))
477 .collect()
478 }
479
480 #[tokio::test]
481 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
482 let service = service(200, Value::Null);
483 service.register_endpoint("epid-1").await.unwrap();
484 let (request, scope) = only_request(&service);
485 assert_eq!(request.method, Method::Put);
486 assert_eq!(
487 request.url,
488 "https://presence.teams.microsoft.com/v1/me/endpoints/"
489 );
490 assert_eq!(
491 request.body,
492 Some(json!({
493 "id": "epid-1",
494 "availability": "Available",
495 "activity": "Available",
496 "activityReporting": "Transport",
497 "deviceType": "Desktop",
498 }))
499 );
500 assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));
501 assert_eq!(
502 header_pairs(&request),
503 [
504 ("x-ms-client-user-agent", "Teams-V2-Desktop"),
505 ("x-ms-endpoint-id", "epid-1"),
506 ("x-ms-client-version", CLIENT_VERSION),
507 ]
508 );
509 }
510
511 #[tokio::test]
512 async fn unregister_endpoint_deletes_by_id_without_body() {
513 let service = service(200, Value::Null);
514 service.unregister_endpoint("epid-1").await.unwrap();
515 let (request, _) = only_request(&service);
516 assert_eq!(request.method, Method::Delete);
517 assert_eq!(
518 request.url,
519 "https://presence.teams.microsoft.com/v1/me/endpoints/epid-1"
520 );
521 assert_eq!(request.body, None);
522 assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));
523 }
524
525 #[tokio::test]
526 async fn report_activity_posts_the_state_for_the_endpoint() {
527 let service = service(200, Value::Null);
528 service.report_activity("epid-1", false).await.unwrap();
529 let (request, _) = only_request(&service);
530 assert_eq!(request.method, Method::Post);
531 assert_eq!(
532 request.url,
533 "https://presence.teams.microsoft.com/v1/me/reportmyactivity/"
534 );
535 assert_eq!(
536 request.body,
537 Some(json!({"endpointId": "epid-1", "isActive": false}))
538 );
539 assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));
540 }
541
542 #[tokio::test]
543 async fn not_found_marks_the_endpoint_as_missing() {
544 let service = service(404, Value::Null);
545 let error = service.report_activity("epid-1", true).await.unwrap_err();
546 assert!(is_endpoint_missing(&error));
547 let service = self::service(500, Value::Null);
548 let error = service.report_activity("epid-1", true).await.unwrap_err();
549 assert!(!is_endpoint_missing(&error));
550 }
551
421 #[tokio::test]
552 #[tokio::test]
422 async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {
553 async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {
423 let service = service(200, Value::Null);
554 let service = service(200, Value::Null);
crates/chatsvc/src/realtime/mod.rs +11 −1
@@ -9,7 +9,7 @@ use std::time::Duration;
9 9
10 10 use futures_util::Stream;
11 11 use session::Session;
12 use tokio::sync::{mpsc, oneshot};
12 use tokio::sync::{mpsc, oneshot, watch};
13 13 use tokio::task::JoinHandle;
14 14
15 15 pub use event::{
@@ -35,6 +35,7 @@ pub struct RealtimeConfig {
35 35 pub instance: InstanceNames,
36 36 pub forward_callbacks: bool,
37 37 pub ringable: bool,
38 pub initially_active: bool,
38 39 }
39 40
40 41 /// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -67,6 +68,7 @@ impl Default for RealtimeConfig {
67 68 instance: InstanceNames::default(),
68 69 forward_callbacks: false,
69 70 ringable: false,
71 initially_active: false,
70 72 }
71 73 }
72 74 }
@@ -76,6 +78,7 @@ pub struct Realtime {
76 78 events: mpsc::UnboundedReceiver<RealtimeEvent>,
77 79 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
78 80 replier: CallbackReplier,
81 activity: watch::Sender<bool>,
79 82 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
80 83 task: JoinHandle<()>,
81 84 }
@@ -94,6 +97,7 @@ impl Realtime {
94 97 let (output, events) = mpsc::unbounded_channel();
95 98 let (callback_output, callbacks) = mpsc::unbounded_channel();
96 99 let (reply_sender, replies) = mpsc::unbounded_channel();
100 let (activity, activity_receiver) = watch::channel(config.initially_active);
97 101 let (stop, stop_receiver) = oneshot::channel();
98 102 let mut runner = Runner::new(
99 103 session,
@@ -105,6 +109,7 @@ impl Realtime {
105 109 output: callback_output,
106 110 replies,
107 111 },
112 activity_receiver,
108 113 );
109 114 if let Err(error) = runner.ensure().await {
110 115 attached.shutdown().await;
@@ -118,6 +123,7 @@ impl Realtime {
118 123 replier: CallbackReplier {
119 124 sender: reply_sender,
120 125 },
126 activity,
121 127 stop: Some(stop),
122 128 task,
123 129 })
@@ -140,6 +146,10 @@ impl Realtime {
140 146 self.replier.clone()
141 147 }
142 148
149 pub fn set_activity(&self, active: bool) {
150 self.activity.send_replace(active);
151 }
152
143 153 /// Deletes the registration and closes the page-side socket.
144 154 pub async fn stop(mut self) {
145 155 if let Some(stop) = self.stop.take() {
@@ -9,7 +9,7 @@ use std::time::Duration;
9
9
10use futures_util::Stream;
10use futures_util::Stream;
11use session::Session;
11use session::Session;
12use tokio::sync::{mpsc, oneshot};
12use tokio::sync::{mpsc, oneshot, watch};
13use tokio::task::JoinHandle;
13use tokio::task::JoinHandle;
14
14
15pub use event::{
15pub use event::{
@@ -35,6 +35,7 @@ pub struct RealtimeConfig {
35 pub instance: InstanceNames,
35 pub instance: InstanceNames,
36 pub forward_callbacks: bool,
36 pub forward_callbacks: bool,
37 pub ringable: bool,
37 pub ringable: bool,
38 pub initially_active: bool,
38}
39}
39
40
40/// Page globals of one Trouter client; a second client in the same tab needs its own names.
41/// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -67,6 +68,7 @@ impl Default for RealtimeConfig {
67 instance: InstanceNames::default(),
68 instance: InstanceNames::default(),
68 forward_callbacks: false,
69 forward_callbacks: false,
69 ringable: false,
70 ringable: false,
71 initially_active: false,
70 }
72 }
71 }
73 }
72}
74}
@@ -76,6 +78,7 @@ pub struct Realtime {
76 events: mpsc::UnboundedReceiver<RealtimeEvent>,
78 events: mpsc::UnboundedReceiver<RealtimeEvent>,
77 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
79 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
78 replier: CallbackReplier,
80 replier: CallbackReplier,
81 activity: watch::Sender<bool>,
79 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
82 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
80 task: JoinHandle<()>,
83 task: JoinHandle<()>,
81}
84}
@@ -94,6 +97,7 @@ impl Realtime {
94 let (output, events) = mpsc::unbounded_channel();
97 let (output, events) = mpsc::unbounded_channel();
95 let (callback_output, callbacks) = mpsc::unbounded_channel();
98 let (callback_output, callbacks) = mpsc::unbounded_channel();
96 let (reply_sender, replies) = mpsc::unbounded_channel();
99 let (reply_sender, replies) = mpsc::unbounded_channel();
100 let (activity, activity_receiver) = watch::channel(config.initially_active);
97 let (stop, stop_receiver) = oneshot::channel();
101 let (stop, stop_receiver) = oneshot::channel();
98 let mut runner = Runner::new(
102 let mut runner = Runner::new(
99 session,
103 session,
@@ -105,6 +109,7 @@ impl Realtime {
105 output: callback_output,
109 output: callback_output,
106 replies,
110 replies,
107 },
111 },
112 activity_receiver,
108 );
113 );
109 if let Err(error) = runner.ensure().await {
114 if let Err(error) = runner.ensure().await {
110 attached.shutdown().await;
115 attached.shutdown().await;
@@ -118,6 +123,7 @@ impl Realtime {
118 replier: CallbackReplier {
123 replier: CallbackReplier {
119 sender: reply_sender,
124 sender: reply_sender,
120 },
125 },
126 activity,
121 stop: Some(stop),
127 stop: Some(stop),
122 task,
128 task,
123 })
129 })
@@ -140,6 +146,10 @@ impl Realtime {
140 self.replier.clone()
146 self.replier.clone()
141 }
147 }
142
148
149 pub fn set_activity(&self, active: bool) {
150 self.activity.send_replace(active);
151 }
152
143 /// Deletes the registration and closes the page-side socket.
153 /// Deletes the registration and closes the page-side socket.
144 pub async fn stop(mut self) {
154 pub async fn stop(mut self) {
145 if let Some(stop) = self.stop.take() {
155 if let Some(stop) = self.stop.take() {
crates/chatsvc/src/realtime/runner.rs +43 −4
@@ -2,7 +2,7 @@ use std::time::Duration;
2 2
3 3 use serde_json::{Value, json};
4 4 use session::{App, Session, TabControl, TabEvents};
5 use tokio::sync::{mpsc, oneshot};
5 use tokio::sync::{mpsc, oneshot, watch};
6 6 use tokio::time::{MissedTickBehavior, interval, sleep};
7 7
8 8 use super::RealtimeConfig;
@@ -49,11 +49,19 @@ impl PageScript {
49 49
50 50 fn ensure_body(&self) -> String {
51 51 format!(
52 "{}\nreturn window.{}.ensure({{token, host: args.host}});",
52 "{}\nreturn window.{}.ensure({{token, host: args.host, activity: args.activity}});",
53 53 self.worker_source, self.global_name
54 54 )
55 55 }
56 56
57 fn set_activity_expression(&self, active: bool) -> String {
58 format!(
59 "window.{name} ? window.{name}.setActivity('{state}') : null",
60 name = self.global_name,
61 state = activity_label(active)
62 )
63 }
64
57 65 fn stop_expression(&self) -> String {
58 66 format!(
59 67 "window.{name} ? window.{name}.stop() : null",
@@ -114,6 +122,7 @@ pub(super) struct Runner {
114 122 callbacks: CallbackPipes,
115 123 host: String,
116 124 output: mpsc::UnboundedSender<RealtimeEvent>,
125 activity: watch::Receiver<bool>,
117 126 force_refresh: bool,
118 127 last_error: Option<String>,
119 128 }
@@ -126,6 +135,7 @@ impl Runner {
126 135 host: String,
127 136 output: mpsc::UnboundedSender<RealtimeEvent>,
128 137 callbacks: CallbackPipes,
138 activity: watch::Receiver<bool>,
129 139 ) -> Self {
130 140 Runner {
131 141 session,
@@ -134,13 +144,14 @@ impl Runner {
134 144 callbacks,
135 145 host,
136 146 output,
147 activity,
137 148 force_refresh: false,
138 149 last_error: None,
139 150 }
140 151 }
141 152
142 153 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
143 let args = json!({"host": self.host});
154 let args = json!({"host": self.host, "activity": activity_label(*self.activity.borrow())});
144 155 let outcome = self
145 156 .session
146 157 .run_with_token(
@@ -223,6 +234,12 @@ impl Runner {
223 234 }
224 235 }
225 236 _ = tick.tick() => self.ensure_and_report().await,
237 changed = self.activity.changed() => {
238 if changed.is_ok() {
239 let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
240 let _ = attached.control.evaluate(&expression).await;
241 }
242 }
226 243 Some(reply) = self.callbacks.replies.recv() => {
227 244 let expression = reply_expression(&self.script.global_name, &reply);
228 245 let _ = attached.control.evaluate(&expression).await;
@@ -279,6 +296,10 @@ impl Runner {
279 296 }
280 297 }
281 298
299 fn activity_label(active: bool) -> &'static str {
300 if active { "active" } else { "inactive" }
301 }
302
282 303 fn is_main_frame_navigation(method: &str, params: &Value) -> bool {
283 304 method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()
284 305 }
@@ -304,6 +325,24 @@ mod tests {
304 325 assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));
305 326 }
306 327
328 #[test]
329 fn activity_is_labelled_and_set_through_the_page_global() {
330 assert_eq!(activity_label(true), "active");
331 assert_eq!(activity_label(false), "inactive");
332 let script = PageScript::new(&RealtimeConfig::default());
333 assert_eq!(
334 script.set_activity_expression(false),
335 "window.__chatsvcTrouter ? window.__chatsvcTrouter.setActivity('inactive') : null"
336 );
337 }
338
339 #[test]
340 fn worker_reports_activity_on_change_only() {
341 let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
342 assert!(!worker.contains("activity();"));
343 assert_eq!(worker.matches("'user.activity'").count(), 1);
344 }
345
307 346 #[test]
308 347 fn rejected_bearer_forces_token_refresh() {
309 348 assert!(is_auth_failure("registrar_http_401"));
@@ -318,7 +357,7 @@ mod tests {
318 357 assert!(
319 358 ensure_body
320 359 .trim_end()
321 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host});")
360 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
322 361 );
323 362 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
324 363 }
@@ -2,7 +2,7 @@ use std::time::Duration;
2
2
3use serde_json::{Value, json};
3use serde_json::{Value, json};
4use session::{App, Session, TabControl, TabEvents};
4use session::{App, Session, TabControl, TabEvents};
5use tokio::sync::{mpsc, oneshot};
5use tokio::sync::{mpsc, oneshot, watch};
6use tokio::time::{MissedTickBehavior, interval, sleep};
6use tokio::time::{MissedTickBehavior, interval, sleep};
7
7
8use super::RealtimeConfig;
8use super::RealtimeConfig;
@@ -49,11 +49,19 @@ impl PageScript {
49
49
50 fn ensure_body(&self) -> String {
50 fn ensure_body(&self) -> String {
51 format!(
51 format!(
52 "{}\nreturn window.{}.ensure({{token, host: args.host}});",
52 "{}\nreturn window.{}.ensure({{token, host: args.host, activity: args.activity}});",
53 self.worker_source, self.global_name
53 self.worker_source, self.global_name
54 )
54 )
55 }
55 }
56
56
57 fn set_activity_expression(&self, active: bool) -> String {
58 format!(
59 "window.{name} ? window.{name}.setActivity('{state}') : null",
60 name = self.global_name,
61 state = activity_label(active)
62 )
63 }
64
57 fn stop_expression(&self) -> String {
65 fn stop_expression(&self) -> String {
58 format!(
66 format!(
59 "window.{name} ? window.{name}.stop() : null",
67 "window.{name} ? window.{name}.stop() : null",
@@ -114,6 +122,7 @@ pub(super) struct Runner {
114 callbacks: CallbackPipes,
122 callbacks: CallbackPipes,
115 host: String,
123 host: String,
116 output: mpsc::UnboundedSender<RealtimeEvent>,
124 output: mpsc::UnboundedSender<RealtimeEvent>,
125 activity: watch::Receiver<bool>,
117 force_refresh: bool,
126 force_refresh: bool,
118 last_error: Option<String>,
127 last_error: Option<String>,
119}
128}
@@ -126,6 +135,7 @@ impl Runner {
126 host: String,
135 host: String,
127 output: mpsc::UnboundedSender<RealtimeEvent>,
136 output: mpsc::UnboundedSender<RealtimeEvent>,
128 callbacks: CallbackPipes,
137 callbacks: CallbackPipes,
138 activity: watch::Receiver<bool>,
129 ) -> Self {
139 ) -> Self {
130 Runner {
140 Runner {
131 session,
141 session,
@@ -134,13 +144,14 @@ impl Runner {
134 callbacks,
144 callbacks,
135 host,
145 host,
136 output,
146 output,
147 activity,
137 force_refresh: false,
148 force_refresh: false,
138 last_error: None,
149 last_error: None,
139 }
150 }
140 }
151 }
141
152
142 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
153 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
143 let args = json!({"host": self.host});
154 let args = json!({"host": self.host, "activity": activity_label(*self.activity.borrow())});
144 let outcome = self
155 let outcome = self
145 .session
156 .session
146 .run_with_token(
157 .run_with_token(
@@ -223,6 +234,12 @@ impl Runner {
223 }
234 }
224 }
235 }
225 _ = tick.tick() => self.ensure_and_report().await,
236 _ = tick.tick() => self.ensure_and_report().await,
237 changed = self.activity.changed() => {
238 if changed.is_ok() {
239 let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
240 let _ = attached.control.evaluate(&expression).await;
241 }
242 }
226 Some(reply) = self.callbacks.replies.recv() => {
243 Some(reply) = self.callbacks.replies.recv() => {
227 let expression = reply_expression(&self.script.global_name, &reply);
244 let expression = reply_expression(&self.script.global_name, &reply);
228 let _ = attached.control.evaluate(&expression).await;
245 let _ = attached.control.evaluate(&expression).await;
@@ -279,6 +296,10 @@ impl Runner {
279 }
296 }
280}
297}
281
298
299fn activity_label(active: bool) -> &'static str {
300 if active { "active" } else { "inactive" }
301}
302
282fn is_main_frame_navigation(method: &str, params: &Value) -> bool {
303fn is_main_frame_navigation(method: &str, params: &Value) -> bool {
283 method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()
304 method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()
284}
305}
@@ -304,6 +325,24 @@ mod tests {
304 assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));
325 assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));
305 }
326 }
306
327
328 #[test]
329 fn activity_is_labelled_and_set_through_the_page_global() {
330 assert_eq!(activity_label(true), "active");
331 assert_eq!(activity_label(false), "inactive");
332 let script = PageScript::new(&RealtimeConfig::default());
333 assert_eq!(
334 script.set_activity_expression(false),
335 "window.__chatsvcTrouter ? window.__chatsvcTrouter.setActivity('inactive') : null"
336 );
337 }
338
339 #[test]
340 fn worker_reports_activity_on_change_only() {
341 let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
342 assert!(!worker.contains("activity();"));
343 assert_eq!(worker.matches("'user.activity'").count(), 1);
344 }
345
307 #[test]
346 #[test]
308 fn rejected_bearer_forces_token_refresh() {
347 fn rejected_bearer_forces_token_refresh() {
309 assert!(is_auth_failure("registrar_http_401"));
348 assert!(is_auth_failure("registrar_http_401"));
@@ -318,7 +357,7 @@ mod tests {
318 assert!(
357 assert!(
319 ensure_body
358 ensure_body
320 .trim_end()
359 .trim_end()
321 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host});")
360 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
322 );
361 );
323 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
362 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
324 }
363 }
crates/chatsvc/tests/realtime.rs +1 −1
@@ -172,7 +172,7 @@ async fn start_injects_worker_and_ensures_with_default_host() {
172 172 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
173 173 assert_eq!(
174 174 arguments,
175 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com"})
175 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com", "activity": "inactive"})
176 176 );
177 177 realtime.stop().await;
178 178 }
@@ -172,7 +172,7 @@ async fn start_injects_worker_and_ensures_with_default_host() {
172 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
172 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
173 assert_eq!(
173 assert_eq!(
174 arguments,
174 arguments,
175 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com"})
175 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com", "activity": "inactive"})
176 );
176 );
177 realtime.stop().await;
177 realtime.stop().await;
178}
178}