lemurclaw 0.0.1

Command-line interface for the lemurclaw AI coding agent
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
use ratatui::layout::Constraint;
use ratatui::layout::Direction;
use ratatui::layout::Layout;
use ratatui::prelude::*;
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::style::Stylize;
use ratatui::widgets::Block;
use ratatui::widgets::BorderType;
use ratatui::widgets::Borders;
use ratatui::widgets::Clear;
use ratatui::widgets::List;
use ratatui::widgets::ListItem;
use ratatui::widgets::ListState;
use ratatui::widgets::Padding;
use ratatui::widgets::Paragraph;
use std::sync::OnceLock;
use std::time::Instant;

use crate::cloud_tasks::app::App;
use crate::cloud_tasks::app::AttemptView;
use crate::cloud_tasks::util::format_relative_time_now;
use lemurclaw_server::cloud_tasks_client::AttemptStatus;
use lemurclaw_server::cloud_tasks_client::TaskStatus;
use lemurclaw_tui::render_markdown_text;

pub fn draw(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(1),    // list
            Constraint::Length(2), // two-line footer (help + status)
        ])
        .split(area);
    if app.new_task.is_some() {
        draw_new_task_page(frame, chunks[0], app);
        draw_footer(frame, chunks[1], app);
    } else {
        draw_list(frame, chunks[0], app);
        draw_footer(frame, chunks[1], app);
    }

    if app.diff_overlay.is_some() {
        draw_diff_overlay(frame, area, app);
    }
    if app.env_modal.is_some() {
        draw_env_modal(frame, area, app);
    }
    if app.best_of_modal.is_some() {
        draw_best_of_modal(frame, area, app);
    }
    if app.apply_modal.is_some() {
        draw_apply_modal(frame, area, app);
    }
}

// ===== Overlay helpers (geometry + styling) =====
static ROUNDED: OnceLock<bool> = OnceLock::new();

fn rounded_enabled() -> bool {
    *ROUNDED.get_or_init(|| {
        std::env::var("CODEX_TUI_ROUNDED")
            .ok()
            .map(|v| v == "1")
            .unwrap_or(true)
    })
}

fn overlay_outer(area: Rect) -> Rect {
    let outer_v = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(10),
            Constraint::Percentage(80),
            Constraint::Percentage(10),
        ])
        .split(area)[1];
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(10),
            Constraint::Percentage(80),
            Constraint::Percentage(10),
        ])
        .split(outer_v)[1]
}

fn overlay_block() -> Block<'static> {
    let base = Block::default().borders(Borders::ALL);
    let base = if rounded_enabled() {
        base.border_type(BorderType::Rounded)
    } else {
        base
    };
    base.padding(Padding::new(2, 2, 1, 1))
}

fn overlay_content(area: Rect) -> Rect {
    overlay_block().inner(area)
}

pub fn draw_new_task_page(frame: &mut Frame, area: Rect, app: &mut App) {
    let title_spans = {
        let mut spans: Vec<ratatui::text::Span> = vec!["New Task".magenta().bold()];
        if let Some(id) = app
            .new_task
            .as_ref()
            .and_then(|p| p.env_id.as_ref())
            .cloned()
        {
            spans.push("".into());
            // Try to map id to label
            let label = app
                .environments
                .iter()
                .find(|r| r.id == id)
                .and_then(|r| r.label.clone())
                .unwrap_or(id);
            spans.push(label.dim());
        } else {
            spans.push("".into());
            spans.push("Env: none (press ctrl-o to choose)".red());
        }
        if let Some(page) = app.new_task.as_ref() {
            spans.push("".into());
            let attempts = page.best_of_n;
            let label = format!(
                "{} attempt{}",
                attempts,
                if attempts == 1 { "" } else { "s" }
            );
            spans.push(label.cyan());
        }
        spans
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .title(Line::from(title_spans));

    frame.render_widget(Clear, area);
    frame.render_widget(block.clone(), area);
    let content = block.inner(area);

    // Expand composer height up to (terminal height - 6), with a 3-line minimum.
    let max_allowed = frame.area().height.saturating_sub(6).max(3);
    let desired = app
        .new_task
        .as_ref()
        .map(|p| p.composer.desired_height(content.width))
        .unwrap_or(3)
        .clamp(3, max_allowed);

    // Anchor the composer to the bottom-left by allocating a flexible spacer
    // above it and a fixed `desired`-height area for the composer.
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(desired)])
        .split(content);
    let composer_area = rows[1];

    if let Some(page) = app.new_task.as_ref() {
        page.composer.render_ref(composer_area, frame.buffer_mut());
        // Composer renders its own footer hints; no extra row here.
    }

    // Place cursor where composer wants it
    if let Some(page) = app.new_task.as_ref()
        && let Some((x, y)) = page.composer.cursor_pos(composer_area)
    {
        frame.set_cursor_position((x, y));
    }
}

