mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Logs dashboard page — live log viewing with per-view pagination and search over the log store.
//!
//! The page has no rail entry: the dashboard's Cmd+L (Ctrl+L elsewhere) shortcut is its only
//! way in. Each view (All Logs / Only Issues) keeps its own entries, pagination state and search
//! query, so switching views never reuses another view's page index or search.

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

use iced::advanced::text::Span;
use iced::widget::{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::PaginatedViewState;
use super::dialog;
use super::menus::{ContextMenu, MenuItem};
use super::theme;
use super::widgets;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogsView {
    AllLogs,
    Issues,
}

impl LogsView {
    /// The level filter this view's query uses — and therefore the exact scope of its clear
    /// button, which always empties the whole view and never the searched subset.
    fn level_filter(self) -> Option<&'static str> {
        match self {
            Self::Issues => Some("ERROR,WARN"),
            Self::AllLogs => None,
        }
    }

    fn switch_label(self) -> &'static str {
        match self {
            Self::AllLogs => "All Logs",
            Self::Issues => "Only Issues",
        }
    }

    fn clear_label(self) -> &'static str {
        match self {
            Self::AllLogs => "Clear logs",
            Self::Issues => "Clear issues",
        }
    }

    /// Consequence paragraphs for this view's clear confirmation, 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 not touched and stay in the All Logs view.",
                "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 view and refresh generation, so stale async responses
    // are dropped instead of overwriting newer data.
    Refreshed(LogsView, u64, Vec<LogEntry>, usize),
    RefreshError(LogsView, u64, String),

    LiveEntry(LogEntry),
    StreamLagged,

    SearchInput(super::editor_widget::EditorAction),

    ViewSelected(LogsView),

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

    PrevPage,
    NextPage,

    AnimTick(Instant),

    Escape,

    FocusSearch,

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

    RequestClear,
    ClearConfirmed,
    ClearDismissed,
    /// A clear finished. `Ok` = the delete committed; `Err` carries the failure to surface in
    /// that view's error banner. Records already buffered by the log writer may still land.
    Cleared(LogsView, Result<(), String>),
}

/// Per-view state shared by the All Logs and Issues views; each keeps its own entries, load
/// state, pagination and query.
type LogsViewData = PaginatedViewState<LogEntry>;

pub struct LogsState {
    all_logs: LogsViewData,
    issues: LogsViewData,

    active_view: LogsView,

    focus_search: bool,

    newest_entry_timestamp: Option<String>,
    fade_anim: Animated<f32>,
    debounce: super::common::DebounceState,
    search_buffer: super::common::SingleLineEditorState,

    /// View whose clear button awaits confirmation. Nothing is deleted without it.
    pending_clear: Option<LogsView>,
}

