mahbot 0.7.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
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
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
//! Sessions dashboard page — view and manage conversation sessions.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::time::Duration;

use crate::ChatMessage;
use crate::session::SessionMetadata;

use iced::widget::{
    Column, Id, Space, button, column, container, markdown, responsive, row, scrollable, text,
};
use iced::{Alignment, Element, Length, Task};

use iced_fonts::lucide;

use super::ToastMessage;
use super::media_markers;
use super::menus::{ContextMenu, MenuItem};
use super::session_view::preview::{
    MAX_PREVIEW_LINES, MessageMeasure, measure_message, re_measure, width_bucket,
};
use super::session_view::{self, SessionEntry, ToolCallEntry};
use super::theme;
use super::widgets::{self, BubbleSide, align_bubble, selectable_text};

/// Fraction of the transcript row width a chat bubble occupies (FillPortion 3
/// of a 3:1 row). The collapse measurement uses this to narrow the measured
/// width to the actual bubble body (container padding + a safety margin).
const BUBBLE_BODY_RATIO: f32 = 0.75;

/// Delay before a click-scheduled collapse of an expanded element actually
/// applies: the widget's double-click window (300 ms) plus a small margin, so
/// a canceling second click published at the window boundary always arrives
/// before the commit. A click inside the margin (beyond the double-click
/// window) is a deliberate second click and re-affirms the still-scheduled
/// collapse.
const COLLAPSE_COMMIT_DELAY: Duration = Duration::from_millis(350);

/// Max characters for the card title (user/workspace name) before an
/// ellipsis is appended — the card column is 350px wide.
const CARD_TITLE_MAX_CHARS: usize = 32;

/// Shared transcript render context: the flat session ledger, its per-entry
/// markdown bodies, the element expansion set, the collapse-measurement
/// cache, the single text measurement width (bubble body width, used for
/// all collapsible-element measurement), and whether the ledger can be
/// truncated (a stored, idle session).
struct TranscriptCtx<'a> {
    entries: &'a [SessionEntry],
    entry_md: &'a [Option<Vec<markdown::Item>>],
    expanded: &'a HashSet<(usize, usize)>,
    measure_cache: &'a RefCell<HashMap<(usize, usize), MessageMeasure>>,
    text_width: f32,
    truncatable: bool,
}

#[derive(Debug, Clone)]
pub(crate) enum SessionsMessage {
    Refreshed(Vec<SessionMetadata>),
    RefreshError(String),
    SelectSession(String),
    SessionMessages(String, Vec<ChatMessage>),
    /// A transcript read failure. `key` is the session the failed read
    /// belonged to, so a slow read for a session the user has since left does
    /// not render in the newly selected transcript.
    SessionError {
        key: String,
        error: String,
    },
    /// Toggle an element's collapsed preview / full content, keyed by
    /// (entry index, element index within entry). Expanding applies
    /// immediately; collapsing is deferred past the double-click window (see
    /// `SessionsState::update`) and confirmed by [`SessionsMessage::ToggleCommit`].
    ToggleExpand(usize, usize),

    /// The second click of a double-click on a collapsible element: a
    /// word/line selection, so any collapse scheduled by the first click is
    /// dropped.
    ToggleCancel(usize, usize),

    /// Apply a collapse previously scheduled by [`SessionsMessage::ToggleExpand`]
    /// once the double-click window has passed without a canceling second
    /// click.
    ToggleCommit(usize, usize),

    /// Scroll position changed in the transcript viewport.
    ScrollChanged(scrollable::Viewport),

    /// Dismiss modals/panels (Escape key).
    Escape,

    /// A link was clicked in rendered markdown.
    LinkClicked(String),

    /// A toast notification to surface from the dashboard.
    Toast(ToastMessage),
    /// Delete a session (context-menu action).
    DeleteSession(String),
    /// A session delete finished — remove it from the list. The bool is the
    /// store-reported row deletion (`true` when a real removal happened).
    SessionDeleted(String, bool),

    /// Truncate the selected session (context-menu action): remove the ledger
    /// entry at this index and every stored message from it on.
    TruncateSession(usize),
    /// A session truncate finished: the store removed `deleted` rows from
    /// `entry` on (`0` = the cut was a no-op).
    SessionTruncated {
        key: String,
        entry: usize,
        deleted: usize,
    },

    /// Coalesced runtime-change tick (250 ms): refresh list timestamps and
    /// merge the selected session's live transcript when its agent is running.
    RuntimeChanged,
}

#[derive(Debug, Clone)]
struct CachedSessionItem {
    agent_id: String,
    /// Agent role parsed from the metadata role string; `None` renders the
    /// title without an icon.
    role: Option<crate::Role>,
    /// User name when present (Some and non-empty), otherwise the workspace
    /// name (may be empty if both are absent).
    title: String,
    /// Pre-formatted message count string.
    msg_count_label: String,
    /// Pre-formatted compact token count (same format as the Running Agents
    /// card), when the session ever recorded a provider-reported length.
    token_label: Option<String>,
    /// Pre-formatted timestamp string.
    timestamp_label: String,
}

