opencrabs 0.3.23

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! Input box rendering
//!
//! Text input area with cursor and slash command autocomplete dropdown.

use super::super::app::App;
use super::utils::format_token_count_raw;
use ratatui::{
    Frame,
    layout::{Alignment, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
};

struct SelConfig<'a> {
    sel_from: usize,
    sel_to: usize,
    selection_style: &'a Style,
    cursor_style: &'a Style,
    cursor_local_byte: Option<usize>,
}

#[allow(clippy::too_many_arguments)]
/// Apply selection highlighting to a visual row's text at the character level.
fn spans_with_selection(
    text: &str,
    row_byte_start: usize,
    row_byte_end: usize,
    sel: &SelConfig<'_>,
    prefix: Span<'static>,
) -> Line<'static> {
    let has_sel = row_byte_end > sel.sel_from && row_byte_start < sel.sel_to;
    let has_cursor = sel.cursor_local_byte.is_some();

    if !has_sel && !has_cursor {
        return Line::from(vec![prefix, Span::raw(text.to_string())]);
    }

    let mut spans: Vec<Span<'static>> = vec![prefix];
    for (idx, ch) in text.char_indices() {
        let global_start = row_byte_start + idx;
        let ch_len = ch.len_utf8();
        let global_end = global_start + ch_len;

        let in_sel = global_start >= sel.sel_from && global_end <= sel.sel_to;
        let is_cursor = sel.cursor_local_byte == Some(idx);

        let span_text = if is_cursor && !in_sel {
            Span::styled(ch.to_string(), *sel.cursor_style)
        } else if in_sel {
            Span::styled(ch.to_string(), *sel.selection_style)
        } else if is_cursor && in_sel {
            Span::styled(
                ch.to_string(),
                Style::default()
                    .fg(Color::White)
                    .bg(Color::Rgb(50, 80, 160)),
            )
        } else {
            Span::raw(ch.to_string())
        };
        spans.push(span_text);
    }

    if sel.cursor_local_byte == Some(text.len()) {
        let at_end_sel =
            row_byte_start + text.len() >= sel.sel_from && row_byte_start + text.len() < sel.sel_to;
        if at_end_sel {
            spans.push(Span::styled(" ", *sel.selection_style));
        } else {
            spans.push(Span::styled(" ", *sel.cursor_style));
        }
    }

    Line::from(spans)
}

/// Render queued messages above the input area.
/// Returns the height consumed (0 if no queue).
pub(super) fn render_queue(f: &mut Frame, app: &App, area: Rect) -> u16 {
    let Some(session) = &app.current_session else {
        return 0;
    };
    // Snapshot the relevant entry under the lock, then drop the guard
    // before doing any rendering — keeps the critical section short and
    // avoids holding the mutex across render work.
    let (msgs_count, last_msg) = {
        let Ok(map) = app.queued_messages.lock() else {
            return 0;
        };
        let Some(msgs) = map.get(&session.id) else {
            return 0;
        };
        if msgs.is_empty() {
            return 0;
        }
        (msgs.len(), msgs.last().cloned().unwrap_or_default())
    };

    let dim_style = Style::default().fg(Color::Rgb(100, 100, 100));
    // Show the last queued message as preview
    let flat = last_msg.replace('\n', " ");
    let content_width = area.width.saturating_sub(2) as usize; // borders
    let max_preview = content_width.saturating_sub(30);
    let preview: String = if flat.chars().count() > max_preview {
        let truncated: String = flat.chars().take(max_preview).collect();
        format!("{}...", truncated)
    } else {
        flat
    };

    let count_label = if msgs_count > 1 {
        format!("⏳ queued ({}): ", msgs_count)
    } else {
        "⏳ queued: ".to_string()
    };

    let line = Line::from(vec![
        Span::styled(count_label, dim_style),
        Span::styled(preview, dim_style.add_modifier(Modifier::ITALIC)),
        Span::styled(
            "  (Up to edit)",
            Style::default().fg(Color::Rgb(70, 70, 70)),
        ),
    ]);

    let queue_height = 2u16;
    let queue_area = Rect {
        x: area.x,
        y: area.y,
        width: area.width,
        height: queue_height,
    };

    let para = Paragraph::new(vec![line]).block(
        Block::default()
            .borders(Borders::TOP)
            .border_style(Style::default().fg(Color::Rgb(80, 80, 80))),
    );
    f.render_widget(para, queue_area);
    queue_height
}

