mahbot 0.6.4

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
//! Logs dashboard page — live log viewing with per-tab pagination/search,
//! plus a Tool Failures tab for browsing tool error entries.
//!
//! Each tab (All Logs / Issues / Tool Failures) keeps its own entries,
//! pagination state and search query, so switching tabs never reuses another
//! tab's page index or search. The bottom bar holds pagination, this tab's
//! clear button (deletes the tab's records from the store, behind the shared
//! confirmation modal) and search; the top bar holds only the tabs.

use crate::logs::{LogEntry, LogQuery, LogStore};

use iced::advanced::text::Span;
use iced::widget::{Column, Space, button, column, container, row, stack, text};
use iced::{Alignment, Element, Length, Subscription, Task, window};
use iced_anim::Animated;
use iced_anim::transition::Easing;
use std::time::{Duration, Instant};

use iced_fonts::lucide;

use super::common::PaginatedTabState;
use super::dialog;
use super::menus::{ContextMenu, MenuItem};
use super::theme;
use super::widgets;

/// Tabs within the Logs page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogsTab {
    AllLogs,
    Issues,
    ToolFailures,
}

impl LogsTab {
    /// The level filter this tab's listing query uses — and therefore the exact
    /// scope of its clear button, which always empties the whole tab and never
    /// the searched subset. Only the log tabs have one (All Logs means every
    /// level); the Tool Failures tab does not read the logs table at all, so
    /// its `None` carries no scope.
    fn level_filter(self) -> Option<&'static str> {
        match self {
            Self::Issues => Some("ERROR,WARN"),
            Self::AllLogs | Self::ToolFailures => None,
        }
    }

    /// Label of this tab's clear button (also the title of its confirmation).
    fn clear_label(self) -> &'static str {
        match self {
            Self::AllLogs => "Clear logs",
            Self::Issues => "Clear issues",
            Self::ToolFailures => "Clear failures",
        }
    }

    /// Consequence paragraphs for this tab's clear confirmation: the scope the
    /// button names, including where the deleted records are shown elsewhere.
    fn clear_consequences(self) -> [&'static str; 3] {
        match self {
            Self::AllLogs => [
                "This permanently deletes every stored log record — informational, \
                 warning and error — for every workspace and user.",
                "The Issues view shows warnings and errors from the same records, so \
                 it is emptied too.",
                "Nothing can be recovered.",
            ],
            Self::Issues => [
                "This permanently deletes every stored warning and error record, for \
                 every workspace and user.",
                "Informational records are kept and stay in the All Logs view.",
                "Nothing can be recovered.",
            ],
            Self::ToolFailures => [
                "This permanently deletes every recorded failed tool call, for every \
                 workspace and user.",
                "Successful tool calls are kept — only the failed rows this tab lists \
                 are deleted.",
                "Nothing can be recovered.",
            ],
        }
    }
}

fn log_stream_producer() -> impl futures_util::Stream<Item = LogMessage> {
    super::common::broadcast_stream_producer(1, &super::LOG_BROADCAST, |output, item| {
        Box::pin(async move {
            match item {
                Some(json) => {
                    if let Ok(entry) = serde_json::from_str::<LogEntry>(&json) {
                        let _ = output.try_send(LogMessage::LiveEntry(entry));
                    }
                }
                None => {
                    let _ = output.try_send(LogMessage::StreamLagged);
                }
            }
        })
    })
}

#[derive(Debug, Clone)]
pub enum LogMessage {
    // Data — tagged with the originating tab and refresh generation so stale
    // async responses (issued before a newer refresh of the same tab) are
    // dropped instead of overwriting newer data.
    Refreshed(LogsTab, u64, Vec<LogEntry>, usize),
    RefreshError(LogsTab, u64, String),

    // Live stream
    LiveEntry(LogEntry),
    StreamLagged,

    // Search
    SearchInput(super::editor_widget::EditorAction),

    // Tab switching
    TabSelected(LogsTab),

    // Debounced refresh after text input (~300ms). Carries the tab whose
    // query changed so the refresh still targets that tab if the user
    // switches tabs within the debounce window.
    DebouncedRefresh(u64, LogsTab),

    // Pagination
    PrevPage,
    NextPage,

    /// Per-frame tick for the fade-in animation.
    AnimTick(Instant),

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

    /// Cmd+F keyboard shortcut — highlight the search input.
    FocusSearch,

    /// Copy a log entry's full formatted content to the clipboard (right-click
    /// context-menu action). Carries the entry so the formatting happens in
    /// `update()`, not in the per-frame `view()`.
    CopyEntry(LogEntry),

