BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / 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 chat: Default::default(),
426 created_at: chrono::Utc::now(),
427 }
428 }
429
430 #[test]
431 fn same_chat_bundles_into_one_toast_with_counter() {
432 let mut stack = ToastStack::default();
433 let now = Instant::now();
434 let first = stack.push(&incoming("a", false), now);
435 let second = stack.push(&incoming("a", false), now + Duration::from_secs(2));
436 assert!(!first.bundled);
437 assert!(second.bundled);
438 assert_eq!(first.id, second.id);
439 assert_eq!(stack.get(first.id).unwrap().count, 2);
440 assert_eq!(stack.visible().len(), 1);
441 }
442
443 #[test]
444 fn bundling_restarts_timer() {
445 let mut stack = ToastStack::default();
446 let now = Instant::now();
447 let id = stack.push(&incoming("a", false), now).id;
448 stack.push(&incoming("a", false), now + Duration::from_secs(5));
449 assert!(stack.expired(now + Duration::from_secs(7)).is_empty());
450 assert_eq!(stack.expired(now + Duration::from_secs(11)), vec![id]);
451 }
452
453 #[test]
454 fn mention_in_burst_upgrades_and_plays_sound() {
455 let mut stack = ToastStack::default();
456 let now = Instant::now();
457 stack.push(&incoming("a", false), now);
458 let outcome = stack.push(&incoming("a", true), now);
459 assert!(outcome.became_mention);
460 assert!(outcome.plays_sound(false));
461 assert!(stack.get(outcome.id).unwrap().mentions_me);
462 let again = stack.push(&incoming("a", true), now);
463 assert!(!again.plays_sound(true));
464 }
465
466 #[test]
467 fn only_first_of_burst_plays_sound() {
468 let mut stack = ToastStack::default();
469 let now = Instant::now();
470 assert!(stack.push(&incoming("a", false), now).plays_sound(true));
471 assert!(!stack.push(&incoming("a", false), now).plays_sound(true));
472 assert!(!stack.push(&incoming("b", false), now).plays_sound(false));
473 }
474
475 fn visible_chats(stack: &ToastStack) -> Vec<&str> {
476 stack
477 .visible()
478 .iter()
479 .map(|toast| toast.conversation_id.as_str())
480 .collect()
481 }
482
483 #[test]
484 fn shows_first_three_and_queues_the_rest() {
485 let mut stack = ToastStack::default();
486 let now = Instant::now();
487 for chat in ["a", "b", "c", "d", "e"] {
488 stack.push(&incoming(chat, false), now);
489 }
490 assert_eq!(visible_chats(&stack), ["a", "b", "c"]);
491 assert_eq!(stack.queued_count(), 2);
492 }
493
494 #[test]
495 fn queued_toast_starts_its_timer_when_promoted() {
496 let mut stack = ToastStack::default();
497 let start = Instant::now();
498 let ids: Vec<u64> = ["a", "b", "c", "d"]
499 .into_iter()
500 .map(|chat| stack.push(&incoming(chat, false), start).id)
501 .collect();
502 let later = start + Duration::from_secs(30);
503 assert!(!stack.expired(later).contains(&ids[3]));
504 stack.remove(ids[0]);
505 stack.promote(later, FADE_IN);
506 assert_eq!(visible_chats(&stack), ["b", "c", "d"]);
507 assert!(
508 !stack
509 .expired(later + Duration::from_secs(5))
510 .contains(&ids[3])
511 );
512 assert!(
513 stack
514 .expired(later + Duration::from_secs(6))
515 .contains(&ids[3])
516 );
517 }
518
519 #[test]
520 fn slow_fade_stays_visible_then_drops_and_is_gone() {
521 let mut stack = ToastStack::default();
522 let now = Instant::now();
523 let id = stack.push(&incoming("a", false), now).id;
524 let hide_at = now + Duration::from_secs(6);
525 stack.fade_out(id, hide_at, SLOW_FADE);
526 let toast = stack.get(id).unwrap();
527 assert!(toast.opacity(hide_at + Duration::from_secs(2)) > 0.8);
528 assert!(stack.gone(hide_at + Duration::from_secs(3)).is_empty());
529 assert_eq!(stack.gone(hide_at + SLOW_FADE), vec![id]);
530 }
531
532 #[test]
533 fn restore_brings_a_fading_toast_back() {
534 let mut stack = ToastStack::default();
535 let now = Instant::now();
536 let id = stack.push(&incoming("a", false), now).id;
537 stack.fade_out(id, now, SLOW_FADE);
538 stack.restore(now + Duration::from_secs(3), FAST_FADE);
539 let toast = stack.get(id).unwrap();
540 assert!(!toast.is_leaving());
541 assert_eq!(toast.opacity(now + Duration::from_secs(4)), 1.);
542 assert!(stack.gone(now + Duration::from_secs(10)).is_empty());
543 }
544
545 #[test]
546 fn hiding_a_queued_toast_drops_it_at_once() {
547 let mut stack = ToastStack::default();
548 let now = Instant::now();
549 let ids: Vec<u64> = ["a", "b", "c", "d"]
550 .into_iter()
551 .map(|chat| stack.push(&incoming(chat, false), now).id)
552 .collect();
553 stack.dismiss(ids[3], now, FAST_FADE);
554 assert!(stack.get(ids[3]).is_none());
555 assert_eq!(stack.queued_count(), 0);
556 }
557
558 #[test]
559 fn dismiss_cuts_a_slow_fade_short_and_hover_does_not_undo_it() {
560 let mut stack = ToastStack::default();
561 let now = Instant::now();
562 let id = stack.push(&incoming("a", false), now).id;
563 stack.fade_out(id, now, SLOW_FADE);
564 stack.dismiss(id, now + Duration::from_secs(1), FAST_FADE);
565 stack.restore(now + Duration::from_millis(1050), FAST_FADE);
566 assert_eq!(stack.gone(now + Duration::from_millis(1150)), vec![id]);
567 }
568
569 #[test]
570 fn mention_lasts_ten_seconds() {
571 let now = Instant::now();
572 let timer = ToastTimer::new(now, true);
573 assert!(!timer.expired(now + Duration::from_secs(9)));
574 assert!(timer.expired(now + Duration::from_secs(10)));
575 }
576
577 #[test]
578 fn hard_cap_beats_restarts() {
579 let mut stack = ToastStack::default();
580 let start = Instant::now();
581 let id = stack.push(&incoming("a", false), start).id;
582 for second in [5, 10, 15, 19] {
583 stack.push(&incoming("a", false), start + Duration::from_secs(second));
584 }
585 assert!(stack.expired(start + Duration::from_secs(19)).is_empty());
586 assert_eq!(stack.expired(start + Duration::from_secs(20)), vec![id]);
587 }
588
589 #[test]
590 fn pause_stops_expiry_and_resume_leaves_two_seconds() {
591 let now = Instant::now();
592 let mut timer = ToastTimer::new(now, false);
593 timer.pause(now + Duration::from_secs(1));
594 assert!(!timer.expired(now + Duration::from_secs(60)));
595 let resumed = now + Duration::from_secs(60);
596 timer.resume(resumed);
597 assert!(!timer.expired(resumed + Duration::from_millis(1900)));
598 assert!(timer.expired(resumed + Duration::from_secs(2)));
599 }
600
601 #[test]
602 fn open_reply_field_holds_toast() {
603 let mut stack = ToastStack::default();
604 let now = Instant::now();
605 let id = stack.push(&incoming("a", false), now).id;
606 stack.get_mut(id).unwrap().reply = ReplyState::Open;
607 assert!(stack.expired(now + Duration::from_secs(60)).is_empty());
608 }
609
610 #[test]
611 fn remove_conversation_returns_ids() {
612 let mut stack = ToastStack::default();
613 let now = Instant::now();
614 let id = stack.push(&incoming("a", false), now).id;
615 stack.push(&incoming("b", false), now);
616 assert_eq!(stack.remove_conversation("a"), vec![id]);
617 assert_eq!(stack.visible().len(), 1);
618 }
619
620 fn agent_toast() -> AgentToast {
621 AgentToast {
622 run_id: 7,
623 session_id: "s".into(),
624 header: "Answer this - Claude - 1:02".into(),
625 title: "Claude finished: Answer this for Mara".into(),
626 body: "Done".into(),
627 failed: false,
628 }
629 }
630
631 #[test]
632 fn agent_toasts_never_bundle_with_messages() {
633 let mut stack = ToastStack::default();
634 let now = Instant::now();
635 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
636 let outcome = stack.push(&incoming("a", false), now);
637 assert!(!outcome.bundled);
638 assert_ne!(outcome.id, agent_id);
639 assert_eq!(stack.visible().len(), 2);
640 }
641
642 #[test]
643 fn opening_the_chat_keeps_the_agent_toast() {
644 let mut stack = ToastStack::default();
645 let now = Instant::now();
646 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
647 let message_id = stack.push(&incoming("a", false), now).id;
648 assert_eq!(stack.remove_conversation("a"), vec![message_id]);
649 assert!(stack.get(agent_id).is_some());
650 }
651}