/// Render the input box
pub(super) fn render_input(f: &mut Frame, app: &App, area: Rect) {
    let input_content_width = area.width.saturating_sub(2) as usize; // borders
    let mut input_lines: Vec<Line> = Vec::new();
    let mut cursor_row: usize = 0;

    // Check if current session has a queued message (for prefix styling)
    let has_queue = app
        .current_session
        .as_ref()
        .and_then(|s| {
            app.queued_messages
                .lock()
                .ok()
                .map(|q| q.contains_key(&s.id))
        })
        .unwrap_or(false);

    let cursor_style = Style::default()
        .fg(Color::Black)
        .bg(Color::Rgb(120, 120, 120));
    let selection_style = Style::default()
        .bg(Color::Rgb(50, 80, 160))
        .fg(Color::White);

    // Compute selection byte range from drag coordinates
    let sel_from_to: Option<(usize, usize)> = if app.input_drag_selecting {
        let a = app.input_drag_anchor.unwrap_or((0, 0));
        let b = app.input_drag_current.unwrap_or(a);
        let (start, end) = if (a.1, a.0) <= (b.1, b.0) {
            (a, b)
        } else {
            (b, a)
        };

        let input_top = app.input_area_y;
        let input_content_width = area.width.saturating_sub(2) as usize;
        let content_left = app.input_area_x + 2;

        if input_content_width == 0 || app.input_buffer.is_empty() {
            None
        } else {
            let start_visual = start.1.saturating_sub(input_top + 1) as usize;
            let end_visual = end.1.saturating_sub(input_top + 1) as usize;

            // Build a list of visual rows: each entry is (global_byte_start, global_byte_end)
            let mut visual_rows: Vec<(usize, usize)> = Vec::new();
            let buf = &app.input_buffer;
            let blen = buf.len();
            let mut ls = 0usize;
            while ls <= blen {
                let le = buf[ls..].find('\n').map(|i| ls + i).unwrap_or(blen);
                let line = &buf[ls..le];
                let lw = unicode_width::UnicodeWidthStr::width(line);
                let rows = if lw == 0 {
                    1
                } else {
                    lw.div_ceil(input_content_width)
                };
                for r in 0..rows {
                    let chunk_start = r * input_content_width;
                    let mut display_w = 0;
                    let mut char_start = 0;
                    let mut char_end = line.len();
                    let mut found_start = false;
                    for (idx, ch) in line.char_indices() {
                        let ch_w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
                        if r > 0 && !found_start && display_w >= chunk_start {
                            char_start = idx;
                            found_start = true;
                        }
                        if display_w + ch_w > chunk_start + input_content_width {
                            char_end = idx;
                            break;
                        }
                        display_w += ch_w;
                    }
                    visual_rows.push((ls + char_start, ls + char_end));
                }
                if le == blen {
                    break;
                }
                ls = le + 1;
            }

            let map_vr_to_byte = |vr: usize, col: u16| -> usize {
                if vr >= visual_rows.len() {
                    return blen;
                }
                let (rs, re) = visual_rows[vr];
                let line_text = &buf[rs..re];
                let target_disp = col.saturating_sub(content_left) as usize;
                let mut w = 0;
                for (idx, ch) in line_text.char_indices() {
                    if w >= target_disp {
                        return rs + idx;
                    }
                    w += unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
                }
                re
            };

            let from = map_vr_to_byte(start_visual, start.0);
            let to = map_vr_to_byte(end_visual, end.0);
            Some((from.min(to), from.max(to)))
        }
    } else {
        None
    };

    if app.input_buffer.is_empty() {
        input_lines.push(Line::from(vec![
            Span::styled("\u{276F} ", Style::default().fg(Color::Rgb(100, 100, 100))),
            Span::styled(" ", cursor_style),
        ]));
    } else {
        let buf = &app.input_buffer;
        let cursor_pos = app.cursor_position;
        let is_queued = has_queue;

        // Build visual rows from logical lines with wrapping
        let mut line_start = 0usize;
        let mut line_idx = 0usize;
        let buf_len = buf.len();
        while line_start <= buf_len {
            let line_end = buf[line_start..]
                .find('\n')
                .map(|i| line_start + i)
                .unwrap_or(buf_len);
            let line = &buf[line_start..line_end];
            let next_start = line_end + 1;
            let is_last_line = line_end == buf_len;

            let cursor_in_line = cursor_pos >= line_start && cursor_pos < line_end;
            let cursor_at_end_of_last_line = cursor_pos >= buf_len && is_last_line;

            let prefix = if line_idx == 0 {
                if is_queued {
                    Span::styled("", Style::default().fg(Color::Rgb(215, 100, 20)))
                } else if buf.starts_with('!') {
                    // Shell-mode prefix: brighter + orange so the prompt
                    // caret itself screams "this is shell, not LLM".
                    Span::styled(
                        "$ ",
                        Style::default()
                            .fg(Color::Rgb(215, 100, 20))
                            .add_modifier(Modifier::BOLD),
                    )
                } else {
                    Span::styled("\u{276F} ", Style::default().fg(Color::Rgb(100, 100, 100)))
                }
            } else {
                Span::raw("  ")
            };

            // Build wrapped visual rows for this logical line
            let lw = unicode_width::UnicodeWidthStr::width(line);
            let num_visual_rows = if lw == 0 {
                1
            } else {
                lw.div_ceil(input_content_width)
            };

            let (sel_from, sel_to) = sel_from_to.unwrap_or((usize::MAX, usize::MAX));

            for vr in 0..num_visual_rows {
                let chunk_start_display = vr * input_content_width;
                let chunk_end_display = chunk_start_display + input_content_width;

                // Find the byte range within `line` that fits this visual row
                let mut disp_w = 0;
                let mut char_start = 0;
                let mut char_end = line.len();
                for (idx, ch) in line.char_indices() {
                    let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
                    if vr == 0 && disp_w + cw > chunk_end_display {
                        char_end = idx;
                        break;
                    }
                    if vr > 0 {
                        if disp_w < chunk_start_display {
                            char_start = idx;
                        }
                        if disp_w + cw > chunk_end_display {
                            char_end = idx;
                            break;
                        }
                    }
                    disp_w += cw;
                }

                let chunk_text = &line[char_start..char_end];
                let global_chunk_start = line_start + char_start;
                let global_chunk_end = line_start + char_end;

                // Cursor position within this visual row (local byte index)
                let local_cursor = if cursor_in_line {
                    let c = cursor_pos.saturating_sub(line_start);
                    if c >= char_start && c <= char_end {
                        Some(c - char_start)
                    } else if c == line.len() && vr == num_visual_rows - 1 {
                        // Cursor at end of line, show on last visual row
                        Some(chunk_text.len())
                    } else {
                        None
                    }
                } else if cursor_at_end_of_last_line && is_last_line && vr == num_visual_rows - 1 {
                    Some(chunk_text.len())
                } else {
                    None
                };

                let line_sel = SelConfig {
                    sel_from,
                    sel_to,
                    selection_style: &selection_style,
                    cursor_style: &cursor_style,
                    cursor_local_byte: local_cursor,
                };
                let padded_line = spans_with_selection(
                    chunk_text,
                    global_chunk_start,
                    global_chunk_end,
                    &line_sel,
                    if vr == 0 {
                        prefix.clone()
                    } else {
                        Span::raw("  ")
                    },
                );

                input_lines.push(padded_line);

                if local_cursor.is_some() {
                    cursor_row = input_lines.len() - 1;
                }
            }

            if is_last_line {
                break;
            }
            line_start = next_start;
            line_idx += 1;
        }

        // If buffer ends with newline, add a cursor line
        if cursor_pos >= buf_len && buf.ends_with('\n') {
            input_lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(" ", cursor_style),
            ]));
            cursor_row = input_lines.len() - 1;
        }
    }

    // Shell-mode visual cue: tint the border orange when the buffer starts
    // with `!` so the user sees at-a-glance that Enter will run the rest
    // as a shell command (via `sh -c`) instead of sending it to the LLM.
    // This cue existed pre-drag-copy refactor and was lost in the rewrite.
    let border_style = if app.input_buffer.starts_with('!') {
        Style::default().fg(Color::Rgb(215, 100, 20)) // ACCENT_GOLD / shell mode
    } else {
        Style::default().fg(Color::Rgb(120, 120, 120))
    };

    // Context usage indicator (right-side bottom title)
    let context_title = if let Some(input_tok) = app.last_input_tokens {
        let pct = app.context_usage_percent();
        let context_color = if pct > 80.0 {
            Color::Red
        } else if pct > 60.0 {
            Color::Rgb(215, 100, 20)
        } else {
            Color::Cyan
        };
        let ctx_label = format_token_count_raw(input_tok as i32);
        let max_label = format_token_count_raw(app.context_max_tokens as i32);
        let context_label = format!(" ctx: {}/{} ({:.0}%) ", ctx_label, max_label, pct);
        Line::from(Span::styled(
            context_label,
            Style::default()
                .fg(context_color)
                .add_modifier(Modifier::BOLD),
        ))
        .alignment(Alignment::Right)
    } else {
        Line::from(Span::styled(
            " Context: – ",
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        ))
        .alignment(Alignment::Right)
    };

    // Build attachment indicator for the top-right title area
    let attach_title = if !app.attachments.is_empty() {
        let spans: Vec<Span> = app
            .attachments
            .iter()
            .enumerate()
            .flat_map(|(i, att)| {
                let focused = app.focused_attachment == Some(i);
                let kind = if att.is_video { "Video" } else { "Image" };
                let label = format!("{} #{}", kind, i + 1);
                let style = if focused {
                    // Highlight focused attachment — inverted colors
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::Rgb(60, 185, 185))
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                        .fg(Color::Rgb(60, 185, 185))
                        .add_modifier(Modifier::BOLD)
                };
                let mut result = vec![Span::styled(label, style)];
                if i + 1 < app.attachments.len() {
                    result.push(Span::styled(
                        " | ",
                        Style::default().fg(Color::Rgb(60, 185, 185)),
                    ));
                }
                result
            })
            .collect();
        let mut all_spans = vec![Span::styled(
            " [",
            Style::default()
                .fg(Color::Rgb(60, 185, 185))
                .add_modifier(Modifier::BOLD),
        )];
        all_spans.extend(spans);
        all_spans.push(Span::styled(
            "] ",
            Style::default()
                .fg(Color::Rgb(60, 185, 185))
                .add_modifier(Modifier::BOLD),
        ));
        Line::from(all_spans).alignment(Alignment::Right)
    } else {
        Line::from("")
    };

    let mut block = Block::default()
        .borders(Borders::TOP | Borders::BOTTOM)
        .title_bottom(context_title)
        .border_style(border_style);

    if !app.attachments.is_empty() {
        block = block.title(attach_title);
    }

    // Compute a vertical scroll so the cursor row is always inside the
    // visible viewport (area.height - 2 for top/bottom borders).
    let inner_rows = area.height.saturating_sub(2) as usize;
    let total_rows = input_lines.len();
    let scroll_y: u16 = if inner_rows == 0 || total_rows <= inner_rows {
        0
    } else if cursor_row >= inner_rows {
        // Keep cursor on the last visible row.
        (cursor_row + 1 - inner_rows) as u16
    } else {
        0
    };

    let input = Paragraph::new(input_lines)
        .style(Style::default().fg(Color::Reset))
        .scroll((scroll_y, 0))
        .block(block);

    f.render_widget(input, area);
}