fn draw_list(frame: &mut Frame, area: Rect, app: &mut App) {
    let items: Vec<ListItem> = app.tasks.iter().map(|t| render_task_item(app, t)).collect();

    // Selection reflects the actual task index (no artificial spacer item).
    let mut state = ListState::default().with_selected(Some(app.selected));
    // Dim task list when a modal/overlay is active to emphasize focus.
    let dim_bg = app.env_modal.is_some()
        || app.apply_modal.is_some()
        || app.best_of_modal.is_some()
        || app.diff_overlay.is_some();
    // Dynamic title includes current environment filter
    let suffix_span = if let Some(ref id) = app.env_filter {
        let label = app
            .environments
            .iter()
            .find(|r| &r.id == id)
            .and_then(|r| r.label.clone())
            .unwrap_or_else(|| "Selected".to_string());
        format!("{label}").dim()
    } else {
        " • All".dim()
    };
    // Percent scrolled based on selection position in the list (0% at top, 100% at bottom).
    let percent_span = if app.tasks.len() <= 1 {
        "  • 0%".dim()
    } else {
        let p = ((app.selected as f32) / ((app.tasks.len() - 1) as f32) * 100.0).round() as i32;
        format!("{}%", p.clamp(0, 100)).dim()
    };
    let title_line = {
        let base = Line::from(vec!["Cloud Tasks".into(), suffix_span, percent_span]);
        if dim_bg {
            base.style(Style::default().add_modifier(Modifier::DIM))
        } else {
            base
        }
    };
    let block = Block::default().borders(Borders::ALL).title(title_line);
    // Render the outer block first
    frame.render_widget(block.clone(), area);
    // Draw list inside with a persistent top spacer row
    let inner = block.inner(area);
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(1)])
        .split(inner);
    let mut list = List::new(items)
        .highlight_symbol("")
        .highlight_style(Style::default().bold());
    if dim_bg {
        list = list.style(Style::default().add_modifier(Modifier::DIM));
    }
    frame.render_stateful_widget(list, rows[1], &mut state);

    // In-box spinner during initial/refresh loads
    if app.refresh_inflight {
        draw_centered_spinner(frame, inner, &mut app.spinner_start, "Loading tasks…");
    }
}

fn draw_footer(frame: &mut Frame, area: Rect, app: &mut App) {
    let mut help = vec![
        "↑/↓".dim(),
        ": Move  ".dim(),
        "r".dim(),
        ": Refresh  ".dim(),
        "Enter".dim(),
        ": Open  ".dim(),
    ];
    // Apply hint; show disabled note when overlay is open without a diff.
    if let Some(ov) = app.diff_overlay.as_ref() {
        if !ov.current_can_apply() {
            help.push("a".dim());
            help.push(": Apply (disabled)  ".dim());
        } else {
            help.push("a".dim());
            help.push(": Apply  ".dim());
        }
        if ov.attempt_count() > 1 {
            help.push("Tab".dim());
            help.push(": Next attempt  ".dim());
            help.push("[ ]".dim());
            help.push(": Cycle attempts  ".dim());
        }
    } else {
        help.push("a".dim());
        help.push(": Apply  ".dim());
    }
    help.push("o : Set Env  ".dim());
    if app.new_task.is_some() {
        help.push("Ctrl+N".dim());
        help.push(format!(": Attempts {}x  ", app.best_of_n).dim());
        help.push("(editing new task)  ".dim());
    } else {
        help.push("n : New Task  ".dim());
    }
    help.extend(vec!["q".dim(), ": Quit  ".dim()]);
    // Split footer area into two rows: help+spinner (top) and status (bottom)
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Length(1)])
        .split(area);

    // Top row: help text + spinner at right
    let top = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Fill(1), Constraint::Length(18)])
        .split(rows[0]);
    let para = Paragraph::new(Line::from(help));
    // Draw help text; avoid clearing the whole footer area every frame.
    frame.render_widget(para, top[0]);
    // Right side: spinner or clear the spinner area if idle to prevent stale glyphs.
    if app.refresh_inflight
        || app.details_inflight
        || app.env_loading
        || app.apply_preflight_inflight
        || app.apply_inflight
    {
        draw_inline_spinner(frame, top[1], &mut app.spinner_start, "Loading…");
    } else {
        frame.render_widget(Clear, top[1]);
    }

    // Bottom row: status/log text across full width (single-line; sanitize newlines)
    let mut status_line = app.status.replace('\n', " ");
    if status_line.len() > 2000 {
        // hard cap to avoid TUI noise
        status_line.truncate(2000);
        status_line.push('');
    }
    // Clear the status row to avoid trailing characters when the message shrinks.
    frame.render_widget(Clear, rows[1]);
    let status = Paragraph::new(status_line);
    frame.render_widget(status, rows[1]);
}

