tilo-notify 0.5.0

User notifications on Linux, macOS and the web: what an app shows its session over its connection, and what each platform keeps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! The notification service an app's session serves it: an app shows, replaces, withdraws and
//! schedules notifications over the connection its launcher opened for it, and what the person
//! does with one comes back on the same connection.
//!
//! An app runs in a process with no bus of its own, so the session is where notifications go: it
//! pushes them into the one notifications daemon every app's and the desktop's own notices reach,
//! attributed to the app the connection was opened for ([`crate::service::FD_ENV`]). The wire is
//! one length-prefixed JSON message per frame, the framing every socket in the tree uses: the app
//! sends [`Request`]s, each naming an id, and the session answers the id with an [`Answer`]; what
//! a notification's actions and dismissals mean for the app arrive as [`Request::Activated`]'s
//! counterpart, [`Message::Activated`] and [`Message::Closed`].
//!
//! [`NotifySide`] is whatever answers on the session's end: the session's notifications service.
//! [`ServiceNotifier`] is the app's end, and the [`Notifier`] a Rust app's process uses when its
//! launcher hands it a connection.

use std::collections::HashMap;
use std::io::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tilo_socket::Stream;
use wire_frame::Framing;

use crate::{
    AlarmSchedule, AlarmState, CalendarAlarm, CloseReason, Feature, Notification, Notifier,
    NotifyError, PriorityContact, Scheduled, SystemTime, Unsupported,
};

/// The descriptor the launcher hands an app it starts: the app's end of the connection served
/// here.
pub const FD_ENV: &str = "TILO_SVC_NOTIFY_FD";

/// One message: its JSON, behind the length prefix.
const FRAME: Framing = Framing::little_endian(1024 * 1024);

/// How long a call waits for the session's answer: the session pushes into the notifications
/// daemon, which never asks the person, so an answer that does not come is a failure rather than
/// a hang.
const WAIT: Duration = Duration::from_secs(30);

/// An alarm as an app hands it over: its local wall-clock time, when the person turned it on, and
/// the date it last rang, which the session reads as `YYYY-MM-DD`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlarmRequest {
    pub hour: u8,
    pub minute: u8,
    /// Monday is bit zero; none rings once.
    pub weekdays: u8,
    pub enabled_at_ms: i64,
    pub last_rung: Option<String>,
}

impl AlarmRequest {
    /// The request an app's [`AlarmSchedule`] makes; `None` when its delivered date is not one
    /// the session reads.
    #[must_use]
    pub fn of(schedule: &AlarmSchedule) -> Option<Self> {
        Some(Self {
            hour: schedule.alarm.hour,
            minute: schedule.alarm.minute,
            weekdays: schedule.alarm.weekdays,
            enabled_at_ms: schedule.enabled_at_ms,
            last_rung: schedule
                .last_rung
                .map(|date| date.to_string())
                .filter(|date| !date.is_empty()),
        })
    }

    /// This request as an app's own [`AlarmSchedule`].
    #[must_use]
    pub fn schedule(&self) -> AlarmSchedule {
        AlarmSchedule {
            alarm: CalendarAlarm {
                hour: self.hour,
                minute: self.minute,
                weekdays: self.weekdays,
            },
            enabled_at_ms: self.enabled_at_ms,
            last_rung: self
                .last_rung
                .as_deref()
                .and_then(|date| jiff::civil::Date::strptime("%Y-%m-%d", date).ok()),
        }
    }
}

/// One call an app makes. Each names an `id` its [`Answer`] comes back under; the id is the
/// app's own and means nothing to the session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Request {
    Show {
        id: u64,
        notification: Notification,
    },
    Withdraw {
        id: u64,
        tag: String,
    },
    Schedule {
        id: u64,
        notification: Notification,
        at: SystemTime,
    },
    ScheduleAlarm {
        id: u64,
        notification: Notification,
        at: SystemTime,
        alarm: AlarmRequest,
    },
    Scheduled {
        id: u64,
    },
    AlarmStates {
        id: u64,
    },
    CancelScheduled {
        id: u64,
        tag: String,
    },
    /// Replace the people whose messages break through focus and Do Not Disturb with the ones
    /// this app knows of.
    PriorityContacts {
        id: u64,
        contacts: Vec<PriorityContact>,
    },
}

