claux 20260908.0.0

Terminal AI coding assistant with tool execution
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
//! Shared UI drawing helpers for the TUI.

use ratatui::{
    layout::{Constraint, Direction, Layout},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, Wrap},
    Frame,
};

use super::chat::{ChatApp, ChatMessage, Mode, ToolStatus};
use super::markdown;

/// Rendered lines for `ChatApp::messages`, cached across frames.
///
/// Rendering history means a markdown parse per message plus a word-wrap
/// pass over everything; at a few hundred messages that costs tens of
/// milliseconds, and draw_chat runs on a 50ms tick while streaming. The
/// cache makes each frame O(streaming tail): it is rebuilt only when the
/// message list changes (`rev`) or the text width changes.
pub struct HistoryCache {
    pub rev: u64,
    pub width: u16,
    pub lines: Vec<Line<'static>>,
    /// Rendered row count of each line at `width`, so the draw path can
    /// select just the visible window without re-wrapping history.
    pub line_rows: Vec<u16>,
    pub rows: u16,
}

/// Exact rendered row count for one line word-wrapped at `width`.
/// WordWrapper wraps logical lines independently, so per-line counts of
/// separate slices add up exactly.
fn count_line_rows(line: &Line<'static>, width: u16) -> u16 {
    Paragraph::new(vec![line.clone()])
        .wrap(Wrap { trim: false })
        .line_count(width) as u16
}

/// Draw the chat screen.
pub fn draw_chat(f: &mut Frame, app: &mut ChatApp) {
    draw_chat_at(f, app, std::time::Instant::now());
}