pub(crate) struct SessionsState {
    sessions: Vec<SessionMetadata>,
    load_state: super::common::AsyncLoadState,
    selected_session: Option<String>,
    /// The flat session ledger built from the selected session's messages.
    entries: Vec<SessionEntry>,
    /// Per-entry markdown bodies, parallel to `entries` (parsed from the
    /// ledger via `session_view::parse_entry_bodies`).
    entry_md: Vec<Option<Vec<markdown::Item>>>,
    /// For each entry, the index of the stored `sessions` row it was built from
    /// (see `session_view::build_ledger_with_sources`). `None` while the ledger
    /// has no stored-row identity: before the first stored load, and after any
    /// live merge — those indices are in-memory history positions, and a
    /// running agent may have rewritten the stored rows since the load. The
    /// truncate action is offered only while this is `Some` on an idle session,
    /// and comes back only on re-select, which reloads the stored ledger.
    entry_rows: Option<Vec<usize>>,
    selected_loading: bool,
    /// Last transcript read failure for the selected session. Rendered in the
    /// transcript pane (instead of the previous/empty transcript) until a
    /// successful load or a new selection clears it.
    selected_error: Option<String>,
    /// Elements the user expanded beyond their collapsed preview, keyed by
    /// (entry index, element index within entry): 0 = body/narration,
    /// 1 = thinking block, 2+j = result block of call `j`. Cleared on
    /// session switch.
    expanded: HashSet<(usize, usize)>,
    /// Expanded elements whose click-scheduled collapse is waiting out the
    /// double-click window (keyed like `expanded`). The second click of a
    /// double-click removes the entry — the double-click belongs to word/line
    /// selection — and a later [`SessionsMessage::ToggleCommit`] applies the
    /// collapse only if the entry survived. Cleared on session switch.
    pending_collapses: HashSet<(usize, usize)>,
    /// Per-element collapse measurement cache, keyed like `expanded`. The
    /// ledger only appends or drops its tail, so a surviving entry keeps its
    /// index and its key stays valid — only new elements are measured lazily.
    /// Mutated during layout (the bubble width is only known there), hence
    /// `RefCell`.
    measure_cache: RefCell<HashMap<(usize, usize), MessageMeasure>>,
    /// Cached session list display data. Rebuilt when `sessions` changes and
    /// on each runtime-change tick (to refresh relative-time labels).
    /// `view()` builds widgets from this data on every frame.
    cached_session_items: Option<Vec<CachedSessionItem>>,

    // ── Transcript viewport fields ───────────────────────────────
    /// Stable scrollable ID for the transcript area, preserves scroll position
    /// across widget rebuilds.
    scrollable_id: Id,
    /// Whether auto-scroll-to-bottom is enabled (user is at or near the bottom).
    auto_scroll_enabled: bool,
}

impl SessionsState {
    pub(crate) fn new() -> Self {
        Self {
            sessions: Vec::new(),
            load_state: super::common::AsyncLoadState::new(),
            selected_session: None,
            entries: Vec::new(),
            entry_md: Vec::new(),
            entry_rows: None,
            selected_loading: false,
            selected_error: None,
            expanded: HashSet::new(),
            pending_collapses: HashSet::new(),
            measure_cache: RefCell::new(HashMap::new()),
            cached_session_items: None,
            scrollable_id: Id::new("session_transcript_scroll"),
            auto_scroll_enabled: false,
        }
    }

    /// Refresh the session list.
    pub(crate) fn refresh() -> Task<SessionsMessage> {
        Task::perform(
            async move {
                let store = crate::session::store();
                store
                    .list_sessions_with_metadata_checked()
                    .await
                    .map_err(|e| e.to_string())
            },
            |res| match res {
                Ok(sessions) => SessionsMessage::Refreshed(sessions),
                Err(e) => SessionsMessage::RefreshError(e),
            },
        )
    }