impl LogsState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            all_logs: PaginatedViewState::new(50),
            issues: PaginatedViewState::new(50),
            active_view: LogsView::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,
        }
    }

    fn view_data(&self, view: LogsView) -> &LogsViewData {
        match view {
            LogsView::AllLogs => &self.all_logs,
            LogsView::Issues => &self.issues,
        }
    }

    fn view_data_mut(&mut self, view: LogsView) -> &mut LogsViewData {
        match view {
            LogsView::AllLogs => &mut self.all_logs,
            LogsView::Issues => &mut self.issues,
        }
    }

    fn active_search(&self) -> &str {
        &self.view_data(self.active_view).search
    }

    fn reset_pagination_for_active_view(&mut self) {
        self.view_data_mut(self.active_view).pagination.reset();
    }

    fn refresh_active_view(&mut self, log_store: &LogStore) -> Task<LogMessage> {
        self.refresh_view(log_store, self.active_view)
    }

    pub fn refresh(&mut self, log_store: &LogStore) -> Task<LogMessage> {
        self.refresh_active_view(log_store)
    }

    /// Issue a refresh for one view, tagging the async response with its origin view and a
    /// generation counter so stale responses are dropped by the handler.
    fn refresh_view(&mut self, log_store: &LogStore, view: LogsView) -> Task<LogMessage> {
        let data = self.view_data_mut(view);
        let generation = data.begin_refresh();
        let query = LogQuery {
            level: view.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(view, generation, entries, total)
                }
                Err((generation, e)) => LogMessage::RefreshError(view, generation, e),
            },
        )
    }

    pub fn subscription(&self) -> Subscription<LogMessage> {
        // Live log stream only while the All Logs view is active. Frame ticks are subscribed only
        // while the fade animation runs — an always-on `frames()` subscription closes a
        // self-sustaining redraw loop. A hidden window draws nothing, so the fade waits for the
        // window to come back.
        let mut subs: Vec<Subscription<LogMessage>> = Vec::new();
        if self.active_view == LogsView::AllLogs {
            subs.push(iced::Subscription::run(log_stream_producer));
        }
        if self.fade_anim.is_animating() && !super::app_window::hidden() {
            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(view, generation, entries, total) => {
                if self
                    .view_data_mut(view)
                    .handle_refreshed(generation, entries, total)
                {
                    return self.refresh_view(log_store, view);
                }
                Task::none()
            }
            LogMessage::RefreshError(view, generation, e) => {
                self.view_data_mut(view).handle_refresh_error(generation, e);
                Task::none()
            }
            LogMessage::RequestClear => {
                self.pending_clear = Some(self.active_view);
                Task::none()
            }
            LogMessage::ClearDismissed => {
                self.pending_clear = None;
                Task::none()
            }
            LogMessage::ClearConfirmed => {
                // The dialog names the view it was opened for, not whichever view is active now,
                // so a view switch behind the modal cannot retarget it.
                let Some(view) = self.pending_clear.take() else {
                    return Task::none();
                };
                let store = log_store.clone();
                Task::perform(
                    // The clear scope is the view's own level filter: All Logs carries none and
                    // empties the table.
                    async move { store.clear_logs(view.level_filter()).await.map(|_| ()) },
                    move |result| LogMessage::Cleared(view, result.map_err(|e| e.to_string())),
                )
            }
            LogMessage::Cleared(view, result) => match result {
                Ok(()) => {
                    // Post-clear: the pressed view returns to its first page and keeps its typed
                    // search; its count is re-read by the refreshes below, never adjusted in place.
                    // Both views read the same table, so the other one is re-read too.
                    self.view_data_mut(view).clear_entries();
                    Task::batch(
                        [LogsView::AllLogs, LogsView::Issues]
                            .map(|view| self.refresh_view(log_store, view)),
                    )
                }
                // No completion-notice plumbing here: the view's error banner is the channel for
                // a failed clear.
                Err(e) => {
                    self.view_data_mut(view).load_state.fail(e);
                    Task::none()
                }
            },
            LogMessage::LiveEntry(entry) => {
                // Live entries only arrive while the All Logs view is active (the subscription is
                // gated in `subscription()`).
                let data = &mut self.all_logs;
                // Only prepend live entries 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 for this view: the live filter and the stored-row
                // query cover the same four parts — target, message, workspace and ticket.
                if entry.matches_search(&data.search) {
                    data.entries.insert(0, entry);
                    data.pagination.total += 1;
                    data.entries.truncate(data.pagination.page_size);
                    self.newest_entry_timestamp = data.entries.first().map(|e| e.timestamp.clone());
                    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 => self.refresh_active_view(log_store),
            LogMessage::SearchInput(action) => {
                if let Some(task) = super::common::focus_navigation_task(&action) {
                    return task;
                }
                let changes_text = action.changes_text();
                self.search_buffer.apply_action(action);
                let text = self.search_buffer.text();
                self.view_data_mut(self.active_view).search = text;
                // Only text changes re-trigger the debounced refresh; cursor movement emits
                // actions too but must not restart the timer.
                if !changes_text {
                    return Task::none();
                }
                self.reset_pagination_for_active_view();
                // Tag the debounced refresh with the view whose query changed, so it still
                // targets that view if the user switches away within the window.
                let view = self.active_view;
                self.debounce
                    .trigger(300)
                    .map(move |g| LogMessage::DebouncedRefresh(g, view))
            }
            LogMessage::DebouncedRefresh(generation, view) => {
                if !self.debounce.should_process(generation) {
                    return Task::none();
                }
                self.refresh_view(log_store, view)
            }
            LogMessage::PrevPage => {
                if self.view_data_mut(self.active_view).pagination.prev_page() {
                    return self.refresh_active_view(log_store);
                }
                Task::none()
            }
            LogMessage::NextPage => {
                if self.view_data_mut(self.active_view).pagination.next_page() {
                    return self.refresh_active_view(log_store);
                }
                Task::none()
            }
            LogMessage::Escape => {
                // Escape never confirms: while the 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.
                iced::clipboard::write(format_log_entry(&entry))
            }
            LogMessage::ViewSelected(view) => {
                self.active_view = view;
                // Sync the shared search buffer to the newly-active view's query.
                let active_search = self.active_search().to_string();
                self.search_buffer.set_text(&active_search);
                self.refresh_active_view(log_store)
            }
        }
    }

    /// One position of the bottom bar's view switch. Both labels always render; the active one
    /// is accent-colored on an elevated fill, so the position is read off the control.
    fn view_switch_segment(view: LogsView, active: LogsView) -> Element<'static, LogMessage> {
        let is_active = view == active;
        let color = if is_active {
            theme::ACCENT
        } else {
            theme::TEXT_FAINT
        };
        let segment = button(text(view.switch_label()).size(theme::TEXT_11).color(color))
            .style(theme::button_text)
            .padding([theme::PAD_2, theme::PAD_8])
            .on_press_maybe((!is_active).then_some(LogMessage::ViewSelected(view)));
        container(segment)
            .style(move |_| {
                let background = if is_active {
                    theme::BG_ELEVATED
                } else {
                    iced::Color::TRANSPARENT
                };
                theme::container_style(background, 4.0, 0.0, iced::Color::TRANSPARENT)
            })
            .into()
    }

    /// The view switch as one hairline-bordered pill in the bottom bar. Rendered
    /// unconditionally: it is the only view switcher on the page, so a store with nothing to
    /// paginate must not hide it.
    fn view_switch(active: LogsView) -> Element<'static, LogMessage> {
        container(
            row![
                Self::view_switch_segment(LogsView::AllLogs, active),
                Self::view_switch_segment(LogsView::Issues, active),
            ]
            .spacing(theme::SPACE_2),
        )
        .padding(theme::PAD_1)
        .style(|_| theme::container_style(iced::Color::TRANSPARENT, 5.0, 1.0, theme::BORDER))
        .into()
    }

    pub fn view(&self) -> Element<'_, LogMessage> {
        let body: Element<'_, LogMessage> = 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 + view switch + clear + search.
        let bottom_bar = self.bottom_bar();

        let content = column![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 and closes.
        let confirm_layer: Element<'_, LogMessage> = match self.pending_clear {
            Some(view) => Self::clear_confirm_dialog(view),
            None => stack([widgets::empty_stack_placeholder()]).into(),
        };
        stack([page, confirm_layer]).into()
    }

    /// The clear confirmation for `view`: the shared confirm-dialog/backdrop pair, with the
    /// view'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(view: LogsView) -> Element<'static, LogMessage> {
        widgets::modal_backdrop(
            dialog::confirm_dialog(
                dialog::dialog_title(format!("{}?", view.clear_label())),
                dialog::dialog_body(view.clear_consequences()),
                [
                    dialog::DialogAction::secondary("Keep records", LogMessage::ClearDismissed),
                    dialog::DialogAction::danger(view.clear_label(), LogMessage::ClearConfirmed),
                ],
            ),
            LogMessage::ClearDismissed,
            0.5,
        )
    }

    /// A warning banner for the log store's own bad news: the write failures observed on it — the
    /// log-writer task's failed batches and panics, and a panic out of one telemetry record's own
    /// write — and the telemetry rows a full queue dropped. Each number gets its own sentence, so
    /// neither hides the other. Empty 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 && info.dropped == 0 {
            return Space::new().height(0).into();
        }

        let mut report = Vec::new();
        if info.count > 0 {
            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 {
                ""
            };
            report.push(format!(
                "Log store write failures: {} — records are not reaching the log store{last}. \
                 Latest error: {detail}{stopped}",
                info.count
            ));
        }
        if info.dropped > 0 {
            report.push(format!(
                "Telemetry rows dropped by a full queue: {} — recording never waits for the \
                 store, so a burst with nowhere to go is dropped.",
                info.dropped
            ));
        }

        container(
            row![
                lucide::triangle_alert::<iced::Theme, iced::Renderer>()
                    .size(theme::TEXT_14)
                    .color(theme::STATUS_WARNING),
                Space::new().width(theme::SPACE_6),
                text(report.join(" "))
                    .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()
    }

    fn bottom_bar(&self) -> Element<'_, LogMessage> {
        let data = self.view_data(self.active_view);
        let (page, total_pages) = (data.pagination.page, data.pagination.total_pages());

        // Pagination cluster — hidden entirely when there are no pages, so "Page X of Y" 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()
        };

        // This view's clear — always rendered: a view 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_view.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),
            Self::view_switch(self.active_view),
            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()
    }

    fn logs_view(&self) -> Element<'_, LogMessage> {
        let data = self.view_data(self.active_view);
        // New live entries insert at position 0, so no scroll-to-newest logic is needed. The fade
        // and the newest-entry timestamp are read per row, never on the loading or empty paths.
        widgets::paginated_body(
            data,
            lucide::activity::<iced::Theme, iced::Renderer>(),
            "No log entries",
            |entry| {
                let is_newest =
                    self.newest_entry_timestamp.as_deref() == Some(entry.timestamp.as_str());
                let fade_progress = if is_newest {
                    *self.fade_anim.value()
                } else {
                    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. Left-click drag selection is unaffected: ContextMenu forwards all
                // non-right-click events to the underlay.
                ContextMenu::new(
                    LogsState::render_log_entry(entry, fade_progress),
                    vec![MenuItem::new(
                        "Copy".into(),
                        LogMessage::CopyEntry(entry.clone()),
                    )],
                )
                .into()
            },
        )
    }

    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),
        );
        for scope in [&entry.ticket, &entry.workspace] {
            if scope.is_empty() {
                continue;
            }
            spans.push(Span::new("  ").size(theme::TEXT_10));
            spans.push(
                Span::new(scope)
                    .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),
        );

        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 by the row's 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: super::selectable::Selectable<'_, (), LogMessage, iced::Theme, iced::Renderer> =
            super::selectable::rich_text(spans)
                .style(|_t| super::selectable::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. Shared by the row renderer (which truncates) and the clipboard format
/// (which must not).
#[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: the full raw RFC 3339 timestamp and level on the
/// first line, a header line with the available role/agent/target/ticket/workspace parts (omitted
/// entirely when none is present), then the complete untruncated message, then each remaining
/// field as a `key: value` line.
///
/// Field lines iterate the stored fields JSON in **sorted key order** (sorted explicitly, so the
/// output is deterministic whatever serde_json's `preserve_order` state is) and skip only the
/// `message` key. The row's scope is promoted out of the record at write time, so the keys that
/// duplicate header parts are no longer fields: the fields section is the record's remaining
/// payload. Non-string values render via [`field_value_str`].
#[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);

    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.ticket.is_empty() {
        header.push(format!("ticket: {}", entry.ticket));
    }
    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, but `preserve_order`
        // could be enabled by feature unification elsewhere in the graph.
        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
}