sigit 0.1.1

siGit Code — ACP-compatible AI coding agent for smbCloud platform.
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
//! Full-screen terminal chat UI for siGit Code.
//!
//! Takes over the alternate screen and multiplexes terminal events with
//! streaming LLM tokens via `tokio::select!`.
//!
//! The UI has two phases:
//!
//! 1. **Loading phase** — a centered spinner is shown while the model loads
//!    in the background.  The oneshot channel from the caller signals
//!    completion or failure.
//! 2. **Chat phase** — normal interactive chat once `load_rx` resolves.

use std::future::pending;
use std::sync::mpsc as std_mpsc;

use anyhow::Result;
use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use futures::StreamExt;
use onde::inference::{ChatEngine, GgufModelConfig, SamplingConfig, StreamChunk};
use ratatui::{
    Frame,
    layout::{Constraint, Layout, Position},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};
use tokio::sync::mpsc;
use tokio::time::{Duration, Instant, interval};

// ── Message types ─────────────────────────────────────────────────────────────

#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
    User,
    Assistant,
    System,
    /// Banner art — each character gets its own color.
    Banner,
}

struct ChatMessage {
    role: Role,
    text: String,
}

impl ChatMessage {
    fn user(text: impl Into<String>) -> Self {
        Self {
            role: Role::User,
            text: text.into(),
        }
    }

    fn assistant(text: impl Into<String>) -> Self {
        Self {
            role: Role::Assistant,
            text: text.into(),
        }
    }

    fn system(text: impl Into<String>) -> Self {
        Self {
            role: Role::System,
            text: text.into(),
        }
    }

    fn banner(text: impl Into<String>) -> Self {
        Self {
            role: Role::Banner,
            text: text.into(),
        }
    }
}

// ── App state ─────────────────────────────────────────────────────────────────

struct App {
    messages: Vec<ChatMessage>,
    input: String,
    cursor: usize,
    scroll_offset: u16,
    stream_rx: Option<mpsc::Receiver<StreamChunk>>,
    stream_buf: String,
    quit: bool,
    /// Flips every few ticks while streaming to make the cursor blink.
    blink_on: bool,
    blink_counter: u8,

    // ── Loading-phase state ───────────────────────────────────────────────────
    /// True while the model is still loading; switches to false on completion.
    is_loading: bool,
    /// Monotonic counter incremented on every animation tick.  Drives the
    /// braille spinner shown during loading.
    load_tick: u32,
    /// Set when model loading fails; keeps the loading view up with the error.
    load_error: Option<String>,
    /// When loading started — drives the elapsed-time counter.
    load_start: Instant,
    /// Display name of the model being loaded (shown in the spinner line).
    load_model_name: String,
}

const BANNER_ART: &str = "\
77777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777
77777777322222222222222222222222222222223777389969902208431358831999699051111177777777777777
1111111125555555555555555555555511113222311159    5002         088    3081771691111111111111
1111111111111111111111111111131136841   1482853332007    05    9043332891    400811111111111
1111111111111111111111111111111201        109    304    40     00    79      100041111111111
333333255555555555555555555552392   102   503    90    7000000005    903    0000023333333333
333333245454545454545454545433381    7600000    302    61    780    109    20009533333333333
3333333333333333333333333333333402      7001    08    761    202    902    90003333333333333
2222255555555555555555555555250899901    49    304    403    08    108    300042222222222222
2222222222222222222222222222269   106    03    901    06    505    402    000052222222222222
2222255555555555555555555555299        708    1002          80     00      90852222222222222
55555555555555555555555555555560953258000866660000051140866908666600008966900065555555555555
88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888";

impl App {
    fn new(load_model_name: String) -> Self {
        Self {
            messages: Vec::new(),
            input: String::new(),
            cursor: 0,
            scroll_offset: 0,
            stream_rx: None,
            stream_buf: String::new(),
            quit: false,
            blink_on: true,
            blink_counter: 0,
            is_loading: true,
            load_tick: 0,
            load_error: None,
            load_start: Instant::now(),
            load_model_name,
        }
    }

    fn is_streaming(&self) -> bool {
        self.stream_rx.is_some()
    }

    fn finalize_stream(&mut self) {
        self.stream_rx = None;
        if !self.stream_buf.is_empty() {
            let text = std::mem::take(&mut self.stream_buf);
            self.messages.push(ChatMessage::assistant(text));
        }
        self.blink_on = false;
    }