/// Sizing math for the slash-autocomplete dropdown.
///
/// Pure function pulled out of `render_slash_autocomplete` so the
/// regression (long skill descriptions overshooting the frame's right
/// edge and panicking ratatui's buffer write) is unit-testable without
/// a live `App`.
///
/// Behaviour: **responsive**. The dropdown grows to fit the longest row
/// (name column + description), capped at `input_area_width - 1` so
/// the right edge stays inside the frame. There is no fixed soft cap —
/// content shorter than the terminal renders without truncation;
/// content wider than the terminal is truncated to fit.
///
/// `name_col_chars` is the visual width reserved for the name column
/// across all rows so they line up — caller passes
/// `max(10, longest_name_chars)`.
///
/// Returns `(width, inner_width, desc_budget)`:
///   - `width`       — final dropdown rect width (incl. 2 borders + 2 pads)
///   - `inner_width` — usable width inside the borders + pads
///   - `desc_budget` — char budget for the truncated description portion
pub(crate) fn dropdown_dimensions(
    name_col_chars: u16,
    description_char_counts: &[usize],
    input_area_width: u16,
    pad_x: u16,
) -> (u16, u16, usize) {
    // Dropdown is anchored at `input_area.x + 1`, so its absolute right
    // edge must stay within the frame's right edge — the maximum width
    // is therefore `input_area_width - 1`. Without this clamp, a long
    // description inflates `width` to `input_area_width` and ratatui
    // rejects the write at column `input_area_width` with an
    // "index outside of buffer" panic.
    let max_dropdown_width = input_area_width.saturating_sub(1).max(1);
    let chrome = 2 + 2 * pad_x; // 2 borders + 2 pads
    // Each rendered row is: "  " + name (padded to name_col_chars) +
    // " " + desc + " ". The leading "  " is part of the name span; the
    // trailing " " bookends the desc span. Total = 2 + name_col + 1 + desc + 1.
    let row_overhead: u16 = 2 + name_col_chars + 1 + 1;
    let max_content_width = description_char_counts
        .iter()
        .map(|&desc_len| row_overhead.saturating_add(desc_len as u16))
        .max()
        .unwrap_or(40);
    // Final width = content + chrome, with a 40-col floor for usability,
    // capped at the terminal-safe maximum.
    let width = (max_content_width.saturating_add(chrome))
        .max(40)
        .min(max_dropdown_width);
    let inner_width = width.saturating_sub(chrome);
    let desc_budget = inner_width.saturating_sub(row_overhead) as usize;
    (width, inner_width, desc_budget)
}