    #[expect(
        clippy::too_many_lines,
        reason = "one arm per transcript interaction; the per-session selection bookkeeping is only readable inline"
    )]
    pub(crate) fn update(&mut self, msg: SessionsMessage) -> Task<SessionsMessage> {
        match msg {
            SessionsMessage::Refreshed(sessions) => {
                self.sessions = sessions;
                self.rebuild_session_cache();
                self.load_state.clear_error();
                self.load_state.finish_loading();
                Task::none()
            }
            SessionsMessage::RefreshError(e) => {
                self.load_state.fail(e);
                Task::none()
            }
            SessionsMessage::SelectSession(key) => {
                self.selected_session = Some(key.clone());
                self.selected_loading = true;
                self.selected_error = None;
                self.expanded.clear();
                self.pending_collapses.clear();
                // The measurement cache is cleared in SessionMessages when the
                // new session's messages actually arrive; a failure for the new
                // session renders the error rather than the previous
                // transcript, so stale cache entries stay unused until the next
                // successful load clears them. Do NOT set auto_scroll_enabled
                // here — ScrollChanged owns it; the initial snap to bottom
                // happens in SessionMessages.
                Task::perform(
                    async move {
                        let store = crate::session::store();
                        match store.load_checked(&key).await {
                            Ok(messages) => Ok::<_, (String, String)>((key, messages)),
                            Err(e) => Err((key, e.to_string())),
                        }
                    },
                    |res| match res {
                        Ok((key, messages)) => SessionsMessage::SessionMessages(key, messages),
                        Err((key, error)) => SessionsMessage::SessionError { key, error },
                    },
                )
            }
            SessionsMessage::SessionMessages(key, messages) => {
                if self.selected_session.as_deref() == Some(&key) {
                    let (entries, rows) = session_view::build_ledger_with_sources(&messages);
                    self.entries = entries;
                    self.entry_rows = Some(rows);
                    self.entry_md = session_view::parse_entry_bodies(&self.entries);
                    // Fresh session load: reset the measurement cache (the
                    // previous session's keys are index-stale) and any pending
                    // collapse from the old ledger.
                    self.measure_cache.borrow_mut().clear();
                    self.pending_collapses.clear();
                    self.selected_loading = false;
                    self.selected_error = None;
                    // Snap to bottom so the user sees the most recent messages
                    // immediately.
                    return iced::widget::operation::snap_to_end(self.scrollable_id.clone());
                }
                Task::none()
            }
            SessionsMessage::SessionError { key, error } => {
                // A slow read for a session the user has since left must not
                // render its failure in the newly selected transcript.
                if self.selected_session.as_deref() == Some(&key) {
                    self.selected_error = Some(error);
                    self.selected_loading = false;
                }
                Task::none()
            }
            SessionsMessage::ScrollChanged(viewport) => {
                let bounds = viewport.bounds();
                let content = viewport.content_bounds();
                let at_bottom = if content.height > bounds.height {
                    viewport.relative_offset().y >= 0.99
                } else {
                    content.height <= bounds.height
                };
                self.auto_scroll_enabled = at_bottom;
                Task::none()
            }
            SessionsMessage::ToggleExpand(i, j) => self.handle_toggle_expand(i, j),
            SessionsMessage::ToggleCancel(i, j) => {
                // Double-click word/line selection: the scheduled collapse is
                // dropped and the block stays put.
                self.pending_collapses.remove(&(i, j));
                Task::none()
            }
            SessionsMessage::ToggleCommit(i, j) => {
                // Apply the collapse only if no double-click canceled it.
                if self.pending_collapses.remove(&(i, j)) {
                    self.expanded.remove(&(i, j));
                }
                Task::none()
            }
            SessionsMessage::DeleteSession(key) => Task::perform(
                async move {
                    // User-initiated deletion: abandon the session's unfinished
                    // sync jobs first — a delete must not orphan them. A failure
                    // surfaces via the error toast and the delete is skipped so
                    // the user can retry.
                    crate::jobs::abandon_session_jobs(&key)
                        .await
                        .map_err(|e| e.to_string())?;
                    let store = crate::session::store();
                    let deleted = store.delete(&key).await.map_err(|e| e.to_string())?;
                    Ok::<_, String>((key, deleted))
                },
                |res| match res {
                    Ok((key, deleted)) => SessionsMessage::SessionDeleted(key, deleted),
                    Err(e) => SessionsMessage::Toast(ToastMessage::Error(e)),
                },
            ),
            SessionsMessage::SessionDeleted(key, deleted) => {
                self.sessions.retain(|s| s.agent_id != key);
                self.rebuild_session_cache();
                if self.selected_session.as_deref() == Some(&key) {
                    self.clear_selection();
                }
                // Only claim a "Deleted" success when a real row removal
                // happened; an already-absent session (cleaned up elsewhere)
                // just vanishes from the list without an inaccurate toast.
                if deleted {
                    Task::done(SessionsMessage::Toast(ToastMessage::Deleted))
                } else {
                    Task::none()
                }
            }
            SessionsMessage::TruncateSession(entry) => {
                let Some(key) = self.selected_session.clone() else {
                    return Task::none();
                };
                // The stored row the entry was built from; without one the
                // ledger has no stored-row identity and the cut is a no-op.
                let Some(row) = self
                    .entry_rows
                    .as_ref()
                    .and_then(|rows| rows.get(entry).copied())
                else {
                    return Task::none();
                };
                Task::perform(
                    async move {
                        let deleted = crate::session::store()
                            .truncate_from(&key, row)
                            .await
                            .map_err(|e| e.to_string())?;
                        Ok::<_, String>((key, entry, deleted))
                    },
                    |res| match res {
                        Ok((key, entry, deleted)) => SessionsMessage::SessionTruncated {
                            key,
                            entry,
                            deleted,
                        },
                        Err(e) => SessionsMessage::Toast(ToastMessage::Error(e)),
                    },
                )
            }
            SessionsMessage::SessionTruncated {
                key,
                entry,
                deleted,
            } => {
                // A no-op cut has nothing to drop. A live merge landing between
                // the click and this reply can at worst prune at a stale index —
                // cosmetic: the store cut is durable and a re-select corrects
                // the view.
                if deleted > 0 && self.selected_session.as_deref() == Some(key.as_str()) {
                    self.entries.truncate(entry);
                    self.entry_md.truncate(entry);
                    if let Some(rows) = self.entry_rows.as_mut() {
                        rows.truncate(entry);
                    }
                    self.expanded.retain(|(i, _)| *i < entry);
                    self.pending_collapses.retain(|(i, _)| *i < entry);
                    self.measure_cache
                        .borrow_mut()
                        .retain(|(i, _), _| *i < entry);
                    // The card's count renders from the list snapshot, which
                    // otherwise refreshes only on page navigation.
                    if let Some(session) = self.sessions.iter_mut().find(|s| s.agent_id == key) {
                        session.message_count = session.message_count.saturating_sub(deleted);
                    }
                    self.rebuild_session_cache();
                }
                Task::none()
            }
            SessionsMessage::RuntimeChanged => self.on_runtime_changed(),
            SessionsMessage::Toast(_) | SessionsMessage::LinkClicked(_) => Task::none(),
            SessionsMessage::Escape => {
                self.clear_selection();
                Task::none()
            }
        }
    }

    /// Click-to-toggle of one collapsible element: expanding applies
    /// immediately; collapsing is scheduled and confirmed by a delayed
    /// [`SessionsMessage::ToggleCommit`]. The widget's second-click message
    /// ([`SessionsMessage::ToggleCancel`]) drops a scheduled collapse so a
    /// word/line-selection double-click never moves the block.
    fn handle_toggle_expand(&mut self, i: usize, j: usize) -> Task<SessionsMessage> {
        let key = (i, j);
        if self.expanded.contains(&key) {
            self.pending_collapses.insert(key);
            Task::perform(
                async { tokio::time::sleep(COLLAPSE_COMMIT_DELAY).await },
                move |()| SessionsMessage::ToggleCommit(i, j),
            )
        } else {
            self.expanded.insert(key);
            Task::none()
        }
    }

    /// Clear the currently selected session and ALL per-session transcript
    /// state, returning the transcript column to its placeholder.
    fn clear_selection(&mut self) {
        self.selected_session = None;
        self.entries.clear();
        self.entry_md.clear();
        self.entry_rows = None;
        self.selected_loading = false;
        self.selected_error = None;
        self.expanded.clear();
        self.pending_collapses.clear();
        self.auto_scroll_enabled = false;
        self.measure_cache.borrow_mut().clear();
    }

    /// Rebuild the cached session list display data. Called when `self.sessions`
    /// changes and on each runtime-change tick (to refresh relative-time labels).
    /// `view()` builds widgets from this data on every frame.
    fn rebuild_session_cache(&mut self) {
        let now = chrono::Local::now();
        let items: Vec<CachedSessionItem> = self
            .sessions
            .iter()
            .map(|s| {
                let role = s
                    .role
                    .as_deref()
                    .and_then(|r| r.parse::<crate::Role>().ok());
                let name = s
                    .user_name
                    .as_deref()
                    .filter(|n| !n.is_empty())
                    .or_else(|| s.workspace_name.as_deref().filter(|n| !n.is_empty()))
                    .unwrap_or("");
                CachedSessionItem {
                    agent_id: s.agent_id.clone(),
                    role,
                    title: crate::util::truncate(name, CARD_TITLE_MAX_CHARS),
                    msg_count_label: format!("{} msgs", s.message_count),
                    token_label: s.token_length.map(theme::format_compact_tokens),
                    timestamp_label: theme::format_relative_time(
                        &s.last_activity.to_rfc3339(),
                        now,
                    ),
                }
            })
            .collect();
        self.cached_session_items = if items.is_empty() { None } else { Some(items) };
    }

    /// Coalesced runtime-change tick: refresh the cached relative-time labels
    /// and, when the selected session's agent is running, merge its live
    /// transcript into the view.
    ///
    /// The merge is append-oriented and diffed by the longest common entry
    /// prefix, so markdown re-parsing is limited to the changed tail and
    /// measurement-cache keys of unchanged entries stay valid (built entries
    /// drop their key and re-measure lazily; an in-place edit changes
    /// `content_len`, which the stale fingerprint re-measures anyway).
    /// Index-keyed expansion sets stay valid because the tail is append-only
    /// and out-of-range keys are harmless. Snapshot lookup doubles as the
    /// running check — `None` when the agent is not running; a recycled agent
    /// id surfaces the new run's fresh (empty) holder, replacing the displayed
    /// transcript wholesale.
    fn on_runtime_changed(&mut self) -> Task<SessionsMessage> {
        self.rebuild_session_cache();

        let Some(ref key) = self.selected_session else {
            return Task::none();
        };
        if self.selected_loading {
            return Task::none();
        }
        let Some(snapshot) = crate::session::TRANSCRIPT_REGISTRY.snapshot(key) else {
            return Task::none();
        };
        let live = session_view::build_ledger(&snapshot.history);
        let common = common_entry_prefix(&self.entries, &live);
        if common == self.entries.len() && common == live.len() {
            return Task::none();
        }
        self.measure_cache
            .borrow_mut()
            .retain(|(i, _), _| *i < common);
        self.entries = live;
        // Live history positions, not stored rows: the merged ledger has no
        // stored-row identity (see `entry_rows`).
        self.entry_rows = None;
        self.entry_md.truncate(common);
        self.entry_md
            .extend(session_view::parse_entry_bodies(&self.entries[common..]));

        // Live updates only auto-scroll when the user was already following
        // the bottom (same rule as the fresh-load path).
        if self.auto_scroll_enabled {
            iced::widget::operation::snap_to_end(self.scrollable_id.clone())
        } else {
            Task::none()
        }
    }

    #[expect(clippy::too_many_lines)]
    pub(crate) fn view(&self) -> Element<'_, SessionsMessage> {
        let mut content = column![];

        // Error display — inset to align with the vscroll-wrapped list below.
        content = widgets::push_error_banner_inset(content, self.load_state.error());

        if self.load_state.loading() && !self.load_state.has_loaded() {
            content = content.push(widgets::scroll_h_inset(widgets::loading_text()));
        } else if self.sessions.is_empty() {
            // A failed read must not masquerade as a legitimately empty list:
            // the error banner above is the only thing rendered.
            if self.load_state.error().is_none() {
                content = content.push(widgets::empty_state_placeholder(
                    lucide::layout_dashboard::<iced::Theme, iced::Renderer>(),
                    "No sessions",
                    theme::TEXT_MUTED,
                ));
            }
        } else {
            // Session list on the left side — built from cached display data.
            // The cache is rebuilt when `self.sessions` changes (in
            // `Refreshed`) and on each runtime-change tick (to refresh
            // relative-time labels); cards are rebuilt from it on every frame.
            let mut session_list = Column::new().spacing(theme::SPACE_4);
            if let Some(ref cached) = self.cached_session_items {
                for item in cached {
                    let is_selected = self.selected_session.as_deref() == Some(&item.agent_id);

                    let mut title_row = iced::widget::Row::new()
                        .width(Length::Fill)
                        .spacing(theme::SPACE_6)
                        .align_y(Alignment::Center);
                    if let Some(role) = item.role {
                        title_row = title_row.push(
                            theme::role_icon(&role)
                                .size(theme::TEXT_14)
                                .color(theme::role_badge_color_for(&role).0),
                        );
                    }
                    let title_color = if is_selected {
                        theme::ACCENT
                    } else {
                        theme::TEXT_PRIMARY
                    };
                    title_row = title_row.push(
                        text(item.title.clone())
                            .size(theme::TEXT_13)
                            .color(title_color),
                    );
                    if crate::agent::registry::AGENT_REGISTRY.contains(item.agent_id.as_str()) {
                        title_row = title_row
                            .push(Space::new().width(Length::Fill))
                            .push(super::spinner(theme::TEXT_14));
                    }

                    let sess_row: Element<'_, SessionsMessage> = ContextMenu::new(
                        container(
                            column![
                                row![
                                    button(
                                        container(
                                            column![
                                                title_row,
                                                {
                                                    // Meta row: messages left / tokens center /
                                                    // time right, spread via two Fill gaps
                                                    // across the card. Sessions that never
                                                    // recorded a token length leave the center
                                                    // empty.
                                                    let mut meta_row = iced::widget::Row::new()
                                                        .width(Length::Fill)
                                                        .push(
                                                            text(&item.msg_count_label)
                                                                .size(theme::TEXT_11)
                                                                .color(theme::TEXT_SECONDARY),
                                                        )
                                                        .push(Space::new().width(Length::Fill));
                                                    if let Some(token) = &item.token_label {
                                                        meta_row = meta_row.push(
                                                            text(token)
                                                                .size(theme::TEXT_11)
                                                                .color(theme::TEXT_SECONDARY),
                                                        );
                                                    }
                                                    meta_row
                                                        .push(Space::new().width(Length::Fill))
                                                        .push(
                                                            text(&item.timestamp_label)
                                                                .size(theme::TEXT_11)
                                                                .color(theme::TEXT_SECONDARY),
                                                        )
                                                },
                                                text(&item.agent_id)
                                                    .size(theme::TEXT_11)
                                                    .color(theme::TEXT_MUTED),
                                            ]
                                            .width(Length::Fill)
                                            .spacing(theme::SPACE_2),
                                        )
                                        .padding(theme::PAD_6)
                                        .width(Length::Fill),
                                    )
                                    .width(Length::Fill)
                                    .style(theme::button_text)
                                    .on_press(
                                        SessionsMessage::SelectSession(item.agent_id.clone())
                                    ),
                                ]
                                .width(Length::Fill)
                                .align_y(Alignment::Center),
                            ]
                            .spacing(theme::SPACE_2),
                        )
                        .style(theme::surface_card_style),
                        vec![MenuItem::with_icon(
                            iced_fonts::lucide::advanced_text::trash,
                            "Delete".into(),
                            SessionsMessage::DeleteSession(item.agent_id.clone()),
                        )],
                    )
                    .into();

                    session_list = session_list.push(sess_row);
                }
            }

            let session_scroll =
                widgets::vscroll_sized(session_list, Length::Fixed(350.0), Length::Shrink);

            // Transcript on the right side. Wrapped in `responsive` so the
            // collapse measurement uses the real bubble body width, correct on
            // first render and after every window resize.
            let transcript: iced::Element<'_, SessionsMessage> = if self.selected_loading {
                iced::widget::container(widgets::loading_text())
                    .width(Length::Fill)
                    .height(Length::Fill)
                    .padding(theme::PAD_16)
                    .into()
            } else if let Some(err) = self.selected_error.as_deref() {
                // The transcript read failed: render the failure where the
                // transcript would be, instead of the previous transcript or
                // the empty-session message.
                container(widgets::error_banner_fill(err))
                    .width(Length::Fill)
                    .height(Length::Fill)
                    .padding(theme::PAD_16)
                    .into()
            } else if self.selected_session.is_some() {
                // Truncate targets stored rows and is offered only on an idle
                // session — the same AGENT_REGISTRY membership that marks an
                // active session with the list spinner above.
                let truncatable = self.entry_rows.is_some()
                    && self
                        .selected_session
                        .as_deref()
                        .is_some_and(|key| !crate::agent::registry::AGENT_REGISTRY.contains(key));
                let entries = &self.entries;
                let entry_md = &self.entry_md;
                let expanded = &self.expanded;
                let measure_cache = &self.measure_cache;
                let scrollable_id = self.scrollable_id.clone();
                responsive(move |size| {
                    // The transcript scrollable wrapper adds 8px padding per
                    // side. Every transcript round (message or tool round)
                    // renders as a chat bubble; all content measures at the
                    // bubble body width = 3/4 of the transcript row minus the
                    // bubble's 10px padding per side, folded in with a +4px
                    // safety margin that errs toward collapse.
                    let text_width = ((size.width - 16.0) * BUBBLE_BODY_RATIO - 24.0).max(0.0);
                    let ctx = TranscriptCtx {
                        entries,
                        entry_md,
                        expanded,
                        measure_cache,
                        text_width,
                        truncatable,
                    };
                    container(render_transcript(&ctx, &scrollable_id))
                        .width(Length::Fill)
                        .height(Length::Fill)
                        .padding([theme::PAD_8, 0.0])
                        .into()
                })
                .into()
            } else {
                container(
                    text("Select a session to view transcript.")
                        .size(theme::TEXT_13)
                        .color(theme::TEXT_MUTED),
                )
                .width(Length::Fill)
                .height(Length::Fill)
                .padding(theme::PAD_16)
                .center_x(Length::Fill)
                .center_y(Length::Fill)
                .into()
            };

            content = content.push(
                row![
                    session_scroll,
                    Space::new().width(theme::SPACE_12),
                    transcript
                ]
                .height(Length::Fill),
            );
        }

        widgets::page(content)
    }
}