    /// Clear button pressed — ask for confirmation before deleting anything.
    RequestClear,
    /// The confirmation's danger action — delete the pending tab's records.
    ClearConfirmed,
    /// The confirmation was dismissed (Keep/backdrop/Escape) — nothing deleted.
    ClearDismissed,
    /// A clear finished. `Ok` = the delete committed; `Err` carries the failure
    /// to surface in that tab's error banner. Records already buffered by the
    /// log writer may still land after it.
    Cleared(LogsTab, Result<(), String>),

    /// Bridged Tool Failures sub-messages.
    ToolFailures(super::tool_failures::ToolFailuresMessage),
}

/// Per-tab state shared by the All Logs and Issues tabs. Each tab keeps its
/// own entries, load state, pagination and search query so switching tabs
/// never reuses another tab's page index or query.
type LogsTabData = PaginatedTabState<LogEntry>;

pub struct LogsState {
    /// All Logs tab data (live-streamed).
    all_logs: LogsTabData,
    /// Issues tab data (ERROR/WARN only).
    issues: LogsTabData,
    /// Tool Failures tab data (delegated sub-state).
    tool_failures_state: super::tool_failures::ToolFailuresState,

    // Tab state
    active_tab: LogsTab,

    /// Visual highlight for search input (Cmd+F).
    focus_search: bool,

    /// Timestamp of the most recently received live entry (for fade-in animation).
    newest_entry_timestamp: Option<String>,
    /// Fade progress: 0.0 = just appeared, 1.0 = fully settled.
    fade_anim: Animated<f32>,
    /// Debounce state for search-text input filtering.
    debounce: super::common::DebounceState,
    /// Buffer for the shared search input (bound to the active tab's query).
    search_buffer: super::common::SingleLineEditorState,

    /// Tab whose clear button awaits confirmation. `Some` while the confirm
    /// modal is open — nothing is deleted without it.
    pending_clear: Option<LogsTab>,
}