/// Truncate `s` to at most `max_chars` Unicode scalar values, appending an
/// ellipsis (`…`) when truncation occurred. Returns a `Cow` so the
/// allocation is skipped on the common no-truncate path. Char count is
/// not the same as terminal display width for emoji/CJK, but it's a
/// close-enough proxy for the dropdown row, and importantly it stops
/// 200-char skill descriptions from overflowing the soft width cap.
pub(crate) fn truncate_to_chars(s: &str, max_chars: usize) -> std::borrow::Cow<'_, str> {
    if max_chars == 0 {
        return std::borrow::Cow::Borrowed("");
    }
    if s.chars().count() <= max_chars {
        return std::borrow::Cow::Borrowed(s);
    }
    // Reserve one char slot for the ellipsis.
    let keep = max_chars.saturating_sub(1);
    let mut out: String = s.chars().take(keep).collect();
    out.push('');
    std::borrow::Cow::Owned(out)
}

/// Result of fitting the slash-autocomplete dropdown into the rows
/// available above the input area.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DropdownFit {
    /// Final dropdown rect height (incl. borders + padding).
    pub height: u16,
    /// Number of items rendered this frame (after scroll window).
    pub visible_items: u16,
    /// Index into the full filtered list at which the visible window starts.
    pub scroll_offset: u16,
}

