magi-rs 0.2.1

Magi Agent: a terminal AI assistant in Rust with sandboxed tool execution, OAuth login, and encrypted local memory (Argon2 + AES-256-GCM-SIV + Reed-Solomon FEC).
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
//! This module implements the Terminal User Interface using Ratatui.

use crate::agent::{Agent, ApprovalRequest};
use crate::system::secrets::SecretStore;
use crossterm::{
    event::{self, DisableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::{Backend, CrosstermBackend},
    layout::{Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
    Frame, Terminal,
};
use std::io;
use tokio::sync::mpsc;

/// Different interaction modes for the TUI.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum AppMode {
    Normal,
    Selection,
    Visual, // Mode for selecting text within a message
}

/// Events that can happen in the UI.
pub enum UiEvent {
    Input(String),
    Clear,
    Login,
    Logout,
    Quit,
}

/// Messages from the Agent to the UI.
pub enum AgentResponse {
    Text(String),
    Error(String),
    Info(String),
    /// An incremental text delta from the streaming provider.
    StreamDelta(String),
}

/// Represents the state of the TUI application.
pub struct App {
    /// The input string currently being typed.
    pub input: String,
    /// Current cursor position in the input string (byte index).
    pub cursor_position: usize,
    /// Selection start position (if any)
    pub selection_start: Option<usize>,
    /// History of messages to display.
    pub messages: Vec<String>,
    /// Channel to send events to the agent runner.
    pub event_tx: mpsc::Sender<UiEvent>,
    /// Channel to receive responses from the agent.
    pub response_rx: mpsc::Receiver<AgentResponse>,
    /// Channel to receive approval requests from the agent.
    pub approval_rx: mpsc::Receiver<ApprovalRequest>,
    /// Pending approval request
    pub pending_approval: Option<ApprovalRequest>,
    /// Current UI mode
    pub mode: AppMode,
    /// Index of the selected message in Selection mode
    pub selected_index: usize,
    /// Cursor position within the selected message (Visual mode)
    pub visual_cursor: usize,
    /// Selection start within the selected message (Visual mode)
    pub visual_selection_start: Option<usize>,
    /// Whether the agent is currently streaming a response.
    pub streaming: bool,
}

impl App {
    pub fn new(
        event_tx: mpsc::Sender<UiEvent>,
        response_rx: mpsc::Receiver<AgentResponse>,
        approval_rx: mpsc::Receiver<ApprovalRequest>,
    ) -> Self {
        Self {
            input: String::new(),
            cursor_position: 0,
            selection_start: None,
            messages: Vec::new(),
            event_tx,
            response_rx,
            approval_rx,
            pending_approval: None,
            mode: AppMode::Normal,
            selected_index: 0,
            visual_cursor: 0,
            visual_selection_start: None,
            streaming: false,
        }
    }

    /// Moves the cursor to the left, respecting Unicode character boundaries.
    pub fn move_cursor_left(&mut self, select: bool) {
        if select && self.selection_start.is_none() {
            self.selection_start = Some(self.cursor_position);
        } else if !select {
            self.selection_start = None;
        }

        if self.cursor_position > 0 {
            let indices = self.input.char_indices().rev();
            for (idx, _) in indices {
                if idx < self.cursor_position {
                    self.cursor_position = idx;
                    return;
                }
            }
            self.cursor_position = 0;
        }
    }

    /// Moves the cursor to the right, respecting Unicode character boundaries.
    pub fn move_cursor_right(&mut self, select: bool) {
        if select && self.selection_start.is_none() {
            self.selection_start = Some(self.cursor_position);
        } else if !select {
            self.selection_start = None;
        }

        if self.cursor_position < self.input.len() {
            let indices = self.input.char_indices();
            for (idx, _) in indices {
                if idx > self.cursor_position {
                    self.cursor_position = idx;
                    return;
                }
            }
            self.cursor_position = self.input.len();
        }
    }

    /// Inserts a character at the current cursor position.
    pub fn insert_char(&mut self, c: char) {
        self.delete_selection();
        // Ensure cursor is at char boundary before insert
        if !self.input.is_char_boundary(self.cursor_position) {
            self.cursor_position = 0; // Emergency fallback
        }
        self.input.insert(self.cursor_position, c);
        self.cursor_position += c.len_utf8();
    }

    /// Deletes the character before the current cursor position.
    pub fn delete_char(&mut self) {
        if self.selection_start.is_some() {
            self.delete_selection();
            return;
        }

        if self.cursor_position > 0 {
            self.move_cursor_left(false);
            let prev_pos = self.cursor_position;
            if self.input.is_char_boundary(prev_pos) {
                self.input.remove(prev_pos);
            }
        }
    }

    /// Deletes the currently selected text.
    pub fn delete_selection(&mut self) {
        if let Some(start) = self.selection_start {
            let end = self.cursor_position;
            let (from, to) = if start < end {
                (start, end)
            } else {
                (end, start)
            };
            if self.input.is_char_boundary(from) && self.input.is_char_boundary(to) {
                self.input.drain(from..to);
                self.cursor_position = from;
            }
            self.selection_start = None;
        }
    }

    /// Returns the selected text if any.
    pub fn get_selected_text(&self) -> Option<String> {
        self.selection_start.and_then(|start| {
            let end = self.cursor_position;
            let (from, to) = if start < end {
                (start, end)
            } else {
                (end, start)
            };
            if self.input.is_char_boundary(from) && self.input.is_char_boundary(to) {
                Some(self.input[from..to].to_string())
            } else {
                None
            }
        })
    }

    /// Appends a message to the UI history.
    pub fn push_message(&mut self, message: String) {
        self.messages.push(message);
    }

    /// Appends a streaming delta to the in-progress assistant message,
    /// creating the line on the first delta. Append-only; never byte-indexes.
    pub fn append_stream_delta(&mut self, delta: String) {
        if self.streaming {
            if let Some(last) = self.messages.last_mut() {
                last.push_str(&delta);
                return;
            }
        }
        self.messages.push(format!("Magi Agent: {}", delta));
        self.streaming = true;
    }

    /// Marks the end of a streamed assistant turn.
    pub fn finalize_stream(&mut self) {
        self.streaming = false;
    }
}

pub async fn run_tui_ext(agent: Agent, startup_notices: Vec<String>) -> anyhow::Result<()> {
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        let _ = disable_raw_mode();
        let mut stdout = io::stdout();
        let _ = execute!(stdout, LeaveAlternateScreen, DisableMouseCapture);
        let _ =
            Terminal::new(CrosstermBackend::new(io::stdout())).and_then(|mut t| t.show_cursor());
        original_hook(panic_info);
    }));

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let (event_tx, mut event_rx) = mpsc::channel(100);
    let (response_tx, response_rx) = mpsc::channel(100);
    let (approval_tx, approval_rx) = mpsc::channel(100);

    for notice in startup_notices {
        let _ = response_tx.send(AgentResponse::Info(notice)).await;
    }

    let mut runner_agent = agent;
    runner_agent.set_approval_channel(approval_tx);

    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            match event {
                UiEvent::Input(text) => {
                    // Stream-bridge: `chunk_tx` is owned by `query_streaming`; when
                    // the method returns it is dropped, which closes the sender end of
                    // the channel. The forwarder task then drains any remaining deltas
                    // and exits its `recv()` loop naturally. `forwarder.await` joins
                    // the task before the end-of-turn marker is sent, guaranteeing
                    // all deltas arrive at the UI before `Text("")` (end-of-turn
                    // convention) or `Error(...)`.
                    let (chunk_tx, mut chunk_rx) = mpsc::channel::<String>(100);
                    let forward_tx = response_tx.clone();
                    let forwarder = tokio::spawn(async move {
                        while let Some(delta) = chunk_rx.recv().await {
                            if forward_tx
                                .send(AgentResponse::StreamDelta(delta))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                    });

                    let result = runner_agent.query_streaming(&text, chunk_tx).await;
                    // Join the forwarder: ensures all deltas are forwarded before the
                    // end-of-turn marker below is enqueued.
                    let _ = forwarder.await;

                    // `Text("")` signals end-of-turn to `run_app`; it calls
                    // `finalize_stream` instead of pushing an empty message line.
                    match result {
                        Ok(_) => {
                            let _ = response_tx.send(AgentResponse::Text(String::new())).await;
                        }
                        Err(e) => {
                            let _ = response_tx.send(AgentResponse::Error(e.to_string())).await;
                        }
                    }
                }
                UiEvent::Clear => {
                    runner_agent.clear_history();
                }
                UiEvent::Login => {
                    let oauth = crate::services::oauth::OAuthService::new();
                    let url = oauth.get_authorize_url();
                    let _ = response_tx.send(AgentResponse::Info(url)).await;

                    match oauth.start_callback_server().await {
                        Ok(code) => {
                            let _ = response_tx
                                .send(AgentResponse::Info("Authenticating...".to_string()))
                                .await;
                            match oauth.exchange_code_for_token(&code).await {
                                Ok(token) => match oauth.create_raw_api_key(&token).await {
                                    Ok(api_key) => {
                                        let store =
                                            crate::system::secrets::KeyringStore::new("magi-rs");
                                        if let Err(e) =
                                            store.set_secret("ANTHROPIC_API_KEY", &api_key).await
                                        {
                                            let _ = response_tx
                                                .send(AgentResponse::Error(format!(
                                                    "Failed to store key: {}",
                                                    e
                                                )))
                                                .await;
                                        } else {
                                            // #9: rebuild the running agent's provider in-session
                                            // so replies use the new key without a restart.
                                            let model = std::env::var("ANTHROPIC_MODEL")
                                                .unwrap_or_else(|_| {
                                                    crate::DEFAULT_MODEL.to_string()
                                                });
                                            // #16: only the canned StaticProvider history is safe to
                                            // clear; a re-login over a live provider must keep the
                                            // real conversation. Read before the swap, build banner
                                            // before `model` moves.
                                            let was_static = runner_agent.provider_is_static();
                                            let banner = if was_static {
                                                format!("Successfully logged in! Now using Magi API (model: {model}) — no restart needed; prior canned replies cleared.")
                                            } else {
                                                format!("Re-authenticated. Now using Magi API (model: {model}) — conversation kept.")
                                            };
                                            runner_agent.set_provider(std::sync::Arc::new(
                                                crate::agent::provider::AnthropicProvider::new(
                                                    api_key, model,
                                                ),
                                            ));
                                            if was_static {
                                                runner_agent.clear_history();
                                            }
                                            let _ =
                                                response_tx.send(AgentResponse::Info(banner)).await;
                                        }
                                    }
                                    Err(e) => {
                                        let _ = response_tx
                                            .send(AgentResponse::Error(format!(
                                                "Failed to create API key: {}",
                                                e
                                            )))
                                            .await;
                                    }
                                },
                                Err(e) => {
                                    let _ = response_tx
                                        .send(AgentResponse::Error(format!(
                                            "OAuth exchange failed: {}",
                                            e
                                        )))
                                        .await;
                                }
                            }
                        }
                        Err(e) => {
                            let _ = response_tx
                                .send(AgentResponse::Error(format!(
                                    "Callback server error: {}",
                                    e
                                )))
                                .await;
                        }
                    }
                }
                UiEvent::Logout => {
                    // Clear from both canonical ("magi-rs") and legacy ("magi-rust") services
                    // so a key stored by either the new or the pre-migration login flow is removed.
                    // Mirrors the CLI --logout path in main.rs. delete_secret treats NoEntry as Ok.
                    let canonical = crate::system::secrets::KeyringStore::new("magi-rs");
                    let legacy = crate::system::secrets::KeyringStore::new("magi-rust");
                    let res_canonical = canonical.delete_secret("ANTHROPIC_API_KEY").await;
                    let res_legacy = legacy.delete_secret("ANTHROPIC_API_KEY").await;
                    match (res_canonical, res_legacy) {
                        (Err(e), _) | (_, Err(e)) => {
                            let _ = response_tx
                                .send(AgentResponse::Error(format!("Logout failed: {}", e)))
                                .await;
                        }
                        (Ok(()), Ok(())) => {
                            let _ = response_tx
                                .send(AgentResponse::Info("Logged out successfully.".to_string()))
                                .await;
                        }
                    }
                }
                UiEvent::Quit => break,
            }
        }
    });

    let app = App::new(event_tx, response_rx, approval_rx);
    let res = run_app(&mut terminal, app).await;

    let _ = disable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    );
    let _ = terminal.show_cursor();

    if let Err(err) = res {
        eprintln!("TUI Error: {:?}", err)
    }
    Ok(())
}

async fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
    loop {
        terminal.draw(|f| ui(f, &app))?;

        while let Ok(response) = app.response_rx.try_recv() {
            match response {
                AgentResponse::StreamDelta(delta) => app.append_stream_delta(delta),
                AgentResponse::Text(t) => {
                    if t.is_empty() {
                        app.finalize_stream();
                    } else {
                        app.push_message(format!("Magi Agent: {}", t));
                    }
                }
                AgentResponse::Error(e) => {
                    app.finalize_stream();
                    app.push_message(format!("Error: {}", e));
                }
                AgentResponse::Info(i) => {
                    app.finalize_stream();
                    app.push_message(format!("System: {}", i));
                }
            }
        }

        while let Ok(req) = app.approval_rx.try_recv() {
            app.push_message(format!("APPROVAL REQUIRED: Execute {}?", req.tool_name));
            app.push_message("Press 'y' to approve, 'c' or 'Esc' to deny.".to_string());
            app.pending_approval = Some(req);
        }

        if event::poll(std::time::Duration::from_millis(50))? {
            if let Event::Key(key) = event::read()? {
                if key.kind != KeyEventKind::Press {
                    continue;
                }

                match app.mode {
                    AppMode::Selection => {
                        match key.code {
                            KeyCode::Up if app.selected_index > 0 => {
                                app.selected_index -= 1;
                            }
                            KeyCode::Down
                                if app.selected_index < app.messages.len().saturating_sub(1) =>
                            {
                                app.selected_index += 1;
                            }
                            KeyCode::Enter => {
                                app.mode = AppMode::Visual;
                                app.visual_cursor = 0;
                                app.visual_selection_start = None;
                            }
                            KeyCode::Char('y') => {
                                if let Some(msg) = app.messages.get(app.selected_index) {
                                    if let Ok(mut clipboard) = arboard::Clipboard::new() {
                                        let _ = clipboard.set_text(msg.clone());
                                        app.push_message("System: Message copied".to_string());
                                    }
                                }
                                app.mode = AppMode::Normal;
                            }
                            KeyCode::Esc | KeyCode::Char('q') => {
                                app.mode = AppMode::Normal;
                            }
                            _ => {}
                        }
                        continue;
                    }
                    AppMode::Visual => {
                        let msg = app
                            .messages
                            .get(app.selected_index)
                            .cloned()
                            .unwrap_or_default();
                        match key.code {
                            KeyCode::Left => {
                                if key.modifiers.contains(KeyModifiers::SHIFT)
                                    && app.visual_selection_start.is_none()
                                {
                                    app.visual_selection_start = Some(app.visual_cursor);
                                } else if !key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.visual_selection_start = None;
                                }
                                if app.visual_cursor > 0 {
                                    let indices = msg.char_indices().rev();
                                    for (idx, _) in indices {
                                        if idx < app.visual_cursor {
                                            app.visual_cursor = idx;
                                            break;
                                        }
                                    }
                                }
                            }
                            KeyCode::Right => {
                                if key.modifiers.contains(KeyModifiers::SHIFT)
                                    && app.visual_selection_start.is_none()
                                {
                                    app.visual_selection_start = Some(app.visual_cursor);
                                } else if !key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.visual_selection_start = None;
                                }
                                if app.visual_cursor < msg.len() {
                                    let indices = msg.char_indices();
                                    for (idx, _) in indices {
                                        if idx > app.visual_cursor {
                                            app.visual_cursor = idx;
                                            break;
                                        }
                                    }
                                }
                            }
                            KeyCode::Enter => {
                                if let (Some(msg_ref), Some(start)) = (
                                    app.messages.get(app.selected_index),
                                    app.visual_selection_start,
                                ) {
                                    let (from, to) = if start < app.visual_cursor {
                                        (start, app.visual_cursor)
                                    } else {
                                        (app.visual_cursor, start)
                                    };
                                    if msg_ref.is_char_boundary(from)
                                        && msg_ref.is_char_boundary(to)
                                    {
                                        if let Ok(mut clipboard) = arboard::Clipboard::new() {
                                            let _ =
                                                clipboard.set_text(msg_ref[from..to].to_string());
                                            app.push_message("System: Fragment copied".to_string());
                                        }
                                    }
                                }
                                app.mode = AppMode::Normal;
                            }
                            KeyCode::Esc | KeyCode::Char('q') => {
                                app.mode = AppMode::Selection;
                            }
                            _ => {}
                        }
                        continue;
                    }
                    AppMode::Normal => {
                        match (key.code, key.modifiers) {
                            (KeyCode::Char('v'), KeyModifiers::CONTROL) => {
                                if let Ok(mut clipboard) = arboard::Clipboard::new() {
                                    if let Ok(text) = clipboard.get_text() {
                                        for c in text.chars() {
                                            app.insert_char(c);
                                        }
                                    }
                                }
                                continue;
                            }
                            (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
                                if let Some(selected) = app.get_selected_text() {
                                    if let Ok(mut clipboard) = arboard::Clipboard::new() {
                                        let _ = clipboard.set_text(selected);
                                        app.push_message("System: Selection copied".to_string());
                                    }
                                    continue;
                                } else {
                                    let _ = app.event_tx.send(UiEvent::Quit).await;
                                    return Ok(());
                                }
                            }
                            (KeyCode::Char('s'), KeyModifiers::CONTROL) => {
                                if !app.messages.is_empty() {
                                    app.mode = AppMode::Selection;
                                    app.selected_index = app.messages.len().saturating_sub(1);
                                }
                                continue;
                            }
                            (KeyCode::Left, m) => {
                                app.move_cursor_left(m.contains(KeyModifiers::SHIFT));
                                continue;
                            }
                            (KeyCode::Right, m) => {
                                app.move_cursor_right(m.contains(KeyModifiers::SHIFT));
                                continue;
                            }
                            _ => {}
                        }

                        if let Some(req) = app.pending_approval.take() {
                            match key.code {
                                KeyCode::Char('y') | KeyCode::Char('Y') => {
                                    let _ = req.tx.send(true);
                                    app.push_message("User: Approved".to_string());
                                }
                                KeyCode::Char('c') | KeyCode::Char('C') | KeyCode::Esc => {
                                    let _ = req.tx.send(false);
                                    app.push_message("User: Denied".to_string());
                                }
                                _ => {
                                    app.pending_approval = Some(req);
                                }
                            }
                            continue;
                        }

                        match key.code {
                            KeyCode::Enter => {
                                let input = app.input.drain(..).collect::<String>();
                                app.cursor_position = 0;
                                let trimmed = input.trim();
                                if !trimmed.is_empty() {
                                    match trimmed {
                                        "/exit" | "/quit" => {
                                            let _ = app.event_tx.send(UiEvent::Quit).await;
                                            return Ok(());
                                        }
                                        "/clear" => {
                                            app.messages.clear();
                                            let _ = app.event_tx.send(UiEvent::Clear).await;
                                            continue;
                                        }
                                        "/login" => {
                                            let _ = app.event_tx.send(UiEvent::Login).await;
                                            continue;
                                        }
                                        "/logout" => {
                                            let _ = app.event_tx.send(UiEvent::Logout).await;
                                            continue;
                                        }
                                        "/help" => {
                                            app.push_message("Available commands:".to_string());
                                            app.push_message(
                                                "  /login, /logout - Identity management"
                                                    .to_string(),
                                            );
                                            app.push_message(
                                                "  /exit, /quit    - Exit the application"
                                                    .to_string(),
                                            );
                                            app.push_message(
                                                "  /clear          - Clear session history"
                                                    .to_string(),
                                            );
                                            app.push_message(
                                                "  /help           - Show this help message"
                                                    .to_string(),
                                            );
                                            continue;
                                        }
                                        _ => {}
                                    }
                                    app.push_message(format!("User: {}", trimmed));
                                    let _ = app
                                        .event_tx
                                        .send(UiEvent::Input(trimmed.to_string()))
                                        .await;
                                }
                            }
                            KeyCode::Char(c) => {
                                app.insert_char(c);
                            }
                            KeyCode::Backspace => {
                                app.delete_char();
                            }
                            KeyCode::Esc => {
                                let _ = app.event_tx.send(UiEvent::Quit).await;
                                return Ok(());
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }
}

fn ui(f: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([Constraint::Percentage(80), Constraint::Length(3)].as_ref())
        .split(f.size());

    let messages: Vec<ListItem> = app
        .messages
        .iter()
        .enumerate()
        .map(|(i, m)| {
            let mut style = Style::default();
            if (app.mode == AppMode::Selection || app.mode == AppMode::Visual)
                && i == app.selected_index
            {
                style = style
                    .bg(Color::Blue)
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD);
            }
            ListItem::new(m.as_str()).style(style)
        })
        .collect();

    let mut state = ListState::default();
    if app.mode == AppMode::Selection || app.mode == AppMode::Visual {
        state.select(Some(app.selected_index));
    }

    let messages_list = List::new(messages)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("Conversation History"),
        )
        .highlight_symbol(">> ");
    f.render_stateful_widget(messages_list, chunks[0], &mut state);

    let mut input_text = Text::raw(app.input.as_str());
    if let Some(start) = app.selection_start {
        let (from, to) = if start < app.cursor_position {
            (start, app.cursor_position)
        } else {
            (app.cursor_position, start)
        };
        if app.input.is_char_boundary(from) && app.input.is_char_boundary(to) {
            let spans = vec![
                Span::raw(&app.input[..from]),
                Span::styled(
                    &app.input[from..to],
                    Style::default().bg(Color::White).fg(Color::Black),
                ),
                Span::raw(&app.input[to..]),
            ];
            input_text = Text::from(Line::from(spans));
        }
    }

    let input_title = match app.mode {
        AppMode::Selection => {
            "SELECT MESSAGE (Enter to select text, 'y' to copy whole, Esc to exit)"
        }
        AppMode::Visual => "VISUAL SELECTION MODE",
        _ if app.pending_approval.is_some() => "WAITING FOR APPROVAL (y/c)",
        _ => "Input (Ctrl+S Copy Mode, Shift+Arrows Select)",
    };

    let input =
        Paragraph::new(input_text).block(Block::default().borders(Borders::ALL).title(input_title));
    f.render_widget(input, chunks[1]);

    if app.mode == AppMode::Normal {
        // Find visible width of input to position cursor correctly
        let prefix_len = app.input[..app.cursor_position].chars().count() as u16;
        f.set_cursor(chunks[1].x + prefix_len + 1, chunks[1].y + 1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_app_cursor_logic() {
        let (event_tx, _) = mpsc::channel(1);
        let (_, response_rx) = mpsc::channel(1);
        let (_, approval_rx) = mpsc::channel(1);
        let mut app = App::new(event_tx, response_rx, approval_rx);

        app.insert_char('a');
        app.insert_char('c');
        assert_eq!(app.input, "ac");
        assert_eq!(app.cursor_position, 2);

        app.move_cursor_left(false);
        app.insert_char('b');
        assert_eq!(app.input, "abc");
        assert_eq!(app.cursor_position, 2);

        app.delete_char();
        assert_eq!(app.input, "ac");
        assert_eq!(app.cursor_position, 1);
    }

    #[tokio::test]
    async fn test_unicode_character_boundary_panic() {
        let (event_tx, _) = mpsc::channel(1);
        let (_, response_rx) = mpsc::channel(1);
        let (_, approval_rx) = mpsc::channel(1);
        let mut app = App::new(event_tx, response_rx, approval_rx);

        app.insert_char('á');
        assert_eq!(app.cursor_position, 2);

        app.move_cursor_left(false);
        assert_eq!(app.cursor_position, 0);

        app.insert_char('x');
        assert_eq!(app.input, "");
    }
}