pub(super) fn draw_chat_at(f: &mut Frame, app: &mut ChatApp, now: std::time::Instant) {
    let input_height = if app.permission_details.is_some() {
        let detail_lines = app
            .permission_details
            .as_ref()
            .map(|d| d.len())
            .unwrap_or(0);
        // Content: summary + blank + details + blank + y/n/a options,
        // plus 2 border rows. Undersizing this clips the options line,
        // leaving the user with a question and no visible answers.
        (detail_lines as u16 + 6).min(f.area().height / 2)
    } else {
        let text = editor_text(app);
        let inner_width = f.area().width.saturating_sub(2).max(1) as usize;
        let cursor = if app.mode == Mode::Input {
            app.cursor
        } else {
            super::input::char_count(&text)
        };
        let rows = super::input::visual_layout(&text, cursor, inner_width)
            .lines
            .len() as u16;
        let max_height = (f.area().height / 2).max(3);
        rows.saturating_add(2).min(max_height)
    };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(input_height),
            Constraint::Length(1),
        ])
        .split(f.area());

    // Header
    let header = Paragraph::new(Line::from(vec![
        Span::styled(
            " claux ",
            Style::default()
                .fg(app.theme.assistant_bold)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("v{}", app.version),
            Style::default().fg(app.theme.dim),
        ),
    ]));
    f.render_widget(header, chunks[0]);

    // Messages area
    let msg_area = chunks[1];
    let inner_width = msg_area.width.saturating_sub(2).max(1);

    // Rebuild the history cache only when messages or width changed
    let cache_valid = app
        .history_cache
        .as_ref()
        .is_some_and(|c| c.rev == app.messages_rev && c.width == inner_width);
    if !cache_valid {
        let lines = history_lines(app);
        let line_rows: Vec<u16> = lines
            .iter()
            .map(|l| count_line_rows(l, inner_width))
            .collect();
        let rows = line_rows.iter().sum();
        app.history_cache = Some(HistoryCache {
            rev: app.messages_rev,
            width: inner_width,
            lines,
            line_rows,
            rows,
        });
    }

    // Streaming buffer (the per-frame tail, rendered fresh each draw)
    let history_empty = app.messages.is_empty();
    let mut tail_lines: Vec<Line> = Vec::new();
    if !app.stream_buffer.is_empty() {
        if !history_empty {
            tail_lines.push(Line::from(""));
        }
        tail_lines.push(Line::from(vec![
            Span::styled("", Style::default().fg(app.theme.success)),
            Span::styled(
                format!("{} ", app.model),
                Style::default()
                    .fg(app.theme.success)
                    .add_modifier(Modifier::BOLD),
            ),
        ]));
        let rendered = markdown::render(&app.stream_buffer, Style::default().fg(app.theme.success));
        for line in rendered {
            let mut indented = vec![Span::raw("  ")];
            indented.extend(line.spans);
            tail_lines.push(Line::from(indented));
        }
        tail_lines.push(Line::from(Span::styled(
            "",
            Style::default().fg(app.theme.success),
        )));
    }
    let tail_rows: Vec<u16> = tail_lines
        .iter()
        .map(|l| count_line_rows(l, inner_width))
        .collect();

    if !app.manual_scroll {
        app.scroll = 0;
    }
    let visible_height = msg_area.height;
    let manual_scroll = app.manual_scroll;
    let user_scroll = app.scroll;

    // Select only the logical lines that intersect the viewport and hand
    // the renderer a local offset. Passing everything makes the render
    // itself O(history): ratatui re-wraps every row above the scroll
    // offset each frame to find the window.
    let (render_lines, local_offset, total_rows) = {
        let cache = app
            .history_cache
            .as_ref()
            .expect("history cache just built");

        let total_rows = cache.rows + tail_rows.iter().sum::<u16>();
        let max_scroll = total_rows.saturating_sub(visible_height);
        let scroll_offset = if manual_scroll {
            max_scroll.saturating_sub(user_scroll.min(max_scroll))
        } else {
            max_scroll
        };

        let line_count = cache.lines.len() + tail_lines.len();
        let rows_at = |i: usize| -> u16 {
            if i < cache.line_rows.len() {
                cache.line_rows[i]
            } else {
                tail_rows[i - cache.line_rows.len()]
            }
        };

        // Skip whole lines that end above the viewport
        let mut first = 0usize;
        let mut skipped: u16 = 0;
        while first < line_count && skipped + rows_at(first) <= scroll_offset {
            skipped += rows_at(first);
            first += 1;
        }
        let local_offset = scroll_offset - skipped;

        // Take lines until the viewport is covered
        let mut render_lines: Vec<Line<'static>> = Vec::new();
        let mut covered: u16 = 0;
        let needed = local_offset.saturating_add(visible_height);
        let mut i = first;
        while i < line_count && covered < needed {
            let line = if i < cache.lines.len() {
                cache.lines[i].clone()
            } else {
                tail_lines[i - cache.lines.len()].clone()
            };
            covered += rows_at(i);
            render_lines.push(line);
            i += 1;
        }

        (render_lines, local_offset, total_rows)
    };

    app.total_lines = total_rows;

    let messages_widget = Paragraph::new(render_lines)
        .block(
            Block::default()
                .borders(Borders::LEFT | Borders::RIGHT)
                .border_style(Style::default().fg(app.theme.dim)),
        )
        .wrap(Wrap { trim: false })
        .scroll((local_offset, 0));
    f.render_widget(messages_widget, msg_area);

    draw_input_and_status(f, app, &chunks, now);
}

