BlueGit

ict rusty-teams

Files

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

stack.rs

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