synaps-tui 0.9.0

Terminal UI layer — ratatui, crossterm, syntect, tachyonfx
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crossterm::event::{KeyCode, KeyEvent};

use super::{
    build_sections, expanded_visible_models, normalize_favorite_id, remove_favorite_compat,
    selected_expanded_model, selected_model, selected_provider, visible_rows, ExpandedLoadState,
    ExpandedModelsState, ModelsModalState, ModelsView,
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InputOutcome {
    None,
    Close,
    Apply(String),
    ExpandProvider(String),
    /// The user explicitly trusted a model mid-session (favorited it). The
    /// caller must propagate this grant into the live delegation policy so
    /// subagent dispatch honors it immediately — not only after a restart.
    Trusted(String),
}

pub(crate) fn handle_event(
    state: &mut ModelsModalState,
    key: KeyEvent,
    current_model: &str,
) -> InputOutcome {
    if state.expanded.is_some() {
        return handle_expanded_event(state, key);
    }

    let sections = build_sections(current_model, state);
    let row_count = visible_rows(&sections, state).len();
    match key.code {
        KeyCode::Esc => InputOutcome::Close,
        KeyCode::Up | KeyCode::Char('k') => {
            state.cursor = state.cursor.saturating_sub(1);
            InputOutcome::None
        }
        KeyCode::Down | KeyCode::Char('j') => {
            if row_count > 0 {
                state.cursor = (state.cursor + 1).min(row_count - 1);
            }
            InputOutcome::None
        }
        KeyCode::Tab => {
            state.view = match state.view {
                ModelsView::All => ModelsView::Favorites,
                ModelsView::Favorites => ModelsView::All,
            };
            state.cursor = 0;
            InputOutcome::None
        }
        KeyCode::Char('c') => {
            let rows = visible_rows(&sections, state);
            if let Some(super::VisibleRow::Section { idx }) = rows.get(state.cursor) {
                if let Some(section) = sections.get(*idx) {
                    if !state.collapsed.remove(&section.provider_key) {
                        state.collapsed.insert(section.provider_key.clone());
                    }
                }
            }
            InputOutcome::None
        }
        KeyCode::Char('e') => {
            if let Some(provider) = selected_provider(&sections, state) {
                let (provider_key, provider_name) = (
                    provider.provider_key.clone(),
                    provider.provider_name.clone(),
                );
                return open_expanded_provider(state, provider_key, provider_name);
            }
            InputOutcome::None
        }
        KeyCode::Char('f') => {
            if let Some(model) = selected_model(&sections, state) {
                let trusted = if model.is_favorite {
                    remove_favorite_compat(&model.favorite_id);
                    None
                } else {
                    let _ = synaps_cli::config::add_favorite_model(&normalize_favorite_id(
                        &model.favorite_id,
                    ));
                    // Runtime-qualified identity of the visible row — the same
                    // exact ID that Apply uses — for the live policy grant.
                    Some(model.id.clone())
                };
                state.refresh_favorites();
                let new_len = visible_rows(&build_sections(current_model, state), state).len();
                if new_len == 0 {
                    state.cursor = 0;
                } else if state.cursor >= new_len {
                    state.cursor = new_len - 1;
                }
                if let Some(model_id) = trusted {
                    return InputOutcome::Trusted(model_id);
                }
            }
            InputOutcome::None
        }
        KeyCode::Enter => {
            if let Some(model) = selected_model(&sections, state) {
                // Apply the provider-qualified identity of the visible row directly.
                // Favorite normalization is compatibility-only and must not reroute it.
                InputOutcome::Apply(model.id.clone())
            } else {
                InputOutcome::None
            }
        }
        KeyCode::Backspace => {
            state.search.pop();
            state.cursor = 0;
            InputOutcome::None
        }
        KeyCode::Char(ch) => {
            if !key
                .modifiers
                .contains(crossterm::event::KeyModifiers::CONTROL)
            {
                state.search.push(ch);
                state.cursor = 0;
            }
            InputOutcome::None
        }
        _ => InputOutcome::None,
    }
}

/// Open the expanded provider browser for `provider_key` (the 'e' key).
///
/// Source-controlled providers (openai-codex) resolve immediately to their
/// static entries — no `ExpandProvider` action is emitted, so no network
/// catalog fetch is ever initiated. All other providers (Anthropic included)
/// enter `Loading` and request an async live catalog fetch as before.
pub(crate) fn open_expanded_provider(
    state: &mut ModelsModalState,
    provider_key: String,
    provider_name: String,
) -> InputOutcome {
    state.expanded = Some(ExpandedModelsState {
        provider_key: provider_key.clone(),
        provider_name,
        cursor: 0,
        search: String::new(),
        load_state: ExpandedLoadState::Loading,
    });
    if provider_key == "openai-codex" {
        // Canonicalization resolves this to the seven static OAuth entries
        // (and marks favorites) — same central invariant as live results.
        super::apply_model_list_result(state, &provider_key, Ok(Vec::new()));
        return InputOutcome::None;
    }
    InputOutcome::ExpandProvider(provider_key)
}

fn handle_expanded_event(state: &mut ModelsModalState, key: KeyEvent) -> InputOutcome {
    match key.code {
        KeyCode::Esc => {
            state.expanded = None;
            InputOutcome::None
        }
        KeyCode::Up | KeyCode::Char('k') => {
            if let Some(expanded) = state.expanded.as_mut() {
                expanded.cursor = expanded.cursor.saturating_sub(1);
            }
            InputOutcome::None
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let visible_len = expanded_visible_models(state).len();
            if let Some(expanded) = state.expanded.as_mut() {
                if visible_len > 0 {
                    expanded.cursor = (expanded.cursor + 1).min(visible_len - 1);
                }
            }
            InputOutcome::None
        }
        KeyCode::Enter => {
            if let Some(model) = selected_expanded_model(state) {
                InputOutcome::Apply(model.id)
            } else {
                InputOutcome::None
            }
        }
        KeyCode::Char('f') => {
            if let Some(model) = selected_expanded_model(state) {
                let trusted = if model.is_favorite {
                    remove_favorite_compat(&model.id);
                    None
                } else {
                    let _ =
                        synaps_cli::config::add_favorite_model(&normalize_favorite_id(&model.id));
                    Some(model.id.clone())
                };
                state.refresh_favorites();
                if let Some(model_id) = trusted {
                    return InputOutcome::Trusted(model_id);
                }
            }
            InputOutcome::None
        }
        KeyCode::Backspace => {
            if let Some(expanded) = state.expanded.as_mut() {
                expanded.search.pop();
                expanded.cursor = 0;
            }
            InputOutcome::None
        }
        KeyCode::Char(ch) => {
            if !key
                .modifiers
                .contains(crossterm::event::KeyModifiers::CONTROL)
            {
                if let Some(expanded) = state.expanded.as_mut() {
                    expanded.search.push(ch);
                    expanded.cursor = 0;
                }
            }
            InputOutcome::None
        }
        _ => InputOutcome::None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::models::{model_id_for_runtime, ExpandedModelEntry};
    use crossterm::event::KeyModifiers;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn every_copilot_curated_selection_emits_provider_qualified_routable_id() {
        for model in synaps_cli::runtime::openai::catalog::copilot_static_catalog_models() {
            let favorite_id = format!("github-copilot/{}", model.id);
            let emitted = model_id_for_runtime(&favorite_id);
            assert_eq!(emitted, favorite_id);
            let route = synaps_cli::runtime::openai::resolve_route(&emitted)
                .unwrap_or_else(|| panic!("Copilot model did not route: {emitted}"));
            assert_eq!(route.provider, "github-copilot");
        }
    }

    #[test]
    fn expanded_copilot_enter_emits_provider_qualified_claude_ids() {
        for wire_id in ["claude-fable-5", "claude-opus-4.8"] {
            let expected = format!("github-copilot/{wire_id}");
            let mut state = ModelsModalState::new();
            state.expanded = Some(ExpandedModelsState {
                provider_key: "github-copilot".to_string(),
                provider_name: "GitHub Copilot".to_string(),
                cursor: 0,
                search: String::new(),
                load_state: ExpandedLoadState::Ready(vec![ExpandedModelEntry::new(
                    expected.clone(),
                    wire_id.to_string(),
                    false,
                )]),
            });
            assert_eq!(
                handle_event(&mut state, key(KeyCode::Enter), "other"),
                InputOutcome::Apply(expected.clone())
            );
            assert_eq!(
                synaps_cli::runtime::openai::resolve_route(&expected)
                    .unwrap()
                    .provider,
                "github-copilot"
            );
        }
    }

    #[test]
    fn expanding_openai_codex_bypasses_network_and_shows_seven_static_rows() {
        let mut state = ModelsModalState::new();
        let outcome = open_expanded_provider(
            &mut state,
            "openai-codex".to_string(),
            "OpenAI Codex".to_string(),
        );
        // No ExpandProvider action → no catalog fetch is ever initiated.
        assert_eq!(
            outcome,
            InputOutcome::None,
            "openai-codex expansion must not request a live catalog fetch"
        );
        let expanded = state.expanded.expect("expanded state");
        assert_eq!(expanded.provider_key, "openai-codex");
        match expanded.load_state {
            ExpandedLoadState::Ready(models) => {
                let ids: Vec<_> = models.iter().map(|m| m.id.as_str()).collect();
                assert_eq!(
                    ids,
                    vec![
                        "openai-codex/gpt-5.6-sol",
                        "openai-codex/gpt-5.6-terra",
                        "openai-codex/gpt-5.6-luna",
                        "openai-codex/gpt-5.5",
                        "openai-codex/gpt-5.4",
                        "openai-codex/gpt-5.4-mini",
                        "openai-codex/gpt-5.3-codex-spark",
                    ],
                    "expanded rows must be exactly the seven static OAuth models, in order"
                );
            }
            other => panic!("expected static Ready rows without fetching, got {other:?}"),
        }
    }

    #[test]
    fn expanding_anthropic_still_requests_live_catalog() {
        let mut state = ModelsModalState::new();
        let outcome =
            open_expanded_provider(&mut state, "anthropic".to_string(), "Anthropic".to_string());
        assert_eq!(
            outcome,
            InputOutcome::ExpandProvider("anthropic".to_string())
        );
        let expanded = state.expanded.expect("expanded state");
        assert_eq!(expanded.load_state, ExpandedLoadState::Loading);
    }

    /// `e` expands whichever provider is under the cursor.
    ///
    /// The expectation is DERIVED from `build_sections`, not hardcoded: that
    /// function reads real host state (`configured_static_provider_keys()` and
    /// `logged_in_oauth_providers()`), so which provider sorts first differs
    /// per machine. Asserting "anthropic" passed only on hosts holding
    /// Anthropic credentials and failed everywhere else — on a clean CI runner
    /// the first row is `azure-openai`.
    ///
    /// Load semantics stay out of scope here because they are provider-class
    /// dependent (live-catalog providers go to `Loading`, static-OAuth ones to
    /// a `Ready` row set without fetching). Those are covered exactly by
    /// `expanding_anthropic_still_requests_live_catalog` and the static-OAuth
    /// test above; this one pins the routing.
    #[test]
    fn e_opens_expanded_provider_browser() {
        let mut state = ModelsModalState::new();
        state.view = ModelsView::All;
        let sections = crate::tui::models::build_sections("claude-opus-4-7", &state);
        let expected = crate::tui::models::selected_provider(&sections, &state)
            .expect("a provider row is selected at cursor 0")
            .provider_key
            .clone();

        let outcome = handle_event(&mut state, key(KeyCode::Char('e')), "claude-opus-4-7");
        assert_eq!(outcome, InputOutcome::ExpandProvider(expected.clone()));
        let expanded = state.expanded.expect("expanded state");
        assert_eq!(expanded.provider_key, expected);
        assert_eq!(expanded.search, "");
    }

    #[test]
    fn expanded_typing_filters_and_enter_applies_selected_model() {
        let mut state = ModelsModalState::new();
        state.expanded = Some(ExpandedModelsState {
            provider_key: "openrouter".to_string(),
            provider_name: "OpenRouter".to_string(),
            cursor: 0,
            search: String::new(),
            load_state: ExpandedLoadState::Ready(vec![
                ExpandedModelEntry::new(
                    "openrouter/deepseek/deepseek-chat".to_string(),
                    "DeepSeek".to_string(),
                    false,
                ),
                ExpandedModelEntry::new(
                    "openrouter/qwen/qwen3-coder".to_string(),
                    "Qwen3 Coder".to_string(),
                    false,
                ),
            ]),
        });

        assert_eq!(
            handle_event(&mut state, key(KeyCode::Char('q')), "claude-opus-4-7"),
            InputOutcome::None
        );
        assert_eq!(
            handle_event(&mut state, key(KeyCode::Enter), "claude-opus-4-7"),
            InputOutcome::Apply("openrouter/qwen/qwen3-coder".to_string())
        );
    }

    #[test]
    fn esc_in_expanded_returns_to_curated_modal() {
        let mut state = ModelsModalState::new();
        state.expanded = Some(ExpandedModelsState {
            provider_key: "openrouter".to_string(),
            provider_name: "OpenRouter".to_string(),
            cursor: 0,
            search: String::new(),
            load_state: ExpandedLoadState::Loading,
        });

        assert_eq!(
            handle_event(&mut state, key(KeyCode::Esc), "claude-opus-4-7"),
            InputOutcome::None
        );
        assert!(state.expanded.is_none());
    }

    #[test]
    fn tab_toggles_all_and_favorites_view() {
        let mut state = ModelsModalState::new();
        state.view = ModelsView::All;
        assert_eq!(
            handle_event(&mut state, key(KeyCode::Tab), "claude-opus-4-7"),
            InputOutcome::None
        );
        assert_eq!(state.view, ModelsView::Favorites);
        assert_eq!(
            handle_event(&mut state, key(KeyCode::Tab), "claude-opus-4-7"),
            InputOutcome::None
        );
        assert_eq!(state.view, ModelsView::All);
    }

    #[test]
    fn typing_updates_search_and_backspace_removes() {
        let mut state = ModelsModalState::new();
        handle_event(&mut state, key(KeyCode::Char('q')), "claude-opus-4-7");
        handle_event(&mut state, key(KeyCode::Char('w')), "claude-opus-4-7");
        assert_eq!(state.search, "qw");
        handle_event(&mut state, key(KeyCode::Backspace), "claude-opus-4-7");
        assert_eq!(state.search, "q");
    }
}