BlueGit

ict rusty-teams

Files

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

stack.rs

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