/// Length of the longest common prefix of two ledgers (first differing
/// entry index). `build_ledger` is deterministic, so an unchanged message
/// prefix yields an identical entry prefix.
fn common_entry_prefix(old: &[SessionEntry], new: &[SessionEntry]) -> usize {
    old.iter().zip(new).take_while(|(a, b)| a == b).count()
}

/// Author label above a bubble, aligned to the bubble's side. One non-accent
/// color for every role, so roles stay visually consistent.
fn author_label<'a>(role: crate::ChatRole) -> Element<'a, SessionsMessage> {
    let name = match role {
        crate::ChatRole::System => "System",
        crate::ChatRole::User => "User",
        crate::ChatRole::Assistant => "Assistant",
        crate::ChatRole::Tool => "Tool",
    };
    let label = text(name).size(theme::TEXT_11).color(theme::TEXT_SECONDARY);
    align_bubble(
        label,
        if matches!(role, crate::ChatRole::Assistant) {
            BubbleSide::Right
        } else {
            BubbleSide::Left
        },
    )
}

/// Author-labeled chat-bubble row for one ledger entry: the label sits above
/// the bubble, both aligned to the bubble's side (assistant right, others
/// left). Same background/typography as the Home chat bubbles.
///
/// `menu` wraps the BUBBLE alone — not the label, and not the spacer
/// `align_bubble` adds beside it, so the menu's hit target is the bubble.
fn bubble_row(
    role: crate::ChatRole,
    body: Column<'_, SessionsMessage>,
    menu: Option<MenuItem<SessionsMessage>>,
) -> Element<'_, SessionsMessage> {
    let assistant = matches!(role, crate::ChatRole::Assistant);
    let bubble: Element<'_, SessionsMessage> = container(body)
        .padding(theme::PAD_10)
        .style(theme::bubble_style(
            if assistant {
                theme::BG_ELEVATED
            } else {
                theme::BG_SURFACE
            },
            Some(theme::TEXT_PRIMARY),
        ))
        .width(Length::FillPortion(3))
        .into();
    let bubble: Element<'_, SessionsMessage> = match menu {
        Some(item) => ContextMenu::new(bubble, vec![item]).into(),
        None => bubble,
    };
    column![
        author_label(role),
        align_bubble(
            bubble,
            if assistant {
                BubbleSide::Right
            } else {
                BubbleSide::Left
            },
        )
    ]
    .spacing(theme::SPACE_2)
    .into()
}