    fn push_stream_delta(&mut self, delta: &str) {
        self.stream_buf.push_str(delta);
        self.blink_counter = self.blink_counter.wrapping_add(1);
        self.blink_on = self.blink_counter % 4 < 2;
    }

    /// Advance the spinner tick counter.
    fn tick(&mut self) {
        self.load_tick = self.load_tick.wrapping_add(1);
    }

    /// Transition from loading phase to normal chat.
    /// Adds the banner art and welcome messages to the message log.
    fn finish_loading(&mut self) {
        self.is_loading = false;
        for line in BANNER_ART.lines() {
            self.messages.push(ChatMessage::banner(line));
        }
        self.messages.push(ChatMessage::system(""));
        self.messages.push(ChatMessage::system(
            "In this world, nothing can be said to be certain, except death and taxes. ~ Pak Sigit",
        ));
        self.messages
            .push(ChatMessage::system("Type /help for commands."));
    }

    /// Record a loading error.  The loading view stays visible so the user can
    /// read the message before pressing Ctrl+C.
    fn set_load_error(&mut self, error: String) {
        self.load_error = Some(error);
        // is_loading stays true so render_loading() keeps rendering.
    }

    /// Total lines the messages area would need (rough estimate for scrolling).
    fn total_message_lines(&self, width: u16) -> u16 {
        if width == 0 {
            return 0;
        }
        let w = width.saturating_sub(2) as usize; // subtract border columns
        let mut lines: u16 = 0;
        for msg in &self.messages {
            lines += wrapped_line_count(&msg.text, msg.role, w);
        }
        // count any in-progress streaming text too
        if !self.stream_buf.is_empty() {
            lines += wrapped_line_count(&self.stream_buf, Role::Assistant, w);
        }
        lines
    }

    fn auto_scroll(&mut self, visible_height: u16, width: u16) {
        let total = self.total_message_lines(width);
        if total > visible_height {
            self.scroll_offset = total - visible_height;
        } else {
            self.scroll_offset = 0;
        }
    }
}



/// How many terminal rows a message takes up after line-wrapping.
fn wrapped_line_count(text: &str, role: Role, width: usize) -> u16 {
    let prefix_len = match role {
        Role::User => 6,      // "you > "
        Role::Assistant => 8, // "siGit > "
        Role::System | Role::Banner => 0,
    };
    let effective = if width > prefix_len {
        width - prefix_len
    } else {
        1
    };

    let mut count: u16 = 0;
    for line in text.split('\n') {
        if line.is_empty() {
            count += 1;
        } else {
            count += ((line.len() as f64) / (effective as f64)).ceil() as u16;
        }
    }
    count.max(1)
}

// ── Model table ──────────────────────────────────────────────────────────────

struct ModelOption {
    /// Name shown in `/models`. Must match `GgufModelConfig::display_name`.
    name: &'static str,
    /// Short blurb shown next to the name, e.g. "~2.7 GB".
    description: &'static str,
    /// True if this model actually handles tool calls.
    tool_calling: bool,
    /// Token budget for generation. Qwen 3 needs 4096+ or it outputs nothing.
    max_tokens: u64,
    config_fn: fn() -> GgufModelConfig,
}

const SIGIT_MODELS: &[ModelOption] = &[
    ModelOption {
        name: "Qwen 3 4B (Q4_K_M)",
        description: "~2.7 GB",
        tool_calling: true,
        max_tokens: 4096,
        config_fn: GgufModelConfig::qwen3_4b,
    },
    ModelOption {
        name: "Qwen 2.5 Coder 3B (Q4_K_M)",
        description: "~1.93 GB",
        tool_calling: false,
        max_tokens: 512,
        config_fn: GgufModelConfig::qwen25_coder_3b,
    },
    ModelOption {
        name: "Qwen 2.5 Coder 1.5B (Q4_K_M)",
        description: "~941 MB",
        tool_calling: false,
        max_tokens: 512,
        config_fn: GgufModelConfig::qwen25_coder_1_5b,
    },
];

// ── Slash commands ────────────────────────────────────────────────────────────

enum SlashCommand {
    Help,
    Clear,
    Status,
    /// `/models` lists models. `/models N` switches to model N (1-based).
    Models(Option<usize>),
    Exit,
    Unknown(String),
}