fn draw_diff_overlay(frame: &mut Frame, area: Rect, app: &mut App) {
    let inner = overlay_outer(area);
    if app.diff_overlay.is_none() {
        return;
    }
    let ov_can_apply = app
        .diff_overlay
        .as_ref()
        .map(super::app::DiffOverlay::current_can_apply)
        .unwrap_or(false);
    let is_error = app
        .diff_overlay
        .as_ref()
        .and_then(|o| o.sd.wrapped_lines().first().cloned())
        .map(|s| s.trim_start().starts_with("Task failed:"))
        .unwrap_or(false)
        && !ov_can_apply;
    let title = app
        .diff_overlay
        .as_ref()
        .map(|o| o.title.clone())
        .unwrap_or_default();

    // Title block
    let title_ref = title.as_str();
    let mut title_spans: Vec<ratatui::text::Span> = if is_error {
        vec![
            "Details ".magenta(),
            "[FAILED]".red().bold(),
            " ".into(),
            title_ref.magenta(),
        ]
    } else if ov_can_apply {
        vec!["Diff: ".magenta(), title_ref.magenta()]
    } else {
        vec!["Details: ".magenta(), title_ref.magenta()]
    };
    if let Some(p) = app
        .diff_overlay
        .as_ref()
        .and_then(|o| o.sd.percent_scrolled())
    {
        title_spans.push("".dim());
        title_spans.push(format!("{p}%").dim());
    }
    frame.render_widget(Clear, inner);
    frame.render_widget(
        overlay_block().title(Line::from(title_spans)).clone(),
        inner,
    );

    // Content area and optional status bar
    let content_full = overlay_content(inner);
    let mut content_area = content_full;
    if let Some(ov) = app.diff_overlay.as_mut() {
        let has_text = ov.current_attempt().is_some_and(AttemptView::has_text);
        let has_diff = ov.current_attempt().is_some_and(AttemptView::has_diff) || ov.base_can_apply;
        if has_diff || has_text {
            let rows = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Length(1), Constraint::Min(1)])
                .split(content_full);
            // Status bar label
            let mut spans: Vec<ratatui::text::Span> = Vec::new();
            if has_diff && has_text {
                let prompt_lbl = if matches!(ov.current_view, crate::cloud_tasks::app::DetailView::Prompt) {
                    "[Prompt]".magenta().bold()
                } else {
                    "Prompt".dim()
                };
                let diff_lbl = if matches!(ov.current_view, crate::cloud_tasks::app::DetailView::Diff) {
                    "[Diff]".magenta().bold()
                } else {
                    "Diff".dim()
                };
                spans.extend(vec![
                    prompt_lbl,
                    "  ".into(),
                    diff_lbl,
                    "  ".into(),
                    "(← → to switch view)".dim(),
                ]);
            } else if has_text {
                spans.push("Conversation".magenta().bold());
            } else {
                spans.push("Diff".magenta().bold());
            }
            if let Some(total) = ov.expected_attempts().or({
                if ov.attempts.is_empty() {
                    None
                } else {
                    Some(ov.attempts.len())
                }
            }) && total > 1
            {
                spans.extend(vec![
                    "  ".into(),
                    format!("Attempt {}/{}", ov.selected_attempt + 1, total)
                        .bold()
                        .dim(),
                    "  ".into(),
                    "(Tab/Shift-Tab or [ ] to cycle attempts)".dim(),
                ]);
            }
            frame.render_widget(Paragraph::new(Line::from(spans)), rows[0]);
            ov.sd.set_width(rows[1].width);
            ov.sd.set_viewport(rows[1].height);
            content_area = rows[1];
        } else {
            ov.sd.set_width(content_full.width);
            ov.sd.set_viewport(content_full.height);
            content_area = content_full;
        }
    }

    // Styled content render
    // Choose styling by the active view, not just presence of a diff
    let is_diff_view = app
        .diff_overlay
        .as_ref()
        .map(|o| matches!(o.current_view, crate::cloud_tasks::app::DetailView::Diff))
        .unwrap_or(false);
    let styled_lines: Vec<Line<'static>> = if is_diff_view {
        let raw = app.diff_overlay.as_ref().map(|o| o.sd.wrapped_lines());
        raw.unwrap_or(&[])
            .iter()
            .map(|l| style_diff_line(l))
            .collect()
    } else {
        app.diff_overlay
            .as_ref()
            .map(|o| style_conversation_lines(&o.sd, o.current_attempt()))
            .unwrap_or_default()
    };
    let raw_empty = app
        .diff_overlay
        .as_ref()
        .map(|o| o.sd.wrapped_lines().is_empty())
        .unwrap_or(true);
    if app.details_inflight && raw_empty {
        draw_centered_spinner(
            frame,
            content_area,
            &mut app.spinner_start,
            "Loading details…",
        );
    } else {
        let scroll = app
            .diff_overlay
            .as_ref()
            .map(|o| o.sd.state.scroll)
            .unwrap_or(0);
        let content = Paragraph::new(Text::from(styled_lines)).scroll((scroll, 0));
        frame.render_widget(content, content_area);
    }
}