/// Resolve the collapse measurement for an element at the current
/// `text_width`, measuring on cache miss (cached per element and width; the
/// session ledger is append-only, so a cached entry stays valid). Returns the
/// wrapped-line count and — only when
/// `need_preview` is set (the element is currently collapsed) — its 3-line
/// plain-text preview, so expanded elements do not pay a per-frame preview
/// clone. `font_size` is the body size the element renders at (body or
/// narration).
///
/// Stale-fingerprint semantics: a cache hit with the same width bucket,
/// `content_len`, and `font_size` is reused; the same content at a different
/// bucket (or size) is re-measured via [`re_measure`]; otherwise a fresh
/// measurement runs.
#[expect(
    clippy::float_cmp,
    reason = "font sizes are theme constants passed verbatim; exact identity is intended"
)]
fn element_measurement(
    measure_cache: &RefCell<HashMap<(usize, usize), MessageMeasure>>,
    key: (usize, usize),
    text_width: f32,
    need_preview: bool,
    content: &str,
    font_size: f32,
) -> (u32, Option<String>) {
    let bucket = width_bucket(text_width);
    let content_len = content.len();
    let mut cache = measure_cache.borrow_mut();
    let cache_hit = cache.get(&key);
    let stale = cache_hit.is_none_or(|m| {
        m.width_bucket != bucket || m.content_len != content_len || m.font_size != font_size
    });
    if stale {
        // Cache miss: measure. A pure width change reuses the cached
        // processed display text (an `Arc` clone); otherwise measure from the
        // caller's plain-text content.
        let m = match cache_hit {
            Some(m)
                if m.width_bucket != bucket
                    && m.content_len == content_len
                    && m.font_size == font_size =>
            {
                re_measure(m, text_width)
            }
            _ => measure_message(content, text_width, content_len, font_size),
        };
        cache.insert(key, m);
    }
    let m = cache.get(&key).expect("measurement resolved above");
    (
        m.wrapped_lines,
        if need_preview {
            m.preview.clone()
        } else {
            None
        },
    )
}

