BlueGit

ict rusty-teams

Files

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

stack.rs

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