BlueGit

ict rusty-teams

Files

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

stack.rs

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