/// The collapsed-preview-versus-full content of a collapsible element: when
/// it can collapse and is collapsed, a [`MAX_PREVIEW_LINES`]-line preview
/// (in `size`/`font`) with a small "ellipsis" marker for the hidden content;
/// otherwise the caller's `expanded` element. Callers wrap the result in
/// [`click_toggle`] — never nesting two toggle areas (a nested double-toggle
/// cancels out).
fn collapsible_text_block(
    collapses: bool,
    is_expanded: bool,
    preview: Option<String>,
    color: iced::Color,
    size: f32,
    font: iced::Font,
    expanded: Element<'_, SessionsMessage>,
) -> Element<'_, SessionsMessage> {
    if collapses && !is_expanded {
        let preview = preview.expect("a collapsing element always has a preview");
        row![
            selectable_text(preview, color).size(size).font(font),
            lucide::ellipsis::<iced::Theme, iced::Renderer>()
                .size(theme::TEXT_11)
                .color(theme::TEXT_MUTED),
        ]
        .spacing(theme::SPACE_4)
        .align_y(Alignment::Start)
        .into()
    } else {
        expanded
    }
}

/// Wrap an element in the click-to-toggle area when it can collapse (a short
/// click anywhere toggles, drag selection keeps working).
fn click_toggle(
    key: (usize, usize),
    active: bool,
    el: Element<'_, SessionsMessage>,
) -> Element<'_, SessionsMessage> {
    if active {
        widgets::click_to_toggle(
            el,
            SessionsMessage::ToggleExpand(key.0, key.1),
            SessionsMessage::ToggleCancel(key.0, key.1),
        )
    } else {
        el
    }
}

/// Shared collapse-state preamble for the transcript's collapsible elements:
/// returns `(is_expanded, collapses, preview)` — whether the user expanded the
/// element, whether it renders more than [`MAX_PREVIEW_LINES`] wrapped lines
/// at `font_size` (measured at the bubble body width), and the measured
/// 3-line preview if it can collapse.
fn collapse_state(
    ctx: &TranscriptCtx<'_>,
    key: (usize, usize),
    content: &str,
    font_size: f32,
) -> (bool, bool, Option<String>) {
    let is_expanded = ctx.expanded.contains(&key);
    let (wrapped_lines, preview) = element_measurement(
        ctx.measure_cache,
        key,
        ctx.text_width,
        !is_expanded,
        content,
        font_size,
    );
    (is_expanded, wrapped_lines > MAX_PREVIEW_LINES, preview)
}

/// A plain-text collapsible element with the 3-line measured collapse rule:
/// when it renders more than [`MAX_PREVIEW_LINES`] wrapped lines and is not
/// expanded, a 3-line preview (with an "ellipsis" marker) is shown; otherwise
/// the full selectable text. The whole element is click-to-toggle when it can
/// collapse, so the selectable text stays drag-selectable. The measurement
/// stays at [`theme::MARKDOWN_TEXT_SIZE`] (the text renders at 11px) — the
/// err-toward-collapsing bias.
fn plain_collapsible<'a>(
    ctx: &TranscriptCtx<'a>,
    key: (usize, usize),
    content: &'a str,
    color: iced::Color,
) -> Element<'a, SessionsMessage> {
    let (is_expanded, collapses, preview) =
        collapse_state(ctx, key, content, theme::MARKDOWN_TEXT_SIZE);
    let el = collapsible_text_block(
        collapses,
        is_expanded,
        preview,
        color,
        theme::TEXT_11,
        theme::FONT_REGULAR,
        selectable_text(content, color).size(theme::TEXT_11).into(),
    );
    click_toggle(key, collapses, el)
}

/// The collapsible Thinking block: lucide `brain` + "Thinking" header above a
/// 3-line-collapse body measured at the bubble body width. The measurement
/// stays at [`theme::MARKDOWN_TEXT_SIZE`] (the body renders at 11px) — the
/// err-toward-collapsing bias.
fn thinking_block<'a>(
    ctx: &TranscriptCtx<'a>,
    key: (usize, usize),
    content: &'a str,
) -> Element<'a, SessionsMessage> {
    let (is_expanded, collapses, preview) =
        collapse_state(ctx, key, content, theme::MARKDOWN_TEXT_SIZE);
    let header = row![
        lucide::brain::<iced::Theme, iced::Renderer>()
            .size(theme::TEXT_11)
            .color(theme::TEXT_MUTED),
        text("Thinking")
            .size(theme::TEXT_11)
            .color(theme::TEXT_MUTED),
    ]
    .spacing(theme::SPACE_4)
    .align_y(Alignment::Center);
    let body = collapsible_text_block(
        collapses,
        is_expanded,
        preview,
        theme::TEXT_MUTED,
        theme::TEXT_11,
        theme::FONT_REGULAR,
        selectable_text(content, theme::TEXT_MUTED)
            .size(theme::TEXT_11)
            .into(),
    );
    let whole: Element<'a, SessionsMessage> = column![header, body].spacing(theme::SPACE_4).into();
    click_toggle(key, collapses, whole)
}

