BlueGit

ict rusty-teams

fix(presence): review findings

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
a755adcc0efa368bdfec293a2380ff5886aebc59
Parent
7b6dcd74
10 files changed +457 −153
crates/app/src/backend.rs +21 −11
@@ -8,7 +8,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, watch};
11 use tokio::sync::{Notify, mpsc, watch};
12 12
13 13 use crate::call::{CallLauncher, fetch_window};
14 14 use crate::presence_link::{self, LinkSignal};
@@ -100,10 +100,11 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
100 100 }
101 101 }
102 102
103 fn link_signal_for(kind: StatusKind) -> LinkSignal {
103 fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {
104 104 match kind {
105 StatusKind::Connected | StatusKind::MessageLoss => LinkSignal::Connected,
106 StatusKind::Disconnected | StatusKind::Error => LinkSignal::Disconnected,
105 StatusKind::Connected => Some(LinkSignal::Connected),
106 StatusKind::Disconnected => Some(LinkSignal::Disconnected),
107 StatusKind::MessageLoss | StatusKind::Error => None,
107 108 }
108 109 }
109 110
@@ -155,13 +156,15 @@ async fn supervise(
155 156 let _ = events.send(BackendEvent::Calls(launcher));
156 157 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
157 158 let (nudge, nudges) = mpsc::unbounded_channel();
158 let link = presence_link::start(&session, activity.clone());
159 let resend = Arc::new(Notify::new());
160 let link = presence_link::start(&session, activity.clone(), resend.clone());
159 161 tokio::spawn(realtime_loop(
160 162 session.clone(),
161 163 engine.clone(),
162 164 events.clone(),
163 165 nudge,
164 166 activity,
167 resend,
165 168 link,
166 169 ));
167 170 tokio::spawn(calendar_loop(session.clone(), events.clone()));
@@ -225,6 +228,7 @@ async fn realtime_loop(
225 228 events: EventSender,
226 229 nudge: mpsc::UnboundedSender<()>,
227 230 mut activity: watch::Receiver<bool>,
231 resend: Arc<Notify>,
228 232 link: mpsc::UnboundedSender<LinkSignal>,
229 233 ) {
230 234 loop {
@@ -242,6 +246,10 @@ async fn realtime_loop(
242 246 realtime.set_activity(*activity.borrow_and_update());
243 247 continue;
244 248 }
249 _ = resend.notified() => {
250 realtime.resend_activity();
251 continue;
252 }
245 253 };
246 254 let Some(event) = event else { break };
247 255 match event {
@@ -267,7 +275,9 @@ async fn realtime_loop(
267 275 }
268 276 RealtimeEvent::Status(status) => {
269 277 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
270 let _ = link.send(link_signal_for(status.kind));
278 if let Some(signal) = link_signal_for(status.kind) {
279 let _ = link.send(signal);
280 }
271 281 let receipt_engine = engine.clone();
272 282 let receipt_status = status.clone();
273 283 tokio::spawn(async move {
@@ -506,10 +516,10 @@ mod tests {
506 516 }
507 517
508 518 #[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);
519 fn only_connect_and_disconnect_move_the_link() {
520 assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected));
521 assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected));
522 assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
523 assert_eq!(link_signal_for(StatusKind::Error), None);
514 524 }
515 525 }
@@ -8,7 +8,7 @@ use 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, watch};
11use tokio::sync::{Notify, mpsc, watch};
12
12
13use crate::call::{CallLauncher, fetch_window};
13use crate::call::{CallLauncher, fetch_window};
14use crate::presence_link::{self, LinkSignal};
14use crate::presence_link::{self, LinkSignal};
@@ -100,10 +100,11 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
100 }
100 }
101}
101}
102
102
103fn link_signal_for(kind: StatusKind) -> LinkSignal {
103fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {
104 match kind {
104 match kind {
105 StatusKind::Connected | StatusKind::MessageLoss => LinkSignal::Connected,
105 StatusKind::Connected => Some(LinkSignal::Connected),
106 StatusKind::Disconnected | StatusKind::Error => LinkSignal::Disconnected,
106 StatusKind::Disconnected => Some(LinkSignal::Disconnected),
107 StatusKind::MessageLoss | StatusKind::Error => None,
107 }
108 }
108}
109}
109
110
@@ -155,13 +156,15 @@ async fn supervise(
155 let _ = events.send(BackendEvent::Calls(launcher));
156 let _ = events.send(BackendEvent::Calls(launcher));
156 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
157 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
157 let (nudge, nudges) = mpsc::unbounded_channel();
158 let (nudge, nudges) = mpsc::unbounded_channel();
158 let link = presence_link::start(&session, activity.clone());
159 let resend = Arc::new(Notify::new());
160 let link = presence_link::start(&session, activity.clone(), resend.clone());
159 tokio::spawn(realtime_loop(
161 tokio::spawn(realtime_loop(
160 session.clone(),
162 session.clone(),
161 engine.clone(),
163 engine.clone(),
162 events.clone(),
164 events.clone(),
163 nudge,
165 nudge,
164 activity,
166 activity,
167 resend,
165 link,
168 link,
166 ));
169 ));
167 tokio::spawn(calendar_loop(session.clone(), events.clone()));
170 tokio::spawn(calendar_loop(session.clone(), events.clone()));
@@ -225,6 +228,7 @@ async fn realtime_loop(
225 events: EventSender,
228 events: EventSender,
226 nudge: mpsc::UnboundedSender<()>,
229 nudge: mpsc::UnboundedSender<()>,
227 mut activity: watch::Receiver<bool>,
230 mut activity: watch::Receiver<bool>,
231 resend: Arc<Notify>,
228 link: mpsc::UnboundedSender<LinkSignal>,
232 link: mpsc::UnboundedSender<LinkSignal>,
229) {
233) {
230 loop {
234 loop {
@@ -242,6 +246,10 @@ async fn realtime_loop(
242 realtime.set_activity(*activity.borrow_and_update());
246 realtime.set_activity(*activity.borrow_and_update());
243 continue;
247 continue;
244 }
248 }
249 _ = resend.notified() => {
250 realtime.resend_activity();
251 continue;
252 }
245 };
253 };
246 let Some(event) = event else { break };
254 let Some(event) = event else { break };
247 match event {
255 match event {
@@ -267,7 +275,9 @@ async fn realtime_loop(
267 }
275 }
268 RealtimeEvent::Status(status) => {
276 RealtimeEvent::Status(status) => {
269 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
277 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
270 let _ = link.send(link_signal_for(status.kind));
278 if let Some(signal) = link_signal_for(status.kind) {
279 let _ = link.send(signal);
280 }
271 let receipt_engine = engine.clone();
281 let receipt_engine = engine.clone();
272 let receipt_status = status.clone();
282 let receipt_status = status.clone();
273 tokio::spawn(async move {
283 tokio::spawn(async move {
@@ -506,10 +516,10 @@ mod tests {
506 }
516 }
507
517
508 #[test]
518 #[test]
509 fn only_a_closed_or_failed_trouter_counts_as_down() {
519 fn only_connect_and_disconnect_move_the_link() {
510 assert_eq!(link_signal_for(StatusKind::Connected), LinkSignal::Connected);
520 assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected));
511 assert_eq!(link_signal_for(StatusKind::MessageLoss), LinkSignal::Connected);
521 assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected));
512 assert_eq!(link_signal_for(StatusKind::Disconnected), LinkSignal::Disconnected);
522 assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
513 assert_eq!(link_signal_for(StatusKind::Error), LinkSignal::Disconnected);
523 assert_eq!(link_signal_for(StatusKind::Error), None);
514 }
524 }
515}
525}
crates/app/src/user_activity.rs +67 −25
@@ -2,6 +2,7 @@ use std::sync::Arc;
2 2 use std::sync::atomic::{AtomicU64, Ordering};
3 3 use std::time::{Duration, Instant};
4 4
5 use gpui_kit::{DispatchPhase, IntoElement, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};
5 6 use tokio::sync::watch;
6 7
7 8 pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
@@ -12,11 +13,13 @@ pub struct UserInput {
12 13 last_input_millis: AtomicU64,
13 14 }
14 15
16 const NO_INPUT: u64 = u64::MAX;
17
15 18 impl UserInput {
16 19 pub fn new() -> Arc<Self> {
17 20 Arc::new(UserInput {
18 21 origin: Instant::now(),
19 last_input_millis: AtomicU64::new(0),
22 last_input_millis: AtomicU64::new(NO_INPUT),
20 23 })
21 24 }
22 25
@@ -25,29 +28,56 @@ impl UserInput {
25 28 self.last_input_millis.store(elapsed, Ordering::Relaxed);
26 29 }
27 30
28 fn last_input(&self) -> Instant {
29 self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))
31 fn last_input(&self) -> Option<Instant> {
32 match self.last_input_millis.load(Ordering::Relaxed) {
33 NO_INPUT => None,
34 millis => Some(self.origin + Duration::from_millis(millis)),
35 }
30 36 }
31 37 }
32 38
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 }
39 pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {
40 canvas(
41 |_, _, _| {},
42 move |_, _, window, _| {
43 let moved = input.clone();
44 window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {
45 if phase == DispatchPhase::Capture {
46 moved.touch();
47 }
48 });
49 let pressed = input.clone();
50 window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {
51 if phase == DispatchPhase::Capture {
52 pressed.touch();
53 }
54 });
55 let scrolled = input.clone();
56 window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {
57 if phase == DispatchPhase::Capture {
58 scrolled.touch();
59 }
60 });
61 },
62 )
63 }
64
65 pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {
66 let system_input = system_idle.and_then(|idle| now.checked_sub(idle));
67 app_input.max(system_input)
38 68 }
39 69
40 pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {
41 now.saturating_duration_since(last_input) < idle_after
70 pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {
71 last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)
42 72 }
43 73
44 pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {
74 pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {
45 75 let current = is_active(last_input, now, idle_after);
46 76 (current != previous).then_some(current)
47 77 }
48 78
49 79 pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
50 let (sender, receiver) = watch::channel(true);
80 let (sender, receiver) = watch::channel(false);
51 81 crate::runtime::handle().spawn(async move {
52 82 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
53 83 loop {
@@ -94,35 +124,47 @@ mod tests {
94 124 #[test]
95 125 fn active_until_the_idle_threshold() {
96 126 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));
127 assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));
128 assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));
129 assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));
130 }
131
132 #[test]
133 fn without_any_input_the_user_is_inactive() {
134 assert!(!is_active(None, Instant::now(), IDLE_AFTER));
135 assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);
100 136 }
101 137
102 138 #[test]
103 139 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));
140 let last_input = Some(Instant::now());
141 let at = |offset: u64| last_input.unwrap() + seconds(offset);
142 assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);
143 assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));
144 assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);
145 assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));
146 assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));
109 147 }
110 148
111 149 #[test]
112 150 fn system_input_counts_when_newer_than_app_input() {
113 151 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));
152 let app_input = Some(now - seconds(900));
153 assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));
116 154 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
117 155 assert_eq!(latest_input(app_input, None, now), app_input);
156 assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));
157 assert_eq!(latest_input(None, None, now), None);
118 158 }
119 159
120 160 #[test]
121 fn touch_moves_the_last_input_forward() {
161 fn touch_sets_and_moves_the_last_input_forward() {
122 162 let input = UserInput::new();
123 let before = input.last_input();
163 assert_eq!(input.last_input(), None);
164 input.touch();
165 let first = input.last_input().unwrap();
124 166 std::thread::sleep(Duration::from_millis(5));
125 167 input.touch();
126 assert!(input.last_input() > before);
168 assert!(input.last_input().unwrap() > first);
127 169 }
128 170 }
@@ -2,6 +2,7 @@ use std::sync::Arc;
2use std::sync::atomic::{AtomicU64, Ordering};
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::time::{Duration, Instant};
3use std::time::{Duration, Instant};
4
4
5use gpui_kit::{DispatchPhase, IntoElement, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};
5use tokio::sync::watch;
6use tokio::sync::watch;
6
7
7pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
8pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
@@ -12,11 +13,13 @@ pub struct UserInput {
12 last_input_millis: AtomicU64,
13 last_input_millis: AtomicU64,
13}
14}
14
15
16const NO_INPUT: u64 = u64::MAX;
17
15impl UserInput {
18impl UserInput {
16 pub fn new() -> Arc<Self> {
19 pub fn new() -> Arc<Self> {
17 Arc::new(UserInput {
20 Arc::new(UserInput {
18 origin: Instant::now(),
21 origin: Instant::now(),
19 last_input_millis: AtomicU64::new(0),
22 last_input_millis: AtomicU64::new(NO_INPUT),
20 })
23 })
21 }
24 }
22
25
@@ -25,29 +28,56 @@ impl UserInput {
25 self.last_input_millis.store(elapsed, Ordering::Relaxed);
28 self.last_input_millis.store(elapsed, Ordering::Relaxed);
26 }
29 }
27
30
28 fn last_input(&self) -> Instant {
31 fn last_input(&self) -> Option<Instant> {
29 self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))
32 match self.last_input_millis.load(Ordering::Relaxed) {
33 NO_INPUT => None,
34 millis => Some(self.origin + Duration::from_millis(millis)),
35 }
30 }
36 }
31}
37}
32
38
33pub fn latest_input(app_input: Instant, system_idle: Option<Duration>, now: Instant) -> Instant {
39pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {
34 match system_idle.and_then(|idle| now.checked_sub(idle)) {
40 canvas(
35 Some(system_input) => app_input.max(system_input),
41 |_, _, _| {},
36 None => app_input,
42 move |_, _, window, _| {
37 }
43 let moved = input.clone();
44 window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {
45 if phase == DispatchPhase::Capture {
46 moved.touch();
47 }
48 });
49 let pressed = input.clone();
50 window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {
51 if phase == DispatchPhase::Capture {
52 pressed.touch();
53 }
54 });
55 let scrolled = input.clone();
56 window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {
57 if phase == DispatchPhase::Capture {
58 scrolled.touch();
59 }
60 });
61 },
62 )
63}
64
65pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {
66 let system_input = system_idle.and_then(|idle| now.checked_sub(idle));
67 app_input.max(system_input)
38}
68}
39
69
40pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {
70pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {
41 now.saturating_duration_since(last_input) < idle_after
71 last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)
42}
72}
43
73
44pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {
74pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {
45 let current = is_active(last_input, now, idle_after);
75 let current = is_active(last_input, now, idle_after);
46 (current != previous).then_some(current)
76 (current != previous).then_some(current)
47}
77}
48
78
49pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
79pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
50 let (sender, receiver) = watch::channel(true);
80 let (sender, receiver) = watch::channel(false);
51 crate::runtime::handle().spawn(async move {
81 crate::runtime::handle().spawn(async move {
52 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
82 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
53 loop {
83 loop {
@@ -94,35 +124,47 @@ mod tests {
94 #[test]
124 #[test]
95 fn active_until_the_idle_threshold() {
125 fn active_until_the_idle_threshold() {
96 let last_input = Instant::now();
126 let last_input = Instant::now();
97 assert!(is_active(last_input, last_input + seconds(299), IDLE_AFTER));
127 assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));
98 assert!(!is_active(last_input, last_input + seconds(300), IDLE_AFTER));
128 assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));
99 assert!(is_active(last_input + seconds(10), last_input, IDLE_AFTER));
129 assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));
130 }
131
132 #[test]
133 fn without_any_input_the_user_is_inactive() {
134 assert!(!is_active(None, Instant::now(), IDLE_AFTER));
135 assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);
100 }
136 }
101
137
102 #[test]
138 #[test]
103 fn only_a_change_of_state_is_reported() {
139 fn only_a_change_of_state_is_reported() {
104 let last_input = Instant::now();
140 let last_input = Some(Instant::now());
105 assert_eq!(activity_change(true, last_input, last_input + seconds(10), IDLE_AFTER), None);
141 let at = |offset: u64| last_input.unwrap() + seconds(offset);
106 assert_eq!(activity_change(true, last_input, last_input + seconds(301), IDLE_AFTER), Some(false));
142 assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);
107 assert_eq!(activity_change(false, last_input, last_input + seconds(301), IDLE_AFTER), None);
143 assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));
108 assert_eq!(activity_change(false, last_input + seconds(400), last_input + seconds(401), IDLE_AFTER), Some(true));
144 assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);
145 assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));
146 assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));
109 }
147 }
110
148
111 #[test]
149 #[test]
112 fn system_input_counts_when_newer_than_app_input() {
150 fn system_input_counts_when_newer_than_app_input() {
113 let now = Instant::now() + seconds(1000);
151 let now = Instant::now() + seconds(1000);
114 let app_input = now - seconds(900);
152 let app_input = Some(now - seconds(900));
115 assert_eq!(latest_input(app_input, Some(seconds(20)), now), now - seconds(20));
153 assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));
116 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
154 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
117 assert_eq!(latest_input(app_input, None, now), app_input);
155 assert_eq!(latest_input(app_input, None, now), app_input);
156 assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));
157 assert_eq!(latest_input(None, None, now), None);
118 }
158 }
119
159
120 #[test]
160 #[test]
121 fn touch_moves_the_last_input_forward() {
161 fn touch_sets_and_moves_the_last_input_forward() {
122 let input = UserInput::new();
162 let input = UserInput::new();
123 let before = input.last_input();
163 assert_eq!(input.last_input(), None);
164 input.touch();
165 let first = input.last_input().unwrap();
124 std::thread::sleep(Duration::from_millis(5));
166 std::thread::sleep(Duration::from_millis(5));
125 input.touch();
167 input.touch();
126 assert!(input.last_input() > before);
168 assert!(input.last_input().unwrap() > first);
127 }
169 }
128}
170}
crates/app/src/views/shell.rs +2 −4
@@ -31,7 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
31 31 use crate::call::{CallMedia, CallWindows};
32 32 use crate::embedded_web::{Overlays, RootFocus};
33 33 use crate::notice::NoticeAction;
34 use crate::user_activity::UserInput;
34 use crate::user_activity::{self, UserInput};
35 35 use crate::notify::{NotificationCenter, selection_for};
36 36 use crate::sidebar_model::Step;
37 37 use crate::theme;
@@ -626,9 +626,6 @@ impl Render for AppShell {
626 626 .id("app-shell")
627 627 .key_context("AppShell")
628 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()))
632 629 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
633 630 this.toggle_switcher("", window, cx);
634 631 }))
@@ -699,6 +696,7 @@ impl Render for AppShell {
699 696 .text_color(theme::text())
700 697 .text_size(px(14.))
701 698 .child(crate::frame_log::probe("first"))
699 .child(user_activity::input_probe(self.user_input.clone()))
702 700 .child(
703 701 v_flex()
704 702 .size_full()
@@ -31,7 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
31use crate::call::{CallMedia, CallWindows};
31use crate::call::{CallMedia, CallWindows};
32use crate::embedded_web::{Overlays, RootFocus};
32use crate::embedded_web::{Overlays, RootFocus};
33use crate::notice::NoticeAction;
33use crate::notice::NoticeAction;
34use crate::user_activity::UserInput;
34use crate::user_activity::{self, UserInput};
35use crate::notify::{NotificationCenter, selection_for};
35use crate::notify::{NotificationCenter, selection_for};
36use crate::sidebar_model::Step;
36use crate::sidebar_model::Step;
37use crate::theme;
37use crate::theme;
@@ -626,9 +626,6 @@ impl Render for AppShell {
626 .id("app-shell")
626 .id("app-shell")
627 .key_context("AppShell")
627 .key_context("AppShell")
628 .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()))
632 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
629 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
633 this.toggle_switcher("", window, cx);
630 this.toggle_switcher("", window, cx);
634 }))
631 }))
@@ -699,6 +696,7 @@ impl Render for AppShell {
699 .text_color(theme::text())
696 .text_color(theme::text())
700 .text_size(px(14.))
697 .text_size(px(14.))
701 .child(crate::frame_log::probe("first"))
698 .child(crate::frame_log::probe("first"))
699 .child(user_activity::input_probe(self.user_input.clone()))
702 .child(
700 .child(
703 v_flex()
701 v_flex()
704 .size_full()
702 .size_full()
crates/chatsvc/assets/trouter.js +1 −0
@@ -306,6 +306,7 @@
306 306 },
307 307 shutdown,
308 308 setActivity,
309 resendActivity: () => transmitActivity(false),
309 310 reply: (id, status, body) => answer(id, status, body),
310 311 stop: async () => {
311 312 let unregistered = null;
@@ -306,6 +306,7 @@
306 },
306 },
307 shutdown,
307 shutdown,
308 setActivity,
308 setActivity,
309 resendActivity: () => transmitActivity(false),
309 reply: (id, status, body) => answer(id, status, body),
310 reply: (id, status, body) => answer(id, status, body),
310 stop: async () => {
311 stop: async () => {
311 let unregistered = null;
312 let unregistered = null;
crates/chatsvc/examples/presence_endpoint_probe.rs +3 −3
@@ -1,6 +1,6 @@
1 1 use std::time::Duration;
2 2
3 use chatsvc::{PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3 use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
4 4 use session::{DEFAULT_ENDPOINT, Session};
5 5
6 6 const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -25,8 +25,8 @@ async fn main() {
25 25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 26 println!("# trouter connected");
27 27
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id).await));
29 realtime.set_activity(true);
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
29 realtime.resend_activity();
30 30 println!("# sent active");
31 31 tokio::time::sleep(SETTLE).await;
32 32 print_own_presence(&presence, &user_id).await;
@@ -1,6 +1,6 @@
1use std::time::Duration;
1use std::time::Duration;
2
2
3use chatsvc::{PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
4use session::{DEFAULT_ENDPOINT, Session};
4use session::{DEFAULT_ENDPOINT, Session};
5
5
6const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
6const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -25,8 +25,8 @@ async fn main() {
25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 println!("# trouter connected");
26 println!("# trouter connected");
27
27
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id).await));
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
29 realtime.set_activity(true);
29 realtime.resend_activity();
30 println!("# sent active");
30 println!("# sent active");
31 tokio::time::sleep(SETTLE).await;
31 tokio::time::sleep(SETTLE).await;
32 print_own_presence(&presence, &user_id).await;
32 print_own_presence(&presence, &user_id).await;
crates/chatsvc/src/lib.rs +2 −2
@@ -43,8 +43,8 @@ pub use pins::{
43 43 PinnedMessage, Pins, TeamLayout,
44 44 };
45 45 pub use presence::{
46 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47 WorkLocationKind, WorkLocationSource, is_endpoint_missing,
46 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47 WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
48 48 };
49 49 pub use reactions::{emotion_key, emotion_keys};
50 50 pub use realtime::{
@@ -43,8 +43,8 @@ pub use pins::{
43 PinnedMessage, Pins, TeamLayout,
43 PinnedMessage, Pins, TeamLayout,
44};
44};
45pub use presence::{
45pub use presence::{
46 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
46 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47 WorkLocationKind, WorkLocationSource, is_endpoint_missing,
47 WorkLocationKind, WorkLocationSource, error_status, 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 +36 −6
@@ -53,6 +53,21 @@ impl ForcedKind {
53 53 }
54 54 }
55 55
56 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
57 pub enum ActivityReporting {
58 Transport,
59 Direct,
60 }
61
62 impl ActivityReporting {
63 fn code(self) -> &'static str {
64 match self {
65 ActivityReporting::Transport => "Transport",
66 ActivityReporting::Direct => "Direct",
67 }
68 }
69 }
70
56 71 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
57 72 pub struct ForcedAvailability {
58 73 pub kind: ForcedKind,
@@ -132,9 +147,9 @@ impl<T: CardTransport> PresenceService<T> {
132 147 self.send(request, &url).await.map(drop)
133 148 }
134 149
135 pub async fn register_endpoint(&self, endpoint_id: &str) -> Result<()> {
150 pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
136 151 let url = format!("{BASE_URL}/me/endpoints/");
137 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id));
152 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
138 153 request.headers = endpoint_headers(endpoint_id);
139 154 self.send(request, &url).await.map(drop)
140 155 }
@@ -211,16 +226,23 @@ impl<T: CardTransport> PresenceService<T> {
211 226 }
212 227 }
213 228
229 pub fn error_status(error: &Error) -> Option<u16> {
230 match error {
231 Error::Session(session::Error::Api { status, .. }) => Some(*status),
232 _ => None,
233 }
234 }
235
214 236 pub fn is_endpoint_missing(error: &Error) -> bool {
215 matches!(error, Error::Session(session::Error::Api { status: 404, .. }))
237 error_status(error) == Some(404)
216 238 }
217 239
218 fn endpoint_body(endpoint_id: &str) -> Value {
240 fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value {
219 241 json!({
220 242 "id": endpoint_id,
221 243 "availability": "Available",
222 244 "activity": "Available",
223 "activityReporting": "Transport",
245 "activityReporting": reporting.code(),
224 246 "deviceType": "Desktop",
225 247 })
226 248 }
@@ -480,7 +502,7 @@ mod tests {
480 502 #[tokio::test]
481 503 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
482 504 let service = service(200, Value::Null);
483 service.register_endpoint("epid-1").await.unwrap();
505 service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
484 506 let (request, scope) = only_request(&service);
485 507 assert_eq!(request.method, Method::Put);
486 508 assert_eq!(
@@ -508,6 +530,14 @@ mod tests {
508 530 );
509 531 }
510 532
533 #[tokio::test]
534 async fn register_endpoint_can_switch_to_direct_reporting() {
535 let service = service(200, Value::Null);
536 service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
537 let (request, _) = only_request(&service);
538 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539 }
540
511 541 #[tokio::test]
512 542 async fn unregister_endpoint_deletes_by_id_without_body() {
513 543 let service = service(200, Value::Null);
@@ -53,6 +53,21 @@ impl ForcedKind {
53 }
53 }
54}
54}
55
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum ActivityReporting {
58 Transport,
59 Direct,
60}
61
62impl ActivityReporting {
63 fn code(self) -> &'static str {
64 match self {
65 ActivityReporting::Transport => "Transport",
66 ActivityReporting::Direct => "Direct",
67 }
68 }
69}
70
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct ForcedAvailability {
72pub struct ForcedAvailability {
58 pub kind: ForcedKind,
73 pub kind: ForcedKind,
@@ -132,9 +147,9 @@ impl<T: CardTransport> PresenceService<T> {
132 self.send(request, &url).await.map(drop)
147 self.send(request, &url).await.map(drop)
133 }
148 }
134
149
135 pub async fn register_endpoint(&self, endpoint_id: &str) -> Result<()> {
150 pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
136 let url = format!("{BASE_URL}/me/endpoints/");
151 let url = format!("{BASE_URL}/me/endpoints/");
137 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id));
152 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
138 request.headers = endpoint_headers(endpoint_id);
153 request.headers = endpoint_headers(endpoint_id);
139 self.send(request, &url).await.map(drop)
154 self.send(request, &url).await.map(drop)
140 }
155 }
@@ -211,16 +226,23 @@ impl<T: CardTransport> PresenceService<T> {
211 }
226 }
212}
227}
213
228
229pub fn error_status(error: &Error) -> Option<u16> {
230 match error {
231 Error::Session(session::Error::Api { status, .. }) => Some(*status),
232 _ => None,
233 }
234}
235
214pub fn is_endpoint_missing(error: &Error) -> bool {
236pub fn is_endpoint_missing(error: &Error) -> bool {
215 matches!(error, Error::Session(session::Error::Api { status: 404, .. }))
237 error_status(error) == Some(404)
216}
238}
217
239
218fn endpoint_body(endpoint_id: &str) -> Value {
240fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value {
219 json!({
241 json!({
220 "id": endpoint_id,
242 "id": endpoint_id,
221 "availability": "Available",
243 "availability": "Available",
222 "activity": "Available",
244 "activity": "Available",
223 "activityReporting": "Transport",
245 "activityReporting": reporting.code(),
224 "deviceType": "Desktop",
246 "deviceType": "Desktop",
225 })
247 })
226}
248}
@@ -480,7 +502,7 @@ mod tests {
480 #[tokio::test]
502 #[tokio::test]
481 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
503 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
482 let service = service(200, Value::Null);
504 let service = service(200, Value::Null);
483 service.register_endpoint("epid-1").await.unwrap();
505 service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
484 let (request, scope) = only_request(&service);
506 let (request, scope) = only_request(&service);
485 assert_eq!(request.method, Method::Put);
507 assert_eq!(request.method, Method::Put);
486 assert_eq!(
508 assert_eq!(
@@ -508,6 +530,14 @@ mod tests {
508 );
530 );
509 }
531 }
510
532
533 #[tokio::test]
534 async fn register_endpoint_can_switch_to_direct_reporting() {
535 let service = service(200, Value::Null);
536 service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
537 let (request, _) = only_request(&service);
538 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539 }
540
511 #[tokio::test]
541 #[tokio::test]
512 async fn unregister_endpoint_deletes_by_id_without_body() {
542 async fn unregister_endpoint_deletes_by_id_without_body() {
513 let service = service(200, Value::Null);
543 let service = service(200, Value::Null);
crates/chatsvc/src/realtime/mod.rs +10 −1
@@ -4,12 +4,13 @@ mod host;
4 4 mod runner;
5 5
6 6 use std::pin::Pin;
7 use std::sync::Arc;
7 8 use std::task::{Context, Poll};
8 9 use std::time::Duration;
9 10
10 11 use futures_util::Stream;
11 12 use session::Session;
12 use tokio::sync::{mpsc, oneshot, watch};
13 use tokio::sync::{Notify, mpsc, oneshot, watch};
13 14 use tokio::task::JoinHandle;
14 15
15 16 pub use event::{
@@ -79,6 +80,7 @@ pub struct Realtime {
79 80 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
80 81 replier: CallbackReplier,
81 82 activity: watch::Sender<bool>,
83 resend: Arc<Notify>,
82 84 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
83 85 task: JoinHandle<()>,
84 86 }
@@ -98,6 +100,7 @@ impl Realtime {
98 100 let (callback_output, callbacks) = mpsc::unbounded_channel();
99 101 let (reply_sender, replies) = mpsc::unbounded_channel();
100 102 let (activity, activity_receiver) = watch::channel(config.initially_active);
103 let resend = Arc::new(Notify::new());
101 104 let (stop, stop_receiver) = oneshot::channel();
102 105 let mut runner = Runner::new(
103 106 session,
@@ -110,6 +113,7 @@ impl Realtime {
110 113 replies,
111 114 },
112 115 activity_receiver,
116 resend.clone(),
113 117 );
114 118 if let Err(error) = runner.ensure().await {
115 119 attached.shutdown().await;
@@ -124,6 +128,7 @@ impl Realtime {
124 128 sender: reply_sender,
125 129 },
126 130 activity,
131 resend,
127 132 stop: Some(stop),
128 133 task,
129 134 })
@@ -150,6 +155,10 @@ impl Realtime {
150 155 self.activity.send_replace(active);
151 156 }
152 157
158 pub fn resend_activity(&self) {
159 self.resend.notify_one();
160 }
161
153 162 /// Deletes the registration and closes the page-side socket.
154 163 pub async fn stop(mut self) {
155 164 if let Some(stop) = self.stop.take() {
@@ -4,12 +4,13 @@ mod host;
4mod runner;
4mod runner;
5
5
6use std::pin::Pin;
6use std::pin::Pin;
7use std::sync::Arc;
7use std::task::{Context, Poll};
8use std::task::{Context, Poll};
8use std::time::Duration;
9use std::time::Duration;
9
10
10use futures_util::Stream;
11use futures_util::Stream;
11use session::Session;
12use session::Session;
12use tokio::sync::{mpsc, oneshot, watch};
13use tokio::sync::{Notify, mpsc, oneshot, watch};
13use tokio::task::JoinHandle;
14use tokio::task::JoinHandle;
14
15
15pub use event::{
16pub use event::{
@@ -79,6 +80,7 @@ pub struct Realtime {
79 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
80 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
80 replier: CallbackReplier,
81 replier: CallbackReplier,
81 activity: watch::Sender<bool>,
82 activity: watch::Sender<bool>,
83 resend: Arc<Notify>,
82 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
84 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
83 task: JoinHandle<()>,
85 task: JoinHandle<()>,
84}
86}
@@ -98,6 +100,7 @@ impl Realtime {
98 let (callback_output, callbacks) = mpsc::unbounded_channel();
100 let (callback_output, callbacks) = mpsc::unbounded_channel();
99 let (reply_sender, replies) = mpsc::unbounded_channel();
101 let (reply_sender, replies) = mpsc::unbounded_channel();
100 let (activity, activity_receiver) = watch::channel(config.initially_active);
102 let (activity, activity_receiver) = watch::channel(config.initially_active);
103 let resend = Arc::new(Notify::new());
101 let (stop, stop_receiver) = oneshot::channel();
104 let (stop, stop_receiver) = oneshot::channel();
102 let mut runner = Runner::new(
105 let mut runner = Runner::new(
103 session,
106 session,
@@ -110,6 +113,7 @@ impl Realtime {
110 replies,
113 replies,
111 },
114 },
112 activity_receiver,
115 activity_receiver,
116 resend.clone(),
113 );
117 );
114 if let Err(error) = runner.ensure().await {
118 if let Err(error) = runner.ensure().await {
115 attached.shutdown().await;
119 attached.shutdown().await;
@@ -124,6 +128,7 @@ impl Realtime {
124 sender: reply_sender,
128 sender: reply_sender,
125 },
129 },
126 activity,
130 activity,
131 resend,
127 stop: Some(stop),
132 stop: Some(stop),
128 task,
133 task,
129 })
134 })
@@ -150,6 +155,10 @@ impl Realtime {
150 self.activity.send_replace(active);
155 self.activity.send_replace(active);
151 }
156 }
152
157
158 pub fn resend_activity(&self) {
159 self.resend.notify_one();
160 }
161
153 /// Deletes the registration and closes the page-side socket.
162 /// Deletes the registration and closes the page-side socket.
154 pub async fn stop(mut self) {
163 pub async fn stop(mut self) {
155 if let Some(stop) = self.stop.take() {
164 if let Some(stop) = self.stop.take() {
crates/chatsvc/src/realtime/runner.rs +25 −1
@@ -1,8 +1,9 @@
1 use std::sync::Arc;
1 2 use std::time::Duration;
2 3
3 4 use serde_json::{Value, json};
4 5 use session::{App, Session, TabControl, TabEvents};
5 use tokio::sync::{mpsc, oneshot, watch};
6 use tokio::sync::{Notify, mpsc, oneshot, watch};
6 7 use tokio::time::{MissedTickBehavior, interval, sleep};
7 8
8 9 use super::RealtimeConfig;
@@ -62,6 +63,13 @@ impl PageScript {
62 63 )
63 64 }
64 65
66 fn resend_activity_expression(&self) -> String {
67 format!(
68 "window.{name} ? window.{name}.resendActivity() : null",
69 name = self.global_name
70 )
71 }
72
65 73 fn stop_expression(&self) -> String {
66 74 format!(
67 75 "window.{name} ? window.{name}.stop() : null",
@@ -123,6 +131,7 @@ pub(super) struct Runner {
123 131 host: String,
124 132 output: mpsc::UnboundedSender<RealtimeEvent>,
125 133 activity: watch::Receiver<bool>,
134 resend: Arc<Notify>,
126 135 force_refresh: bool,
127 136 last_error: Option<String>,
128 137 }
@@ -136,6 +145,7 @@ impl Runner {
136 145 output: mpsc::UnboundedSender<RealtimeEvent>,
137 146 callbacks: CallbackPipes,
138 147 activity: watch::Receiver<bool>,
148 resend: Arc<Notify>,
139 149 ) -> Self {
140 150 Runner {
141 151 session,
@@ -145,6 +155,7 @@ impl Runner {
145 155 host,
146 156 output,
147 157 activity,
158 resend,
148 159 force_refresh: false,
149 160 last_error: None,
150 161 }
@@ -234,6 +245,10 @@ impl Runner {
234 245 }
235 246 }
236 247 _ = tick.tick() => self.ensure_and_report().await,
248 _ = self.resend.notified() => {
249 let expression = self.script.resend_activity_expression();
250 let _ = attached.control.evaluate(&expression).await;
251 }
237 252 changed = self.activity.changed() => {
238 253 if changed.is_ok() {
239 254 let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
@@ -336,6 +351,15 @@ mod tests {
336 351 );
337 352 }
338 353
354 #[test]
355 fn resend_goes_through_the_page_global() {
356 let script = PageScript::new(&RealtimeConfig::default());
357 assert_eq!(
358 script.resend_activity_expression(),
359 "window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"
360 );
361 }
362
339 363 #[test]
340 364 fn worker_reports_activity_on_change_only() {
341 365 let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
@@ -1,8 +1,9 @@
1use std::sync::Arc;
1use std::time::Duration;
2use std::time::Duration;
2
3
3use serde_json::{Value, json};
4use serde_json::{Value, json};
4use session::{App, Session, TabControl, TabEvents};
5use session::{App, Session, TabControl, TabEvents};
5use tokio::sync::{mpsc, oneshot, watch};
6use tokio::sync::{Notify, mpsc, oneshot, watch};
6use tokio::time::{MissedTickBehavior, interval, sleep};
7use tokio::time::{MissedTickBehavior, interval, sleep};
7
8
8use super::RealtimeConfig;
9use super::RealtimeConfig;
@@ -62,6 +63,13 @@ impl PageScript {
62 )
63 )
63 }
64 }
64
65
66 fn resend_activity_expression(&self) -> String {
67 format!(
68 "window.{name} ? window.{name}.resendActivity() : null",
69 name = self.global_name
70 )
71 }
72
65 fn stop_expression(&self) -> String {
73 fn stop_expression(&self) -> String {
66 format!(
74 format!(
67 "window.{name} ? window.{name}.stop() : null",
75 "window.{name} ? window.{name}.stop() : null",
@@ -123,6 +131,7 @@ pub(super) struct Runner {
123 host: String,
131 host: String,
124 output: mpsc::UnboundedSender<RealtimeEvent>,
132 output: mpsc::UnboundedSender<RealtimeEvent>,
125 activity: watch::Receiver<bool>,
133 activity: watch::Receiver<bool>,
134 resend: Arc<Notify>,
126 force_refresh: bool,
135 force_refresh: bool,
127 last_error: Option<String>,
136 last_error: Option<String>,
128}
137}
@@ -136,6 +145,7 @@ impl Runner {
136 output: mpsc::UnboundedSender<RealtimeEvent>,
145 output: mpsc::UnboundedSender<RealtimeEvent>,
137 callbacks: CallbackPipes,
146 callbacks: CallbackPipes,
138 activity: watch::Receiver<bool>,
147 activity: watch::Receiver<bool>,
148 resend: Arc<Notify>,
139 ) -> Self {
149 ) -> Self {
140 Runner {
150 Runner {
141 session,
151 session,
@@ -145,6 +155,7 @@ impl Runner {
145 host,
155 host,
146 output,
156 output,
147 activity,
157 activity,
158 resend,
148 force_refresh: false,
159 force_refresh: false,
149 last_error: None,
160 last_error: None,
150 }
161 }
@@ -234,6 +245,10 @@ impl Runner {
234 }
245 }
235 }
246 }
236 _ = tick.tick() => self.ensure_and_report().await,
247 _ = tick.tick() => self.ensure_and_report().await,
248 _ = self.resend.notified() => {
249 let expression = self.script.resend_activity_expression();
250 let _ = attached.control.evaluate(&expression).await;
251 }
237 changed = self.activity.changed() => {
252 changed = self.activity.changed() => {
238 if changed.is_ok() {
253 if changed.is_ok() {
239 let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
254 let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
@@ -336,6 +351,15 @@ mod tests {
336 );
351 );
337 }
352 }
338
353
354 #[test]
355 fn resend_goes_through_the_page_global() {
356 let script = PageScript::new(&RealtimeConfig::default());
357 assert_eq!(
358 script.resend_activity_expression(),
359 "window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"
360 );
361 }
362
339 #[test]
363 #[test]
340 fn worker_reports_activity_on_change_only() {
364 fn worker_reports_activity_on_change_only() {
341 let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
365 let worker = PageScript::new(&RealtimeConfig::default()).worker_source;