fn parse_slash(input: &str) -> Option<SlashCommand> {
    let trimmed = input.trim();
    if !trimmed.starts_with('/') {
        return None;
    }
    let mut parts = trimmed.splitn(2, char::is_whitespace);
    let cmd = parts.next().unwrap_or("");
    let arg = parts.next().map(|s| s.trim());
    Some(match cmd {
        "/help" => SlashCommand::Help,
        "/clear" => SlashCommand::Clear,
        "/status" => SlashCommand::Status,
        "/models" => SlashCommand::Models(arg.and_then(|s| s.parse::<usize>().ok())),
        "/exit" | "/quit" | "/q" => SlashCommand::Exit,
        other => SlashCommand::Unknown(other.to_string()),
    })
}

// ── Rendering ─────────────────────────────────────────────────────────────────

fn render(frame: &mut Frame, app: &mut App) {
    let area = frame.area();

    if app.is_loading {
        // Loading phase: title bar with spinner | loading info | footer hint.
        let zones = Layout::vertical([
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(1),
        ])
        .split(area);

        render_loading_title(frame, app, zones[0]);
        render_loading(frame, app, zones[1]);
        render_loading_footer(frame, zones[2]);
    } else {
        // Chat phase: title | messages | input | footer.
        let zones = Layout::vertical([
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(3),
            Constraint::Length(1),
        ])
        .split(area);

        render_title(frame, zones[0]);
        render_messages(frame, app, zones[1]);
        render_input(frame, app, zones[2]);
        render_footer(frame, app, zones[3]);
    }
}