/// Fit a popup of `total_items` rows into `rows_above_input` rows. If the
/// popup would overflow (default macOS Terminal / Ghostty / old Windows
/// Terminal sit at 80×24, while the full SLASH_COMMANDS + skills list
/// regularly hits 30+ entries), clamp height and scroll the visible
/// window so `selected` stays in view.
///
/// `chrome` is rows consumed by borders + padding (top + bottom).
///
/// Returns `None` when there's literally no room (need at least
/// `chrome + 1` rows for one item) — caller should skip rendering rather
/// than draw an oversized Rect that panics ratatui's buffer write. That
/// panic is the root cause of the "complete empty window, only Ctrl+C
/// escapes" lock-up seen on macOS Terminal / Ghostty.
pub(crate) fn fit_dropdown(
    total_items: u16,
    selected: u16,
    rows_above_input: u16,
    chrome: u16,
) -> Option<DropdownFit> {
    if total_items == 0 || rows_above_input < chrome + 1 {
        return None;
    }
    let desired = total_items.saturating_add(chrome);
    let height = desired.min(rows_above_input);
    let visible_items = height.saturating_sub(chrome);
    // Scroll so the selected row stays inside the visible window.
    let scroll_offset = if selected < visible_items {
        0
    } else {
        selected.saturating_sub(visible_items - 1)
    };
    // Clamp so scroll_offset + visible_items never overshoots total_items.
    let scroll_offset = scroll_offset.min(total_items.saturating_sub(visible_items));
    Some(DropdownFit {
        height,
        visible_items,
        scroll_offset,
    })
}

