Skip to main content

aios_cli/benchmark_next_app/baselines/
notification.rs

1//! Notification-based baseline predictors for the next-app benchmark.
2
3use std::collections::{HashMap, HashSet};
4use std::time::Instant;
5
6use aios_spec::{SanitizedEventType, SemanticHint};
7
8use crate::benchmark_next_app::types::{NextAppPredictor, PredictionResult, ScoredPrediction};
9
10use super::simple::cmp_score_desc;
11
12/// Predict the app that most recently posted a notification.
13pub struct RecentNotificationBackend;
14
15impl NextAppPredictor for RecentNotificationBackend {
16    fn name(&self) -> &'static str {
17        "recent_notification"
18    }
19
20    fn predict(
21        &self,
22        ctx: &aios_spec::StructuredContext,
23        _current_app: &str,
24        candidates: &[String],
25    ) -> PredictionResult {
26        let start = Instant::now();
27        let ranked = ctx
28            .events
29            .iter()
30            .filter_map(|e| match &e.event_type {
31                SanitizedEventType::Notification { source_package, .. } => {
32                    Some((e.timestamp_ms, source_package.clone()))
33                },
34                _ => None,
35            })
36            .max_by(|a, b| a.0.cmp(&b.0).then_with(|| b.1.cmp(&a.1)))
37            .and_then(|(_, package)| {
38                if candidates.contains(&package) {
39                    Some(vec![ScoredPrediction {
40                        package,
41                        score: 1.0,
42                    }])
43                } else {
44                    None
45                }
46            })
47            .unwrap_or_default();
48        PredictionResult {
49            ranked,
50            latency_us: start.elapsed().as_micros() as u64,
51            rationale_present: false,
52        }
53    }
54}
55
56/// Rank candidates by notification priority heuristics.
57pub struct NotificationPriorityBackend;
58
59/// True for categories that launcher-style ranking treats as time-critical.
60fn is_priority_category(category: &Option<String>) -> bool {
61    category.as_ref().is_some_and(|cat| {
62        cat.eq_ignore_ascii_case("alarm")
63            || cat.eq_ignore_ascii_case("call")
64            || cat.eq_ignore_ascii_case("event")
65    })
66}
67
68/// Score a single notification event for priority ranking.
69///
70/// Weights mirror launcher-style notification priority:
71/// - ongoing notifications (+3) are persistent and high-visibility.
72/// - rich attachments / mentions (+2 for file/image/link) signal actionable content.
73/// - social/calendar signals and system categories (+1 each) are weaker but still salient.
74/// - the most recent notification timestamp (+1) gives recency bias.
75fn score_notification(
76    category: &Option<String>,
77    is_ongoing: bool,
78    semantic_hints: &[SemanticHint],
79    is_most_recent: bool,
80) -> f32 {
81    let mut score = 0.0;
82    if is_ongoing {
83        score += 3.0;
84    }
85    for hint in semantic_hints {
86        match hint {
87            SemanticHint::FileMention
88            | SemanticHint::ImageMention
89            | SemanticHint::LinkAttachment => score += 2.0,
90            SemanticHint::UserMentioned | SemanticHint::CalendarInvitation => score += 1.0,
91            _ => {},
92        }
93    }
94    if is_priority_category(category) {
95        score += 1.0;
96    }
97    if is_most_recent {
98        score += 1.0;
99    }
100    score
101}
102
103/// Sort by score descending, then by most recent timestamp descending,
104/// and finally by package name ascending for determinism.
105fn rank_by_priority(
106    mut scored: Vec<ScoredPrediction>,
107    latest_ts: &HashMap<String, i64>,
108) -> Vec<ScoredPrediction> {
109    scored.sort_by(|a, b| {
110        cmp_score_desc(a, b)
111            .then_with(|| {
112                let ta = latest_ts.get(&a.package).copied().unwrap_or(i64::MIN);
113                let tb = latest_ts.get(&b.package).copied().unwrap_or(i64::MIN);
114                tb.cmp(&ta)
115            })
116            .then_with(|| a.package.cmp(&b.package))
117    });
118    scored
119}
120
121impl NextAppPredictor for NotificationPriorityBackend {
122    fn name(&self) -> &'static str {
123        "notification_priority"
124    }
125
126    fn predict(
127        &self,
128        ctx: &aios_spec::StructuredContext,
129        _current_app: &str,
130        candidates: &[String],
131    ) -> PredictionResult {
132        let start = Instant::now();
133
134        let notifications: Vec<&aios_spec::SanitizedEvent> = ctx
135            .events
136            .iter()
137            .filter(|e| matches!(e.event_type, SanitizedEventType::Notification { .. }))
138            .collect();
139
140        if notifications.is_empty() {
141            return PredictionResult {
142                ranked: Vec::new(),
143                latency_us: start.elapsed().as_micros() as u64,
144                rationale_present: false,
145            };
146        }
147
148        let candidate_set: HashSet<String> = candidates.iter().cloned().collect();
149        let max_ts = notifications
150            .iter()
151            .map(|e| e.timestamp_ms)
152            .max()
153            .expect("notifications are non-empty");
154
155        let mut scores: HashMap<String, f32> = HashMap::new();
156        let mut latest_ts: HashMap<String, i64> = HashMap::new();
157
158        for event in &notifications {
159            if let SanitizedEventType::Notification {
160                source_package,
161                category,
162                is_ongoing,
163                semantic_hints,
164                ..
165            } = &event.event_type
166            {
167                if !candidate_set.contains(source_package) {
168                    continue;
169                }
170
171                latest_ts
172                    .entry(source_package.clone())
173                    .and_modify(|v| *v = (*v).max(event.timestamp_ms))
174                    .or_insert(event.timestamp_ms);
175
176                let delta = score_notification(
177                    category,
178                    *is_ongoing,
179                    semantic_hints,
180                    event.timestamp_ms == max_ts,
181                );
182                *scores.entry(source_package.clone()).or_insert(0.0) += delta;
183            }
184        }
185
186        if scores.is_empty() {
187            return PredictionResult {
188                ranked: Vec::new(),
189                latency_us: start.elapsed().as_micros() as u64,
190                rationale_present: false,
191            };
192        }
193
194        let scored: Vec<ScoredPrediction> = scores
195            .into_iter()
196            .map(|(package, score)| ScoredPrediction { package, score })
197            .collect();
198        let ranked = rank_by_priority(scored, &latest_ts);
199
200        PredictionResult {
201            ranked,
202            latency_us: start.elapsed().as_micros() as u64,
203            rationale_present: false,
204        }
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use aios_spec::{
211        ContextSummary, SanitizedEvent, SanitizedEventType, ScriptHint, SemanticHint, SourceTier,
212        StructuredContext, TextHint,
213    };
214
215    use super::*;
216
217    fn text_hint() -> TextHint {
218        TextHint {
219            length_chars: 0,
220            script: ScriptHint::Unknown,
221            is_emoji_only: false,
222        }
223    }
224
225    fn ctx_with_events(events: Vec<SanitizedEvent>) -> StructuredContext {
226        StructuredContext {
227            window_id: "w1".into(),
228            window_start_ms: 0,
229            window_end_ms: 10_000,
230            duration_secs: 10,
231            events,
232            summary: ContextSummary {
233                foreground_apps: vec![],
234                notified_apps: vec![],
235                all_semantic_hints: vec![],
236                file_activity: vec![],
237                latest_system_status: None,
238                source_tier: SourceTier::PublicApi,
239            },
240        }
241    }
242
243    fn notification_event(
244        timestamp_ms: i64,
245        source_package: &str,
246        category: Option<&str>,
247        is_ongoing: bool,
248        semantic_hints: Vec<SemanticHint>,
249    ) -> SanitizedEvent {
250        SanitizedEvent {
251            event_id: format!("n{timestamp_ms}"),
252            timestamp_ms,
253            event_type: SanitizedEventType::Notification {
254                source_package: source_package.into(),
255                category: category.map(Into::into),
256                channel_id: None,
257                title_hint: text_hint(),
258                text_hint: text_hint(),
259                semantic_hints,
260                is_ongoing,
261                group_key: None,
262            },
263            source_tier: SourceTier::PublicApi,
264            app_package: Some(source_package.into()),
265            uid: None,
266        }
267    }
268
269    #[test]
270    fn recent_notification_is_noop_for_empty_context() {
271        let backend = RecentNotificationBackend;
272        let result = backend.predict(&ctx_with_events(vec![]), "A", &["B".into(), "C".into()]);
273        assert!(result.ranked.is_empty());
274    }
275
276    #[test]
277    fn recent_notification_noop_when_source_not_in_candidates() {
278        let ctx = ctx_with_events(vec![notification_event(100, "B", None, false, vec![])]);
279        let backend = RecentNotificationBackend;
280        let result = backend.predict(&ctx, "A", &["C".into()]);
281        assert!(result.ranked.is_empty());
282    }
283
284    #[test]
285    fn recent_notification_picks_most_recent_in_candidates() {
286        let ctx = ctx_with_events(vec![
287            notification_event(100, "B", None, false, vec![]),
288            notification_event(200, "C", None, false, vec![]),
289        ]);
290        let backend = RecentNotificationBackend;
291        let result = backend.predict(&ctx, "A", &["B".into(), "C".into()]);
292        assert_eq!(result.ranked.len(), 1);
293        assert_eq!(result.ranked[0].package, "C");
294        assert_eq!(result.ranked[0].score, 1.0);
295    }
296
297    #[test]
298    fn recent_notification_tie_breaks_alphabetically() {
299        let ctx = ctx_with_events(vec![
300            notification_event(100, "B", None, false, vec![]),
301            notification_event(100, "A", None, false, vec![]),
302        ]);
303        let backend = RecentNotificationBackend;
304        let result = backend.predict(&ctx, "Z", &["A".into(), "B".into()]);
305        assert_eq!(result.ranked[0].package, "A");
306    }
307
308    #[test]
309    fn notification_priority_is_noop_without_notifications() {
310        let backend = NotificationPriorityBackend;
311        let result = backend.predict(&ctx_with_events(vec![]), "A", &["B".into()]);
312        assert!(result.ranked.is_empty());
313    }
314
315    #[test]
316    fn notification_priority_is_noop_when_no_candidates_match() {
317        let ctx = ctx_with_events(vec![notification_event(100, "B", None, false, vec![])]);
318        let backend = NotificationPriorityBackend;
319        let result = backend.predict(&ctx, "A", &["C".into()]);
320        assert!(result.ranked.is_empty());
321    }
322
323    #[test]
324    fn notification_priority_applies_weights_and_ranks() {
325        let ctx = ctx_with_events(vec![
326            // A: file mention = 2 points.
327            notification_event(100, "A", None, false, vec![SemanticHint::FileMention]),
328            // B: ongoing + alarm + user mention + most recent = 3 + 1 + 1 + 1 = 6.
329            notification_event(
330                200,
331                "B",
332                Some("alarm"),
333                true,
334                vec![SemanticHint::UserMentioned],
335            ),
336        ]);
337        let backend = NotificationPriorityBackend;
338        let result = backend.predict(&ctx, "Z", &["A".into(), "B".into()]);
339        assert_eq!(result.ranked.len(), 2);
340        assert_eq!(result.ranked[0].package, "B");
341        assert_eq!(result.ranked[0].score, 6.0);
342        assert_eq!(result.ranked[1].package, "A");
343        assert_eq!(result.ranked[1].score, 2.0);
344    }
345
346    #[test]
347    fn notification_priority_tie_breaks_by_timestamp_then_name() {
348        // A and B end with the same total score (5), but A is more recent.
349        let ctx = ctx_with_events(vec![
350            notification_event(100, "B", None, true, vec![SemanticHint::ImageMention]), // 3+2 = 5
351            notification_event(200, "A", None, true, vec![SemanticHint::UserMentioned]), // 3+1+1(most recent) = 5
352        ]);
353        let backend = NotificationPriorityBackend;
354        let result = backend.predict(&ctx, "Z", &["A".into(), "B".into()]);
355        assert_eq!(result.ranked[0].package, "A");
356        assert_eq!(result.ranked[1].package, "B");
357
358        // Same score and timestamp: alphabetical tie-break.
359        let ctx_tied = ctx_with_events(vec![
360            notification_event(100, "B", None, true, vec![SemanticHint::UserMentioned]), // 3+1+1(most recent) = 5
361            notification_event(100, "A", None, true, vec![SemanticHint::UserMentioned]), // 3+1+1(most recent) = 5
362        ]);
363        let result_tied = backend.predict(&ctx_tied, "Z", &["A".into(), "B".into()]);
364        assert_eq!(result_tied.ranked[0].package, "A");
365        assert_eq!(result_tied.ranked[1].package, "B");
366    }
367
368    #[test]
369    fn is_priority_category_is_case_insensitive() {
370        assert!(is_priority_category(&Some("Alarm".into())));
371        assert!(is_priority_category(&Some("CALL".into())));
372        assert!(is_priority_category(&Some("event".into())));
373        assert!(!is_priority_category(&Some("msg".into())));
374        assert!(!is_priority_category(&None));
375    }
376}