faculties 0.21.0

An office suite for AI agents: kanban, wiki, files, messaging, and a Lissajous-backed viewer — all persisted in a TribleSpace pile.
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! Read-only GORBIE-embeddable message panel.
//!
//! Renders the canonical immutable envelopes in a Message collection as a
//! chronological feed: oldest at the top,
//! newest at the bottom. Each message lays out as a sharp-cornered
//! paper-card bubble — sender + recipient chips, body text (with
//! search-match underlines when a notebook-wide search is active),
//! optional read receipts, and a short id footer.
//!
//! The widget holds UI + cached-query state only; the host supplies
//! the message dataset (required) and an optional `relations`
//! dataset at render time.
//!
//! Identity display is resolved against the Relations collection (if
//! supplied): `alias → first_name last_name → display_name → 8-char
//! hex prefix`. If relations is absent the widget quietly degrades to
//! the hex-prefix view. Per-person color chips use
//! `GORBIE::themes::colorhash::ral_categorical` keyed on the user id
//! bytes.
//!
//! ```ignore
//! let mut panel = MessagesPanel::default();
//! panel.render(ctx, messages_view, Some(relations_view));
//! ```

use std::collections::HashMap;

use triblespace::core::id::Id;
use triblespace::core::metadata;
use triblespace::macros::{find, pattern};
use triblespace::prelude::TryFromInline;
use GORBIE::prelude::CardCtx;
use GORBIE::themes::colorhash;

use crate::message as message_model;
use crate::message::operations::{envelope_id, inbox, read_by, settled_identity};
use crate::relations::{self, Head, ProfileInput, ProfileView};
use crate::schemas::message::{local as message_attrs, KIND_MESSAGE_ID, KIND_READ_ID};
use crate::widgets::storage::{DatasetRevision, DatasetView};

// ── ID / time helpers ────────────────────────────────────────────────

/// Full hex of an Id — used as a fallback label when no friendly name
/// is resolvable from the relations branch.
fn id_hex(id: Id) -> String {
    format!("{id:x}")
}

/// The lower bound of a stored interval, for ordering only.
fn interval_start(interval: message_model::IntervalValue) -> Option<i128> {
    interval
        .try_from_inline::<(i128, i128)>()
        .ok()
        .map(|(start, _)| start)
}

fn now_tai_ns() -> Option<i128> {
    crate::clock::tai_nanoseconds_now().ok()
}

fn format_age(now_key: Option<i128>, maybe_key: Option<i128>) -> String {
    let Some(key) = maybe_key else {
        return "-".to_string();
    };
    let Some(now_key) = now_key else {
        return "unknown".to_string();
    };
    let delta_ns = now_key.saturating_sub(key);
    let delta_s = (delta_ns / 1_000_000_000).max(0) as i64;
    if delta_s < 60 {
        format!("{delta_s}s")
    } else if delta_s < 60 * 60 {
        format!("{}m", delta_s / 60)
    } else if delta_s < 24 * 60 * 60 {
        format!("{}h", delta_s / 3600)
    } else {
        format!("{}d", delta_s / 86_400)
    }
}

fn format_age_key(now_key: Option<i128>, past_key: i128) -> String {
    format_age(now_key, Some(past_key))
}

/// Absolute timestamp from a TAI ns key. Used for hover tooltips so the
/// compact age chips can still surface precise times on demand.
fn format_timestamp_key(key: i128) -> String {
    let ns = hifitime::Duration::from_total_nanoseconds(key);
    let epoch = hifitime::Epoch::from_tai_duration(ns);
    let (y, m, d, h, min, s, _) = epoch.to_gregorian_utc();
    format!("{y:04}-{m:02}-{d:02} {h:02}:{min:02}:{s:02} UTC")
}

// ── Color palette (reuses compass.rs conventions) ────────────────────

// Theme-adaptive neutrals (mirror of compass.rs). The accent /
// read / person colors are legible on both themes, but the
// frame / bubble / muted greys need to flip so theme-aware text
// doesn't land dark-on-dark in light mode.

fn color_frame(ui: &egui::Ui) -> egui::Color32 {
    if ui.visuals().dark_mode {
        egui::Color32::from_rgb(0x29, 0x32, 0x36) // RAL 7016
    } else {
        egui::Color32::from_rgb(0xec, 0xec, 0xec)
    }
}

fn color_muted(ui: &egui::Ui) -> egui::Color32 {
    if ui.visuals().dark_mode {
        egui::Color32::from_rgb(0x9a, 0x9a, 0x9a)
    } else {
        egui::Color32::from_rgb(0x6a, 0x6a, 0x6a)
    }
}