impl LogsState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            all_logs: PaginatedTabState::new(50),
            issues: PaginatedTabState::new(50),
            tool_failures_state: super::tool_failures::ToolFailuresState::new(),
            active_tab: LogsTab::AllLogs,
            focus_search: false,
            newest_entry_timestamp: None,
            fade_anim: Animated::transition(
                0.0f32,
                Easing::EASE_OUT.with_duration(Duration::from_millis(theme::ANIM_LOG_FADE_MS)),
            ),
            debounce: super::common::DebounceState::new(),
            search_buffer: super::common::SingleLineEditorState::new(""),
            pending_clear: None,
        }
    }

    /// Immutable access to one log tab's data. Returns `None` for the Tool
    /// Failures tab (handled via `tool_failures_state`).
    fn tab_data(&self, tab: LogsTab) -> Option<&LogsTabData> {
        match tab {
            LogsTab::AllLogs => Some(&self.all_logs),
            LogsTab::Issues => Some(&self.issues),
            LogsTab::ToolFailures => None,
        }
    }

    /// Mutable access to one log tab's data. Returns `None` for the Tool
    /// Failures tab (handled via `tool_failures_state`).
    fn tab_data_mut(&mut self, tab: LogsTab) -> Option<&mut LogsTabData> {
        match tab {
            LogsTab::AllLogs => Some(&mut self.all_logs),
            LogsTab::Issues => Some(&mut self.issues),
            LogsTab::ToolFailures => None,
        }
    }

    /// The active tab's search query (bound to the shared search input).
    fn active_search(&self) -> &str {
        match self.active_tab {
            LogsTab::AllLogs => &self.all_logs.search,
            LogsTab::Issues => &self.issues.search,
            LogsTab::ToolFailures => self.tool_failures_state.search(),
        }
    }

    /// Reset pagination for whichever tab is currently active.
    fn reset_pagination_for_active_tab(&mut self) {
        match self.tab_data_mut(self.active_tab) {
            Some(data) => data.pagination.reset(),
            None => self.tool_failures_state.reset_pagination(),
        }
    }

    /// Refresh whichever tab is currently active.
    fn refresh_active_tab(&mut self, log_store: &LogStore) -> Task<LogMessage> {
        self.refresh_tab(log_store, self.active_tab)
    }

    /// Public entry point: refresh the currently active tab (used at boot).
    pub fn refresh(&mut self, log_store: &LogStore) -> Task<LogMessage> {
        self.refresh_active_tab(log_store)
    }

    /// Issue a refresh for one specific tab, tagging the async response with
    /// its origin tab and a generation counter so stale responses (issued
    /// before a newer refresh of the same tab) are dropped by the handler.
    /// Total over all three tabs: the Tool Failures tab refreshes through
    /// its own state/store path instead.
    fn refresh_tab(&mut self, log_store: &LogStore, tab: LogsTab) -> Task<LogMessage> {
        // Tool Failures has its own state and store path.
        let Some(data) = self.tab_data_mut(tab) else {
            return self
                .tool_failures_state
                .refresh()
                .map(LogMessage::ToolFailures);
        };
        let generation = data.begin_refresh();
        let query = LogQuery {
            level: tab.level_filter().map(str::to_owned),
            target: None,
            search: crate::util::none_if_empty(&data.search),
            since: None,
            limit: Some(data.pagination.page_size),
            offset: Some(data.pagination.offset()),
        };
        let store = log_store.clone();
        Task::perform(
            async move {
                store
                    .query(&query)
                    .await
                    .map(|(entries, total)| (generation, entries, total))
                    .map_err(|e| (generation, e.to_string()))
            },
            move |res| match res {
                Ok((generation, entries, total)) => {
                    LogMessage::Refreshed(tab, generation, entries, total)
                }
                Err((generation, e)) => LogMessage::RefreshError(tab, generation, e),
            },
        )
    }

    pub fn subscription(&self) -> Subscription<LogMessage> {
        // Live log stream only while the All Logs tab is active. Frame ticks are subscribed only while the fade animation is running —
        // an always-on frames() subscription closes a self-sustaining redraw
        // loop (redraw → AnimTick → redraw).
        let mut subs: Vec<Subscription<LogMessage>> = Vec::new();
        if self.active_tab == LogsTab::AllLogs {
            subs.push(iced::Subscription::run(log_stream_producer));
        }
        if self.fade_anim.is_animating() {
            subs.push(window::frames().map(LogMessage::AnimTick));
        }
        Subscription::batch(subs)
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, msg: LogMessage, log_store: &LogStore) -> Task<LogMessage> {
        match msg {
            LogMessage::Refreshed(tab, generation, entries, total) => {
                // A ToolFailures-tagged refresh cannot originate from
                // `refresh_tab`; drop it defensively rather than panic.
                let Some(data) = self.tab_data_mut(tab) else {
                    return Task::none();
                };
                if data.handle_refreshed(generation, entries, total) {
                    return self.refresh_tab(log_store, tab);
                }
                Task::none()
            }
            LogMessage::RefreshError(tab, generation, e) => {
                let Some(data) = self.tab_data_mut(tab) else {
                    return Task::none();
                };
                data.handle_refresh_error(generation, e, false);
                Task::none()
            }
            LogMessage::RequestClear => {
                self.pending_clear = Some(self.active_tab);
                Task::none()
            }
            LogMessage::ClearDismissed => {
                self.pending_clear = None;
                Task::none()
            }
            LogMessage::ClearConfirmed => {
                // The dialog names the tab it was opened for, not whichever tab
                // is active now, so a tab switch behind the modal cannot retarget it.
                let Some(tab) = self.pending_clear.take() else {
                    return Task::none();
                };
                let store = log_store.clone();
                Task::perform(
                    async move {
                        // Explicit per tab: a catch-all would turn a future tab
                        // into an unfiltered `DELETE FROM logs`.
                        let result = match tab {
                            LogsTab::AllLogs => store.clear_logs(None).await,
                            LogsTab::Issues => {
                                store.clear_logs(LogsTab::Issues.level_filter()).await
                            }
                            LogsTab::ToolFailures => store.clear_tool_errors().await,
                        };
                        result.map(|_| ()).map_err(|e| e.to_string())
                    },
                    move |result| LogMessage::Cleared(tab, result),
                )
            }
            LogMessage::Cleared(tab, result) => match result {
                Ok(()) => {
                    // Post-clear: the pressed tab returns to its first page and
                    // keeps its typed search; its count is re-read by the
                    // refresh below, never adjusted in place.
                    match self.tab_data_mut(tab) {
                        Some(data) => data.clear_entries(),
                        None => self.tool_failures_state.clear_entries(),
                    }
                    let pressed = self.refresh_tab(log_store, tab);
                    if tab == LogsTab::ToolFailures {
                        return pressed;
                    }
                    // Both log tabs read the same table, so the other one holds
                    // rows this clear just deleted — and it may be the tab on
                    // screen. Drop that copy and re-read it too.
                    let (sibling, sibling_tab) = if tab == LogsTab::AllLogs {
                        (&mut self.issues, LogsTab::Issues)
                    } else {
                        (&mut self.all_logs, LogsTab::AllLogs)
                    };
                    sibling.entries.clear();
                    Task::batch([pressed, self.refresh_tab(log_store, sibling_tab)])
                }
                Err(e) => {
                    // This surface has no completion-notice plumbing; its
                    // per-tab error banner is the channel for a failed clear.
                    match self.tab_data_mut(tab) {
                        Some(data) => data.load_state.fail(e),
                        None => self.tool_failures_state.fail(e),
                    }
                    Task::none()
                }
            },
            LogMessage::LiveEntry(entry) => {
                // Live entries only arrive while the All Logs tab is active
                // (the subscription is gated in `subscription()`).
                let data = &mut self.all_logs;
                // Only prepend live entries when on page 0 (the live view).
                // Other pages are static snapshots from the database.
                if data.pagination.page != 0 {
                    return Task::none();
                }

                // Client-side search filter matching this tab's query (the
                // level filter comes from the DB query for the Issues tab,
                // which never receives live entries).
                let passes = data.search.is_empty()
                    || entry
                        .message
                        .to_lowercase()
                        .contains(&data.search.to_lowercase())
                    || entry
                        .target
                        .to_lowercase()
                        .contains(&data.search.to_lowercase());

                if passes {
                    data.entries.insert(0, entry);
                    data.pagination.total += 1;
                    // Auto-evict: keep exactly page_size entries visible.
                    data.entries.truncate(data.pagination.page_size);
                    // Mark this entry as newest so the view can fade it in.
                    self.newest_entry_timestamp = data.entries.first().map(|e| e.timestamp.clone());
                    // Reset the fade animation so it goes 0→1 for the new entry.
                    self.fade_anim = Animated::transition(
                        0.0f32,
                        Easing::EASE_OUT
                            .with_duration(Duration::from_millis(theme::ANIM_LOG_FADE_MS)),
                    );
                    self.fade_anim.set_target(1.0f32);
                }
                Task::none()
            }
            LogMessage::AnimTick(instant) => {
                self.fade_anim.tick(instant);
                Task::none()
            }
            LogMessage::StreamLagged => {
                // Only delivered while the All Logs stream is active.
                self.refresh_active_tab(log_store)
            }
            LogMessage::SearchInput(action) => {
                // Single-line Tab moves focus rather than editing.
                if let Some(task) = super::common::focus_navigation_task(&action) {
                    return task;
                }
                // The search input is bound to the active tab's own query.
                let changes_text = action.changes_text();
                self.search_buffer.apply_action(action);
                let text = self.search_buffer.text();
                match self.tab_data_mut(self.active_tab) {
                    Some(data) => data.search = text,
                    None => self.tool_failures_state.set_search(text),
                }
                // Only text changes re-trigger the debounced refresh; cursor
                // movement emits actions too but shouldn't restart the timer.
                if !changes_text {
                    return Task::none();
                }
                self.reset_pagination_for_active_tab();
                // Tag the debounced refresh with the tab whose query changed
                // so it still targets that tab if the user switches away
                // within the debounce window.
                let tab = self.active_tab;
                self.debounce
                    .trigger(300)
                    .map(move |g| LogMessage::DebouncedRefresh(g, tab))
            }
            LogMessage::DebouncedRefresh(generation, tab) => {
                if !self.debounce.should_process(generation) {
                    return Task::none();
                }
                self.refresh_tab(log_store, tab)
            }
            LogMessage::PrevPage => match self.tab_data_mut(self.active_tab) {
                Some(data) => {
                    if data.pagination.prev_page() {
                        return self.refresh_active_tab(log_store);
                    }
                    Task::none()
                }
                None => self
                    .tool_failures_state
                    .prev_page()
                    .map(LogMessage::ToolFailures),
            },
            LogMessage::NextPage => match self.tab_data_mut(self.active_tab) {
                Some(data) => {
                    if data.pagination.next_page() {
                        return self.refresh_active_tab(log_store);
                    }
                    Task::none()
                }
                None => self
                    .tool_failures_state
                    .next_page()
                    .map(LogMessage::ToolFailures),
            },
            LogMessage::Escape => {
                // Escape never confirms: while the confirm modal is open it only
                // dismisses it.
                if self.pending_clear.take().is_some() {
                    return Task::none();
                }
                self.focus_search = false;
                Task::none()
            }
            LogMessage::FocusSearch => {
                self.focus_search = true;
                Task::none()
            }
            LogMessage::CopyEntry(entry) => {
                // Silent copy — no toast, matching the app's clipboard
                // convention for context-menu actions (Home bubbles, editor).
                iced::clipboard::write(format_log_entry(&entry))
            }
            LogMessage::TabSelected(tab) => {
                self.active_tab = tab;
                // Sync the shared search buffer to the newly-active tab's query.
                let active_search = self.active_search().to_string();
                self.search_buffer.set_text(&active_search);
                self.refresh_active_tab(log_store)
            }
            LogMessage::ToolFailures(msg) => self
                .tool_failures_state
                .update(msg)
                .map(LogMessage::ToolFailures),
        }
    }

    /// Build a tab button element. Returns a highlighted container when the
    /// tab is active, or a plain container when inactive.
    fn tab_button(label: &str, tab: LogsTab, active_tab: LogsTab) -> Element<'_, LogMessage> {
        let is_active = tab == active_tab;
        let color = if is_active {
            theme::ACCENT
        } else {
            theme::TEXT_FAINT
        };
        let b = button(
            container(text(label.to_string()).size(theme::TEXT_13).color(color))
                .padding([theme::PAD_6, theme::PAD_14]),
        )
        .style(theme::button_text)
        .on_press(LogMessage::TabSelected(tab));
        if is_active {
            container(b).style(theme::container_bar).into()
        } else {
            container(b).into()
        }
    }

    pub fn view(&self) -> Element<'_, LogMessage> {
        // ── Tab bar (top bar: tabs only) ──────────────────────────
        let all_logs_btn = Self::tab_button("All Logs", LogsTab::AllLogs, self.active_tab);
        let issues_btn = Self::tab_button("Issues", LogsTab::Issues, self.active_tab);
        let tf_btn = Self::tab_button("Tool Failures", LogsTab::ToolFailures, self.active_tab);

        let tab_bar = container(
            row![all_logs_btn, issues_btn, tf_btn]
                .spacing(theme::SPACE_2)
                .align_y(Alignment::Center),
        )
        .width(Length::Fill)
        .style(theme::surface_container_style);

        // ── Tab content ────────────────────────────────────────────
        let body: Element<'_, LogMessage> = match self.active_tab {
            LogsTab::ToolFailures => self
                .tool_failures_state
                .view()
                .map(LogMessage::ToolFailures),
            LogsTab::AllLogs | LogsTab::Issues => self.logs_view(),
        };

        // ── Log-writer persistence warning banner ──────────────────
        // Surfaces log-store insert failures (the writer task cannot use
        // tracing to report them without recursing into itself).
        let write_error_banner = Self::write_error_banner();

        // ── Bottom bar: pagination + clear + search ────────────────
        let bottom_bar = self.bottom_bar();

        let content = column![tab_bar, write_error_banner, body, bottom_bar]
            .width(Length::Fill)
            .height(Length::Fill);

        let page = widgets::page_bare(content);
        // Confirm-dialog overlay: the page is stack child 0, the dialog (or a
        // type-stable placeholder) child 1 — the shapes never change, so the
        // page keeps its widget state as the modal opens/closes (same pattern
        // as the Running page).
        let confirm_layer: Element<'_, LogMessage> = match self.pending_clear {
            Some(tab) => Self::clear_confirm_dialog(tab),
            None => stack([widgets::empty_stack_placeholder()]).into(),
        };
        stack([page, confirm_layer]).into()
    }

    /// The clear confirmation for `tab`: the shared confirm-dialog/backdrop
    /// pair, with the tab's scope named in the title, the danger button and the
    /// listed consequences. There is no undo, so nothing is deleted without it.
    fn clear_confirm_dialog(tab: LogsTab) -> Element<'static, LogMessage> {
        widgets::modal_backdrop(
            dialog::confirm_dialog(
                dialog::dialog_title(format!("{}?", tab.clear_label())),
                dialog::dialog_body(tab.clear_consequences()),
                [
                    dialog::DialogAction::secondary("Keep records", LogMessage::ClearDismissed),
                    dialog::DialogAction::danger(tab.clear_label(), LogMessage::ClearConfirmed),
                ],
            ),
            LogMessage::ClearDismissed,
            0.5,
        )
    }

    /// Render a warning banner when the log-writer task has observed DB insert
    /// failures (visible on the Logs page — the sanctioned observability
    /// surface for log-persistence outages). Returns an empty element when
    /// there is nothing to report.
    fn write_error_banner() -> Element<'static, LogMessage> {
        let info = crate::logs::log_write_error_info();
        if info.count == 0 {
            return Space::new().height(0).into();
        }

        let last = info
            .last_timestamp
            .as_deref()
            .map(|ts| format!(" (last: {ts})"))
            .unwrap_or_default();
        let detail = info
            .last_message
            .as_deref()
            .unwrap_or("unknown log insert failure");
        let stopped = if info.panic_state.writer_stopped {
            " Log persistence is STOPPED until the daemon restarts."
        } else {
            ""
        };

        container(
            row![
                lucide::triangle_alert::<iced::Theme, iced::Renderer>()
                    .size(theme::TEXT_14)
                    .color(theme::STATUS_WARNING),
                Space::new().width(theme::SPACE_6),
                text(format!(
                    "Log store write failures: {} — durable log persistence is degraded{last}. \
                     Latest error: {detail}{stopped}",
                    info.count
                ))
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY),
            ]
            .align_y(Alignment::Center),
        )
        .width(Length::Fill)
        .padding([theme::PAD_4, theme::PAD_8])
        .style(|_| {
            theme::container_style(iced::Color::TRANSPARENT, 4.0, 1.0, theme::STATUS_WARNING)
        })
        .into()
    }

    /// Render the bottom bar: pagination controls, the active tab's clear
    /// button and the search input, all bound to the active tab.
    fn bottom_bar(&self) -> Element<'_, LogMessage> {
        let (page, total_pages) = match self.tab_data(self.active_tab) {
            Some(d) => (d.pagination.page, d.pagination.total_pages()),
            None => (
                self.tool_failures_state.page(),
                self.tool_failures_state.total_pages(),
            ),
        };

        // Pagination cluster — hidden entirely when there are no pages so the
        // "Page X of Y" indicator never shows an invalid page.
        let pagination_cluster: Element<'_, LogMessage> = if total_pages == 0 {
            Space::new().width(0).into()
        } else {
            let prev_button = button(text("← Prev").size(theme::TEXT_12))
                .style(theme::button_text)
                .on_press_maybe(if page > 0 {
                    Some(LogMessage::PrevPage)
                } else {
                    None
                });
            let next_button = button(text("Next →").size(theme::TEXT_12))
                .style(theme::button_text)
                .on_press_maybe(if page + 1 < total_pages {
                    Some(LogMessage::NextPage)
                } else {
                    None
                });
            row![
                prev_button,
                Space::new().width(theme::SPACE_8),
                text(format!("Page {} of {}", page + 1, total_pages))
                    .size(theme::TEXT_12)
                    .color(theme::TEXT_SECONDARY),
                Space::new().width(theme::SPACE_8),
                next_button,
            ]
            .align_y(Alignment::Center)
            .into()
        };

        // Clear this tab — sits between the paging controls and the search box.
        // Always rendered: a tab refilling from live activity right after a
        // clear must stay clearable, so this is not tied to the paging state.
        let clear_button = button(text(self.active_tab.clear_label()).size(theme::TEXT_12))
            .style(theme::button_text_danger)
            .on_press(LogMessage::RequestClear);

        let search_input: Element<'_, LogMessage> = if self.focus_search {
            container(super::widgets::single_line_editor(
                &self.search_buffer.buffer,
                "search",
                false,
                Length::Fill,
                Some(iced::widget::Id::new("logs_search")),
                LogMessage::SearchInput,
            ))
            .padding(theme::PAD_2)
            .style(|_| theme::container_style(iced::Color::TRANSPARENT, 4.0, 1.0, theme::ACCENT))
            .into()
        } else {
            super::widgets::single_line_editor(
                &self.search_buffer.buffer,
                "search",
                false,
                Length::Fill,
                Some(iced::widget::Id::new("logs_search")),
                LogMessage::SearchInput,
            )
        };

        let search_group = row![
            lucide::search::<iced::Theme, iced::Renderer>()
                .size(theme::TEXT_12)
                .color(theme::TEXT_MUTED),
            Space::new().width(theme::SPACE_4),
            search_input,
        ]
        .align_y(Alignment::Center);

        let bottom_row = row![
            pagination_cluster,
            Space::new().width(theme::SPACE_8),
            clear_button,
            Space::new().width(Length::Fill),
            search_group,
        ]
        .align_y(Alignment::Center)
        .width(Length::Fill);

        container(bottom_row)
            .width(Length::Fill)
            .padding([theme::PAD_8, theme::PAD_24])
            .style(theme::surface_container_style)
            .into()
    }

    /// Render the Logs/Issues tab content (entries list). Pagination lives in
    /// the shared bottom bar.
    fn logs_view(&self) -> Element<'_, LogMessage> {
        // Only the log tabs reach this view (the caller routes Tool Failures
        // separately); fall back to the Tool Failures view rather than panic
        // if a future caller misroutes.
        let Some(data) = self.tab_data(self.active_tab) else {
            return self
                .tool_failures_state
                .view()
                .map(LogMessage::ToolFailures);
        };
        let mut content = Column::new();

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

        // Log entries
        if data.load_state.loading() && !data.load_state.has_loaded() {
            content = content.push(widgets::scroll_h_inset(widgets::loading_text()));
        } else if data.entries.is_empty() {
            content = content.push(widgets::empty_state_placeholder(
                lucide::activity::<iced::Theme, iced::Renderer>(),
                "No log entries",
                theme::TEXT_MUTED,
            ));
        } else {
            let entries_view = {
                let fade_progress = *self.fade_anim.value();
                let newest_ts = self.newest_entry_timestamp.clone();
                let scroll = widgets::vscroll(
                    Column::with_children(
                        data.entries
                            .iter()
                            .map(|entry| {
                                let is_newest = newest_ts.as_deref() == Some(&entry.timestamp);
                                let rendered = if is_newest && fade_progress < 1.0 {
                                    // Fade-in: render with animated background opacity
                                    LogsState::render_log_entry(entry, fade_progress)
                                } else {
                                    LogsState::render_log_entry(entry, 1.0)
                                };
                                // Per-row context menu: right-click copies the
                                // full entry in formatted form. Wrapping only
                                // the row — not the column — keeps the
                                // inter-row spacing a fall-through (same
                                // convention as the per-bubble menus on the
                                // Home page). Left-click drag selection on the
                                // row is unaffected: ContextMenu forwards all
                                // non-right-click events to the underlay.
                                let row: Element<'_, LogMessage> = ContextMenu::new(
                                    rendered,
                                    vec![MenuItem::new(
                                        "Copy".into(),
                                        LogMessage::CopyEntry(entry.clone()),
                                    )],
                                )
                                .into();
                                row
                            })
                            .collect::<Vec<_>>(),
                    )
                    .spacing(theme::SPACE_2),
                );

                // New live entries insert at position 0, so no scrolling is
                // needed to keep the latest entry visible.

                scroll
            };

            content = content.push(entries_view);
        }

        widgets::page(content)
    }

    fn render_log_entry(entry: &LogEntry, fade_progress: f32) -> Element<'_, LogMessage> {
        let (level_color, level_bg) = theme::log_level_color(&entry.level);

        // One selectable Rich widget per entry so a whole log line can be
        // copied in a single drag. Pills are emulated with span highlights.
        let mut spans: Vec<Span<'_, (), iced::Font>> = vec![
            Span::new(theme::format_hhmmss(&entry.timestamp))
                .size(theme::TEXT_10)
                .color(theme::TEXT_MUTED),
            Span::new("  ").size(theme::TEXT_10),
            Span::new(&entry.level)
                .size(theme::TEXT_10)
                .color(level_color)
                .background(level_bg)
                .border(iced::border::rounded(4))
                .padding([theme::PAD_1, theme::PAD_6]),
            Span::new("  ").size(theme::TEXT_10),
        ];
        if !entry.agent_role.is_empty() {
            let (role_color, role_bg) = theme::role_badge_color(&entry.agent_role);
            spans.push(
                Span::new(&entry.agent_role)
                    .size(theme::TEXT_10)
                    .color(role_color)
                    .background(role_bg)
                    .border(iced::border::rounded(4))
                    .padding([theme::PAD_1, theme::PAD_6]),
            );
            spans.push(Span::new("  ").size(theme::TEXT_10));
        }
        spans.push(
            Span::new(&entry.target)
                .size(theme::TEXT_11)
                .color(theme::TEXT_SECONDARY),
        );
        if !entry.workspace.is_empty() {
            spans.push(Span::new("  ").size(theme::TEXT_10));
            spans.push(
                Span::new(&entry.workspace)
                    .size(theme::TEXT_10)
                    .color(theme::TEXT_MUTED),
            );
        }

        spans.push(Span::new("\n").size(theme::TEXT_10));
        spans.push(
            Span::new(&entry.message)
                .size(theme::TEXT_13)
                .color(theme::TEXT_PRIMARY)
                .font(super::JETBRAINS_MONO),
        );

        // Extra fields as key-value tags
        if let Some(obj) = entry.fields.as_object() {
            for (key, value) in obj {
                if key == "message" {
                    continue;
                }
                // Cap the tag text so long fields (e.g. error_chain) render
                // as readable tags instead of overflowing the row; the full
                // value stays queryable in the log store and is copied in
                // full via the row's "Copy" context menu.
                let val_str = crate::util::truncate(&field_value_str(value), 200);
                spans.push(Span::new("\n").size(theme::TEXT_10));
                spans.push(
                    Span::new(format!("{key}: {val_str}"))
                        .size(theme::TEXT_10)
                        .color(theme::TEXT_SECONDARY),
                );
            }
        }

        let rich: iced_selection::text::Rich<'_, (), LogMessage, iced::Theme, iced::Renderer> =
            iced_selection::text::Rich::from_iter(spans)
                .style(|_t| iced_selection::text::Style {
                    color: None,
                    selection: theme::ACCENT_DIM,
                })
                .width(Length::Fill);

        if fade_progress < 1.0 {
            // Fade-in: interpolate background/border alpha from 0.6 → 1.0
            container(rich)
                .padding(theme::PAD_6)
                .style(move |_theme: &iced::Theme| container::Style {
                    background: Some(iced::Background::Color(iced::Color::from_rgba(
                        theme::BG_SURFACE.r,
                        theme::BG_SURFACE.g,
                        theme::BG_SURFACE.b,
                        0.6 + 0.4 * fade_progress,
                    ))),
                    border: iced::Border {
                        radius: 4.0.into(),
                        width: 1.0,
                        color: iced::Color::from_rgba(
                            theme::BORDER.r,
                            theme::BORDER.g,
                            theme::BORDER.b,
                            0.6 + 0.4 * fade_progress,
                        ),
                    },
                    ..container::Style::default()
                })
                .into()
        } else {
            container(rich)
                .padding(theme::PAD_6)
                .style(theme::surface_card_style)
                .into()
        }
    }
}