/// Render `app.messages` into styled lines. Called only on cache misses.
fn history_lines(app: &ChatApp) -> Vec<Line<'static>> {
    let mut lines: Vec<Line> = Vec::new();

    for msg in &app.messages {
        if !lines.is_empty() {
            lines.push(Line::from(""));
        }

        match msg {
            ChatMessage::Text { role, content } => match role.as_str() {
                "user" => {
                    let bubble_lines: Vec<Line> = content
                        .lines()
                        .map(|line| {
                            Line::from(Span::styled(
                                format!("  {line}"),
                                Style::default()
                                    .fg(app.theme.user_message_fg)
                                    .bg(app.theme.user_message_bg),
                            ))
                        })
                        .collect();

                    lines.push(Line::from(vec![
                        Span::styled("", Style::default().fg(app.theme.user)),
                        Span::styled(
                            "You",
                            Style::default()
                                .fg(app.theme.user)
                                .add_modifier(Modifier::BOLD),
                        ),
                    ]));
                    for line in bubble_lines {
                        lines.push(line);
                    }
                }
                "assistant" => {
                    lines.push(Line::from(vec![
                        Span::styled("", Style::default().fg(app.theme.assistant)),
                        Span::styled(
                            format!("{} ", app.model),
                            Style::default()
                                .fg(app.theme.assistant_bold)
                                .add_modifier(Modifier::BOLD),
                        ),
                    ]));
                    let rendered = markdown::render(content, Style::default().fg(app.theme.fg));
                    for line in rendered {
                        let mut indented = vec![Span::raw("  ")];
                        indented.extend(line.spans);
                        lines.push(Line::from(indented));
                    }
                }
                "system" => {
                    lines.push(Line::from(Span::styled(
                        "",
                        Style::default().fg(app.theme.warning),
                    )));
                    for line in content.lines() {
                        lines.push(Line::from(Span::styled(
                            format!("  {line}"),
                            Style::default().fg(app.theme.warning),
                        )));
                    }
                }
                "error" => {
                    lines.push(Line::from(Span::styled(
                        "",
                        Style::default().fg(app.theme.error),
                    )));
                    for line in content.lines() {
                        lines.push(Line::from(Span::styled(
                            format!("  {line}"),
                            Style::default().fg(app.theme.error),
                        )));
                    }
                }
                _ => {
                    lines.push(Line::from(Span::styled(
                        "",
                        Style::default().fg(app.theme.dim),
                    )));
                    for line in content.lines() {
                        lines.push(Line::from(Span::styled(
                            format!("  {line}"),
                            Style::default().fg(app.theme.fg),
                        )));
                    }
                }
            },
            ChatMessage::Tool {
                name,
                summary,
                detail,
                status,
                output,
            } => {
                let (indicator, indicator_color) = match status {
                    ToolStatus::Queued => ("", app.theme.dim),
                    ToolStatus::Running => ("", app.theme.warning),
                    ToolStatus::Success => ("", app.theme.tool_success),
                    ToolStatus::Error => ("", app.theme.tool_error),
                };
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("{indicator} "),
                        Style::default().fg(indicator_color),
                    ),
                    Span::styled(
                        format!("{name} "),
                        Style::default()
                            .fg(app.theme.tool_name)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(summary.clone(), Style::default().fg(app.theme.tool_summary)),
                ]));
                if let Some(detail) = detail {
                    lines.push(Line::from(vec![
                        Span::styled("  └─ ", Style::default().fg(app.theme.dim)),
                        Span::styled(detail.clone(), Style::default().fg(app.theme.dim)),
                    ]));
                }
                if !output.is_empty() {
                    let preview: Vec<_> = output.lines().collect();
                    let start = if app.expand_tool_output {
                        0
                    } else {
                        preview.len().saturating_sub(3)
                    };
                    lines.push(Line::from(Span::styled(
                        if app.expand_tool_output {
                            "  output (Ctrl+O to collapse)"
                        } else {
                            "  output preview (Ctrl+O to expand when idle)"
                        },
                        Style::default().fg(app.theme.dim),
                    )));
                    for line in &preview[start..] {
                        lines.push(Line::from(Span::styled(
                            format!("{line}"),
                            Style::default().fg(app.theme.fg),
                        )));
                    }
                }
            }
        }
    }

    lines
}