/// Render slash command autocomplete dropdown above the input area
pub(super) fn render_slash_autocomplete(f: &mut Frame, app: &App, input_area: Rect) {
    let count = app.slash_filtered.len() as u16;
    if count == 0 {
        return;
    }

    // Padding: 1 char each side (left/right inside border), 1 empty line top/bottom.
    let pad_x: u16 = 1;
    let pad_y: u16 = 1;
    let chrome = 2 + pad_y * 2;

    // Fit into the rows ABOVE the input area. Without this clamp,
    // a long built-in + skills list produces a dropdown taller than
    // the terminal (default Terminal.app / Ghostty / Windows Terminal
    // sit at 24 rows), ratatui panics writing out of buffer bounds,
    // catch_unwind clears the screen, the next frame panics again,
    // and the user sees a totally blank TUI that only Ctrl+C escapes.
    let selected = app.slash_selected_index as u16;
    let Some(fit) = fit_dropdown(count, selected, input_area.y, chrome) else {
        return;
    };
    let visible_items_count = fit.visible_items as usize;
    let scroll_offset = fit.scroll_offset as usize;

    // Sizing math is in `dropdown_dimensions` so the regression (long
    // skill descriptions overflowing the buffer) is unit-testable without
    // a live App. The dropdown is responsive — width grows to fit the
    // longest row, capped at `input_area.width - 1`.
    let visible_end = (scroll_offset + visible_items_count).min(app.slash_filtered.len());
    let visible_slice = &app.slash_filtered[scroll_offset..visible_end];
    let mut name_lengths: Vec<usize> = Vec::with_capacity(visible_slice.len());
    let mut desc_lengths: Vec<usize> = Vec::with_capacity(visible_slice.len());
    for &idx in visible_slice {
        name_lengths.push(app.slash_command_name(idx).unwrap_or("").chars().count());
        desc_lengths.push(
            app.slash_command_description(idx)
                .unwrap_or("")
                .chars()
                .count(),
        );
    }
    // Name column is the longest name across the visible set, with a
    // 10-char floor so very short names don't make the dropdown look
    // cramped. The display format `{:<10}` pads short names to 10
    // automatically; longer names render at their natural width.
    let name_col_chars = name_lengths.iter().copied().max().unwrap_or(10).max(10) as u16;
    let (width, _inner_width, desc_budget) =
        dropdown_dimensions(name_col_chars, &desc_lengths, input_area.width, pad_x);
    let dropdown_area = Rect {
        x: input_area.x + 1,
        y: input_area.y.saturating_sub(fit.height),
        width,
        height: fit.height,
    };

    // Build dropdown lines (supports built-in commands, user-defined commands, and skills)
    let lines: Vec<Line> = visible_slice
        .iter()
        .enumerate()
        .map(|(i, &cmd_idx)| {
            let name = app.slash_command_name(cmd_idx).unwrap_or("???");
            let raw_desc = app.slash_command_description(cmd_idx).unwrap_or("");
            let desc = truncate_to_chars(raw_desc, desc_budget);
            let is_selected = (scroll_offset + i) == app.slash_selected_index;

            let style = if is_selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Gray)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::Reset)
            };

            let desc_style = if is_selected {
                Style::default().fg(Color::Black).bg(Color::Gray)
            } else {
                Style::default().fg(Color::DarkGray)
            };

            // Pad the name column to `name_col_chars` so descriptions
            // line up vertically. `format!` width arg has to be `usize`.
            let name_col = name_col_chars as usize;
            Line::from(vec![
                Span::styled(format!("  {:<width$}", name, width = name_col), style),
                Span::styled(format!(" {} ", desc.as_ref()), desc_style),
            ])
        })
        .collect();

    // Wrap with empty lines for top/bottom padding
    let mut padded_lines = Vec::with_capacity(lines.len() + 2);
    padded_lines.push(Line::from(""));
    padded_lines.extend(lines);
    padded_lines.push(Line::from(""));

    // Clear the area and render the dropdown
    f.render_widget(Clear, dropdown_area);
    let dropdown = Paragraph::new(padded_lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Rgb(120, 120, 120))),
    );
    f.render_widget(dropdown, dropdown_area);
}

