oxi-cli 0.6.12

Terminal-based AI coding assistant — multi-provider, streaming-first, extensible
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
//! Event handlers for the TUI.

use super::app::{AppState, SetupStep, UiEvent};
use super::slash;
use crate::agent_session::{AgentSession, CompactionReason, SessionEvent};
use oxi_agent::AgentEvent;
use tokio::sync::mpsc;

use crossterm::event::{
    Event as CEvent, KeyCode, KeyModifiers, MouseEventKind,
    KeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    KeyEventKind,
};

/// Actions returned from input handling that need async work in the main loop.
pub(crate) enum Action {
    SendPrompt(String),
    ExecuteSlashCommand(String),
}

/// Handle a crossterm input event. Returns an action if the main loop needs to do async work.
pub async fn handle_input(
    event: CEvent,
    state: &mut AppState,
    session: &AgentSession,
    ui_tx: &mpsc::Sender<UiEvent>,
    _prompt_tx: &mpsc::Sender<String>,
    running: &mut bool,
) -> Option<Action> {
    match event {
        CEvent::Key(key) => {
            if state.setup_step.is_some() {
                handle_setup_key(key, state).await
            } else {
                handle_key(key, state, session, ui_tx, running).await
            }
        }
        CEvent::Mouse(mouse) => {
            match mouse.kind {
                MouseEventKind::ScrollUp => state.scroll_up(3),
                MouseEventKind::ScrollDown => state.scroll_down(3),
                _ => {}
            }
            None
        }
        // IME 조합 완료 텍스트나 클립보드 붙여넣기 처리
        CEvent::Paste(text) => {
            if !state.is_agent_busy {
                state.input.insert_str(&text);
                state.update_slash_completions();
            }
            None
        }
        _ => None,
    }
}

async fn handle_key(
    key: crossterm::event::KeyEvent,
    state: &mut AppState,
    session: &AgentSession,
    _ui_tx: &mpsc::Sender<UiEvent>,
    running: &mut bool,
) -> Option<Action> {
    // 키보드 이벤트 타입이 지원되는 경우 Press만 처리
    // (Repeat/Release 무시 — IME 조합 중 Repeat 이벤트 방지)
    if key.kind != KeyEventKind::Press {
        return None;
    }

    match key.code {
        KeyCode::Enter => {
            if !state.is_agent_busy {
                // 슬래시 명령 팝업이 활성 상태면 선택된 명령 바로 실행
                if state.slash_completion_active {
                    let cmd = state.selected_slash_command().map(|c| c.name.clone());
                    state.clear_slash_completions();
                    state.input_clear();
                    if let Some(cmd) = cmd {
                        return Some(Action::ExecuteSlashCommand(cmd));
                    }
                    return None;
                }
                let value = state.input_value().to_string();
                if !value.is_empty() {
                    if value.starts_with('/') {
                        let handled = slash::handle_slash_command(
                            &value, session, state, running,
                        );
                        state.input_clear();
                        if handled {
                            return None;
                        }
                    }
                    return Some(Action::SendPrompt(value));
                }
            }
            None
        }
        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            if state.is_agent_busy {
                let sh = session.clone_handle();
                tokio::spawn(async move { sh.abort().await });
                state.cancel_streaming();
                state.add_system_message("⏹ Interrupted".to_string());
            } else {
                *running = false;
            }
            None
        }
        KeyCode::PageUp => {
            state.scroll_up(10);
            None
        }
        KeyCode::PageDown => {
            state.scroll_down(10);
            None
        }
        KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
            if !state.is_agent_busy {
                state.input.insert_char(c);
                state.update_slash_completions();
            }
            None
        }
        KeyCode::Backspace => {
            if !state.is_agent_busy {
                state.input.backspace();
                state.update_slash_completions();
            }
            None
        }
        KeyCode::Delete => {
            if !state.is_agent_busy {
                state.input.delete();
                state.update_slash_completions();
            }
            None
        }
        KeyCode::Left => {
            if !state.is_agent_busy {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    let text: Vec<char> = state.input.text.chars().collect();
                    let mut pos = state.input.cursor;
                    while pos > 0 && text[pos - 1].is_whitespace() {
                        pos -= 1;
                    }
                    while pos > 0 && !text[pos - 1].is_whitespace() {
                        pos -= 1;
                    }
                    state.input.cursor = pos;
                } else {
                    state.input.move_left();
                }
            }
            None
        }
        KeyCode::Right => {
            if !state.is_agent_busy {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    let text: Vec<char> = state.input.text.chars().collect();
                    let mut pos = state.input.cursor;
                    while pos < text.len() && !text[pos].is_whitespace() {
                        pos += 1;
                    }
                    while pos < text.len() && text[pos].is_whitespace() {
                        pos += 1;
                    }
                    state.input.cursor = pos;
                } else {
                    state.input.move_right();
                }
            }
            None
        }
        KeyCode::Home => {
            if !state.is_agent_busy {
                state.input.move_home();
            }
            None
        }
        KeyCode::End => {
            if !state.is_agent_busy {
                state.input.move_end();
            }
            None
        }
        KeyCode::Tab => {
            if !state.is_agent_busy && state.slash_completion_active {
                let cmd = state.selected_slash_command().map(|c| c.name.clone());
                state.clear_slash_completions();
                state.input_clear();
                if let Some(cmd) = cmd {
                    return Some(Action::ExecuteSlashCommand(cmd));
                }
            }
            None
        }
        KeyCode::Up => {
            if !state.is_agent_busy && state.slash_completion_active {
                state.prev_slash_completion();
            } else if !state.is_agent_busy
                && state.input.text.is_empty()
                && !state.input_history.is_empty()
            {
                if state.history_index == 0 {
                    state.saved_input = state.input.text.clone();
                }
                if state.history_index < state.input_history.len() {
                    state.history_index += 1;
                    state.input_set_text(
                        state.input_history[state.history_index - 1].clone(),
                    );
                    state.clear_slash_completions();
                }
            } else {
                state.scroll_up(3);
            }
            None
        }
        KeyCode::Down => {
            if !state.is_agent_busy && state.slash_completion_active {
                state.next_slash_completion();
            } else if !state.is_agent_busy && state.history_index > 0 {
                state.history_index -= 1;
                if state.history_index == 0 {
                    state.input_set_text(state.saved_input.clone());
                } else {
                    state.input_set_text(
                        state.input_history[state.history_index - 1].clone(),
                    );
                }
                state.clear_slash_completions();
            } else {
                state.scroll_down(3);
            }
            None
        }
        KeyCode::Esc => {
            if state.slash_completion_active {
                state.clear_slash_completions();
            }
            None
        }
        _ => None,
    }
}