/// Draw the slash-command menu floating above the input box.
///
/// Rendered after the main layout so it overlays the transcript rather than
/// displacing it - the input line must not jump around while the user types.
/// Nothing is drawn when no completion is active, so this is a no-op on the
/// overwhelming majority of frames.
fn draw_completion_popup(f: &mut Frame, app: &mut ChatApp, input_area: ratatui::layout::Rect) {
    let Some(active) = app.completion.active(&app.input, app.cursor) else {
        return;
    };

    // Show the whole list when it fits. A fixed cap hid commands outright: with
    // eleven commands and a cap of eight, typing `/` never revealed the last
    // three, and the window only scrolled once the selection moved past the
    // edge - so they were invisible until the user typed enough to filter them
    // in. Bound by the space above the input instead, keeping a couple of rows
    // of conversation visible, and only scroll when the list genuinely cannot
    // fit.
    let room = (input_area.y as usize).saturating_sub(2); // leave some transcript
    let max_rows = room.saturating_sub(2).max(1); // borders
    let visible = active.matches.len().min(max_rows);
    // Keep the selection inside the window when the list is taller than the
    // space available.
    let first = active
        .selected
        .saturating_sub(visible.saturating_sub(1))
        .min(active.matches.len().saturating_sub(visible));

    let width = active
        .matches
        .iter()
        .map(|spec| spec.usage().chars().count() + spec.summary.chars().count() + 4)
        .max()
        .unwrap_or(20)
        .clamp(20, input_area.width.saturating_sub(2) as usize) as u16;
    let height = (visible as u16 + 2).min(input_area.y.max(1)); // borders

    // Sit directly on top of the input box.
    let area = ratatui::layout::Rect {
        x: input_area.x,
        y: input_area.y.saturating_sub(height),
        width: width.min(input_area.width),
        height,
    };
    if area.height < 3 || area.width < 10 {
        return; // no room to draw anything legible
    }

    let name_width = active
        .matches
        .iter()
        .map(|spec| spec.usage().chars().count())
        .max()
        .unwrap_or(0);

    let rows: Vec<Line> = active
        .matches
        .iter()
        .enumerate()
        .skip(first)
        .take(visible)
        .map(|(idx, spec)| {
            let selected = idx == active.selected;
            let marker = if selected { "" } else { "  " };
            Line::from(vec![
                Span::styled(
                    format!("{marker}{:<name_width$}", spec.usage()),
                    Style::default().fg(if selected {
                        app.theme.user
                    } else {
                        app.theme.fg
                    }),
                ),
                Span::styled(
                    format!("  {}", spec.summary),
                    Style::default().fg(app.theme.dim),
                ),
            ])
        })
        .collect();

    let popup = Paragraph::new(rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(app.theme.dim)),
    );

    f.render_widget(Clear, area);
    f.render_widget(popup, area);
}

/// Draw the input (or permission) box and the status bar.
fn draw_input_and_status(
    f: &mut Frame,
    app: &mut ChatApp,
    chunks: &[ratatui::layout::Rect],
    now: std::time::Instant,
) {
    // Input area
    if let (Some(ref prompt), Some(ref details)) = (&app.permission_prompt, &app.permission_details)
    {
        let mut perm_lines: Vec<Line> = Vec::new();
        perm_lines.push(Line::from(vec![
            Span::styled("", Style::default().fg(app.theme.warning)),
            Span::styled(
                prompt.as_str(),
                Style::default()
                    .fg(app.theme.warning)
                    .add_modifier(Modifier::BOLD),
            ),
        ]));
        perm_lines.push(Line::from(""));
        for detail in details {
            let style = if detail.starts_with("  +") {
                Style::default().fg(app.theme.success)
            } else if detail.starts_with("  -") {
                Style::default().fg(app.theme.error)
            } else if detail.ends_with(':') {
                Style::default()
                    .fg(app.theme.fg)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(app.theme.dim)
            };
            perm_lines.push(Line::from(Span::styled(detail.clone(), style)));
        }
        perm_lines.push(Line::from(""));
        let always_label = if app.permission_always_is_command {
            "(a)lways allow this command"
        } else {
            "(a)lways allow"
        };
        perm_lines.push(Line::from(vec![
            Span::styled("  (y)es  ", Style::default().fg(app.theme.success)),
            Span::styled("(n)o  ", Style::default().fg(app.theme.error)),
            Span::styled(always_label, Style::default().fg(app.theme.warning)),
        ]));

        let perm_widget = Paragraph::new(perm_lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(app.theme.warning))
                .title(" Permission Required "),
        );
        f.render_widget(perm_widget, chunks[2]);
    } else {
        let input_text = editor_text(app);
        let inner_width = chunks[2].width.saturating_sub(2).max(1) as usize;
        let cursor = if app.mode == Mode::Input {
            app.cursor
        } else {
            super::input::char_count(&input_text)
        };
        let layout = super::input::visual_layout(&input_text, cursor, inner_width);
        let visible_rows = chunks[2].height.saturating_sub(2).max(1) as usize;
        let vertical_scroll = if app.mode == Mode::Input {
            layout.cursor_row.saturating_sub(visible_rows - 1)
        } else {
            layout.lines.len().saturating_sub(visible_rows)
        };
        let input_lines: Vec<Line> = layout
            .lines
            .iter()
            .map(|line| Line::from(line.as_str()))
            .collect();

        let input_widget = Paragraph::new(input_lines)
            .style(Style::default().fg(app.theme.fg))
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(if app.mode == Mode::Input {
                        app.theme.user
                    } else if let Some(activity) = &app.activity {
                        if now.saturating_duration_since(activity.updated).as_secs() >= 10 {
                            app.theme.warning
                        } else {
                            app.theme.assistant
                        }
                    } else {
                        app.theme.dim
                    }))
                    .title(activity_title(app, now)),
            )
            .scroll((vertical_scroll as u16, 0));
        f.render_widget(input_widget, chunks[2]);

        if app.mode == Mode::Input {
            draw_completion_popup(f, app, chunks[2]);

            let cursor_y = layout.cursor_row.saturating_sub(vertical_scroll);
            f.set_cursor_position((
                chunks[2].x + layout.cursor_col as u16 + 1,
                chunks[2].y + cursor_y as u16 + 1,
            ));
        }
    }

    // Status bar
    let thinking_indicator = if app.thinking {
        let spinner = ["", "", "", "", "", "", "", "", "", ""];
        let idx = (chrono::Local::now().timestamp_millis() / 100) as usize % spinner.len();
        format!(" {} ", spinner[idx])
    } else {
        " ".to_string()
    };

    let status = Paragraph::new(Line::from(vec![
        Span::styled(thinking_indicator, Style::default().fg(app.theme.success)),
        Span::styled(
            if app.save_error.is_some() {
                " UNSAVED · Ctrl+S retry · keep this chat open ".to_string()
            } else if !app.jobs.is_empty() {
                format!(
                    " {} background job(s) running · F6 tasks · {} ",
                    app.jobs.iter().filter(|j| j.status.active()).count(),
                    app.status
                )
            } else {
                format!(" {} ", app.status)
            },
            Style::default().fg(if app.save_error.is_some() {
                app.theme.tool_error
            } else {
                app.theme.dim
            }),
        ),
    ]));
    f.render_widget(status, chunks[3]);
    if app.show_jobs && app.mode != Mode::Permission {
        draw_jobs(f, app);
    }
}