pub fn draw_apply_modal(frame: &mut Frame, area: Rect, app: &mut App) {
    use ratatui::widgets::Wrap;
    let inner = overlay_outer(area);
    let title = Line::from("Apply Changes?".magenta().bold());
    let block = overlay_block().title(title);
    frame.render_widget(Clear, inner);
    frame.render_widget(block.clone(), inner);
    let content = overlay_content(inner);

    if let Some(m) = &app.apply_modal {
        // Header
        let header = Paragraph::new(Line::from(
            format!("Apply '{}' ?", m.title).magenta().bold(),
        ))
        .wrap(Wrap { trim: true });
        // Footer instructions
        let footer =
            Paragraph::new(Line::from("Press Y to apply, P to preflight, N to cancel.").dim())
                .wrap(Wrap { trim: true });

        // Split into header/body/footer
        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(1),
                Constraint::Min(1),
                Constraint::Length(1),
            ])
            .split(content);

        frame.render_widget(header, rows[0]);
        // Body: spinner while preflight/apply runs; otherwise show result message and path lists
        if app.apply_preflight_inflight {
            draw_centered_spinner(frame, rows[1], &mut app.spinner_start, "Checking…");
        } else if app.apply_inflight {
            draw_centered_spinner(frame, rows[1], &mut app.spinner_start, "Applying…");
        } else if m.result_message.is_none() {
            draw_centered_spinner(frame, rows[1], &mut app.spinner_start, "Loading…");
        } else if let Some(msg) = &m.result_message {
            let mut body_lines: Vec<Line> = Vec::new();
            let first = match m.result_level {
                Some(crate::cloud_tasks::app::ApplyResultLevel::Success) => msg.clone().green(),
                Some(crate::cloud_tasks::app::ApplyResultLevel::Partial) => msg.clone().magenta(),
                Some(crate::cloud_tasks::app::ApplyResultLevel::Error) => msg.clone().red(),
                None => msg.clone().into(),
            };
            body_lines.push(Line::from(first));

            // On partial or error, show conflicts/skips if present
            if !matches!(m.result_level, Some(crate::cloud_tasks::app::ApplyResultLevel::Success)) {
                use ratatui::text::Span;
                if !m.conflict_paths.is_empty() {
                    body_lines.push(Line::from(""));
                    body_lines.push(
                        Line::from(format!("Conflicts ({}):", m.conflict_paths.len()))
                            .red()
                            .bold(),
                    );
                    for p in &m.conflict_paths {
                        body_lines
                            .push(Line::from(vec!["".into(), Span::raw(p.clone()).dim()]));
                    }
                }
                if !m.skipped_paths.is_empty() {
                    body_lines.push(Line::from(""));
                    body_lines.push(
                        Line::from(format!("Skipped ({}):", m.skipped_paths.len()))
                            .magenta()
                            .bold(),
                    );
                    for p in &m.skipped_paths {
                        body_lines
                            .push(Line::from(vec!["".into(), Span::raw(p.clone()).dim()]));
                    }
                }
            }
            let body = Paragraph::new(body_lines).wrap(Wrap { trim: true });
            frame.render_widget(body, rows[1]);
        }
        frame.render_widget(footer, rows[2]);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ConversationSpeaker {
    User,
    Assistant,
}