/// Handle an agent UI event.
pub fn handle_ui_event(event: UiEvent, state: &mut AppState) {
    match event {
        UiEvent::Start | UiEvent::Thinking => {}
        UiEvent::TextDelta(text) => {
            state.stream_text_delta(&text);
        }
        UiEvent::ToolCall { name, .. } => {
            state.stream_text_delta(&format!("\n{}\n", name));
        }
        UiEvent::ToolStart { tool_name } => {
            state.stream_text_delta(&format!("\n{}...\n", tool_name));
        }
        UiEvent::ToolResult {
            tool_name,
            content,
            is_error,
        } => {
            let label = if tool_name.is_empty() {
                "tool"
            } else {
                &tool_name
            };
            if is_error {
                let preview: String = content.chars().take(200).collect();
                state.stream_text_delta(&format!("{}: {}\n", label, preview));
            } else {
                let preview: String = content.lines().take(3).collect::<Vec<_>>().join("\n  ");
                if !preview.is_empty() {
                    state.stream_text_delta(&format!("{}\n", preview));
                }
            }
        }
        UiEvent::Complete => {
            state.finish_streaming();
        }
        UiEvent::Error(msg) => {
            state.cancel_streaming();
            state.add_system_message(format!("Error: {}", msg));
        }
        UiEvent::CompactionStart { reason } => {
            let reason_str = match reason {
                CompactionReason::Manual => "manual",
                CompactionReason::Threshold => "auto",
                CompactionReason::Overflow => "overflow",
            };
            state.add_system_message(format!("📦 Compacting ({})...", reason_str));
        }
        UiEvent::CompactionEnd {
            _reason,
            error_message,
        } => {
            let msg = if let Some(err) = error_message {
                format!("⚠ Compaction failed: {}", err)
            } else {
                "✅ Compaction complete".to_string()
            };
            state.add_system_message(msg);
        }
        UiEvent::RetryStart {
            attempt,
            max_attempts,
            error_message,
        } => {
            state.add_system_message(format!(
                "🔄 Retry ({}/{}): {}",
                attempt, max_attempts, error_message
            ));
        }
        UiEvent::ModelChanged { model_id } => {
            state.add_system_message(format!("🤖 → {}", model_id));
            state.footer_state.data.model_name = model_id;
        }
        UiEvent::ThinkingLevelChanged { level } => {
            state.add_system_message(format!("💭 Thinking: {}", level));
        }
        UiEvent::QueueUpdate { pending } => {
            if pending > 0 {
                tracing::debug!("Queue: {} pending", pending);
            }
        }
    }
}

