llm-manager 1.10.0

Terminal UI for managing LLMs
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
use crossterm::event::KeyCode;

use crate::models::ListSort;
use crate::tui::app::pending_events::PendingEvent;
use crate::tui::app::{App, GlobalMode, LoadingPhase, ModelsMode};

pub async fn handle_models_key(app: &mut App, key: crossterm::event::KeyEvent) {
    if app.search.filtering_local {
        match key.code {
            KeyCode::Esc => {
                app.search.filtering_local = false;
                app.search.local_filter.clear();
                app.invalidate_list_caches();
                app.on_model_selection_change();
            }
            KeyCode::Enter => {
                app.search.filtering_local = false;
            }
            KeyCode::Char(c) => {
                app.search.local_filter.push(c);
                app.invalidate_list_caches();
                app.on_model_selection_change();
            }
            KeyCode::Backspace => {
                app.search.local_filter.pop();
                app.invalidate_list_caches();
                app.on_model_selection_change();
            }
            _ => {}
        }
        return;
    }

    match key.code {
        KeyCode::Char('f') => {
            if matches!(app.models_mode, ModelsMode::List { .. }) {
                app.search.filtering_local = true;
                if app.selected_model_idx.is_none() {
                    let filtered = app.get_filtered_model_indices();
                    if !filtered.is_empty() {
                        app.selected_model_idx = Some(filtered[0]);
                        app.on_model_selection_change();
                    }
                }
            }
        }
        KeyCode::Up | KeyCode::Char('k') => {
            let sorted = if let ModelsMode::List { .. } = &app.models_mode {
                app.get_sorted_model_indices().to_vec()
            } else {
                let filtered = app.get_filtered_model_indices();
                get_sorted_indices(app, &filtered)
            };
            if let Some(idx) = app.selected_model_idx {
                if let Some(pos) = sorted.iter().position(|&i| i == idx) {
                    if pos > 0 {
                        app.selected_model_idx = Some(sorted[pos - 1]);
                        app.on_model_selection_change();
                    }
                } else if !sorted.is_empty() {
                    app.selected_model_idx = Some(sorted[0]);
                    app.on_model_selection_change();
                }
            } else if !sorted.is_empty() {
                app.selected_model_idx = Some(sorted[0]);
                app.on_model_selection_change();
            }
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let sorted = if let ModelsMode::List { .. } = &app.models_mode {
                app.get_sorted_model_indices().to_vec()
            } else {
                let filtered = app.get_filtered_model_indices();
                get_sorted_indices(app, &filtered)
            };
            if let Some(idx) = app.selected_model_idx {
                if let Some(pos) = sorted.iter().position(|&i| i == idx) {
                    if pos + 1 < sorted.len() {
                        app.selected_model_idx = Some(sorted[pos + 1]);
                        app.on_model_selection_change();
                    }
                } else if !sorted.is_empty() {
                    app.selected_model_idx = Some(sorted[0]);
                    app.on_model_selection_change();
                }
            } else if !sorted.is_empty() {
                app.selected_model_idx = Some(sorted[0]);
                app.on_model_selection_change();
            }
        }
        KeyCode::Enter | KeyCode::Char('l')
            if !matches!(app.models_mode, ModelsMode::Files { .. }) =>
        {
            if app.pending.backend_resolving {
                app.add_log(
                    "Wait for backend installation to finish...",
                    crate::config::LogLevel::Info,
                );
                return;
            }
            if let Some(idx) = app.selected_model_idx {
                let model = app.models[idx].clone();
                let already_loaded = matches!(
                    app.model_states.get(&model.display_name),
                    Some(crate::models::ModelState::Loaded { .. })
                );
                if already_loaded {
                    app.add_log(
                        format!("{} is already loaded", model.display_name),
                        crate::config::LogLevel::Info,
                    );
                } else {
                    app.update_model_metadata();
                    let settings = if app.settings != app.model_settings_cache {
                        app.settings.clone()
                    } else {
                        app.selected_model_settings()
                    };

                    if let Some(handle) = &app.server.server_handle
                        && !crate::backend::server::check_health(&handle.host, handle.port).await
                    {
                        app.add_log(
                            "Router unresponsive, restarting...",
                            crate::config::LogLevel::Info,
                        );
                        if let Some(h) = app.server.server_handle.take() {
                            let _ = app
                                .pending_tx
                                .send(PendingEvent::KillHandle { handle: h })
                                .await;
                        }
                    }

                    if app.server.server_handle.is_none() {
                        // Start server (with model in CLI for normal mode, without model for router mode)
                        app.clear_toasts();

                        if app.server_mode == crate::models::ServerMode::BenchTune {
                            let bench_tune_config = crate::models::BenchTuneConfig::new(
                                model.path.clone(),
                                3, // Default iterations
                                crate::models::BENCHMARK_PROMPT.to_string(),
                            );
                            app.ui.global_mode = crate::tui::app::GlobalMode::BenchTuneSetup {
                                config: bench_tune_config,
                                selected_idx: 0,
                                editing_param: false,
                                editing_param_field: 0,
                                param_edit_buffer: String::new(),
                                param_edit_cursor_pos: 0,
                                bench_mode_selection: 0,
                                editing_prompt: false,
                                editing_kwargs: false,
                            };
                            return;
                        }
                        if app.server_mode == crate::models::ServerMode::Router {
                            // Router mode: start server without a model, then load via /load API
                            let _ = app
                                .pending_tx
                                .send(PendingEvent::Spawn {
                                    model: None,
                                    settings: settings.clone(),
                                })
                                .await;
                            // Queue the load so it triggers once server is ready
                            app.pending.pending_api_load = Some(model.display_name.clone());
                            app.loading.loading_phases =
                                std::iter::once(LoadingPhase::ServerStarting).collect();
                            app.loading.last_active_phase = Some(LoadingPhase::ServerStarting);
                            app.loading.loading_progress = 0.25;
                            app.add_log(
                                "Starting router server...".to_string(),
                                crate::config::LogLevel::Info,
                            );
                        } else {
                            // Normal mode: start server WITH the specific model directly
                            let _ = app
                                .pending_tx
                                .send(PendingEvent::Spawn {
                                    model: Some(model.clone()),
                                    settings,
                                })
                                .await;
                            app.loading.loading_phases =
                                std::iter::once(LoadingPhase::ServerStarting).collect();
                            app.loading.last_active_phase = Some(LoadingPhase::ServerStarting);
                            app.loading.loading_progress = 0.25;
                            app.add_log(
                                format!("Starting server with {}...", model.display_name),
                                crate::config::LogLevel::Info,
                            );
                        }
                    } else {
                        // Server already running, load via API

                        // In Normal mode, block if any model is already loaded
                        if app.server_mode == crate::models::ServerMode::Normal
                            && app
                                .model_states
                                .values()
                                .any(|s| matches!(s, crate::models::ModelState::Loaded { .. }))
                        {
                            app.add_log(
                                crate::t!("models.already_loaded"),
                                crate::config::LogLevel::Warning,
                            );
                            return;
                        }

                        // Check if we reached the limit of models to load (based on Max Concurrent Predictions)
                        let active_count = app
                            .model_states
                            .values()
                            .filter(|s| {
                                matches!(
                                    s,
                                    crate::models::ModelState::Loaded { .. }
                                        | crate::models::ModelState::Loading
                                )
                            })
                            .count();

                        if let Some(max) = app.settings.max_concurrent_predictions
                            && active_count as u32 >= max
                        {
                            app.add_log(format!("Limit reached: already {} model(s) loaded (Max Concurrent Predictions limit: {})", active_count, max), crate::config::LogLevel::Warning);
                            return;
                        }

                        app.clear_toasts();
                        app.pending.pending_api_load = Some(model.display_name.clone());
                        app.loading.loading_phases =
                            std::iter::once(LoadingPhase::LoadingModel).collect();
                        app.loading.last_active_phase = Some(LoadingPhase::LoadingModel);
                        app.loading.loading_progress = 0.5;
                        app.add_log(
                            format!("Loading {} via API...", model.display_name),
                            crate::config::LogLevel::Info,
                        );
                    }
                }
            }
        }
        KeyCode::Char('u') => {
            if let Some(idx) = app.selected_model_idx {
                let model = app.models[idx].clone();
                if let Some(crate::models::ModelState::Loaded { .. }) =
                    app.model_states.get(&model.display_name)
                {
                    app.ui.global_mode = GlobalMode::Confirmation {
                        selected: false,
                        kind: crate::tui::app::ConfirmationKind::Unload,
                        display_name: model.display_name.clone(),
                        detail: Some(model.path.to_string_lossy().to_string()),
                    };
                    app.pending.pending_api_unload = Some(model.display_name.clone());
                } else {
                    app.add_log(
                        format!("{} is not loaded", model.display_name),
                        crate::config::LogLevel::Warning,
                    );
                }
            } else if app.server.server_handle.is_some() {
                app.add_log(
                    "Select a loaded model to unload",
                    crate::config::LogLevel::Warning,
                );
            } else if app.server_mode == crate::models::ServerMode::Router {
                // Router mode: no server running, no model loaded — fine
            } else {
                app.add_log(
                    "No model is currently loaded",
                    crate::config::LogLevel::Warning,
                );
            }
        }
        KeyCode::Delete if app.ui.active_panel == crate::tui::app::ActivePanel::Models => {
            if let Some(model) = app.selected_model() {
                let display_name = model.display_name.clone();
                let path_str = model.path.to_string_lossy().to_string();
                app.ui.global_mode = GlobalMode::Confirmation {
                    selected: false,
                    kind: crate::tui::app::ConfirmationKind::Delete,
                    display_name: display_name.clone(),
                    detail: Some(path_str),
                };
                app.add_log(
                    format!("Delete confirmation for {} shown", display_name),
                    crate::config::LogLevel::Info,
                );
            } else {
                app.add_log(
                    "No model selected to delete",
                    crate::config::LogLevel::Warning,
                );
            }
        }
        KeyCode::Char('d')
            if key
                .modifiers
                .contains(crossterm::event::KeyModifiers::CONTROL) =>
        {
            if app.ui.active_panel != crate::tui::app::ActivePanel::Models {
                app.add_log(
                    "Press ⇥ to switch to Models panel, then ^D or Del to delete",
                    crate::config::LogLevel::Warning,
                );
                return;
            }
            if let Some(model) = app.selected_model() {
                let display_name = model.display_name.clone();
                let path_str = model.path.to_string_lossy().to_string();
                app.ui.global_mode = GlobalMode::Confirmation {
                    selected: false,
                    kind: crate::tui::app::ConfirmationKind::Delete,
                    display_name: display_name.clone(),
                    detail: Some(path_str),
                };
                app.add_log(
                    format!("Delete confirmation for {} shown", display_name),
                    crate::config::LogLevel::Info,
                );
            } else {
                app.add_log(
                    "No model selected to delete",
                    crate::config::LogLevel::Warning,
                );
            }
        }
        _ => {}
    }
}