impl Request {
    /// The call's id, which its answer names.
    #[must_use]
    pub const fn id(&self) -> u64 {
        match self {
            Self::Show { id, .. }
            | Self::Withdraw { id, .. }
            | Self::Schedule { id, .. }
            | Self::ScheduleAlarm { id, .. }
            | Self::Scheduled { id }
            | Self::AlarmStates { id }
            | Self::CancelScheduled { id, .. }
            | Self::PriorityContacts { id, .. } => *id,
        }
    }
}

/// One alarm as the session reports it: its state and what it rang.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlarmStateWire {
    pub tag: String,
    pub alarm: AlarmRequest,
    pub next_at: Option<SystemTime>,
    pub last_at: Option<SystemTime>,
}

impl AlarmStateWire {
    /// The state an [`AlarmState`] reports.
    #[must_use]
    pub fn of(state: &AlarmState) -> Self {
        Self {
            tag: state.tag.clone(),
            alarm: AlarmRequest {
                hour: state.alarm.hour,
                minute: state.alarm.minute,
                weekdays: state.alarm.weekdays,
                enabled_at_ms: state.enabled_at_ms,
                last_rung: state.last_rung.map(|date| date.to_string()),
            },
            next_at: state.next_at,
            last_at: state.last_at,
        }
    }

    /// This wire state as an [`AlarmState`].
    #[must_use]
    pub fn state(&self) -> AlarmState {
        AlarmState {
            tag: self.tag.clone(),
            alarm: self.alarm.schedule().alarm,
            enabled_at_ms: self.alarm.enabled_at_ms,
            next_at: self.next_at,
            last_at: self.last_at,
            last_rung: self
                .alarm
                .last_rung
                .as_deref()
                .and_then(|date| jiff::civil::Date::strptime("%Y-%m-%d", date).ok()),
        }
    }
}

/// What the session answered a call with.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Answer {
    Done,
    Scheduled(Vec<Scheduled>),
    Alarms(Vec<AlarmStateWire>),
    /// The session would not do it, and why.
    Refused(Refusal),
}

/// Why the session refused a call.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Refusal {
    /// This host cannot do it: scheduling, the one feature the session may lack.
    Unsupported,
    Invalid(String),
    Failed(String),
    /// This connection reaches no notification service.
    Unavailable,
}

impl Refusal {
    /// The refusal as the error an app's [`Notifier`] reports.
    #[must_use]
    pub fn error(&self) -> NotifyError {
        match self {
            Self::Unsupported => NotifyError::Unsupported(Unsupported::of(Feature::Schedule)),
            Self::Invalid(reason) | Self::Failed(reason) => NotifyError::Failed(reason.clone()),
            Self::Unavailable => NotifyError::Unavailable,
        }
    }
}

/// One message on its way to the app: the answer to a call, and what the person did with a
/// notification the app showed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Message {
    Answer {
        id: u64,
        answer: Answer,
    },
    /// The person chose the notification, or one of its buttons: the URI it was shown with.
    Activated {
        uri: String,
    },
    /// The notification is gone, and why: the person dismissed it, it expired, or it was closed.
    Closed {
        tag: String,
        reason: CloseReason,
    },
}

/// What answers on the session's end of an app's notification connection: the session's
/// notifications daemon, attributed to the app the connection is for.
pub trait NotifySide: Send + Sync {
    /// The side of this connection that tells the app what happened to its notifications, before
    /// the first request. The connection closes with the app, and so does the side.
    fn attached(&self, channel: Arc<Channel>) {
        drop(channel);
    }

    /// Show `notification`, or replace the app's notification with its tag.
    fn show(&self, notification: &Notification) -> Result<(), Refusal>;

    /// Withdraw the app's notification with `tag`.
    fn withdraw(&self, tag: &str) -> Result<(), Refusal>;

    /// Hand `notification` over for `at`, with `alarm` for one that rings at a wall-clock time.
    fn schedule(
        &self,
        notification: &Notification,
        at: SystemTime,
        alarm: Option<&AlarmRequest>,
    ) -> Result<(), Refusal>;

    /// The app's deadlines still to fall due.
    fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal>;

    /// The app's alarms, and what the session delivered of them.
    fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal>;

    /// Cancel the app's deadline with `tag`.
    fn cancel_scheduled(&self, tag: &str) -> Result<(), Refusal>;

    /// Replace the people whose messages may break through focus and Do Not Disturb with
    /// `contacts`, as this app knows them.
    /// A side that keeps no priority contacts.
    fn priority_contacts(&self, _contacts: &[PriorityContact]) -> Result<(), Refusal> {
        Err(Refusal::Unsupported)
    }
}