/// Render the emoji picker popup above the input box.
pub(super) fn render_emoji_picker(f: &mut Frame, app: &App, input_area: Rect) {
    let count = app.emoji_filtered.len() as u16;
    if count == 0 {
        return;
    }

    // Same fit-or-skip rule as the slash dropdown — an oversized popup
    // (e.g. unfiltered emoji list = 100+ entries) on a 24-row terminal
    // would write past the buffer and crash the render loop.
    let chrome: u16 = 4; // borders + padding
    let Some(fit) = fit_dropdown(count, app.emoji_selected_index as u16, input_area.y, chrome)
    else {
        return;
    };
    let visible_items_count = fit.visible_items as usize;
    let scroll_offset = fit.scroll_offset as usize;
    let visible_end = (scroll_offset + visible_items_count).min(app.emoji_filtered.len());
    let visible_slice = &app.emoji_filtered[scroll_offset..visible_end];

    let width = 36u16.min(input_area.width);
    let dropdown_area = Rect {
        x: input_area.x + 1,
        y: input_area.y.saturating_sub(fit.height),
        width,
        height: fit.height,
    };

    let lines: Vec<Line> = visible_slice
        .iter()
        .enumerate()
        .map(|(i, &(emoji, shortcode))| {
            let is_selected = (scroll_offset + i) == app.emoji_selected_index;
            let style = if is_selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Gray)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::Reset)
            };
            let sc_style = if is_selected {
                Style::default().fg(Color::Black).bg(Color::Gray)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            Line::from(vec![
                Span::styled(format!("  {} ", emoji), style),
                Span::styled(format!(":{}: ", shortcode), sc_style),
            ])
        })
        .collect();

    let mut padded = Vec::with_capacity(lines.len() + 2);
    padded.push(Line::from(""));
    padded.extend(lines);
    padded.push(Line::from(""));

    f.render_widget(Clear, dropdown_area);
    let dropdown = Paragraph::new(padded).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Rgb(120, 120, 120))),
    );
    f.render_widget(dropdown, dropdown_area);
}