fn color_read() -> egui::Color32 {
    // RAL 6017 may green — "read" accent, matches playground diagnostics.
    egui::Color32::from_rgb(0x4a, 0x77, 0x29)
}

/// Deterministic per-person color chip via GORBIE's colorhash palette.
fn person_color(id: Id) -> egui::Color32 {
    colorhash::ral_categorical(id.as_ref())
}

// ── Row structs ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
struct MessageRow {
    id: Id,
    from: Id,
    to: Id,
    body: String,
    /// TAI ns of the message's `metadata::created_at` (sort key).
    created_at: Option<i128>,
    /// Canonical read markers and every additive observation attached to them.
    reads: Vec<ReadReceipt>,
    /// At least one current operator is a canonical inbox recipient.
    is_inbox: bool,
    /// At least one eligible operator has no equivalent canonical read marker.
    is_unread: bool,
}

impl MessageRow {
    fn sort_key(&self) -> i128 {
        self.created_at.unwrap_or(i128::MIN)
    }
}

#[derive(Clone, Debug)]
struct ReadReceipt {
    reader: Id,
    observations: Vec<i128>,
}

/// Everything we know about a person for UI purposes.
#[derive(Clone, Debug, Default)]
struct Person {
    alias: Option<String>,
    first_name: Option<String>,
    last_name: Option<String>,
    display_name: Option<String>,
    /// True when the relations entry carries the `operator` affinity —
    /// i.e. this is a human the agents work for, not another agent.
    /// Messages addressed to an operator form the "inbox" subset.
    is_operator: bool,
}

impl Person {
    fn from_profile(profile: ProfileInput) -> Self {
        Self {
            alias: Some(profile.label),
            first_name: profile.first_name,
            last_name: profile.last_name,
            display_name: profile.display_name,
            is_operator: profile
                .affinities
                .iter()
                .any(|affinity| affinity.eq_ignore_ascii_case("operator")),
        }
    }

    /// Display name: alias > first+last > display_name > hex prefix.
    fn display(&self, fallback_id: Id) -> String {
        if let Some(a) = self.alias.as_ref() {
            if !a.trim().is_empty() {
                return a.clone();
            }
        }
        match (self.first_name.as_ref(), self.last_name.as_ref()) {
            (Some(f), Some(l)) if !f.trim().is_empty() && !l.trim().is_empty() => {
                return format!("{f} {l}");
            }
            (Some(f), _) if !f.trim().is_empty() => return f.clone(),
            (_, Some(l)) if !l.trim().is_empty() => return l.clone(),
            _ => {}
        }
        if let Some(d) = self.display_name.as_ref() {
            if !d.trim().is_empty() {
                return d.clone();
            }
        }
        id_hex(fallback_id)
    }
}

// ── Cached message query state ───────────────────────────────────────

/// Cached canonical projections + revision markers + resolved people map.
/// Rebuilt whenever the Message or Relations dataset revision changes.
struct MessagesLive {
    cached_revision: DatasetRevision,
    relations_cached_revision: Option<DatasetRevision>,
    people: HashMap<Id, Person>,
    messages: Vec<MessageRow>,
    diagnostics: Vec<String>,
}

impl MessagesLive {
    /// Refresh canonical Message/Relations projections from the provided
    /// dataset views.
    fn refresh(view: DatasetView<'_>, relations: Option<DatasetView<'_>>) -> Self {
        let (relations_cached_revision, people, mut diagnostics) = match relations {
            Some(relations) => {
                let (people, diagnostics) = build_people(relations);
                (Some(relations.revision), people, diagnostics)
            }
            None => (None, HashMap::new(), Vec::new()),
        };
        let (messages, message_diagnostics) = collect_messages(view, relations, &people);
        diagnostics.extend(message_diagnostics);

        MessagesLive {
            cached_revision: view.revision,
            relations_cached_revision,
            people,
            messages,
            diagnostics,
        }
    }

    /// Friendly display name for an Id, falling back to hex prefix.
    fn display_name(&self, id: Id) -> String {
        match self.people.get(&id) {
            Some(p) => p.display(id),
            None => id_hex(id),
        }
    }
}