/// Render a stored log-field value as text: strings verbatim, everything else
/// via serde_json's Display (numbers/bools as literals, nested JSON compact).
/// Shared by the row renderer (which then truncates) and the clipboard format
/// (which must stay untruncated).
#[must_use]
fn field_value_str(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Format a [`LogEntry`] for clipboard copy ("Copy" context-menu action): the
/// full raw RFC 3339 timestamp and level on the first line, a header line with
/// the available role/agent/target/workspace parts, then the complete
/// untruncated message, then each remaining field as a `key: value` line.
///
/// Concrete layout (only the parts present in the entry are emitted; the
/// header line is omitted entirely when no role/agent/target/workspace part
/// exists):
///
/// ```text
/// 2026-08-17T20:15:44.581360Z  ERROR
/// role: engineer  agent: ticket_42_engineer  target: run_agent  workspace: mahbot
///
/// The full untruncated message, possibly spanning multiple lines.
/// error_chain: crate::foo at src/foo.rs:42
/// attempt: 3
/// ```
///
/// Field lines iterate the stored fields JSON in **sorted key order** (the
/// format function sorts explicitly, so the output is deterministic regardless
/// of serde_json's `preserve_order` feature state) and skip only the `message`
/// key, mirroring the row renderer. Keys that duplicate header parts (e.g.
/// `agent_id`/`role` inside fields) are kept: the fields section is a faithful
/// dump of the stored JSON, exactly as the row displays them. Non-string
/// values render via [`field_value_str`] — numbers/bools as literals, nested
/// JSON compact.
#[must_use]
fn format_log_entry(entry: &LogEntry) -> String {
    let mut out = String::new();
    out.push_str(&entry.timestamp);
    out.push_str("  ");
    out.push_str(&entry.level);

    // Header: only the parts that are present, fixed order, two-space gaps.
    let mut header: Vec<String> = Vec::new();
    if !entry.agent_role.is_empty() {
        header.push(format!("role: {}", entry.agent_role));
    }
    if !entry.agent_id.is_empty() {
        header.push(format!("agent: {}", entry.agent_id));
    }
    if !entry.target.is_empty() {
        header.push(format!("target: {}", entry.target));
    }
    if !entry.workspace.is_empty() {
        header.push(format!("workspace: {}", entry.workspace));
    }
    if !header.is_empty() {
        out.push('\n');
        out.push_str(&header.join("  "));
    }

    out.push_str("\n\n");
    out.push_str(&entry.message);

    if let Some(obj) = entry.fields.as_object() {
        // Sort explicitly: serde_json's Map is a BTreeMap in this build
        // (sorted), but `preserve_order` could be enabled by feature
        // unification elsewhere in the graph — the sort keeps the copy format
        // deterministic either way.
        let mut keys: Vec<&String> = obj.keys().collect();
        keys.sort();
        for key in keys {
            if key == "message" {
                continue;
            }
            out.push('\n');
            out.push_str(key);
            out.push_str(": ");
            out.push_str(&field_value_str(&obj[key]));
        }
    }
    out
}

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

    fn entry() -> LogEntry {
        LogEntry {
            timestamp: "2026-08-17T20:15:44.581360Z".to_string(),
            level: "ERROR".to_string(),
            target: "run_agent".to_string(),
            message: "Agent failed".to_string(),
            // Written out of order on purpose: fields are emitted in sorted
            // key order, so the fixture order must not leak into the output.
            fields: json!({
                "error_chain": "crate::foo at src/foo.rs:42",
                "message": "not copied",
                "attempt": 3,
                "agent_id": "ticket_42_engineer",
                "role": "engineer",
            }),
            agent_id: "ticket_42_engineer".to_string(),
            agent_role: "engineer".to_string(),
            workspace: "mahbot".to_string(),
        }
    }

    #[test]
    fn format_log_entry_full_layout() {
        let out = format_log_entry(&entry());
        assert_eq!(
            out,
            "2026-08-17T20:15:44.581360Z  ERROR\n\
             role: engineer  agent: ticket_42_engineer  target: run_agent  workspace: mahbot\n\
             \n\
             Agent failed\n\
             agent_id: ticket_42_engineer\n\
             attempt: 3\n\
             error_chain: crate::foo at src/foo.rs:42\n\
             role: engineer"
        );
    }

    #[test]
    fn format_log_entry_minimal_omits_header_and_empty_fields() {
        let entry = LogEntry {
            timestamp: "2026-08-17T20:15:44.581360Z".to_string(),
            level: "INFO".to_string(),
            target: String::new(),
            message: "plain message".to_string(),
            ..Default::default()
        };
        let out = format_log_entry(&entry);
        assert_eq!(
            out,
            "2026-08-17T20:15:44.581360Z  INFO\n\
             \n\
             plain message"
        );
    }
}