fn render_title(frame: &mut Frame, area: ratatui::layout::Rect) {
    let title = Line::from(vec![
        Span::styled(
            "siGit",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" Code", Style::default().fg(Color::White)),
        Span::styled(
            format!(" v{}", env!("CARGO_PKG_VERSION")),
            Style::default().fg(Color::DarkGray),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(title).style(Style::default().bg(Color::Black)),
        area,
    );
}

/// Title bar during loading: `⠹ siGit Code v0.1.1`
fn render_loading_title(frame: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    const SPINNER: &[char] = &['', '', '', '', '', '', '', '', '', ''];
    let spinner = SPINNER[(app.load_tick as usize) % SPINNER.len()];

    let title = Line::from(vec![
        Span::styled(
            format!("{spinner} "),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            "siGit",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" Code", Style::default().fg(Color::White)),
        Span::styled(
            format!(" v{}", env!("CARGO_PKG_VERSION")),
            Style::default().fg(Color::DarkGray),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(title).style(Style::default().bg(Color::Black)),
        area,
    );
}

/// Loading body — model name, elapsed time, or error message.
fn render_loading(frame: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let elapsed = app.load_start.elapsed();
    let elapsed_str = if elapsed.as_secs() >= 60 {
        format!("{}m {:02}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
    } else {
        format!("{}s", elapsed.as_secs())
    };

    let mut lines: Vec<Line<'_>> = Vec::new();

    if let Some(ref err) = app.load_error {
        lines.push(Line::from(vec![
            Span::styled(
                "",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
            Span::styled(err.clone(), Style::default().fg(Color::Red)),
        ]));
    } else {
        lines.push(Line::from(vec![
            Span::styled(" Loading ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                app.load_model_name.clone(),
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("  {elapsed_str}"),
                Style::default().fg(Color::DarkGray),
            ),
        ]));
    }

    frame.render_widget(Paragraph::new(lines), area);
}

/// One-line footer shown only during the loading phase.
fn render_loading_footer(frame: &mut Frame, area: ratatui::layout::Rect) {
    let spans = vec![
        Span::styled(
            " Ctrl+C ",
            Style::default()
                .fg(Color::Black)
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" quit", Style::default().fg(Color::DarkGray)),
    ];
    frame.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(Color::Black)),
        area,
    );
}

fn render_messages(frame: &mut Frame, app: &mut App, area: ratatui::layout::Rect) {
    let mut lines: Vec<Line<'_>> = Vec::new();

    for msg in &app.messages {
        render_chat_message(&mut lines, msg);
    }

    // Streaming partial response.
    if !app.stream_buf.is_empty() || app.is_streaming() {
        let mut spans = vec![Span::styled(
            "siGit > ",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        )];

        // Split on newlines so multi-line streaming renders correctly.
        let buf_lines: Vec<&str> = app.stream_buf.split('\n').collect();
        for (i, segment) in buf_lines.iter().enumerate() {
            if i > 0 {
                lines.push(Line::from(std::mem::take(&mut spans)));
                // Continuation lines get no prefix.
            }
            spans.push(Span::raw(segment.to_string()));
        }

        // Blinking block cursor while streaming.
        if app.is_streaming() && app.blink_on {
            spans.push(Span::styled("", Style::default().fg(Color::Green)));
        }

        lines.push(Line::from(spans));
    }

    app.auto_scroll(area.height, area.width);

    let paragraph = Paragraph::new(lines)
        .wrap(Wrap { trim: false })
        .scroll((app.scroll_offset, 0))
        .style(Style::default());

    frame.render_widget(paragraph, area);
}

fn render_chat_message<'a>(lines: &mut Vec<Line<'a>>, msg: &ChatMessage) {
    let text_lines: Vec<&str> = msg.text.split('\n').collect();

    match msg.role {
        Role::User => {
            for (i, segment) in text_lines.iter().enumerate() {
                let mut spans = Vec::new();
                if i == 0 {
                    spans.push(Span::styled(
                        "you > ",
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    ));
                }
                spans.push(Span::styled(
                    segment.to_string(),
                    Style::default().fg(Color::White),
                ));
                lines.push(Line::from(spans));
            }
        }
        Role::Assistant => {
            for (i, segment) in text_lines.iter().enumerate() {
                let mut spans = Vec::new();
                if i == 0 {
                    spans.push(Span::styled(
                        "siGit > ",
                        Style::default()
                            .fg(Color::Green)
                            .add_modifier(Modifier::BOLD),
                    ));
                }
                spans.push(Span::styled(
                    segment.to_string(),
                    Style::default().fg(Color::White),
                ));
                lines.push(Line::from(spans));
            }
        }
        Role::System => {
            for segment in &text_lines {
                lines.push(Line::from(Span::styled(
                    segment.to_string(),
                    Style::default().fg(Color::DarkGray),
                )));
            }
        }
        Role::Banner => {
            for segment in &text_lines {
                lines.push(Line::from(Span::styled(
                    segment.to_string(),
                    Style::default().fg(Color::White),
                )));
            }
        }
    }
}

fn render_input(frame: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let block = Block::default()
        .borders(Borders::TOP)
        .border_style(Style::default().fg(Color::DarkGray))
        .title(if app.is_streaming() {
            " streaming… "
        } else {
            " message "
        })
        .title_style(Style::default().fg(if app.is_streaming() {
            Color::Yellow
        } else {
            Color::DarkGray
        }));

    let input_text = Paragraph::new(app.input.as_str())
        .style(Style::default().fg(if app.is_streaming() {
            Color::DarkGray
        } else {
            Color::White
        }))
        .block(block);

    frame.render_widget(input_text, area);

    // Place cursor inside the input block (offset by 1 for the border).
    if !app.is_streaming() {
        let x = area.x + app.cursor as u16 + 1;
        let y = area.y + 1;
        frame.set_cursor_position(Position::new(x.min(area.right().saturating_sub(1)), y));
    }
}

fn render_footer(frame: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let hints: &[(&str, &str)] = if app.is_streaming() {
        &[("Ctrl+C", "cancel")]
    } else {
        &[("Enter", "send"), ("/help", "commands"), ("Ctrl+C", "quit")]
    };

    let mut spans: Vec<Span<'_>> = Vec::new();
    for (i, (key, label)) in hints.iter().enumerate() {
        if i > 0 {
            spans.push(Span::styled("  ", Style::default()));
        }
        spans.push(Span::styled(
            format!(" {key} "),
            Style::default()
                .fg(Color::White)
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(
            format!(" {label}"),
            Style::default().fg(Color::DarkGray),
        ));
    }

    frame.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(Color::Black)),
        area,
    );
}

// ── Input handling ────────────────────────────────────────────────────────────

fn handle_key(app: &mut App, key: KeyEvent) -> Option<String> {
    if key.kind != KeyEventKind::Press {
        return None;
    }

    match key.code {
        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.quit = true;
            None
        }
        KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.quit = true;
            None
        }
        KeyCode::Enter => {
            if app.input.trim().is_empty() {
                return None;
            }
            let text = app.input.drain(..).collect::<String>();
            app.cursor = 0;
            Some(text)
        }
        KeyCode::Backspace => {
            if app.cursor > 0 {
                app.cursor -= 1;
                app.input.remove(app.cursor);
            }
            None
        }
        KeyCode::Delete => {
            if app.cursor < app.input.len() {
                app.input.remove(app.cursor);
            }
            None
        }
        KeyCode::Left => {
            app.cursor = app.cursor.saturating_sub(1);
            None
        }
        KeyCode::Right => {
            if app.cursor < app.input.len() {
                app.cursor += 1;
            }
            None
        }
        KeyCode::Home => {
            app.cursor = 0;
            None
        }
        KeyCode::End => {
            app.cursor = app.input.len();
            None
        }
        KeyCode::Char(ch) => {
            app.input.insert(app.cursor, ch);
            app.cursor += 1;
            None
        }
        _ => None,
    }
}