fn style_conversation_lines(
    sd: &crate::cloud_tasks::scrollable_diff::ScrollableDiff,
    attempt: Option<&AttemptView>,
) -> Vec<Line<'static>> {
    use ratatui::text::Span;

    let wrapped = sd.wrapped_lines();
    if wrapped.is_empty() {
        return Vec::new();
    }

    let indices = sd.wrapped_src_indices();
    let mut styled: Vec<Line<'static>> = Vec::new();
    let mut speaker: Option<ConversationSpeaker> = None;
    let mut in_code = false;
    let mut last_src: Option<usize> = None;
    let mut bullet_indent: Option<usize> = None;

    for (display, &src_idx) in wrapped.iter().zip(indices.iter()) {
        let raw = sd.raw_line_at(src_idx);
        let trimmed = raw.trim();
        let is_new_raw = last_src.map(|prev| prev != src_idx).unwrap_or(true);

        if trimmed.eq_ignore_ascii_case("user:") {
            speaker = Some(ConversationSpeaker::User);
            in_code = false;
            bullet_indent = None;
            styled.push(conversation_header_line(
                ConversationSpeaker::User,
                /*attempt*/ None,
            ));
            last_src = Some(src_idx);
            continue;
        }
        if trimmed.eq_ignore_ascii_case("assistant:") {
            speaker = Some(ConversationSpeaker::Assistant);
            in_code = false;
            bullet_indent = None;
            styled.push(conversation_header_line(
                ConversationSpeaker::Assistant,
                attempt,
            ));
            last_src = Some(src_idx);
            continue;
        }
        if raw.is_empty() {
            let mut spans: Vec<Span> = Vec::new();
            if let Some(role) = speaker {
                spans.push(conversation_gutter_span(role));
            } else {
                spans.push(Span::raw(String::new()));
            }
            styled.push(Line::from(spans));
            last_src = Some(src_idx);
            bullet_indent = None;
            continue;
        }

        if is_new_raw {
            let trimmed_start = raw.trim_start();
            if trimmed_start.starts_with("```") {
                in_code = !in_code;
                bullet_indent = None;
            } else if !in_code
                && (trimmed_start.starts_with("- ") || trimmed_start.starts_with("* "))
            {
                let indent = raw.chars().take_while(|c| c.is_whitespace()).count();
                bullet_indent = Some(indent);
            } else if !in_code {
                bullet_indent = None;
            }
        }

        let mut spans: Vec<Span> = Vec::new();
        if let Some(role) = speaker {
            spans.push(conversation_gutter_span(role));
        }

        spans.extend(conversation_text_spans(
            display,
            in_code,
            is_new_raw,
            bullet_indent,
        ));

        styled.push(Line::from(spans));
        last_src = Some(src_idx);
    }

    if styled.is_empty() {
        wrapped.iter().map(|l| Line::from(l.to_string())).collect()
    } else {
        styled
    }
}