fn get_sorted_indices(app: &App, filtered: &[usize]) -> Vec<usize> {
    let sort_by = match &app.models_mode {
        ModelsMode::List { sort_by } => *sort_by,
        _ => ListSort::Name,
    };

    let mut sorted = filtered.to_vec();
    sorted.sort_by(|&a, &b| {
        let model_a = &app.models[a];
        let model_b = &app.models[b];
        match sort_by {
            ListSort::Name => model_a.display_name.cmp(&model_b.display_name),
            ListSort::Status => {
                let state_a = app.model_states.get(&model_a.display_name);
                let state_b = app.model_states.get(&model_b.display_name);
                let prio_a = match state_a {
                    Some(crate::models::ModelState::Loaded { .. }) => 3,
                    Some(crate::models::ModelState::Loading) => 2,
                    Some(crate::models::ModelState::Benchmarking) => 1,
                    _ => 0,
                };
                let prio_b = match state_b {
                    Some(crate::models::ModelState::Loaded { .. }) => 3,
                    Some(crate::models::ModelState::Loading) => 2,
                    Some(crate::models::ModelState::Benchmarking) => 1,
                    _ => 0,
                };
                prio_b.cmp(&prio_a)
            }
            ListSort::Params => {
                let ka = &*model_a.path.to_string_lossy();
                let kb = &*model_b.path.to_string_lossy();
                let meta_a = app.search.gguf_metadata_cache.get(ka);
                let meta_b = app.search.gguf_metadata_cache.get(kb);
                let val_a = meta_a
                    .map(|m| {
                        let trimmed = m.model_parameters.trim();
                        let num_str = trimmed.trim_end_matches(['B', 'b']).trim();
                        num_str.parse::<f64>().unwrap_or(0.0)
                    })
                    .unwrap_or(0.0);
                let val_b = meta_b
                    .map(|m| {
                        let trimmed = m.model_parameters.trim();
                        let num_str = trimmed.trim_end_matches(['B', 'b']).trim();
                        num_str.parse::<f64>().unwrap_or(0.0)
                    })
                    .unwrap_or(0.0);
                val_b
                    .partial_cmp(&val_a)
                    .unwrap_or(std::cmp::Ordering::Equal)
            }
            ListSort::Qual => {
                let ka = &*model_a.path.to_string_lossy();
                let kb = &*model_b.path.to_string_lossy();
                let meta_a = app.search.gguf_metadata_cache.get(ka);
                let meta_b = app.search.gguf_metadata_cache.get(kb);
                let rank_a = meta_a.map(|m| m.quality_rank).unwrap_or(0);
                let rank_b = meta_b.map(|m| m.quality_rank).unwrap_or(0);
                rank_b.cmp(&rank_a)
            }
            ListSort::Context => {
                let ctx_a = app
                    .search
                    .ctx_cache
                    .get(&model_a.display_name)
                    .map(|(c, _, _)| *c)
                    .unwrap_or(0);
                let ctx_b = app
                    .search
                    .ctx_cache
                    .get(&model_b.display_name)
                    .map(|(c, _, _)| *c)
                    .unwrap_or(0);
                ctx_b.cmp(&ctx_a)
            }
        }
    });
    sorted
}