// ── Slash command execution ───────────────────────────────────────────────────

async fn exec_slash<B: ratatui::backend::Backend>(
    app: &mut App,
    cmd: SlashCommand,
    engine: &ChatEngine,
    terminal: &mut ratatui::Terminal<B>,
) {
    match cmd {
        SlashCommand::Help => {
            app.messages.push(ChatMessage::system(
                "/help      — show this message\n\
                 /models    — list available models\n\
                 /models N  — switch to model N\n\
                 /clear     — wipe conversation history\n\
                 /status    — show engine status\n\
                 /exit      — quit chat",
            ));
        }
        SlashCommand::Clear => {
            let cleared = engine.clear_history().await;
            app.messages.clear();
            app.scroll_offset = 0;
            app.messages.push(ChatMessage::system(format!(
                "Cleared {cleared} turn(s). History is empty.",
            )));
        }
        SlashCommand::Status => {
            let info = engine.info().await;
            let model = info.model_name.as_deref().unwrap_or("(none)");
            let mem = info.approx_memory.as_deref().unwrap_or("unknown");
            app.messages.push(ChatMessage::system(format!(
                "status: {:?}  model: {}  memory: {}  history: {} turns",
                info.status, model, mem, info.history_length,
            )));
        }
        SlashCommand::Models(selection) => match selection {
            None => {
                // Show the model list.
                let info = engine.info().await;
                let current = info.model_name.clone().unwrap_or_default();

                let mut text = String::from("Available models — type /models <n> to switch:\n");
                for (i, model) in SIGIT_MODELS.iter().enumerate() {
                    let current_marker = if current == model.name {
                        "  ← current"
                    } else {
                        ""
                    };
                    let tool_badge = if model.tool_calling {
                        "  ✓ tool calling"
                    } else {
                        ""
                    };
                    text.push_str(&format!(
                        "\n  {}  {}  {}{}{}",
                        i + 1,
                        model.name,
                        model.description,
                        tool_badge,
                        current_marker,
                    ));
                }
                app.messages.push(ChatMessage::system(text));
            }
            Some(n) => {
                let idx = n.saturating_sub(1);
                match SIGIT_MODELS.get(idx) {
                    None => {
                        app.messages.push(ChatMessage::system(format!(
                            "error: no model #{n} — type /models to see the list."
                        )));
                    }
                    Some(model) => {
                        // Redraw first — "Loading…" has to be on screen before
                        // we block for however long the load takes.
                        app.messages
                            .push(ChatMessage::system(format!("Loading {}", model.name)));
                        terminal.draw(|frame| render(frame, app)).ok();

                        engine.unload_model().await;

                        let config = (model.config_fn)();
                        let sampling = SamplingConfig {
                            max_tokens: Some(model.max_tokens),
                            ..SamplingConfig::default()
                        };

                        match engine.load_gguf_model(config, None, Some(sampling)).await {
                            Ok(_) => {
                                engine.clear_history().await;
                                app.messages.push(ChatMessage::system(format!(
                                    "✓ Switched to {}",
                                    model.name
                                )));
                            }
                            Err(err) => {
                                app.messages.push(ChatMessage::system(format!(
                                    "error loading {}: {err}",
                                    model.name
                                )));
                            }
                        }
                    }
                }
            }
        },
        SlashCommand::Exit => {
            app.quit = true;
        }
        SlashCommand::Unknown(cmd) => {
            app.messages
                .push(ChatMessage::system(format!("unknown command: {cmd}")));
        }
    }
}

// ── Main loop ─────────────────────────────────────────────────────────────────