fn conversation_header_line(
    speaker: ConversationSpeaker,
    attempt: Option<&AttemptView>,
) -> Line<'static> {
    use ratatui::text::Span;

    let mut spans: Vec<Span> = vec!["".dim()];
    match speaker {
        ConversationSpeaker::User => {
            spans.push("User".cyan().bold());
            spans.push(" prompt".dim());
        }
        ConversationSpeaker::Assistant => {
            spans.push("Assistant".magenta().bold());
            spans.push(" response".dim());
            if let Some(attempt) = attempt
                && let Some(status_span) = attempt_status_span(attempt.status)
            {
                spans.push("".dim());
                spans.push(status_span);
            }
        }
    }
    Line::from(spans)
}

fn conversation_gutter_span(speaker: ConversationSpeaker) -> ratatui::text::Span<'static> {
    match speaker {
        ConversationSpeaker::User => "".cyan().dim(),
        ConversationSpeaker::Assistant => "".magenta().dim(),
    }
}

fn conversation_text_spans(
    display: &str,
    in_code: bool,
    is_new_raw: bool,
    bullet_indent: Option<usize>,
) -> Vec<ratatui::text::Span<'static>> {
    use ratatui::text::Span;

    if in_code {
        return vec![Span::styled(
            display.to_string(),
            Style::default().fg(Color::Cyan),
        )];
    }

    let trimmed = display.trim_start();

    if let Some(indent) = bullet_indent {
        if is_new_raw {
            let rest = trimmed.get(2..).unwrap_or("").trim_start();
            let mut spans: Vec<Span> = Vec::new();
            if indent > 0 {
                spans.push(Span::raw(" ".repeat(indent)));
            }
            spans.push("".into());
            spans.push(Span::raw(rest.to_string()));
            return spans;
        }
        let mut continuation = String::new();
        continuation.push_str(&" ".repeat(indent + 2));
        continuation.push_str(trimmed);
        return vec![Span::raw(continuation)];
    }

    if is_new_raw
        && (trimmed.starts_with("### ") || trimmed.starts_with("## ") || trimmed.starts_with("# "))
    {
        return vec![Span::styled(
            display.to_string(),
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        )];
    }

    let mut rendered = render_markdown_text(display);
    if rendered.lines.is_empty() {
        return vec![Span::raw(display.to_string())];
    }
    // `render_markdown_text` can yield multiple lines when the input contains
    // explicit breaks. We only expect a single line here; join the spans of the
    // first rendered line for styling.
    rendered.lines.remove(0).spans.into_iter().collect()
}

fn attempt_status_span(status: AttemptStatus) -> Option<ratatui::text::Span<'static>> {
    match status {
        AttemptStatus::Completed => Some("Completed".green()),
        AttemptStatus::Failed => Some("Failed".red().bold()),
        AttemptStatus::InProgress => Some("In progress".magenta()),
        AttemptStatus::Pending => Some("Pending".cyan()),
        AttemptStatus::Cancelled => Some("Cancelled".dim()),
        AttemptStatus::Unknown => None,
    }
}

fn style_diff_line(raw: &str) -> Line<'static> {
    use ratatui::style::Color;
    use ratatui::style::Modifier;
    use ratatui::style::Style;
    use ratatui::text::Span;

    if raw.starts_with("@@") {
        return Line::from(vec![Span::styled(
            raw.to_string(),
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        )]);
    }
    if raw.starts_with("+++") || raw.starts_with("---") {
        return Line::from(vec![Span::styled(
            raw.to_string(),
            Style::default().add_modifier(Modifier::DIM),
        )]);
    }
    if raw.starts_with('+') {
        return Line::from(vec![Span::styled(
            raw.to_string(),
            Style::default().fg(Color::Green),
        )]);
    }
    if raw.starts_with('-') {
        return Line::from(vec![Span::styled(
            raw.to_string(),
            Style::default().fg(Color::Red),
        )]);
    }
    Line::from(vec![Span::raw(raw.to_string())])
}