fn draw_jobs(f: &mut Frame, app: &ChatApp) {
    let area = f.area();
    f.render_widget(Clear, area);
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2),
            Constraint::Length((app.jobs.len().min(8) as u16).max(1)),
            Constraint::Min(1),
            Constraint::Length(1),
        ])
        .split(area);
    f.render_widget(Paragraph::new(" Background jobs (session-owned; stop on close)\n ↑/↓ select · PgUp/PgDn output · x cancel · Esc/F6 close"), rows[0]);
    let start = app.selected_job.saturating_sub(7);
    let list: Vec<Line> = app
        .jobs
        .iter()
        .enumerate()
        .skip(start)
        .take(8)
        .map(|(i, job)| {
            Line::from(Span::styled(
                format!(
                    "{} {} | {} | {}s | {}",
                    if i == app.selected_job { ">" } else { " " },
                    job.id,
                    job.status.label(),
                    job.elapsed.as_secs(),
                    job.command.replace('\n', " ")
                ),
                Style::default().fg(if i == app.selected_job {
                    app.theme.warning
                } else {
                    app.theme.fg
                }),
            ))
        })
        .collect();
    f.render_widget(
        Paragraph::new(if list.is_empty() {
            vec![Line::from(
                " No jobs yet. Ask Claux to run a command in the background.",
            )]
        } else {
            list
        }),
        rows[1],
    );
    if let Some(job) = app.jobs.get(app.selected_job) {
        let text = if job.output.is_empty() {
            "No output yet."
        } else {
            &job.output
        };
        let output = Paragraph::new(text).wrap(Wrap { trim: false }).block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" {} output (bounded) ", job.id)),
        );
        let total = output.line_count(rows[2].width.saturating_sub(2).max(1)) as u16;
        let scroll = total
            .saturating_sub(rows[2].height.saturating_sub(2))
            .saturating_sub(app.job_scroll);
        f.render_widget(output.scroll((scroll, 0)), rows[2]);
    }
    f.render_widget(
        Paragraph::new(" Closing this panel keeps jobs running. Closing the session cancels them."),
        rows[3],
    );
}