/// The session's end of one app's connection, for what the person did with its notifications.
pub struct Channel {
    writer: Mutex<Stream>,
}

impl Channel {
    /// The person chose a notification: `uri` is what the app showed it with.
    pub fn activated(&self, uri: &str) {
        self.send(&Message::Activated {
            uri: uri.to_owned(),
        });
    }

    /// The app's notification with `tag` is gone, for `reason`.
    pub fn closed(&self, tag: &str, reason: CloseReason) {
        self.send(&Message::Closed {
            tag: tag.to_owned(),
            reason,
        });
    }

    fn answer(&self, id: u64, answer: Answer) {
        self.send(&Message::Answer { id, answer });
    }

    fn send(&self, message: &Message) {
        let Ok(bytes) = serde_json::to_vec(message) else {
            return;
        };
        let Ok(mut writer) = self.writer.lock() else {
            return;
        };
        if FRAME.write(&mut *writer, &bytes).is_ok() {
            let _ = writer.flush();
        }
    }
}

/// Serve an app's notification calls on `stream` until it closes the connection.
pub fn serve(stream: Stream, side: &dyn NotifySide) {
    let Ok(writer) = stream.try_clone() else {
        return;
    };
    let channel = Arc::new(Channel {
        writer: Mutex::new(writer),
    });
    side.attached(Arc::clone(&channel));
    let mut reader = stream;
    while let Ok(Some(frame)) = FRAME.read(&mut reader) {
        let Ok(request) = serde_json::from_slice::<Request>(&frame) else {
            return;
        };
        let id = request.id();
        channel.answer(id, answer(side, request));
    }
}

/// What `side` answers `request` with.
fn answer(side: &dyn NotifySide, request: Request) -> Answer {
    let done = match request {
        Request::Show { notification, .. } => crate::validate(&notification)
            .map_err(refused)
            .and_then(|()| side.show(&notification)),
        Request::Withdraw { tag, .. } => crate::validate_tag(&tag)
            .map_err(refused)
            .and_then(|()| side.withdraw(&tag)),
        Request::Schedule {
            notification, at, ..
        } => crate::validate(&notification)
            .map_err(refused)
            .and_then(|()| side.schedule(&notification, at, None)),
        Request::ScheduleAlarm {
            notification,
            at,
            alarm,
            ..
        } => crate::validate(&notification)
            .map_err(refused)
            .and_then(|()| side.schedule(&notification, at, Some(&alarm))),
        Request::Scheduled { .. } => {
            return match side.scheduled() {
                Ok(rows) => Answer::Scheduled(rows),
                Err(refusal) => Answer::Refused(refusal),
            };
        }
        Request::AlarmStates { .. } => {
            return match side.alarm_states() {
                Ok(states) => Answer::Alarms(states.iter().map(AlarmStateWire::of).collect()),
                Err(refusal) => Answer::Refused(refusal),
            };
        }
        Request::CancelScheduled { tag, .. } => crate::validate_tag(&tag)
            .map_err(refused)
            .and_then(|()| side.cancel_scheduled(&tag)),
        Request::PriorityContacts { contacts, .. } => side.priority_contacts(&contacts),
    };
    match done {
        Ok(()) => Answer::Done,
        Err(refusal) => Answer::Refused(refusal),
    }
}

/// A malformed request, as the refusal an app is told.
fn refused(error: NotifyError) -> Refusal {
    match error {
        NotifyError::Invalid(reason) => Refusal::Invalid(reason.to_owned()),
        NotifyError::Unsupported(_) => Refusal::Unsupported,
        NotifyError::Failed(reason) => Refusal::Failed(reason),
        NotifyError::Unavailable => Refusal::Unavailable,
    }
}

/// This process's connection to its session's notification service, taken once: what the system
/// notifier and an app's priority contacts both use. `None` when the launcher handed none, or it
/// is already closed.
fn inherited() -> Option<&'static Arc<Connection>> {
    static INHERITED: std::sync::OnceLock<Option<Arc<Connection>>> = std::sync::OnceLock::new();
    INHERITED
        .get_or_init(|| {
            let fd = std::env::var(FD_ENV).ok()?.parse::<i32>().ok()?;
            if fd < 0 {
                return None;
            }
            // SAFETY: the launcher passes this descriptor to this process, and it is this
            // process's from here: nothing else in the app holds the number.
            let stream = Stream::from(unsafe {
                <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd)
            });
            Connection::start(stream)
        })
        .as_ref()
}