fn render_task_item(_app: &App, t: &lemurclaw_server::cloud_tasks_client::TaskSummary) -> ListItem<'static> {
    let status = match t.status {
        TaskStatus::Ready => "READY".green(),
        TaskStatus::Pending => "PENDING".magenta(),
        TaskStatus::Applied => "APPLIED".blue(),
        TaskStatus::Error => "ERROR".red(),
    };

    // Title line: [STATUS] Title
    let title = Line::from(vec![
        "[".into(),
        status,
        "] ".into(),
        t.title.clone().into(),
    ]);

    // Meta line: environment label and relative time (dim)
    let mut meta: Vec<ratatui::text::Span> = Vec::new();
    if let Some(lbl) = t.environment_label.as_ref().filter(|s| !s.is_empty()) {
        meta.push(lbl.clone().dim());
    }
    let when = format_relative_time_now(t.updated_at).dim();
    if !meta.is_empty() {
        meta.push("  ".into());
        meta.push("".dim());
        meta.push("  ".into());
    }
    meta.push(when);
    let meta_line = Line::from(meta);

    // Subline: summary when present; otherwise show "no diff"
    let sub = if t.summary.files_changed > 0
        || t.summary.lines_added > 0
        || t.summary.lines_removed > 0
    {
        let adds = t.summary.lines_added;
        let dels = t.summary.lines_removed;
        let files = t.summary.files_changed;
        Line::from(vec![
            format!("+{adds}").green(),
            "/".into(),
            format!("{dels}").red(),
            " ".into(),
            "".dim(),
            " ".into(),
            format!("{files}").into(),
            " ".into(),
            "files".dim(),
        ])
    } else {
        Line::from("no diff".to_string().dim())
    };

    // Insert a blank spacer line after the summary to separate tasks
    let spacer = Line::from("");
    ListItem::new(vec![title, meta_line, sub, spacer])
}

fn draw_inline_spinner(
    frame: &mut Frame,
    area: Rect,
    spinner_start: &mut Option<Instant>,
    label: &str,
) {
    use ratatui::widgets::Paragraph;
    let start = spinner_start.get_or_insert_with(Instant::now);
    let blink_on = (start.elapsed().as_millis() / 600).is_multiple_of(2);
    let dot = if blink_on {
        "".into()
    } else {
        "".dim()
    };
    let label = label.cyan();
    let line = Line::from(vec![dot, label]);
    frame.render_widget(Paragraph::new(line), area);
}

fn draw_centered_spinner(
    frame: &mut Frame,
    area: Rect,
    spinner_start: &mut Option<Instant>,
    label: &str,
) {
    // Center a 1xN spinner within the given rect
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(50),
            Constraint::Length(1),
            Constraint::Percentage(49),
        ])
        .split(area);
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(50),
            Constraint::Length(18),
            Constraint::Percentage(50),
        ])
        .split(rows[1]);
    draw_inline_spinner(frame, cols[1], spinner_start, label);
}

// Styling helpers for diff rendering live inline where used.

