BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / stack.rs

stack.rs

stack.rs 20.1 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use super::rules::{ChatKind, Incoming, Preview};
4
5pub const MAX_VISIBLE: usize = 3;
6pub const MESSAGE_DURATION: Duration = Duration::from_secs(6);
7pub const MENTION_DURATION: Duration = Duration::from_secs(10);
8pub const MAX_TOTAL: Duration = Duration::from_secs(20);
9pub const RESUME_REMAINING: Duration = Duration::from_secs(2);
10pub const SENT_DURATION: Duration = Duration::from_millis(1500);
11pub const FADE_IN: Duration = Duration::from_millis(150);
12pub const FAST_FADE: Duration = Duration::from_millis(150);
13pub const SLOW_FADE: Duration = Duration::from_secs(4);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Curve {
17 Linear,
18 EaseInCirc,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Fade {
23 from: f32,
24 to: f32,
25 start: Instant,
26 duration: Duration,
27 curve: Curve,
28}
29
30impl Fade {
31 pub fn new(from: f32, to: f32, start: Instant, duration: Duration, curve: Curve) -> Self {
32 Fade {
33 from,
34 to,
35 start,
36 duration,
37 curve,
38 }
39 }
40
41 #[cfg(test)]
42 pub fn shown(now: Instant) -> Self {
43 Fade::new(1., 1., now, Duration::ZERO, Curve::Linear)
44 }
45
46 pub fn value(&self, now: Instant) -> f32 {
47 if self.duration.is_zero() {
48 return self.to;
49 }
50 let progress = (now.saturating_duration_since(self.start).as_secs_f32()
51 / self.duration.as_secs_f32())
52 .clamp(0., 1.);
53 let eased = match self.curve {
54 Curve::Linear => progress,
55 Curve::EaseInCirc => 1. - (1. - progress * progress).sqrt(),
56 };
57 self.from + (self.to - self.from) * eased
58 }
59
60 pub fn is_leaving(&self) -> bool {
61 self.to == 0.
62 }
63
64 fn is_gone(&self, now: Instant) -> bool {
65 self.is_leaving() && now.saturating_duration_since(self.start) >= self.duration
66 }
67}
68
69#[derive(Debug, Clone, Copy)]
70pub struct ToastTimer {
71 first_shown: Instant,
72 started: Instant,
73 duration: Duration,
74 paused: Option<Instant>,
75 paused_total: Duration,
76}
77
78impl ToastTimer {
79 pub fn new(now: Instant, mention: bool) -> Self {
80 ToastTimer {
81 first_shown: now,
82 started: now,
83 duration: base_duration(mention),
84 paused: None,
85 paused_total: Duration::ZERO,
86 }
87 }
88
89 pub fn restart(&mut self, now: Instant, mention: bool) {
90 self.started = now;
91 self.duration = base_duration(mention);
92 if self.paused.is_some() {
93 self.paused = Some(now);
94 }
95 }
96
97 pub fn pause(&mut self, now: Instant) {
98 self.paused.get_or_insert(now);
99 }
100
101 pub fn resume(&mut self, now: Instant) {
102 if let Some(paused_at) = self.paused.take() {
103 self.paused_total += now.saturating_duration_since(paused_at);
104 self.started = now;
105 self.duration = RESUME_REMAINING;
106 }
107 }
108
109 fn elapsed(&self, now: Instant) -> Duration {
110 self.paused
111 .unwrap_or(now)
112 .saturating_duration_since(self.started)
113 }
114
115 pub fn expired(&self, now: Instant) -> bool {
116 if self.paused.is_some() {
117 return false;
118 }
119 self.elapsed(now) >= self.duration
120 || now
121 .saturating_duration_since(self.first_shown)
122 .saturating_sub(self.paused_total)
123 >= MAX_TOTAL
124 }
125}
126
127fn base_duration(mention: bool) -> Duration {
128 if mention {
129 MENTION_DURATION
130 } else {
131 MESSAGE_DURATION
132 }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub enum ReplyState {
137 Closed,
138 Open,
139 Sent,
140 Failed,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct AgentToast {
145 pub run_id: u64,
146 pub session_id: String,
147 pub header: String,
148 pub title: String,
149 pub body: String,
150 pub failed: bool,
151}
152
153#[derive(Debug, Clone)]
154pub struct ToastModel {
155 pub id: u64,
156 pub conversation_id: String,
157 pub message_id: String,
158 pub kind: ChatKind,
159 pub chat_title: String,
160 pub sender_id: Option<String>,
161 pub sender_name: String,
162 pub preview: Preview,
163 pub mentions_me: bool,
164 pub count: u32,
165 pub timer: ToastTimer,
166 pub reply: ReplyState,
167 pub reply_text: String,
168 pub hovered: bool,
169 pub time: String,
170 pub queued: bool,
171 pub dismissed: bool,
172 pub fade: Fade,
173 pub agent: Option<AgentToast>,
174}
175
176impl ToastModel {
177 pub fn holds_open(&self) -> bool {
178 self.reply != ReplyState::Closed
179 }
180
181 pub fn opacity(&self, now: Instant) -> f32 {
182 self.fade.value(now)
183 }
184
185 pub fn is_leaving(&self) -> bool {
186 self.fade.is_leaving()
187 }
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub struct PushOutcome {
192 pub id: u64,
193 pub bundled: bool,
194 pub became_mention: bool,
195}
196
197impl PushOutcome {
198 pub fn plays_sound(self, throttle_allows: bool) -> bool {
199 self.became_mention || (!self.bundled && throttle_allows)
200 }
201}
202
203#[derive(Default)]
204pub struct ToastStack {
205 toasts: Vec<ToastModel>,
206 next_id: u64,
207}
208
209impl ToastStack {
210 pub fn push(&mut self, incoming: &Incoming, now: Instant) -> PushOutcome {
211 if let Some(existing) = self
212 .toasts
213 .iter_mut()
214 .find(|toast| toast.agent.is_none() && toast.conversation_id == incoming.conversation_id)
215 {
216 let became_mention = incoming.mentions_me && !existing.mentions_me;
217 existing.count += 1;
218 existing.mentions_me |= incoming.mentions_me;
219 existing.message_id = incoming.message_id.clone();
220 existing.sender_id = incoming.sender_id.clone();
221 existing.sender_name = incoming.sender_name.clone();
222 existing.preview = incoming.preview.clone();
223 let mention = existing.mentions_me;
224 existing.timer.restart(now, mention);
225 return PushOutcome {
226 id: existing.id,
227 bundled: true,
228 became_mention,
229 };
230 }
231 self.next_id += 1;
232 let queued = self.toasts.len() >= MAX_VISIBLE;
233 self.toasts.push(ToastModel {
234 id: self.next_id,
235 conversation_id: incoming.conversation_id.clone(),
236 message_id: incoming.message_id.clone(),
237 kind: incoming.kind.clone(),
238 chat_title: incoming.chat_title.clone(),
239 sender_id: incoming.sender_id.clone(),
240 sender_name: incoming.sender_name.clone(),
241 preview: incoming.preview.clone(),
242 mentions_me: incoming.mentions_me,
243 count: 1,
244 timer: ToastTimer::new(now, incoming.mentions_me),
245 reply: ReplyState::Closed,
246 reply_text: String::new(),
247 hovered: false,
248 time: String::new(),
249 queued,
250 dismissed: false,
251 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
252 agent: None,
253 });
254 PushOutcome {
255 id: self.next_id,
256 bundled: false,
257 became_mention: false,
258 }
259 }
260
261 pub fn push_agent(
262 &mut self,
263 agent: AgentToast,
264 conversation_id: &str,
265 message_id: &str,
266 now: Instant,
267 ) -> u64 {
268 self.next_id += 1;
269 let queued = self.toasts.len() >= MAX_VISIBLE;
270 self.toasts.push(ToastModel {
271 id: self.next_id,
272 conversation_id: conversation_id.to_owned(),
273 message_id: message_id.to_owned(),
274 kind: ChatKind::Direct,
275 chat_title: String::new(),
276 sender_id: None,
277 sender_name: String::new(),
278 preview: Preview::Text(agent.body.clone()),
279 mentions_me: false,
280 count: 1,
281 timer: ToastTimer::new(now, true),
282 reply: ReplyState::Closed,
283 reply_text: String::new(),
284 hovered: false,
285 time: String::new(),
286 queued,
287 dismissed: false,
288 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
289 agent: Some(agent),
290 });
291 self.next_id
292 }
293
294 pub fn get(&self, id: u64) -> Option<&ToastModel> {
295 self.toasts.iter().find(|toast| toast.id == id)
296 }
297
298 pub fn get_mut(&mut self, id: u64) -> Option<&mut ToastModel> {
299 self.toasts.iter_mut().find(|toast| toast.id == id)
300 }
301
302 pub fn remove(&mut self, id: u64) -> Option<ToastModel> {
303 let index = self.toasts.iter().position(|toast| toast.id == id)?;
304 Some(self.toasts.remove(index))
305 }
306
307 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
308 let matches = |toast: &ToastModel| {
309 toast.agent.is_none() && toast.conversation_id == conversation_id
310 };
311 let ids: Vec<u64> = self
312 .toasts
313 .iter()
314 .filter(|toast| matches(toast))
315 .map(|toast| toast.id)
316 .collect();
317 self.toasts.retain(|toast| !matches(toast));
318 ids
319 }
320
321 pub fn visible(&self) -> &[ToastModel] {
322 let shown = self
323 .toasts
324 .iter()
325 .position(|toast| toast.queued)
326 .unwrap_or(self.toasts.len());
327 &self.toasts[..shown]
328 }
329
330 pub fn queued_count(&self) -> usize {
331 self.toasts.len() - self.visible().len()
332 }
333
334 pub fn promote(&mut self, now: Instant, fade_in: Duration) {
335 for toast in self.toasts.iter_mut().take(MAX_VISIBLE) {
336 if toast.queued {
337 toast.queued = false;
338 toast.timer = ToastTimer::new(now, toast.mentions_me);
339 toast.fade = Fade::new(0., 1., now, fade_in, Curve::Linear);
340 }
341 }
342 }
343
344 pub fn fade_out(&mut self, id: u64, now: Instant, duration: Duration) {
345 if let Some(toast) = self.get_mut(id)
346 && !toast.is_leaving()
347 {
348 toast.fade = Fade::new(toast.opacity(now), 0., now, duration, Curve::EaseInCirc);
349 }
350 }
351
352 pub fn dismiss(&mut self, id: u64, now: Instant, duration: Duration) {
353 let Some(index) = self.toasts.iter().position(|toast| toast.id == id) else {
354 return;
355 };
356 if self.toasts[index].queued {
357 self.toasts.remove(index);
358 return;
359 }
360 let toast = &mut self.toasts[index];
361 if !toast.dismissed {
362 toast.dismissed = true;
363 toast.hovered = false;
364 toast.fade = Fade::new(toast.opacity(now), 0., now, duration, Curve::Linear);
365 }
366 }
367
368 pub fn restore(&mut self, now: Instant, duration: Duration) {
369 for toast in self
370 .toasts
371 .iter_mut()
372 .filter(|toast| toast.is_leaving() && !toast.dismissed)
373 {
374 toast.fade = Fade::new(toast.opacity(now), 1., now, duration, Curve::Linear);
375 }
376 }
377
378 pub fn any_hovered(&self) -> bool {
379 self.toasts.iter().any(|toast| toast.hovered)
380 }
381
382 pub fn ids(&self) -> Vec<u64> {
383 self.toasts.iter().map(|toast| toast.id).collect()
384 }
385
386 pub fn gone(&self, now: Instant) -> Vec<u64> {
387 self.toasts
388 .iter()
389 .filter(|toast| toast.fade.is_gone(now))
390 .map(|toast| toast.id)
391 .collect()
392 }
393
394 pub fn is_empty(&self) -> bool {
395 self.toasts.is_empty()
396 }
397
398 pub fn expired(&self, now: Instant) -> Vec<u64> {
399 self.toasts
400 .iter()
401 .filter(|toast| {
402 !toast.queued
403 && !toast.is_leaving()
404 && !toast.holds_open()
405 && toast.timer.expired(now)
406 })
407 .map(|toast| toast.id)
408 .collect()
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 fn incoming(conversation: &str, mention: bool) -> Incoming {
417 Incoming {
418 conversation_id: conversation.into(),
419 message_id: "m".into(),
420 kind: ChatKind::Direct,
421 chat_title: "Chat".into(),
422 sender_id: None,
423 sender_name: "Mara".into(),
424 preview: Preview::Text("Hello".into()),
425 mentions_me: mention,
426 muted: false,
427 signals: Default::default(),
428 created_at: chrono::Utc::now(),
429 }
430 }
431
432 #[test]
433 fn same_chat_bundles_into_one_toast_with_counter() {
434 let mut stack = ToastStack::default();
435 let now = Instant::now();
436 let first = stack.push(&incoming("a", false), now);
437 let second = stack.push(&incoming("a", false), now + Duration::from_secs(2));
438 assert!(!first.bundled);
439 assert!(second.bundled);
440 assert_eq!(first.id, second.id);
441 assert_eq!(stack.get(first.id).unwrap().count, 2);
442 assert_eq!(stack.visible().len(), 1);
443 }
444
445 #[test]
446 fn bundling_restarts_timer() {
447 let mut stack = ToastStack::default();
448 let now = Instant::now();
449 let id = stack.push(&incoming("a", false), now).id;
450 stack.push(&incoming("a", false), now + Duration::from_secs(5));
451 assert!(stack.expired(now + Duration::from_secs(7)).is_empty());
452 assert_eq!(stack.expired(now + Duration::from_secs(11)), vec![id]);
453 }
454
455 #[test]
456 fn mention_in_burst_upgrades_and_plays_sound() {
457 let mut stack = ToastStack::default();
458 let now = Instant::now();
459 stack.push(&incoming("a", false), now);
460 let outcome = stack.push(&incoming("a", true), now);
461 assert!(outcome.became_mention);
462 assert!(outcome.plays_sound(false));
463 assert!(stack.get(outcome.id).unwrap().mentions_me);
464 let again = stack.push(&incoming("a", true), now);
465 assert!(!again.plays_sound(true));
466 }
467
468 #[test]
469 fn only_first_of_burst_plays_sound() {
470 let mut stack = ToastStack::default();
471 let now = Instant::now();
472 assert!(stack.push(&incoming("a", false), now).plays_sound(true));
473 assert!(!stack.push(&incoming("a", false), now).plays_sound(true));
474 assert!(!stack.push(&incoming("b", false), now).plays_sound(false));
475 }
476
477 fn visible_chats(stack: &ToastStack) -> Vec<&str> {
478 stack
479 .visible()
480 .iter()
481 .map(|toast| toast.conversation_id.as_str())
482 .collect()
483 }
484
485 #[test]
486 fn shows_first_three_and_queues_the_rest() {
487 let mut stack = ToastStack::default();
488 let now = Instant::now();
489 for chat in ["a", "b", "c", "d", "e"] {
490 stack.push(&incoming(chat, false), now);
491 }
492 assert_eq!(visible_chats(&stack), ["a", "b", "c"]);
493 assert_eq!(stack.queued_count(), 2);
494 }
495
496 #[test]
497 fn queued_toast_starts_its_timer_when_promoted() {
498 let mut stack = ToastStack::default();
499 let start = Instant::now();
500 let ids: Vec<u64> = ["a", "b", "c", "d"]
501 .into_iter()
502 .map(|chat| stack.push(&incoming(chat, false), start).id)
503 .collect();
504 let later = start + Duration::from_secs(30);
505 assert!(!stack.expired(later).contains(&ids[3]));
506 stack.remove(ids[0]);
507 stack.promote(later, FADE_IN);
508 assert_eq!(visible_chats(&stack), ["b", "c", "d"]);
509 assert!(!stack.expired(later + Duration::from_secs(5)).contains(&ids[3]));
510 assert!(stack.expired(later + Duration::from_secs(6)).contains(&ids[3]));
511 }
512
513 #[test]
514 fn slow_fade_stays_visible_then_drops_and_is_gone() {
515 let mut stack = ToastStack::default();
516 let now = Instant::now();
517 let id = stack.push(&incoming("a", false), now).id;
518 let hide_at = now + Duration::from_secs(6);
519 stack.fade_out(id, hide_at, SLOW_FADE);
520 let toast = stack.get(id).unwrap();
521 assert!(toast.opacity(hide_at + Duration::from_secs(2)) > 0.8);
522 assert!(stack.gone(hide_at + Duration::from_secs(3)).is_empty());
523 assert_eq!(stack.gone(hide_at + SLOW_FADE), vec![id]);
524 }
525
526 #[test]
527 fn restore_brings_a_fading_toast_back() {
528 let mut stack = ToastStack::default();
529 let now = Instant::now();
530 let id = stack.push(&incoming("a", false), now).id;
531 stack.fade_out(id, now, SLOW_FADE);
532 stack.restore(now + Duration::from_secs(3), FAST_FADE);
533 let toast = stack.get(id).unwrap();
534 assert!(!toast.is_leaving());
535 assert_eq!(toast.opacity(now + Duration::from_secs(4)), 1.);
536 assert!(stack.gone(now + Duration::from_secs(10)).is_empty());
537 }
538
539 #[test]
540 fn hiding_a_queued_toast_drops_it_at_once() {
541 let mut stack = ToastStack::default();
542 let now = Instant::now();
543 let ids: Vec<u64> = ["a", "b", "c", "d"]
544 .into_iter()
545 .map(|chat| stack.push(&incoming(chat, false), now).id)
546 .collect();
547 stack.dismiss(ids[3], now, FAST_FADE);
548 assert!(stack.get(ids[3]).is_none());
549 assert_eq!(stack.queued_count(), 0);
550 }
551
552 #[test]
553 fn dismiss_cuts_a_slow_fade_short_and_hover_does_not_undo_it() {
554 let mut stack = ToastStack::default();
555 let now = Instant::now();
556 let id = stack.push(&incoming("a", false), now).id;
557 stack.fade_out(id, now, SLOW_FADE);
558 stack.dismiss(id, now + Duration::from_secs(1), FAST_FADE);
559 stack.restore(now + Duration::from_millis(1050), FAST_FADE);
560 assert_eq!(stack.gone(now + Duration::from_millis(1150)), vec![id]);
561 }
562
563 #[test]
564 fn mention_lasts_ten_seconds() {
565 let now = Instant::now();
566 let timer = ToastTimer::new(now, true);
567 assert!(!timer.expired(now + Duration::from_secs(9)));
568 assert!(timer.expired(now + Duration::from_secs(10)));
569 }
570
571 #[test]
572 fn hard_cap_beats_restarts() {
573 let mut stack = ToastStack::default();
574 let start = Instant::now();
575 let id = stack.push(&incoming("a", false), start).id;
576 for second in [5, 10, 15, 19] {
577 stack.push(&incoming("a", false), start + Duration::from_secs(second));
578 }
579 assert!(stack.expired(start + Duration::from_secs(19)).is_empty());
580 assert_eq!(stack.expired(start + Duration::from_secs(20)), vec![id]);
581 }
582
583 #[test]
584 fn pause_stops_expiry_and_resume_leaves_two_seconds() {
585 let now = Instant::now();
586 let mut timer = ToastTimer::new(now, false);
587 timer.pause(now + Duration::from_secs(1));
588 assert!(!timer.expired(now + Duration::from_secs(60)));
589 let resumed = now + Duration::from_secs(60);
590 timer.resume(resumed);
591 assert!(!timer.expired(resumed + Duration::from_millis(1900)));
592 assert!(timer.expired(resumed + Duration::from_secs(2)));
593 }
594
595 #[test]
596 fn open_reply_field_holds_toast() {
597 let mut stack = ToastStack::default();
598 let now = Instant::now();
599 let id = stack.push(&incoming("a", false), now).id;
600 stack.get_mut(id).unwrap().reply = ReplyState::Open;
601 assert!(stack.expired(now + Duration::from_secs(60)).is_empty());
602 }
603
604 #[test]
605 fn remove_conversation_returns_ids() {
606 let mut stack = ToastStack::default();
607 let now = Instant::now();
608 let id = stack.push(&incoming("a", false), now).id;
609 stack.push(&incoming("b", false), now);
610 assert_eq!(stack.remove_conversation("a"), vec![id]);
611 assert_eq!(stack.visible().len(), 1);
612 }
613
614 fn agent_toast() -> AgentToast {
615 AgentToast {
616 run_id: 7,
617 session_id: "s".into(),
618 header: "Answer this - Claude - 1:02".into(),
619 title: "Claude finished: Answer this for Mara".into(),
620 body: "Done".into(),
621 failed: false,
622 }
623 }
624
625 #[test]
626 fn agent_toasts_never_bundle_with_messages() {
627 let mut stack = ToastStack::default();
628 let now = Instant::now();
629 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
630 let outcome = stack.push(&incoming("a", false), now);
631 assert!(!outcome.bundled);
632 assert_ne!(outcome.id, agent_id);
633 assert_eq!(stack.visible().len(), 2);
634 }
635
636 #[test]
637 fn opening_the_chat_keeps_the_agent_toast() {
638 let mut stack = ToastStack::default();
639 let now = Instant::now();
640 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
641 let message_id = stack.push(&incoming("a", false), now).id;
642 assert_eq!(stack.remove_conversation("a"), vec![message_id]);
643 assert!(stack.get(agent_id).is_some());
644 }
645}