fn activity_title(app: &ChatApp, now: std::time::Instant) -> String {
    let Some(activity) = &app.activity else {
        return " > ".to_string();
    };
    let elapsed = now.saturating_duration_since(activity.started);
    let quiet = now.saturating_duration_since(activity.updated).as_secs();
    let spinner = ["", "", "", "", "", "", "", "", "", ""];
    let frame = (elapsed.as_millis() / 100) as usize % spinner.len();
    let silence = if quiet >= 10 {
        format!(" · no updates for {quiet}s")
    } else {
        String::new()
    };
    format!(
        " {} {} · {}s{} ",
        spinner[frame],
        activity.label,
        elapsed.as_secs(),
        silence
    )
}

fn editor_text(app: &ChatApp) -> String {
    if app.mode == Mode::Streaming {
        let steer = app.steer_buf.lock().expect("steer buffer poisoned");
        if steer.is_empty() {
            "... (type to steer, Enter to queue, Ctrl+C to interrupt)".to_string()
        } else {
            steer.clone()
        }
    } else {
        app.input.clone()
    }
}

#[cfg(test)]
mod perf_probe {
    use super::*;
    use crate::theme::Theme;

    #[test]
    fn activity_shows_elapsed_and_quiet_time_without_claiming_progress() {
        let mut app = ChatApp::new("test-model", Theme::dark());
        app.set_activity("Running Bash");
        let start = app.activity.as_ref().unwrap().started;
        let title = activity_title(&app, start + std::time::Duration::from_secs(45));
        assert!(title.contains("Running Bash · 45s · no updates for 45s"));
        assert_ne!(
            activity_title(&app, start),
            activity_title(&app, start + std::time::Duration::from_millis(100))
        );

        app.activity.as_mut().unwrap().updated = start + std::time::Duration::from_secs(44);
        let title = activity_title(&app, start + std::time::Duration::from_secs(45));
        assert!(title.contains("Running Bash · 45s"));
        assert!(!title.contains("no updates"));
        app.activity = None;
        assert_eq!(activity_title(&app, start), " > ");
    }

    #[test]
    fn queued_tools_are_distinct_from_running_tools() {
        let mut app = ChatApp::new("test-model", Theme::dark());
        app.add_tool("Bash", "sleep 30", ToolStatus::Queued);
        let queued = history_lines(&app);
        assert_eq!(queued[0].spans[0].content, "");
        app.set_tool_status_at(0, ToolStatus::Running);
        let running = history_lines(&app);
        assert_eq!(running[0].spans[0].content, "");
    }

    #[test]
    fn time_draw_with_large_history() {
        let mut app = ChatApp::new("test-model", Theme::dark());
        for i in 0..150 {
            app.add_message(
                "user",
                &format!(
                    "question {i} about the codebase, with some length to it so wrapping happens"
                ),
            );
            app.add_message(
                "assistant",
                &format!("Here is a **detailed** answer {i} with `inline code`, a list:\n- point one about the design\n- point two with more words that will wrap on narrow terminals\n\nAnd a table:\n| a | b |\n|---|---|\n| {i} | value |\n\nPlus a trailing paragraph that is long enough to wrap at eighty columns for sure, repeating itself to add width and weight to the rendering cost."),
            );
            app.add_tool("Bash", "cargo test", ToolStatus::Success);
        }
        app.stream_buffer = "streaming tail ".repeat(20);
        app.mode = Mode::Streaming;

        // warm up
        let _ = tuishot::render_to_buffer(120, 40, |f| draw_chat(f, &mut app));

        let n = 20;
        let start = std::time::Instant::now();
        for _ in 0..n {
            let _ = tuishot::render_to_buffer(120, 40, |f| draw_chat(f, &mut app));
        }
        let per_draw = start.elapsed() / n;
        println!("per-draw: {per_draw:?} for {} messages", app.messages.len());

        // Regression guard: warm-cache draws must stay O(viewport), not
        // O(history). Before the history cache + viewport slicing this
        // measured ~58ms in a debug build; sliced it's ~3ms. The bound is
        // loose to tolerate slow CI, but tight enough to catch a return
        // to per-frame full-history rendering.
        assert!(
            per_draw < std::time::Duration::from_millis(25),
            "draw with large history too slow: {per_draw:?}"
        );
    }
}