/// The message/narration body with the 3-line collapse rule: a collapsed
/// element shows a plain clickable preview; an expanded (or short) element
/// shows the markdown body parsed from `md`. `content` is the plain text used
/// for the collapse measurement (at the bubble body width); `md` is the parsed
/// markdown for the expanded view. Narration bodies render italic at
/// [`theme::NARRATION_TEXT_SIZE`]; user/assistant bodies stay at
/// [`theme::MARKDOWN_TEXT_SIZE`] regular.
fn body_block<'a>(
    ctx: &TranscriptCtx<'a>,
    key: (usize, usize),
    content: &'a str,
    md: Option<&'a [markdown::Item]>,
    is_narration: bool,
) -> Element<'a, SessionsMessage> {
    let size = if is_narration {
        theme::NARRATION_TEXT_SIZE
    } else {
        theme::MARKDOWN_TEXT_SIZE
    };
    let (is_expanded, collapses, preview) = collapse_state(ctx, key, content, size);
    let font = if is_narration {
        theme::FONT_ITALIC
    } else {
        theme::FONT_REGULAR
    };
    let expanded: Element<'a, SessionsMessage> = if let Some(md) = md {
        let settings = if is_narration {
            theme::narration_markdown_settings()
        } else {
            theme::markdown_settings()
        };
        media_markers::selectable_markdown_view(md, settings).map(SessionsMessage::LinkClicked)
    } else {
        selectable_text(content, theme::TEXT_PRIMARY)
            .size(size)
            .font(font)
            .into()
    };
    let el = collapsible_text_block(
        collapses,
        is_expanded,
        preview,
        theme::TEXT_PRIMARY,
        size,
        font,
        expanded,
    );
    click_toggle(key, collapses, el)
}

/// The tool-call result block: plain collapsible text at [`theme::TEXT_SECONDARY`]
/// (11px) with the 3-line collapse — no leading icon (results are recognizable
/// from context; "(no result)" keeps its arrow below). Results render inside
/// the assistant bubble, so they measure at the bubble body width.
fn result_block<'a>(
    ctx: &TranscriptCtx<'a>,
    key: (usize, usize),
    result: &'a str,
) -> Element<'a, SessionsMessage> {
    plain_collapsible(ctx, key, result, theme::TEXT_SECONDARY)
}

/// Render one session round as a single assistant bubble containing the
/// reasoning block, the narration body, and one tool block per call with its
/// collapsible result beneath. An empty narration slot with a decoded
/// Reasoning block promotes the reasoning into the narration slot (plain
/// text) instead of a separate Thinking block.
fn render_tool_round<'a>(
    ctx: &TranscriptCtx<'a>,
    i: usize,
    narration: Option<&'a str>,
    reasoning: Option<&'a str>,
    calls: &'a [ToolCallEntry],
) -> Element<'a, SessionsMessage> {
    let md = ctx.entry_md.get(i).and_then(|m| m.as_deref());
    let mut bubble_col = Column::new().spacing(theme::SPACE_4);

    if let Some(reasoning) = session_view::promoted_reasoning(narration, reasoning) {
        // The reasoning IS the narration for this round: render it in the
        // narration slot as plain text (md None — no markdown parse, so CoT
        // characters never become formatting) and skip the Thinking block,
        // whose text would duplicate it.
        bubble_col = bubble_col.push(body_block(ctx, (i, 0), reasoning, None, true));
    } else {
        if let Some(reasoning) = reasoning {
            bubble_col = bubble_col.push(thinking_block(ctx, (i, 1), reasoning));
        }
        if let Some(narration) = narration {
            bubble_col = bubble_col.push(body_block(ctx, (i, 0), narration, md, true));
        }
    }

    for (j, call) in calls.iter().enumerate() {
        let key = (i, 2 + j);
        // Only a result that actually collapses makes the tool block a click
        // target (toggling a short result's expansion would be a no-op).
        let collapses = call.result.as_deref().is_some_and(|result| {
            let (wrapped_lines, _) = element_measurement(
                ctx.measure_cache,
                key,
                ctx.text_width,
                false,
                result,
                theme::MARKDOWN_TEXT_SIZE,
            );
            wrapped_lines > MAX_PREVIEW_LINES
        });
        // The tool block is wrapped in a click-to-toggle (not a button) so the
        // shared tool block's hover tooltip keeps working; a short click
        // anywhere toggles the associated result's collapse, and dragging over
        // the selectable tool-args text selects instead. click_to_toggle also
        // never captures the pointer, so the tooltip stays.
        let tool_block = container(session_view::tool_block(
            &call.tool,
            session_view::ToolBlockView::Full,
        ))
        .width(Length::Fill)
        .padding([theme::PAD_2, theme::PAD_4]);
        if collapses {
            bubble_col = bubble_col.push(click_toggle(key, true, tool_block.into()));
        } else {
            bubble_col = bubble_col.push(tool_block);
        }

        match call.result.as_deref() {
            Some(result) if !result.is_empty() => {
                bubble_col = bubble_col.push(result_block(ctx, key, result));
            }
            // Empty or missing ToolResult record: the old view's explicit
            // "(no result)" indicator.
            _ => {
                bubble_col = bubble_col.push(
                    row![
                        lucide::arrow_down_to_line::<iced::Theme, iced::Renderer>()
                            .size(theme::TEXT_11)
                            .color(theme::TEXT_MUTED),
                        text("(no result)")
                            .size(theme::TEXT_10)
                            .color(theme::TEXT_SECONDARY),
                    ]
                    .spacing(theme::SPACE_4)
                    .align_y(Alignment::Center),
                );
            }
        }
    }

    // One bubble for the whole round, same container as assistant text rounds
    // (right-aligned, 75% width, author label above).
    bubble_row(crate::ChatRole::Assistant, bubble_col, None)
}