/// Render the single-line status bar below the input box.
///
/// Layout:  provider / model  ·  [policy]          ⠙ OpenCrabs is thinking... (3s)
pub(super) fn render_status_bar(f: &mut Frame, app: &App, area: Rect) {
    if area.height == 0 || area.width == 0 {
        return;
    }

    let orange = Color::Rgb(215, 100, 20);

    // --- Session name (left) ---
    let session_name = app
        .current_session
        .as_ref()
        .and_then(|s| s.title.as_deref())
        .unwrap_or("Chat")
        .to_string();

    // --- Provider / model ---
    // Read from the authoritative source: agent_service.session_providers.
    // DB records (current_session.provider_name/model) can lag behind
    // after sticky fallbacks or /models swaps. session_providers is always
    // live and per-session isolated.
    let (provider_str, model_str) = if let Some(ref session) = app.current_session {
        let prov = app.agent_service.provider_name_for_session(session.id);
        let model = app.agent_service.provider_model_for_session(session.id);
        let prefix = format!("{}/", prov);
        let stripped = model.strip_prefix(&prefix).unwrap_or(&model);
        (
            prov,
            crate::tui::provider_selector::model_display_label(stripped).to_string(),
        )
    } else {
        (
            app.agent_service.provider_name(),
            crate::tui::provider_selector::model_display_label(
                app.agent_service.provider_model().as_str(),
            )
            .to_string(),
        )
    };

    // Working directory — collapse $HOME to ~, then truncate if still long
    let raw_dir = app.working_directory.to_string_lossy();
    let home_dir = dirs::home_dir()
        .map(|h| h.to_string_lossy().to_string())
        .unwrap_or_default();
    let short_dir = if !home_dir.is_empty() && raw_dir.starts_with(&home_dir) {
        format!("~{}", &raw_dir[home_dir.len()..])
    } else {
        raw_dir.to_string()
    };
    let display_dir = if short_dir.len() > 40 {
        let mut start = short_dir.len().saturating_sub(37);
        while start > 0 && !short_dir.is_char_boundary(start) {
            start -= 1;
        }
        format!("...{}", &short_dir[start..])
    } else {
        short_dir
    };

    let session_text = format!(" {}", session_name);
    let provider_model_dir_text =
        format!("  ·  {} / {}  ·  {}", provider_str, model_str, display_dir);
    let sep_text = "  ·  ";

    // --- Approval policy (centre-left) ---
    let (policy_text, policy_color) = if app.approval_auto_always {
        ("⚡ yolo", Color::Red)
    } else if app.approval_auto_session {
        ("⚡ auto (session)", orange)
    } else {
        ("🔒 approve", Color::DarkGray)
    };

    let mut spans = vec![
        Span::styled(
            session_text,
            Style::default().fg(orange).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            provider_model_dir_text,
            Style::default().fg(Color::Rgb(90, 110, 150)),
        ),
        Span::styled(sep_text, Style::default().fg(Color::DarkGray)),
        Span::styled(policy_text, Style::default().fg(policy_color)),
    ];

    // Split pane indicator
    if app.pane_manager.is_split() {
        let pane_count = app.pane_manager.pane_count();
        let focused_idx = app
            .pane_manager
            .pane_ids_in_order()
            .iter()
            .position(|id| *id == app.pane_manager.focused)
            .map(|i| i + 1)
            .unwrap_or(1);
        spans.push(Span::styled("  ·  ", Style::default().fg(Color::DarkGray)));
        spans.push(Span::styled(
            format!("[{}/{}]", focused_idx, pane_count),
            Style::default().fg(Color::Rgb(80, 200, 120)),
        ));
    }

    let line = Line::from(spans);
    let para = Paragraph::new(line).alignment(Alignment::Left);
    f.render_widget(para, area);
}