/// Whether the launcher handed this process a notification service.
#[must_use]
pub fn inherited_service() -> bool {
    inherited().is_some()
}

/// Replace the people whose messages may break through focus and Do Not Disturb with `contacts`,
/// as this app knows them, over the connection its session opened for it.
///
/// # Errors
/// This process was handed no notification service, or the session refused the list.
pub fn publish_priority_contacts(contacts: &[PriorityContact]) -> Result<(), NotifyError> {
    let Some(connection) = inherited() else {
        return Err(NotifyError::Unavailable);
    };
    let notifier = ServiceNotifier {
        connection: Arc::clone(connection),
    };
    let contacts = contacts.to_vec();
    ServiceNotifier::did(notifier.ask(move |id| Request::PriorityContacts { id, contacts })?)
}

/// An app's end of its notification connection: a Rust app's [`Notifier`], the same service a
/// tilolang instance reaches.
pub struct ServiceNotifier {
    connection: Arc<Connection>,
}

struct Connection {
    writer: Mutex<Stream>,
    /// The calls waiting for their answers, by the id they named.
    waiting: Mutex<HashMap<u64, Sender<Answer>>>,
    next: AtomicU64,
}

impl ServiceNotifier {
    /// The notifier over the connection the launcher opened for this app, named by [`FD_ENV`];
    /// `None` when this process was handed none.
    #[must_use]
    pub fn from_env() -> Option<Self> {
        Some(Self {
            connection: Arc::clone(inherited()?),
        })
    }

    /// The notifier over `stream`, the connection the session opened for the app; `None` when it
    /// cannot be read and written beside this end.
    #[must_use]
    pub fn connect(stream: Stream) -> Option<Self> {
        Some(Self {
            connection: Connection::start(stream)?,
        })
    }

    /// Ask the session `request`, built with the id it answers under.
    fn ask(&self, request: impl FnOnce(u64) -> Request) -> Result<Answer, NotifyError> {
        let id = self.connection.next.fetch_add(1, Ordering::Relaxed);
        let (reply, answer) = mpsc::channel();
        self.connection
            .waiting
            .lock()
            .map_err(|_| NotifyError::Unavailable)?
            .insert(id, reply);
        let sent = serde_json::to_vec(&request(id)).ok().and_then(|bytes| {
            let mut writer = self.connection.writer.lock().ok()?;
            FRAME.write(&mut *writer, &bytes).ok()?;
            writer.flush().ok()
        });
        if sent.is_none() {
            if let Ok(mut waiting) = self.connection.waiting.lock() {
                waiting.remove(&id);
            }
            return Err(NotifyError::Unavailable);
        }
        answer.recv_timeout(WAIT).map_err(|_| {
            if let Ok(mut waiting) = self.connection.waiting.lock() {
                waiting.remove(&id);
            }
            NotifyError::Failed("the notification service did not answer".into())
        })
    }

    /// `answer` as a result of doing it, or the refusal.
    fn did(answer: Answer) -> Result<(), NotifyError> {
        match answer {
            Answer::Done => Ok(()),
            Answer::Refused(refusal) => Err(refusal.error()),
            Answer::Scheduled(_) | Answer::Alarms(_) => Err(NotifyError::Failed(
                "the notification service answered the wrong call".into(),
            )),
        }
    }
}

impl Connection {
    /// The connection over `stream`, with the thread that takes what the session says on it.
    fn start(stream: Stream) -> Option<Arc<Self>> {
        let reader = stream.try_clone().ok()?;
        let connection = Arc::new(Self {
            writer: Mutex::new(stream),
            waiting: Mutex::default(),
            next: AtomicU64::new(1),
        });
        let following = Arc::clone(&connection);
        std::thread::Builder::new()
            .name("tilo-notify-service".into())
            .spawn(move || following.listen(reader))
            .ok()?;
        Some(connection)
    }

