BlueGit

ict rusty-teams

Files

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

stack.rs

stack.rs 20.2 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.toasts.iter_mut().find(|toast| {
212 toast.agent.is_none() && toast.conversation_id == incoming.conversation_id
213 }) {
214 let became_mention = incoming.mentions_me && !existing.mentions_me;
215 existing.count += 1;
216 existing.mentions_me |= incoming.mentions_me;
217 existing.message_id = incoming.message_id.clone();
218 existing.sender_id = incoming.sender_id.clone();
219 existing.sender_name = incoming.sender_name.clone();
220 existing.preview = incoming.preview.clone();
221 let mention = existing.mentions_me;
222 existing.timer.restart(now, mention);
223 return PushOutcome {
224 id: existing.id,
225 bundled: true,
226 became_mention,
227 };
228 }
229 self.next_id += 1;
230 let queued = self.toasts.len() >= MAX_VISIBLE;
231 self.toasts.push(ToastModel {
232 id: self.next_id,
233 conversation_id: incoming.conversation_id.clone(),
234 message_id: incoming.message_id.clone(),
235 kind: incoming.kind.clone(),
236 chat_title: incoming.chat_title.clone(),
237 sender_id: incoming.sender_id.clone(),
238 sender_name: incoming.sender_name.clone(),
239 preview: incoming.preview.clone(),
240 mentions_me: incoming.mentions_me,
241 count: 1,
242 timer: ToastTimer::new(now, incoming.mentions_me),
243 reply: ReplyState::Closed,
244 reply_text: String::new(),
245 hovered: false,
246 time: String::new(),
247 queued,
248 dismissed: false,
249 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
250 agent: None,
251 });
252 PushOutcome {
253 id: self.next_id,
254 bundled: false,
255 became_mention: false,
256 }
257 }
258
259 pub fn push_agent(
260 &mut self,
261 agent: AgentToast,
262 conversation_id: &str,
263 message_id: &str,
264 now: Instant,
265 ) -> u64 {
266 self.next_id += 1;
267 let queued = self.toasts.len() >= MAX_VISIBLE;
268 self.toasts.push(ToastModel {
269 id: self.next_id,
270 conversation_id: conversation_id.to_owned(),
271 message_id: message_id.to_owned(),
272 kind: ChatKind::Direct,
273 chat_title: String::new(),
274 sender_id: None,
275 sender_name: String::new(),
276 preview: Preview::Text(agent.body.clone()),
277 mentions_me: false,
278 count: 1,
279 timer: ToastTimer::new(now, true),
280 reply: ReplyState::Closed,
281 reply_text: String::new(),
282 hovered: false,
283 time: String::new(),
284 queued,
285 dismissed: false,
286 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
287 agent: Some(agent),
288 });
289 self.next_id
290 }
291
292 pub fn get(&self, id: u64) -> Option<&ToastModel> {
293 self.toasts.iter().find(|toast| toast.id == id)
294 }
295
296 pub fn get_mut(&mut self, id: u64) -> Option<&mut ToastModel> {
297 self.toasts.iter_mut().find(|toast| toast.id == id)
298 }
299
300 pub fn remove(&mut self, id: u64) -> Option<ToastModel> {
301 let index = self.toasts.iter().position(|toast| toast.id == id)?;
302 Some(self.toasts.remove(index))
303 }
304
305 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
306 let matches =
307 |toast: &ToastModel| toast.agent.is_none() && toast.conversation_id == conversation_id;
308 let ids: Vec<u64> = self
309 .toasts
310 .iter()
311 .filter(|toast| matches(toast))
312 .map(|toast| toast.id)
313 .collect();
314 self.toasts.retain(|toast| !matches(toast));
315 ids
316 }
317
318 pub fn visible(&self) -> &[ToastModel] {
319 let shown = self
320 .toasts
321 .iter()
322 .position(|toast| toast.queued)
323 .unwrap_or(self.toasts.len());
324 &self.toasts[..shown]
325 }
326
327 pub fn queued_count(&self) -> usize {
328 self.toasts.len() - self.visible().len()
329 }
330
331 pub fn promote(&mut self, now: Instant, fade_in: Duration) {
332 for toast in self.toasts.iter_mut().take(MAX_VISIBLE) {
333 if toast.queued {
334 toast.queued = false;
335 toast.timer = ToastTimer::new(now, toast.mentions_me);
336 toast.fade = Fade::new(0., 1., now, fade_in, Curve::Linear);
337 }
338 }
339 }
340
341 pub fn fade_out(&mut self, id: u64, now: Instant, duration: Duration) {
342 if let Some(toast) = self.get_mut(id)
343 && !toast.is_leaving()
344 {
345 toast.fade = Fade::new(toast.opacity(now), 0., now, duration, Curve::EaseInCirc);
346 }
347 }
348
349 pub fn dismiss(&mut self, id: u64, now: Instant, duration: Duration) {
350 let Some(index) = self.toasts.iter().position(|toast| toast.id == id) else {
351 return;
352 };
353 if self.toasts[index].queued {
354 self.toasts.remove(index);
355 return;
356 }
357 let toast = &mut self.toasts[index];
358 if !toast.dismissed {
359 toast.dismissed = true;
360 toast.hovered = false;
361 toast.fade = Fade::new(toast.opacity(now), 0., now, duration, Curve::Linear);
362 }
363 }
364
365 pub fn restore(&mut self, now: Instant, duration: Duration) {
366 for toast in self
367 .toasts
368 .iter_mut()
369 .filter(|toast| toast.is_leaving() && !toast.dismissed)
370 {
371 toast.fade = Fade::new(toast.opacity(now), 1., now, duration, Curve::Linear);
372 }
373 }
374
375 pub fn any_hovered(&self) -> bool {
376 self.toasts.iter().any(|toast| toast.hovered)
377 }
378
379 pub fn ids(&self) -> Vec<u64> {
380 self.toasts.iter().map(|toast| toast.id).collect()
381 }
382
383 pub fn gone(&self, now: Instant) -> Vec<u64> {
384 self.toasts
385 .iter()
386 .filter(|toast| toast.fade.is_gone(now))
387 .map(|toast| toast.id)
388 .collect()
389 }
390
391 pub fn is_empty(&self) -> bool {
392 self.toasts.is_empty()
393 }
394
395 pub fn expired(&self, now: Instant) -> Vec<u64> {
396 self.toasts
397 .iter()
398 .filter(|toast| {
399 !toast.queued
400 && !toast.is_leaving()
401 && !toast.holds_open()
402 && toast.timer.expired(now)
403 })
404 .map(|toast| toast.id)
405 .collect()
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 fn incoming(conversation: &str, mention: bool) -> Incoming {
414 Incoming {
415 conversation_id: conversation.into(),
416 message_id: "m".into(),
417 kind: ChatKind::Direct,
418 chat_title: "Chat".into(),
419 sender_id: None,
420 sender_name: "Mara".into(),
421 preview: Preview::Text("Hello".into()),
422 mentions_me: mention,
423 muted: false,
424 signals: Default::default(),
425 created_at: chrono::Utc::now(),
426 }
427 }
428
429 #[test]
430 fn same_chat_bundles_into_one_toast_with_counter() {
431 let mut stack = ToastStack::default();
432 let now = Instant::now();
433 let first = stack.push(&incoming("a", false), now);
434 let second = stack.push(&incoming("a", false), now + Duration::from_secs(2));
435 assert!(!first.bundled);
436 assert!(second.bundled);
437 assert_eq!(first.id, second.id);
438 assert_eq!(stack.get(first.id).unwrap().count, 2);
439 assert_eq!(stack.visible().len(), 1);
440 }
441
442 #[test]
443 fn bundling_restarts_timer() {
444 let mut stack = ToastStack::default();
445 let now = Instant::now();
446 let id = stack.push(&incoming("a", false), now).id;
447 stack.push(&incoming("a", false), now + Duration::from_secs(5));
448 assert!(stack.expired(now + Duration::from_secs(7)).is_empty());
449 assert_eq!(stack.expired(now + Duration::from_secs(11)), vec![id]);
450 }
451
452 #[test]
453 fn mention_in_burst_upgrades_and_plays_sound() {
454 let mut stack = ToastStack::default();
455 let now = Instant::now();
456 stack.push(&incoming("a", false), now);
457 let outcome = stack.push(&incoming("a", true), now);
458 assert!(outcome.became_mention);
459 assert!(outcome.plays_sound(false));
460 assert!(stack.get(outcome.id).unwrap().mentions_me);
461 let again = stack.push(&incoming("a", true), now);
462 assert!(!again.plays_sound(true));
463 }
464
465 #[test]
466 fn only_first_of_burst_plays_sound() {
467 let mut stack = ToastStack::default();
468 let now = Instant::now();
469 assert!(stack.push(&incoming("a", false), now).plays_sound(true));
470 assert!(!stack.push(&incoming("a", false), now).plays_sound(true));
471 assert!(!stack.push(&incoming("b", false), now).plays_sound(false));
472 }
473
474 fn visible_chats(stack: &ToastStack) -> Vec<&str> {
475 stack
476 .visible()
477 .iter()
478 .map(|toast| toast.conversation_id.as_str())
479 .collect()
480 }
481
482 #[test]
483 fn shows_first_three_and_queues_the_rest() {
484 let mut stack = ToastStack::default();
485 let now = Instant::now();
486 for chat in ["a", "b", "c", "d", "e"] {
487 stack.push(&incoming(chat, false), now);
488 }
489 assert_eq!(visible_chats(&stack), ["a", "b", "c"]);
490 assert_eq!(stack.queued_count(), 2);
491 }
492
493 #[test]
494 fn queued_toast_starts_its_timer_when_promoted() {
495 let mut stack = ToastStack::default();
496 let start = Instant::now();
497 let ids: Vec<u64> = ["a", "b", "c", "d"]
498 .into_iter()
499 .map(|chat| stack.push(&incoming(chat, false), start).id)
500 .collect();
501 let later = start + Duration::from_secs(30);
502 assert!(!stack.expired(later).contains(&ids[3]));
503 stack.remove(ids[0]);
504 stack.promote(later, FADE_IN);
505 assert_eq!(visible_chats(&stack), ["b", "c", "d"]);
506 assert!(
507 !stack
508 .expired(later + Duration::from_secs(5))
509 .contains(&ids[3])
510 );
511 assert!(
512 stack
513 .expired(later + Duration::from_secs(6))
514 .contains(&ids[3])
515 );
516 }
517
518 #[test]
519 fn slow_fade_stays_visible_then_drops_and_is_gone() {
520 let mut stack = ToastStack::default();
521 let now = Instant::now();
522 let id = stack.push(&incoming("a", false), now).id;
523 let hide_at = now + Duration::from_secs(6);
524 stack.fade_out(id, hide_at, SLOW_FADE);
525 let toast = stack.get(id).unwrap();
526 assert!(toast.opacity(hide_at + Duration::from_secs(2)) > 0.8);
527 assert!(stack.gone(hide_at + Duration::from_secs(3)).is_empty());
528 assert_eq!(stack.gone(hide_at + SLOW_FADE), vec![id]);
529 }
530
531 #[test]
532 fn restore_brings_a_fading_toast_back() {
533 let mut stack = ToastStack::default();
534 let now = Instant::now();
535 let id = stack.push(&incoming("a", false), now).id;
536 stack.fade_out(id, now, SLOW_FADE);
537 stack.restore(now + Duration::from_secs(3), FAST_FADE);
538 let toast = stack.get(id).unwrap();
539 assert!(!toast.is_leaving());
540 assert_eq!(toast.opacity(now + Duration::from_secs(4)), 1.);
541 assert!(stack.gone(now + Duration::from_secs(10)).is_empty());
542 }
543
544 #[test]
545 fn hiding_a_queued_toast_drops_it_at_once() {
546 let mut stack = ToastStack::default();
547 let now = Instant::now();
548 let ids: Vec<u64> = ["a", "b", "c", "d"]
549 .into_iter()
550 .map(|chat| stack.push(&incoming(chat, false), now).id)
551 .collect();
552 stack.dismiss(ids[3], now, FAST_FADE);
553 assert!(stack.get(ids[3]).is_none());
554 assert_eq!(stack.queued_count(), 0);
555 }
556
557 #[test]
558 fn dismiss_cuts_a_slow_fade_short_and_hover_does_not_undo_it() {
559 let mut stack = ToastStack::default();
560 let now = Instant::now();
561 let id = stack.push(&incoming("a", false), now).id;
562 stack.fade_out(id, now, SLOW_FADE);
563 stack.dismiss(id, now + Duration::from_secs(1), FAST_FADE);
564 stack.restore(now + Duration::from_millis(1050), FAST_FADE);
565 assert_eq!(stack.gone(now + Duration::from_millis(1150)), vec![id]);
566 }
567
568 #[test]
569 fn mention_lasts_ten_seconds() {
570 let now = Instant::now();
571 let timer = ToastTimer::new(now, true);
572 assert!(!timer.expired(now + Duration::from_secs(9)));
573 assert!(timer.expired(now + Duration::from_secs(10)));
574 }
575
576 #[test]
577 fn hard_cap_beats_restarts() {
578 let mut stack = ToastStack::default();
579 let start = Instant::now();
580 let id = stack.push(&incoming("a", false), start).id;
581 for second in [5, 10, 15, 19] {
582 stack.push(&incoming("a", false), start + Duration::from_secs(second));
583 }
584 assert!(stack.expired(start + Duration::from_secs(19)).is_empty());
585 assert_eq!(stack.expired(start + Duration::from_secs(20)), vec![id]);
586 }
587
588 #[test]
589 fn pause_stops_expiry_and_resume_leaves_two_seconds() {
590 let now = Instant::now();
591 let mut timer = ToastTimer::new(now, false);
592 timer.pause(now + Duration::from_secs(1));
593 assert!(!timer.expired(now + Duration::from_secs(60)));
594 let resumed = now + Duration::from_secs(60);
595 timer.resume(resumed);
596 assert!(!timer.expired(resumed + Duration::from_millis(1900)));
597 assert!(timer.expired(resumed + Duration::from_secs(2)));
598 }
599
600 #[test]
601 fn open_reply_field_holds_toast() {
602 let mut stack = ToastStack::default();
603 let now = Instant::now();
604 let id = stack.push(&incoming("a", false), now).id;
605 stack.get_mut(id).unwrap().reply = ReplyState::Open;
606 assert!(stack.expired(now + Duration::from_secs(60)).is_empty());
607 }
608
609 #[test]
610 fn remove_conversation_returns_ids() {
611 let mut stack = ToastStack::default();
612 let now = Instant::now();
613 let id = stack.push(&incoming("a", false), now).id;
614 stack.push(&incoming("b", false), now);
615 assert_eq!(stack.remove_conversation("a"), vec![id]);
616 assert_eq!(stack.visible().len(), 1);
617 }
618
619 fn agent_toast() -> AgentToast {
620 AgentToast {
621 run_id: 7,
622 session_id: "s".into(),
623 header: "Answer this - Claude - 1:02".into(),
624 title: "Claude finished: Answer this for Mara".into(),
625 body: "Done".into(),
626 failed: false,
627 }
628 }
629
630 #[test]
631 fn agent_toasts_never_bundle_with_messages() {
632 let mut stack = ToastStack::default();
633 let now = Instant::now();
634 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
635 let outcome = stack.push(&incoming("a", false), now);
636 assert!(!outcome.bundled);
637 assert_ne!(outcome.id, agent_id);
638 assert_eq!(stack.visible().len(), 2);
639 }
640
641 #[test]
642 fn opening_the_chat_keeps_the_agent_toast() {
643 let mut stack = ToastStack::default();
644 let now = Instant::now();
645 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
646 let message_id = stack.push(&incoming("a", false), now).id;
647 assert_eq!(stack.remove_conversation("a"), vec![message_id]);
648 assert!(stack.get(agent_id).is_some());
649 }
650}