fn build_people(relations_view: DatasetView<'_>) -> (HashMap<Id, Person>, Vec<String>) {
    let mut people = HashMap::new();
    let mut diagnostics = Vec::new();
    for (person, view) in
        relations::person_profile_views(relations_view.reader, relations_view.facts)
    {
        match view {
            ProfileView::Current { value, .. } => {
                people.insert(person, Person::from_profile(value));
            }
            ProfileView::Forked(heads) => diagnostics.push(format!(
                "Relations profile {person:x} is forked across {}",
                heads
                    .iter()
                    .map(|id| format!("{id:x}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )),
            ProfileView::Invalid(error) => {
                diagnostics.push(format!("Relations profile {person:x} is invalid: {error}"));
            }
        }

        match relations::lifecycle_head(relations_view.facts, person) {
            Ok(Head::Unique(snapshot)) => {
                if let Err(error) = relations::lifecycle_snapshot(relations_view.facts, snapshot) {
                    diagnostics.push(format!(
                        "Relations lifecycle {person:x} is invalid: {error}"
                    ));
                }
            }
            Ok(Head::Forked(heads)) => diagnostics.push(format!(
                "Relations lifecycle {person:x} is forked across {}",
                heads
                    .iter()
                    .map(|id| format!("{id:x}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )),
            Ok(Head::Missing) => diagnostics.push(format!(
                "Relations person {person:x} has no lifecycle snapshot"
            )),
            Err(error) => diagnostics.push(format!(
                "Relations lifecycle {person:x} is invalid: {error}"
            )),
        }
    }
    (people, diagnostics)
}

fn collect_messages(
    view: DatasetView<'_>,
    relations_view: Option<DatasetView<'_>>,
    people: &HashMap<Id, Person>,
) -> (Vec<MessageRow>, Vec<String>) {
    let mut diagnostics = Vec::new();

    // Every envelope this view answers with, and only the columns the panel
    // draws. An entity carrying fields the panel does not model still shows;
    // one missing a field it draws simply does not.
    let mut envelopes: Vec<(
        Id,
        Id,
        Id,
        message_model::TextHandle,
        message_model::IntervalValue,
    )> = find!(
        (
            id: Id,
            from: Id,
            to: Id,
            body: message_model::TextHandle,
            created_at: message_model::IntervalValue
        ),
        pattern!(view.facts, [{ ?id @
            metadata::tag: &KIND_MESSAGE_ID,
            message_attrs::from: ?from,
            message_attrs::to: ?to,
            message_attrs::body: ?body,
            metadata::created_at: ?created_at,
        }])
    )
    .collect();

    // One row per envelope, newest witness first, so a repeated field cannot
    // make the panel show one message twice or mix two witnesses' fields.
    envelopes.sort_by(|left, right| {
        left.0
            .cmp(&right.0)
            .then_with(|| interval_start(right.4).cmp(&interval_start(left.4)))
    });
    envelopes.dedup_by_key(|envelope| envelope.0);

    let mut messages: HashMap<Id, MessageRow> = HashMap::new();
    for (id, from, to, body, created_at) in &envelopes {
        let text = match message_model::read_body(view.reader, *body) {
            Ok(text) => text,
            Err(error) => {
                diagnostics.push(format!("Message {id:x} body is unavailable: {error}"));
                "⚠ body unavailable".to_owned()
            }
        };
        let created_at = match created_at.try_from_inline::<(i128, i128)>() {
            Ok((start, _)) => Some(start),
            Err(error) => {
                diagnostics.push(format!(
                    "Message {id:x} has an invalid creation interval: {error:?}"
                ));
                None
            }
        };
        messages.entry(*id).or_insert_with(|| MessageRow {
            id: *id,
            from: *from,
            to: *to,
            body: text,
            created_at,
            reads: Vec::new(),
            is_inbox: false,
            is_unread: false,
        });
    }

    // Canonical `(message, reader)` markers, with every additive observation
    // attached to them. Observations are a set, never a scalar winner.
    let markers: Vec<(Id, Id, Id)> = find!(
        (marker: Id, message: Id, reader: Id),
        pattern!(view.facts, [{ ?marker @
            metadata::tag: &KIND_READ_ID,
            message_attrs::about_message: ?message,
            message_attrs::reader: ?reader,
        }])
    )
    .collect();

    for &(marker, message, reader) in &markers {
        let mut observations: Vec<i128> = find!(
            at: message_model::IntervalValue,
            pattern!(view.facts, [{ marker @ message_attrs::read_at: ?at }])
        )
        .filter_map(|at| match at.try_from_inline::<(i128, i128)>() {
            Ok((start, _)) => Some(start),
            Err(error) => {
                diagnostics.push(format!(
                    "Read marker {marker:x} has an invalid observation: {error:?}"
                ));
                None
            }
        })
        .collect();
        observations.sort_unstable();
        observations.dedup();
        match messages.get_mut(&message) {
            Some(row) => row.reads.push(ReadReceipt {
                reader,
                observations,
            }),
            None => diagnostics.push(format!(
                "Read marker {marker:x} names absent message {message:x}"
            )),
        }
    }

    if let Some(relations_view) = relations_view {
        match relations::IdentityComponents::from_facts(relations_view.facts) {
            Ok(identities) => {
                // Each operator as Relations has settled them, then the same
                // question the Message operations ask: what was delivered to
                // this identity, and has it acknowledged any of it. An
                // operator's own envelopes are outgoing and never answer here.
                for (operator, _) in people.iter().filter(|(_, person)| person.is_operator) {
                    let anchors = settled_identity(&identities, *operator);
                    for envelope in inbox(view.facts, relations_view.facts, &anchors) {
                        let id = envelope_id(&envelope);
                        let Some(row) = messages.get_mut(&id) else {
                            continue;
                        };
                        row.is_inbox = true;
                        if !read_by(view.facts, id, &anchors) {
                            row.is_unread = true;
                        }
                    }
                }
            }
            Err(error) => diagnostics.push(format!(
                "Relations identity catalog cannot classify the inbox: {error}"
            )),
        }
    }

    for message in messages.values_mut() {
        message.reads.sort_by_key(|read| read.reader);
    }
    let mut messages: Vec<_> = messages.into_values().collect();
    messages.sort_by(|left, right| {
        left.sort_key()
            .cmp(&right.sort_key())
            .then_with(|| left.id.cmp(&right.id))
    });
    (messages, diagnostics)
}

// ── Widget ───────────────────────────────────────────────────────────

/// GORBIE-embeddable message panel with compose, relations
/// identity lookup, scroll-to-bottom on new messages, and automatic
/// read-receipts for inbound messages.
///
/// See the module docs for construction examples.
/// Which subset of the stream to show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StreamFilter {
    /// Everything — agent-to-agent traffic included.
    All,
    /// Only messages addressed to an operator (a relations entry with
    /// the `operator` affinity) — the human's inbox.
    Inbox,
}

pub struct MessagesPanel {
    /// Rebuilt when the messages / relations revision changes.
    live: Option<MessagesLive>,
    /// Current stream filter — toggled via the ALL / INBOX chips.
    filter: StreamFilter,
}

impl Default for MessagesPanel {
    fn default() -> Self {
        Self {
            live: None,
            filter: StreamFilter::All,
        }
    }
}

impl MessagesPanel {
    /// New read-only panel.
    pub fn new() -> Self {
        Self::default()
    }

    /// Backwards-compatibility shim: the panel no longer has an
    /// internal scroll area (the notebook's own scroll handles
    /// overflow), so a configured height is a no-op.
    pub fn with_height(self, _height: f32) -> Self {
        self
    }

    /// Render the panel. `view` is the messages dataset;
    /// `relations` is optional and, when provided, is used for
    /// friendly-name resolution.
    pub fn render(
        &mut self,
        ctx: &mut CardCtx<'_>,
        view: DatasetView<'_>,
        relations: Option<DatasetView<'_>>,
    ) {
        // Refresh cached state if either logical dataset changed.
        let revision = view.revision;
        let relations_revision = relations.map(|view| view.revision);
        let need_refresh = match self.live.as_ref() {
            None => true,
            Some(l) => {
                l.cached_revision != revision || l.relations_cached_revision != relations_revision
            }
        };
        if need_refresh {
            self.live = Some(MessagesLive::refresh(view, relations));
        }

        let filter = &mut self.filter;
        ctx.section("Messages", |ctx| {
            let Some(live) = self.live.as_ref() else {
                return;
            };

            // Pre-materialize everything the UI closure needs.
            let messages = live.messages.clone();

            // Build a name lookup for every id we'll paint.
            let mut names: HashMap<Id, String> = HashMap::new();
            for m in &messages {
                names
                    .entry(m.from)
                    .or_insert_with(|| live.display_name(m.from));
                names.entry(m.to).or_insert_with(|| live.display_name(m.to));
                for read in &m.reads {
                    names
                        .entry(read.reader)
                        .or_insert_with(|| live.display_name(read.reader));
                }
            }

            let now = now_tai_ns();
            let count = messages.len();
            let latest_age = messages
                .iter()
                .filter_map(|m| m.created_at)
                .max()
                .map(|k| format_age_key(now, k));

            // Inbox stats: messages addressed to an operator (a human
            // per the relations `operator` affinity); unread = the
            // recipient hasn't filed a read receipt yet.
            let inbox_total = messages.iter().filter(|m| m.is_inbox).count();
            let inbox_unread = messages
                .iter()
                .filter(|m| m.is_inbox && m.is_unread)
                .count();
            // No operators in relations → no inbox notion; pin the
            // filter back to ALL so the chip row doesn't strand the
            // view on a permanently-empty subset.
            if inbox_total == 0 {
                *filter = StreamFilter::All;
            }

            // Open a notebook-wide search session — makes the bar
            // appear in the top-right and lets us filter messages by
            // body / from-name / to-name substring.
            let mut search = ctx.search();
            let needle = search.query().to_lowercase();
            let search_active = !needle.is_empty();

            ctx.grid(|g| {
                for diagnostic in &live.diagnostics {
                    g.full(|ctx| render_diagnostic(ctx.ui_mut(), diagnostic));
                }

                // Header row: filter chips + count on the left,
                // "LAST <age>" right.
                g.full(|ctx| {
                    let ui = ctx.ui_mut();
                    ui.horizontal(|ui| {
                        ui.spacing_mut().item_spacing.x = 6.0;

                        // Filter chips — only offered when an inbox
                        // notion exists (some relations entry carries
                        // the operator affinity and has mail).
                        if inbox_total > 0 {
                            let all_label = format!("ALL {count}");
                            let inbox_label = if inbox_unread > 0 {
                                format!("\u{1F4E5} INBOX {inbox_total} · {inbox_unread} NEW")
                            } else {
                                format!("\u{1F4E5} INBOX {inbox_total}")
                            };
                            if render_filter_chip(ui, &all_label, *filter == StreamFilter::All) {
                                *filter = StreamFilter::All;
                            }
                            if render_filter_chip(ui, &inbox_label, *filter == StreamFilter::Inbox)
                            {
                                *filter = StreamFilter::Inbox;
                            }
                        } else {
                            ui.label(
                                egui::RichText::new(format!("{count} MESSAGES"))
                                    .monospace()
                                    .strong()
                                    .small()
                                    .color(color_muted(ui)),
                            );
                        }

                        if let Some(age) = latest_age.as_ref() {
                            ui.with_layout(
                                egui::Layout::right_to_left(egui::Align::Center),
                                |ui| {
                                    ui.label(
                                        egui::RichText::new(format!("LAST {}", age.to_uppercase()))
                                            .monospace()
                                            .small()
                                            .strong()
                                            .color(color_muted(ui)),
                                    );
                                },
                            );
                        }
                    });
                });

                if messages.is_empty() {
                    g.full(|ctx| {
                        render_messages_empty_state(ctx.ui_mut(), "No messages yet.", None);
                    });
                    return;
                }

                // One grid cell per message; the notebook's own scroll
                // area handles overflow. No nested ScrollArea + no
                // arrival/stickiness state machine — the viewer is
                // read-only, so the user just scrolls the notebook.
                for msg in &messages {
                    let msg_is_inbox = msg.is_inbox;
                    if *filter == StreamFilter::Inbox && !msg_is_inbox {
                        continue;
                    }
                    if search_active && !message_matches_search(msg, &names, &needle) {
                        continue;
                    }
                    let match_info = if search_active {
                        Some(search.report(egui::Id::new(("messages_match", msg.id))))
                    } else {
                        None
                    };
                    let is_focused = match_info.as_ref().map_or(false, |i| i.is_focused);
                    let inbox_unread_msg = msg.is_unread;
                    g.full(|ctx| {
                        let ui = ctx.ui_mut();
                        let pre_y = ui.cursor().min.y;
                        render_message(
                            ui,
                            msg,
                            now,
                            &names,
                            &needle,
                            is_focused,
                            msg_is_inbox,
                            inbox_unread_msg,
                        );
                        if let Some(info) = match_info {
                            if info.should_scroll_to {
                                let post_y = ui.cursor().min.y;
                                let msg_rect = egui::Rect::from_min_max(
                                    egui::pos2(ui.min_rect().left(), pre_y),
                                    egui::pos2(ui.min_rect().right(), post_y),
                                );
                                ui.scroll_to_rect(msg_rect, Some(egui::Align::Center));
                            }
                        }
                    });
                }
            });
        });
    }
}

// ── Row rendering ────────────────────────────────────────────────────

/// True if the message's body, sender display name, or recipient
/// display name contains the (lowercased) needle.
fn message_matches_search(msg: &MessageRow, names: &HashMap<Id, String>, needle: &str) -> bool {
    if msg.body.to_lowercase().contains(needle) {
        return true;
    }
    for id in [msg.from, msg.to] {
        if let Some(name) = names.get(&id) {
            if name.to_lowercase().contains(needle) {
                return true;
            }
        }
    }
    false
}

/// Toggle chip for the stream filter. Active chip fills with RAL 1003
/// signal yellow; inactive renders on the frame colour. Returns true
/// on click.
fn render_filter_chip(ui: &mut egui::Ui, label: &str, active: bool) -> bool {
    let (fill, text) = if active {
        let fill = egui::Color32::from_rgb(0xf7, 0xba, 0x0b); // RAL 1003
        (fill, colorhash::text_color_on(fill))
    } else {
        (color_frame(ui), color_muted(ui))
    };
    let resp = ui.add(
        egui::Button::new(
            egui::RichText::new(label)
                .monospace()
                .small()
                .strong()
                .color(text),
        )
        .fill(fill)
        .corner_radius(egui::CornerRadius::ZERO)
        .min_size(egui::vec2(0.0, 18.0)),
    );
    resp.clicked()
}

/// Small filled badge used for 📥 INBOX / NEW markers in the bubble
/// header row.
fn render_badge(ui: &mut egui::Ui, label: &str, fill: egui::Color32) {
    let text = colorhash::text_color_on(fill);
    egui::Frame::NONE
        .fill(fill)
        .corner_radius(egui::CornerRadius::ZERO)
        .inner_margin(egui::Margin::symmetric(5, 1))
        .show(ui, |ui| {
            ui.label(
                egui::RichText::new(label)
                    .monospace()
                    .small()
                    .strong()
                    .color(text),
            );
        });
}

#[allow(clippy::too_many_arguments)]
fn render_message(
    ui: &mut egui::Ui,
    msg: &MessageRow,
    now: Option<i128>,
    names: &HashMap<Id, String>,
    // Lowercased search needle ("" = no search).
    search_needle: &str,
    // True when this bubble is the bar's currently-focused match;
    // makes every needle occurrence inside render with the double
    // underline (same emphasis the typst widget uses).
    focused: bool,
    // True when the recipient is an operator (human) — gets an 📥
    // badge so operator-directed mail stands out in the ALL stream.
    is_inbox: bool,
    // True when an inbox message has no read receipt from its
    // recipient yet — gets a NEW badge in RAL 1003.
    is_unread: bool,
) {
    let bubble_fill = ui.visuals().window_fill;
    let from_color = person_color(msg.from);
    let to_color = person_color(msg.to);
    // Sender/recipient stripes flank the bubble (compass-card idiom).
    // Width 18 fits a 9-pt monospace name rotated 90°. Inner content
    // is inset on both sides to leave room.
    const STRIPE_WIDTH: f32 = 18.0;
    const STRIPE_GAP: f32 = 8.0;
    const STROKE_INSET: f32 = 1.0;

    ui.vertical(|ui| {
        let inner_margin = egui::Margin {
            left: (STROKE_INSET + STRIPE_WIDTH + STRIPE_GAP) as i8,
            right: (STROKE_INSET + STRIPE_WIDTH + STRIPE_GAP) as i8,
            top: 6,
            bottom: 6,
        };
        let frame_resp = egui::Frame::NONE
            .fill(bubble_fill)
            .stroke(egui::Stroke::new(STROKE_INSET, color_frame(ui)))
            // Hard offset shadow + sharp corners: same paper-card idiom
            // compass goals use, giving the bubble physical "lift" instead
            // of a backlit LCD look.
            .shadow(egui::epaint::Shadow {
                offset: [2, 2],
                blur: 0,
                spread: 0,
                color: egui::Color32::from_black_alpha(48),
            })
            .corner_radius(egui::CornerRadius::ZERO)
            .inner_margin(inner_margin)
            .show(ui, |ui| {
                // Header row: just the age, right-aligned. Sender/recipient
                // are conveyed via the colored side stripes painted after
                // the Frame returns — no need for in-header chips.
                //
                // `Align::Min` on the cross-axis (top) so the layout
                // doesn't try to fill the cell's available_rect.height —
                // with frame-delayed cell sizing, that fill would feed
                // back into next frame's larger cell, growing forever.
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
                    let (age, hover) = match msg.created_at {
                        Some(k) => (format_age_key(now, k), Some(format_timestamp_key(k))),
                        None => ("-".to_string(), None),
                    };
                    let resp = ui.label(
                        egui::RichText::new(age)
                            .monospace()
                            .small()
                            .color(color_muted(ui)),
                    );
                    if let Some(h) = hover {
                        resp.on_hover_text(h);
                    }

                    // Inbox badges flow in from the LEFT edge of this
                    // right-to-left row, i.e. they render before the
                    // age. NEW (RAL 1003) only while the operator
                    // hasn't read-receipted; 📥 marks operator mail
                    // permanently so it stands out in the ALL stream.
                    ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {
                        ui.spacing_mut().item_spacing.x = 4.0;
                        if is_inbox {
                            render_badge(
                                ui,
                                "\u{1F4E5} INBOX",
                                egui::Color32::from_rgb(0x23, 0x7f, 0x52), // RAL 6032
                            );
                        }
                        if is_unread {
                            render_badge(
                                ui,
                                "NEW",
                                egui::Color32::from_rgb(0xf7, 0xba, 0x0b), // RAL 1003
                            );
                        }
                    });
                });

                ui.add_space(2.0);

                // Body. When a search is active, occurrences of the needle
                // are underlined inline; the bar's focused match gets a
                // second underline overlay via `highlight_label`.
                let base = egui::TextFormat {
                    font_id: egui::TextStyle::Body.resolve(ui.style()),
                    color: ui.visuals().text_color(),
                    ..Default::default()
                };
                GORBIE::search::highlight_label(ui, &msg.body, search_needle, base, focused);

                // Read receipts — compact "✓✓ NameA · NameB · 2h" line in
                // the may-green accent. Newest receipt's age is used as the
                // overall age; individual ages show on hover.
                if !msg.reads.is_empty() {
                    ui.add_space(4.0);
                    ui.horizontal_wrapped(|ui| {
                        ui.spacing_mut().item_spacing.x = 4.0;
                        ui.label(
                            egui::RichText::new("\u{2713}\u{2713}")
                                .small()
                                .color(color_read()),
                        );
                        let mut first = true;
                        for read in &msg.reads {
                            if !first {
                                ui.label(
                                    egui::RichText::new("\u{00b7}")
                                        .small()
                                        .color(color_muted(ui)),
                                );
                            }
                            first = false;
                            let name = names
                                .get(&read.reader)
                                .cloned()
                                .unwrap_or_else(|| id_hex(read.reader));
                            // Tint each reader name with its own person
                            // color so the reader list matches the
                            // sender/recipient chips above.
                            let response = ui.label(
                                egui::RichText::new(name)
                                    .small()
                                    .color(person_color(read.reader)),
                            );
                            let hover = if read.observations.is_empty() {
                                "read · no timestamp observation".to_owned()
                            } else {
                                read.observations
                                    .iter()
                                    .map(|timestamp| {
                                        format!(
                                            "read {} · {}",
                                            format_age_key(now, *timestamp),
                                            format_timestamp_key(*timestamp),
                                        )
                                    })
                                    .collect::<Vec<_>>()
                                    .join("\n")
                            };
                            response.on_hover_text(hover);
                        }
                        // Most recent observation is a compact presentation
                        // summary; every observation remains visible on hover.
                        if let Some(newest_ts) = msg
                            .reads
                            .iter()
                            .flat_map(|read| read.observations.iter())
                            .max()
                        {
                            ui.label(
                                egui::RichText::new(format!(
                                    "\u{00b7} {}",
                                    format_age_key(now, *newest_ts)
                                ))
                                .small()
                                .color(color_muted(ui)),
                            );
                        }
                    });
                }

                // Short id footer.
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new(id_hex(msg.id))
                            .monospace()
                            .small()
                            .color(color_muted(ui)),
                    );
                });
            });

        // ── Sender / recipient stripes (compass-card idiom) ─────────────
        //
        // After the Frame has measured + painted, lay two colored stripes
        // along the bubble's left and right edges (inset by the stroke so
        // the 1px outline draws around them). Each stripe carries the
        // person's monospace name rotated 90° — sender top-down on the
        // left, recipient bottom-up on the right — so the bubble reads
        // like an envelope: FROM ➝ TO without any in-body chips eating
        // the header.
        let outer = frame_resp.response.rect;
        let from_name = names
            .get(&msg.from)
            .cloned()
            .unwrap_or_else(|| id_hex(msg.from));
        let to_name = names
            .get(&msg.to)
            .cloned()
            .unwrap_or_else(|| id_hex(msg.to));
        paint_party_stripe(
            ui.painter(),
            outer,
            StripeSide::Left,
            from_color,
            &from_name.to_uppercase(),
        );
        paint_party_stripe(
            ui.painter(),
            outer,
            StripeSide::Right,
            to_color,
            &to_name.to_uppercase(),
        );
    });
}

#[derive(Clone, Copy)]
enum StripeSide {
    Left,
    Right,
}

/// Paint a compass-style colored stripe along one vertical edge of
/// `outer`, with `label` rendered as monospace rotated 90°. The text
/// is skipped when the stripe is too short to hold the glyphs (avoids
/// overflowing into the bubble body on one-line messages).
fn paint_party_stripe(
    painter: &egui::Painter,
    outer: egui::Rect,
    side: StripeSide,
    color: egui::Color32,
    label: &str,
) {
    const STRIPE_WIDTH: f32 = 18.0;
    const STROKE_INSET: f32 = 1.0;
    let stripe_min = match side {
        StripeSide::Left => outer.min + egui::vec2(STROKE_INSET, STROKE_INSET),
        StripeSide::Right => egui::pos2(
            outer.right() - STROKE_INSET - STRIPE_WIDTH,
            outer.top() + STROKE_INSET,
        ),
    };
    let stripe_rect = egui::Rect::from_min_size(
        stripe_min,
        egui::vec2(STRIPE_WIDTH, outer.height() - 2.0 * STROKE_INSET),
    );
    painter.rect_filled(stripe_rect, egui::CornerRadius::ZERO, color);

    let font = egui::FontId::monospace(9.0);
    let text_color = colorhash::text_color_on(color);
    let galley = painter.layout_no_wrap(label.to_string(), font, text_color);
    // Need height for the glyphs + a little breathing room.
    if galley.size().x + 6.0 > stripe_rect.height() {
        return;
    }
    let gh = galley.size().y;
    let mut text_shape = match side {
        StripeSide::Left => {
            // 90° clockwise rotation: text reads top-to-bottom. egui's
            // `TextShape::angle = +π/2` rotates around `pos` such that
            // the galley extends LEFT and DOWN from `pos`. So `pos`
            // sits on the right edge of where the text should appear.
            let pos = egui::pos2(
                stripe_rect.left() + (STRIPE_WIDTH + gh) * 0.5,
                stripe_rect.top() + 5.0,
            );
            let mut s = egui::epaint::TextShape::new(pos, galley, text_color);
            s.angle = std::f32::consts::FRAC_PI_2;
            s
        }
        StripeSide::Right => {
            // 90° counter-clockwise (bottom-to-top read) so the
            // recipient name visually faces the sender across the
            // bubble. `angle = -π/2` rotates around `pos` such that
            // the galley extends RIGHT and UP — so `pos` sits at the
            // left edge of where the rotated text should appear.
            let pos = egui::pos2(
                stripe_rect.left() + (STRIPE_WIDTH - gh) * 0.5,
                stripe_rect.bottom() - 5.0,
            );
            let mut s = egui::epaint::TextShape::new(pos, galley, text_color);
            s.angle = -std::f32::consts::FRAC_PI_2;
            s
        }
    };
    text_shape.fallback_color = text_color;
    painter.add(text_shape);
}

fn render_diagnostic(ui: &mut egui::Ui, message: &str) {
    let accent = egui::Color32::from_rgb(0xe6, 0x32, 0x46);
    egui::Frame::NONE
        .fill(accent.gamma_multiply(0.12))
        .stroke(egui::Stroke::new(1.0, accent))
        .corner_radius(egui::CornerRadius::ZERO)
        .inner_margin(egui::Margin::symmetric(8, 6))
        .show(ui, |ui| {
            ui.set_min_width(ui.available_width());
            ui.label(
                egui::RichText::new(format!("⚠ {message}"))
                    .monospace()
                    .small()
                    .color(ui.visuals().text_color()),
            );
        });
}

/// Centered empty-state block with an envelope glyph, a headline
/// message, and an optional muted sub-line. Used whenever the
/// messages panel has nothing to show.
fn render_messages_empty_state(ui: &mut egui::Ui, headline: &str, hint: Option<&str>) {
    ui.add_space(24.0);
    ui.vertical_centered(|ui| {
        ui.label(
            egui::RichText::new("\u{2709}")
                .size(32.0)
                .color(color_muted(ui)),
        );
        ui.add_space(6.0);
        ui.label(
            egui::RichText::new(headline)
                .monospace()
                .small()
                .strong()
                .color(color_muted(ui)),
        );
        if let Some(h) = hint {
            ui.add_space(2.0);
            ui.label(egui::RichText::new(h).small().color(color_muted(ui)));
        }
    });
    ui.add_space(24.0);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn canonical_relation_profile_controls_name_and_operator_classification() {
        let person = Person::from_profile(ProfileInput {
            label: "Example".to_owned(),
            aliases: vec!["sample".to_owned()],
            affinities: vec!["Operator".to_owned()],
            first_name: Some("Example".to_owned()),
            ..ProfileInput::default()
        });

        let id = Id::new([1; 16]).unwrap();
        assert_eq!(person.display(id), "Example");
        assert!(person.is_operator);
    }

    #[test]
    fn read_marker_without_observation_remains_visible() {
        let reader = Id::new([2; 16]).unwrap();
        let message = MessageRow {
            id: Id::new([3; 16]).unwrap(),
            from: Id::new([4; 16]).unwrap(),
            to: reader,
            body: "hello".to_owned(),
            created_at: None,
            reads: vec![ReadReceipt {
                reader,
                observations: Vec::new(),
            }],
            is_inbox: true,
            is_unread: false,
        };

        assert_eq!(message.reads.len(), 1);
        assert_eq!(message.reads[0].reader, reader);
        assert!(message.reads[0].observations.is_empty());
    }
}