    /// Take the session's answers and what happened to the app's notifications, until the
    /// connection closes.
    fn listen(&self, mut reader: Stream) {
        while let Ok(Some(frame)) = FRAME.read(&mut reader) {
            let Ok(message) = serde_json::from_slice::<Message>(&frame) else {
                return;
            };
            match message {
                Message::Answer { id, answer } => {
                    let waiting = self
                        .waiting
                        .lock()
                        .ok()
                        .and_then(|mut waiting| waiting.remove(&id));
                    if let Some(reply) = waiting {
                        let _ = reply.send(answer);
                    }
                }
                Message::Activated { uri } => crate::activated(&uri),
                Message::Closed { tag, reason } => crate::closed(&tag, reason),
            }
        }
    }
}

impl Notifier for ServiceNotifier {
    fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
        crate::validate(notification)?;
        let notification = notification.clone();
        Self::did(self.ask(move |id| Request::Show { id, notification })?)
    }

    fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
        crate::validate_tag(tag)?;
        let tag = tag.to_owned();
        Self::did(self.ask(move |id| Request::Withdraw { id, tag })?)
    }

    fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
        crate::validate(notification)?;
        let notification = notification.clone();
        Self::did(self.ask(move |id| Request::Schedule {
            id,
            notification,
            at,
        })?)
    }

    fn schedule_alarm(
        &self,
        notification: &Notification,
        at: SystemTime,
        schedule: AlarmSchedule,
    ) -> Result<(), NotifyError> {
        crate::validate(notification)?;
        if !schedule.alarm.valid() {
            return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
        }
        let alarm = AlarmRequest::of(&schedule)
            .ok_or(NotifyError::Invalid("invalid delivered alarm date"))?;
        let notification = notification.clone();
        Self::did(self.ask(move |id| Request::ScheduleAlarm {
            id,
            notification,
            at,
            alarm,
        })?)
    }

    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
        match self.ask(|id| Request::Scheduled { id })? {
            Answer::Scheduled(rows) => Ok(rows),
            Answer::Refused(refusal) => Err(refusal.error()),
            Answer::Done | Answer::Alarms(_) => Err(NotifyError::Failed(
                "the notification service answered the wrong call".into(),
            )),
        }
    }

    fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
        match self.ask(|id| Request::AlarmStates { id })? {
            Answer::Alarms(states) => Ok(states.iter().map(AlarmStateWire::state).collect()),
            Answer::Refused(refusal) => Err(refusal.error()),
            Answer::Done | Answer::Scheduled(_) => Err(NotifyError::Failed(
                "the notification service answered the wrong call".into(),
            )),
        }
    }

    fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
        crate::validate_tag(tag)?;
        let tag = tag.to_owned();
        Self::did(self.ask(move |id| Request::CancelScheduled { id, tag })?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{NotificationButton, NotificationSender, Severity};
    use std::sync::Mutex;

    #[derive(Default)]
    struct Recorded {
        shown: Vec<Notification>,
        withdrawn: Vec<String>,
        scheduled: Vec<(Notification, SystemTime, Option<AlarmRequest>)>,
        cancelled: Vec<String>,
        contacts: Vec<PriorityContact>,
        channel: Mutex<Option<Arc<Channel>>>,
    }

    struct Recording(Arc<Mutex<Recorded>>);

    impl NotifySide for Recording {
        fn attached(&self, channel: Arc<Channel>) {
            *self.0.lock().unwrap().channel.lock().unwrap() = Some(channel);
        }

        fn show(&self, notification: &Notification) -> Result<(), Refusal> {
            self.0.lock().unwrap().shown.push(notification.clone());
            Ok(())
        }

        fn withdraw(&self, tag: &str) -> Result<(), Refusal> {
            self.0.lock().unwrap().withdrawn.push(tag.to_owned());
            Ok(())
        }

        fn schedule(
            &self,
            notification: &Notification,
            at: SystemTime,
            alarm: Option<&AlarmRequest>,
        ) -> Result<(), Refusal> {
            self.0
                .lock()
                .unwrap()
                .scheduled
                .push((notification.clone(), at, alarm.cloned()));
            Ok(())
        }

        fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal> {
            Ok(self
                .0
                .lock()
                .unwrap()
                .scheduled
                .iter()
                .map(|(notification, at, _)| Scheduled {
                    tag: notification.tag.clone(),
                    at: *at,
                })
                .collect())
        }

        fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal> {
            Ok(self
                .0
                .lock()
                .unwrap()
                .scheduled
                .iter()
                .filter_map(|(notification, at, alarm)| {
                    let alarm = alarm.as_ref()?.schedule();
                    Some(AlarmState {
                        tag: notification.tag.clone(),
                        alarm: alarm.alarm,
                        enabled_at_ms: alarm.enabled_at_ms,
                        next_at: Some(*at),
                        last_at: None,
                        last_rung: alarm.last_rung,
                    })
                })
                .collect())
        }

        fn cancel_scheduled(&self, tag: &str) -> Result<(), Refusal> {
            self.0.lock().unwrap().cancelled.push(tag.to_owned());
            Ok(())
        }

        fn priority_contacts(&self, contacts: &[PriorityContact]) -> Result<(), Refusal> {
            self.0.lock().unwrap().contacts = contacts.to_vec();
            Ok(())
        }
    }

    /// A client over one end of a socket pair, with a recording side and a channel on the other.
    fn session() -> (ServiceNotifier, Arc<Mutex<Recorded>>) {
        let (app, service) = tilo_socket::pair().expect("a socket pair");
        let recorded = Arc::new(Mutex::new(Recorded::default()));
        let side = Arc::new(Recording(Arc::clone(&recorded)));
        std::thread::spawn(move || serve(service, &*side));
        let client = ServiceNotifier::connect(app).expect("the connection is usable");
        (client, recorded)
    }

    fn waiting(recorded: &Arc<Mutex<Recorded>>) -> Arc<Channel> {
        for _ in 0..1000 {
            let channel = { recorded.lock().unwrap().channel.lock().unwrap().clone() };
            if let Some(channel) = channel {
                return channel;
            }
            std::thread::yield_now();
        }
        panic!("the service never attached its channel");
    }

    #[test]
    fn an_app_shows_replaces_and_withdraws_its_notifications_over_its_connection() {
        let (client, recorded) = session();
        let shown = Notification::new("task", "Saved", "Your change is on every device")
            .with_activation("tilo-test:open")
            .with_button("Undo", "tilo-test:undo")
            .with_severity(Severity::Warning)
            .quietly();
        client.show(&shown).expect("the service took it");
        assert_eq!(recorded.lock().unwrap().shown, [shown]);
        client.withdraw("task").expect("the service withdrew it");
        assert_eq!(recorded.lock().unwrap().withdrawn, ["task"]);
    }

    #[test]
    fn a_malformed_notification_is_refused_before_it_reaches_the_session() {
        let (client, recorded) = session();
        assert!(matches!(
            client.show(&Notification::new("", "Title", "")),
            Err(NotifyError::Invalid(_))
        ));
        assert!(matches!(
            client.withdraw("t\nag"),
            Err(NotifyError::Invalid(_))
        ));
        assert!(
            recorded.lock().unwrap().shown.is_empty(),
            "nothing malformed reaches the service"
        );
    }

    #[test]
    fn what_the_person_chose_reaches_the_app_that_showed_it() {
        let (client, recorded) = session();
        let (seen, chosen) = std::sync::mpsc::channel();
        crate::set_activation_handler("tilo-service-test", move |uri| {
            let _ = seen.send(uri.to_owned());
        });
        client
            .show(&Notification::new("task", "Saved", "").with_activation("tilo-service-test:open"))
            .expect("the service took it");
        let channel = waiting(&recorded);
        channel.activated("tilo-service-test:open");
        assert_eq!(
            chosen.recv_timeout(Duration::from_secs(30)),
            Ok("tilo-service-test:open".to_owned())
        );
    }

    #[test]
    fn a_notification_that_goes_away_is_reported_under_its_tag_and_reason() {
        let (client, recorded) = session();
        let (gone, closings) = std::sync::mpsc::channel();
        crate::set_close_handler("tilo-service-close-test:", move |tag, reason| {
            let _ = gone.send((tag.to_owned(), reason));
        });
        client
            .show(&Notification::new("tilo-service-close-test:1", "Saved", ""))
            .expect("the service took it");
        let channel = waiting(&recorded);
        channel.closed("tilo-service-close-test:1", CloseReason::Dismissed);
        assert_eq!(
            closings.recv_timeout(Duration::from_secs(30)),
            Ok((
                "tilo-service-close-test:1".to_owned(),
                CloseReason::Dismissed
            ))
        );
    }

    #[test]
    fn an_alarm_is_scheduled_read_back_and_cancelled_over_the_connection() {
        let (client, recorded) = session();
        let notification = Notification::new("wake", "Wake up", "It is 7:00");
        let at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
        let alarm = AlarmSchedule {
            alarm: CalendarAlarm {
                hour: 7,
                minute: 0,
                weekdays: 0,
            },
            enabled_at_ms: 1_700_000_000_000,
            last_rung: Some(jiff::civil::date(2026, 11, 25)),
        };
        client
            .schedule_alarm(&notification, at, alarm)
            .expect("the service scheduled it");
        let scheduled = client.scheduled().expect("the deadlines");
        assert_eq!(
            scheduled,
            [Scheduled {
                tag: "wake".to_owned(),
                at
            }]
        );
        let states = client.alarm_states().expect("the alarms");
        assert_eq!(states.len(), 1, "{states:?}");
        assert_eq!(states[0].alarm, alarm.alarm);
        assert_eq!(states[0].enabled_at_ms, alarm.enabled_at_ms);
        assert_eq!(states[0].last_rung, alarm.last_rung);
        client
            .cancel_scheduled("wake")
            .expect("the service cancelled it");
        assert_eq!(recorded.lock().unwrap().cancelled, ["wake"]);
    }

    #[test]
    fn priority_contacts_go_over_the_connection_that_names_the_app() {
        let (client, recorded) = session();
        let contacts = vec![PriorityContact {
            id: "person-1".to_owned(),
            name: "Ada".to_owned(),
            endpoints: vec!["ada@example.com".to_owned()],
        }];
        client
            .ask(move |id| Request::PriorityContacts { id, contacts })
            .map(ServiceNotifier::did)
            .expect("the service answered")
            .expect("the service took them");
        assert_eq!(recorded.lock().unwrap().contacts.len(), 1);
        assert_eq!(recorded.lock().unwrap().contacts[0].id, "person-1");
    }

    #[test]
    fn a_refusal_is_the_error_the_app_reads() {
        struct Refusing;

        impl NotifySide for Refusing {
            fn show(&self, _notification: &Notification) -> Result<(), Refusal> {
                Err(Refusal::Failed("the notification centre is off".into()))
            }

            fn withdraw(&self, _tag: &str) -> Result<(), Refusal> {
                Err(Refusal::Unsupported)
            }

            fn schedule(
                &self,
                _notification: &Notification,
                _at: SystemTime,
                _alarm: Option<&AlarmRequest>,
            ) -> Result<(), Refusal> {
                Err(Refusal::Unsupported)
            }

            fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal> {
                Err(Refusal::Unsupported)
            }

            fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal> {
                Err(Refusal::Unsupported)
            }

            fn cancel_scheduled(&self, _tag: &str) -> Result<(), Refusal> {
                Err(Refusal::Unsupported)
            }
        }

        let (app, service) = tilo_socket::pair().expect("a socket pair");
        std::thread::spawn(move || {
            let side = Refusing;
            serve(service, &side);
        });
        let client = ServiceNotifier::connect(app).expect("the connection is usable");
        assert_eq!(
            client.show(&Notification::new("t", "Title", "")),
            Err(NotifyError::Failed("the notification centre is off".into()))
        );
        assert!(matches!(
            client.withdraw("t"),
            Err(NotifyError::Unsupported(_))
        ));
    }

    #[test]
    fn a_process_the_launcher_handed_no_service_is_refused() {
        let mut env = tilo_test_env::ScopedEnv::new();
        env.remove(FD_ENV);
        let notifier = crate::system(Some("so.tilo.notify-test"));
        assert_eq!(
            notifier.show(&Notification::new("t", "Title", "")),
            Err(NotifyError::Unavailable)
        );
        assert_eq!(notifier.withdraw("t"), Err(NotifyError::Unavailable));
    }

    #[test]
    fn every_notification_shape_survives_the_wire() {
        let notification = Notification {
            tag: "tag".into(),
            title: "Title".into(),
            body: "Body".into(),
            activation: Some("tilo-test:open".into()),
            action: Some("Open".into()),
            severity: Severity::Error,
            buttons: vec![NotificationButton {
                label: "Retry".into(),
                activation: "tilo-test:retry".into(),
            }],
            silent: true,
            app: Some("Files".into()),
            from: Some(NotificationSender {
                name: "Ada".into(),
                id: "person-1".into(),
                agent: false,
            }),
        };
        let request = Request::Show {
            id: 7,
            notification,
        };
        let bytes = serde_json::to_vec(&request).expect("the request");
        assert_eq!(
            serde_json::from_slice::<Request>(&bytes).expect("the request"),
            request
        );
    }
}