/// Render one ledger entry as a chat-bubble row: a `Message` renders its own
/// bubble, and a `ToolRound` renders a single assistant bubble containing the
/// round's reasoning, narration, and tool calls with their results.
fn render_entry<'a>(ctx: &TranscriptCtx<'a>, i: usize) -> Element<'a, SessionsMessage> {
    let md = ctx.entry_md.get(i).and_then(|m| m.as_deref());
    let entry = &ctx.entries[i];
    match entry {
        SessionEntry::Message {
            role,
            content,
            thinking,
        } => {
            let mut bubble_col = Column::new().spacing(theme::SPACE_4);
            if let Some(thinking) = thinking {
                bubble_col = bubble_col.push(thinking_block(ctx, (i, 1), thinking));
            }
            if let Some(content) = content {
                bubble_col = bubble_col.push(body_block(ctx, (i, 0), content, md, false));
            }
            if thinking.is_some() || content.is_some() {
                let menu = (ctx.truncatable && matches!(role, crate::ChatRole::User))
                    .then(|| MenuItem::new("Truncate".into(), SessionsMessage::TruncateSession(i)));
                bubble_row(*role, bubble_col, menu)
            } else {
                // Nothing to show but the author.
                author_label(*role)
            }
        }
        SessionEntry::ToolRound {
            narration,
            reasoning,
            calls,
        } => render_tool_round(ctx, i, narration.as_deref(), reasoning.as_deref(), calls),
    }
}

/// Render the transcript column for the selected session: build the chat
/// bubbles from the shared ledger and apply the 3-line collapse rule to
/// message bodies, thinking blocks, and tool results.
fn render_transcript<'a>(
    ctx: &TranscriptCtx<'a>,
    scrollable_id: &Id,
) -> Element<'a, SessionsMessage> {
    if ctx.entries.is_empty() {
        return text("No messages in this session.")
            .size(theme::TEXT_13)
            .color(theme::TEXT_MUTED)
            .into();
    }
    let mut items = Column::new().spacing(widgets::CHAT_VERTICAL_RHYTHM);
    for i in 0..ctx.entries.len() {
        items = items.push(render_entry(ctx, i));
    }
    widgets::vscroll_tracked(
        items,
        Length::Fill,
        Length::Fill,
        scrollable_id.clone(),
        SessionsMessage::ScrollChanged,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ChatRole;
    use crate::agent::registry::RunningTool;

    fn msg(role: ChatRole, content: Option<&str>) -> SessionEntry {
        SessionEntry::Message {
            role,
            content: content.map(str::to_string),
            thinking: None,
        }
    }

    fn tool_round() -> SessionEntry {
        SessionEntry::ToolRound {
            narration: Some("checking the file".to_string()),
            reasoning: None,
            calls: vec![ToolCallEntry {
                tool_call_id: "call_0".to_string(),
                tool: RunningTool {
                    name: "read".to_string(),
                    args: vec![("path".to_string(), "a.rs".to_string())],
                },
                result: Some("ok".to_string()),
            }],
        }
    }

    #[test]
    fn common_entry_prefix_empty_vs_empty() {
        assert_eq!(common_entry_prefix(&[], &[]), 0);
    }

    #[test]
    fn common_entry_prefix_identical() {
        let old = vec![msg(ChatRole::User, Some("hi")), tool_round()];
        let new = old.clone();
        assert_eq!(common_entry_prefix(&old, &new), old.len());
    }

    #[test]
    fn common_entry_prefix_pure_append() {
        let old = vec![msg(ChatRole::User, Some("hi"))];
        let mut new = old.clone();
        new.push(msg(ChatRole::Assistant, Some("hello")));
        new.push(tool_round());
        assert_eq!(common_entry_prefix(&old, &new), old.len());
    }

    #[test]
    fn common_entry_prefix_in_place_edit() {
        let old = vec![
            msg(ChatRole::User, Some("a")),
            msg(ChatRole::Assistant, Some("b")),
            msg(ChatRole::User, Some("c")),
            msg(ChatRole::Assistant, Some("d")),
        ];
        let mut new = old.clone();
        new[2] = msg(ChatRole::User, Some("edited"));
        assert_eq!(common_entry_prefix(&old, &new), 2);
    }

    #[test]
    fn common_entry_prefix_differing_lengths() {
        let old = vec![
            msg(ChatRole::User, Some("a")),
            msg(ChatRole::Assistant, Some("b")),
        ];
        let new = vec![msg(ChatRole::User, Some("a"))];
        assert_eq!(common_entry_prefix(&old, &new), 1);
    }

    #[test]
    fn transcript_error_stays_out_of_the_list_banner() {
        let mut state = SessionsState::new();
        state.selected_session = Some("s1".to_string());
        state.selected_loading = true;

        let _ = state.update(SessionsMessage::SessionError {
            key: "s1".to_string(),
            error: "read failed".to_string(),
        });

        assert_eq!(state.selected_error.as_deref(), Some("read failed"));
        assert!(!state.selected_loading);
        assert!(
            state.load_state.error().is_none(),
            "a transcript failure must not surface in the session-list banner"
        );

        // An error for a session the user has since left is ignored.
        state.selected_error = None;
        state.selected_loading = true;
        let _ = state.update(SessionsMessage::SessionError {
            key: "s2".to_string(),
            error: "stale failure".to_string(),
        });
        assert!(state.selected_error.is_none());
        assert!(state.selected_loading);
    }

    #[test]
    fn successful_transcript_load_clears_the_error() {
        let mut state = SessionsState::new();
        state.selected_session = Some("s1".to_string());
        state.selected_error = Some("old failure".to_string());
        state.selected_loading = true;

        let _ = state.update(SessionsMessage::SessionMessages("s1".to_string(), vec![]));

        assert!(state.selected_error.is_none());
        assert!(!state.selected_loading);
    }
}