/// Handle a session event, forwarding relevant ones as UI events.
pub async fn handle_session_event(
    event: SessionEvent,
    ui_tx: &mpsc::Sender<UiEvent>,
) {
    match event {
        SessionEvent::CompactionStart { reason } => {
            let _ = ui_tx.send(UiEvent::CompactionStart { reason }).await;
        }
        SessionEvent::CompactionEnd {
            reason, error_message, ..
        } => {
            let _ = ui_tx
                .send(UiEvent::CompactionEnd {
                    _reason: reason,
                    error_message,
                })
                .await;
        }
        SessionEvent::ThinkingLevelChanged { level } => {
            let _ = ui_tx
                .send(UiEvent::ThinkingLevelChanged {
                    level: format!("{:?}", level),
                })
                .await;
        }
        SessionEvent::QueueUpdate { steering, follow_up } => {
            let pending = steering.len() + follow_up.len();
            let _ = ui_tx.send(UiEvent::QueueUpdate { pending }).await;
        }
        SessionEvent::SessionInfoChanged { name: _ } => {}
        SessionEvent::Agent(agent_event) => match &agent_event {
            AgentEvent::Fallback { to_model, .. } => {
                let _ = ui_tx
                    .send(UiEvent::ModelChanged {
                        model_id: to_model.clone(),
                    })
                    .await;
            }
            AgentEvent::Retry {
                attempt,
                max_retries,
                reason,
                ..
            } => {
                let _ = ui_tx
                    .send(UiEvent::RetryStart {
                        attempt: *attempt as u32,
                        max_attempts: *max_retries as u32,
                        error_message: reason.clone(),
                    })
                    .await;
            }
            AgentEvent::Compaction { .. } => {}
            _ => {}
        },
    }
}

// ── Setup wizard key handling ────────────────────────────────────────────

async fn handle_setup_key(
    key: crossterm::event::KeyEvent,
    state: &mut AppState,
) -> Option<Action> {
    if key.kind != KeyEventKind::Press {
        return None;
    }

    match &state.setup_step {
        Some(SetupStep::SelectProvider { .. }) => {
            match key.code {
                KeyCode::Up => {
                    if let Some(SetupStep::SelectProvider { providers, selected }) = &state.setup_step {
                        let new_sel = if *selected == 0 { providers.len() - 1 } else { *selected - 1 };
                        state.setup_step = Some(SetupStep::SelectProvider { providers: providers.clone(), selected: new_sel });
                    }
                }
                KeyCode::Down => {
                    if let Some(SetupStep::SelectProvider { providers, selected }) = &state.setup_step {
                        let new_sel = (*selected + 1) % providers.len();
                        state.setup_step = Some(SetupStep::SelectProvider { providers: providers.clone(), selected: new_sel });
                    }
                }
                KeyCode::Enter => {
                    if let Some(SetupStep::SelectProvider { providers, selected }) = &state.setup_step {
                        if let Some((name, _)) = providers.get(*selected).cloned() {
                            state.setup_step = Some(SetupStep::EnterApiKey {
                                provider: name,
                                key: String::new(),
                                masked_cursor: 0,
                            });
                        }
                    }
                }
                KeyCode::Char('q') | KeyCode::Esc => {
                    state.setup_step = None;
                }
                _ => {}
            }
        }

        Some(SetupStep::EnterApiKey { provider, .. }) => {
            let provider = provider.clone();
            match key.code {
                KeyCode::Char(c) => {
                    if let Some(SetupStep::EnterApiKey { key, .. }) = &mut state.setup_step {
                        key.push(c);
                    }
                }
                KeyCode::Backspace => {
                    if let Some(SetupStep::EnterApiKey { key, .. }) = &mut state.setup_step {
                        key.pop();
                    }
                }
                KeyCode::Enter => {
                    let key_val = if let Some(SetupStep::EnterApiKey { key, .. }) = &state.setup_step {
                        key.clone()
                    } else { String::new() };

                    if !key_val.is_empty() {
                        // Save the API key
                        let auth = crate::auth_storage::AuthStorage::new();
                        auth.set_api_key(&provider, key_val);

                        // Also register as custom provider if it's a known non-built-in
                        let model = format!("{}/default", provider);
                        state.footer_state.data.model_name = model.clone();
                        state.footer_state.data.provider_name = provider.clone();

                        state.setup_step = Some(SetupStep::Done {
                            provider: provider.clone(),
                            model,
                        });
                    }
                }
                KeyCode::Esc => {
                    // Go back to provider selection
                    let providers = vec![
                        ("anthropic".to_string(), false),
                        ("openai".to_string(), false),
                        ("google".to_string(), false),
                        ("deepseek".to_string(), false),
                        ("groq".to_string(), false),
                        ("openrouter".to_string(), false),
                        ("mistral".to_string(), false),
                        ("xai".to_string(), false),
                        ("minimax".to_string(), false),
                        ("zai".to_string(), false),
                    ];
                    state.setup_step = Some(SetupStep::SelectProvider { providers, selected: 0 });
                }
                _ => {}
            }
        }

        Some(SetupStep::Done { .. }) => {
            if key.code == KeyCode::Enter {
                // Exit setup wizard, go to normal chat
                state.setup_step = None;
                state.add_system_message(" Ready to chat. Type a message to start.".to_string());
            }
        }

        None => {}
    }

    None
}