pub fn draw_env_modal(frame: &mut Frame, area: Rect, app: &mut App) {
    use ratatui::widgets::Wrap;

    // Use shared overlay geometry and padding.
    let inner = overlay_outer(area);

    // Title: primary only; move long hints to a subheader inside content.
    let title = Line::from(vec!["Select Environment".magenta().bold()]);
    let block = overlay_block().title(title);

    frame.render_widget(Clear, inner);
    frame.render_widget(block.clone(), inner);
    let content = overlay_content(inner);

    if app.env_loading {
        draw_centered_spinner(
            frame,
            content,
            &mut app.spinner_start,
            "Loading environments…",
        );
        return;
    }

    // Layout: subheader + search + results list
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // subheader
            Constraint::Length(1), // search
            Constraint::Min(1),    // list
        ])
        .split(content);

    // Subheader with usage hints (dim cyan)
    let subheader = Paragraph::new(Line::from(
        "Type to search, Enter select, Esc cancel".cyan().dim(),
    ))
    .wrap(Wrap { trim: true });
    frame.render_widget(subheader, rows[0]);

    let query = app
        .env_modal
        .as_ref()
        .map(|m| m.query.clone())
        .unwrap_or_default();
    let ql = query.to_lowercase();
    let search = Paragraph::new(format!("Search: {query}")).wrap(Wrap { trim: true });
    frame.render_widget(search, rows[1]);

    // Filter environments by query (case-insensitive substring over label/id/hints)
    let envs: Vec<&crate::cloud_tasks::app::EnvironmentRow> = app
        .environments
        .iter()
        .filter(|e| {
            if ql.is_empty() {
                return true;
            }
            let mut hay = String::new();
            if let Some(l) = &e.label {
                hay.push_str(&l.to_lowercase());
                hay.push(' ');
            }
            hay.push_str(&e.id.to_lowercase());
            if let Some(h) = &e.repo_hints {
                hay.push(' ');
                hay.push_str(&h.to_lowercase());
            }
            hay.contains(&ql)
        })
        .collect();

    let mut items: Vec<ListItem> = Vec::new();
    items.push(ListItem::new(Line::from("All Environments (Global)")));
    for env in envs.iter() {
        let primary = env.label.clone().unwrap_or_else(|| "<unnamed>".to_string());
        let mut spans: Vec<ratatui::text::Span> = vec![primary.into()];
        if env.is_pinned {
            spans.push("  ".into());
            spans.push("PINNED".magenta().bold());
        }
        spans.push("  ".into());
        spans.push(env.id.clone().dim());
        if let Some(hint) = &env.repo_hints {
            spans.push("  ".into());
            spans.push(hint.clone().dim());
        }
        items.push(ListItem::new(Line::from(spans)));
    }

    let sel_desired = app.env_modal.as_ref().map(|m| m.selected).unwrap_or(0);
    let sel = sel_desired.min(envs.len());
    let mut list_state = ListState::default().with_selected(Some(sel));
    let list = List::new(items)
        .highlight_symbol("")
        .highlight_style(Style::default().bold())
        .block(Block::default().borders(Borders::NONE));
    frame.render_stateful_widget(list, rows[2], &mut list_state);
}

pub fn draw_best_of_modal(frame: &mut Frame, area: Rect, app: &mut App) {
    use ratatui::widgets::Wrap;

    let inner = overlay_outer(area);
    const MAX_WIDTH: u16 = 40;
    const MIN_WIDTH: u16 = 20;
    const MAX_HEIGHT: u16 = 12;
    const MIN_HEIGHT: u16 = 6;
    let modal_width = inner.width.min(MAX_WIDTH).max(inner.width.min(MIN_WIDTH));
    let modal_height = inner
        .height
        .min(MAX_HEIGHT)
        .max(inner.height.min(MIN_HEIGHT));
    let modal_x = inner.x + (inner.width.saturating_sub(modal_width)) / 2;
    let modal_y = inner.y + (inner.height.saturating_sub(modal_height)) / 2;
    let modal_area = Rect::new(modal_x, modal_y, modal_width, modal_height);
    let title = Line::from(vec!["Parallel Attempts".magenta().bold()]);
    let block = overlay_block().title(title);

    frame.render_widget(Clear, modal_area);
    frame.render_widget(block.clone(), modal_area);
    let content = overlay_content(modal_area);

    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(2), Constraint::Min(1)])
        .split(content);

    let hint = Paragraph::new(Line::from("Use ↑/↓ to choose, 1-4 jump".cyan().dim()))
        .wrap(Wrap { trim: true });
    frame.render_widget(hint, rows[0]);

    let selected = app.best_of_modal.as_ref().map(|m| m.selected).unwrap_or(0);
    let options = [1usize, 2, 3, 4];
    let mut items: Vec<ListItem> = Vec::new();
    for &attempts in &options {
        let noun = if attempts == 1 { "attempt" } else { "attempts" };
        let mut spans: Vec<ratatui::text::Span> = vec![format!("{attempts} {noun:<8}").into()];
        spans.push("  ".into());
        spans.push(format!("{attempts}x parallel").dim());
        if attempts == app.best_of_n {
            spans.push("  ".into());
            spans.push("Current".magenta().bold());
        }
        items.push(ListItem::new(Line::from(spans)));
    }
    let sel = selected.min(options.len().saturating_sub(1));
    let mut list_state = ListState::default().with_selected(Some(sel));
    let list = List::new(items)
        .highlight_symbol("")
        .highlight_style(Style::default().bold())
        .block(Block::default().borders(Borders::NONE));
    frame.render_stateful_widget(list, rows[1], &mut list_state);
}