/// Run the interactive chat UI.  Blocks until the user quits.
///
/// Accepts a terminal that has already been initialised by the caller —
/// [`ratatui::init`] and [`ratatui::restore`] are the caller's responsibility.
///
/// `load_rx` is the receiving end of a [`std::sync::mpsc`] channel.  A
/// dedicated OS thread loads the model and sends `Ok(())` or `Err(msg)` when
/// done.  The event loop polls `try_recv()` on every tick — non-blocking,
/// zero contention with the tokio runtime.
pub async fn run_with<B: ratatui::backend::Backend>(
    terminal: &mut ratatui::Terminal<B>,
    engine: &ChatEngine,
    load_rx: std_mpsc::Receiver<Result<(), String>>,
) -> Result<()> {
    let config = GgufModelConfig::platform_default();
    let model_name = config.display_name.clone();
    event_loop(terminal, engine, load_rx, model_name).await
}

async fn event_loop<B: ratatui::backend::Backend>(
    terminal: &mut ratatui::Terminal<B>,
    engine: &ChatEngine,
    load_rx: std_mpsc::Receiver<Result<(), String>>,
    load_model_name: String,
) -> Result<()> {
    let mut app = App::new(load_model_name);
    let mut event_stream = EventStream::new();

    // 100 ms per tick ≈ 10 fps — enough for a smooth spinner.
    let mut ticker = interval(Duration::from_millis(100));

    loop {
        // ── Poll the loader channel (non-blocking) ────────────────────────
        if app.is_loading {
            match load_rx.try_recv() {
                Ok(Ok(())) => app.finish_loading(),
                Ok(Err(e)) => app.set_load_error(e),
                Err(std_mpsc::TryRecvError::Empty) => {}
                Err(std_mpsc::TryRecvError::Disconnected) => {
                    app.set_load_error("Model loader thread crashed.".to_string());
                }
            }
        }

        // redraw every iteration
        terminal.draw(|frame| render(frame, &mut app))?;

        if app.quit {
            break;
        }

        tokio::select! {
            biased;

            // ── Spinner tick (loading phase only) ─────────────────────────
            _ = ticker.tick(), if app.is_loading => {
                app.tick();
            }

            // ── Streaming LLM tokens ──────────────────────────────────────
            chunk = async {
                match app.stream_rx.as_mut() {
                    Some(rx) => rx.recv().await,
                    None => pending().await,
                }
            } => {
                match chunk {
                    Some(chunk) => {
                        if !chunk.delta.is_empty() {
                            app.push_stream_delta(&chunk.delta);
                        }
                        if chunk.done {
                            app.finalize_stream();
                        }
                    }
                    // Sender dropped without sending done=true.
                    None => {
                        app.finalize_stream();
                    }
                }
            }

            // ── Terminal events ───────────────────────────────────────────
            maybe_event = event_stream.next() => {
                let Some(Ok(event)) = maybe_event else {
                    break;
                };

                if let Event::Key(key) = event {
                    // During loading, only Ctrl+C / Ctrl+D are accepted.
                    if app.is_loading {
                        if key.kind == KeyEventKind::Press {
                            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                            if ctrl
                                && (key.code == KeyCode::Char('c')
                                    || key.code == KeyCode::Char('d'))
                            {
                                app.quit = true;
                            }
                        }
                        continue;
                    }

                    // While streaming, only Ctrl+C / Ctrl+D cancel the stream.
                    if app.is_streaming() {
                        if key.kind == KeyEventKind::Press {
                            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                            if ctrl
                                && (key.code == KeyCode::Char('c')
                                    || key.code == KeyCode::Char('d'))
                            {
                                app.finalize_stream();
                                app.messages.push(ChatMessage::system("(cancelled)"));
                            }
                        }
                        continue;
                    }

                    if let Some(text) = handle_key(&mut app, key) {
                        if let Some(cmd) = parse_slash(&text) {
                            exec_slash(&mut app, cmd, engine, terminal).await;
                            continue;
                        }

                        app.messages.push(ChatMessage::user(&text));

                        match engine.stream_message(text).await {
                            Ok(rx) => {
                                app.stream_rx = Some(rx);
                                app.stream_buf.clear();
                                app.blink_counter = 0;
                                app.blink_on = true;
                            }
                            Err(err) => {
                                app.messages
                                    .push(ChatMessage::system(format!("error: {err}")));
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(())
}